In his (very good) book "Pratical Vim" Drew Neil shows how to collect all the lines containing the word "TODO" into a register to use them latter.

To do so he simply use a global command: :g/TODO/yank A (The capital A allows to happen lines to the named register a).

I think that's a pretty cool trick but I need to improve it: I'm trying to insert the number of the line before it's content. I think the solution would be to get the line number and use it in the last part of the command I mentioned before. The problem is that I don't know how to get this line number.

So my question is: How in a global command can I get the number of the matched line and how can I use this number?

Just to be clear here is an example. Let's consider this file:

1  //TODO: Hey this is a todo
2  int main(void){
3      //TODO: and this is another one
4      printf("Hello world");
6      return 0;
7  }

When I type :g/TODO/yank A and I put the content of the register in a file I get:

//TODO: Hey this is a todo
    //TODO: and this is another one

What I would like to get is:

1 //TODO: Hey this is a todo
3    //TODO: and this is another one

Bonus the yank also include the indentation of the line, it would be pretty cool if I could remove it directly from the global command.

1 Answer 1


One way to do it:

  1. clear the register:

    :let @a=''
  2. append search results in it:

    :g/TODO/let @A = getpos('.')[1] . ' ' . getline('.') . "\n"

Re: BONUS remove indentation in the global command:

    :g/TODO/let @A = getpos('.')[1] . ' ' . substitute(getline('.'), '^\s*', '', '') . "\n"
  • 1
    Thanks that's exactly what I was looking for! I didn't know the getpos() and getline() commands. Also as you answered the bonus question you deserve a dancing cookie ;)
    – statox
    Jun 14, 2015 at 14:57
  • A cookie, yay :)
    – VanLaser
    Jun 14, 2015 at 15:04
  • 1
    @statox Bookmark this: :help function-list. It's a very useful reference. Also, +1 for the mention of "Practical Vim". :)
    – lcd047
    Jun 14, 2015 at 16:01
  • @lcd047: Wow thanks!! I wish I knew this help entry before, that's so nice to have this list here. Vim documentation is really amazing! Also yay I'm pretty new to vim and "Practical Vim" is my Bible at the moment :)
    – statox
    Jun 14, 2015 at 16:07
  • @Laser also a quickest way to empty the a register in normal mode is to record an empty macro with qaq maybe it's less elegant than your solution but it works ;) Also your solution can be used in a vimscript whereas I don't think it's possible with mine.
    – statox
    Jun 14, 2015 at 18:18

Your Answer

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

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