Using vim as pager

From raju

Requirement

Use vim as a pager with the following features

  • syntax highlighting should work
  • "less" like key bindings (ex:- q for quit)
  • preserve settings in ~/.vimrc

Assumptions

Assume that the user is using zsh and vim 7.4.

Solution

Add the following line to ~/.zshrc

    alias vless="/usr/share/vim/vim74/macros/less.sh"
    

Use it as

    vless file.txt
    cat file.txt | vless
    

In some cases, the latter command does not detect the filetypes correctly . For example, while reading C++ programs through stdin, vim is setting the filetype to 'conf' instead of cpp. As a work around, set the file type on the command line.

    cat prog.cpp | vless -c "set ft=cpp" -
    

Other approaches

  • Instead of using /usr/share/vim/vim74/macros/less.sh, we can use "vim -u /usr/share/vim/vim74/macros/less.vim" . But this does not source standard configuration files such as ~/.vimrc . So all the custom settings will be lost.

System Information

Tested it on Debian Jessie (stable) using

     % dpkg -l vim\* zsh\* | grep ^ii 
    ii  vim               2:7.4.488-7  amd64        Vi IMproved - enhanced vi editor
    ii  vim-common        2:7.4.488-7  amd64        Vi IMproved - Common files
    ii  vim-gtk           2:7.4.488-7  amd64        Vi IMproved - enhanced vi editor - with GTK2 GUI
    ii  vim-gui-common    2:7.4.488-7  all          Vi IMproved - Common GUI files
    ii  vim-runtime       2:7.4.488-7  all          Vi IMproved - Runtime files
    ii  vim-tiny          2:7.4.488-7  amd64        Vi IMproved - enhanced vi editor - compact version
    ii  zsh               5.0.7-5      amd64        shell with lots of features
    ii  zsh-antigen       1-2          all          manage your zsh plugins
    ii  zsh-common        5.0.7-5      all          architecture independent files for Zsh
    ii  zsh-doc           5.0.7-5      all          zsh documentation - info/HTML format
    

Further reading

  • :h less in vim

Useful shortcuts

The following shortcuts are available when a file is opened this way.

    h         List available commands.
    
    <Space>   One page forward          b         One page backward
    d         Half a page forward       u         Half a page backward
    <Enter>   One line forward          k         One line backward
    G         End of file               g         Start of file
    N%        percentage in file
    
    /pattern  Search for pattern        ?pattern  Search backward for pattern
    n         next pattern match        N         Previous pattern match
    
    :n<Enter> Next file                 :p<Enter> Previous file
    
    q         Quit                      v         Edit file