2

I'm currently writing a plugin to quickly appends commented TODO: codetags to the end of a line in any file type.

How can I make vim make use of it's commenstring feature to append a comment that corresponds to the filetype?

I am currently entering those manually but I feel like there may be a more platform agnostic way to do this...

Here is what some of my maps look like right now:

" Markdown todo's
autocmd FileType markdown nnoremap <buffer> td o<Esc>o<Esc>O[comment]:<Space>#<Space>TODO:<Space>
autocmd FileType markdown nnoremap <buffer> TD 0/TODO:<Enter>kd2j
" Vim todo's
autocmd FileType vim nnoremap <buffer> td A<Space><Space>"TODO:<Space>
autocmd FileType vim nnoremap <buffer> TD 0/"TODO:<Enter>d$
" PHP todo's
autocmd FileType php nnoremap <buffer> td A<Space><Space>//TODO:<Space>
autocmd FileType php nnoremap <buffer> TD j0?//TODO:<Enter>d$
" Javascript todo's
autocmd FileType javascript nnoremap <buffer> td A<Space><Space>//TODO:<Space>
autocmd FileType javascript nnoremap <buffer> TD j0?//TODO:<Enter>d$

Thanks!

1 Answer 1

2

You could use a combination of :execute and substitute. The idea would be to use substitute to replace the %s in the commentstring by your TODO and then use execute to forge the content of the mapping.

Your js mapping could be something like this:

nnoremap td :execute "norm! A  " . substitute(&commentstring, '%s', 'TODO ', '')<CR>A

Where

  • execute lets you execute a command forged from a concatenation of strings.
  • The concatenated strings are
    • norm! A to execute A as in normal mode (The ! is important if your users remaps A)
    • substitute(&commentstring, '%s', 'TODO ', '') is the commentstring with %s replaced by TODO
  • <CR> validates the execute command
  • The final A allows the user continue to type their comment.

Relevant help topics:

You could also have a look at the source code of NERDCommenter to see how they use 'commentstring'.

2
  • That's awesome! This reply suggests that markdown comments should have their own line. Do you know how I could make Comment start a new line for .md file? I tried adding au BufRead,BufNewFile *.md set filetype=markdown | let Comment="foo" | let EndComment="bar" to my vimscript plugin but it isn't detected... So I can't even try to add a new line using \n [comment]: . Mar 11, 2019 at 14:11
  • I'm not sure what you are trying to do with let Comment="foo" actually. Maybe your solution could be to setup up 'commentstring by yourself for markdown files with something like setlocal commentstring="\n[comment]: # %s"? (I haven't tested that I'm not sure it works)
    – statox
    Mar 11, 2019 at 14:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.