Example: VimL Vimscript File Expansion

File expansions

Get help from Vim about filename and path expansion modifiers:

:help filename-modifiers

Path of file. % expands into current file path.

echo expand("%")
## /Users/mertnuhoglu/projects/study/vim/ex_viml_file_expansion.Rmd

Path of directory. h: head. p: path. :p:h head of path of file

echo expand("%:p:h")
## /Users/mertnuhoglu/projects/study/vim

Path of file. p: path of file

echo expand("%:p")
## /Users/mertnuhoglu/projects/study/vim/ex_viml_file_expansion.Rmd

Path of file without extension. r: root of file name

echo expand("%:r")
## /Users/mertnuhoglu/projects/study/vim/ex_viml_file_expansion

Run an R command to render rmarkdown files from within Vim

In bash, the following command renders an .Rmd file to .html file

R -e 'rmarkdown::render("%")'

To run this command from within Vim easily, I defined a custom command in .vimrc file:

command! Rmarkdown :!R -e 'rmarkdown::render("%")'

Now simply typing the following auto-completable command inside Vim is enough:

:Rmarkdown

Open the generated html file after rendering rmarkdown

:Rmarkdown command above renders .Rmd file into .html file. Now, I want to open it from within Vim easily.

The following custom command let’s me open generated html file easily:

command! OpenHtml :execute '!open ' . expand("%:r") . '.html'
command! Ohtml OpenHtml 

 Tech    20 Jan, 2018

Any work (images, writings, presentations, ideas or whatever) which I own is always provided under
Creative Commons License Creative Commons Attribution-Share Alike 3.0 License

Mert Nuhoglu is a Trabzon-born programmer and data scientist.

You may also like...