Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collect markdown headlines in vim?

Tags:

vim

markdown

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

like image 917
Thomas D Avatar asked Oct 29 '25 22:10

Thomas D


1 Answers

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
like image 121
perelo Avatar answered Nov 02 '25 05:11

perelo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!