Я заинтересован в настройке подсветки синтаксиса Python (но, надеюсь, она будет распространяться и на другие языки) с использованием списков в латексе. К сожалению, я не эксперт по латексу, и я собрал что-то вместе, что близко к тому, что я хочу, но все еще немного не хватает. (Я хотел бы выделить код Python, как в среде TigerJython для образовательных целей). Выделение чисел, которых нет в символьных строках, было одной из основных проблем, и решение по существу не позволяет мне использовать грамотные или более ключевые слова для выделения операторов с одним символом. Я могу дать всем другим символам в таблице символов отдельный цвет, но я бы хотел, чтобы для операторов и скобок были разные цвета. Это последнее, что я до сих пор скучаю. Я приведу рабочий пример:
\documentclass[a4paper,12pt]{article}
\usepackage[utf8]{inputenc}
\usepackage{textcomp}
\usepackage{xcolor}
\usepackage{epstopdf} %converting to PDF
\usepackage{listings} % for python code snippets
\usepackage{xinttools}% for expandable and non-expandable loops
% color definitions
\definecolor{Code}{RGB}{0,0,0}
\definecolor{Keywords}{RGB}{0,51,170}
\definecolor{Keyfunctions}{RGB}{119,0,136}
\definecolor{Strings}{RGB}{204,102,0}
\definecolor{Comments}{RGB}{0,128,0}
\definecolor{Numbers}{RGB}{204,51,0}
\definecolor{Operators}{RGB}{128,64,64}
\definecolor{Datatypes}{RGB}{0,128,128}
\definecolor{Brackets}{RGB}{0,51,102}
% make @ interpretable as a character
\makeatletter
% various operator characters for the after sign function
\lst@SaveOutputDef{"25}\lstum@percent
\lst@SaveOutputDef{"26}\lstum@and
\lst@SaveOutputDef{"2A}\lstum@star
\lst@SaveOutputDef{"2D}\lstum@minus
\lst@SaveOutputDef{"2D}\lstum@dot
\lst@SaveOutputDef{"3C}\lstum@lt
\lst@SaveOutputDef{"3D}\lstum@equal
\lst@SaveOutputDef{"3E}\lstum@gt
\lst@SaveOutputDef{"7B}\lstum@lbrace
\lst@SaveOutputDef{"7D}\lstum@rbrace
% some complex replacement setup to highlight numbers correctly
\newif\iffirstchar\firstchartrue
\newif\ifstartedbyadigit
\newif\ifprecededbysign
\newif\ifbracketfalse
\newcommand{\brackets}{()[]}
% this is where the preceding operators are declared
\lst@AddToHook{OutputOther}%
{%
\lst@IfLastOtherOneOf{,?!=+/([ \lstum@percent \lstum@and \lstum@star \lstum@minus \lstum@lt \lstum@gt \lstum@lbrace \lstum@lbrace}
{\global\precededbysigntrue}
{}%
\IsOperator
}
% replacement function for numbers
\lst@AddToHook{Output}%
{%
\ifprecededbysign
\ifstartedbyadigit
\def\lst@thestyle{\color{Numbers}}%
\fi
\fi
\global\firstchartrue
\global\startedbyadigitfalse
\global\precededbysignfalse
}
\newcommand\processletter
{%
\ifnum\lst@mode=\lst@Pmode
\iffirstchar%
\global\startedbyadigitfalse
\fi
\global\firstcharfalse
\fi
}
\newcommand\processdigit
{%
\ifnum\lst@mode=\lst@Pmode
\iffirstchar
\global\startedbyadigittrue
\fi
\global\firstcharfalse
\fi
}
\newcommand\addtoletterdef[2]
{%
\expandafter\lst@DefSaveDef
\expandafter{%
\expandafter`%
\expandafter#2%
\expandafter}%
\csname why#2\expandafter\endcsname
\expandafter{\csname why#2\endcsname #1}%
}
% helper macro for operators
\newcommand\IsOperator
{%
\ifnum\lst@mode=\lst@Pmode% % If we're in `Processing' mode...
\def\lst@thestyle{\color{Operators}}% % ... redefine the style locally
\fi%
}
\newcommand\IsBracket
{%
\ifnum\lst@mode=\lst@Pmode% % If we're in `Processing' mode...
\def\lst@thestyle{\color{Brackets}}% % ... redefine the style locally
\fi%
}
\makeatother
% Default fixed font does not support bold face
\DeclareFixedFont{\ttb}{T1}{txtt}{bx}{n}{12} % for bold
\DeclareFixedFont{\ttm}{T1}{txtt}{m}{n}{12} % for normal
\newcommand\pythonstyle{\lstset{
language=Python,
basicstyle=\ttm,
otherkeywords={self}, % Add keywords here
deletekeywords={sum,str,int,input}, % remove keywords here
keywordstyle=\ttb\color{Keywords},
emph={len,range,True,False,input}, % Custom highlighting
emphstyle=\color{Keyfunctions}, % Custom highlighting style
emph=[2]{int,str}, % Custom highlighting
emphstyle=[2]\ttb\color{Datatypes}, % Custom highlighting style
%emph=[3]{(,),[,]}, % Custom highlighting
%emphstyle=[3]\color{Brackets}, % Custom highlighting style
emph=[4]{sum}, % Custom highlighting
emphstyle=[4]\color{black}, % Custom highlighting style
stringstyle=\color{Strings},
commentstyle=\ttb\color{Comments},
frame=tb, % Any extra options here
showstringspaces=false , %
upquote = true, % quotes are straight dashes
showtabs=true,
tab=\rightarrowfill ,
alsoletter=0123456789.,
SelectCharTable=%
\xintApplyInline{\addtoletterdef\processdigit}{0123456789.}%
\xintApplyInline{\addtoletterdef\processletter}
{abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ}%
}
}
% Python environment
\lstnewenvironment{python}[1][]
{
\pythonstyle
\lstset{#1}
}
{}
\begin{document}
\begin{python}
i = 5+a #no symbol highlighting in comments )=?+ etc
hex_num = 0xad344
dec_num = 5.5
word = str(4) # number 4
other_dot = c.call()
my_str='4+=5*(5+5)'
\end{python}
\end{document}
Я полагаю, что хочу использовать \ lst@IfSubstring и \ lst@token для создания выбора if между IsBracket и IsOperator в \ lst@AddToHook {OutputOther} блок, но я просто не очень хорошо понимаю латекс и списки, чтобы понять, как все это соединить: (
Как уже говорилось, мне все еще не хватает выделения операторов и скобок разными цветами. может выделять символ «.» как оператор, если не в числе, которое округляет все, и решение не должно нарушать ничего из работающего в данный момент кода, в частности подсветку номера. T