Giter Site home page Giter Site logo

numtostr / comment.nvim Goto Github PK

View Code? Open in Web Editor NEW
3.5K 17.0 133.0 300 KB

:brain: :muscle: // Smart and powerful comment plugin for neovim. Supports treesitter, dot repeat, left-right/up-down motions, hooks, and more

License: MIT License

Lua 100.00%
neovim nvim plugin neovim-plugin comment neovim-lua comment-plugin treesitter hacktoberfest lua

comment.nvim's Introduction

// Comment.nvim

⚡ Smart and Powerful commenting plugin for neovim ⚡

Comment.nvim

✨ Features

  • Supports treesitter. Read more
  • Supports commentstring. Read :h comment.commentstring
  • Supports line (//) and block (/* */) comments
  • Dot (.) repeat support for gcc, gbc and friends
  • Count support for [count]gcc and [count]gbc
  • Left-right (gcw gc$) and Up-Down (gc2j gc4k) motions
  • Use with text-objects (gci{ gbat)
  • Supports pre and post hooks
  • Ignore certain lines, powered by Lua regex

🚀 Installation

-- add this to your lua/plugins.lua, lua/plugins/init.lua,  or the file you keep your other plugins:
{
    'numToStr/Comment.nvim',
    opts = {
        -- add any options here
    },
    lazy = false,
}
use {
    'numToStr/Comment.nvim',
    config = function()
        require('Comment').setup()
    end
}
Plug 'numToStr/Comment.nvim'

" Somewhere after plug#end()
lua require('Comment').setup()

📖 Getting Help

Comment.nvim provides help docs which can be accessed by running :help comment-nvim

⚒️ Setup

First you need to call the setup() method to create the default mappings.

Note - If you are facing Keybindings are mapped but they are not working issue then please try this

  • Lua
require('Comment').setup()
  • VimL
lua << EOF
require('Comment').setup()
EOF

Configuration (optional)

Following are the default config for the setup(). If you want to override, just modify the option that you want then it will be merged with the default config. Read :h comment.config for more info.

{
    ---Add a space b/w comment and the line
    padding = true,
    ---Whether the cursor should stay at its position
    sticky = true,
    ---Lines to be ignored while (un)comment
    ignore = nil,
    ---LHS of toggle mappings in NORMAL mode
    toggler = {
        ---Line-comment toggle keymap
        line = 'gcc',
        ---Block-comment toggle keymap
        block = 'gbc',
    },
    ---LHS of operator-pending mappings in NORMAL and VISUAL mode
    opleader = {
        ---Line-comment keymap
        line = 'gc',
        ---Block-comment keymap
        block = 'gb',
    },
    ---LHS of extra mappings
    extra = {
        ---Add comment on the line above
        above = 'gcO',
        ---Add comment on the line below
        below = 'gco',
        ---Add comment at the end of line
        eol = 'gcA',
    },
    ---Enable keybindings
    ---NOTE: If given `false` then the plugin won't create any mappings
    mappings = {
        ---Operator-pending mapping; `gcc` `gbc` `gc[count]{motion}` `gb[count]{motion}`
        basic = true,
        ---Extra mapping; `gco`, `gcO`, `gcA`
        extra = true,
    },
    ---Function to call before (un)comment
    pre_hook = nil,
    ---Function to call after (un)comment
    post_hook = nil,
}

🔥 Usage

When you call setup() method, Comment.nvim sets up some basic mapping which can be used in NORMAL and VISUAL mode to get you started with the pleasure of commenting stuff out.

Basic mappings

These mappings are enabled by default. (config: mappings.basic)

  • NORMAL mode
`gcc` - Toggles the current line using linewise comment
`gbc` - Toggles the current line using blockwise comment
`[count]gcc` - Toggles the number of line given as a prefix-count using linewise
`[count]gbc` - Toggles the number of line given as a prefix-count using blockwise
`gc[count]{motion}` - (Op-pending) Toggles the region using linewise comment
`gb[count]{motion}` - (Op-pending) Toggles the region using blockwise comment
  • VISUAL mode
`gc` - Toggles the region using linewise comment
`gb` - Toggles the region using blockwise comment

Extra mappings

These mappings are enabled by default. (config: mappings.extra)

  • NORMAL mode
`gco` - Insert comment to the next line and enters INSERT mode
`gcO` - Insert comment to the previous line and enters INSERT mode
`gcA` - Insert comment to end of the current line and enters INSERT mode
Examples
# Linewise

`gcw` - Toggle from the current cursor position to the next word
`gc$` - Toggle from the current cursor position to the end of line
`gc}` - Toggle until the next blank line
`gc5j` - Toggle 5 lines after the current cursor position
`gc8k` - Toggle 8 lines before the current cursor position
`gcip` - Toggle inside of paragraph
`gca}` - Toggle around curly brackets

# Blockwise

`gb2}` - Toggle until the 2 next blank line
`gbaf` - Toggle comment around a function (w/ LSP/treesitter support)
`gbac` - Toggle comment around a class (w/ LSP/treesitter support)

🌳 Treesitter

This plugin has native treesitter support for calculating commentstring which works for multiple (injected/embedded) languages like Vue or Markdown. But due to the nature of the parsed tree, this implementation has some known limitations.

  1. No jsx/tsx support. Its implementation was quite complicated.
  2. Invalid comment on the region where one language ends and the other starts. Read more
  3. Unexpected comment on a line with multiple languages. #144

For advance use cases, use nvim-ts-context-commentstring. See pre_hook section for the integration.

Note - This plugin does not depend on nvim-treesitter however it is recommended in order to easily install tree-sitter parsers.

🎣 Hooks

There are two hook methods i.e pre_hook and post_hook which are called before comment and after comment respectively. Both should be provided during setup().

  • pre_hook - Called with a ctx argument (Read :h comment.utils.CommentCtx) before (un)comment. Can optionally return a commentstring to be used for (un)commenting.
{
    pre_hook = function(ctx)
        if ctx.range.srow == ctx.range.erow then
            -- do something with the current line
        else
            -- do something with lines range
        end
    end,
}

You can also integrate nvim-ts-context-commentstring using pre_hook to easily comment tsx/jsx files.

Note - Comment.nvim already supports treesitter out-of-the-box for all the languages except tsx/jsx.

{
    pre_hook = require('ts_context_commentstring.integrations.comment_nvim').create_pre_hook(),
}

  • post_hook - This method is called after (un)commenting. It receives the same ctx (Read :h comment.utils.CommentCtx) argument as pre_hook.
{
    post_hook = function(ctx)
        if ctx.range.srow == ctx.range.erow then
            -- do something with the current line
        else
            -- do something with lines range
        end
    end,
}

The post_hook can be implemented to cover some niche use cases like the following:

  • Using newlines instead of padding e.g. for commenting out code in C with #if 0. See an example here.
  • Duplicating the commented block (using pre_hook) and moving the cursor to the next block (using post_hook). See this.

NOTE: When pressing gc, gb and friends, cmode (Comment mode) inside pre_hook will always be toggle because when pre-hook is called, in that moment we don't know whether gc or gb will comment or uncomment the lines. But luckily, we do know this before post_hook and this will always receive either comment or uncomment status

🚫 Ignoring lines

You can use ignore to ignore certain lines during comment/uncomment. It can takes lua regex string or a function that returns a regex string and should be provided during setup().

NOTE: Ignore only works when with linewise comment. This is by design. As ignoring lines in block comments doesn't make that much sense.

  • With string
-- ignores empty lines
ignore = '^$'

-- ignores line that starts with `local` (excluding any leading whitespace)
ignore = '^(%s*)local'

-- ignores any lines similar to arrow function
ignore = '^const(.*)=(%s?)%((.*)%)(%s?)=>'
  • With function
{
    ignore = function()
        -- Only ignore empty lines for lua files
        if vim.bo.filetype == 'lua' then
            return '^$'
        end
    end,
}

🗨️ Filetypes + Languages

Most languages/filetypes have native support for comments via commentstring but there might be a filetype that is not supported. There are two ways to enable commenting for unsupported filetypes:

  1. You can set commentstring for that particular filetype like the following. Read :h commentstring for more info.
vim.bo.commentstring = '//%s'

-- or
vim.api.nvim_command('set commentstring=//%s')

  1. You can also use this plugin interface to store both line and block commentstring for the filetype. You can treat this as a more powerful version of the commentstring. Read :h comment.ft for more info.
local ft = require('Comment.ft')

-- 1. Using set function

ft
 -- Set only line comment
 .set('yaml', '#%s')
 -- Or set both line and block commentstring
 .set('javascript', {'//%s', '/*%s*/'})

-- 2. Metatable magic

ft.javascript = {'//%s', '/*%s*/'}
ft.yaml = '#%s'

-- Multiple filetypes
ft({'go', 'rust'}, ft.get('c'))
ft({'toml', 'graphql'}, '#%s')

PR(s) are welcome to add more commentstring inside the plugin

🤝 Contributing

There are multiple ways to contribute reporting/fixing bugs, feature requests. You can also submit commentstring to this plugin by updating ft.lua and sending PR.

📺 Videos

💐 Credits

  • tcomment - To be with me forever and motivated me to write this.
  • nvim-comment - Little and less powerful cousin. Also I took some code from it.
  • kommentary - Nicely done plugin but lacks some features. But it helped me to design this plugin.

🚗 Roadmap

  • Doc comment i.e /**%s*/ (js), ///%s (rust)
  • Header comment
----------------------
-- This is a header --
----------------------

comment.nvim's People

Contributors

akmadan23 avatar aspeddro avatar codyopel avatar eeexun avatar figsoda avatar fraserlee avatar halbaroth avatar jandamm avatar jmbuhr avatar mithicspirit avatar mvllow avatar numtostr avatar oyarsa avatar p-miranda avatar rafamadriz avatar rasa-silva avatar rielj avatar saecki avatar sahashirshendu avatar sbennett33 avatar shubham-cpp avatar sudhih avatar tjdevries avatar tjex avatar toh995 avatar tornaxo7 avatar tristan957 avatar ttytm avatar vlad-tymoshchyk avatar wesleimp avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

comment.nvim's Issues

Smart block comments

I was thinking if it makes sense to remove the current block comment with gbc.

What I mean:

let name = /* som|ething */ else
-> (gbc) ->
let name = som|ething else
let name = |/* something */ else
-> (gbc) ->
/* let name = |/* something */ else */

Maybe another mapping would make more sense, but I think this feature is handy.
What do you think?

[Feature request] toggle_visual()

This is an amazing commenting plugin, the only reason stopping me form using it is the fact that it does the mappings for you
now I don't use motions to comment but visual commenting is a must.

I can do single lines with mapping :lua require "Comment".toggle()<CR> however as far as I know there is no equivalent to that function to visual mode.

Expose `<Plug>` mappings

I can't do much about it. You'll still need to know a little about how VISUAL mode works. Also, we can mention this in docs :)

My mappings with Kommentay were like this:

local map = require'map'
map.n{'<leader>c', '<Plug>kommentary_line_default', noremap = false}
map.x{'<leader>c', '<Plug>kommentary_visual_default<C-c>', noremap = false}

I don't know what it's going on under the hood. I wonder if it's something that could be applied here as well?

Originally posted by @mbenford in #78 (comment)

Restore cursor position

Currently when the cursor is in the middle of a paragraph and I comment it out with gcap the cursor is moved to the beginning of the paragraph. I would like the cursor not to move but to stay at the same position.

With vim-commentary I worked around that by overriding gcap with a mapping which would create a mark before commenting the paragraph and than move the cursor back to that mark.

nn gcap my<cmd>norm vip<bar>gc<cr>`y

However, because of issue #24 the mark gets deleted after commenting with Comment.nvim and the cursor can not jump back.

migrate to `nvim_buf_set_text`

Currently, nvim_buf_set_lines() is used which should be replaced with nvim_buf_set_text().

Why?

This is from :h nvim_buf_set_text()

                This is recommended over nvim_buf_set_lines when only
                modifying parts of a line, as extmarks will be preserved on
                non-modified parts of the touched lines.

How?

Currently, comment/uncomment is done by slicing, dicing, and modifying the lines. Because of this we only had to care about line numbers or rows. But for nvim_buf_set_text() we also need to consider the start and end of the starting and ending column to perfectly place/remove the comments

Partial block comments ie. `gba{`, `gb34w`

Say you have this code:

config = {
   Some text here
}

If I put my cursor inside Some and type gciw/gbiw itll comment out just the word. Basically any subline motion will do a block comment. this is good

If I do gca{ it linewise comments all 3 lines, this is expected. But if I do gba{ it will blockwise comment but the config = will also be included inside the block comment. So its practically equivalent to linewise commenting the whole thing.

So it seems multiline block comments expand to fill the whole lines, but I think just commenting out the part of the motion would make more sense. Is this a bug or intended behaviour?

[FEATURE] Allow to use a newline instead of padding

Hi,

it would be great to have support to comment out code blocks in C using #if 0, like:

#if 0
/* main */
int main(void)
{
    return 0;
}
#endif

The reason is that also comment blocks can be commented out. Sadly the following doesn't work (yet):

ft.set('c', {'/*%s*/', '#if 0\n%s\n#endif'})

Thanks!

how to remove mappings ?

hi, it might come across as a simple question but how can I remove mappings?

in the config, I tried this but it gives an error

    toggler = {
        ---line-comment keymap
        line = 'gcc',
        ---block-comment keymap
        block = '',
    },

in the config, I tried this but it the default mapping is set

    toggler = {
        ---line-comment keymap
        line = 'gcc',
        ---block-comment keymap
        block = nil,
    },

in the config, I tried this but it the default mapping is set

    toggler = {
        ---line-comment keymap
        line = 'gcc',

    },

Allow default line commenting to /* */ for C

Hey,
currently line commenting(gcc) comments line starting with // and /* / for block commenting, I like to have / */ commenting for one line comments as well, it's also the default behavior with tpope's commentary plugin.

Configurable padding for `norm_A`.

Hello and thank you for the plugin.

I'm looking to configure the number of padding characters for norm_A. I see the utility with the note for adding configurable padding, but I specifically would like padding between the end of line and the comment character. The current usage of get_padding seems to be for the padding between the comment character and the comment text.

alphabet = "abcdefg"  # the comment character is preceded by two spaces

Implementation-wise, I think padding could be a table with left and right keys. I'd be willing to implement it if you'd give a description of possible configurations, like:

  • true -> {left = ' ', right = ' '}, false -> { left = ' ', right = ''},
  • number -> {left = ' ' * num, right = ' '}
  • table -> if key is number, then it's ' ' * num, if key is string then it's used as is, missing keys taken as ' '

Option to duplicate + comment

Very often I like to duplicate a block of code and comment out a copy.

For example,

for i in range(2, 20:
     print(i)
# for i in range(2, 20:
#     print(i)
for i in range(2, 20:
     print(i)

Right now, I have to repeat a motion twice -- once to yank and once to comment out. And then of course I have to hit p to paste in the duplicate. It gets more complicated if I have to avoid clobbering my default register.

It would be nice to have this all rolled into one motion (that takes care of saving/restoring the registers).
Eg., gC" (or gyetc.) will behave just likegc`` but will paste a copy of the uncommented code next to the commented one.

Is it possible to support this?

Add an option for enforcing `gc` for line comments only and `gb` for block comments only

Current behaviour

Performing gc on a text object that is within a single line's bounds puts it in a block comment.

Expected behaviour

Performing gc will always comment selected range line-wise. For block comments, I can always use gb. kommentary has prefer_single_line_comments option, which does exactly that.

Some examples

  • gcl

    return function() end

    Result:

     --[[   ]]return function() end

    Expected:

      -- return function() end
  • gcaf (w/ tree-sitter)

    return function() end

    Result:

     
      return --[[ function() end ]]

    Expected:

     
      -- return function() end

Proposed solution

Modify block_x definition to include the option for enforcing comment type.

    local block_x = partial_block and same_line and not (cfg.enforced_type and ctype == U.ctype.line)

Support advanced multiline strings in lua e.g. --[=[ something ]=]

Just from reading the readme it sounds like this might be possible using the pre_hook, but I'm not sure exactly how I'd go about it.

I have copied the text below from my kommentary request for the same functionality (b3nj5m1n/kommentary#67)


Lua supports semi-arbitrary multiline comment strings in the form of matching numbers of equals signs. Meaning --[==[, --[===[, and --[=[ will only end the comment when it encounters ]==], ]===], and ]=] respectively.

It would be a great idea to match an opening regex like --\[\(=*\)\[ (or --\[(=*)\[ in PCRE style just to make sure it's clear) to the closing ]\1] (using the capture group from the opening regex to guarantee the same number of =)

This may not be as important when creating the comments, but is important to effectively uncomment them.

Block line commenting is broken

Here's my config:

return {
  'numToStr/Comment.nvim',
  config = function()
    require('Comment').setup({
      mappings = {
        basic = false,
        extra = false,
      },
      toggler = {
        line = '<leader>c',
        block = '<leader>c',
      },
    })
  end,
}

And when I do <leader>c I get this error: E5108: Error executing lua ...ite/pack/packer/start/Comment.nvim/lua/Comment/utils.lua:200: attempt to index local 'ln' (a nil value)

[Feature]: adding vim-commentary's `gcgc`?

vim-commentary has a normal mode gcgc keybinding to uncomment a block of commented lines.

Before ↓

printf("Hello");
// printf("Hello");
// printf("Hello");
printf("Hello");

After pressing gcgc with cursor on line 2 or 3 ↓

printf("Hello");
printf("Hello");
printf("Hello");
printf("Hello");

Also gbgb would be really useful to delete block comment without having to select it manually

Calling the linewise comment toggle on multiple lines with visual mode loses selection

If you select multiple lines in visual mode, then run the command documented in the api page (Shown below), then typing gv to reselect previous selection only reselects the starting line, and not the entire selection.

This happens when typing in the lua command manually too, not just when having it mapped.

-- Linewise toggle using C-/
map('x', '<C-_>', '<ESC><CMD>lua require("Comment.api").toggle_linewise_op(vim.fn.visualmode())<CR>')

Add [count]gbc keymap

Hi! Thank you for the plugin, it's really useful!

I'm really missing the feature to toggle block comment for multiple lines using [count]gbc keymap. What do you think about adding it?

I know that there is gb[count]{motion} but for me it's less comfortable

Issue with bindings + commands that enter insert mode

If I bind something that includes a comment.nvim binding, e.g one that adds a comment:

gcATEST you'd expect that TEST would be added to the comment, but it seems that when TEST is input Vim is not yet in insert mode.

gcAaTEST<ESC> tries to account for this, but then I'm left in insert mode at the end.

gcAaTEST yields a comment string TESTa, hinting that you're using a to get into insert mode.

It seems that the command is not done synchronously and this makes is to there's a bit of a race between the function behind gcA and the rest of my mapping.

This is actually not an issue

local langtree = vim.treesitter.get_parser(bufnr)
local cursor = vim.api.nvim_win_get_cursor(win)
local current_tree = langtree:language_for_range {
  cursor[1],
  cursor[2],
  cursor[1],
  cursor[2],
}
local lang = current_tree:lang()

Invalid `css` comments on empty lines

Okay so I found out some of the issues and why they happen (I think). It seems to be the case like you say that treesitter is interpreting it as another language, but I could only reproduce this if the newline is between the starting tag and the first line inside the tags.

<script lang="ts">

import { defineComponent } from 'vue';
export default defineComponent({
  name: 'test',
  },
});
</script>

With the newline there, treesitter interprets that as filetype vue, and I don't think there is much we can do about that. One thing I think we can do is calculate the commentstring based on where the cursor is when doing the motion. Right now it looks like the cursor jumps to the start of the motion, and then when finding the language where the cursor is currently, the language is returned as vue. After this the cursor returns to where it was (probably has something to do with the sticky option). If one is holding the cursor over the newline and uncomment, there isn't much we can do (to my knowledge) since treesitter interprets this as vue.

However there is also a slight issue with empty lines if the commentstring surrounds the string (commentstrings like /* %s */ for example). If there is a newline inside the tag when doing gcit for example, the newline will only get /* inserted on the line. This will mess with the logic of checking if a line is commented or not, so therefore it will try to comment this again instead of uncommenting.

<style>
/* body { */
/*   height: 100vh; */
/*
/* } */
</style>

Note that this will not be an issue with commentstrings like // %s, and also not for those who chose to ignore the newlines in lua pattern option in the setup function. I also don't think this is related to this PR, so this could probably be fixed in another PR.

If we add the rhs of the commentstring (*/) to the newline, after /* the problem is fixed. Like this

<style>
/* body { */
/*   height: 100vh; */
/* */
/* } */
</style>

Originally posted by @seblj in #62 (comment)

Add mappings to insert comment below/above/end of current line

Problem

Sometimes I want to start writing a new comment above/below of current line. I do NOT mean un/commenting a line above/below the current line. I mean create a new empty line below/above the current line, insert commentstring at new line, enter insert mode after commentstring so I can immediately start writing the comment I want to write.

In the case of adding a new comment at the end of the current line I mean that the correct commentstring gets inserted at end of the current line and then the cursor gets moved to the end of the current line and put in insert mode.

Reason

Comment.nvim is great because I can un/comment lines quick without thinking what is the correct commentstring for the particular language. Comment.nvim automatically chooses the correct commentstring for me. However, if I want to write a new comment I have to think about the commentstring and insert it myself. I want Comment.nvim to insert the correct commentstring for me if I want to write a new comment.

The only commenter-plugin I know of which can do that is https://github.com/tyru/caw.vim. This feature would certainly distinguish Comment.nvim from most other commenter-plugins.

Solution

Add mappings:

  • gco creates a new comment below the current line.
  • gcO create a new comment above the current line.
  • gca create a new comment at the end of the current line.

Examples

Cursor position is |.

gco

print("foo|")

type gco

print("foo")
// |

gcO

print("foo|")

type gcO

// |
print("foo")

gca

print("foo|")

type gca

print("foo") // |

Configure relative priority of built-in comments (ft.lua) and commentstring

From the README:

Although, Comment.nvim supports neovim's commentstring but unfortunately it has the least priority. The commentstring is taken from the following place in the respective order.

pre_hook - If a string is returned from this method then it will be used for commenting.

ft_table - If the current filetype is found in the table, then the string there will be used.

commentstring - Neovim's native commentstring for the filetype

README then goes on to provide pre_hook code for integrating with JoosephAlviste/nvim-ts-context-commentstring.

Why not let the user decide whether ft_table or commentstring gets priority (ideally configurable per-filetype?). Letting commentstring have priority would eliminate the need for any integration code at all for nvim-ts-context-commentstring.

[Solved] Blockwise comments broken with context-commentstring

👋🏼,

Cheers for making a great commenting plugin!

I'm running the following config:

require('Comment').setup({
    ignore = '^$',
    pre_hook = function()
        return
            require('ts_context_commentstring.internal').calculate_commentstring()
    end
})

Take the following TypeScript snippet:

if (text == null) {
  text = await readTextFromStdin();
}

Running gbc on the if line gives me:

// if (text == null) {

when it really should give me:

/* if (text == null) { */

Paste as comment

I often find my self wanting to paste yanked text as a comment.

Example:
This is an exam|ple text -> This is an example text #|with a comment

Would this somehow be possible to implement in this plugin? I think what i want is some sort of pasting motion, but i couldn't find anything like that on the internet.
I'm happy for any pointers and tips.

Toggle comment on word doesn't work

I think it worked before but now any time I do gciw it comments the word and next gciw will generate nested comment instead of removing previous one. Is it just my issue? I'm trying that on lua and cpp files with the same results.

Nix: line comment command uses /*%s*/ instead of #%s

If I try to add a line comment in a nix file by using gcc, the line will be changed like this:

/*{ plugin = headwind-nvim; config = "lua require'headwind'.setup{}"; }*/

instead of this:

#{ plugin = headwind-nvim; config = "lua require'headwind'.setup{}"; }

If I add this to my config:

local ft = require('Comment.ft')
ft.nix = {'#%s', '/*%s*/'}

it now works properly.

How to change `gb` to something else

I use gb for Go Back, so I will need to find something else for blockwise comments, probably gC. But either way I don't think I see an option in the configs for changing the mappings?

Does not work with aligned C++ multiblock comment frame

In C++, when one already has aligned comment-frame (e.g. notes for me inserted by a colleague using an external tool like par or boxes or with another neovim plugin, e.g. nvim-commentframe), the keystroke gb} at the start of the multi-line comment does not correctly uncomment the multi-line commented block.

Example

int main() {

    /*
     * Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy
     * eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam
     * voluptua.At vero eos et accusam et justo duo dolores et ea rebum.Stet
     * clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit
     * amet.
     */

    return 0;
}

Expected output of gb} at the start of the comment block

     Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy
     eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam
     voluptua.At vero eos et accusam et justo duo dolores et ea rebum.Stet
     clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit
     amet.

Current output of gb} at the start of the comment block

     * Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy
     * eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam
     * voluptua.At vero eos et accusam et justo duo dolores et ea rebum.Stet
     * clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit
     * amet.

Incorrect documentation about `post_hook`

I am trying post_hook

post_hook = function(ctx, start_col, end_col, start_row, end_row)
    print(start_row, end_row, start_col, end_col)
end

From the print result, it looks to me the function prototype should be

post_hook = function(ctx, start_row, end_row, start_col, end_col, )
    print(start_row, end_row, start_col, end_col)
end

Is there something wrong?

[Feature request] Configure operator pending mode and visual mode mappings separately

Currently, opleader.line and opleader.block are used to configure both operator pending mode mappings and visual mode mappings. I think it would be a bit nicer to have separate config options for the two (that is, add another couple of options for visual.line and visual.block).

My personal use case for this is that I pretty much never use operator pending mode, but use normal mode, count prefixes and visual mode all the time. The way mappings are configured currently, you can't have the same key for toggling comments in both normal and visual mode (without disabling all mappings and creating them yourself, which is what I currently do).

Happy to submit a PR for this if you'd accept it, but I expect it would be a ~2 minute change and the main complication would be making the config somewhat backward incompatible, so not sure how you'd want to handle it.

On a somewhat related note, I think the implementation of the mappings themselves could be simplified, and toggle_current_linewise_op could be made redundant if toggle_linewise_count used v:count1 instead of v:count. Then it would still work to toggle a single line when the user doesn't type a count prefix. Haven't tried it so might be missing something.

API availability and mappings

Is there a reason some API methods are only available when some mappings are enabled? I guess many people (myself included) will use the API to define their own custom key mappings. It would be nice if one could disable all mappings and yet be able to use all API methods.

Count and motion issues

Hi!

Looks like there are some count and motion issues. Look at this example:

2021-10-27.15.58.15.mov

I was using 2gcc or gc1j1 expecting that the first line will become commented and the second one will become uncommented. But the second line is commented twice instead.

Bug or expected behavior?

Is it possible to configure Commment.nvim to add a new comment on a new line

Assuming I have the following:

// one
// two
// three
foo
bar

and my cursor is on 'three', then I would like to be able to press o and for every new line created in insert mode below this one to be automatically-commented. If, however, I want to add an uncommented line after // three then I just move to foo and press O to create an uncommented new line in insert mode above foo. This is commenting behaviour that I'm used to, and it's a lot less work than pressing gco > type comment esc``gco > type comment esc``gco > type comment.

Is this currently possible in Comment.nvim?

Marks disappear in un-/commented lines

If I set a mark at line x (ex. mm to set mark m at line x) and than un-/comment line x with gcc the mark gets deleted. This isn't an issue with vim-commentary.

[Question] Fallback on linewise comment

Hi,

Is there a way to fallback on linewise comment (perhaps with pre-hook?) when invoking blockwise comment when it is not defined for a particular language.

For example, in python, multi-line comments do not exist, so calling blockwise comment on a region in visual mode will result in only the first line being highlighted.

Thanks!

Last visual selection is broken

  1. Press ggV5j
  2. Press gc
  3. Press gv

Behavior:
First line of the file is selected

Expectation:
First five lines of the file are selected.

[Feature] Toggle mixed comments

Given a similar situation ↓ how to comment uncommented lines and uncomment commented ones?

printf("Line 1\n");
printf("Line 2\n");
// printf("Line 3\n");
// printf("Line 4\n");

Expected result: ↓

// printf("Line 1\n");
// printf("Line 2\n");
printf("Line 3\n");
printf("Line 4\n");

The result I get when I select these 4 lines and press gc: ↓

// printf("Line 1\n");
// printf("Line 2\n");
// // printf("Line 3\n");
// // printf("Line 4\n");

I think gc should toggle comments. To comment everything g> is already available...

Feature: Add "duplicate" (yank, comment, paste) function?

Would it be possible to add in a motion for "duplicating" text? I often (hopefully I'm not the only one) will yank and paste and a line/paragraph of code and then comment out the original so I can look at it for reference while I rework it. For example:

def cool_function(hello)
	puts hello
end

Typing something like gcd{motion} (ip here for a paragraph) would give us:

# def cool_function(hello)
# 	puts hello
# end

def cool_function(hello)
	puts hello
end

This was suggested as a feature with vim-commentary but I think it's still being discussed/considered: tpope/vim-commentary#42

It would be neat to see here too 😃

Love the plugin, btw!

Smart `gc{motion}`

Hi, I'm no sure to call this bug or not, but coming from tcomment I miss this feature the most.

Let's say I have the following situation

local str = 'This is a test'
-- local str = 'This is not a test'

with tcomment I can do gc{motion} let's say j or k and the line will switch comment and become

-- local str = 'This is a test'
local str = 'This is not a test'

with Comment.nvim resulting code is

-- local str = 'This is a test'
-- -- local str = 'This is not a test'

so to get the result like tcomment I have to press gcc twice, one on each line.
It's not much but I think this behavior is quality of life improvement.

Thank you for this amazing plugin 👍🏽

Problem with commenting /etc/pacman.conf

Hi,

I have little strange problem. I use Arch Linux, and there is /etc/pacman.conf where you configure option for Arch package manager.
If I do this with

sudo nvim /etc/pacman.conf

or as root

nvim /etc/pacman.conf

And I do gcc it add at start of line ; , like from

#NoUpgrade   =

to

; #NoUpgrade   =

But if I do this with command

sudoedit /etc/pacman.conf

It commenting and uncommenting without problem.
I even nuked my init.lua config to just

-- load plugin manager first
require('plugins._packer')

To be sure, that nothing from my neovim config interrupt with Comment.nvim, but without success.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.