• Stars
    star
    1,061
  • Rank 42,054 (Top 0.9 %)
  • Language
    Lua
  • License
    MIT License
  • Created about 3 years ago
  • Updated 18 days ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Neovim treesitter plugin for setting the commentstring based on the cursor location in a file.

nvim-ts-context-commentstring

A Neovim plugin for setting the commentstring option based on the cursor location in the file. The location is checked via treesitter queries.

This is useful when there are embedded languages in certain types of files. For example, Vue files can have many different sections, each of which can have a different style for comments.

Note that this plugin only changes the commentstring setting. It does not add any mappings for commenting. It is recommended to use a commenting plugin like Comment.nvim alongside this plugin.

Demo gif

Getting started

Requirements:

Installation:

Use your favorite plugin manager. For example, here's how it would look like with lazy.nvim:

require('lazy').setup {
  {
    'nvim-treesitter/nvim-treesitter',
    dependencies = {
      'JoosepAlviste/nvim-ts-context-commentstring',
    },
  },
}

Setup:

Enable the module from nvim-treesitter setup

require('nvim-treesitter.configs').setup {
  -- Install the parsers for the languages you want to comment in
  -- Here are the supported languages:
  ensure_installed = {
    'astro', 'css', 'glimmer', 'graphql', 'handlebars', 'html', 'javascript',
    'lua', 'nix', 'php', 'python', 'rescript', 'scss', 'svelte', 'tsx', 'twig',
    'typescript', 'vim', 'vue',
  },

  context_commentstring = {
    enable = true,
  },
}

Note

There is a minimal configuration file available at utils/minimal_init.lua for reference.

Note

Don't forget to use :h lua-heredoc if you're using init.vim.

Configuration

It is recommended to use a commenting plugin that has an integration available with this plugin. Then, the commentstring calculation can be triggered only when commenting. The available integrations are listed in the wiki. The following plugins have an integration available:

However, if an integration is not set up, then the default behavior is to calculate the commentstring on the CursorHold autocmd, meaning that the :h updatetime should be set to a smaller value than the default of 4s:

vim.opt.updatetime = 100

Note

For more advanced configuration options, see :h ts-context-commentstring.

More demos

React:

React demo gif

Svelte:

Svelte demo gif

HTML:

html

Nesting:

I injected HTML into JavaScript strings and created multiple levels of nesting with language tree. This sort of nesting of languages works without any extra configuration in the plugin.

nested