Showing posts with label texlatex. Show all posts
Showing posts with label texlatex. Show all posts

Monday, February 04, 2013

LaTeX template for NSF-style Biographical Sketch

On large multi-university NSF grant proposals, NSF requires that senior personnel submit a 2-page biographical sketch ("biosketch") that is formatting according to certain rules in their Grant Proposal Guide (GPG). The format is pretty simple, and so there does not seem to be much demand for a solid LaTeX template for one. Nevertheless, I thought some people might find one helpful. I've posted a PDF of my NSF-style biosketch below along with the TeX source used to generate it. On a related note, you can also find my curriculum vitae (CV) tailored for faculty searches (PDF, TeX) as well as for industry searches (PDF, TeX).

Tuesday, October 09, 2012

natbib-like frontend for chicago-style macros

For some reason, the ACM has baked in chicago-like citation macros into the ACM SIG proceedings LaTeX templates instead of using the far superior natbib that literally everyone else on the planet uses. I'm much more accustomed to typing \citet as opposed to \shortciteN, \citeauthor as opposed to \shortciteANP, etc. So I decided to add this little translation table to my preamble:
\def\citet{\shortciteN}
\def\Citet{\shortciteN}
\def\citeauthor{\shortciteANP}
\def\Citeauthor{\shortciteANP}

\let\chicagociteyear\citeyear
\def\citeyearpar{\chicagociteyear}
\def\citeyear{\citeyearNP}

\def\citep{\shortcite}
Unfortunately, that means I can't use any of the optional arguments to \citep or \citet. If you are just looking for a translation table so you can use the chicago-style macros directly, try this:
natbibchicago
\citet or \Citet\shortciteN
\citeauthor or \Citeauthor\shortciteANP
\citeyear\citeyearNP
\citeyearpar\citeyear
\citep\shortcite
It's crazy how chicago-style macros sometimes use "N" to mean "noun" and other times to be the first half of "NP" being "no parentheses."

Tuesday, August 23, 2011

Update to my LaTeX CV templates: Space allowed after sections now!

In preparation for setting up MultiMarkDown (MMD) to write my CV for me, I've been thinking about ways to refactor my old résumé/CV LaTeX templates to make them look a little cleaner. A fix I came up with tonight should help with that, and I think it will also make the templates easier for others to work with even if they're not doing anything with MMD.

In particular, the \section macro used to be renewed as a \marginpar with some other ugly stuff. Putting the sections in the margins caused problems because people like to put spaces after the sections, which generates a \par that means the section content will not be aligned with the section heading in the margin note. So the old way I got around that problem was to force people not to use spaces between \section and the section content. If they needed visual space in their source code, they could use comments to do that.

