Robert Audi
Robert Audi

Reputation: 8477

Markdown lists in Vim

When creating a list in a markdown file, I would like to insert a new item when pressing <CR>. I want that to apply to both ordered and unordered lists. That implies that, in ordered lists, the list item number will increment automatically. Also, if I press <CR> on a list item with no content, I would like to remove the item and add a new line, essentially ending the list; This is the current behaviour.

I managed to achieve some of the functionality that I want thanks to this StackOverflow question with this autocommand:

autocmd Filetype markdown setlocal com=s1:/*,mb:*,ex:*/,://,b:#,:%,:XCOMM,n:>,b:- | set formatoptions=tcroqln

But that autocommand doesn't work with ordered lists and doesn't end the list when <CR> is pressed on a blank list item.

Is it possible to add those two features?

Upvotes: 2

Views: 2916

Answers (3)

whoamadfd
whoamadfd

Reputation: 41

Put the following to ~/.vim/after/ftplugin/markdown.vim

" list markers (*, -, 1.)
function! s:list_marker() abort
  let line = substitute(getline(line('.')), '^\s*', '', '')
  let marker = matchstr(line, '^\([*-]\|\d\+\.\)\s')
  if !empty(marker) && marker == line
    return "\<c-u>"
  endif
  if marker =~ '\d'
    let marker = marker + 1 . '. '
  endif
  return "\<cr>" . marker
endfunction
inoremap <expr><buffer> <cr> <sid>list_marker() 
nmap <buffer> o A<cr>

Upvotes: 0

Ryenski
Ryenski

Reputation: 9692

Bullets.vim is a plugin that that makes this a lot easier than modifying the comments command.

https://github.com/dkarter/bullets.vim

You can insert a bulleted list by typing "-", and the following line will automatically insert a bullet.

You can also insert a numbered list by typing "1.", and subsequent lines will be automatically numbered in order.

From the readme:

Bullets.vim is a Vim plugin for automated bullet lists.

Usage

In markdown or a text file start a bulleted list using - or *. Press return to go to the next line, a new list item will be created.

Upvotes: 2

Ingo Karkat
Ingo Karkat

Reputation: 172608

To handle the ordered lists, you could treat them as comments like you do with the - sigil, just add :setlocal com+=b:1. This won't auto-increment, but I think Markdown does this for you when rendering the list, anyway.

There's no built-in logic for ending a list, but you can simply press <C-U> to remove the automatically inserted comment. If that's not good enough for you, an :imap <buffer> <CR> <CR>... mapping can detect such situations (by a function to be invoked in the ... part) and then remove that automatically.

Upvotes: 1

Related Questions