Thomas D
Thomas D

Reputation: 53

Collect markdown headlines in vim?

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...

Upvotes: 4

Views: 373

Answers (1)

perelo
perelo

Reputation: 495

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
:g/^#/p
: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.

:v/\#/d
: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 :

:g/^#/t?end-toc?-1

Upvotes: 5

Related Questions