É possível corrigir os números sempre em romano usando listagem

É possível corrigir os números sempre em romano usando listagem

Minhas tags são as seguintes:

\documentclass{book}
\usepackage{xcolor}
\usepackage{textcomp,listings}%

\lstnewenvironment{python}[1][]{%
\lstset{%
mathescape=false,%
language=python,%
basicstyle=\ttfamily\normalsize,%
otherkeywords={*,\{, \} },%
keywordstyle=\color{black},%
stringstyle=\color{black},%
showstringspaces=false,%
emph={class, pass, in, for, while, if, is, elif, else, not, and, or,%
def, print, exec, break, continue, return},%
emphstyle=\color{black}\bfseries,%
emph={[3]True, False, None, self},%
emphstyle=[2]\color{black!10},%
emph={[3]from, import, as},%
emphstyle=[3]\color{black},%
upquote=true,%
morecomment=[s]{"""}{"""},%
commentstyle=\color{gray}\slshape,%
aboveskip=12pt,belowskip=12pt,xleftmargin=-2pt,xrightmargin=3pt,framexleftmargin=20pt,framextopmargin=1pt,%
rulesepcolor=\color{gray},#1%
}}{}%

\begin{document}

\begin{python}
In [7]: np.searchsorted(X, 0.5)
Out[7]: 4998210 # This is 1 for test 1000
\end{python}

\begin{python}
In [7]: np.searchsorted(X, 0.5) # left edge 1234567890

 from scipy import stats
    dist stats.uniform (0, 2)  # left edge 0, width  2
\end{python}

\end{document}

Está funcionando bem sem problemas. Por favor, confirme que preciso que o arabic numerals (i.e., 0 to 9)item esteja romansempre presente, consulte a captura de tela:

insira a descrição da imagem aqui

Isso é possível consertar? Por favor, avise...

Responder1

Aqui está uma solução que faz uso da abordagem geral de destaque de números apresentada emListagens: números de cores apenas fora de palavras-chave.

Precisamos fazer algumas alterações no OutputOthergancho dessa solução, porque neste caso você deseja substituir o estilo padrão, independentemente de estar em um comentário ou não. O novo gancho se parece com:

\lst@AddToHook{OutputOther}{%
    \lst@ifparsenumbers
        \expandafter\@hook@ifnumber\the\lst@token\@end {%
            \let\orig@thestyle=\lst@thestyle
            \def\lst@thestyle{\orig@thestyle\lst@numbersstyle}%
        }{}%
    \fi
}

Também ao seu \lstsetcomando as seguintes linhas devem ser adicionadas:

parsenumbers=true,
numbersstyle=\upshape

Sempre que um número for analisado listingsna entrada, ele numbersstyleserá adicionado ao estilo atualmente ativo.


Código de exemplo completo:

\documentclass{book}
\usepackage{xcolor}
\usepackage{textcomp,listings}%


\makeatletter

%%% Copied from https://tex.stackexchange.com/a/500690/23765
% Some conditional tests
\def\@genericif#1{#1\expandafter\@firstoftwo\else\expandafter\@secondoftwo\fi}
\def\@ifdigit#1{\@genericif{\ifnum1<1\noexpand#1\relax}}
\def\@ifempty#1{\@genericif{\if\relax\detokenize{#1}\relax}}

