In
this article the author discusses the use of \# to put correct spacings after full stops that are not at the end of a sentence e.g. Mr. i.e. etc.
The macro suggested
\newcommand\etc{etc\#ifnextchar.{}{.\#}}
is not quite perfect since in the case (\etc more text) it produces (etc.more text).
I have seen a lot of authors who have made their own versions of the \etc macro, mostly variations on etc.\.
What macros for \etc, \ie, \etal, \eg produce the nicest results in the most situations?
Is this something too personal in taste to be solved in general?
Earlier I used macros for "et al.", etc., but nowadays I would discourage people from defining that kind of macros.
One problem is what you already observed: it's surprisingly tricky to get the definitions right so that they handle all special cases correctly (including the interactions with other packages – e.g., those that re-define the "\cite" command and tweak spacing before references).
But more importantly, even if you have a bunch of macros that suit your needs and you know how to use them, your co-authors are likely to be confused with exactly how to use your macros correctly in various special cases.
Hence I'd recommend that you avoid macros for trivial things such as "et al." and simply spell out everything by using standard Latex markup. After all, most cases don't need any special handling ("e.g." is often followed by a comma; "et al." is often followed by "~\cite", etc.), and whenever special handling is needed, all Latex users should know how to use commands such as "\ " and "\#".
In CVPR's style package, it is defined as:
\usepackage{xspace}
% Add a period to the end of an abbreviation unless there's one
% already, then \xspace.
\makeatletter
\DeclareRobustCommand\onedot{\futurelet\#let#token\#onedot}
\def\#onedot{\ifx\#let#token.\else.\null\fi\xspace}
\def\eg{\emph{e.g}\onedot} \def\Eg{\emph{E.g}\onedot}
\def\ie{\emph{i.e}\onedot} \def\Ie{\emph{I.e}\onedot}
\def\cf{\emph{c.f}\onedot} \def\Cf{\emph{C.f}\onedot}
\def\etc{\emph{etc}\onedot} \def\vs{\emph{vs}\onedot}
\def\wrt{w.r.t\onedot} \def\dof{d.o.f\onedot}
\def\etal{\emph{et al}\onedot}
\makeatother
Have you tried using the xspace package?
Example macro:
\def\etc{etc.\#\xspace}
Some tests:
Cat, dog, \etc. And so on. \\
Cat, dog, \etc! And so on. \\
Cat, dog, \etc, and so on. \\
Cat (dog, \etc). And so on. \\
Produces:
From the documentation:
The xspace package provides a single
command that looks at what comes after
it in the command stream, and decides
whether to insert a space to replace
one "eaten" by the TeX command
decoder.
A technical challenge! We can avoid the problem of letters after spaces by looking at the catcode of the next character and seeing whether or not it is a letter; this can be done with the Latex3's expl3 macro \peek_charcode:NTF (my first expl3 code!):
\documentclass{article}
\usepackage{expl3}
\ExplSyntaxOn
\newcommand\latinabbrev[1]{
\peek_meaning:NTF . {% Same as \#ifnextchar
#1\#}%
{ \peek_catcode:NTF a {% Check whether next char has same catcode as \'a, i.e., is a letter
#1.\# }%
{#1.\#}}}
\ExplSyntaxOff
%Omit final dot from each def.
\def\eg{\latinabbrev{e.g}}
\def\etal{\latinabbrev{et al}}
\def\etc{\latinabbrev{etc}}
\def\ie{\latinabbrev{i.e}}
\begin{document}
Maybe a list, \eg, a, b, c, and d. Which is to say (\ie) a, b, \etc. Consider Knuth, \cf The TeXbook.
\end{document}
Jukka's advice I think is sound, though: I'd say the problem Will works around with his \etc macro we should see as a bug in Tex's implementation of double spacing (Will Robertson should ask for his cheque): if you know the bug is there, you can workaround it directly by putting in \# in cases such as ".)", or you can have tricky code that means you don't have to think in this case, but you have added complexity to the way you typeset which is not going to work for you with the next unexpected glitch, one you probably have introduced yourself.
Postscript Previous version fixed, thanks to Joseph Wright noticing a stupid error at tex.stackexchange.com.
All LaTeX commands eliminate space after them. If you want a space, you need to escape it:
\etc\ and more
This is necessary, because you need to be clear where the command name ends. \etcno space cannot be correctly interpreted.
Related
I have a question concerning LaTeX. I have the symbol 99mTc which I need to have: up-elevated(99m) and Tc at the main line of text. How can I do it?
Thank you
P.S. you can see here at the first line how I need it to be: http://en.wikipedia.org/wiki/Technetium-99m
Use a chemical typesetting package like mhchem. Additionally, if you're going to use this symbol often, define a macro to re-use when you need it - it promotes consistency:
\documentclass{article}
\usepackage[version=3]{mhchem}
\newcommand{\Technetium}{\ce{^{99m}Tc}}
\begin{document}
\textbf{Technetium-99m} is a metastable nuclear isomer of technetium-99, symbolized as
\Technetium, that is used in tens of millions of medical diagnostic procedures annually,
making it the most commonly used medical radioisotope.
\end{document}
Note that this no-argument macro should be used as \Technetium{} whenever it should be followed by a space, as TeX gobble spaces following a control sequence.
I'm writing my thesis/dissertation and since its an on-going work I don't always have the actual images ready for the figures I put into my document, but for various reasons want to automatically have it substitute a dummy figure in place when the included graphics file doesn't exist. E.g. I can do something like \includegraphics[width=8cm]{\chapdir/figures/fluxcapacitor} (where \chapdir is a macro for my 'current' chapter directory, e.g. \def\chapdir{./ch_timetravel} and if there's no ./ch_timetravel/figures/fluxcapacitor.jpg it'll insert ./commands/dummy.jpg instead.
I've structured my macros (perhaps naïvely?) so that I have a macro (\figFileOrDummy) that determines the appropriate file to include by checking if the argument provided to it exists, so that I can call \includegraphics[properties]{\figFileOrDummy{\chapdir/figures/fluxcapacitor}}. Except I'm getting various errors depending on how I try to call this, which seem to suggest that I'm approaching the problem in a fundamentally flawed way as far as 'good LaTeX programming' goes.
Here's the macro to check if the file exists (and 'return' either filename or the dummy filename):
\newcommand{\figFileOrDummy}[1]{%
% Figure base name (no extension) to be used if the file exists
\def\fodname{#1}%
\def\dummyfig{commands/dummy}%
% Check if output is PS (.EPS) or PDF (.JPG/.PDF/.PNG/...) figures
\ifx\pdfoutput\undefined%
% EPS figures only
\IfFileExists{\fodname.eps}{}{\def\fodname{\dummyfig}}%
\else%
% Check existence of various extensions: PDF, TIF, TIFF, JPG, JPEG, PNG, MPS
\def\figtest{0}% flag below compared to this value
\IfFileExists{\fodname.pdf}{\def\figfilenamefound{1}}{\def\figfilenamefound{0}}%
\IfFileExists{\fodname.jpg}{\def\figfilenamefound{1}}{}%
\IfFileExists{\fodname.png}{\def\figfilenamefound{1}}{}%
% and so on...
% If no files found matching the filename (flag is 0) then use the dummy figure
\ifx\figfilenamefound\figtest%
\def\fodname{\dummyfig}%
\fi%
\fi%
% 'return' the filename
\fodname%
}%
Alternatively, here's a much simpler version which seems to have similar problems:
\newcommand{\figFileOrDummy}[1]{%
\def\dummyfig{commands/dummy}%
\dummyfig%
}
The \def commands seems to be processed after the expansion of the macro they're trying to define, so it ends up being \def {commands/dummy}... (note the space after \def) and obviously complains.
Also it seems to treat the literal contents of the macro as the filename for \includegraphics, rather than resolving/expanding it first, so complains that the file '\def {commands/dummy}... .png' doesn't exist..
I've tried also doing something like
\edef\figfilename{\figFileOrDummy{\chapdir/figures/fluxcapacitor}} to try to force it to make \figfilename hold just the value rather than the full macro, but I get an Undefined control sequence error complaining the variables I'm trying to \def in the \figFileOrDummy macro are undefined.
So my question is either
How do I make this macro expand properly?; or
If this is the wrong way of structuring my macros, how should I actually structure such a macro, in order to be able to insert dummy/real figures automatically?; or
Is there a package that already handles this type of thing nicely that I've overlooked?
I feel like I'm missing something pretty fundamental here...
I think the point is that \expandafter is only interested in its arguments as a string representing a filename, so doesn't evaluate it — macro languages are lazy! Try \expandafter {\includegraphics[width=8cm]}{\chapdir/figures/fluxcapacitor}.
Two points of style:
You don't need to put % at the end of a line to stop spurious whitespace if the line ends with a control sequence: the control sequence gobbles up all following whitespace, including the end of line. This makes the code much more readable, to my taste. Note that, in particular, to Tex's "mouth" both \def\newcs{abc} and \def \newcs {abc} are identical: they are exactly the same sequence of tokens.
I dropped the code around \figtest: you get better error reporting -always at a premium with Tex- if you use either \newif primitive (create new test with \newif\figexists, set/reset with \figexiststrue, \figexistsfalse, and test with \iffigexists...) or the Latex ifthenelse package (to keep with orthodoxy).
Cleaned-up code
I first thought the problem lay elsewhere, so wrote something prettier:
\def\dummypath{commands/dummy}%
\ifx\pdfoutput\undefined
\def\figFileOrDummy#1{\IfFileExists
{#1.eps}{#1}\dummypath}
\else
\def\figFileOrDummy#1{\IfFileExists
{#1.pdf}{#1}{\IfFileExists
{#1.jpg}{#1}{\IfFileExists
{#1.png}{#1}\dummypath}}} %or have more graphics types, if you like.
\fi
Alright, so I've found a possible answer to #2, by restructuring the way the macros work (and sort of using some suggestions from Charles Stewart's answer — I'll admit I don't like the 'look' of what seems to be widely considered good LaTeX code, I'm perhaps too ingrained in my C/C++ ways to be a real LaTeX programmer).
Anyway, my answer...
Instead of trying to produce the file name in a macro to pass to the \includegraphics macro, make a macro that wraps \includegraphics and passes it the real or dummy file name. This seems to avoid passing (as an argument) a long script/macro, though I don't see any good reason why it should have to be written this way. But it does work...
% Dummy figure file
\def\dummyfigure{commands/dummy}%
% Includegraphics wrapper macro to include either dummy or real figure
\ifx\pdfoutput\undefined
\newcommand{\incgfx}[2]{%
\def\testfile{\chapdir/fig/#2}%
\IfFileExists{\testfile.eps}%
{\includegraphics[#1]{\testfile}}% test file found
{\includegraphics[#1]{\dummyfigure}}% test file not found
}
\else
\newcommand{\incgfx}[2]{%
\def\figfilename{\dummyfigure}
\def\testfile{\chapdir/fig/#2}
\IfFileExists{\testfile.jpg}{\def\figfilename{\testfile}}{}
\IfFileExists{\testfile.png}{\def\figfilename{\testfile}}{}
\IfFileExists{\testfile.pdf}{\def\figfilename{\testfile}}{}
\IfFileExists{\testfile.jpeg}{\def\figfilename{\testfile}}{}
\IfFileExists{\testfile.tif}{\def\figfilename{\testfile}}{}
\IfFileExists{\testfile.tiff}{\def\figfilename{\testfile}}{}
\includegraphics[#1]{\figfilename}
}
\fi
This allows one to use it as intended:
\begin{figure}
\begin{center}
\incgfx{height=3cm}{\chapdir/fig/fluxcapacitor}
\caption{...}\label{fig:...}
\end{center}
\end{figure}
Again, I'd like to think there's a way to make the original idea work rather than having to make a wrapper for existing functions, but this will do for now...
Answer to #3: For this purpose, I find very useful the todonotes package. It does not provide the level of automation that your code is aiming to offer, but it has a very nice \missingfigure command that lets you put a dummy box for, you guess it, a missing figure.
I know one of LaTeX's bragging points is that it doesn't have this Microsoftish behavior. Nevertheless, it's sometimes useful.
LaTeX already adds an extra space after you type a (non-backslashed) period, so it should be possible to make it automatically capitalize the following letter as well.
Is there an obvious way to write a macro that does this, or is there a LaTeX package that does it already?
The following code solves the problem.
\let\period.
\catcode`\.\active
\def\uppercasesingleletter#1{\uppercase{#1}}
\def.{\period\afterassignment\periodx\let\next= }
\def \periodx{\ifcat\space\next \next\expandafter\uppercasesingleletter \else\expandafter\next\fi}
First. second.third. relax.relax. up
\let\period. save period
\catcode\.\active make all periods to be active symbol (like macro).
\def\uppercasesingleletter#1{\uppercase{#1}} defines macro \uppercasesingleletter to make automatically capitalize the following letter.
\def.{\period\afterassignment\periodx\let\next= } writes saved period and checkes the next symbol.
\def \periodx{\ifcat\space\next \next\expandafter\uppercasesingleletter \else\expandafter\next\fi} If the next letter is a space then \uppercasesingleletter is inserted.
ages ago there was discussion of this idea on comp.text.tex, and the general conclusion was you can't do it satisfactorily. satisfactory, in my book, involves not making characters active, but i can't see how that could work at all.
personally, i would want to make space active, and have it then look at \spacefactor and \MakeUppercase the following character if the factor is 3000.
something like
\catcode\ \active % latex already has a saved space character -- \space
\def {\ifhmode% \spacefactor is invalid
% (or something) in vertical mode
\ifnum\spacefactor<3000\else% note: with space active,
% even cs-ended lines need %-termination
\expandafter\gobbleandupper\fi}%
\def\gobbleandupper#1{\def\tempa{#1}\def\tempb{ }%
\ifx\tempa\tempb% can''t indent the code, either :-(
% here, we have another space
\expandafter\gobbleandupper% try again
\else\space% insert a "real" space to soak up the
% space factor
\expandafter\MakeUppercase\fi}%
this doesn't really do the job -- there are enough loose ends to knit a fairisle jumper. for example, given that we can't rely on \everypar in latex, how do you uppercase the first letter of a paragraph?
no ... however much it hurts (which is why i avoid unnecessary key operations) we need to type latex "properly" :-(
I decided to solve it in the following way:
Since I always compile the LaTeX code three times before i okular the result (to get pagination and references right), I decided to build the capitalization of sentences into that process.
Thus, I now have a shell script that calls my capitalization script (written in CRM114) first, then pdflatex three times, and then okular. This way, all the stuff happens as the result of a single command.
I am using LaTeX and I have a problem concerning string manipulation.
I want to have an operation applied to every character of a string, specifically
I want to replace every character "x" with "\discretionary{}{}{}x". I want to do
this because I have a long string (DNA) which I want to be able to separate at
any point without hyphenation.
Thus I would like to have a command called "myDNA" that will do this for me instead of
inserting manually \discretionary{}{}{} after every character.
Is this possible? I have looked around the web and there wasnt much helpful
information on this topic (at least not any I could understand) and I hoped
that you could help.
--edit
To clarify:
What I want to see in the finished document is something like this:
the dna sequence is CTAAAGAAAACAGGACGATTAGATGAGCTTGAGAAAGCCATCACCACTCA
AATACTAAATGTGTTACCATACCAAGCACTTGCTCTGAAATTTGGGGACTGAGTACACCAAATACGATAG
ATCAGTGGGATACAACAGGCCTTTACAGCTTCTCTGAACAAACCAGGTCTCTTGATGGTCGTCTCCAGGT
ATCCCATCGAAAAGGATTGCCACATGTTATATATTGCCGATTATGGCGCTGGCCTGATCTTCACAGTCAT
CATGAACTCAAGGCAATTGAAAACTGCGAATATGCTTTTAATCTTAAAAAGGATGAAGTATGTGTAAACC
CTTACCACTATCAGAGAGTTGAGACACCAGTTTTGCCTCCAGTATTAGTGCCCCGACACACCGAGATCCT
AACAGAACTTCCGCCTCTGGATGACTATACTCACTCCATTCCAGAAAACACTAACTTCCCAGCAGGAATT
just plain linebreaks, without any hyphens. The DNA sequence will be one
long string without any spaces or anything but it can break at any point.
This is why my idea was to inesert a "\discretionary{}{}{}" after every
character, so that it can break at any point without inserting any hyphens.
This takes a string as an argument and calls \discretionary{}{}{} after each character. The input string stops at the first dollar sign, so you should not use that.
\def\hyphenateWholeString #1{\xHyphenate#1$\wholeString}
\def\xHyphenate#1#2\wholeString {\if#1$%
\else\say{#1}\discretionary{}{}{}%
\takeTheRest#2\ofTheString
\fi}
\def\takeTheRest#1\ofTheString\fi
{\fi \xHyphenate#1\wholeString}
\def\say#1{#1}
You’d call it like \hyphenateWholeString{CTAAAGAAAACAGGACG}.
Instead of \discretionary{}{}{} you can also try \hspace{0pt}, if you like that more (and are in a latex environment). In order to align the right margin, I think you’d need to do some more fine tuning (but see below). The effect is of course minimised by using a font of fixed width.
Revision:
\def\hyphenateWholeString #1{\xHyphenate#1$\wholeString\unskip}
\def\xHyphenate#1#2\wholeString {\if#1$%
\else\transform{#1}%
\takeTheRest#2\ofTheString\fi}
\def\takeTheRest#1\ofTheString\fi
{\fi \xHyphenate#1\wholeString}
\def\transform#1{#1\hskip 0pt plus 1pt}
Steve’s suggestion of using \hskip sounds like a very good idea to me, so I made a few corrections. Note that I’ve renamed the \say macro and made it more useful in that it now actually does the transformation. (However, if you remove the \hskip from \transform, you’ll also need to remove the \unskip in the main macro definition.
Edit:
There is also the seqsplit package which seems to be made for printing DNA data or long numbers. They also bring a few options for nicer output, so maybe that is what you’re looking for…
Debilski's post is definitely a solid way to do it, although the \say is not necessary. Here's a shorter way that makes use of some LaTeX internal shortcuts (\#gobble and \#ifnextchar):
\makeatletter
\def\hyphenatestring#1{\xHyphen#te#1$\unskip}
\def\xHyphen#te{\#ifnextchar${\#gobble}{\sw#p{\hskip 0pt plus 1pt\xHyphen#te}}}
\def\sw#p#1#2{#2#1}
\makeatother
Note the use of \hskip 0pt plus 1pt instead of \discretionary - when I tried your example I ended up with a ragged margin because there's no stretchability. The \hskip adds some stretchable glue in between each character (and the \unskip afterwards cancels the extra one we added). Also note the LaTeX style convention that "end user" macros are all lowercase, while internal macros have an # in them somewhere so that users don't accidentally call them.
If you want to figure out how this works, \#gobble just eats whatever's in front of it (in this case the $, since that branch is only run when a $ is the next char). The main point is that \sw#p is only given one argument in the "else" branch, so it swaps that argument with the next char (that isn't a $). We could just as well have written \def\hyphenate#next#1{#1\hskip...\xHyphen#te} and put that with no args in the "else" branch, but (in my opinion) \sw#p is more general (and I'm surprised it's not in standard LaTeX already).
There is a contrib package on CTAN that deals with typesetting DNA sequences. It does a little more than just line-breaking, for example, it also supports colouring. I'm not sure if it is possible to get the output you are after though, and I have no experience in the DNA-sequence-typesetting area, but is one long string the most readable representation?
Assuming your string is the same, in your preamble, use the \newcommand{}{}. Like this:
\newcommand{\myDNA}{blah blah blah}
if that doesn't satisfy your requirements, I suggest:
2. Break the strings down to the smallest portion, then use the \newcommand and then call the new commands in sequence: \myDNA1 \myDNA2.
If that still doesn't work, you might want to look at writing a perl script to satisfy your string replacement needs.
I'm looking for a way to do a substring replace on a string in LaTeX. What I'd like to do is build a command that I can call like this:
\replace{File,New}
and that would generate something like
\textbf{File}$\rightarrow$\textbf{New}
This is a simple example, but I'd like to be able to put formatting/structure in a single command rather than everywhere in the document. I know that I could build several commands that take increasing numbers of parameters, but I'm hoping that there is an easier way.
Edit for clarification
I'm looking for an equivalent of
string.replace(",", "$\rightarrow$)
something that can take an arbitrary string, and replace a substring with another substring.
So I could call the command with \replace{File}, \replace{File,New}, \replace{File,Options,User}, etc., wrap the words with bold formatting, and replace any commas with the right arrow command. Even if the "wrapping with bold" bit is too difficult (as I think it might be), just the replace part would be helpful.
The general case is rather more tricky (when you're not using commas as separators), but the example you gave can be coded without too much trouble with some knowledge of the LaTeX internals.
\documentclass[12pt]{article}
\makeatletter
\newcommand\formatnice[1]{%
\let\#formatsep\#formatsepinit
\#for\#ii:=#1\do{%
\#formatsep
\formatentry{\#ii}%
}%
}
\def\#formatsepinit{\let\#formatsep\formatsep}
\makeatother
\newcommand\formatsep{,}
\newcommand\formatentry[1]{#1}
\begin{document}
\formatnice{abc,def}
\renewcommand\formatsep{\,$\rightarrow$\,}
\renewcommand\formatentry[1]{\textbf{#1}}
\formatnice{abc,def}
\end{document}
it looks like your "spaces" problem is from a bug in that package. If you surround the "\GetTokens" macro with, say, commas, then you'll see that the extra space is inserted by that macro.
Yes there are bugs in tokenizer package. As I said on my blog, the bugfix is to use the following correcting code instead of just "\usepackage[trim]{tokenizer}":
\usepackage[trim]{tokenizer}
\def\SH#GetTokens#1,#2\#empty{%
\def\SH#token{#1}%
\ifx\SH#trimtokens\SH#true% strip spaces if requested
\TrimSpaces\SH#token%
\fi%
\SH#DefineCommand{\SH#FirstArgName}{\SH#token}%
\SH#DefineCommand{\SH#SecondArgName}{#2}%
}
\def\SH#CheckTokenSep#1,#2\#empty{%
\def\SH#CTSArgTwo{#2}%
\ifx\SH#CTSArgTwo\#empty%
\edef\SH#TokenValid{\SH#false}%
\else%
\edef\SH#TokenValid{\SH#true}%
\fi%
}
I will report this bugfix to the developer Sascha Herpers
Try the xstring package:
\usepackage{xstring}
[…]
\StrSubstitute{File,New}{,}{\(\rightarrow\)}
There's a LaTeX package called tokenizer which may help you to do what you want.
Here's a hack (but pure LaTeX, no internals) which gets close to what I think you want, but with some extraneous spaces I haven't quite been able to fix. Perhaps Will Robertson can advise further? Unlike his slightly more polished answer, I haven't parameterised the bits and pieces, Here goes:
\usepackage{forloop}
\usepackage[trim]{tokenizer}
...
\newcounter{rrCount}
\newcommand{\replace}[1]{%
\GetTokens{rrFirst}{rrRest}{#1,}%
\textbf{\rrFirst}%
\forloop{rrCount}{0}{\value{rrCount} < 100}{%
\ifthenelse{\equal{\rrRest}{}}{%
\setcounter{rrCount}{101}%
}{%
\GetTokens{rrFirst}{rrRest}{\rrRest}%
$\rightarrow$\textbf{\rrFirst}%
}%
}%
}%
% -----------------------------------------------------------------
\replace{a1}\\
\replace{a2,b2}\\
\replace{a3,b3,c3}\\
OK, I withdraw this answer. Thanks for clarifying the question.
I suspect this may not be what you want, but here goes anyway:
\newcommand{\replace}[2]{\textbf{#1}$\rightarrow$\textbf{#2}}
\replace{File}{New}
If this isn't what you're looking for, could you clarify the question, please?