## 21 September 2011

### Fully integrated LaTeX in Macvim

I've been less than pleased with TeXShop on Lion. I do most of my editing in Vim using Vim-LaTeX, but I compile with TeXShop. Most importantly, I sometimes use SyncTeX to jump between my compiled document and source.

To switch away from TeXShop, I want both an integrated compiler and an external editor with SyncTeX. Skim with this configuration fit the bill. Yet Vim-LaTeX won't play nicely with my dissertation, which uses a file for each chapter and the TeXShop convention of

``````% !TEX root = ../thesis.tex
``````

to denote the true TeX file. The solution involves this feature of Vim-LaTeX, and the following function I wrote:

``````" Look for main file by looking in the first 20 lines, same as TeXShop, for:
" % !TEX root = [filename].tex
" Author: Seth R. Johnson
let g:Tex_MainFileExpression = 'SRJMainFile(modifier)'

function! SRJMainFile(fmod)
let s:Tex_Match = '\v^\s*\%\s+!TEX\s+root\s+\=\s+\zs(.*\.tex)\ze\s*\$'
let s:lnum = 1
while s:lnum < 20
let s:basefile = matchstr( getline(s:lnum), s:Tex_Match)
if !empty(s:basefile)
break
endif
let s:lnum += 1
endwhile

if !empty(s:basefile)
let s:origdir = fnameescape(getcwd())
let s:newdir = fnameescape(expand('%:p:h'))
exec 'cd'.s:newdir
let s:basefile = fnamemodify(s:basefile, a:fmod)
exec 'cd'.s:origdir
else
let s:basefile = expand('%'.a:fmod)
endif

return s:basefile
endfunction

" Command-R will write, open for viewing, compile, go to the end of the quickfix, hide the
" preview, switch back to main window
imap <D-r> <ESC><D-r>
" Inverse search
``````

Now typing `\ll` in my individual chapter files will compile the true thesis. Typing `\lv` will open the thesis in Skim, `\ls` will jump from the TeX source to the corresponding output line, and command-shift-clicking in Skim will cause MacVim to jump to the appropriate source line. Command-R is a shortcut to compile and view.

UPDATE 2011/9/25: I've uploaded my vim scripts to GitHub.

UPDATE 2011/9/27: Modify the "reverse lookup" in Skim to be `--remote-silent +":silent %line" "%file"` to avoid the obnoxious `Press ENTER to continue` prompt in Vim.

Anonymous said...

The ":silent %line" .. is not getting rid of the 'Press ENTER to continue' prompt for me on Lion. Does it really work for you?

Toban said...

When you match the filename, your regex is enforcing at least one space in some places (`\s+`). I hit a snag because I had copied `%!TEX root = ...` from elsewhere on the web, so it didn't match because of no space between % and ! -- but a quick fix (`\s*`) allows for 0 or more spaces.