Friday, January 16, 2015

VIM + texlive + vim-latex suite + zathura +pdf + arch + so on

With a very little effort, one can learn to use the VIM editor. Once you are used to its keybindings, I am sure that no amount of development in touch screen or mouse technology will appeal to you. And the side effect is that you will frantically try to look for programs using similar keybindings for different purposes. This post is an example of such desperation.

Here, I will share my knowledge to set up an environment to complie .tex files into pdfs, while keeping it as lightweight as possible, while having access to several totally awesome features such as:
  • key binding of vim both in editor and viewer
  • vim-latex suite to reduce typing efforts
  • forward and inverse search
  • partial compilation
 All of the information presented here are available for a patient google user.

 Components used:
  1. Terminal: xterm
  2. TeX compiling package: texlive
  3. Editor: vim
  4. Plugin: vim-latex suite
  5. Output Format: pdf
  6. PDF viewer: zathura
 1. Installation of packages:

pacman -S texlive-core texlive-bin texlive-science gvim zathura zathura-pdf-poppler

Note: replace vim by gvim

(a) texlive package:
        Minimal: texlive-core
        Probably needed: texlive-bin, texlive-science

(b) vim editor:
        Obviously: vim
        For this purpose, we need to install gvim to enable +serverclient feature. and replace vim by gvim, although we will not use gvim. I could not find any other way but to recompile vim from source which seemed like a tremendous waste of time when installing gvim took very less time. Agreed, it is not cntradictory to my "minimalistic" approach, but, oh, well.

(c) pdf viewer:
        obviously: zathura
        For viewing pdfs: zathura-pdf-poppler
This is an excellent viewer with vim-like key binding. supports scrolling also. Capable of viewing djvu and ps as well. (install zathura-djvu, zathura-ps). Also, it supposedly supports plugins which I am yet to check out.


Now that you have all the tools needed to create a tex file and compile it using
pdflatex .tex
and view it in pdf viewer using
zathura .pdf
to get a pdf file, give it a try to see if everything works.


 2. Installing vim plugin vim-latex suite:

link: http://sourceforge.net/projects/vim-latex/

(a) Download the compressed files and extract it.
(b) Copy the content to ~/.vim
cp  ~/.vim/ftplugin/latex-suite/texrc ~/.vim/ftplugin/tex.vim

(c) The config file for the vim-latex suite will be ~/.vim/ftplugin/tex.vim
This file does not exist, but we can create it. This will have precedence over the file ~/.vim/ftplugin/latex-suite/texrc, which is the actual config file. But for our   need, we will modify it.


No action required for this step. We can take care of it in due time.

(d) Add the following lines to ~/.vimrc:

"""""""""""""""""""""""""""""""""""""""""""""""""
" REQUIRED. This makes vim invoke Latex-Suite when you open a tex file.
filetype plugin on

" IMPORTANT: grep will sometimes skip displaying the file name if you
" search in a singe file. This will confuse Latex-Suite. Set your grep
" program to always generate a file-name.
set grepprg=grep\ -nH\ $*

" OPTIONAL: This enables automatic indentation as you type.
"filetype indent on

" OPTIONAL: Starting with Vim 7, the filetype of empty .tex files defaults to
" 'plaintex' instead of 'tex', which results in vim-latex not being loaded.
" The following changes the default filetype back to 'tex':
let g:tex_flavor='latex'
"""""""""""""""""""""""""""""""""""""""""""""""""


(e) Optionally, add (create first, possibly, and) these lines to the file ~/.vim/ftplugin/tex.vim:

"""""""""""""""""""""""""""""""""""""""""""""""""
" this is mostly a matter of taste. but LaTeX looks good with just a bit
" of indentation.
set sw=2
" TIP: if you write your \label's as \label{fig:something}, then if you
" type in \ref{fig: and press you will automatically cycle through
" all the figure labels. Very useful!
set iskeyword+=:
"""""""""""""""""""""""""""""""""""""""""""""""""



At his moment, you should be able to utilise all the typing functionalities of vim-latex  while editing a .tex file. For example, type equation and press to see if you get 

\begin{equation}
 <++>
\end{equation}

etc. 

3. Setting up the default compiler and viewer:

If you follow the previous steps of installations, I can safely assume the following:

  • SyncTex is installed. Check if /usr/bin/synctex exists. If it is not installed, have to figure out how to.
  • Vim has +clientserver module enabled (made it sure by installing gvim). To check that it works, open vim and type: :version. There should be a '+' sign before  clientserver.
Create the file ~/.vim/ftplugin/tex.vim 
If it does not exist and add the following  lines to it:

"""""""""""""""""""""""""""""""""""""""""""""""""
" Default compiling format
let g:Tex_DefaultTargetFormat='pdf'


" Never Forget, To set the default viewer:: Very Important
let g:Tex_ViewRule_pdf = 'zathura'

