Limit scope of `newcommand` (without using `renewcommand`)? - latex

I'm combining a few latex documents and would like to limit the scope of my macros. I would like something like the following to work:
{
\input{macros1.tex}
\input{body1.tex}
}
{
\input{macros2.tex}
\input{body2.tex}
}
Where body1.tex uses macros defined via newcommand in macros1.tex, and macros2 and body2 are similar. However, macros2.tex might redefine commands found in macros1.tex. I thought that the braces might limit the scope of the macros, but it seems like that is not the case (I get "command already defined errors). Is there a way to solve this without replacing everything in macros2 with renewcommand?

Macros defined inside groups get local scope. However other things, such as length names or custom counters, still become global at least by default as in this answer. While it is possible via packages, author of those files would have to prepare code for this case.
If you uncomment lines (re)defining counters and names in this code below, you get error "<something> already exists"
\begin{filecontents*}[overwrite]{fileA.tex}
\newcommand\xxx{A}
\newlength\lenx
\setlength\lenx{15pt}
\newcounter{cx}
\setcounter{cx}{3}
\xxx, \the\lenx, \thecx
\end{filecontents*}
\begin{filecontents*}[overwrite]{fileB.tex}
\newcommand\xxx{B}
% \newlength\lenx % !!! Error
\setlength\lenx{30pt}
% \newcounter{cx} % !!! Error
\setcounter{cx}{6}
\xxx, \the\lenx, \thecx
\end{filecontents*}
\begin{filecontents*}[overwrite]{fileC.tex}
\newcommand\xxx{C}
% \newlength\lenx % !!! Error
\setlength\lenx{45pt}
% \newcounter{cx} 5 !!! Error
\setcounter{cx}{9}
\xxx, \the\lenx, \thecx
\end{filecontents*}
%%%
\documentclass{article}
\begin{document}
%%% Group A
\begingroup
\input{fileA.tex}
\endgroup
%%% Group B
\begingroup
\input{fileB.tex}
\endgroup
%%% Group C
\begingroup
\input{fileC.tex}
\endgroup
\end{document}

Related

Missing = inserted for \ifnum

I am using iopart template, and I do not know why get this error :
Missing = inserted for \ifnum. \begin
Missing number, treated as zero. \begin
I really appreciate any help
\documentclass[10pt]{iopart}
%\newcommand{\gguide}{{\it Preparing graphics for IOP Publishing journals}}
%Uncomment next line if AMS fonts required
%\usepackage{iopams}
\usepackage{graphicx}
\usepackage{booktabs}
\usepackage{nicefrac}
\expandafter\let\csname equation*\endcsname\relax
\expandafter\let\csname endequation*\endcsname\relax
\usepackage{amsmath,mathtools}
\DeclareMathOperator{\cotinv}{cot\,inverse}
\usepackage{amssymb}
\let\amscases\cases
\makeatletter
\def\cases{\#ifnextchar\bgroup\plaincases\amscases}
\def\plaincases#1{\begin{cases*}#1\end{cases*}}
\makeatother
\usepackage{multirow}
\usepackage{subfloat}
\usepackage{subfig}
\usepackage{gensymb}
%\newcommand{\acot}{\cot^{-1}}
\begin{document}
\title[]{}
\author{}
\author{}
\address{Department of}
\vspace{10pt}
\begin{indented}
\item[]November 2022
\end{indented}
\begin{abstract}
lll
\end{abstract}
%
% Uncomment for keywords
\vspace{2pc}
\noindent{\it Keywords}: electronics
%
% Uncomment for Submitted to journal title message
%\submitto{\JPA}
%
% Uncomment if a separate title page is required
\maketitle
%
% For two-column output uncomment the next line and choose [10pt] rather than [12pt] in the \documentclass declaration
\ioptwocol
%
\section{Introduction}\label{sec:introduction}
\end{document}```
I tried to recreate this instance. It first asked for the missing iopart.cls documentclass. I could get that from a GitHub repository belonging to Tianjin University named "etgroup". You can simply find it by searching "iop latex template" in Github. After the second compilation, it asked for a class dependency named iopart10.clo(it's available in the same repository).
Finally, after the third compilation, I could get a PDF output(Please see the figure attached).
Solution: If you are using a local LaTeX IDE/Studio, I recommend updating the packages you are using. Sometimes there are conflicts between some packages but they usually resolve quickly by releasing an update and you might see that there was nothing wrong with your commands.
Alternatively, you may try using an online LaTeX editor. They always have the last version of the most common packages and are equipped with multiple LaTeX render engine types.

Highlighting inline code snippets with the latex listings package

In my latex document I am using the listings package extensively.
I have many short inline code snippets that I like to give a proper highlighting in the text, and I am using the \lstMakeShortInline construct. Now I am interested in highlighting (background coloring) at least some of those code inserts for clarity, and was trying the following:
\lstMakeShortInline[language=Python,basicstyle=\ttfamily, backgroundcolor=\color{lightgray}]!
hoping that usage like:
some text some text !read_csv()! some more text
Will result in read_csv() appearing on a light-gray background, but it does not seem to work. The \ttfamily format works well in this situation.
(Thanks to samcarter_is_at_topanswers.xyz)
Here is a minimal example:
\documentclass{book}
\usepackage{listings}
\usepackage{color}
\lstset{language=Python}
\begin{document}
\lstMakeShortInline[language=Python, keywordstyle={\bfseries \color{blue}}, backgroundcolor=\color{yellow}]!
Here is the keyword !for!, showing that the \textbf{keywordstyle} setting takes effect, but the \textbf{backgroundcolor} setting does not.
\textbf{backgroundcolor} fails to take effect also when applied to a non-keyword !df.read_csv()! code snippet.
\end{document}
Is this possible with the listings package?
Thanks
Michael
Based on https://tex.stackexchange.com/a/357239/36296 you could do something like (make sure that ! does not occur in the normal text or use a different character):
% !TeX program = lualatex
\documentclass{article}
\usepackage{xcolor,listings,realboxes,fancyvrb} % fancyvrb for '\Verb' macro
\definecolor{mygray}{rgb}{0.8,0.8,0.8}
\lstset{basicstyle=\ttfamily, breaklines = true, backgroundcolor=\color{mygray}}
\usepackage[doublespacing]{setspace} % just for this example
\usepackage{luacode} % for 'luacode' environment
\begin{luacode}
-- the following code employs Lua's powerful "string.gsub" function
function color_lstinline ( s )
s = string.gsub ( s , "%b!!", "\\Colorbox{mygray}{%0}" )
return s
end
\end{luacode}
%% Define 2 LaTeX macros to switch operation of Lua function on and off
\newcommand{\ColorLstinlineOn}{\directlua{
luatexbase.add_to_callback ( "process_input_buffer" ,
color_lstinline, "color_lstinline" )}}
\newcommand{\ColorLstinlineOff}{\directlua{
luatexbase.remove_from_callback ( "process_input_buffer" ,
"color_lstinline" )}}
\AtBeginDocument{\ColorLstinlineOn} % Default: activate the Lua function
\lstMakeShortInline[language=Python, keywordstyle={\bfseries \color{blue}}, backgroundcolor=\color{yellow}]!
\begin{document}
!for!
\end{document}

Is there a way to extract initials from macro containing a name with latex?

I am writing a cv class, and want to extract the cvauthor initials. I have declare a macro in a .cls file that should contains the author name, after getting it, i want to split it according to a certain separator and gets the first letters of each sub-string. Here is what I did, but still getting an error message.
myclass.cls
\ProvidesClass{resumecv}[2020/09/12 CV class]
\LoadClass{article}
\NeedsTeXFormat{LaTeX2e}
\RequirePackage{xstring}
\RequirePackage{soul}
\RequirePackage[absolute, overlay]{textpos}
\sodef\myspace{}{.1em}{0.5em plus0.5em}{2em plus.1em minus.1em} % User-defined letter spacing
\newcommand{\cvauthor}[1]{\renewcommand{\cvauthor}{\textsc{\myspace{#1}}}}
\newcommand{\FirstInitial}{}
\newcommand{\SecondInitial}{}
\newcommand*{\ExtractInitials}[1]{%
\StrRemoveBraces{#1}[\FirstInit]%
\StrChar{\FirstInit}{1}[\FirstInit]
\renewcommand{\FirstInitial}{\FirstInit}
\StrBehind{#1}{ }[\second]%
\StrRemoveBraces{\second}[\SecondInit]%
\StrChar{\SecondInit}{1}[\SecondInitial]
}
\newcommand*{\makeskeleton}{
\begin{textblock}{20}(0,0)
\ifthenelse{\equal{\cvauthor}{}}{}{
%\Huge\textcolor{darkYellow}{\textbf{\cvauthor}}
% \renewcommand{\name}{\cvauthor}
% \name
\ExtractInitials{\cvauthor}
\FirstInitial
\SecondInitial
}
\end{textblock}
}
my-resume.tex
\documentclass[a4paper,11pt]{myclass}
\cvauthor{John Smith} %%% whant to extract J and S
\begin{document}
\makeskeleton
\end{document}
Error
! Use of \TP#textblock doesn't match its definition.
\text#command #1->\def \reserved#a {
#1}\ifx \reserved#a \#empty \let \check#...
l.5 \makeskeleton
?
Need somebody's help.
ifthen package is missing
\ExtractInitials fails because \cvauthor saves the name with all the formatting like small caps etc. An easy workaround is to define a macro that just saves the plain name
please keep in mind that your \ExtractInitials will fail in many cases: more than two name parts, names with prefix etc. Instead of reinventing the wheel, have a look at biblatex which is very good at parsing all kinds of names
\ProvidesClass{myclass}[2020/09/12 CV class]
\LoadClass{article}
\NeedsTeXFormat{LaTeX2e}
\RequirePackage{xstring}
\RequirePackage{soul}
\RequirePackage[absolute, overlay]{textpos}
\RequirePackage{ifthen}
\sodef\myspace{}{.1em}{0.5em plus0.5em}{2em plus.1em minus.1em} % User-defined letter spacing
\newcommand{\cvauthor}[1]{\newcommand{\mycvauthor}{#1}\renewcommand{\cvauthor}{\textsc{\myspace{#1}}}}
\newcommand{\FirstInitial}{}
\newcommand{\SecondInitial}{}
\newcommand*{\ExtractInitials}[1]{%
\StrRemoveBraces{#1}[\FirstInit]%
\StrChar{\FirstInit}{1}[\FirstInit]
\renewcommand{\FirstInitial}{\FirstInit}
\StrBehind{#1}{ }[\second]%
\StrRemoveBraces{\second}[\SecondInit]%
\StrChar{\SecondInit}{1}[\SecondInitial]
}
\newcommand*{\makeskeleton}{
\begin{textblock}{20}(0,0)
\ifthenelse{\equal{\cvauthor}{}}{}{
%\Huge\textcolor{darkYellow}{\textbf{\cvauthor}}
% \renewcommand{\name}{\cvauthor}
% \name
\ExtractInitials{\mycvauthor}
\FirstInitial
\SecondInitial
}
\end{textblock}
}

\afterpage and \endfloat

How do I combine \afterpage and \endfloat to easily switch between having figures and tables at the end of the document or having them in the text?
I want to easily choose between my figures at the end of the document and my figures in the text. Because of that, sometimes I will use \afterpage package and other times I will use \endfloat would be nice to combine both.
Right now, all the times I try to run \endfloat when I have a clear page, I get the following message:
Argument of \efloat#xfloat has an extra }.
I already tried to include after page in the DeclareDelayedFloatFlavor, something like:
\DeclareDelayedFloatFlavor{afterpage}{figure}
It did not work.
\documentclass[12pt,a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage{float}
\usepackage{afterpage}
% ---------------------
%figures at the end
% ---------------------
\usepackage[nolists]{endfloat}
% force landscape at the end
\begin{document}
{\afterpage{
\begin{figure}
\end{figure}
}
\end{document}
If you want to switch between having figures within the text and at the end, I suggest to only use the endfloat package. Commenting or commenting it's optional argument disable will allow you to quickly alternate between figures at the end or in the text.
I'm not entirely certain what the purpose of afterpage was in your example, but if you used it to move the figure to a separate page, this can conveniently be done with the p floating specifier.
\documentclass{article}
\usepackage[
disable
]{endfloat}
\begin{document}
test
\begin{figure}[p]
xxx
\caption{caption}
\end{figure}
test
\end{document}

Figures occurring after ^ and _ macros (was: LaTeX limitation?)

I've hit an annoying problem in LaTeX. I've got a tex file of about 1000 lines. I've already got a few figures, but when I try to add another figure, It barfs with:
! Undefined control sequence.
<argument> ... \sf#size \z# \selectfont \#currbox
l.937 \begin{figure}[t]
If I move the figure to other parts of the file, I can get similar errors on different lines:
! Undefined control sequence.
<argument> ... \sf#size \z# \selectfont \#currbox
l.657 \paragraph
{A Centering Algorithm}
If I comment out the figure, all is ok.
%\begin{figure}[t]
% \caption{Example decision tree, from Reiter and Dale [2000]}
% \label{fig:relation-decision-tree}
% \centering
% \includegraphics[keepaspectratio=true]{./relation-decision-tree.eps}
%\end{figure}
If I keep just the begin and end like:
\begin{figure}%[t]
% \caption{Example decision tree, from Reiter and Dale [2000]}
% \label{fig:relation-decision-tree}
% \centering
% \includegraphics[keepaspectratio=true]{./relation-decision-tree.eps}
\end{figure}
I get:
! Undefined control sequence.
<argument> ... \sf#size \z# \selectfont \#currbox
l.942 \end
{figure}
At first, I thought maybe LaTeX has hit some limit, and I tried playing with the ulimits, but that didn't help. Any ideas?
i've got other figures with graphics already. my preamble looks like:
\documentclass[acmcsur,acmnow]{acmtrans2n}
\usepackage{array}
\usepackage{lastpage}
\usepackage{pict2e}
\usepackage{amsmath}
\usepackage{varioref}
\usepackage{epsfig}
\usepackage{graphics}
\usepackage{qtree}
\usepackage{rotating}
\usepackage{tree-dvips}
\usepackage{mdwlist}
\makecompactlist{quote*}{quote}
\usepackage{verbatim}
\usepackage{ulem}
I found, not that it's a problem with \textsuperscript, but that it's with a ^ def I picked up from http://anthony.liekens.net/index.php/LaTeX/SubscriptAndSuperscriptInTextMode . The fix is to put the use of ^ in {}, as in I've put entire sections where I use lots of ^ and _ in {}. Hurrah!
During the end of my Master Thesis I also had the problem that after some amount of figures, I got an error without any special error message. After I read you thread, I also tried something with the packages included and in the end I was successful by taking out the \usepackage{pxfonts} and \usepackage{txfonts}. Yeah, finally.. I almost went crazy.. ;)
If I Google for "latex undefined control sequence" I get this.
I've successfully included a graphic into LaTeX using something like this:
\usepackage{amsmath,amsthm,graphicx}
...
I just wanted to test adding an image to a \LaTeX file:
\includegraphics[scale=0.60]{basic-info.png}
I typeset an entire dissertation of 200 pages with lots of figures in LaTeX and didn't run into a limit like that. I'd bet on a syntax problem first before I'd assume a size issue.
Your error lies elsewhere. I wouldn't be the least surprised if it turned out to be the document class. Try altering your document for \documentclass{article} and see where you get. If that fixes the problem you can complain to the ACM (ROTFLMAO—I've dealth with ACM).
If that doesn't fix, the problem, slip in a \tracingall somewhat before the offending figure or section, put the results into http://pastebin.com/, and let us know.
Please receive the thanks of a (formerly) utterly-confounded graduate student. Quick clarification for other users:
{The quickest ^{way} to put this solution into practice is to bracket all sections of text involving the character ``\^'' as shown here.}

Resources