I had this requirement when writing README.md file to generate TOC (Table Of Content) automatically in vim right above the particular ### 34. Title XYZ
https://github.com/xjantoth/helmfile-course/blob/master/img/vim-trick.svg
Let's pretend here is my title in markdown.
vim README.md
...
### 20. This is my title I would like to generate TOC for
Lorem Ipsum is simply dummy text of the printing
and typesetting industry. Lorem Ipsum has been
the industrys standard dummy text ever since
the 1500s, when an unknown printer took a galley
of type and scrambled it to make a type specimen book.
It has survived not only five centuries, but publishing
software like Aldus PageMaker including versions of Lorem Ipsum.
...
:wq!
Here is the code snippet you need to paste in your ~/.vimrc
" quick .vimrc access with ,t
function! Toc()
let $file = @%
let $linenr = line(".")
.t.
w
"echo system('sed -i -E "${linenr}s/^[#]{2,} (.*)/<!-- - [\1](#\L\1) ->/; :a s/(\(#[^ ]+) /\1-/g; ta" $file')
echo system('sed -i -E -e "${linenr}s/^[#]{2,} (.*)/<!-- - [\1](#\L\1) ->/; :a s/(\(#[^ ]+) /\1-/g; ta" -e "s/(.*)(\(#[0-9]{1,2})(\.)(.*)/\1\2\4/g" $file')
e!
endfunction
let mapleader = ","
" quick .vimrc access with ,t
nmap <leader>t :call Toc()<CR>
Open up your README.md file once again and navigate to line:
- (
### 20. What is Lorem Ipsum?
) with your title. - hit
,t
keys +Enter
vim README.md
...
### 20. This is my title I would like to generate TOC for
Lorem Ipsum is simply dummy text of the printing
and typesetting industry. Lorem Ipsum has been
the industrys standard dummy text ever since
the 1500s, when an unknown printer took a galley
of type and scrambled it to make a type specimen book.
It has survived not only five centuries, but publishing
software like Aldus PageMaker including versions of Lorem Ipsum.
...
:wq!
Output:
vim README.md
...
<!-- - [20. This is my title I would like to generate TOC for](#20-this-is-my-title-i-would-like-to-generate-toc-for)-->
### 20. This is my title I would like to generate TOC for
Lorem Ipsum is simply dummy text of the printing
and typesetting industry. Lorem Ipsum has been
the industrys standard dummy text ever since
the 1500s, when an unknown printer took a galley
of type and scrambled it to make a type specimen book.
It has survived not only five centuries, but publishing
software like Aldus PageMaker including versions of Lorem Ipsum.
...
:wq!
Check my other work at Udemy
Learn AWS EKS Kubernetes cluster and devops in AWS (Part 1)
Learn Kubernetes Docker/DevOps and helm charts from scratch
Top comments (0)