Showing posts with label examples. Show all posts
Showing posts with label examples. Show all posts

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, 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.

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.

Friday, June 27, 2008

Interpolating for Zero-Crossing Detection in MATLAB

Today someone who read my post on sinc interpolation in MATLAB e-mailed me to ask about how to interpolate between data points in MATLAB to do accurate zero-crossing detection. Here, I summarize my response.

Detecting zero crossings of (nearly) square waves that are sampled is difficult to do accurately because it pushes the limits of the "band-limited" signal approximation we use when sampling. That being said, if you'd like to use sinc interpolation, you should decide *HOW* close you need to be to the zero crossing. For example, your original signal might have 50 picoseconds between samples, and so without interpolation, you can detect zero crossings accurate within 50 picoseconds (ps). Maybe you need a closer result. How close do you need to be? 10ps? 5ps? 1ps? Less than that?

Figure out how close you need to be and then generate the appropriate upsampled time vector:
uptime = 0:step_size:final_time;
where step_size is your tolerance (e.g., 5 ps) and final_time is the maximum value of your sampled time vector. It is a good idea to engineer your step_size and final_time so that length(uptime)/length(old_time) is an INTEGER. It's also a good idea to make sure that all of your old_time points (except maybe your last point) exist in your uptime vector (i.e., your uptime vector just has time ADDED between old_time points).