" Trying to add same for pdfs, hoping that package SynTex is installed
let g:Tex_CompileRule_pdf = 'pdflatex -synctex=1 -interaction=nonstopmode $*'


" Get the correct servername, which should be the filename of the tex file,
" without the extension.
" Using the filename, without the extension, not in uppercase though, but
" that's okay for a servername, it automatically get uppercased
let theuniqueserv = expand("%:r")

" Working!!!, when we run vim appropriately
let g:Tex_ViewRuleComplete_pdf = 'zathura -x "vim --servername '.theuniqueserv.' --remote +\%{line} \%{input}" $*.pdf 2>/dev/nul &'

" I like my sums and limits to have placeholders
let g:Tex_Com_sum = "\\sum\\limits\_{<++>}\^{<++>}<++>"
let g:Tex_Com_cap = "\\bigcap\\limits\_{<++>}\^{<++>}<++>"
let g:Tex_Com_cup = "\\bigcup\\limits\_{<++>}\^{<++>}<++>"
let g:Tex_Com_lim = "\\lim\\limits\_{<++>}\^{<++>}<++>"

" Forward search
" syntax for zathura: zathura --synctex-forward 193:1:paper.tex paper.pdf
function! SyncTexForward()
        let execstr = 'silent! !zathura --synctex-forward '.line('.').':1:"'.expand('%').'" "'.expand("%:p:r").'".pdf'
        execute execstr
endfunction
nmap f :call SyncTexForward()

" To save and compile with one command \k (k=kompile) :)
" no need to launch the pdf along with this because zathura can refresh
" itself after every compilation produces a new pdf, so \k is enough
nmap k :w ll

" I will just reamp this \lv thing to \v just to be consistent with \k and \f
nmap v lv

"""""""""""""""""""""""""""""""""""""""""""""""""""""""


Reasons for each line is included in the comments.

 4. Launching vim with servername:

Now we create a custom command for this mini setup that we have created. We create  the file called vtex and paste the following lines:


#######################################################
# The file called vtex, make it better, make it recognize only tex files
# while pressing
for i in "$@"; do
    if [[ ${i} == *.tex ]]; then
        fileName=$i;
        # Strip off path and extension, and convert to uppercase.
        # although there is no need to turn into upper case
        serverName=$(sed -e 's:\(.*/\)\?\(.*\)\.tex:\U\2\E:' <<< $i)
        break;
    fi
done

if [[ ${serverName} == '' ]]; then
        echo 'not a tex file or no non-extension part, no server to create'
else
        # run in server mode
        # now we need to make sure the forward search connects to the right server
        # check in .vimrc or tex.vim to see if it is correct
        echo 'creating server called $serverName'
        exec vim --servername $serverName "$@"
fi

#######################################################

Make this file executable (chmod +x) and keep it in a place where your $PATH can find it to be executed. In my case, .myscr.

So, typing vtex .tex in terminal will launch vim with proper server name so that zathura can be linked with it for inverse search, as specified in the tex.vim file.


Hence, the setup is done.


 5. Taking advantage of this whole setup:

Syntax Folding:

\rf to collapse all the equns.
za to expand individual folds. How to expand all? Ans: zi


Compiling and viewing: \l

After creating a .tex file, pressing \ll should compile the tex to generate a pdf file along with some other files. If there is any error or warning, it will pop up in the vim window. You can hit to jump to line the corresponding to error and, correct it, and press \ll again to compile again. To jump between error window and main file, press .

After a successful compilation, pressing \lv will open zathura to show the pdf file.

Note: pressing \ll or \lv requires the user to be quick while typing these keys.

According to our setup, pressing \k will compile and open zathura at the same time.

Forward search: \f

Pressing \f will perform a forward search, i.e. highlight the region in the pdf file opened in zathura, corresponding to the current line of code. This will work only if there has been a successful compilation (i.e. a pdf file has been generated by pdflatex command).

Inverse Search: Ctrl+Click

After opening the pdf file in zathura through \l or \lv, clicking any line in the pdf file while holding down the Ctrl key will make the cursor in vim window jump to the line corresponding to it.

Partial Compilation:

You can select a chunk of lines in visual mode (Shift+v) and press \ll or \l to compile that part of the tex file along with the preambles. In this process, a temporary tex file is created which can be handled like just any other tex file. You can \ll, \l, \f etc and when you are done, simply save and exit to get back to the original tex file.



Reducing typing efforts:

pressing F7 while the cursor is touching a word will turn it into a keyword along with the format. E.g.
frac becomes \frac{<<++>>}{<<++>>}<<++>>
word becomes \word{}<<++>>
etc.

Ctrl+j jumps through <<++>>.

Useful: frac , textbf

I have added a few more in tex.vim for sum, cup, cap, limit etc.

