Search code examples
documentneovimtxt

How to Write and Highlight Custom Documentation for Neovim


I am new to Neovim, and I have written some plugins.

I want to learn how to write documentation. As far as I know:

*tag*         - Defines a tag
|link|        - Links to other help topics. Press `K` (uppercase) to navigate to the tag, `ctrl+o` to go back, and `ctrl+i` to switch to the previous.
>command<     - Command (or codeblock)
`example`     - Code example

I wrote a test template:

~/.config/nvim/doc/myplugin.txt

*myplugin.txt*    For Vim version 8.0 and above       Last Change: YYYY-MM-DD

My Plugin Documentation                          *myplugin*

==============================================================================
1. Introduction~                                *myplugin-intro*
This plugin provides custom key mappings for executing selections in Neovim.

>
    <leader>r
<

Then I ran the command:

:helptags ~/.config/nvim/doc

It successfully generated:

:helptags ~/.config/nvim/doc/tags

However, when I use :help myplugin.txt to open the corresponding help file, there's no syntax highlighting.

This is different from what I see when I access :help plugin (which contains color highlights).

So, I want to know how to achieve that effect.


Solution

  • First, you can check the current file's filetype with:

    # Check filetype
    :set ft?
    

    In Vim, the highlighting is tied to the filetype=help.

    Therefore, you can enforce the help filetype with:

    :set ft=help
    

    Once set, you will see the syntax highlighting.


    The recommended approach is to configure this setting in init.lua. For example:

    vim.api.nvim_create_augroup("FiletypeHelp",
            { clear = true } -- Deletes the group if it already exists
    )
    vim.api.nvim_create_autocmd({ "BufRead", "BufNewFile" }, {
        pattern = "*/doc/*.txt",
        callback = function()
            vim.bo.filetype = "help"
        end,
        group = "FiletypeHelp", -- The above content belongs to this group
    })
    

    With this configuration, all files matching the pattern */doc/*.txt will automatically have their filetype set to help.

    This avoids the need to manually set :set ft=help each time.