8

I've the following sample html code:

vim http://example.com/

Is there any way to actually render html inside vim editor? In example using markdown formatting or something similar?

Example scenario: I'm logged on remote machine when I don't have access to GUI and I'd like to check how the html code looks like without opening external web browsers.

Martin Tournoij
  • 62,054
  • 25
  • 192
  • 271
kenorb
  • 18,433
  • 18
  • 72
  • 134

2 Answers2

9

Not really. Vim's rendering engine is not designed for this sort of thing. It just renders text.

However, you could use a text-mode browser such as w3m to turn your HTML into text and then load that into vim. Create a new buffer and use :r ! (see :help :r) to read in the result of the w3m conversion:

:r !w3m -dump your-html-file.html
3

Rendering html can be implemented by using a text-based web browser which can extract a formatted view of the text from an html file or a web page.

In example:

:!links -dump %
:!elinks -dump %
:!lynx -dump %
:!w3m -dump %

To define your own html preview command, try:

:command! ViewHtml execute ':!links -dump %'
:ViewHtml

Then you can associate this custom command with some key for easier access, by e.g.:

:nnoremap <Leader>H :ViewHtml<CR>

then pressing \H will preview html of the current file.

To preview current file in separate window or to open hyperlinks, you may try to use the following code:

function! ViewHtmlText(url)
  if !empty(a:url)
    new
    setlocal buftype=nofile bufhidden=hide noswapfile
    execute 'r !elinks ' . a:url . ' -dump -dump-width ' . winwidth(0)
    1d
  endif
endfunction
" Save and view text for current html file.
nnoremap <Leader>H :update<Bar>call ViewHtmlText(expand('%:p'))<CR>
" View text for visually selected url.
vnoremap <Leader>h y:call ViewHtmlText(@@)<CR>
" View text for URL from clipboard.
" On Linux, use @* for current selection or @+ for text in clipboard.
nnoremap <Leader>h :call ViewHtmlText(@+)<CR>

Source: vim wikia

Using above code, you can press \H to save and preview the current file. To preview currently selected hyperlink, press \h.

Related:

kenorb
  • 18,433
  • 18
  • 72
  • 134