You can select some text in visual mode (v) and then press and enter the desired keyword to turn it into the arguments of a keyword.

Useful: If you want to make some text bold, select the text in visual mode, press and type textbf and hit to make that text boldface.
Or, select a long expression through visual mode and press and type sum and to put a sum sign beofre that.

Shift+ will let you change the parent command that you are inside.

For inserting things like \begin{equation} ...\end{equation}, enter equation and press . Shift+ works accordingly.


Typing SSE will turn into
\section{New Section}
which is a nice way to start a section. Others are:


SPA for part
SCH for chapter
SSE for section
SSS for subsection
SS2 for subsubsection
SPG for paragraph
SSP for subparagraph


Most useful:::
Greek Letter Mappings

Lower case
`a through `z expand to \alpha through \zeta.

Note: That's a "tick" and not an "apostrophie".

Upper case Greek:

`D = \Delta
`F = \Phi
`G = \Gamma
`Q = \Theta
`L = \Lambda
`X = \Xi
`Y = \Psi
`S = \Sigma
`U = \Upsilon
`W = \Omega

Expanding the arrangement situation:

`^   Expands To   \Hat{<++>}<++>
`_   expands to   \bar{<++>}<++>
`6   expands to   \partial
`8   expands to   \infty
`/   expands to   \frac{<++>}{<++>}<++>
`%   expands to   \frac{<++>}{<++>}<++>
`@   expands to   \circ
`0   expands to   ^\circ
`=   expands to   \equiv
`\   expands to   \setminus
`.   expands to   \cdot
`*   expands to   \times
`&   expands to   \wedge
`-   expands to   \bigcap
`+   expands to   \bigcup
`(   expands to   \subset
`)   expands to   \supset
`<   expands to   \le
`>   expands to   \ge
`,   expands to   \nonumber
`~   expands to   \tilde{<++>}<++>
`;   expands to   \dot{<++>}<++>
`:   expands to   \ddot{<++>}<++>
`2   expands to   \sqrt{<++>}<++>
`|   expands to   \Big|
`I   expands to   \int_{<++>}^{<++>}<++>

Must get used to it. As soon as possible.

 In addition the visual mode macros are provided:

`(  encloses selection in \left( and \right)
`[  encloses selection in \left[ and \right]
`{  encloses selection in \left\{ and \right\}
`$  encloses selection in $$ or \[ \] depending on characterwise or linewise selection

Use the Alt key to make inserting all the \left ... \right stuff very easy: see the help, does not work because Alt is being used somewhere in my system. MOving on.

Pressing the Alt+B however, converts the previous character into a \mathbf{} character which is super-useful. Figure out a way to turn it into \mathbb{} which I use more often. Shouldn't be hard. Or, make your own. Have to find out how. It is in the Macro Customisation Section: http://vim-latex.sourceforge.net/documentation/latex-suite/customizing-macros.html



There is a referencing help section in completion section. Read later if you are into the \ref{equn:name} kind of things. Not useful for me now.

Pressing ... (3 dots) results in \ldots outside math mode and \cdots in math mode.


 Templates:

Insert a template in an empty tex file by :TTemplate
You can create your own template with <++> and required packages inside /ftplugins/latex-suite/templates.
Here is an example template I prefer to use usually:

File: ~/vim/ftplugins/latex-suite/templates/usual.tex

%%%%%%%%%%%%%%Please do not copy this line%%%%%%%%%%%%%
<+      +>      !comp!  !exe!
%        File: !comp!expand("%")!comp!
%     Created: !comp!strftime("%a %b %d %I:00 %p %Y ").substitute(strftime('%Z'), '\<\(\w\)\(\w*\)\>\(\W\|$\)', '\1', 'g')!comp!
% Last Change: !comp!strftime("%a %b %d %I:00 %p %Y ").substitute(strftime('%Z'), '\<\(\w\)\(\w*\)\>\(\W\|$\)', '\1', 'g')!comp!
%

% Documentclass
\documentclass{article}

% To use \text{} inside math mode
\usepackage{amsmath}
% To use \newtheorem styles
\usepackage{amsthm}
% To use \mathbb{} for fancy fonts
\usepackage{amsfonts}

% User defined fun
\newtheorem{thm}{Theorem}
\newtheorem{defn}{Definition}
\newtheorem{result}{Result}
\newtheorem*{notation}{Notation}

\begin{document}

<++>

\end{document}
%%%%%%%%%%%%%%Please do not copy this line%%%%%%%%%%%%%%


Now, in order to use this template, after creating an empty tex file with vtex, type:
:TTemplate
then select the template to use, and done.

Conclusion: The whole article is too big to be read by anybody who wants to setup a quick latex-compiling environments. For this reason, I plan to add a quick-setup guide to the beginning of this post so that I can follow the steps blindly without rediscovering the whole wheel.