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?
Related
I always like my figures to be placed in between text as opposed to the top or bottom of the page. I also like to talk about the figure before it is shown. So I am trying to have something like this:
By looking at Figure~\ref{fig:VCO} you can see that blah blah blah.
\begin{figure}[h]
\caption{VCO test circuit}\label{fig:VCO}
\begin{center}
\includegraphics[width=0.9\columnwidth]{figures/VCO_circuit.eps}
\end{center}
\end{figure}
This doesn't seem to work because it I guess it is referencing something that hasn't occurred yet? Does anyone have some simple solution? I am still very new to LaTeX.
Generally LaTeX needs at least two passes to resolve all its references, the first time to write them to an auxiliary file and the second time to put them into the final ps/pdf/dvi file. So it does not matter where the reference is.
A third pass will be needed, for example, if your document has a long table-of-contents which will screw up page numbers.
It failed the first time because labeling and referencing are a two-pass process. The first time you processed your latex, all the labels were being indexed so the ref failed. The second time around, since the labels had been indexed the ref knew what it was actually referencing.
I would add that latexmk (link) has proven invaluable to me over the years. This is a LaTeX "build" script written in Perl that is designed to compile .tex source files the right number of times. It parses the output from the latex command and performs dependency checking to ensure that the output document is kept up-to-date with the minimum number of passes. It can also deal with BibTeX bibliography files. Generally speaking, I invoke latexmk from either an Ant or GNU Make makefile and treat it just like I'm compiling C++ code, for example.
I had same problem and I found this solution:
\graphicspath{{images/}}
\DeclareGraphicsExtensions{.jpg}
\makeatletter
\newenvironment{tablehere}
{\def\#captype{table}}
{}
\newenvironment{figurehere}
{\def\#captype{figure}}
{}
\makeatother
\begin{figurehere}
\includegraphics[height=5cm]{2-14aGa-Sur.jpg}
\caption{Hliněná destička s mapou severu Mezopotámie}
\label{fig:Ga-Sur}
\end{figurehere}
\graphicspath{{images/}} is there to declare your path to your pictures
\DeclareGraphicsExtensions{.jpg} is there for declare picture extension (multiple can be with comma (I think ;-))
\makeatletter
\newenvironment{tablehere}
{\def\#captype{table}}
{}
\newenvironment{figurehere}
{\def\#captype{figure}}
{}
\makeatother
is there for precise determination of position here
\begin{figurehere}
\includegraphics[height=5cm]{2-14aGa-Sur.jpg}
\caption{Hliněná destička s mapou severu Mezopotámie}
\label{fig:Ga-Sur}
\end{figurehere}
there is your picture with height specified and caption and label with it...
I hope it will help you ;-).
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.
It seems to be common practice, when writing mathematics, to add punctuation to displayed formulas.
Is there any trick to avoid putting the punctuation mark inside the formula?
I want to avoid
Consider the function
\[ \sin(x).\]
I'd rather have something like:
Consider the function
\[ \sin(x)\].
But of course the full stop is displayed below the formula.
Is there a clever way to separate formulas and punctuation in LaTeX?
\catcode`\#=11
\let\seveendformula\]
\def\]{\#ifnextchar.\PointAndEndFormula\seveendformula}
\def \PointAndEndFormula #1{.\seveendformula}
\catcode`\#=12
Add
More complex solution works with .,?!;: :
\catcode`\#=11
\def\addtopunct#1{\expandafter\let\csname punct#\meaning#1\endcsname\let}
\addtopunct{.} \addtopunct{,} \addtopunct{?}
\addtopunct{!} \addtopunct{;} \addtopunct{:}
\let\seveendformula\]
\def\PunctAndEndFormula #1{#1\seveendformula}
\def\]{\futurelet\punctlet\checkpunct#i}
\def\checkpunct#i{\expandafter\ifx\csname punct#\meaning\punctlet\endcsname\let
\expandafter\PunctAndEndFormula
\else \expandafter\seveendformula\fi}
\catcode`\#=12
There's also the issue of which font the punctuation should be in. You won't see a problem until you try a different math font such as Euler. Then commas and periods are clearly different in text mode and in math mode. I've written text-mode punctuation in displayed formulas as \mbox{,} or lazily as \mbox, just before $$.
You can load the breqn package (compatible with amsmath) and have this behaviour inbuilt with its dmath environment:
Consider the function
\begin{dmath}\sin(x)\end{dmath}.
Will output the same as \[\sin(x).\], i.e., as if the dot was inside the expression.
As a bonus, you'll also get automatic line-breaking in your math equation.
Putting the punctuation inside a display environment is the usual way. The problem is that when Latex processes the \], it ends the mathbox, so anything following will be part of a new vertical box.
You could try something like:
\hbox{\[My formula\]}.
This is not tested, and probably has spacing issues, but if you are interested in this kind of solution, I could try and get something working.
FWIW, you might be interested in https://mathoverflow.net/questions/6675/periods-and-commas-in-mathematical-writing
Maybe there is a package to do this, but I have not been able to find it. If it doesn't exist, I would appreciate ideas as to how to do ithis. Basically, I need something that would box characters. Something like this:
-------
| A| L|
- - - ...
| 2| 3|
-------
Knuth has something like this in TAOCP, when he discusses MIX's word... without the bottom part, though.
So, a character, and some other char or chars below. Any idea? (I'm foreseeing a tumbleweed)...
Thanks.
Sorry, but I have too little rep to leave a comment. So what you need is a box around each letter without disturbing the text flow? What about a
\framebox{x}?
I don't know enough about latex, but you should look into building your own Latex makro where this is done for each letter that you pass to your new command. Admittedly this is kind of brute force...
You can use \raisebox to fix the vertical height. See the example at the end of this discussion of boxes. Since you can put boxes inside boxes, I think something like this is the answer (gives me a something that looks like your example).
Some text.
\framebox[1.1\width][s]{
\parbox[b]{7.2ex}{
\raisebox{2.0ex}{
\framebox[1.6\width][s]{A}
\framebox[1.6\width][s]{L}
}
\raisebox{0ex}{
\framebox[1.6\width][s]{2}
\framebox[1.6\width][s]{3}
}
}
}
Some more text.
Here's a basic loop that boxes each character (actually each token, so it won't work if there are macros within that take arguments):
\documentclass{article}
\makeatletter
\newcommand\eachboxed[1]{%
\#tfor\#ii:=#1\do{%
\fbox{\strut\#ii}%
}%
}
\makeatother
\begin{document}
\eachboxed{hello}
\end{document}
Not sure if this addresses your problem, however.
If tabular is not what you want, and I think crunchdog is right and it is what you want, perhaps fbox is. Both are well described in the usual sources of LaTeX information.
My instinct is to go with \framebox for single instances or small groups, and to use the tabular environment for more complicated situation (which would usually mean setting up a table).
I'm using LaTeX's "listings" package to format source code. Unfortunately I get curly quotes instead of straight quotes. Since the curly quotes don't always point in the right direction, it looks bad. How can I get straight quotes instead?
I'd prefer not to change or filter the source code itself. Filtering the code to properly change " to `` or '' would work, but this is easier done than said with multiple quotes on a line, or quotes spanning multiple lines. Or you could use symbol or a host of other things. But I'd really like to keep the source unchanged.
Example LaTeX:
\documentclass{article}
\usepackage{listings}
\begin{document}
\begin{lstlisting}
Fahrenheit=input("What is the Fahrenheit temperature?")
Celsius=(5.0/9.0)*(Fahrenheit-32)
print"The temperature is",Celsius,"degrees Celsius"
\end{lstlisting}
\end{document}
Example output (using Miktex on windows):
(Direct link to image of incorrect output)
I see in the documentation (which should have been distributed with the packge, but is available at http://www.ctan.org/tex-archive/macros/latex/contrib/listings/listings.pdf) for listings that there is a settable property called upquote to take care of this.
From the documentation:
upquote=⟨true|false⟩ false
determines whether the left and right quote are printed ‘’ or `'. This
key requires the textcomp package if true.
Do something like
\lstset{upquote=true}
before begining the list environment, or use
\begin{lstlisting}[upquote=true]
...
\end{lstlisting}
It is also possible that tis property is already set for you in the appropriate language
definition (see the docs again, big list of predefined languages on page 12).
Use:
\lstloadlanguages{<dialects you need>}
in the header. And then set the language using either of the above conventions for choosing options.
Have you considered using a monospaced (typewriter) font for the listing? The following example works:
\documentclass{article}
\usepackage{listings}
\lstset{basicstyle=\ttfamily} % <<< This line added
\begin{document}
\begin{lstlisting}
Fahrenheit=input("What is the Fahrenheit temperature?")
Celsius=(5.0/9.0)*(Fahrenheit-32)
print"The temperature is",Celsius,"degrees Celsius"
\end{lstlisting}
\end{document}
dmckee's answer above probably works. If you drop your last condition, i.e. you permit changes to the code, then there is a more generic solution, which I tend to use whenever (La)TeX renders a character somehow differently than I expect it to do is to use the \symbol command. I list it here because it can be useful in other situations as well:
\newcommand{\qq}{\symbol{34}} % 34 is the decimal ascii code for "
And then your example:
\begin{lstlisting}
...
print{\qq}The temperature is{\qq},Celsius,{\qq}degrees Celsius{\qq}
...
\end{lstlisting}
Note the curly braces which supposedly take listings back to LaTeX mode (see escapechars option of the package.)
Here is a solution
\usepackage[T1]{fontenc}
\usepackage{textcomp}
\usepackage{lmodern}
% in the listings package configuration, try:
literate={"}{\textquotedbl}1,
I had the same problem, using fontspec, and the solution was to not set \defaultfontfeatures{Mapping=tex-text}, but instead setting Mapping=tex-text specifically on only the main and sans font, and leaving the tt font to it's own devices. :)
Maybe it's because I installed listings early as a LaTeX user, but I'm surprised to learn that without the listings package the behaviour is any different.
My solution was similar to David Hanak's, but I used the symbols for double-quote as described in the LaTeX Cheat Sheet (http://stdout.org/~winston/latex)
\newcommand{\QQ}[1]{``#1''}