Search code examples
vimtableofcontents

Vim: generate table of contents for plain text files (not Markdown)?


I'm aware of Vim plugins such as vim-markdown-toc, etc. but those apply to markdown files. Are there any approaches/suggestions for auto-generating a tables of contents in plain-text files (.txt, or no extension) in Vim? For example, something like:

CONTENTS

  ∙ Executive Summary
  ∙ Technical Review
    ∙ Biomedical Natural Language Processing
  ∙ Preliminary Work

... where (for convenience) headers could adopt the markdown syntax:

# EXECUTIVE SUMMARY

Lorem ipsum dolor sit amet, consectetur adipiscing elit. ...
...

# TECHNICAL REVIEW

Lorem ipsum dolor sit amet, consectetur adipiscing elit. ...
...

##  BIOMEDICAL NATURAL LANGUAGE PROCESSING

Lorem ipsum dolor sit amet, consectetur adipiscing elit. ...
...

# PROPOSED WORK

Lorem ipsum dolor sit amet, consectetur adipiscing elit. ...

Solution

  • You could use something like that:

    :g/^#* /t0
    

    This will copy all this lines to the top. Unfortunaly in the wrong order, reverse it:

    :0,4g/^/m0
    

    (You may need to increase the numer 4 here, it is for your example). Then select the lines in visual line mode and replace # with tab or spaces.

    :'<,'>s/#/  /g
    

    Then do some formating. You could of course automate this further.