How to open a file also in browser as HTML with style you use in Vim

2018-10-02 18:56:04 UTC

TLDR: you can do it with some plugins like this. This opens the README.md in Vim (raw and HTML) and also in browser (HTML).

You need:

 Screenshot of this article's reStructuredText as HTML on browser

Vim commands from command line

Vim takes 2 type options for commands,

According help,

  • --cmd <command> execute <command> before loading any vimrc file

  • -c <command> execute <command> after loading the first file

In this case, we need `-c <command>` because we want to handle the target file.

Vim Commands

Let's look at the following parts, one by one.

%foldopen!

This is optional.

Without this command, if you have some `fold` (s) in the file, it will be converted exactly look like.

e.g. HTML of My .vimrc (without %foldopen!)

 My .vimrc with foldings as HTML

% means whole content, ! means foldopen works recursively.

%TOhtml

:[range]TOhtml is a standard plugin. (included in Vim)

You can specify % as range for entire file content (same as for foldopen).

This command converts current Text into HTML with your current color scheme.

b2

b, bu, buf, buffer are all same.

b2 is a switching to second buffer, because TOhtml opens converted HTML file into second (next) buffer.

call quickrun#run()

quickrun is a plugin to do something to current file.

I have settings for HTML file type in vimrc like this:

let g:quickrun_config['html'] = {
        \ 'command': 'cat',
        \ 'outputter': 'browser',
        \ 'exec': "%c %s",
        \}
        

For browser outputter, you need also open-browser.vim.

If you have above settings, you can just run `QuickRun` command to open current HTML file in browser. (I like to just type <leader>r.)

You can set various behaviors for any filetype.

To avoid some errors, I use quickrun#run() function via call instead of QuickRun here.

q

Finally, q will close only HTML buffer. But HTML file is also still in there.

:buffers
        1 %a   "/path/to/file"         line 3
        2 #h + "/path/to/file.html"    line 2
        

HTML will be appeared in your browser, but original file is also still opend in Vim ;)

Scripts

There are scripts I named it `"often"` (Open File as hTml via Editor commaNd)

Without %foldopen! (simple version):

With `-zO` (same %foldopen!) option (full version):

You can do this (open often script itself!):

If you use browser in fullscreen mode, you may be confused. I often try to edit the HTML file, accidentally ;)

 Result of `often /path/to/often`