Then you can use any interpolation mechanism you'd like. If you want to use the sinc_interp function that I wrote, do something like:
new_values = sinc_interp( old_values, old_time, uptime );
If you use sinc_interp, make sure you use the VECTORIZED version, which is MUCH faster. Actually, MATLAB provides a MUCH faster function that does NEARLY the exact same thing — the interpft command. In that case, you do
new_values = interpft( old_values, length(uptime) )
Otherwise, you might have luck using the resample command in MATLAB (it does NOT do pure sinc interpolation; it's more sophisticated, and it may not match at every data point):
new_values = resample( old_values, P, Q );
where P/Q is the INTEGER representing length(new_time)/length(old_time) (again, engineer your step_size to make this possible). ALTERNATIVELY, interp works OK too:
new_values = interp( old_values, P/Q );
Try all three and see which one works best for you.

Once you have this new interpolated vector, use some mechanism to detect zero crossings. Off the top of my head, here's the fastest way I can think of to do the zero-detection. Assume that we have
  • y (column vector of data -- e.g., new_values)
  • t (column vector of time -- e.g., uptime)
Also assume that t is already sorted. Then... (note that union sorts too)
i = union( find(y==0), find(conv(sign(y),[1 1]) == 0) );
should give you the MATLAB indexes where y crosses zero.

To test, try...
plot( t, y );
hold on;
stem( t(i), max(y)*ones(size(i)) );
hold off;
The result should be a plot of your data with spikes added at each zero crossing. That example also demonstrates how you recover the particular zero-crossing times with
t(i)
For example, when I apply this algorithm to a sin(t) waveform, t(i) gives me 0, pi, 2*pi, and 3*pi out, as expected.

Thursday, June 26, 2008

sinc interpolation in MATLAB

UPDATE: The examples given here are meant to give mathematical insight into how sinc interpolation works by using a finite-time APPROXIMATION. Sinc interpolation necessarily involves a circular convolution, which is not a finite computation in the time domain. If you actually need to do sinc interpolation, use the interpft function. It does an FFT, pads the FFT with zeros, and does an IFFT. Consequently, it is VERY FAST. Moreover, using an FFT (or DFT, in general) is the only way to use a finite computation to do a sinc interpolation (or circular convolution in general). Just make sure that the resampled time vector you use has a length that is an integer multiple of your original time vector. Also make sure that it lands on the same points as your original time vector (i.e., it should only add new points between old points).

I've also created a interpftw that does the same job as interpft but allows you to reconstruct samples from different aliasing windows. Whereas interpft pads the end of the FFT with zeros, interpftw pads both the beginning and the end. In other words, the former is a low-pass filter and the latter is a bandpass filter.
If you search Google for sinc interpolation in MATLAB, many pages will reference the sinc_interp example from John Loomis. Unfortunately, I've found few sites that recognize that the function is not meant to do general purpose sinc interpolation. That is, it makes a few assumptions about the sampling rates that may not be evident to the average user.

So, I'm giving some of my students this example:
% Ideally "resamples" x vector from s to u by sinc interpolation
function y = sinc_interp(x,s,u)
    % Interpolates x sampled sampled at "s" instants
    % Output y is sampled at "u" instants ("u" for "upsampled")


    % Find the sampling period of the undersampled signal
    T = s(2)-s(1);

    for i=1:length(u)
        y( i ) = sum( x .* sinc( (1/T)*(u(i) - s) ) );
    end

    % Make sure y is same shape as u (row->row, col->col)
    y = reshape(y, size(u));
end
Here's a vectorized (i.e., MUCH FASTER) version:
% Ideally "resamples" x vector from s to u by sinc interpolation
function y = sinc_interp(x,s,u)
    % Interpolates x sampled at "s" uniformly spaced instants
    % Output y is sampled at "u" uniformly spaced instants
    % ("s" for "sampled" and "u" for "upsampled")
    % (consequently, length(x)=length(s))


    % Find the period of the undersampled signal
    T = s(2)-s(1);

    % The entries of this matrix are each u-s permutation.
    % It will be used to generate the sinc transform that will
    % be convolved below with the input signal to do the
    % interpolation.
    %
    % (recall that u(:) will be a column vector regardless
    % of the row-ness of u. So u(:) is a row, and s(:) is a
    % column)

    sincM = repmat( u(:), 1, length(s) ) ...
           - repmat( s(:)', length(u), 1 );

    % * Sinc is the inverse Fourier transform of the boxcar in
    % the frequency domain that was used to filter out the
    % ambiguous copies of the signal generated from sampling.
    % * That sinc, which is now sampled at length(u) instants,
    % is convolved with the input signal becuse the boxcar was
    % multipled with its Fourier transform.
    % So this multiplication (which is a matrix transformation
    % of the input vector x) is an implementation of a
    % convolution.
    % (reshape is used to ensure y has same shape as upsampled u)

    y = reshape( sinc( sincM/T )*x(:) , size(u) );
end
My function sinc_interp resamples the data in the x vector. The original time vector is given by the s vector and the new time vector is given by the u vector.

Alternatively, you can try this more advanced one that lets you pick which aliasing window you want to use to reconstruct (i.e., it's an ideal bandpass filter rather than just a low-pass filter).
% Ideally "resamples" x vector from s to u by sinc interpolation
function y = sinc_interp(x,s,u,N)
    % Interpolates x sampled sampled at "s" instants
    % Output y is sampled at "u" instants ("u" for "upsampled")
    % Optionally, uses the Nth sampling window where N=0 is DC
    %     (so non-baseband signals have N = 1,2,3,...)


    if nargin < 4
        N = 0;
    end

    % Find the period of the undersampled signal
    T = s(2)-s(1);

    for i=1:length(u)
        y( i ) = ...
            sum( x .* ...
                ( (N+1)*sinc( ((N+1)/T)*(u(i) - s) ) - ...
                  N*sinc( (N/T)*(u(i) - s) ) ) );
    end
end
Here's a vectorized (i.e., MUCH FASTER) version:
% Ideally "resamples" x vector from s to u by sinc interpolation
function y = sinc_interp(x,s,u,N)
    % Interpolates x sampled sampled at "s" instants
    % Output y is sampled at "u" instants ("u" for "upsampled")
    % Optionally, uses the Nth sampling window where N=0 is DC
    % (so non-baseband signals have N = 1,2,3,...)


    if nargin < 4
        N = 0;
    end

    % Find the period of the undersampled signal
    T = s(2)-s(1);

    % When generating this matrix, remember that "s" and "u" are
    % passed as ROW vectors and "y" is expected to also be a ROW
    % vector. If everything were column vectors, we'd do.
    %
    % sincM = repmat( u, 1, length(s) ) - repmat( s', length(u), 1 );
    %
    % So that the matrix would be longer than it is wide.
    % Here, we generate the transpose of that matrix.

    sincM = repmat( u, length(s), 1 ) - repmat( s', 1, length(u) );

    % Equivalent to column vector math:
    % y = sinc( sincM'(N+1)/T )*x';

    y = x*( (N+1)*sinc( sincM*(N+1)/T ) - N*sinc( sincM*N/T ) );
end

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.

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.

Thursday, July 26, 2007

Tedly Quick Searches

If you're not familiar with keywords and quick searches in Mozilla Firefox and Mozilla Camino, you should check out "Fifteen Firefox Quick Searches" and "Firefox and the art of keyword bookmarking." Mozilla quick searches and keywords shave hours off each of my weeks (if not days).

I've posted my quick searches, and you can save them and import them into your own Mozilla bookmarks. For instructions on how to do this, see the quick searches post from above. My quick search bookmarks are basically an improvement on the bookmarks given in that post. I've fixed some annoying things about her selections, and I've added a few more.

If you do use my bookmarks, be sure to modify the local one and change the zipcode from 43210 to your zipcode.

Thursday, July 19, 2007

Hot Key References

NOTE: The two updates below may serve as good LaTeX examples featuring the use of multicol.

UPDATE 2: I have used the Thunderbird list to make a Thunderbird quick reference PDF (LaTeX source available).

UPDATE 1: I have used the Camino list to make a Camino quick reference PDF (LaTeX source available).

I have been posting about quick references a lot lately [e.g., 1, 2]. I found another good quick reference site, allhotkeys.com. It has lots of software hotkey quick references. For example,
So that's potentially helpful. But right now the pages are really slow to come up, so I have no idea what they look like. Nor do I know if I can easily get them onto a landscape sheet of paper that I can tape to the wall somewhere...

Wednesday, July 18, 2007

Traditional way to change cleveref defaults

UPDATE: cleveref also includes a set of defaults for the ntheorem package when the ntheorem option is given. I've just put those defaults into cleveref_nthoerem_defaults.tex. Include it with \input{cleveref_ntheorem_defaults.tex} after (or instead of) including the other file.

Because it will probably be a long time until a simpler way of changing cleveref defaults gets implemented, I needed a way to change these defaults without adding tens of lines to my LaTeX source. I came up with cleveref_defaults.tex, which basically contains all of the default lines from the cleveref documentation, plus a set of table defaults. You can include it with:
\input{cleveref_defaults.tex}
Then, go ahead and modify cleveref_defaults.tex to match your conventions (e.g., change the four "eq." to "Eq." and the four "eqs." to "Eqs.").

Protype for simplifying changing cleveref defaults

UPDATE: I have created crefntheoremdefaults.tex, which does this same stuff to the ntheorem package. You have to be sure to include the crefdefaults.tex file first. The files crefntheoremdefault_constants.tex and crefntheoremdefault_formats.tex play a similar role as the analogous ones below.

I think the package cleveref is great. In fact, I think it has much of what has been missing from LaTeX for a long time. See its documentation for more information about the package.

My only gripe about cleveref is that it is tedious to change something like all of the default "eq." and "eqs." to "Eq." and "Eqs.", respectively. So I put together these scripts as a kind of proof of concept (they also setup cleveref to handle table references, something that is not done by default at the moment):

The first script, crefdefaults.tex, is simply crefdefault_constants.tex concatenated with crefdefault_formats.tex. Therefore,
\input{crefdefaults.tex}
is equivalent to
\input{crefdefault_constants.tex}
\input{crefdefault_formats.tex}
However, if the poorman option is used and the corresponding sed script is applied, the resulting file will need to have the content of crefdefault_formats.tex removed; crefdefault_constants.tex should not be removed. In other words, if you are planning on using poorman, use the 2-line include and comment the crefdefault_formats.tex line out of the script that results from the sed script.

What's the outcome of this? I can now do
\renewcommand{\crefenumilabelformat}[3]{\textup{(#2#1#3)}}
in order to change every item reference so that it is surrounded by upright round braces. Additionally, changing "eq." to "Eq." and "eqs." to "Eqs." is as simple as it was in hyperref (for use with \autoref); that is, it is these two lines:
\renewcommand{\crefequationname}{Eq.}
\renewcommand{\crefpluralequationname}{Eqs.}
Unfortunately, the output of the poorman sed filter is a little messy. However, if these are someday integrated into cleveref, that could be fixed. There are other shortcuts built into crefdefaults.tex as well. It probably requires documentation, but it's just a prototype for now.

Good idea? Bad?

Tuesday, July 17, 2007

Using Skim, PDFSync, and TeXShop

UPDATE 3: I have updated the script to support command-line options that will prevent TeXShop from doing things like refreshing text (and trashing your unsaved changes), activating (taking your focus away), and opening (possibly getting in front of your view). Try the -h option for details.

UPDATE 2: There is a related Skim revision that will make it easier to use AppleScript for PDFSync interfacing. This change will prevent having to make UNIX shell scripts that must be modified with chmod.

UPDATE 1: As you can see in the Skim revision history, future versions of Skim will include their "Application Support" directory (e.g., ~/Library/Application Support/Skim/) as well as a "Scripts" subdirectory in their path. When that occurs, scripts like the one below can be stored there and executed from Skim without specifying the full path name.

I know there are ways to change TeXShop's previewer; however, I don't know how to do them. Additionally, I don't use TeXShop, so I have little incentive to look those things up.

However, I do use Skim, which is compatible with pdfsync, and recently someone asked me how they could get Skim to call up TeXShop at a particular line (as someone would want to do when using pdfsync).

For that, I generated a texshop script that looks like this (an earlier version of this can be found on the Skim wiki):
fileName="$1"
lineNumber="$2"
gotoString=""

[ "${fileName:0:1}" == "/" ] || fileName="${PWD}/${fileName}"
[ "${lineNumber}" == "" ] || gotoString="goto line ${lineNumber}"

exec osascript \
-e "set texFile to POSIX file \"${fileName}\"" \
-e "tell application \"TeXShop\"" \
-e "activate" \
-e "open texFile" \
-e "tell front document" \
-e "refreshtext" \
-e "${gotoString}" \
-e "end tell" \
-e "end tell"
To use this script, follow these steps:
  1. Save that file as something (preferably in the PATH somewhere, but this is not necessary) like
    /usr/local/bin/texshop
    or anywhere you would like (e.g., /Users/username/bin/texshop). However, if you place it somewhere differently, be sure to update the red text in these instructions.

  2. Next, chmod it 0755, as in
    chmod 0755 /usr/local/bin/texshop
    This can be done from the Terminal.

  3. Finally, tell Skim's PDFSync preferences (under Preferences->LaTeX or Preferences->Sync depending on your Skim version) to use a "Custom" editor with
    Command: /usr/local/bin/texshop
    Arguments: "%file" %line
    Make sure you click AWAY (e.g., onto a different tab) from the PDFSync settings before you close the Preferences. Otherwise, one of your text boxes may not get saved.
After this is done, doing Shift+Command+CLICK in Skim on a location in the PDF will bring up the source in TeXShop located at the that generated that point in the PDF.

Note that if you have saved texshop somewhere in your PATH, then you should be able to drop the /usr/local/bin/ from the front of the Command: line.

Wednesday, July 11, 2007

PDFSync inverse searches on Vim for OS X

FINAL UPDATE: See the new post, "PDFSync Inverse Searches in MacVim," for the state of the art on this subject.
UPDATE 8: Skim 0.6 and up supports spell checking of a PDF. This is a strange feature of a PDF viewer since Skim does not allow you to edit the PDF text directly. However, it makes a lot of sense when inverse searches are supported. After doing Shift+Command+CLICK on the misspelled word, the TeX editor will open up near the line of TeX where the word is found.

UPDATE 7: caveat Vimmer! Inverse searches in Skim are called up with Shift+Command+CLICK. This is fine; however, if you hold Shift+Command too long, the AppleScript for calling up Vim is going to get confused. In other words, be sure to release the modifier keys as soon as possible after the "click."

UPDATE 6: I found information about doing both forward and backward searches with Vim and PDFView (see also: using gotoline.sh). From these, I've made hacks to the VIM-LaTeX scripts for PDFView and other viewers (like Skim and TeXniscope). I will describe these hacks in another post.

UPDATE 5: See Vim Tip #225 and the corresponding wiki entry for information about both backward and FORWARD searches in Vim. I also found a nice LaTeX tools script for Vim that has forward searching built in. I found these pages linked from a page on xdvi inverse searches.

UPDATE 4: Very trivial updates have been made in a 1.03 version of this script.

UPDATE 3: I have posted a 1.02 version of this script. The changes are fairly trivial, but you might be interested in checking it out.

UPDATE 2: This script is now a part of the Skim wiki.

UPDATE 1: I have mirrored this post at my web site.

WINDOWS USERS: See "Performing inverse searches" from the VIM-LaTeX quick start guide.

I have posted information about this in a number of places [1, 2, 3, 4, 5]. I plan to add something at MacResearch sometime soon too.

The package PDFSync allows users to do "backward searches" or "inverse searches" from PDF viewers like iTeXMac, TeXniscope, Skim, and others. That is, if you generate a PDF with LaTeX (or Plain TeX or ConTeXt), you will be able to click on text in the PDF and have an editor open up and position the cursor at the TeX source code that generated that text. That can be very nice.

There is a related feature for DVI files, but there are very few good DVI viewers out there (TeXniscope comes close), so I just focus on PDFSync).

I use Vim with VIM-LaTeX to do my document preparation. I would like to also be able to use PDFSync. However, while inverse searching is supported in Windows, it is not easily done in OS X.

I found a thread describing how to do inverse searching with AppleScript that issues raw commands to Vim. I decided to take that AppleScript, package it into a bash script, and fix it so that it had no problem handling files with spaces or symlinked files or multiple files with the same base name. The result is this script:
#!/bin/bash

filename="$1"
lineNum="$2"

[ "${filename:0:1}" == "/" ] || filename="${PWD}/${filename}"

exec osascript \
-e "set ESC to ASCII character of 27" \
-e "tell application \"Vim\" to activate" \
-e "tell application \"System Events\"" \
-e "tell process \"Vim\"" \
-e "keystroke ESC & \":set hidden\" & return " \
-e "keystroke \":if bufexists('$filename')\" & return " \
-e "keystroke \":exe \\\":buffer \\\" . bufnr('${filename}')\" & return " \
-e "keystroke \":else \" & return " \
-e "keystroke \": edit ${filename// /\\\\ }\" & return " \
-e "keystroke \":endif\" & return " \
-e "keystroke \":${lineNum}\" & return " \
-e "keystroke \"zO\" " \
-e "end tell" \
-e "end tell"
Copy that script in a place (preferably in your PATH) like
/usr/local/bin/gvim-pdfsync
and chmod it 0755. That is, do
chmod 0755 /usr/local/bin/gvim-pdfsync
Then you can use the script like
gvim-pdfsync "%file" %line
where %file is the name of the file to be opened and %line is the line to place the cursor on. So, for Skim, you would put in your LaTeX (or Sync) preferences under "PDFSync" support:
Preset: Custom
Command: gvim-pdfsync
Arguments: "%file" %line
After configuring Skim, BE SURE TO CLICK AWAY FROM THE TEXT BOXES before closing the configuration. For example, click on one of the other tabs. Otherwise, the dialog box may not record your changes to the last text box you changed.

I hope that's useful to someone.

Friday, July 06, 2007

Script to open file in TeXniscope from command line

UPDATE 2: A much fancier version of this script is now available. It has options that make it easier to make TeXniscope update its file and position (via PDFSync or DVI source specials) in the background. The options are described briefly with the -h parameter.

UPDATE 1: A more mature version of this script is now available. It has a usage line. It checks for the existence of files. It tries to guess at a file name if the file does not exist. It's a little more convenient for the command-line user.

Here's a script to open a (PDF or PostScript) file in TeXniscope from the command line:
#!/bin/sh

[ "`echo $*|cut -c 1`" == "/" ] || filename_prefix="`pwd`"

exec osascript \
-e "tell application \"TeXniscope\"" \
-e "activate" \
-e "open file ((POSIX file \"$filename_prefix/$*\") as string)" \
-e "refresh of the front document" \
-e "end tell";
or, alternatively,
#!/bin/bash

arguments="$*"
[ "${arguments:0:1}" == "/" ] || filename_prefix="$PWD"

exec osascript \
-e "tell application \"TeXniscope\"" \
-e "activate" \
-e "open file ((POSIX file \"$filename_prefix/$*\") as string)" \
-e "refresh of the front document" \
-e "end tell";

Create an executable script called texniscope (e.g., /usr/local/bin/texniscope that is chmod'd 755) and try texniscope FILENAME where FILENAME is the name of the PDF or PostScript file that you want to open (be sure to include the file extension).

This allows you to use TeXniscope as a LaTeX document viewer in the VIM-LaTeX suite for Vim.

See also: Script to open file in Skim from command line

I use this for Vim/GVim; however, this script was inspired by code in an example in the TeXniscope help file for making TeXniscope work with iTeXMac. See the TeXniscope documentation for information on how to build a script that will let iTeXMac call TeXniscope from the command-line (and even make use of PDFSync [CTAN, iTM]).

Script to open file in Skim from command line

UPDATE 4: I have updated the script to accept command line options. A -h option gives help text describing the new usage. The options can prevent Skim from being activated or opening the file. This may be useful when trying to get Skim to update in the background.

UPDATE 3: I have updated the script to check for whether or not files exist, try to guess the right files if they don't, and bail if it fails. It also has support for PS and DVI files. Also fixed a problem with symlinked files.

UPDATE 2: I have generated a more mature version of this script that also has the ability to position Skim's PDF view at a position corresponding to a line of your TeX source (provided you built the PDF with pdfsync).

UPDATE 1: As discussed in this feature request and this Wiki entry, in iTeXMac, you can also try
Skim.app/Contents/SharedSupport/displayline %line "%pdffile" "%texfile"
which lets you make use of Skim's PDFSync support. The Wiki page includes instructions on using this in Emacs and TextMate as well. If you just want to open the file, you might try
Skim.app/Contents/SharedSupport/displayline 1 "%pdffile"
but this might break if the TEX file isn't available (so maybe you should still use the AppleScript below).

Here's a script to open a (PDF or PostScript) file in Skim from the command line:
#!/bin/sh

[ "`echo $*|cut -c 1`" == "/" ] || filename_prefix="`pwd`"

exec osascript \
-e "tell application \"Skim\"" \
-e "activate" \
-e "open ((POSIX file \"$filename_prefix/$*\") as string)" \
-e "revert front document" \
-e "end tell";
or, alternatively,
#!/bin/bash

arguments="$*"
[ "${arguments:0:1}" == "/" ] || filename_prefix="$PWD"

exec osascript \
-e "tell application \"Skim\"" \
-e "activate" \
-e "open ((POSIX file \"$filename_prefix/$*\") as string)" \
-e "revert front document" \
-e "end tell";

Create an executable script called skim (e.g., /usr/local/bin/skim that is chmod'd 755) and try skim FILENAME where FILENAME is the name of the PDF or PostScript file that you want to open (be sure to include the file extension).

This allows you to use Skim as a LaTeX document viewer in the VIM-LaTeX suite for Vim.

NOTE ABOUT revert: The line with revert in it requires Skim version 0.5 or higher. If you don't have that version of Skim (or you don't care about refreshing the document), then delete that line.

See also: Script to open file in TeXniscope from command line

I use this for Vim/GVim; however, this script was inspired by code in an example in the TeXniscope help file for making TeXniscope work with iTeXMac. See the TeXniscope documentation for information on how to build a script that will let iTeXMac call TeXniscope from the command-line (and even make use of PDFSync [CTAN, iTM]). It should be easy to modify the script they give there to call Skim instead of TeXniscope; use my script here as an example. Note that Skim's AppleScript also supports all of the goto line stuff of TeXniscope. However, the syntax is different; see the Skim AppleScript dictionary for more information.

Thursday, June 28, 2007

Preamble for Journal of Mathematical Biology

Update 5: The updated svglov2.clo and svglov3.clo are not needed if the preamble is used below (i.e., if the \RequirePackage{fix-cm} line is added before the documentclass line.

Update 4: See the section that redefines \autoref. Changed definition to support starred commands that are unlinked.

Update 3: See the section starting with the comment "%% Level 1 Subsections". It forces subsections to show up like sections in the PDF bookmarks; this is a (strange) JMB convention. In the comment I make some suggestions for improvements.

Update 2: See the small commented section "%%%% Table Support". If the LaTeX code is uncommented there, there is no need for the \noalign{\smallskip} stuff around \hline horizontal table rules. It uses the tabls package to do this.

Update 1: I've mirrored this content on my web page.

I'd like to combine some of the previous posts. I've been trying to fix and modernize some of the Springer LaTeX support files for the Journal of Mathematical Biology (JMB). I've come up with these...

  • svglov2.clo - document class option for svjour2.cls. I used fix-cm to get rid of some of the warnings about not being able to scale the Computer Modern fonts. This is not needed if the preamble below is used (i.e., with the fix-cm line before the documentclass line).

  • svglov3.clo - document class option for svjour3.cls. I used fix-cm to get rid of some of the warnings about not being able to scale the Computer Modern fonts. This is not needed if the preamble below is used (i.e., with the fix-cm line before the documentclass line).

  • spmpsci.bst - BiBTeX bibliography style file for JMB. The original version of this did not reverse the first and last name of the editors as required; I fixed that.

  • spmpscinat.bst - natbib compatible BiBTeX bibliography style file for JMB. Be sure to include natbib with numbers and sort&compress options.
I recommend using a preamble like this one...
%%%% Journal of Mathematical Biology (JMB) setup

% Allow Computer Modern fonts to be scaled (must be before svjour3)
\RequirePackage{fix-cm}

% Use running heads
\documentclass[runningheads]{svjour3}

% The journal's name
\journalname{Journal of Mathematical Biology}

% use Times fonts
\usepackage{mathptmx}

% flush right qed marks (Halmos square),
% e.g., at end of proof
\smartqed

% Use natbib for \citet, \citep, etc.
% (JMB: numbered citations that are sorted
% and compressed)
\usepackage[numbers,sort&compress]{natbib}
%\bibliographystyle{spmpsci}
\bibliographystyle{spmpscinat}

%%%% Some useful packages

% Allow for smarter labeling of enumerations
% and itemizations (consider using enumitem instead)
\usepackage{paralist}

% Provides \labelformat, which changes how \ref
% references look
\usepackage{varioref}

% Mathematical symbols, etc.
\usepackage{amssymb,amsfonts,amsmath}

%%%% Table Support

% UNCOMMENT THE FOLLOWING LINES TO GET RID OF
% \noalign{\smallskip} STUFF AROUND \hline's IN
% TABLES
%
% % The following three lines remove the need for
% % the \noalign{\smallskip} around the \hline's
% % in the _Journal of Mathematical Biology_ LaTeX
% % template
% \usepackage{tabls}
% \addtolength\extrarulesep{\smallskipamount}
% \addtolength\extrarulesep{1pt}

%%%% Graphics and Figure Support

% Use subfig for subfigures
\usepackage[nearskip=-3pt,captionskip=4pt,
listofformat=subsimple,
labelformat=simple]{subfig}

% Make sure subfigures have parentheses around
% them everywhere
\renewcommand\thesubfigure{(\alph{subfigure})}

% Use graphicx for including graphics
\usepackage{graphicx}

% When picture environments are used, use
% pict2e for better resolution and flexibility
\usepackage{pict2e}

%%%% Hyperlink and Autoreference Support

%% Level 1 Subsections
%
% JMB does this weird thing where all
% subsection-level PDF bookmarks are displayed as
% section-level bookmarks. Strangely, they do
% *NOT* turn on the ``bookmarksnumbered'' hyperref
% option. I think their articles would be MUCH more
% readable with all level-1 bookmarks if they were
% prefixed by their section number. I'm sure they'd
% argue that since the sections are linked within
% the document, this is not needed.
%
% (note: another option is to set tocdepth=2 and turn
% on the ``bookmarksopen'' hyperref option)
%
% Anyway, the following redefines \addcontents line
% to setup the bookmarks like JMB articles. Must do
% this after hyperref because it redefines
% \addcontentsline. Therefore, just use an
% AtBeginDocument.
%
\usepackage{ifthen}
\AtBeginDocument{%
\let\orgaddcontentsline\addcontentsline
\renewcommand{\addcontentsline}[3]{
\ifthenelse{\equal{#1}{toc}}
{\ifthenelse{\equal{#2}{subsection}}
{\orgaddcontentsline{#1}{section}{#3}}
{\orgaddcontentsline{#1}{#2}{#3}}}
{\orgaddcontentsline{#1}{#2}{#3}}}}

% Include hyperref for link support
% Include hyperref for link support
%\usepackage[dvipdfmx, % If need dvipdfmx
%\usepackage[dvips, % If need dvips
\usepackage[% % Fine in most cases
pdfpagelabels,hypertexnames=true,
plainpages=false,
naturalnames=false]{hyperref}

% Configure the hyperlink color
\usepackage{color}
\definecolor{darkblue}{rgb}{0,0.1,0.5}
\hypersetup{colorlinks,
linkcolor=darkblue,
anchorcolor=darkblue,
citecolor=darkblue}

% In the future, it would be nice to use the package
%
% cleveref
%
% Right now, it breaks svjour3 and svjour2, so we just
% have to use autoref and labelformat :(.

% Make sure \autoref puts parentheses around
% equations and enumeration items (similar to \eqref)
% NOTE: This allows us to use \ref instead of \eqref
\labelformat{equation}{\textup{(#1)}}
\labelformat{enumi}{\textup{(#1)}}

% Make sure equations are numbered by section
\numberwithin{equation}{section}

%% We need to redefine \autoref. We should use
%% abbreviations inside the sentence and full names
%% at the beginning of sentences. Additionally,
%% need to handle the plural cases.

% \Autoref is for the beginning of the sentence
\let\orgautoref\autoref
\providecommand{\Autoref}
{\def\equationautorefname{Equation}%
\def\figureautorefname{Figure}%
\def\subfigureautorefname{Figure}%
\def\sectionautorefname{Section}%
\def\subsectionautorefname{Section}%
\def\subsubsectionautorefname{Section}%
\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\sectionautorefname{Sections}%
\def\subsectionautorefname{Sections}%
\def\subsubsectionautorefname{Sections}%
\def\Itemautorefname{Items}%
\def\tableautorefname{Tables}%
\orgautoref}

% \autoref is used inside a sentence
% (this is a renew of the standard)
\renewcommand{\autoref}
{\def\equationautorefname{Eq.}%
\def\figureautorefname{Fig.}%
\def\subfigureautorefname{Fig.}%
\def\sectionautorefname{Sect.}%
\def\subsectionautorefname{Sect.}%
\def\subsubsectionautorefname{Sect.}%
\def\Itemautorefname{item}%
\def\tableautorefname{Table}%
\orgautoref}

% \autorefs is plural for inside a sentence
\providecommand{\autorefs}
{\def\equationautorefname{Eqs.}%
\def\figureautorefname{Figs.}%
\def\subfigureautorefname{Figs.}%
\def\sectionautorefname{Sects.}%
\def\subsectionautorefname{Sects.}%
\def\subsubsectionautorefname{Sects.}%
\def\Itemautorefname{items}%
\def\tableautorefname{Tables}%
\orgautoref}

This lets you do cool things like... (hyperlinks depicted in blue)

\ref{eq:1} produces linked "(1)"
\ref*{eq:1} produces unlinked "(1)"
\autoref{eq:1} produces linked "Eq. (1)"
\autoref*{eq:1} produces unlinked "Eq. (1)"
\Autoref{eq:1} produces linked "Equation (1)"
\autoref{sec:2} produces linked "Sect. 2.1"
\Autoref{sec:2} produces linked "Section 2.1"
\Autorefs{sec:1} and \ref{sec:2} produces linked "Sections 1 and 2.1"
\autorefs{sec:1} and \ref{sec:2} produces linked "Sects. 1 and 2.1"
\autoref{item:1} produces linked "item (i)"
\autorefs{item:1} and \ref{item:2} produces linked "items (i) and (ii)"
\citep{SK86} produces linked "[61]"
\citep[p.~41]{SK86} produces linked "[61, p. 41]"
\citep{Cha76,SK86} produces linked "[14, 61]"
\citep[e.g.,][]{SK86,Cha76} produces linked "[e.g., 14, 61]"
\citeauthor{SK86} produces linked "Stephens and Krebs"
\citet{SK86} produces linked "Stephens and Krebs [61]"

Friday, June 15, 2007

Thesis, Defense, and Source Available

I packaged it all up, documented it, and made it available on-line. Hopefully having a whole LaTeX thesis source on-line will be helpful to someone. This thesis has multiple indices (people and topic), glossaries, and all sorts of PDF hyperlinking and referencing. It uses packages like authorindex, hyperref, index, and natbib. I hope it serves as a good example for putting together a digital book.

Archives are also stored in the source directory. The defense presentation is best viewed in latest Adobe Acrobat as it makes use of a number of very modern PDF features. The presentation is built with LaTeX using powerdot.

The source directory also includes a modified osudissert96-mods.sty and the standard osudissert96.cls file, which is part of the osudissert96 (info, source) package. The modifications:

  • Force title to uppercase to match updated submission rules.

  • Additional hyperref support: If phantomsection defined, will add phantomsection in dedication page.

  • Additional hyperref support: alphanumeric page numbers on title page to prevent page name conflicts.
Just so everyone knows, the two acceptable graduate unit names for the OSU ECE department are

  • Graduate Program in Electrical & Computer Engineering

  • Electrical & Computer Engineering Graduate Program