Because I was curious how well this would work, I've hacked something together
that sort of works.
As mentioned in the comments on the earlier answer, the only way to do this is
to fill up regions with spaces; which is exactly what we do; before write, we
remove these spaces, so you shouldn't be bothering anyone else with it.
Note that this example is very specific for the markdown filetype!
Side effects:
- Copying text will also copy a lot of spaces
- Using $ and End no longer work as expected (it goes to column 80), and keys such as
j and k also behave different.
- The background is not displayed when
'list'
is enabled
- Completely blank lines don't work, you need to manually add a tab or 4 spaces
- ... Perhaps more?
First, you need to add this to your ~/.vim/after/syntax/markdown.vim
:
syn clear markdownCodeBlock
syn region markdownCodeBlock start=" \|\t" end="$"
hi def markdownCodeBlock ctermbg=230 guibg=lightyellow
You can adjust the colours to your liking, of course ;-)
Then, add this to your vimrc:
fun! MarkdownBlocks()
fun! s:fill(line)
" Remove all trailing whitespace
let l:line = substitute(a:line, " *$", "", "")
" Add trailing whitespace up to 'textwidth' length
return l:line . repeat(' ', (&tw > 0 ? &tw : 80) - strdisplaywidth(l:line))
endfun
" Get all lines in a list
let l:lines = getline(1, line('$'))
" Map s:fill() to the lines that are a code block
call map(l:lines, 'v:val[0] == "\t" || v:val[:3] == " " ? s:fill(v:val) : v:val')
" Reset the buffer to the lines
call setline(1, l:lines)
endfun
" Remove all the trailing spaces
fun! MarkdownBlocksClean()
let l:save_cursor = getpos(".")
silent %s/^\( \|\t\)\(.\{-}\)\( *\)$/\1\2/e
call setpos('.', l:save_cursor)
endfun
au BufWritePre *.markdown call MarkdownBlocksClean()
" Set spaces on loading the file, leaving insert mode, and after writing it
au FileType markdown call MarkdownBlocks()
au InsertLeave *.markdown call MarkdownBlocks()
au BufWritePost *.markdown call MarkdownBlocks()
I'm not going to explain the code line-by-line, the comments should make
the general gist of it clear ;-)