0

The post:

How to highlight Python syntax in LaTeX Listings \lstinputlistings command

produced answer from redmode, that gives a colored python code listing. Although the text produces minus/hyphens in this latex code. When I introduced it to my own code (below) it did not. Can someone help me solve this? I am using TeXstudio 3.0.1 on Ubuntu 20.04.1 LTS.

----------------------- redmode wrote ----------------------

Good approach is defining new environments for programming language. Minimal setup can be around this:

\documentclass[a4paper,12pt]{article}
\usepackage[utf8]{inputenc}

% 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

% Custom colors
\usepackage{color}
\definecolor{deepblue}{rgb}{0,0,0.5}
\definecolor{deepred}{rgb}{0.6,0,0}
\definecolor{deepgreen}{rgb}{0,0.5,0}

\usepackage{listings}

% Python style for highlighting
\newcommand\pythonstyle{\lstset{
language=Python,
basicstyle=\ttm,
otherkeywords={self},             % Add keywords here
keywordstyle=\ttb\color{deepblue},
emph={MyClass,__init__},          % Custom highlighting
emphstyle=\ttb\color{deepred},    % Custom highlighting style
stringstyle=\color{deepgreen},
frame=tb,                         % Any extra options here
showstringspaces=false            % 
}}


% Python environment
\lstnewenvironment{python}[1][]
{
\pythonstyle
\lstset{#1}
}
{}

% Python for external files
\newcommand\pythonexternal[2][]{{
\pythonstyle
\lstinputlisting[#1]{#2}}}

% Python for inline
\newcommand\pythoninline[1]{{\pythonstyle\lstinline!#1!}}

\begin{document}

\section{``In-text'' listing highlighting}

\begin{python}
class MyClass(Yourclass):
    def __init__(self, my, yours):
        bla = '-5 1 2 3 -4'
        -10
        print bla
\end{python}

%\section{External listing highlighting}

%\pythonexternal{demo.py}

\section{Inline highlighting}

Definition \pythoninline{class MyClass} means \dots

\end{document}

enter image description here

Here is my latex code with the above code placed in it, but shows no minus signs.

%\documentclass[12pt]{scrartcl}
%\documentclass[12pt]{amsart}
%\documentclass[12pt]{article}
\documentclass[a4paper,12pt]{article}
\usepackage[utf8]{inputenc}
%\documentclass{article}
\usepackage{geometry}
\usepackage{graphicx}
%\pagestyle{empty}
%\mathchardef\hyphenmathcode=\mathcode`\- % BJD added here 16.12.2020

\usepackage[version=4]{mhchem} % BJD added here 14.8.2018
\usepackage{breqn}  % BJD added here 14.8.2018

\usepackage[colorlinks=true, citecolor=blue, linkcolor=blue, urlcolor=blue]{hyperref}
\newgeometry{asymmetric, centering}
\usepackage [english]{babel} % BJD added here
\usepackage [autostyle, english = american]{csquotes} % BJD added here
%\usepackage[T1]{fontenc} % BJD 20.10.2018
%\usepackage[utf8]{inputenc} %BJD 20.10.2018
%\usepackage[font=small,labelfont=bf,tableposition=top]{caption} %BJD 20.10.2018
%\MakeOuterQuote{"} % BJD added here
%% show notes and keys in the draft mode %%%%%%%%%
\usepackage{ifdraft}
\ifoptionfinal{
\usepackage[disable]{todonotes}
}{
\usepackage[norefs, nocites]{refcheck}
\usepackage{soul}
%\providecommand*\showkeyslabelformat[1]{\normalfont\tiny\ttfamily#1} %BJD 20.2.2020
%\usepackage[notref, notcite]{showkeys} %BJD 20.2.2020
\usepackage[bordercolor=white, color=white]{todonotes}
}
\usepackage{xfrac}  % BJD added here 15.8.2018
\usepackage{amsmath, amsthm, amssymb, amsfonts} % BJD added here 23.8.2018 
\usepackage{upgreek} % BJD added here 25.8.2018 

\usepackage{rotating, graphicx} % BJD added here 20.10.2018
\usepackage{tikz} % BJD added here 20.10.2018
\usepackage{blindtext} % BJD added here 20.10.2018
\usepackage{caption} % BJD added here 20.10.2018
%\usepackage{tikz} % BJD added here 20.10.2018
\usepackage{hyperref}
\usepackage{xcolor}

%------------BJD 15.8.2018-----------------------
\makeatletter
\def\@settitle{\begin{center}%
        \baselineskip14\p@\relax
        \bfseries
        \uppercasenonmath\@title
        \@title
        \ifx\@subtitle\@empty\else
        \\[1ex]\uppercasenonmath\@subtitle
        \footnotesize\mdseries\@subtitle
        \fi
    \end{center}%
}
\def\subtitle#1{\gdef\@subtitle{#1}}
\def\@subtitle{}
\makeatother

%\usepackage{listings}
%\lstset{
%   defaultdialect=[Visual]Basic
%   ,frameround=fttt
%   ,language=SQL
%   ,numbers=left
%   ,breaklines=true
%   ,showstringspaces=false
%   ,basicstyle=\small
%}
%---------------BJD added 16.12.2020--------------------
% 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

% Custom colors
\usepackage{color}
\definecolor{deepblue}{rgb}{0,0,0.5}
\definecolor{deepred}{rgb}{0.6,0,0}
\definecolor{deepgreen}{rgb}{0,0.5,0}

\usepackage{listings}

% Python style for highlighting
\newcommand\pythonstyle{\lstset{
        language=Python,
        basicstyle=\ttm,
        otherkeywords={self},             % Add keywords here
        keywordstyle=\ttb\color{deepblue},
        emph={MyClass,__init__},          % Custom highlighting
        emphstyle=\ttb\color{deepred},    % Custom highlighting style
        stringstyle=\color{deepgreen},
        frame=tb,                         % Any extra options here
        showstringspaces=false            % 
}}


% Python environment
\lstnewenvironment{python}[1][]
{
    \pythonstyle
    \lstset{#1}
}
{}

% Python for external files
\newcommand\pythonexternal[2][]{{
        \pythonstyle
        \lstinputlisting[#1]{#2}}}

% Python for inline
\newcommand\pythoninline[1]{{\pythonstyle\lstinline!#1!}}

%-------------------------------------------
% \let\origlstlisting=\lstlisting
%\let\endoriglstlisting=\endlstlisting
%\renewenvironment{lstlisting}
%{\mathcode`\-=\hyphenmathcode
%   \everymath{}\mathsurround=0pt\origlstlisting}
%{\endoriglstlisting}
%-------------------end 16.12.2020--------------------------------------


%-------------------------------------------------
%******BJD change****************
%\documentclass{article}
%\usepackage{graphicx}
%\graphicspath{ {/home/user/images/} }
%\graphicspath{ {/home/bjd/Downloads/} }
%******BJD change end****************
\newcommand{\HOX}[1]{\todo[noline, size=\footnotesize]{#1}}
\newcommand{\TODO}[1]{\hfill\todo[inline, bordercolor=black, color=green!10]{#1}}
%% HACK from Sec. 1.6.4 of the manual of todonotes package
\makeatletter\providecommand\@dotsep{5}\def\listtodoname{List of Todos}\def\listoftodos{\hypersetup{linkcolor=black}\@starttoc{tdo}\listtodoname\hypersetup{linkcolor=blue}}\makeatother
%%%%%%%%%%%%%%%%%%

%% numbering %%%%%%%%%
\newtheorem{lemma}{Lemma}
\newtheorem{proposition}{Proposition}
\newtheorem{theorem}{Theorem}
\newtheorem{corollary}{Corollary}
\newtheorem{definition}{Definition}
\theoremstyle{remark} 
\newtheorem{example}{Example}
\newtheorem{remark}{Remark}

%% definitions %%%%%%%%% 
\def\C{\mathbb C}
\def\R{\mathbb R}
\def\Q{\mathbb Q}
\def\Z{\mathbb Z}
\def\N{\mathbb N}

\def\p{\partial}
\DeclareMathOperator{\supp}{supp}
\newcommand{\pair}[1]{\left\langle #1 \right\rangle}
\newcommand{\norm}[1]{\left\|#1 \right\|}
%\newcommand{\dd}[1]{\mathrm{d}#1}
%\def\inter{\text{int}}
%\let\dim\relax
%\DeclareMathOperator{\dim}{dim}

\usepackage{fancyhdr}

\pagestyle{fancy}
\fancyhf{}
\rhead{Model G Vortical Motion Group}
%\lhead{}
\rfoot{Page \thepage}


%\begin{document}
    
\begin{document}
    
\section{``In-text'' listing highlighting}
    
\begin{python}
class MyClass(Yourclass):
    def __init__(self, my, yours):
        bla = '-5 1 2 3 -4'
        -10
        print bla
\end{python}
    
    %\section{External listing highlighting}
    
    %\pythonexternal{demo.py}
    
    \section{Inline highlighting}
    
    Definition \pythoninline{class MyClass} means \dots
    
\end{document}

enter image description here

1
  • 1
    Please make an example that contains minus/hyphens and describe, what output you expect
    – DG'
    Dec 16, 2020 at 21:59

1 Answer 1

2

I think it is a font issue. When you use \DeclareFixedFont{\ttm}{T1}{txtt}{m}{n}{12}, the font does not come with a minus sign. I am not sure why you don't try something like

\newcommand\pythonstyle{\lstset{
        language=Python,
        basicstyle=\ttfamily,
        otherkeywords={self},             % Add keywords here
        keywordstyle=\ttb\color{deepblue},
        emph={MyClass,__init__},          % Custom highlighting
        emphstyle=\ttb\color{deepred},    % Custom highlighting style
        stringstyle=\color{deepgreen},
        frame=tb,                         % Any extra options here
        showstringspaces=false            % 
}}

Just in case you do not know, the minted package provides better syntax highlighting results with the help of pygments.

enter image description here

\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage{minted}

\usemintedstyle{manni}

\newmintinline[pyinl]{Python}{}

\begin{document}


\begin{minted}{python}
class MyClass(Yourclass):
    def __init__(self, my, yours):
        bla = '-5 1 2 3 -4'
        -10
        print bla
\end{minted}

\pyinl|class MyClass|

\end{document}
4
  • Hi @Alan Xiang. I am having trouble installing pygmentize. I receive the error message: Package minted Error: You must have pygmentize installed to use this package. \begin{document}. I have tried to install pygmentize using: sudo apt install python3-pygments, but still no solution. Dec 18, 2020 at 16:52
  • I also receive error message: Package minted Error: Missing Pygments output; \inputminted wasor may be using frozencache with a missing file. \end{minted} Dec 18, 2020 at 17:01
  • Thank you very much! I tried the first part of your answer (without minted), and it worked!! Dec 18, 2020 at 17:34
  • 1
    @BrendanDarrer Regarding minted, there can be multiple causes. First of all, you need to compile your document with -shell-escape flag, which grants LaTeX access to shell. If you can run pygmentize --help in bash, pygmentize should have been correctly installed.
    – Alan Xiang
    Dec 18, 2020 at 17:46

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .