nvf manual

Version v0.6


Table of Contents

Preface
Try it out
Using Prebuilt Configs
Default Configs
Maximal
Nix
Installing nvf
Standalone Installation
Standalone Installation on NixOS
Standalone Installation on Home-Manager
Module Installation
NixOS Module
Home-Manager Module
Configuring nvf
Custom Neovim Package
Custom Plugins
Adding Plugins
Language Support
LSP Custom Packages/Command
Using DAGs
entryAnywhere
entryAfter
entryBefore
entryBetween
entriesAnywhere
entriesAfter
entriesBefore
entriesBetween
Hacking nvf
Getting Started
Guidelines
Testing Changes
Keybinds
Adding Plugins
A. Plugin specific quirks
NodeJS
B. Neovim Flake Configuration Options
C. Release Notes
Release 0.1
Release 0.2
Release 0.3
Release 0.4
Release 0.5
Release 0.6
Release 0.7

Preface

If you noticed a bug caused by nvf then please consider reporting it over the issue tracker.

Bugfixes, feature additions and upstreamed changes from your local configurations are always welcome in the the pull requests tab.

Try it out

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, three configurations are provided:

  • Nix

  • Maximal

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 Configs

Nix

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

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.

You are strongly recommended to use the binary cache if you would like to try the Maximal configuration.

Default Configs

While you can configure nvf yourself using the builder, you can also use the pre-built configs that are available. Here are a few default configurations you can use.

Table of Contents

Maximal
Nix

Maximal

$ nix shell github:notashelf/nvf#maximal test.nix

It is the same fully configured Neovim as with the Nix configuration, but with every supported language enabled.

Note

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

Nix

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

Enables all the of Neovim plugins, with language support for specifically Nix. This lets you see what a fully configured neovim setup looks like without downloading a whole bunch of language servers and associated tools.

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 by nvf extended library. It takes in the configuration as a module, and returns an attribute set 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";
}

Standalone Installation on NixOS

Your built Neoevim 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.

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

  outputs = {nixpkgs, 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 {
      modules = [configModule];
      inherit pkgs;
    };
  in {
    # this will make the package available as a flake input
    packages.${system}.my-neovim = customNeovim.neovim;

    # this is an example nixosConfiguration using the built neovim package
    nixosConfigurations = {
      yourHostName = nixpkgs.lib.nixosSystem {
        # ...
        modules = [
          ./configuration.nix # or whatever your configuration is

          # this will make wrapped neovim available in your system packages
          {environment.systemPackages = [customNeovim.neovim];}
        ];
        # ...
      };
    };
  };
}

Standalone Installation on Home-Manager

Your built Neoevim 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.

{
  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 {
      modules = [configModule];
      inherit pkgs;
    };
  in {
    # this will make the package available as a flake input
    packages.${system}.my-neovim = customNeovim.neovim;

    # this is an example home-manager configuration
    # using the built neovim package
    homeConfigurations = {
      "your-username@your-hostname" = home-manager.lib.homeManagerConfiguration {
        # ...
        modules = [
          ./home.nix

          # this will make wrapped neovim available in your system packages
          {environment.systemPackages = [customNeovim.neovim];}
        ];
        # ...
      };
    };
  };
}

Module Installation

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 = {
    obsidian-nvim.url = "github:epwalsh/obsidian.nvim";
    nvf = {
      url = "github:notashelf/nvf";
      # you can override input nixpkgs
      inputs.nixpkgs.follows = "nixpkgs";
      # 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, ... }: let
  system = "x86_64-linux"; in {
    # ↓ this is your host output in the flake schema
    nixosConfigurations."yourUsername»" = nixpkgs.lib.nixosSystem {
      modules = [
        nvf.nixosModules.default # <- this imports the NixOS module that provides the options
        ./configuration.nix # <- your host entrypoint
      ];
    };
  };
}

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 avaliable 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 = {
    obsidian-nvim.url = "github:epwalsh/obsidian.nvim";
    nvf = {
      url = "github:notashelf/nvf";
      # you can override input nixpkgs
      inputs.nixpkgs.follows = "nixpkgs";
      # 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 argset
  # see example 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, ... }: let
  system = "x86_64-linux"; in {
    # ↓ this is your home output in the flake schema, expected by home-manager
    "your-username@your-hostname" = home-manager.lib.homeManagerConfiguration
      modules = [
        nvf.homeManagerModules.default # <- this imports the home-manager module that provides the options
        ./home.nix # <- your home entrypoint
      ];
    };
  };
}

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 avaliable options in the appendix

Configuring nvf

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.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

nvf, by default, exposes a wide variety of plugins as module options for your convience and bundles necessary dependencies into nvf’s runtime. In case a plugin is not available in nvf, you may consider making a pull request to nvf to include it as a module or you may add it to your configuration locally.

Adding Plugins

There are multiple ways of adding custom plugins to your nvf configuration.

You can use custom plugins, before they are implemented in the flake. To add a plugin to the runtime, you need to add it to the vim.startPlugins list in your configuration.

Adding a plugin to startPlugins will not allow you to configure the plugin that you have adeed, but nvf provides multiple way 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. In that case, you can write custom vimscript or lua config, using either config.vim.configRC or config.vim.luaConfigRC respectively. Both of these options are attribute sets, and you need to give the configuration you’re adding some name, like this:

{
  # this will create an "aquarium" section in your init.vim with the contents of your custom config
  # which will be *appended* to the rest of your configuration, inside your init.vim
  config.vim.configRC.aquarium = "colorscheme aquiarum";
}

Note

If your configuration needs to be put in a specific place in the config, you can use functions from inputs.nvf.lib.nvim.dag to order it. Refer to https://github.com/nix-community/home-manager/blob/master/modules/lib/dag.nix to find out more about the DAG system.

If you successfully made your plugin work, please feel free to create a PR to add it to nvf or open an issue with your findings so that we can make it available for everyone easily.

New Method

As of version 0.5, we have a more extensive API for configuring plugins, under vim.extraPlugins. Instead of using DAGs exposed by the library, you may use the extra plugin module as follows:

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

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

Old Method

Prior to version 0.5, the method of adding new plugins was adding the plugin package to vim.startPlugins and add its configuration as a DAG under one of vim.configRC or vim.luaConfigRC. Users who have not yet updated to 0.5, or prefer a more hands-on approach may use the old method where the load order of the plugins is determined by DAGs.

Adding plugins

To add a plugin to nvf’s runtime, you may add it

{pkgs, ...}: {
  # add a package from nixpkgs to startPlugins
  vim.startPlugins = [
    pkgs.vimPlugins.aerial-nvim  ];
}

And to configure the added plugin, you can use the luaConfigRC option to provide configuration as a DAG using the nvf extended library.

{inputs, ...}: let
  # assuming you have an input called nvf pointing at the nvf repository
  inherit (inputs.nvf.lib.nvim.dag) entryAnywhere;
in {
  vim.luaConfigRC.aerial-nvim= entryAnywhere ''
    require('aerial').setup {
      -- your configuration here
    }
  '';
}

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

In any of the opt.languages.<language>.lsp.package options you can provide your own LSP package, or provide the command to launch the language server, as 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`
    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 configRC or 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;
}

Hacking nvf

nvf is designed for developers as much as it is for the end user. I would like any potential contributor to be able to propagate their desired changes into the repository without the extra effort. As such, below are guides (and guidelines) to streamline the contribution process and ensure that your valuable input seamlessly integrates into nvf’s development without leaving question marks in your head.

This section is mainly directed towards those who wish to contribute code into nvf. If you wish to instead report a bug or discuss a potential feature implementation, 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.

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 msot 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 fullfills 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

Most, if not all, changes warrant changes to the documentation. Module options should be documented with Nixpkgs-flavoured Markdown, albeit with exceptions.

Note

As of v0.5, nvf is itself documented using full markdown in both module options and the manual. With v0.6, this manual has also been converted to markdown in full.

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 grammers

Long description can be ommitted 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
        someOtherValue = mkOption {
            type = lib.types.bool;
            description = "Some other description";
            default = true;
        };
    };
}

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 throughly. 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 posssible.

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.maps.<<mode>>. The available modes are:

  • normal

  • insert

  • select

  • visual

  • terminal

  • normalVisualOp

  • visualOnly

  • operator

  • insertCommand

  • lang

  • command

An example, simple keybinding, can look like this:

{
  vim.maps.normal = {
    "<leader>wq" = {
      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 list of helper commands, so that you don’t have to write the mapping attribute sets every time:

  • mkBinding = key: action: desc: - makes a basic binding, with silent set to true.

  • mkExprBinding = key: action: desc: - makes an expression binding, with lua, silent, and expr set to true.

  • mkLuaBinding = key: action: desc: - makes an expression binding, with lua, and silent set to true.

Do note that the Lua in these bindings is actual Lua, and not pasted into a :lua command. Therefore, you should either pass in a function like require('someplugin').some_function, without actually calling it, or you should define your own functions, for example

function()
  require('someplugin').some_function()
end

Additionally, to not have to repeat the descriptions, there’s another utility function with its own set of functions: Utility function that takes two attribute sets:

  • { someKey = "some_value" }

  • { someKey = { description = "Some Description"; }; }

and merges them into { someKey = { value = "some_value"; description = "Some Description"; }; }

addDescriptionsToMappings = actualMappings: mappingDefinitions:

This function can be used in combination with the same mkBinding functions as above, except they only take two arguments - binding and action, and have different names:

  • mkSetBinding = binding: action: - makes a basic binding, with silent set to true.

  • mkSetExprBinding = binding: action: - makes an expression binding, with lua, silent, and expr set to true.

  • mkSetLuaBinding = binding: action: - makes an expression binding, with lua, and silent set to true.

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

# plugindefinition.nix
{lib, ...}: with lib; {
  options.vim.plugin = {
    enable = mkEnableOption "Enable plugin";

    # Mappings should always be inside an attrset called mappings
    mappings = {
      # mkMappingOption is a helper function from lib,
      # that takes a description (which will also appear in which-key),
      # and a default mapping (which can be null)
      toggleCurrentLine = mkMappingOption "Toggle current line comment" "gcc";
      toggleCurrentBlock = mkMappingOption "Toggle current block comment" "gbc";

      toggleOpLeaderLine = mkMappingOption "Toggle line comment" "gc";
      toggleOpLeaderBlock = mkMappingOption "Toggle block comment" "gb";

      toggleSelectedLine = mkMappingOption "Toggle selected comment" "gc";
      toggleSelectedBlock = mkMappingOption "Toggle selected block" "gb";
    };

  };
}
# config.nix
{
  config,
  pkgs,
  lib,
  ...
}:
  with lib;
  with builtins; let
    cfg = config.vim.plugin;
    self = import ./plugindefinition.nix {inherit lib;};
    mappingDefinitions = self.options.vim.plugin;

    # addDescriptionsToMappings is a helper function from lib,
    # that merges mapping values and their descriptions
    # into one nice attribute set
    mappings = addDescriptionsToMappings cfg.mappings mappingDefinitions;
in {
  config = mkIf (cfg.enable) {
    # ...
    vim.maps.normal = mkMerge [
      # mkSetBinding is another helper function from lib,
      # that actually adds the mapping with a description.
      (mkSetBinding mappings.findFiles "<cmd> Telescope find_files<CR>")
      (mkSetBinding mappings.liveGrep "<cmd> Telescope live_grep<CR>")
      (mkSetBinding mappings.buffers "<cmd> Telescope buffers<CR>")
      (mkSetBinding mappings.helpTags "<cmd> Telescope help_tags<CR>")
      (mkSetBinding mappings.open "<cmd> Telescope<CR>")

      (mkSetBinding mappings.gitCommits "<cmd> Telescope git_commits<CR>")
      (mkSetBinding mappings.gitBufferCommits "<cmd> Telescope git_bcommits<CR>")
      (mkSetBinding mappings.gitBranches "<cmd> Telescope git_branches<CR>")
      (mkSetBinding mappings.gitStatus "<cmd> Telescope git_status<CR>")
      (mkSetBinding mappings.gitStash "<cmd> Telescope git_stash<CR>")

      (mkIf config.vim.lsp.enable (mkMerge [
        (mkSetBinding mappings.lspDocumentSymbols "<cmd> Telescope lsp_document_symbols<CR>")
        (mkSetBinding mappings.lspWorkspaceSymbols "<cmd> Telescope lsp_workspace_symbols<CR>")

        (mkSetBinding mappings.lspReferences "<cmd> Telescope lsp_references<CR>")
        (mkSetBinding mappings.lspImplementations "<cmd> Telescope lsp_implementations<CR>")
        (mkSetBinding mappings.lspDefinitions "<cmd> Telescope lsp_definitions<CR>")
        (mkSetBinding mappings.lspTypeDefinitions "<cmd> Telescope lsp_type_definitions<CR>")
        (mkSetBinding mappings.diagnostics "<cmd> Telescope diagnostics<CR>")
      ]))

      (
        mkIf config.vim.treesitter.enable
        (mkSetBinding mappings.treesitter "<cmd> Telescope treesitter<CR>")
      )
    ];
    # ...
  };
}

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, first add the source url in the inputs section of flake.nix with the prefix plugin-


{
  inputs = {
    # ...
    plugin-neodev-nvim = {
      url = "github:folke/neodev.nvim";
      flake = false;
    };
    # ...
  };
}

The addition of the plugin- prefix will allow nvf to autodiscover the input from the flake inputs automatically, allowing you to refer to it in areas that require a very specific plugin type as defined in lib/types/plugins.nix

You can now reference this plugin using its string name, the plugin will be built with the name and source URL from the flake input, allowing you to refer to it as a string.

config.vim.startPlugins = ["neodev-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
  '';
}