Well, I've swapped out that ugly definition for a slightly less ugly one that uses \llap (with a \smashed \parbox) and some creative gobbling. In particular,
% The section headings
%
% Usage: \section{section name}
\renewcommand{\section}[1]{\pagebreak[3]%
    \hyphenpenalty=10000%
    \vspace{1.3\baselineskip}%
    \phantomsection\addcontentsline{toc}{section}{#1}%
    \noindent\llap{\scshape\smash{%
        \parbox[t]{\marginparwidth}{\raggedright #1}}}%
    \vspace{-\baselineskip}\par}
The \vspace and \par combination should ensure that an additional \par isn't added by LaTeX. So before you were restricted to things like...
\section{Stuff} \begin{bibsection} %...
and
\section{Stuff}
%
Junk
But now you don't have to be so careful about the whitespace. You are allowed:
\section{Stuff}

\begin{bibsection} %...
and
\section{Stuff}

Junk
So that's cool. Much more readable.

You can get my most recent LaTeX CV templates at their page on my website. You can find a detailed history of the source code changes within my Mercurial repositories of documents.

(updated: new \gobblepars allows for arbitrary amount of space after each \section)
(updated: replaced \gobblepars with \par hack that still allows for arbitrary amount of space after each \section but also prevents lists from adding a \par when placed directly after a \section; consequently, adjusted all of the lone-lists to get rid of their leading negative vertical space (probably can get rid of them now, actually). I'm trying to shift toward using conventional lists (or perhaps conventional modifications of them from paralist or enumitem))

Wednesday, September 08, 2010

How to put "1 of ..." page numbers on a LaTeX letter

Someone e-mailed me recently to ask how to add "1 of LAST_PAGE" page numbers to a LaTeX letter document. I generated the sample LaTeX document fancy_letter_numbering.tex to show how it's done using the fancyhdr and lastpage packages.

Here is my response, which gives more details:
I have attached a sample letter with "1 of ..." page numbering throughout. fancyhdr works with "letter" just as well as it works with "article." You just have to treat "\opening" just like you do "\maketitle."

In particular, put this up in your preamble:
\usepackage{lastpage}
\usepackage{fancyhdr}
\fancyhead{}
\fancyfoot{}
\cfoot{\thepage{}~of~\pageref{LastPage}}
\pagestyle{fancy}
\renewcommand{\headrulewidth}{0pt}
\renewcommand{\footrulewidth}{0pt}
Then, after each "\opening" (in the case of a single letter, there will only be one), put the line:
\thispagestyle{fancy}
Otherwise you will get page numbers on every page except for the first one.
Of course, you will have to run LaTeX (or PDFLaTeX) at least twice to place the "LastPage" label properly and generate the correct page refeference.

[ Additionally, you may further customize the headings and footers making use of all of the nice features that come with the fancyhdr package. ]

Thursday, December 25, 2008

BibTeX Bibliography Style File (BST) for Engineering Applications of Artificial Intelligence (EAAI)

The Elsevier journal Engineering Applications of Artificial Intelligence suggests that authors use the elsart-harv.bst BibTeX bibliography style (BST) file to match its Harvard-style author-year reference format. However, elsart-harv.bst does not match the conventions used in EAAI proofs. In particular,
  • EAAI proofs use "Thesis" (instead of "thesis")
  • EAAI proofs surround the volume of an "in proceedings" entry with commas (instead of periods)
  • EAAI proofs use "vol." (instead of "Vol.")
  • EAAI proofs don't put any space between abbreviated parts of author names (but they do keep the hyphens in hyphenated abbreviations)
So I modified elsart-harv.bst to match EAAI conventions. My modified form is: To use it, just download it, place it in the same directory as your compuscript, and change your
\bibliographystyle{elsart-harv}
line to
\bibliographystyle{elsart-harv-EAAI}
Of course, elsart-harv-EAAI.bst is still natbib compatible.

[ NOTE: More-advanced users may prefer my elsart-harv-EAAI.patch. ]

Thursday, October 16, 2008

Fixing bug in hyperref's autoref: amsmath-type equations under items get "item" label

Earlier this year, in a comp.text.tex posting, I discussed a bug I found in hyperref. That bug was then fixed in hyperref 6.77a, but there are still plenty of old packages hanging around that have this bug (for example, the hyperref from TeXLive 2007 on my system that I still haven't upgraded to TeXLive 2008).

The problem happens when
  • amsmath (or mathtools) is loaded.
  • An equation (or any other type of displayed-math environment) environment with labels occurs INSIDE an enumerated item.
  • You try to use \autoref to generate a reference to one of those equation labels later.
The \autoref macro will not properly return an "Equation" label (e.g., "Equation 1"). Instead, it will return an "item" label (e.g., "item 1").

To fix this problem, I use these lines of code just after I load hyperref in my preamble:
\makeatletter
\newcommand{\AMShreffix}[1]{%
    \expandafter\let\csname old#1\expandafter\endcsname%
        \csname #1\endcsname%
    \expandafter\renewcommand\csname #1\endcsname{%
        \@hyper@itemfalse\csname old#1\endcsname}}
\makeatother
\AMShreffix{equation}
\AMShreffix{align}
\AMShreffix{gather}
The \AMShreffix (i.e., AMS-href-fix) macro "fixes" the displayed-math environment that you pass it. This example fixes equation, align, and gather. If you want to fix alignat too, add a \AMShreffix{alignat} at the end of those lines. Make similar changes for your other displayed-math environments (e.g., flalign and multline too).

That fix changes all of the improper "item" labels back into proper "Equation" labels.

Tuesday, September 23, 2008

Fixing natbib: Adding tie between author and citation

Something that bugs me about natbib is that \citet puts a formal SPACE between the authors and the citation list, and so LaTeX like...
. . . as discussed by \citet{SK86}.
that shows up near the end of a typeset line can turn into
as discussed by Stephens and Krebs
[1].
Not only does this put a number at the beginning of a line, which is a typography no-no when you aren't starting a numerical item in a list, but it separates the citation list from its neighbors. If natbib would just us a TIE (~ in TeX) instead, then the "Krebs" in the example above would never get separated from the "[1]."

The best solution is to fix natbib so that this character is configurable. That would really help when using superscript references because you could get rid of the character all together (right now superscripts get a space before them, and that looks a little silly (especially when superscripts show up on the next line!)). However, that could take a while to get fixed (CTAN isn't quite SourceForge)... So I put together the following fix, which should work OK for \citet, \citet*, \Citet, and \Citet* regardless of how many optional arguments (0, 1, or 2) are present.

(note: the \makeatletter and \makeatother commands are not needed if these lines are put into a .sty file or in a natbib.cfg file (in the same directory as your TeX document source).
% Unfortunately, natbib does not TIE textual 
% references to their citations. So authors
% sometimes get separated from citations when
% they come at the end of the line. The following
% lines attempt to fix this problem.
%
% The lines below do the equivalent of . . .
%
% \renewcommand\citet[1]%
% {\citeauthor{#1}~\citep{#1}}
%
% but they handle the star and capitalization and
% optional argument cases too.
%
% (the \makeatletter and \makeatother are not needed if
% these lines are put into a .sty file or in a natbib.cfg
% file)
\makeatletter
%
%%% These lines test for star and number of arguments
%%% and call the workhorses below
%
% Test for star (mid-sentence and start-sentence forms)
\def\citet{\@ifstar{\citetstar}{\citetnostar}}
\def\Citet{\@ifstar{\Citetstar}{\Citetnostar}}
%
% No star found. Now test for argument count.
\def\citetnostar%
{\@ifnextchar[{\squarecitet}{\simplecitet}}
\def\squarecitet[#1]%
{\@ifnextchar[{\twocitet[#1]}{\onecitet[#1]}}
\def\Citetnostar%
{\@ifnextchar[{\squareCitet}{\simpleCitet}}
\def\squareCitet[#1]%
{\@ifnextchar[{\twoCitet[#1]}{\oneCitet[#1]}}
%
% Star found. Now test for argument count.
\def\citetstar%
{\@ifnextchar[{\squarecitetstar}{\simplecitetstar}}
\def\squarecitetstar[#1]%
{\@ifnextchar[{\twocitetstar[#1]}{\onecitetstar[#1]}}
\def\Citetstar%
{\@ifnextchar[{\squareCitetstar}{\simpleCitetstar}}
\def\squareCitetstar[#1]%
{\@ifnextchar[{\twoCitetstar[#1]}{\oneCitetstar[#1]}}
%
\makeatother
%
%%% The following actually do the \cite work
%
% The \citet cases (no arg, one arg, and two args)
\def\simplecitet#1%
{\citeauthor{#1}~\citep{#1}}
\def\onecitet[#1]#2%
{\citeauthor{#2}~\citep[#1]{#2}}
\def\twocitet[#1][#2]#3%
{\citeauthor{#3}~\citep[#1][#2]{#3}}
%
% The \citet* cases (no arg, one arg, and two args)
\def\simplecitetstar#1%
{\citeauthor*{#1}~\citep{#1}}
\def\onecitetstar[#1]#2%
{\citeauthor*{#2}~\citep[#1]{#2}}
\def\twocitetstar[#1][#2]#3%
{\citeauthor*{#3}~\citep[#1][#2]{#3}}
%
% The \Citet cases (no arg, one arg, and two args)
\def\simpleCitet#1%
{\Citeauthor{#1}~\citep{#1}}
\def\oneCitet[#1]#2%
{\Citeauthor{#2}~\citep[#1]{#2}}
\def\twoCitet[#1][#2]#3%
{\Citeauthor{#3}~\citep[#1][#2]{#3}}
%
% The \Citet* cases (no arg, one arg, and two args)
\def\simpleCitetstar#1%
{\Citeauthor*{#1}~\citep{#1}}
\def\oneCitetstar[#1]#2%
{\Citeauthor*{#2}~\citep[#1]{#2}}
\def\twoCitetstar[#1][#2]#3%
{\Citeauthor*{#3}~\citep[#1][#2]{#3}}
Even if this problem gets fixed within natbib, it still might serve as a good example of how to deal with TWO or more optional arguments in macros...

UPDATE: For author-year citations (i.e., "Harvard style citations"), you must replace the \citep with \citeyearpar. That is, replace the final section of the code above with this section:
%%% The following actually do the \cite work
%
% The \citet cases (no arg, one arg, and two args)
\def\simplecitet#1%
{\citeauthor{#1}~\citeyearpar{#1}}
\def\onecitet[#1]#2%
{\citeauthor{#2}~\citeyearpar[#1]{#2}}
\def\twocitet[#1][#2]#3%
{\citeauthor{#3}~\citeyearpar[#1][#2]{#3}}
%
% The \citet* cases (no arg, one arg, and two args)
\def\simplecitetstar#1%
{\citeauthor*{#1}~\citeyearpar{#1}}
\def\onecitetstar[#1]#2%
{\citeauthor*{#2}~\citeyearpar[#1]{#2}}
\def\twocitetstar[#1][#2]#3%
{\citeauthor*{#3}~\citeyearpar[#1][#2]{#3}}
%
% The \Citet cases (no arg, one arg, and two args)
\def\simpleCitet#1%
{\Citeauthor{#1}~\citeyearpar{#1}}
\def\oneCitet[#1]#2%
{\Citeauthor{#2}~\citeyearpar[#1]{#2}}
\def\twoCitet[#1][#2]#3%
{\Citeauthor{#3}~\citeyearpar[#1][#2]{#3}}
%
% The \Citet* cases (no arg, one arg, and two args)
\def\simpleCitetstar#1%
{\Citeauthor*{#1}~\citeyearpar{#1}}
\def\oneCitetstar[#1]#2%
{\Citeauthor*{#2}~\citeyearpar[#1]{#2}}
\def\twoCitetstar[#1][#2]#3%
{\Citeauthor*{#3}~\citeyearpar[#1][#2]{#3}}
Those lines seem to work for me.

Thursday, September 04, 2008

Course web pages, LaTeX, and Mercurial — Oh, my!

I have been assigned to TA yet another different course for the Autumn 2008 quarter. That was a bummer for me because I have been taking instruction way too seriously, and it has been taking up way too much of my time. However, I've been pretty happy with the results. I've been getting flattering praise and very helpful feedback. More importantly for this post, I've been producing lots of revision-controlled content that can be used for reference or as examples.

The four course web pages that I've produced so far...I've tried to generate lots of reference material all with LaTeX, and I've tried to put the sites together so that everything can be build via standard Makefiles. I've put all of the source code (minus the exams/quizzes) at my public Mercurial repository home:In my latest adventure, ECE 209, I'm going to give my students extra credit if they use TeX for any assignments they hand in. So I've put getting-started information at those web pages, and they can use the Mercurial repositories for more working examples.

I'm really a lot more proud of this work than I thought I'd be. I'm actually looking forward to the new ECE 209 class. It's the youngest group of college students I've taught since a long time ago, and I think it will be interesting. Yesterday I went through and got the lab in order. I put up instructive signs about how to use oscilloscope probes and pin-outs of commonly-used ICs. I numbered all of the tables. I added notes to the function generators telling them how to set them for high impedance output termination. Earlier I went through and repaired all of the phase-shifter circuits (out of 16 circuits, only about 4 were working, but the other 12 could be easily repaired with a little solder and/or a new op-amp IC) and added a little instructive page on how they work. Now all that's left is the actual experience that will make me even more jaded and realize that all of that work was for nothing. :)

Meanwhile though... Lots of free LaTeX examples and circuit references. Yay!

Tuesday, August 19, 2008

Building MATLAB images from Makefiles

Recently I beefed up my LaTeX Makefiles to make image generation more automatic. These implicit rules have worked very well for me (note that the indentation is done with TABS — that's important).
%.pdf : %.eps
epstopdf $*.eps

%.eps : %.m
matlab -nosplash -nodesktop -r "$*;quit"

%.eps : %.png
convert -density $(RESOLUTION) $*.png $*.eps

%.eps : %.jpg
convert -density $(RESOLUTION) $*.jpg $*.eps

%.eps : %.dvi
dvips $* -D $(RESOLUTION) -E -o $*.eps

%.dvi : %.tex
latex -interaction=nonstopmode $*.tex
rm -f $*.log
rm -f $*.aux
That if, if I need a file called FILENAME.eps or FILENAME.pdf, the Makefile will look for FILENAME.m, FILENAME.png, FILENAME.jpg, or FILENAME.tex. Depending on which one it finds, it will run the appropriate command to generate the image I need. Note that I define RESOLUTION=1500 in the top of my Makefile.

I want to point out the MATLAB build line:
matlab -nosplash -nodesktop -r "$*;quit"
That handy line starts up as little of MATLAB as possible and runs a script that contains something like:
% First, generate a figure somehow

% Next, setup the figure's print proportions
set( gcf, 'PaperType', 'usletter', ...
'PaperOrientation', 'portrait', ...
'PaperPosition', [0.0 3.5 11 3.5] );

% Finally, save the figure as a (color) EPS
saveas( gcf, 'FILENAME.eps', 'epsc2' );
After the script finishes, MATLAB exits. It won't get started on any subsequent makes so long as the script file doesn't change or the image isn't deleted.

Getting back to the more general case, up high in my Makefile, I have something like
RESOLUTION=1500
BASETEXIMAGES=$(shell perl -ne \
'/\\includegraphics\s*(?:\[.*?\]|)\s*{\s*(.*?)\s*}/ \
&& do { print "$$1 " \
if (-e "$${1}.tex" || \
-e "$${1}.png" || \
-e "$${1}.jpg" || \
-e "$${1}.m"); };' *.tex)
TEXIMAGES=$(addsuffix .eps,$(BASETEXIMAGES))
and a little later I make $(TEXIMAGES) a dependency for my document (or something equivalent to that).

Those lines have saved me a lot of time, and I'm pretty happy about them.

Monday, July 28, 2008

Adding section or subsection to every reference (but not label)

In the form topic, "Full context variable depth references to list labels?," someone wanted to force LaTeX to
  • use legal-format lists
  • reformat its references to prefix them with the full subsection number (e.g., "2.1-") when inside a subsection and section number (e.g., "2-") otherwise.
I suggested:
\usepackage{enumitem}
\newlist{legal}{enumerate}{10}
\makeatletter
\setlist[legal]{label*=\arabic*.,
ref=\csname
the\enit@prevlabel
\endcsname\arabic*.}
\newcommand\thesectionlabel{%
\ifnum\value{subsection}=0
\thesection
\else
\thesubsection
\fi}
\newcommand{\thelegal}{\thesectionlabel-}
\makeatother

\usepackage{varioref}
\labelformat{equation}%
{\thesectionlabel-\textup{(#1)}}
\labelformat{figure}{\thesectionlabel-#1}
\labelformat{table}{\thesectionlabel-#1}
I've wrapped lines (by inserting VERY important % characters in special places to make the snippet viewable in this thin blog. As you can see in the original thread, my suggestion looked shorter because the lines were unwrapped.

It seems to work well and is one of those solutions that TeXnicians would probably do on their own without a second thought and would never document, but it's something complicated-enough that everyone else would tear their hair out searching for it.

Saturday, June 28, 2008

pedagogical moment: LaTeX, TeX, environments, and csname

On the MiKTeX mailing list, a thread descended into a flame that someone bracketed with \flameon and \flameoff, which is a sort of Fantastic Four version of a LaTeX environment. The thread involved the differences between TeX, Plain TeX, and LaTeX, and so I took the opportunity to point a few things out. I received several positive responses, and so I decided to reproduce my post here.
\pedagogical

There's a TeX vs. LaTeX teachable moment here . . .

> > \flameon
...
> > \flameoff


     As an example, if you're using LaTeX, the proper code for a flame environment is:
\begin{flame}
\end{flame}
However, the \begin and \end macros do nothing more than call:
\flame
\endflame
and so bracketing an environment in these macros is (in principle) equivalent to using the \begin and \end environments.

     Further, a naive implementation of \begin and \end is:
\newcommand\begin[1]{\csname #1\endcsname}
\newcommand\end[1]{\csname end#1\endcsname}
which is equivalent to the "raw" TeX (which may also be used in LaTeX):
\def\begin#1{\csname #1\endcsname}
\def\end#1{\csname end#1\endcsname}
In other words, \newcommand and \def are basically the same beast. However, \newcommand is a macro (created with \def) that checks to make sure you haven't already \newcommand'd before. SIMILARLY, the REAL \begin and \end wrappers have extra sanity checks for safety.

     Finally, that leaves
\csname BLAH\endcsname
which is equivalent to
\BLAH
Notice that it looks like an environment. So I could also do:
\begin{csname}today\end{csname}
which actually gives me the same output as \today.

\endpedagogical

     --Ted
I should also note that the source code for LaTeX is listed in the source2e.pdf documentation that comes with nearly every LaTeX distribution (it does not appear to come with MiKTeX). Execute
texdoc source2e
to see the document on your system.

Thursday, June 12, 2008

LaTeX generated figures: Using preview instead of pst-eps

I've been using the pst-eps package when I want to generate EPS versions of coded graphics (e.g., graphics produced with PSTricks or the standard picture environment). From the pst-eps description:
Pst-eps is a PSTricks (pstricks)-based package for exporting PSTricks images ‘on the fly’ to encapsulated PostScript (EPS) image files, which can then be read into a document in the usual way.
By wrapping lines in a TeXtoEPS environment, you setup LaTeX to produce an image of the enclosed content with a tight bounding box. It works well, but you must use dvips -E to generate your EPS files with the proper bounding box. If you want to then generate a PDF, you have to use something like epstopdf (possibly with the EPSCrop GhostScript option) to do it. Additionally, there's a lot of overhead within the actual TeX source. In other words, it's not quite easy to use.

A BETTER OPTION: Today, I discovered the preview package, which is described with:
The package is a free-standing part of the preview-latex bundle. The package provides the support preview-latex needs, when it chooses the matter it will preview. The output may reasonably be expected to have other uses, as in html translators, etc.
This package appears to be a much nicer solution. You can use standard latex or pdflatex to compile. If you need to use latex but still want EPS or PDF outputs, you can use dvips and ps2pdf without any special options. Otherwise, the introduced preview environment works very similar to the old TeXtoEPS environment, but it requires less work to use and seems to apply to a broader class of content.

Here's an example that should not require anything fancy to build. If you don't have the amsmath package (you should), you can omit it and get rid of the gather* environment:
\documentclass{article} 
\usepackage{amsmath} % for gather*
\usepackage[active, % Turns previewing on
tightpage, % Squeezes pages around previews
textmath, % Subjects textual math to a preview
displaymath, % Subjects math displays to preview
floats % Subjects floats to preview
]{preview}
% There is a ``graphics'' option too that subjects
% includegraphics to preview. If they are already in a
% float, the ``floats'' option is sufficient.
\begin{document}

This text will NOT get printed.

\begin{equation}
a = b
\end{equation}

The math following the colon gets printed: $x = 5$?

\begin{gather*}
c = d
\end{gather*}

More text not printed.

\begin{preview}
Page 2 is here (with tight border).
\end{preview}

You'll never see this text.

\begin{figure}
\fbox{\fbox{\fbox{A figure that is printed}}}
\end{figure}

\end{document}
If the active option of preview is commented out, the file builds as if preview didn't exist. However, with it turned on, only the sections in preview environments get printed, and they each get put on a separate page with tight borders. Options like displaymath, textmath, and floats cause those types of content to get automatically wrapped with a preview environment.

Related posts:

Tuesday, June 10, 2008

Safari Books On-line: Searchable TLC2

Check out Safari Books Online:It's pretty pricey to pay for a login, but requests that come from many universities (or libraries?) get a free login automatically. For example, from outside OSU, I can use my OSU login at:That is, I added ".proxy.lib.ohio-state.edu" to the end of the server name, which forces the request through the OSU library's proxy server.

There are lots of useful digital copies of reference books on-line. I think all of the O'Reilly books are available. More importantly (to me), you can find a digital (and searchable) copy of The LaTeX Companion (Second edition) by Mittelbach and Goossens. You can even copy and paste code samples directly out of the book!

Wednesday, March 05, 2008

Fixing Vim-LaTeX Compiler Error Messages

UPDATE: Another interesting option is to use rubber, a Python-based LaTeX wrapper. Among lots of other things, it sanitizes both error and warning messages in a format that's easy to use by Vim.
UPDATE: Most recent implementations of LaTeX can be told to generate sanitized error (but not warning!!) messages automatically. See Additionally, Martin Sander has put together a Python version of the vimlatex script.

NOTE: Personally, I use vimlatex and I do not instruct LaTeX to sanitize its error messages internally.

Quick Links:
  • vimlatex — LaTeX wrapper that sanitizes error messages for Vim
  • vimlatexpipe — a piped version
  • vimlatex.py — Martin Sander's Python alternative to the vimlatex shell script

If you use Vim-LaTeX, you've probably noticed that sometimes errors will cause Vim to open up a completely unrelated file on top of your current file. This is Vim's way of bringing you to the source of the error, but it parsed the latex return text improperly.

The problem is that LaTeX status messages keep track of which file is being used with parentheses over multiple lines. So, in order to figure out where an error is, Vim has to match opening parentheses with closing parentheses over multiple lines. Unfortunately, Vim's compiler error message features cannot do this if multiple parentheses are on one line.

So, I shamelessly borrowed an solution from Luc Hermitte's VIM Macros. Specifically, I was inspired by the vim-tex.sh, which pipes TeX output through a filter that corrects any problems that could confuse Vim. However, I didn't like that his script needed to create a temporary file, so I then borrowed a shell script tip off of a UNIX forum that copies file descriptors around so that actual disk files aren't needed.

The result is vimlatex, a shell script that post-processes TeX output so that it's in a form that Vim likes. To use it, just put it in your PATH and make it executable (i.e., chmod it 0755) and then add vimlatex in front of any compiler command you have. For example, if you have a compiler line in your .vimrc or in your Makefile that starts with latex, insert vimlatex (and a space) in front of the latex (i.e., change latex to vimlatex latex).

Alternatively, any output piped to vimlatexpipe will get properly sanitized for Vim too.

Vim-LaTeX, Vim 7.0, and the filetype plugin

Have you noticed that Vim-LaTeX sometimes does not automatically load when you open up a new .tex file?

If you're using Vim-LaTeX with Vim 7 or higher, you may want make sure you have this somewhere in your .vimrc:
" Prevents Vim 7.0 from setting filetype to 'plaintex'
let g:tex_flavor='latex'
Otherwise, some of your .tex files will not automatically kick off vim-latex on opening! In particular, vim-latex is usually only loaded if Vim finds a \documentclass, \begin, or \usepackage in the first 1000 uncommented lines of a .tex file. This change forces it to load for all .tex files.

So, if you're having problems getting Vim-LaTeX to load when Vim opens a .tex file, try making that change (as well as all of the filetype plugin changes to your .vimrc that are documented).

Some alternative solutions:
  • ALTERNATIVE 1: If you don't want to make that change, you can add
    %&latex
    to the top of any .tex file that you want to force to load vim-latex. That is, Vim will still default to using the plaintex flavor unless it sees that comment or commands like \documentclass, \begin, or \usepackage.

  • ALTERNATIVE 2: You can actually add
    % vim: filetype=tex
    OR
    % vim: ft=tex
    to ANY file to force vim-latex to load. (note: you may need to have the modeline option turned on in Vim for this to work)

  • ALTERNATIVE 3: While editing ANY file, you can execute the Vim command (in command mode):
    :set filetype=tex
    OR
    :set ft=tex
    to load vim-latex at that instant.
This post was updated on August 7, 2008.

Saturday, December 29, 2007

PDFSync Inverse Searches in MacVim

Remember the post on doing inverse searches in Vim on OS X? The idea was to drop gvim-pdfsync into
/usr/local/bin
(or somewhere else in your PATH) and then execute
gvim-pdfsync "%file" %line
to do inverse searches in Vim for OS X just like you can in Windows or in other UNIXes. For example, in Skim, under the PDFSync section of the Sync tab of the Preferences, you can put
Preset: Custom
Command: gvim-pdfsync
Arguments: "%file" %line

For MacVim

I thought it might be nice if I published how to do the same thing in the nascent MacVim, which supports servers just like Vim for Windows. Provided that you've installed the mvim shell script somewhere in your PATH, you can setup Skim with
Preset: Custom
Command: mvim
Arguments: --remote-tab-silent +":%line;foldo!" "%file"

or, if you don't like tabs
Preset: Custom
Command: mvim
Arguments: --remote-silent +":%line;foldo!" "%file"

Retro-Approach

Alternatively, if you really liked the gvim-pdfsync approach and want something similar for mvim, put mvimtab-pdfsync or (if you don't like tabs) mvim-pdfsync in your PATH (e.g., in /usr/local/bin) and then setup Skim for:
Preset: Custom
Command: mvimtab-pdfsync
Arguments: "%file" %line

or (if you used mvim-pdfsync)
Preset: Custom
Command: mvim-pdfsync
Arguments: "%file" %line
I hope that helps.

Friday, August 31, 2007

American Naturalist BibTeX BST style file

The American Naturalist, a University of Chicago Press - Journals Division journal, specifies that AASTeX should be used to typeset submissions; however, it does not provide any BibTeX BST bibliography style file. That means that authors still have to manually manage their reference list rather than using BibTeX and a central BIB bibliography database.

The BST: I've tried to remedy this by creating amnatnat.bst, a natbib-compatible BibTeX Bibliography STyle (BST) file for the American Naturalist.

As far as I can tell, this BST will generate a properly formatted BBL file that should not require modifications. Note that American Naturalist requires authors to upload their BBL files and NOT their BIB files (i.e., they don't have the ability to run BibTeX on the server).

ONE CAVEAT: If you have titles that contain colons in them, you will have to manually (either in the BIB or the BBL) change the case of the letter following the colon. For example, if "Some Title: Subtitle" is the title, change the "S" in "Subtitle" to "s". A feature/bug of BibTeX is that its sentence case keeps letters following colons capitalized. This does not match the sentence case definition used by many journals, which considers the words after a colon being at the middle of a sentence rather than the start of a new sentence. As far as I know right now, there is no easy way to change the BST file to do this automatically for you.

FYI: This BST file was generated using amnatnat.dbj (for more details, see amnatnat_full.dbj) and amnatnat.patch.

Thursday, August 23, 2007

LaTeX for generating Behavioral Ecology manuscript

UPDATE: Check out a more complete math-oriented template/example, that I posted as behavecol_math_template.tex. This is ready to use out of the box. It has comments. It is setup for AMS math. It has table, figure, and autoreferencing examples too.

IMPORTANT NOTE: If using amsmath environments, be sure to check out my information on making lineno compatible with amsmath environments.

UPDATE: I have put behavecol_template.tex and behavecol.bst on-line so that you don't have to do any of the following to get them.

The Oxford Journal Behavioral Ecology is not setup for LaTeX manuscript submissions. This baffles me.

So, I spent some time putting together some macros and a BibTeX style file to get up and running with this journal.

First, a template (that uses the article document class), which fixes incompatibilities between figcaps, caption, and anything that uses \ref (see behavecol_template.tex for what is below, or see behavecol_math_template.tex for a more complete example):
\documentclass[12pt]{article}

\usepackage[paper=letterpaper,margin=1.5in]{geometry}
\usepackage{setspace}\doublespacing

\usepackage{graphicx}

\usepackage[%
labelsep=newline,
justification=RaggedRight,
singlelinecheck=false,
labelfont=bf,
tableposition=top,
]{caption}
\captionsetup[table]{textfont=bf,position=above}
\makeatletter
\let\oldmakecaption\@makecaption
\makeatother

\usepackage[figon,printfigures]{figcaps}
\def\figurecapname{Figure legends}
\def\tablepagename{Tables}
\def\figurepagename{Figures}

\makeatletter
% This lets figcaps work with \ref
% However, forces \label outside of \caption
\def\phantomsection{\relax}
\let\oldfigurepage\@figurepage
\def\@figurepage{%
\@ifundefined{tf@pof}{}{%
\let\oldlabel\label%
\let\oldinput\@input%
\def\@input{\def\label{\oldlabel}\oldinput}%
\phantomsection%
\addcontentsline{toc}{section}{\figurepagename}}%
\oldfigurepage%
}
\let\@makefcaption\@makecaption
\let\oldtablepage\@tablepage
\def\@tablepage{%
\@ifundefined{tf@pot}{}{%
\clearpage%
\phantomsection%
\addcontentsline{toc}{section}{\tablepagename}}%
\oldtablepage%
}
\makeatother
\usepackage[subrefformat=subparens,labelformat=parens]{subfig}
\captionsetup[subfloat]{position=top}

\setcounter{secnumdepth}{0}

% Lines are numbered, starting at 1
% (add pagewise to reset at each page)
%\usepackage[modulo,pagewise,mathlines]{lineno}
\usepackage[modulo,mathlines]{lineno}
\modulolinenumbers[1]
\firstlinenumber{1}
\linenumbers

\usepackage{natbib}
\bibliographystyle{behavecol}
\setcitestyle{%
authoryear,round,semicolon,%
aysep={},%
yysep={,},%
notesep={, }%
}

\usepackage{tocbibind}
\def\tocbibname{\refname}

\usepackage{varioref}
\labelformat{equation}{\textup{(#1)}}
\labelformat{enumi}{\textup{(#1)}}

\usepackage[%
pdftitle={},
pdfsubject={},
pdfauthor={},
pdfkeywords={},
pdfstartview=FitH,
bookmarks=true,bookmarksopen=true,
breaklinks=true,
colorlinks=false,
pdfpagelabels=true,hypertexnames=true,
plainpages=false,naturalnames=false,
%draft,
]{hyperref}

% \Autoref is for the beginning of the sentence
\let\orgautoref\autoref
\providecommand{\Autoref}
{\def\equationautorefname{Equation}%
\def\figureautorefname{Figure}%
\def\subfigureautorefname{Figure}%
\def\Itemautorefname{Item}%
\def\tableautorefname{Table}%
\orgautoref}

% \Autorefs is plural for the beginning of the sentence
\providecommand{\Autorefs}
{\def\equationautorefname{Equations}%
\def\figureautorefname{Figures}%
\def\subfigureautorefname{Figures}%
\def\Itemautorefname{Items}%
\def\tableautorefname{Tables}%
\orgautoref}

% \autoref is used inside a sentence
% (renew of the standard autoref)
\renewcommand{\autoref}{\Autoref}

% \autorefs is plural for inside a sentence
\providecommand{\autorefs}{\Autorefs}

\let\oldsection\section
\newcommand{\uppercasesection}[2][]{%
\oldsection[#1]{\MakeUppercase{#2}}}
\newcommand{\uppercasesectionstar}[1]{%
\oldsection*{\MakeUppercase{#1}}}
\makeatletter
\def\section{%
\@ifstar{\uppercasesectionstar}%
{\@dblarg{\uppercasesection}}}
\makeatother

\hypersetup{%
pdftitle=
{The title},
}
\title{The title}
\author{}
\date{}

\begin{document}

\maketitle

\begin{abstract}
% ...The abstract...
\textit{Key words:} Keywords separated with comma+space,
List ends with period.
\hypersetup{%
pdfkeywords=
{Keywords separated with comma+space,
List ends with period},
}
\end{abstract}
\newpage

% ...The document...

% The following line loads the references
\bibliography{the_bib_database_name}

\end{document}
Of course, remember to put table captions before the actual table insertion. In fact, it is important that the inside of a table environment has caption first, then label OUTSIDE of the caption, then the actual table content. Additionally, subfigures should be inserted (within a figure environment) with something like:
\subfloat[]{
% ... something like an \includegraphics ...
\label{fig:a}
}
Also, when you're ready to submit, get rid of the % on the %draft, line of the hyperref options. This will turn off all hyper linking, which will prevent strange little unlinked boxes from being drawn in your autogenerated proof.

Next, the bibliography style file, which I may end up posting later separately. As of right now, it has to be constructed from pieces. First, save the following as behavecol.dbj (see behavecol_full.dbj for more details):
%% Driver file to produce behavecol.bst from merlin.mbs
%% Generated with makebst, version 4.1 (2003/09/08)
%% Produced on 2007/08/23 at 12:02
%%
\input docstrip

\preamble
----------------------------------------
*** Bibliography style for _Behavioral Ecology_. ***

\endpreamble

\postamble
End of customized bst file
\endpostamble

\keepsilent

\askforoverwritefalse
\def\MBopts{\from{merlin.mbs}{%
ay,nat,nm-rvx,ed-rev,jnrlst,keyxyr,dt-beg,yr-per,note-yr,jxper,%
jttl-rm,thtit-a,vnum-x,pp-last,num-xser,btit-rm,bt-rm,add-pub,%
pre-edn,in-col,pp,abr,ednx,ord,jabr,xand,etal-xc,nfss,}}
\generate{\file{behavecol.bst}{\MBopts}}
\endbatchfile
and then run latex behavecol.dbj. Next, save the following to behavecol.patch:
--- behavecol.bst 2007-08-29 12:07:40.000000000 -0400
+++ behavecol_new.bst 2007-08-29 12:08:01.000000000 -0400
@@ -89,7 +89,7 @@
FUNCTION {output.nonnull}
{ 's :=
output.state mid.sentence =
- { ", " * write$ }
+ { ". " * write$ }
{ output.state after.block =
{ add.period$ write$
newline$
@@ -144,6 +144,9 @@
FUNCTION {add.blank}
{ " " * before.all 'output.state :=
}
+FUNCTION {add.semicolon}
+{ ";" * before.all 'output.state :=
+}

FUNCTION {date.block}
{
@@ -248,7 +251,7 @@
{ "in" }

FUNCTION {bbl.pages}
-{ "pp." }
+{ "p." }

FUNCTION {bbl.page}
{ "p." }
@@ -260,10 +263,10 @@
{ "Tech. Rep." }

FUNCTION {bbl.mthesis}
-{ "Master's thesis" }
+{ "[Master's thesis]" }

FUNCTION {bbl.phdthesis}
-{ "Ph.D. thesis" }
+{ "[PhD thesis]" }

FUNCTION {bbl.first}
{ "1st" }
@@ -488,6 +491,16 @@
}
if$
}
+FUNCTION {format.book.pages}
+{ pages "pages" bibinfo.check
+ %duplicate$ empty$ 'skip$
+ empty$ 'skip$
+ { add.semicolon
+ add.blank
+ pages "pages" bibinfo.check
+ " " * bbl.pages * }
+ if$
+}
FUNCTION {format.note}
{
note empty$
@@ -950,6 +963,10 @@
}
if$
}
+FUNCTION {format.university.address}
+{ school "school" bibinfo.warn format.org.or.pub
+}
+
FUNCTION {format.publisher.address}
{ publisher "publisher" bibinfo.warn format.org.or.pub
}
@@ -1148,12 +1165,11 @@
author format.key output
format.date "year" output.check
date.block
- format.title
- "title" output.check
- new.block
+ format.title "title" output.check
+ add.blank
bbl.mthesis format.thesis.type output.nonnull
- school "school" bibinfo.warn output
- address "address" bibinfo.check output
+ format.university.address output
+ format.book.pages output
new.block
format.note output
fin.entry
@@ -1178,12 +1194,11 @@
author format.key output
format.date "year" output.check
date.block
- format.title
- "title" output.check
- new.block
+ format.title "title" output.check
+ add.blank
bbl.phdthesis format.thesis.type output.nonnull
- school "school" bibinfo.warn output
- address "address" bibinfo.check output
+ format.university.address output
+ format.book.pages output
new.block
format.note output
fin.entry
Then run
patch < behavecol.patch
from the same directory that you ran the DBJ command in. That should generate the behavecol.bst file that is needed for the above template to work.

Wednesday, August 08, 2007

Broken sections in Elsevier elsart1p, elsart3p, and elsart5p

UPDATE: You should probably add
\def\@seccntformat#1{{\@secnumfont{}\csname the#1\endcsname.}\quad}
around line 128 (i.e., after the \@secnumfont definition) as well. Alternatively, you could add something similar (surrounded by \makeatletter and \makeatother) to your preamble.

Ever notice how section* is broken in elsart1p.cls, elsart3p.cls, and elsart5p.cls from Elsevier? Because of this, the section titles for the acknowledgments (i.e., from \ack) and the references look like normal text. Plus, the references do not show up in the PDF bookmarks. This "feature" is annoying; working with journals generally is.

How to fix this? You have to hack the document class files. In particular, you need to remove (or comment by placing a % on the beginning of the line) a chunk of lines from the document class of interest to you. In particular, remove
  • elsart1p.cls - lines 144--196
  • elsart3p.cls - lines 147--199
  • elsart5p.cls - lines 144--196
These lines redefine the LaTeX internals \@startsection, \@sect, and \@ssect. However, it does not appear there is any good reason why Elsevier has done this, so just stick with the standard ones. This will make your document look much better too.

Until Elsevier does this for you, you should upload your modified document class with your article OR use the elsart document class in the version you send to Elsevier.

Tuesday, August 07, 2007

lineno and amsmath compatibility

UPDATE 2 (READ THIS!): As Ulrich Diez points out, this can be made more compact. Here's the result (place this in the preamble, probably anywhere):
\newcommand*\patchAmsMathEnvironmentForLineno[1]{%
\expandafter\let\csname old#1\expandafter\endcsname\csname #1\endcsname
\expandafter\let\csname oldend#1\expandafter\endcsname\csname end#1\endcsname
\renewenvironment{#1}%
{\linenomath\csname old#1\endcsname}%
{\csname oldend#1\endcsname\endlinenomath}}%
\newcommand*\patchBothAmsMathEnvironmentsForLineno[1]{%
\patchAmsMathEnvironmentForLineno{#1}%
\patchAmsMathEnvironmentForLineno{#1*}}%
\AtBeginDocument{%
\patchBothAmsMathEnvironmentsForLineno{equation}%
\patchBothAmsMathEnvironmentsForLineno{align}%
\patchBothAmsMathEnvironmentsForLineno{flalign}%
\patchBothAmsMathEnvironmentsForLineno{alignat}%
\patchBothAmsMathEnvironmentsForLineno{gather}%
\patchBothAmsMathEnvironmentsForLineno{multline}%
}
This is all that is needed for the standard AMS math environments. However, if you want to add environment BLAH, you can add
\patchAmsMathEnvironmentForLineno{BLAH}
before the closing curly brace. If you want to add environments BLAH and BLAH*, you can add
\patchBothAmsMathEnvironmentsForLineno{BLAH}
before the closing curly brace.

UPDATE 1: If you use the mathlines lineno option, you may notice that amsmath environments like align may create strange double numbers at the end of the environment. I haven't looked into why this is the case. If you really need mathlines loaded, you may want to consider ways of using equation or equation* exclusively. Keep in mind that you will still need to load at least the equation and equation* lines:
\AtBeginDocument{%
%
\let\oldequation\equation%
\let\endoldequation\endequation%
\renewenvironment{equation}%
{\linenomath\oldequation}{\endoldequation\endlinenomath}%
%
\expandafter\let\expandafter\oldequationstar\csname equation*\endcsname%
\expandafter\let\expandafter\endoldequationstar\csname endequation*\endcsname%
\renewenvironment{equation*}%
{\linenomath\oldequationstar}{\endoldequationstar\endlinenomath}%
}
You may think that the displaymath option of lineno will do this for you, but loading amsmath seems to prevent that. I haven't looked into why.

A comp.text.tex post gives some history behind this fix.

It's well-known that lineno and amsmath don't play well together. After loading amsmath, the paragraph that precedes an equation, equation*, align, align*, or any of the other amsmath environments will cease to get line numbers. The ugly fix to this is to wrap every math environment with a linenomath environment. That's pretty annoying. Here's a fix that redefines the equation environment and the amsmath environments so that they'll work with noalign. Yes, it even handles the starred versions of these.
% To deal with amsmath, must redefine math environments later
\AtBeginDocument{%
%
\let\oldequation\equation%
\let\endoldequation\endequation%
\renewenvironment{equation}%
{\linenomath\oldequation}{\endoldequation\endlinenomath}%
%
\expandafter\let\expandafter\oldequationstar\csname equation*\endcsname%
\expandafter\let\expandafter\endoldequationstar\csname endequation*\endcsname%
\renewenvironment{equation*}%
{\linenomath\oldequationstar}{\endoldequationstar\endlinenomath}%
%
\let\oldalign\align%
\let\endoldalign\endalign%
\renewenvironment{align}%
{\linenomath\oldalign}{\endoldalign\endlinenomath}%
%
\expandafter\let\expandafter\oldalignstar\csname align*\endcsname%
\expandafter\let\expandafter\endoldalignstar\csname endalign*\endcsname%
\renewenvironment{align*}%
{\linenomath\oldalignstar}{\endoldalignstar\endlinenomath}%
%
\let\oldflalign\flalign%
\let\endoldflalign\endflalign%
\renewenvironment{flalign}%
{\linenomath\oldflalign}{\endoldflalign\endlinenomath}%
%
\expandafter\let\expandafter\oldflalignstar\csname flalign*\endcsname%
\expandafter\let\expandafter\endoldflalignstar\csname endflalign*\endcsname%
\renewenvironment{flalign*}%
{\linenomath\oldflalignstar}{\endoldflalignstar\endlinenomath}%
%
\let\oldalignat\alignat%
\let\endoldalignat\endalignat%
\renewenvironment{alignat}%
{\linenomath\oldalignat}{\endoldalignat\endlinenomath}%
%
\expandafter\let\expandafter\oldalignatstar\csname alignat*\endcsname%
\expandafter\let\expandafter\endoldalignatstar\csname endalignat*\endcsname%
\renewenvironment{alignat*}%
{\linenomath\oldalignatstar}{\endoldalignatstar\endlinenomath}%
%
\let\oldgather\gather%
\let\endoldgather\endgather%
\renewenvironment{gather}%
{\linenomath\oldgather}{\endoldgather\endlinenomath}%
%
\expandafter\let\expandafter\oldgatherstar\csname gather*\endcsname%
\expandafter\let\expandafter\endoldgatherstar\csname endgather*\endcsname%
\renewenvironment{gather*}%
{\linenomath\oldgatherstar}{\endoldgatherstar\endlinenomath}%
%
\let\oldmultline\multline%
\let\endoldmultline\endmultline%
\renewenvironment{multline}%
{\linenomath\oldmultline}{\endoldmultline\endlinenomath}%
%
\expandafter\let\expandafter\oldmultlinestar\csname multline*\endcsname%
\expandafter\let\expandafter\endoldmultlinestar\csname endmultline*\endcsname%
\renewenvironment{multline*}%
{\linenomath\oldmultlinestar}{\endoldmultlinestar\endlinenomath}%
%
}
The pattern is pretty clear. You can use it along with any of your own environments. For example, add this at the end (before the closing curly brace) to fix your BLAH environment:
\let\oldBLAH\BLAH%
\let\endoldBLAH\endBLAH%
\renewenvironment{BLAH}%
{\linenomath\oldBLAH}{\endoldBLAH\endlinenomath}%
and drop this at the end (before the closing curly brace) to fix your BLAH* environment:
\expandafter\let\expandafter\oldBLAHstar\csname BLAH*\endcsname%
\expandafter\let\expandafter\endoldBLAHstar\csname endBLAH*\endcsname%
\renewenvironment{BLAH*}%
{\linenomath\oldBLAHstar}{\endoldBLAHstar\endlinenomath}%
I hope that's useful for someone.