nvf manual

Version v0.8


Table of Contents

Preface
Try it out
Installing nvf
Standalone Installation
Module Installation
Configuring nvf
Custom Neovim Package
Custom Plugins
Overriding plugins
Language Support
Using DAGs
DAG entries in nvf
Autocommands and Autogroups
Helpful Tips
Debugging nvf
Offline Documentation
Pure Lua Configuration
Adding Plugins From Different Sources
Hacking nvf
A. Known Issues and Quirks
B. nvf Configuration Options
C. Release Notes

Preface

Table of Contents

What is nvf
Bugs & Suggestions

What is nvf

nvf is a highly modular, configurable, extensible and easy to use Neovim configuration in Nix. Designed for flexibility and ease of use, nvf allows you to easily configure your fully featured Neovim instance with a few lines of Nix.

Bugs & Suggestions

If you notice any issues with nvf, or this documentation, then please consider reporting them over at the issue tracker. Issues tab, in addition to the discussions tab is a good place as any to request new features.

You may also consider submitting bugfixes, feature additions and upstreamed changes that you think are critical over at the pull requests tab.

Try it out

Table of Contents

Using Prebuilt Configs

Thanks to the portability of Nix, you can try out nvf without actually installing it to your machine. Below are the commands you may run to try out different configurations provided by this flake. As of v0.5, two specialized configurations are provided:

  • Nix - Nix language server + simple utility plugins

  • Maximal - Variable language servers + utility and decorative plugins

You may try out any of the provided configurations using the nix run command on a system where Nix is installed.

$ cachix use nvf                   # Optional: it'll save you CPU resources and time
$ nix run github:notashelf/nvf#nix # will run the default minimal configuration

Do keep in mind that this is susceptible to garbage collection meaning it will be removed from your Nix store once you garbage collect.

Using Prebuilt Configs

$ nix run github:notashelf/nvf#nix
$ nix run github:notashelf/nvf#maximal

Available Configurations

::: {.info}

The below configurations are provided for demonstration purposes, and are not designed to be installed as is. You may

Nix

Nix configuration by default provides LSP/diagnostic support for Nix alongside a set of visual and functional plugins. By running nix run .#, which is the default package, you will build Neovim with this config.

$ nix run github:notashelf/nvf#nix test.nix

This command will start Neovim with some opinionated plugin configurations, and is designed specifically for Nix. the nix configuration lets you see how a fully configured Neovim setup might look like without downloading too many packages or shell utilities.

Maximal

Maximal is the ultimate configuration that will enable support for more commonly used language as well as additional complementary plugins. Keep in mind, however, that this will pull a lot of dependencies.

$ nix run github:notashelf/nvf#maximal -- test.nix

It uses the same configuration template with the Nix configuration, but supports many more languages, and enables more utility, companion or fun plugins.

Warning

Running the maximal config will download a lot of packages as it is downloading language servers, formatters, and more.

Installing nvf

There are multiple ways of installing nvf on your system. You may either choose the standalone installation method, which does not depend on a module system and may be done on any system that has the Nix package manager or the appropriate modules for NixOS and home-manager as described in the module installation section.

Standalone Installation

It is possible to install nvf without depending on NixOS or Home-Manager as the parent module system, using the neovimConfiguration function exposed in the extended library. This function will take modules and extraSpecialArgs as arguments, and return the following schema as a result.

{
  options = "The options that were available to configure";
  config = "The outputted configuration";
  pkgs = "The package set used to evaluate the module";
  neovim = "The built neovim package";
}

An example flake that exposes your custom Neovim configuration might look like

{
  inputs = {
    nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
    nvf.url = "github:notashelf/nvf";
  };

  outputs = {nixpkgs, ...} @ inputs: {
    packages.x86_64-linux = {
      # Set the default package to the wrapped instance of Neovim.
      # This will allow running your Neovim configuration with
      # `nix run` and in addition, sharing your configuration with
      # other users in case your repository is public.
      default =
        (inputs.nvf.lib.neovimConfiguration {
          pkgs = nixpkgs.legacyPackages.x86_64-linux;
          modules = [
            {
              config.vim = {
                # Enable custom theming options
                theme.enable = true;

                # Enable Treesitter
                treesitter.enable = true;

                # Other options will go here. Refer to the config
                # reference in Appendix B of the nvf manual.
                # ...
              };
            }
          ];
        })
        .neovim;
    };
  };
}

The above setup will allow to set up nvf as a standalone flake, which you can build independently from your system configuration while also possibly sharing it with others. The next two chapters will detail specific usage of such a setup for a package output in the context of NixOS or Home-Manager installation.

Standalone Installation on NixOS

Your built Neovim configuration can be exposed as a flake output to make it easier to share across machines, repositories and so on. Or it can be added to your system packages to make it available across your system.

The following is an example installation of nvf as a standalone package with the default theme enabled. You may use other options inside config.vim in configModule, but this example will not cover that extensively.

{
  inputs = {
    nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
    home-manager.url = "github:nix-community/home-manager";
    nvf.url = "github:notashelf/nvf";
  };

  outputs = {
    nixpkgs,
    nvf,
    self,
    ...
  }: {
    # This will make the package available as a flake output under 'packages'
    packages.x86_64-linux.my-neovim =
      (nvf.lib.neovimConfiguration {
        pkgs = nixpkgs.legacyPackages.x86_64-linux;
        modules = [
          # Or move this to a separate file and add it's path here instead
          # IE: ./nvf_module.nix
          (
            {pkgs, ...}: {
              # Add any custom options (and do feel free to upstream them!)
              # options = { ... };
              config.vim = {
                theme.enable = true;
                # and more options as you see fit...
              };
            }
          )
        ];
      })
      .neovim;

    # Example nixosConfiguration using the configured Neovim package
    nixosConfigurations = {
      yourHostName = nixpkgs.lib.nixosSystem {
        # ...
        modules = [
          # This will make wrapped neovim available in your system packages
          # Can also move this to another config file if you pass inputs/self around with specialArgs
          ({pkgs, ...}: {
            environment.systemPackages = [self.packages.${pkgs.stdenv.system}.neovim];
          })
        ];
        # ...
      };
    };
  };
}```

Standalone Installation on Home-Manager

Your built Neovim configuration can be exposed as a flake output to make it easier to share across machines, repositories and so on. Or it can be added to your system packages to make it available across your system.

The following is an example installation of nvf as a standalone package with the default theme enabled. You may use other options inside config.vim in configModule, but this example will not cover that extensively.

{
  inputs = {
    nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
    home-manager.url = "github:nix-community/home-manager";
    nvf.url = "github:notashelf/nvf";
  };

  outputs = {nixpkgs, home-manager, nvf, ...}: let
    system = "x86_64-linux";
    pkgs = nixpkgs.legacyPackages.${system};
    configModule = {
      # Add any custom options (and do feel free to upstream them!)
      # options = { ... };

      config.vim = {
        theme.enable = true;
        # and more options as you see fit...
      };
    };

    customNeovim = nvf.lib.neovimConfiguration {
      inherit pkgs;
      modules = [configModule];
    };
  in {
    # This will make the package available as a flake output under 'packages'
    packages.${system}.my-neovim = customNeovim.neovim;

    # Example Home-Manager configuration using the configured Neovim package
    homeConfigurations = {
      "your-username@your-hostname" = home-manager.lib.homeManagerConfiguration {
        # ...
        modules = [
          # This will make Neovim available to users using the Home-Manager
          # configuration. To make the package available to all users, prefer
          # environment.systemPackages in your NixOS configuration.
          {home.packages = [customNeovim.neovim];}
        ];
        # ...
      };
    };
  };
}

Module Installation

Table of Contents

NixOS Module
Home-Manager Module

The below chapters will describe installing nvf as NixOS and Home-Manager modules. Note that those methods are mutually exclusive, and will likely cause path collisions if used simultaneously.

NixOS Module

Table of Contents

Example Installation

The NixOS module allows us to customize the different vim options from inside the NixOS configuration without having to call for the wrapper yourself. It is the recommended way to use nvf alongside the home-manager module depending on your needs.

To use it, we first add the input flake.

{
  inputs = {
    # Optional, if you intend to follow nvf's obsidian-nvim input
    # you must also add it as a flake input.
    obsidian-nvim.url = "github:epwalsh/obsidian.nvim";

    # Required, nvf works best and only directly supports flakes
    nvf = {
      url = "github:notashelf/nvf";
      # You can override the input nixpkgs to follow your system's
      # instance of nixpkgs. This is safe to do as nvf does not depend
      # on a binary cache.
      inputs.nixpkgs.follows = "nixpkgs";
      # Optionally, you can also override individual plugins
      # for example:
      inputs.obsidian-nvim.follows = "obsidian-nvim"; # <- this will use the obsidian-nvim from your inputs
    };
  };
}

Followed by importing the NixOS module somewhere in your configuration.

{
  # assuming nvf is in your inputs and inputs is in the argset
  # see example below
  imports = [ inputs.nvf.nixosModules.default ];
}

Example Installation

{
  inputs = {
    nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
    nvf.url = "github:notashelf/nvf";
  };

  outputs = { nixpkgs, nvf, ... }: {
    # ↓ this is your host output in the flake schema
    nixosConfigurations."your-hostname" = nixpkgs.lib.nixosSystem {
      modules = [
        nvf.nixosModules.default # <- this imports the NixOS module that provides the options
        ./configuration.nix # <- your host entrypoint, `programs.nvf.*` may be defined here
      ];
    };
  };
}

Once the module is properly imported by your host, you will be able to use the programs.nvf module option anywhere in your configuration in order to configure nvf.

  programs.nvf = {
    enable = true;
    # your settings need to go into the settings attribute set
    # most settings are documented in the appendix
    settings = {
      vim.viAlias = false;
      vim.vimAlias = true;
      vim.lsp = {
        enable = true;
      };
    };
  };
}

Note

nvf exposes a lot of options, most of which are not referenced in the installation sections of the manual. You may find all available options in the appendix

Home-Manager Module

Table of Contents

Example Installation

The home-manager module allows us to customize the different vim options from inside the home-manager configuration without having to call for the wrapper yourself. It is the recommended way to use nvf alongside the NixOS module depending on your needs.

To use it, we first add the input flake.

{
  inputs = {
    # Optional, if you intend to follow nvf's obsidian-nvim input
    # you must also add it as a flake input.
    obsidian-nvim.url = "github:epwalsh/obsidian.nvim";

    # Required, nvf works best and only directly supports flakes
    nvf = {
      url = "github:notashelf/nvf";
      # You can override the input nixpkgs to follow your system's
      # instance of nixpkgs. This is safe to do as nvf does not depend
      # on a binary cache.
      inputs.nixpkgs.follows = "nixpkgs";
      # Optionally, you can also override individual plugins
      # for example:
      inputs.obsidian-nvim.follows = "obsidian-nvim"; # <- this will use the obsidian-nvim from your inputs
    };
  };
}

Followed by importing the home-manager module somewhere in your configuration.

{
  # Assuming "nvf" is in your inputs and inputs is in the argument set.
  # See example installation below
  imports = [ inputs.nvf.homeManagerModules.default ];
}

Example Installation

{
  inputs = {
    nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
    home-manager.url = "github:nix-community/home-manager";
    nvf.url = "github:notashelf/nvf";
  };

  outputs = { nixpkgs, home-manager, nvf, ... }: {
    # ↓ this is your home output in the flake schema, expected by home-manager
    "your-username@your-hostname" = home-manager.lib.homeManagerConfiguration {
      pkgs = nixpkgs.legacyPackages.x86_64-linux;
      modules = [
        nvf.homeManagerModules.default # <- this imports the home-manager module that provides the options
        ./home.nix # <- your home entrypoint, `programs.nvf.*` may be defined here
      ];
    };
  };
}

Once the module is properly imported by your host, you will be able to use the programs.nvf module option anywhere in your configuration in order to configure nvf.

  programs.nvf = {
    enable = true;
    # your settings need to go into the settings attribute set
    # most settings are documented in the appendix
    settings = {
      vim.viAlias = false;
      vim.vimAlias = true;
      vim.lsp = {
        enable = true;
      };
    };
  };
}

Note

nvf exposes a lot of options, most of which are not referenced in the installation sections of the manual. You may find all available options in the appendix

Configuring nvf

nvf allows for very extensive configuration in Neovim through the Nix module interface. The below chapters describe several of the options exposed in nvf for your convenience. You might also be interested in the helpful tips section for more advanced or unusual configuration options supported by nvf.

Note that this section does not cover module options. For an overview of all module options provided by nvf, please visit the appendix

Custom Neovim Package

As of v0.5, you may now specify the Neovim package that will be wrapped with your configuration. This is done with the vim.package option.

{inputs, pkgs, ...}: {
  # using the neovim-nightly overlay
  vim.package = inputs.neovim-overlay.packages.${pkgs.stdenv.system}.neovim;
}

The neovim-nightly-overlay always exposes an unwrapped package. If using a different source, you are highly recommended to get an “unwrapped” version of the neovim package, similar to neovim-unwrapped in nixpkgs.

{ pkgs, ...}: {
  # using the neovim-nightly overlay
  vim.package = pkgs.neovim-unwrapped;
}

Custom Plugins

Table of Contents

Adding Plugins

nvf exposes a very wide variety of plugins by default, which are consumed by module options. This is done for your convenience, and to bundle all necessary dependencies into nvf’s runtime with full control of versioning, testing and dependencies. In the case a plugin you need is not available, you may consider making a pull request to add the package you’re looking for, or you may add it to your configuration locally. The below section describes how new plugins may be added to the user’s configuration.

Adding Plugins

Per nvf’s design choices, there are several ways of adding custom plugins to your configuration as you need them. As we aim for extensive configuration, it is possible to add custom plugins (from nixpkgs, pinning tools, flake inputs, etc.) to your Neovim configuration before they are even implemented in nvf as a module.

:::{.info}

To add a plugin to your runtime, you will need to add it to vim.startPlugins list in your configuration. This is akin to cloning a plugin to ~/.config/nvim, but they are only ever placed in the Nix store and never exposed to the outside world for purity and full isolation.

:::

As you would configure a cloned plugin, you must configure the new plugins that you’ve added to startPlugins. nvf provides multiple ways of configuring any custom plugins that you might have added to your configuration.

Configuring

Just making the plugin to your Neovim configuration available might not always be enough., for example, if the plugin requires a setup table. In that case, you can write custom Lua configuration using one of

  • config.vim.lazy.plugins.*.setupOpts

  • config.vim.extraPlugins.*.setup

  • config.vim.luaConfigRC.

Lazy Plugins

config.vim.lazy.plugins.*.setupOpts is useful for lazy-loading plugins, and uses an extended version of lz.n's PluginSpec to expose a familiar interface. setupModule and setupOpt can be used if the plugin uses a require('module').setup(...) pattern. Otherwise, the before and after hooks should do what you need.

{
  config.vim.lazy.plugins = {
    aerial.nvim = {
    # ^^^^^^^^^ this name should match the package.pname or package.name
      package = aerial-nvim;

      setupModule = "aerial";
      setupOpts = {option_name = false;};

      after = "print('aerial loaded')";
    };
  };
}

Standard API

vim.extraPlugins uses an attribute set, which maps DAG section names to a custom type, which has the fields package, after, setup. They allow you to set the package of the plugin, the sections its setup code should be after (note that the extraPlugins option has its own DAG scope), and the its setup code respectively. For example:

{pkgs, ...}: {
  config.vim.extraPlugins = {
    aerial = {
      package = pkgs.vimPlugins.aerial-nvim;
      setup = "require('aerial').setup {}";
    };

    harpoon = {
      package = pkgs.vimPlugins.harpoon;
      setup = "require('harpoon').setup {}";
      after = ["aerial"]; # place harpoon configuration after aerial
    };
  };
}
Setup using luaConfigRC

vim.luaConfigRC also uses an attribute set, but this one is resolved as a DAG directly. The attribute names denote the section names, and the values lua code. For example:

{
  # This will create a section called "aquarium" in the 'init.lua' with the
  # contents of your custom configuration. By default 'entryAnywhere' is implied
  # in DAGs, so this will be inserted to an arbitrary position. In the case you 
  # wish to control the position of this section with more precision, please
  # look into the DAGs section of the manual.
  config.vim.luaConfigRC.aquarium = "vim.cmd('colorscheme aquiarum')";
}

Note

One of the greatest strengths of nvf is the ability to order configuration snippets precisely using the DAG system. DAGs are a very powerful mechanism that allows specifying positions of individual sections of configuration as needed. We provide helper functions in the extended library, usually under inputs.nvf.lib.nvim.dag that you may use.

Please refer to the DAG section in the nvf manual to find out more about the DAG system.

Lazy Method

As of version 0.7, an API is exposed to allow configuring lazy-loaded plugins via lz.n and lzn-auto-require. Below is a comprehensive example of how it may be loaded to lazy-load an arbitrary plugin.

{
  config.vim.lazy.plugins = {
    "aerial.nvim" = {
      package = pkgs.vimPlugins.aerial-nvim;
      setupModule = "aerial";
      setupOpts = {
        option_name = true;
      };
      after = ''
        -- custom lua code to run after plugin is loaded
        print('aerial loaded')
      '';

      # Explicitly mark plugin as lazy. You don't need this if you define one of
      # the trigger "events" below
      lazy = true;

      # load on command
      cmd = ["AerialOpen"];

      # load on event
      event = ["BufEnter"];

      # load on keymap
      keys = [
        {
          key = "<leader>a";
          action = ":AerialToggle<CR>";
        }
      ];
    };
  };
}

LazyFile event

nvf re-implements LazyFile as a familiar user event to load a plugin when a file is opened:

{
  config.vim.lazy.plugins = {
    "aerial.nvim" = {
      package = pkgs.vimPlugins.aerial-nvim;
      event = [{event = "User"; pattern = "LazyFile";}];
      # ...
    };
  };
}

You can consider the LazyFile event as an alias to the combination of "BufReadPost", "BufNewFile" and "BufWritePre", i.e., a list containing all three of those events: ["BufReadPost" "BufNewFile" "BufWritePre"]

Non-lazy Method

As of version 0.5, we have a more extensive API for configuring plugins that should be preferred over the legacy method. This API is available as vim.extraPlugins. Instead of using DAGs exposed by the library directly, you may use the extra plugin module as follows:

{pkgs, ...}: {
  config.vim.extraPlugins = {
    aerial = {
      package = pkgs.vimPlugins.aerial-nvim;
      setup = ''
        require('aerial').setup {
          -- some lua configuration here
        }
      '';
    };

    harpoon = {
      package = pkgs.vimPlugins.harpoon;
      setup = "require('harpoon').setup {}";
      after = ["aerial"];
    };
  };
}

This provides a level of abstraction over the DAG system for faster iteration.

Legacy Method

Prior to version 0.5, the method of adding new plugins was adding the plugin package to vim.startPlugins and adding its configuration as a DAG under one of vim.configRC or vim.luaConfigRC. While configRC has been deprecated, users who have not yet updated to 0.5 or those who prefer a more hands-on approach may choose to use the old method where the load order of the plugins is explicitly determined by DAGs without internal abstractions.

Adding New Plugins

To add a plugin not available in nvf as a module to your configuration using the legacy method, you must add it to vim.startPlugins in order to make it available to Neovim at runtime.

{pkgs, ...}: {
  # Add a Neovim plugin from Nixpkgs to the runtime.
  # This does not need to come explicitly from packages. 'vim.startPlugins'
  # takes a list of *string* (to load internal plugins) or *package* to load
  # a Neovim package from any source.
  vim.startPlugins = [pkgs.vimPlugins.aerial-nvim];
}

Once the package is available in Neovim’s runtime, you may use the luaConfigRC option to provide configuration as a DAG using the nvf extended library in order to configure the added plugin,

{inputs, ...}: let
  # This assumes you have an input called 'nvf' in your flake inputs
  # and 'inputs' in your specialArgs. In the case you have passed 'nvf'
  # to specialArgs, the 'inputs' prefix may be omitted.
  inherit (inputs.nvf.lib.nvim.dag) entryAnywhere;
in {
  # luaConfigRC takes Lua configuration verbatim and inserts it at an arbitrary
  # position by default or if 'entryAnywhere' is used.
  vim.luaConfigRC.aerial-nvim= entryAnywhere ''
    require('aerial').setup {
      -- your configuration here
    }
  '';
}

Overriding plugins

The additional plugins section details the addition of new plugins to nvf under regular circumstances, i.e. while making a pull request to the project. You may override those plugins in your config to change source versions, e.g., to use newer versions of plugins that are not yet updated in nvf.

vim.pluginOverrides = {
  lazydev-nvim = pkgs.fetchFromGitHub {
    owner = "folke";
    repo = "lazydev.nvim";
    rev = "";
    hash = "";
  };
 # It's also possible to use a flake input
 lazydev-nvim = inputs.lazydev-nvim;
 # Or a local path 
 lazydev-nvim = ./lazydev;
 # Or a npins pin... etc
};

This will override the source for the neodev.nvim plugin that is used in nvf with your own plugin.

Warning

While updating plugin inputs, make sure that any configuration that has been deprecated in newer versions is changed in the plugin’s setupOpts. If you depend on a new version, requesting a version bump in the issues section is a more reliable option.

Language Support

Table of Contents

LSP Custom Packages/Command

Language specific support means there is a combination of language specific plugins, treesitter support, nvim-lspconfig language servers, and null-ls integration. This gets you capabilities ranging from autocompletion to formatting to diagnostics. The following languages have sections under the vim.languages attribute.

Adding support for more languages, and improving support for existing ones are great places where you can contribute with a PR.

LSP Custom Packages/Command

One of the strengths of nvf is convenient aliases to quickly configure LSP servers through the Nix module system. By default the LSP packages for relevant language modules will be pulled into the closure. If this is not desirable, you may provide a custom LSP package (e.g., a Bash script that calls a command) or a list of strings to be interpreted as the command to launch the language server. By using a list of strings, you can use this to skip automatic installation of a language server, and instead use the one found in your $PATH during runtime, for example:

vim.languages.java = {
  lsp = {
    enable = true;

    # This expects 'jdt-language-server' to be in your PATH or in
    # 'vim.extraPackages.' There are no additional checks performed to see
    # if the command provided is valid.
    package = ["jdt-language-server" "-data" "~/.cache/jdtls/workspace"];
  };
}

Using DAGs

We conform to the NixOS options types for the most part, however, a noteworthy addition for certain options is the DAG (Directed acyclic graph) type which is borrowed from home-manager’s extended library. This type is most used for topologically sorting strings. The DAG type allows the attribute set entries to express dependency relations among themselves. This can, for example, be used to control the order of configuration sections in your luaConfigRC.

The below section, mostly taken from the home-manager manual explains in more detail the overall usage logic of the DAG type.

entryAnywhere

lib.dag.entryAnywhere (value: T) : DagEntry<T>

Indicates that value can be placed anywhere within the DAG. This is also the default for plain attribute set entries, that is

foo.bar = {
  a = lib.dag.entryAnywhere 0;
}

and

foo.bar = {
  a = 0;
}

are equivalent.

entryAfter

lib.dag.entryAfter (afters: list string) (value: T) : DagEntry<T>

Indicates that value must be placed after each of the attribute names in the given list. For example

foo.bar = {
  a = 0;
  b = lib.dag.entryAfter [ "a" ] 1;
}

would place b after a in the graph.

entryBefore

lib.dag.entryBefore (befores: list string) (value: T) : DagEntry<T>

Indicates that value must be placed before each of the attribute names in the given list. For example

foo.bar = {
  b = lib.dag.entryBefore [ "a" ] 1;
  a = 0;
}

would place b before a in the graph.

entryBetween

lib.dag.entryBetween (befores: list string) (afters: list string) (value: T) : DagEntry<T>

Indicates that value must be placed before the attribute names in the first list and after the attribute names in the second list. For example

foo.bar = {
  a = 0;
  c = lib.dag.entryBetween [ "b" ] [ "a" ] 2;
  b = 1;
}

would place c before b and after a in the graph.

There are also a set of functions that generate a DAG from a list. These are convenient when you just want to have a linear list of DAG entries, without having to manually enter the relationship between each entry. Each of these functions take a tag as argument and the DAG entries will be named ${tag}-${index}.

entriesAnywhere

lib.dag.entriesAnywhere (tag: string) (values: [T]) : Dag<T>

Creates a DAG with the given values with each entry labeled using the given tag. For example

foo.bar = lib.dag.entriesAnywhere "a" [ 0 1 ];

is equivalent to

foo.bar = {
  a-0 = 0;
  a-1 = lib.dag.entryAfter [ "a-0" ] 1;
}

entriesAfter

lib.dag.entriesAfter (tag: string) (afters: list string) (values: [T]) : Dag<T>

Creates a DAG with the given values with each entry labeled using the given tag. The list of values are placed are placed after each of the attribute names in afters. For example

foo.bar =
  { b = 0; } // lib.dag.entriesAfter "a" [ "b" ] [ 1 2 ];

is equivalent to

foo.bar = {
  b = 0;
  a-0 = lib.dag.entryAfter [ "b" ] 1;
  a-1 = lib.dag.entryAfter [ "a-0" ] 2;
}

entriesBefore

lib.dag.entriesBefore (tag: string) (befores: list string) (values: [T]) : Dag<T>

Creates a DAG with the given values with each entry labeled using the given tag. The list of values are placed before each of the attribute names in befores. For example

foo.bar =
  { b = 0; } // lib.dag.entriesBefore "a" [ "b" ] [ 1 2 ];

is equivalent to

foo.bar = {
  b = 0;
  a-0 = 1;
  a-1 = lib.dag.entryBetween [ "b" ] [ "a-0" ] 2;
}

entriesBetween

lib.dag.entriesBetween (tag: string) (befores: list string) (afters: list string) (values: [T]) : Dag<T>

Creates a DAG with the given values with each entry labeled using the given tag. The list of values are placed before each of the attribute names in befores and after each of the attribute names in afters. For example

foo.bar =
  { b = 0; c = 3; } // lib.dag.entriesBetween "a" [ "b" ] [ "c" ] [ 1 2 ];

is equivalent to

foo.bar = {
  b = 0;
  c = 3;
  a-0 = lib.dag.entryAfter [ "c" ] 1;
  a-1 = lib.dag.entryBetween [ "b" ] [ "a-0" ] 2;
}

DAG entries in nvf

From the previous chapter, it should be clear that DAGs are useful, because you can add code that relies on other code. However, if you don’t know what the entries are called, it’s hard to do that, so here is a list of the internal entries in nvf:

vim.luaConfigRC (top-level DAG)

  1. (luaConfigPre) - not a part of the actual DAG, instead, it’s simply inserted before the rest of the DAG

  2. globalsScript - used to set globals defined in vim.globals

  3. basic - used to set basic configuration options

  4. optionsScript - used to set options defined in vim.o

  5. theme (this is simply placed before pluginConfigs and lazyConfigs, meaning that surrounding entries don’t depend on it) - used to set up the theme, which has to be done before other plugins

  6. lazyConfigs - lz.n and lzn-auto-require configs. If vim.lazy.enable is false, this will contain each plugin’s config instead.

  7. pluginConfigs - the result of the nested vim.pluginRC (internal option, see the Custom Plugins page for adding your own plugins) DAG, used to set up internal plugins

  8. extraPluginConfigs - the result of vim.extraPlugins, which is not a direct DAG, but is converted to, and resolved as one internally

  9. mappings - the result of vim.maps

Autocommands and Autogroups

This module allows you to declaratively configure Neovim autocommands and autogroups within your Nix configuration.

Autogroups (vim.augroups)

Autogroups (augroup) organize related autocommands. This allows them to be managed collectively, such as clearing them all at once to prevent duplicates. Each entry in the list is a submodule with the following options:

OptionTypeDefaultDescriptionExample
enablebooltrueEnables or disables this autogroup definition.true
namestrNoneRequired. The unique name for the autogroup."MyFormatGroup"
clearbooltrueClears any existing autocommands within this group before adding new ones defined in vim.autocmds.true

Example:

{
  vim.augroups = [
    {
      name = "MyCustomAuGroup";
      clear = true; # Clear previous autocommands in this group on reload
    }
    {
      name = "Formatting";
      # clear defaults to true
    }
  ];
}

Autocommands (vim.autocmds)

Autocommands (autocmd) trigger actions based on events happening within Neovim (e.g., saving a file, entering a buffer). Each entry in the list is a submodule with the following options:

OptionTypeDefaultDescriptionExample
enablebooltrueEnables or disables this autocommand definition.true
eventnullOr (listOf str)nullRequired. List of Neovim events that trigger this autocommand (e.g., BufWritePre, FileType).[ "BufWritePre" ]
patternnullOr (listOf str)nullList of file patterns (globs) to match against (e.g., *.py, *). If null, matches all files for the given event.[ "*.lua", "*.nix" ]
callbacknullOr luaInlinenullA Lua function to execute when the event triggers. Use lib.nvim.types.luaInline or lib.options.literalExpression "mkLuaInline '''...'''". Cannot be used with command.lib.nvim.types.luaInline "function() print('File saved!') end"
commandnullOr strnullA Vimscript command to execute when the event triggers. Cannot be used with callback."echo 'File saved!'"
groupnullOr strnullThe name of an augroup (defined in vim.augroups) to associate this autocommand with."MyCustomAuGroup"
descnullOr strnullA description for the autocommand (useful for introspection)."Format buffer on save"
onceboolfalseIf true, the autocommand runs only once and then automatically removes itself.false
nestedboolfalseIf true, allows this autocommand to trigger other autocommands.false

Warning

You cannot define both callback (for Lua functions) and command (for Vimscript) for the same autocommand. Choose one.

Examples:

{ lib, ... }:
{
  vim.augroups = [ { name = "UserSetup"; } ];

  vim.autocmds = [
    # Example 1: Using a Lua callback
    {
      event = [ "BufWritePost" ];
      pattern = [ "*.lua" ];
      group = "UserSetup";
      desc = "Notify after saving Lua file";
      callback = lib.nvim.types.luaInline ''
        function()
          vim.notify("Lua file saved!", vim.log.levels.INFO)
        end
      '';
    }

    # Example 2: Using a Vim command
    {
      event = [ "FileType" ];
      pattern = [ "markdown" ];
      group = "UserSetup";
      desc = "Set spellcheck for Markdown";
      command = "setlocal spell";
    }

    # Example 3: Autocommand without a specific group
    {
      event = [ "BufEnter" ];
      pattern = [ "*.log" ];
      desc = "Disable line numbers in log files";
      command = "setlocal nonumber";
      # No 'group' specified
    }

    # Example 4: Using Lua for callback
    {
      event = [ "BufWinEnter" ];
      pattern = [ "*" ];
      desc = "Simple greeting on entering a buffer window";
      callback = lib.generators.mkLuaInline ''
        function(args)
          print("Entered buffer: " .. args.buf)
        end
      '';
      
      # Run only once per session trigger
      once = true; 
    }
  ];
}

These definitions are automatically translated into the necessary Lua code to configure vim.api.nvim_create_augroup and vim.api.nvim_create_autocmd when Neovim starts.

Helpful Tips

This section provides helpful tips that may be considered “unorthodox” or “too advanced” for some users. We will cover basic debugging steps, offline documentation, configuring nvf with pure Lua and using custom plugin sources in nvf in this section. For general configuration tips, please see previous chapters.

Debugging nvf

Table of Contents

Accessing neovimConfig

There may be instances where the your Nix configuration evaluates to invalid Lua, or times when you will be asked to provide your built Lua configuration for easier debugging by nvf maintainers. nvf provides two helpful utilities out of the box.

nvf-print-config and nvf-print-config-path will be bundled with nvf as lightweight utilities to help you view or share your built configuration when necessary.

To view your configuration with syntax highlighting, you may use the bat pager.

nvf-print-config | bat --language=lua

Alternatively, cat or less may also be used.

Accessing neovimConfig

It is also possible to access the configuration for the wrapped package. The built Neovim package will contain a neovimConfig attribute in its passthru.

Offline Documentation

The manpages provided by nvf contains an offline version of the option search normally available at https://notashelf.github.io/nvf/options.html. You may use the man 5 nvf command to view option documentation from the comfort of your terminal.

Note that this is only available for NixOS and Home-Manager module installations.

Pure Lua Configuration

We recognize that you might not always want to configure your setup purely in Nix, sometimes doing things in Lua is simply the “superior” option. In such a case you might want to configure your Neovim instance using Lua, and nothing but Lua. It is also possible to mix Lua and Nix configurations.

Pure Lua or hybrid Lua/Nix configurations can be achieved in two different ways. Purely, by modifying Neovim’s runtime directory or impurely by placing Lua configuration in a directory found in $HOME. For your convenience, this section will document both methods as they can be used.

Pure Runtime Directory

As of 0.6, nvf allows you to modify Neovim’s runtime path to suit your needs. One of the ways the new runtime option is to add a configuration located relative to your flake.nix, which must be version controlled in pure flakes manner.

{
  # Let us assume we are in the repository root, i.e., the same directory as the
  # flake.nix. For the sake of the argument, we will assume that the Neovim lua
  # configuration is in a nvim/ directory relative to flake.nix.
  vim = {
    additionalRuntimeDirectories = [
      # This will be added to Neovim's runtime paths. Conceptually, this behaves
      # very similarly to ~/.config/nvim but you may not place a top-level
      # init.lua to be able to require it directly.
      ./nvim
    ];
  };
}

This will add the nvim directory, or rather, the store path that will be realised after your flake gets copied to the Nix store, to Neovim’s runtime directory. You may now create a lua/myconfig directory within this nvim directory, and call it with vim.luaConfigRC.

{pkgs, ...}: {
  vim = {
    additionalRuntimeDirectories = [
      # You can list more than one file here.
      ./nvim-custom-1

      # To make sure list items are ordered, use lib.mkBefore or lib.mkAfter
      # Simply placing list items in a given order will **not** ensure that
      # this list  will be deterministic.
      ./nvim-custom-2
    ];

    startPlugins = [pkgs.vimPlugins.gitsigns];

    # Neovim supports in-line syntax highlighting for multi-line strings.
    # Simply place the filetype in a /* comment */ before the line.
    luaConfigRC.myconfig = /* lua */ ''
      -- Call the Lua module from ./nvim/lua/myconfig
      require("myconfig")

      -- Any additional Lua configuration that you might want *after* your own
      -- configuration. For example, a plugin setup call.
      require('gitsigns').setup({})
    '';
  };
}

Impure Absolute Directory

As of Neovim 0.9, $NVIM_APPNAME is a variable expected by Neovim to decide on the configuration directory. nvf sets this variable as "nvf", meaning ~/.config/nvf will be regarded as the configuration directory by Neovim, similar to how ~/.config/nvim behaves in regular installations. This allows some degree of Lua configuration, backed by our low-level wrapper mnw. Creating a lua/ directory located in $NVIM_APPNAME (“nvf” by default) and placing your configuration in, e.g., ~/.config/nvf/lua/myconfig will allow you to require it as a part of the Lua module system through nvf’s module system.

Let’s assume your ~/.config/nvf/lua/myconfig/init.lua consists of the following:

-- init.lua
vim.keymap.set("n", " ", "<Nop>", { silent = true, remap = false })
vim.g.mapleader = " "

The following Nix configuration via vim.luaConfigRC will allow loading this

{
  # The attribute name "myconfig-dir" here is arbitrary. It is required to be
  # a *named* attribute by the DAG system, but the name is entirely up to you.
  vim.luaConfigRC.myconfig-dir = ''
    require("myconfig")

    -- Any additional Lua
  '';
}

After you load your custom configuration, you may use an init.lua located in your custom configuration directory to configure Neovim exactly as you would without a wrapper like nvf. If you want to place your require call in a specific position (i.e., before or after options you set in nvf) the DAG system will let you place your configuration in a location of your choosing.

Adding Plugins From Different Sources

nvf attempts to avoid depending on Nixpkgs for Neovim plugins. For the most part, this is accomplished by defining each plugin’s source and building them from source.

To define plugin sources, we use npins and pin each plugin source using builtin fetchers. You are not bound by this restriction. In your own configuration, any kind of fetcher or plugin source is fine.

Nixpkgs & Friends

vim.startPlugins and vim.optPlugins options take either a string, in which case a plugin from nvf’s internal plugins registry will be used, or a package. If your plugin does not require any setup, or ordering for it s configuration, then it is possible to add it to vim.startPlugins to load it on startup.

{pkgs, ...}: {
  # Aerial does require some setup. In the case you pass a plugin that *does*
  # require manual setup, then you must also call the setup function.
  vim.startPlugins = [pkgs.vimPlugins.aerial-nvim];
}

This will fetch aerial.nvim from nixpkgs, and add it to Neovim’s runtime path to be loaded manually. Although for plugins that require manual setup, you are encouraged to use vim.extraPlugins.

{
  vim.extraPlugins = {
    aerial = {
      package = pkgs.vimPlugins.aerial-nvim;
      setup = "require('aerial').setup {}";
    };
  };
}

More details on the extraPlugins API is documented in the custom plugins section.

Building Your Own Plugins

In the case a plugin is not available in Nixpkgs, or the Nixpkgs package is outdated (or, more likely, broken) it is possible to build the plugins from source using a tool, such as npins. You may also use your flake inputs as sources.

Example using plugin inputs:

{
  # In your flake.nix
  inputs = {
    aerial-nvim = {
      url = "github:stevearc/aerial.nvim"
      flake = false;
    };
  };

  # Make sure that 'inputs' is properly propagated into Nvf, for example, through
  # specialArgs.
  outputs = { ... };
}

In the case, you may use the input directly for the plugin’s source attribute in buildVimPlugin.

# Make sure that 'inputs' is properly propagated! It will be missing otherwise
# and the resulting errors might be too obscure.
{inputs, ...}: let
  aerial-from-source = pkgs.vimUtils.buildVimPlugin {
      name = "aerial-nvim";
      src = inputs.aerial-nvim;
    };
in {
  vim.extraPlugins = {
    aerial = {
      package = aerial-from-source;
      setup = "require('aerial').setup {}";
    };
  };
}

Alternatively, if you do not want to keep track of the source using flake inputs or npins, you may call fetchFromGitHub (or other fetchers) directly. An example would look like this.

regexplainer = buildVimPlugin {
  name = "nvim-regexplainer";
  src = fetchFromGitHub {
    owner = "bennypowers";
    repo = "nvim-regexplainer";
    rev = "4250c8f3c1307876384e70eeedde5149249e154f";
    hash = "sha256-15DLbKtOgUPq4DcF71jFYu31faDn52k3P1x47GL3+b0=";
  };

  # The 'buildVimPlugin' imposes some "require checks" on all plugins build from
  # source. Failing tests, if they are not relevant, can be disabled using the
  # 'nvimSkipModule' argument to the 'buildVimPlugin' function.
  nvimSkipModule = [
    "regexplainer"
    "regexplainer.buffers.init"
    "regexplainer.buffers.popup"
    "regexplainer.buffers.register"
    "regexplainer.buffers.shared"
    "regexplainer.buffers.split"
    "regexplainer.component.descriptions"
    "regexplainer.component.init"
    "regexplainer.renderers.narrative.init"
    "regexplainer.renderers.narrative.narrative"
    "regexplainer.renderers.init"
    "regexplainer.utils.defer"
    "regexplainer.utils.init"
    "regexplainer.utils.treesitter"
  ];
}

Hacking nvf

nvf is designed for the developer as much as it is designed for the end-user. We would like for any contributor to be able to propagate their changes, or add new features to the project with minimum possible friction. As such, below are the guides and guidelines written to streamline the contribution process and to ensure that your valuable input integrates into nvf’s development as seamlessly as possible without leaving any question marks in your head.

This section is directed mainly towards those who wish to contribute code into the project. If you instead wish to report a bug, or discuss a potential new feature implementation (which you do not wish to implement yourself) first look among the already open issues and if no matching issue exists you may open a new issue and describe your problem/request.

While creating an issue, please try to include as much information as you can, ideally also include relevant context in which an issue occurs or a feature should be implemented. If you wish to make a contribution, but feel stuck - please do not be afraid to submit a pull request, we will help you get it in.

Getting Started

You, naturally, would like to start by forking the repository to get started. If you are new to Git and GitHub, do have a look at GitHub’s Fork a repo guide for instructions on how you can do this. Once you have a fork of nvf, you should create a separate branch based on the most recent main branch. Give your branch a reasonably descriptive name (e.g. feature/debugger or fix/pesky-bug) and you are ready to work on your changes

Implement your changes and commit them to the newly created branch and when you are happy with the result, and positive that it fulfills our Contributing Guidelines, push the branch to GitHub and create a pull request. The default pull request template available on the nvf repository will guide you through the rest of the process, and we’ll gently nudge you in the correct direction if there are any mistakes.

Guidelines

If your contribution tightly follows the guidelines, then there is a good chance it will be merged without too much trouble. Some of the guidelines will be strictly enforced, others will remain as gentle nudges towards the correct direction. As we have no automated system enforcing those guidelines, please try to double check your changes before making your pull request in order to avoid “faulty” code slipping by.

If you are uncertain how these rules affect the change you would like to make then feel free to start a discussion in the discussions tab ideally (but not necessarily) before you start developing.

Adding Documentation

Almost all changes warrant updates to the documentation: at the very least, you must update the changelog. Both the manual and module options use Nixpkgs Flavoured Markdown.

The HTML version of this manual containing both the module option descriptions and the documentation of nvf (such as this page) can be generated and opened by typing the following in a shell within a clone of the nvf Git repository:

$ nix build .#docs-html
$ xdg-open $PWD/result/share/doc/nvf/index.html

Formatting Code

Make sure your code is formatted as described in code-style section. To maintain consistency throughout the project you are encouraged to browse through existing code and adopt its style also in new code.

Formatting Commits

Similar to code style guidelines we encourage a consistent commit message format as described in commit style guidelines.

Commit Style

The commits in your pull request should be reasonably self-contained. Which means each and every commit in a pull request should make sense both on its own and in general context. That is, a second commit should not resolve an issue that is introduced in an earlier commit. In particular, you will be asked to amend any commit that introduces syntax errors or similar problems even if they are fixed in a later commit.

The commit messages should follow the seven rules, except for “Capitalize the subject line”. We also ask you to include the affected code component or module in the first line. A commit message ideally, but not necessarily, follow the given template from home-manager’s own documentation

  {component}: {description}

  {long description}

where {component} refers to the code component (or module) your change affects, {description} is a very brief description of your change, and {long description} is an optional clarifying description. As a rare exception, if there is no clear component, or your change affects many components, then the {component} part is optional. See example commit message for a commit message that fulfills these requirements.

Example Commit

The commit 69f8e47e9e74c8d3d060ca22e18246b7f7d988ef in home-manager contains the following commit message.

starship: allow running in Emacs if vterm is used

The vterm buffer is backed by libvterm and can handle Starship prompts
without issues.

Similarly, if you are contributing to nvf, you would include the scope of the commit followed by the description:

languages/ruby: init module

Adds a language module for Ruby, adds appropriate formatters and Treesitter grammars

Long description can be omitted if the change is too simple to warrant it. A minor fix in spelling or a formatting change does not warrant long description, however, a module addition or removal does as you would like to provide the relevant context, i.e. the reasoning behind it, for your commit.

Finally, when adding a new module, say modules/foo.nix, we use the fixed commit format foo: add module. You can, of course, still include a long description if you wish.

In case of nested modules, i.e modules/languages/java.nix you are recommended to contain the parent as well - for example languages/java: some major change.

Code Style

Treewide

Keep lines at a reasonable width, ideally 80 characters or less. This also applies to string literals and module descriptions and documentation.

Nix

nvf is formatted by the alejandra tool and the formatting is checked in the pull request and push workflows. Run the nix fmt command inside the project repository before submitting your pull request.

While Alejandra is mostly opinionated on how code looks after formatting, certain changes are done at the user’s discretion based on how the original code was structured.

Please use one line code for attribute sets that contain only one subset. For example:

# parent modules should always be unfolded
# which means module = { value = ... } instead of module.value = { ... }
module = {
  value = mkEnableOption "some description" // { default = true; }; # merges can be done inline where possible

    # same as parent modules, unfold submodules
    subModule = {
        # this is an option that contains more than one nested value
        # Note: try to be careful about the ordering of `mkOption` arguments.
        # General rule of thumb is to order from least to most likely to change.
        # This is, for most cases, type < default < description.
        # Example, if present, would be between default and description
        someOtherValue = mkOption {
            type = lib.types.bool;
            default = true;
            description = "Some other description";
        };
    };
}

If you move a line down after the merge operator, Alejandra will automatically unfold the whole merged attrset for you, which we do not want.

module = {
  key = mkEnableOption "some description" // {
    default = true; # we want this to be inline
  }; # ...
}

For lists, it is mostly up to your own discretion how you want to format them, but please try to unfold lists if they contain multiple items and especially if they are to include comments.

# this is ok
acceptableList = [
  item1 # comment
  item2
  item3 # some other comment
  item4
];

# this is not ok
listToBeAvoided = [item1 item2 /* comment */ item3 item4];

# this is ok
acceptableList = [item1 item2];

# this is also ok if the list is expected to contain more elements
acceptableList= [
  item1
  item2
  # more items if needed...
];

Testing Changes

Once you have made your changes, you will need to test them thoroughly. If it is a module, add your module option to configuration.nix (located in the root of this project) inside neovimConfiguration. Enable it, and then run the maximal configuration with nix run .#maximal -Lv to check for build errors. If neovim opens in the current directory without any error messages (you can check the output of :messages inside neovim to see if there are any errors), then your changes are good to go. Open your pull request, and it will be reviewed as soon as possible.

If it is not a new module, but a change to an existing one, then make sure the module you have changed is enabled in the maximal configuration by editing configuration.nix, and then run it with nix run .#maximal -Lv. Same procedure as adding a new module will apply here.

Keybinds

As of 0.4, there exists an API for writing your own keybinds and a couple of useful utility functions are available in the extended standard library. The following section contains a general overview to how you may utilize said functions.

Custom Key Mappings Support for a Plugin

To set a mapping, you should define it in vim.keymaps.

An example, simple keybinding, can look like this:

{
  vim.keymaps = [
    {
      key = "<leader>wq";
      mode = ["n"];
      action = ":wq<CR>";
      silent = true;
      desc = "Save file and quit";
    }
  ];
}

There are many settings available in the options. Please refer to the documentation to see a list of them.

nvf provides a helper function, so that you don’t have to write the mapping attribute sets every time:

  • mkKeymap, which mimics neovim’s vim.keymap.set function

You can read the source code of some modules to see them in action, but the usage should look something like this:

# plugindefinition.nix
{lib, ...}: let
  inherit (lib.options) mkEnableOption;
  inherit (lib.nvim.binds) mkMappingOption;
in {
  options.vim.plugin = {
    enable = mkEnableOption "Enable plugin";

    # Mappings should always be inside an attrset called mappings
    mappings = {
      workspaceDiagnostics = mkMappingOption "Workspace diagnostics [trouble]" "<leader>lwd";
      documentDiagnostics = mkMappingOption "Document diagnostics [trouble]" "<leader>ld";
      lspReferences = mkMappingOption "LSP References [trouble]" "<leader>lr";
      quickfix = mkMappingOption "QuickFix [trouble]" "<leader>xq";
      locList = mkMappingOption "LOCList [trouble]" "<leader>xl";
      symbols = mkMappingOption "Symbols [trouble]" "<leader>xs";
    };
}
# config.nix
{
  config,
  lib,
  options,
  ...
}: let
  inherit (lib.modules) mkIf;
  inherit (lib.nvim.binds) mkKeymap;

  cfg = config.vim.plugin;

  keys = cfg.mappings;
  inherit (options.vim.lsp.trouble) mappings;
in {
  config = mkIf cfg.enable {
    vim.keymaps = [
      (mkKeymap "n" keys.workspaceDiagnostics "<cmd>Trouble toggle diagnostics<CR>" {desc = mappings.workspaceDiagnostics.description;})
      (mkKeymap "n" keys.documentDiagnostics "<cmd>Trouble toggle diagnostics filter.buf=0<CR>" {desc = mappings.documentDiagnostics.description;})
      (mkKeymap "n" keys.lspReferences "<cmd>Trouble toggle lsp_references<CR>" {desc = mappings.lspReferences.description;})
      (mkKeymap "n" keys.quickfix "<cmd>Trouble toggle quickfix<CR>" {desc = mappings.quickfix.description;})
      (mkKeymap "n" keys.locList "<cmd>Trouble toggle loclist<CR>" {desc = mappings.locList.description;})
      (mkKeymap "n" keys.symbols "<cmd>Trouble toggle symbols<CR>" {desc = mappings.symbols.description;})
    ];
  };
}

Note

If you have come across a plugin that has an API that doesn’t seem to easily allow custom keybindings, don’t be scared to implement a draft PR. We’ll help you get it done.

Adding Plugins

To add a new Neovim plugin, use npins

Use:

nix-shell -p npins or nix shell nixpkgs#npins

Then run:

npins add --name <plugin name> github <owner> <repo> -b <branch>

Be sure to replace any non-alphanumeric characters with - for --name

For example

npins add --name lazydev-nvim github folke lazydev.nvim -b main

You can now reference this plugin as a string.

config.vim.startPlugins = ["lazydev-nvim"];

Modular setup options

Most plugins is initialized with a call to require('plugin').setup({...}).

We use a special function that lets you easily add support for such setup options in a modular way: mkPluginSetupOption.

Once you have added the source of the plugin as shown above, you can define the setup options like this:

# in modules/.../your-plugin/your-plugin.nix

{lib, ...}:
let
  inherit (lib.types) bool int;
  inherit (lib.nvim.types) mkPluginSetupOption;
in {
  options.vim.your-plugin = {
    setupOpts = mkPluginSetupOption "plugin name" {
      enable_feature_a = mkOption {
        type = bool;
        default = false;
        # ...
      };

      number_option = mkOption {
        type = int;
        default = 3;
        # ...
      };
    };
  };
}
# in modules/.../your-plugin/config.nix
{lib, config, ...}:
let
  cfg = config.vim.your-plugin;
in {
  vim.luaConfigRC = lib.nvim.dag.entryAnywhere ''
    require('plugin-name').setup(${lib.nvim.lua.toLuaObject cfg.setupOpts})
  '';
}

This above config will result in this lua script:

require('plugin-name').setup({
  enable_feature_a = false,
  number_option = 3,
})

Now users can set any of the pre-defined option field, and can also add their own fields!

# in user's config
{
  vim.your-plugin.setupOpts = {
    enable_feature_a = true;
    number_option = 4;
    another_field = "hello";
    size = { # nested fields work as well
      top = 10;
    };
  };
}

Details of toLuaObject

As you’ve seen above, toLuaObject is used to convert our nix attrSet cfg.setupOpts, into a lua table. Here are some rules of the conversion:

  1. nix null converts to lua nil

  2. number and strings convert to their lua counterparts

  3. nix attrSet/list convert into lua tables

  4. you can write raw lua code using lib.generators.mkLuaInline. This function is part of nixpkgs.

Example:

vim.your-plugin.setupOpts = {
  on_init = lib.generators.mkLuaInline ''
    function()
      print('we can write lua!')
    end
  '';
}

Lazy plugins

If the plugin can be lazy-loaded, vim.lazy.plugins should be used to add it. Lazy plugins are managed by lz.n.

# in modules/.../your-plugin/config.nix
{lib, config, ...}:
let
  cfg = config.vim.your-plugin;
in {
  vim.lazy.plugins.your-plugin = {
    # instead of vim.startPlugins, use this:
    package = "your-plugin";

    # if your plugin uses the `require('your-plugin').setup{...}` pattern
    setupModule = "your-plugin";
    inherit (cfg) setupOpts;

    # events that trigger this plugin to be loaded
    event = ["DirChanged"];
    cmd = ["YourPluginCommand"];

    # keymaps
    keys = [
      # we'll cover this in detail in the keymaps section
      {
        key = "<leader>d";
        mode = "n";
        action = ":YourPluginCommand";
      }
    ];
  };
;
}

This results in the following lua code:

require('lz.n').load({
  {
    "name-of-your-plugin",
    after = function()
      require('your-plugin').setup({--[[ your setupOpts ]]})
    end,

    event = {"DirChanged"},
    cmd = {"YourPluginCommand"},
    keys = {
      {"<leader>d", ":YourPluginCommand", mode = {"n"}},
    },
  }
})

A full list of options can be found [here](https://notashelf.github.io/nvf/options.html#opt-vim.lazy.plugins