I have the following code
\DeclareCaptionLabelFormat{algocaption}{Algorithm} % defines a new caption label as Algorithm x.y
\lstnewenvironment{algorithm}[1][
{
\captionsetup
{
justification=raggedright,
singlelinecheck=false,
labelformat=algocaption
}
\lstset
{
mathescape=true,
escapeinside={}, % I think I need to change this
literate={\\\\[0pt]}{{}}1,
breaklines=false,
frame=tB,
basicstyle=\scriptsize,
keywordstyle=\color{black}\bfseries,
keywords=
{
,input,
output,
return,
datatype,
function,
in,
if,
else,
foreach,
while,
begin,
end,
}
xleftmargin=0.4\textwidth,
#1
}
}{}
which should turn
\begin{algorithm}
input: int N, int D\\[0pt]
output: int\\[0pt]
begin\\[0pt]
res $\gets$ 0\\[0pt] %% I manually edited this in overleaf
while N \(\geq\) D\\[0pt]
N \(\gets\) N - D\\[0pt]
res \(\gets\) res + 1\\[0pt]
end\\[0pt]
return res\\[0pt]
end\\[0pt]
\end{algorithm}
Into the following...
but instead latex gives me...
I know I can use $$
instead to get the desired result, but that is not what I am trying to do (this gets automatically formatted this way after exporting from emacs org mode, and as far as I know, the behavior cannot be changed). Additionally, I know I could add ''
to escapeinside
but I'd really prefer not to add any extra characters. It seems like it should be possible to set the escape inside delimiters as \\(
and \\)
, but trying this does not work.
MWE
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{color}
\usepackage{listings}
\usepackage{caption}
\DeclareCaptionLabelFormat{algocaption}{Algorithm} % defines a new caption label as Algorithm x.y
\lstnewenvironment{algorithm}[1][]{\captionsetup{justification=raggedright,singlelinecheck=false,labelformat=algocaption}\lstset{mathescape=true, escapeinside={}, literate={\\\\[0pt]}{{}}1, breaklines=false, frame=tB,basicstyle=\scriptsize, keywordstyle=\color{black}\bfseries,keywords={,input, output, return, datatype, function, in, if, else, foreach, while, begin, end, } xleftmargin=0.4\textwidth,#1}}{}
\begin{document}
%% Problematic
\begin{algorithm}
input: int N, int D\\[0pt]
output: int\\[0pt]
begin\\[0pt]
res \(\gets\) 0\\[0pt]
while N \(\geq\) D\\[0pt]
N \(\gets\) N - D\\[0pt]
res \(\gets\) res + 1\\[0pt]
end\\[0pt]
return res\\[0pt]
end\\[0pt]
\end{algorithm}
%% Desired
\begin{algorithm}
input: int N, int D\\[0pt]
output: int\\[0pt]
begin\\[0pt]
res $\gets$ 0\\[0pt]
while N $\geq$ D\\[0pt]
N $\gets$ N - D\\[0pt]
res $\gets$ res + 1\\[0pt]
end\\[0pt]
return res\\[0pt]
end\\[0pt]
\end{algorithm}
\end{document}