I am trying to come up with a TOC (table of contents) of a text document: lines starting with # (hashtag) VIM would "collect" into the buffer or maybe place them at the TOP OF FILE.

(Or - other idea - erase all lines in a duplicate file NOT starting with a #)
There must be solutions to this question...

  • Is it necessary to use a plugin (e.g. github.com/wikimatze/tocdown )? – Thomas D Aug 13 at 14:48
  • 3
    github.com/mzlogin/vim-markdown-toc – phd Aug 13 at 16:10

I think you are looking for the :global command.

You can see all lines starting with # with :g/^#/p and put them in a file using the :redir command :

:redir > toc.txt
:redir END

Note that toc.txt will contain the line numbers if you have set number. There is also this post on the subject.

Alternatively, you can delete all lines not starting with # with :v or :g! and save it to another file.

:w! toc.txt | undo

Look also for :copy (:t) and :move.

:global applies the command you provide to each matched lines in the order they appear in the file, so :g/^#/t0 will copy headers to the top of the file but in reverse. We could do :v/^#/m$ to move all non-header lines to the end, leaving the headers on top but stripped from the original text. Another way is to place some marker to mark the end of the table of content and copy header lines one line above this marker :

  • The t does not move the lines, it copies them – SergioAraujo Aug 13 at 19:50
  • @perelo: The redir - solution works as I thought of. Line-Numbers help to find the marked lines! Great, thanks! PS: redir can also copy to a buffer (see vim help) – Thomas D Aug 13 at 21:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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