Different ways to configure plugins through lazy vim what do they mean and which one do I use?

Hi eastking, I’ll try to help, having recently spent time setting up lazy.nvim myself.

When you set up a bunch of plugins in lazy, all you are doing is specifying a big table of tables. It is declarative, not imperative. Thus you are rightly asking “when will it get executed?”

Once all the plugins are specified, lazy will (I presume) determine some order in which to load them. Some plugins might be given a higher priority by the user (folke recommends to give the colorscheme a high priority, for instance). Some plugins are dependent on others, so the dependencies are loaded first. Some plugins will never be loaded because the trigger never occurs. For example, I have ‘vimtex’ set to load only on ft=tex.

When a plugin is ‘loaded’, what occurs?

Well, most plugins need setup to be called. Take mini.surround as a simple example. If you simply specify ‘echasnovski/mini.surround’ and that’s it, nothing will happen. You need the following code to be run: require('echasnovski/mini.surround').setup() in order to activate the plugin. If you want to provide additional configuration (say, to disable a mapping), then you provide options to the setup function, like require('echasnovski/mini.surround').setup({ mappings = { find = '', find_left = '' } }).

OK, so how do we make this code get run in lazy.nvim?

One way is:

config = function(_, _)  -- I am not using either parameter
  require('echasnovski/mini.surround').setup({ mappings = { find = '', find_left = '' } })
}

Sweet. But a shorter way is to do this:

opts = {
  mappings = { find = '', find_left = '' }
}

Lazy will see that you have provided options and that will trigger it to call setup for you with those options.

What if you don’t want to change any mappings? Here are your choices. They are equivalent.

-- Choice 1
{
  'echasnovski/mini.surround',
  opts = {}
}

-- Choice 2
{
  'echasnovski/mini.surround',
  config = true
}

Both of these are more convenient than

{
  'echasnovski/mini.surround',
  config = function()
    require('mini.surround').setup()
  end
}

especially when you have a lot of plugins.

Lazy is just helping you out by optimising the common path. But it is only easy to understand this if you already know the background. I would like to have been able to read this kind of material in the docs when I was starting out.

While I’m here, I’ll mention the init function. I like to use that for keymaps.

  {
    "Pocco81/auto-save.nvim",
    init = function()
      require('which-key').register({
        t = {
          a = { ':ASToggle<CR>', 'Autosave' },
        }
      }, { prefix = '<leader>' })
    end
  },

(Note that the auto-save plugin does not require setup to be called, hence I do not have config = true in the spec.)

7 Likes