% The main parsing macros
\def\parse@num#1{%
    \@ifempty{#1}%
        {\parse@num@false}%
        {\@genericif{\parsesign}%
            {\parse@num@sign#1{}\@end}%
            {\parse@num@dig#1{}\@end}%
        }%
}
% Parse sign
\def\parse@num@sign#1#2\@end{%
    \@genericif{\ifx\parse@num@minus#1}%
        {\@ifempty{#2}{\parse@num@false}{\parse@num@dig#2\@end}}%
        {\@genericif{\ifx\parse@num@plus#1}%
            {\@ifempty{#2}{\parse@num@false}{\parse@num@dig#2\@end}}%
            {\parse@num@dig#1#2\@end}%
        }%
}
% Parse first digit
\def\parse@num@dig#1#2\@end{%
    \@ifdigit{#1}%
        {\@ifempty{#2}{\parse@num@true}{\parse@num@digs#2\@end}}%
        {\parse@num@false}%
}
% Parse optional following digits
\def\parse@num@digs#1#2\@end{%
    \@ifdigit{#1}{%
        \@ifempty{#2}%
            {\parse@num@true}%
            {\parse@num@digs#2\@end}%
    }{%
        \@genericif{\parsefloat}{%
            \@genericif{\ifx\parse@num@point#1}%
                {\@ifempty{#2}{\parse@num@false}{\parse@num@decs#2\@end}}%
                {\parse@num@false}%
        }{\parse@num@false}%
    }%
}
% Parse decimal places
\def\parse@num@decs#1#2\@end{%
    \@ifdigit{#1}{%
        \@ifempty{#2}%
            {\parse@num@true}%
            {\parse@num@decs#2\@end}%
    }{\parse@num@false}%
}

% User interface
\newcommand\ifnumber[4][]{%
    \begingroup
    \let\parsesign=\iftrue
    \let\parsefloat=\iftrue
    \let\parse@num@minus=-%
    \let\parse@num@plus=+%
    \let\parse@num@point=.%
    #1%
    \def\parse@num@true{\endgroup#3}%
    \def\parse@num@false{\endgroup#4}%
    \parse@num{#2}%
}   


%%% Additions to the listings package
\lst@Key{numbersstyle}{}{\def\lst@numbersstyle{#1}}
\lst@Key{parsenumbers}{false}[t]{\lstKV@SetIf{#1}\lst@ifparsenumbers}

\lst@AddToHook{OutputOther}{%
    \lst@ifparsenumbers
        \expandafter\@hook@ifnumber\the\lst@token\@end {%
            \let\orig@thestyle=\lst@thestyle
            \def\lst@thestyle{\orig@thestyle\lst@numbersstyle}%
        }{}%
    \fi
}
\def\@hook@ifnumber#1#2\@end{%
    \@genericif{\ifx\lst@nolig#1}%
        {\@hook@ifnumber@{#2}}%
        {\@hook@ifnumber@{#1#2}}%
}
\def\@hook@ifnumber@{%
    \ifnumber[\expandafter\let\expandafter\parse@num@minus\csname lst@um-\endcsname]%
}

\makeatother


\lstnewenvironment{python}[1][]{%
\lstset{%
mathescape=false,%
language=python,%
basicstyle=\ttfamily\normalsize,%
otherkeywords={*,\{, \} },%
keywordstyle=\color{black},%
stringstyle=\color{black},%
showstringspaces=false,%
emph={class, pass, in, for, while, if, is, elif, else, not, and, or,%
def, print, exec, break, continue, return},%
emphstyle=\color{black}\bfseries,%
emph={[3]True, False, None, self},%
emphstyle=[2]\color{black!10},%
emph={[3]from, import, as},%
emphstyle=[3]\color{black},%
upquote=true,%
morecomment=[s]{"""}{"""},%
commentstyle=\color{gray}\slshape,%
aboveskip=12pt,belowskip=12pt,xleftmargin=-2pt,xrightmargin=3pt,framexleftmargin=20pt,framextopmargin=1pt,%
rulesepcolor=\color{gray},#1,
parsenumbers=true,
numbersstyle=\upshape
}}{}%

\begin{document}

\begin{python}
In [7]: np.searchsorted(X, 0.5)
Out[7]: 4998210 # This is 1 for test 1000
"""
Some text 1234
"""
\end{python}

\end{document}

insira a descrição da imagem aqui


EDITAR:O problema de 0não aparecer em fonte vertical se deve ao fato de listingsanalisar 0e ,como uma unidade (pois ambos possuem códigosdígitoououtro). O OutputOthergancho então tenta analisar 0,como um número que falha e, portanto, não fornece a fonte esperada.

Como solução alternativa, você pode adicionar a seguinte linha ao \lstsetcomando:

literate={,}{{\char`\,}}{1}

quais saídas

insira a descrição da imagem aqui

Isso faz com que o analisador seja interrompido antes de ler a vírgula. Neste caso especial não deverá haver efeitos colaterais, porque as vírgulas não devem fazer parte de palavras-chave ou outros elementos de sintaxe especiais. Infelizmente, listingsisso torna difícil adicionar o processamento de novos elementos de sintaxe; portanto, solucionar um problema aqui geralmente levanta outro ali.

informação relacionada