For the purpose of writing MarkDown documentation, I wanted to extend Vim with the ability to slugify selected text and to replace it with an anchor URL. The idea is to copy/paste a heading and use it to create index.

Example: say I have this text:

Some header

The text.

I want to copy Some header to the beginning of the doc, select it, and easily turn it into [Some text](#some-text).

What I came up with is this:

" Slugify selection
function Slugify(text)
    let result = substitute(a:text, ".*", "\\L&", "")
    let result = substitute(result, "[^a-z]\\+", "-" ,"g")
    return result
command -range Slug :<line1>,<line2>s/\%V.*\%V./\=Slugify(submatch(0))/
command -range Slurl :<line1>,<line2>s/\%V.*\%V./\="[" . submatch(0) . "](#" . Slugify(submatch(0)) . ")"/


  1. Select text.
  2. Type :Slurl for the whole anchor URL thing or :Slug to just slugify the selected text.

It seems to work fine for me, but I am a complete n00b with Vimscript (only started with it to get this working). Remarks and improvements would be quite welcome.

A minor side-question: is there an easy way to remove the selection or redefine it to match only the part inside [...] when done with Slurl?



Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.