6

From MacVim is there a command to open the currently edited HTML file in a web browser?

peth
  • 9,890
  • 3
  • 34
  • 41
Florent2
  • 263
  • 5
  • 11

2 Answers2

15

To do it just once, you can

:!open %

which will call the shell command open with the path to the current file as argument. I don't use Mac myself, but open seems appropriate to me. If it isn't, replace with whatever program you wish the file be opened with.

Of course you can bind a key, if you'll need it frequently:

:map <silent> <F5> :!open %<CR>

And you may want to

:set nowarn

to suppress warnings about unsaved file changes.

See:

  • :help :!
  • :help cmdline-special
  • :help 'warn'

Note that you can get arbitrarily sophisticated with Vim scripting. For example, this function lets you view the current unsaved changes by use of an intermediate file:

function! BrowserPreview()
    if &modified
        let tmpfile = tempname()
        execute "silent write " . tmpfile
        call system("firefox " . shellescape(tmpfile))
        if delete(tmpfile) != 0
            echoerr "could not remove " . tmpfile
        endif
    else
        call system("firefox " . shellescape(expand("%:p")))
    endif
endfunction

map <silent> <F5> :call BrowserPreview()<CR>

(Replace both occurrences of firefox with open if that worked earlier.)

peth
  • 9,890
  • 3
  • 34
  • 41
  • Just be sure that your file names don't have spaces. Otherwise, vim tries to open every space-delimited word as its own page. It's pretty annoying, in my opinion. – dylnmc Oct 19 '15 at 13:06
-1

:w | !xdg-open %

for me under Ubuntu opens the Opera browser

bertieb
  • 7,344
  • 36
  • 42
  • 54
  • Can you explain the syntax of this command, and how it differs from the accepted answer? – Scott - Слава Україні Feb 26 '17 at 18:57
  • I opened chrome with syntax above thks – Eugen Jinga Jan 31 '18 at 19:03
  • The question is about MacVim. MacVim runs on OS X. MacVim is not likely to get ported to Ubuntu. This answer is only relevant if a user has some reason to prefer xdg-open over OS X's open(1). If addressing that case, we should mention that [installing xdg-open on OS X](https://superuser.com/q/911735/115912) is possible. – minopret Jan 05 '20 at 22:35