GeneralDefining new languages for listings package

LaTeX specific issues not fitting into one of the other forums of this category.
ebigunso
Posts: 9
Joined: Sat Jul 29, 2017 5:04 pm

Defining new languages for listings package

Post by ebigunso »

thomasb wrote:The Array color is not bluegreen already... Try without the

Code: Select all

morekeywords = [5]{boolean(},
line, maybe it's the unclosed parenthesis that causes problem... (Here, everything is black, the pdf has no colors)
hmm, weird. Seems there are more to this pLaTeX/LaTeX compatibility issue. Unforeseen problems really make things harder to solve :(

Recommended reading 2024:

LaTeXguide.org • LaTeX-Cookbook.net • TikZ.org

NEW: TikZ book now 40% off at Amazon.com for a short time.

thomasb
Posts: 134
Joined: Thu Aug 03, 2017 10:54 am

Defining new languages for listings package

Post by thomasb »

Try to define the keywords like this:

Code: Select all

\lstset{classoffset=0,
morekeywords={one,three,five},keywordstyle=\color{red},
classoffset=1,
morekeywords={two,four,six},keywordstyle=\color{blue},
classoffset=0}% restore default
ebigunso
Posts: 9
Joined: Sat Jul 29, 2017 5:04 pm

Defining new languages for listings package

Post by ebigunso »

thomasb wrote:Try to define the keywords like this:

Code: Select all

\lstset{classoffset=0,
morekeywords={one,three,five},keywordstyle=\color{red},
classoffset=1,
morekeywords={two,four,six},keywordstyle=\color{blue},
classoffset=0}% restore default
Tried. Doesn't work.
Image

Code: Select all

\documentclass{article}
 
\usepackage{listings}
\usepackage[dvipdfmx]{color}
 
%Define Colors
\definecolor{gray}{RGB}{102,102,102}		%#666666
\definecolor{lightblue}{RGB}{0,102,153}		%#006699
\definecolor{lightgreen}{RGB}{102,153,0}	%#669900
\definecolor{bluegreen}{RGB}{51,153,126}	%#33997e
\definecolor{magenta}{RGB}{217,74,122}		%#d94a7a
\definecolor{orange}{RGB}{226,102,26}		%#e2661a
\definecolor{purple}{RGB}{125,71,147}		%#7d4793
\definecolor{green}{RGB}{113,138,98}		%#718a62
 
\lstdefinelanguage{Processing}{
  %keyword1&2&6
  classoffset = 1,
  morekeywords = {abstract, class, continue, default, enum, extends, false, final, finally, implements, import, instanceof, interface, native, new, null, package, private, protected, public, static, strictfp, throws, transient, true, void, volatile, length, assert, case, return, super, this, throw},
  keywordstyle = \color{bluegreen},
  %keyword3
  classoffset = 2,
  morekeywords = {catch, do, for, if, else, switch, synchronized, while, try},
  keywordstyle = \color{lightgreen},
  %keyword4
  classoffset = 3,
  morekeywords = {width, height, pixelHight, displayHeight, displayWidth, focused, frameCount, frameRate, key, keyCode, keyPressed, mouseButton, mousePressed, mouseX, mouseY, pixels, pixelWidth, pmouseX, pmouseY},
  keywordstyle = \color{magenta},
  %keyword5
  classoffset = 4,
  morekeywords = {Array, ArrayList, Boolean, Byte, BufferedReader, Character, Class, Double, Float, Integer, HashMap, PrintWriter, String, StringBuffer, StringBuilder, Thread, boolean, byte, char, color, double, float, int, long, short, FloatDict, FloatList, IntDict, IntList, JSONArray, JSONObject, PFont, PGraphics, PImage, PShader, PShape, PVector, StringDict, StringList, Table, TableRow, XML},
  keywordstyle = \color{orange},
  %function1
  classoffset = 5,
  morekeywords = {boolean(},
  keywordstyle = \color{lightblue},
  classoffset = 0,
  sensitive = true,
  morecomment = [l]{//},
  morecomment = [s]{/*}{*/},
  morecomment = [s]{/**}{*/},
  commentstyle = \color{gray},
  morestring = [b]",
  morestring = [b]',
  stringstyle = \color{purple}
}
\lstset{
  language={Processing},
  basicstyle={\small},
  identifierstyle={\small},
  commentstyle={\small\itshape},
  keywordstyle={\small\bfseries},
  ndkeywordstyle={\small},
  stringstyle={\small\ttfamily},
  frame={tb},
  breaklines=true,
  columns=[l]{fullflexible},
  numbers=left,
  xrightmargin=0em,
  xleftmargin=3em,
  numberstyle={\scriptsize},
  stepnumber=1,
  numbersep=1em,
  lineskip=-0.5ex,
}
 
\begin{document}
\begin{lstlisting}
boolean;
boolean(1);
\end{lstlisting}
\end{document}
thomasb
Posts: 134
Joined: Thu Aug 03, 2017 10:54 am

Defining new languages for listings package

Post by thomasb »

The bug comes from the parenthesis... This works without, and doesn't with :

Code: Select all

\documentclass{article}

\usepackage{listings}

\usepackage{color}
 
\definecolor{codegreen}{rgb}{0,0.6,0}
\definecolor{codegray}{rgb}{0.5,0.5,0.5}
\definecolor{codepurple}{rgb}{0.58,0,0.82}
\definecolor{backcolour}{rgb}{0.95,0.95,0.92}
 
\lstloadlanguages{Python}

\lstdefinestyle{mystyle}{
  language=Python,
  backgroundcolor=\color{backcolour},   
  commentstyle=\color{codegreen},
  keywordstyle=\color{magenta},
  numberstyle=\tiny\color{codegray},
  stringstyle=\color{codepurple},
  basicstyle=\footnotesize,
  breakatwhitespace=false,         
  breaklines=true,                 
  captionpos=b,                    
  keepspaces=true,                 
  numbers=left,                    
  numbersep=5pt,                  
  showspaces=false,                
  showstringspaces=false,
  showtabs=false,                  
  tabsize=2,
  morekeywords = {boolean},
  morekeywords = [2]{myboolean}, % HERE : add remove the parenthesis
  keywordstyle = [2]\color{codegreen}
}
 
\begin{document}
The next code will be directly imported from a file

\lstset{style=mystyle}

\begin{lstlisting}
  import numpy as np
  
  def incmatrix(genl1,genl2):
  m = len(genl1)
  n = len(genl2)
  M = None #to become the incidence matrix
  VT = np.zeros((n*m,1), int)  #dummy variable
  
  #compute the bitwise xor matrix
  M1 = bitxormatrix(genl1)
  M2 = np.triu(bitxormatrix(genl2),1) 
  
  for i in range(m-1):
  for j in range(i+1, m):
  [r,c] = np.where(M2 == M1[i,j])
  for k in range(len(r)):
  VT[(i)*n + r[k]] = 1;
  VT[(i)*n + c[k]] = 1;
  VT[(j)*n + r[k]] = 1;
  VT[(j)*n + c[k]] = 1;
  
  if M is None:
  M = np.copy(VT)
  else:
  M = np.concatenate((M, VT), 1)
  
  VT = np.zeros((n*m,1), int)
  
  return M

  boolean b;
  myboolean c;
\end{lstlisting}

\end{document}
thomasb
Posts: 134
Joined: Thu Aug 03, 2017 10:54 am

Defining new languages for listings package

Post by thomasb »

Here is a possible solution :

Code: Select all

\begin{lstlisting}[escapechar=!] % here : the ! is declared an escape character
  boolean b;
  myboolean c;
  !\color{codegreen}{boolean}! c; % boolean will be green, but shorter...
\end{lstlisting}
and keep the rest of the code.

Another solution is to define another style, mystyleforbooleanonly, and switch when you need an orange "boolean". The line count will be reset to zero, but it can be set with the firstnumber keyword of the lstlisting environment : firstnumber=last.
And, there is a name keyword : \begin{lstlisting}[name=asdf, ... to force a name to the lstlisting environement ; and then join them together with the \vspace{-\baselineskip} command :

Code: Select all

\begin{lstlisting}
  boolean b;
\end{lstlisting}
\vspace{-\baselineskip}
\begin{lstlisting}[firstnumber=last,name=asdf]
  boolean b;
\end{lstlisting}
\vspace{-\baselineskip}
\begin{lstlisting}[name=asdf]
  myboolean c;
\end{lstlisting}
\vspace{-\baselineskip}
\begin{lstlisting}[escapechar=!,name=asdf]
  !\color{codegreen}{boolean}! c;
\end{lstlisting}
thomasb
Posts: 134
Joined: Thu Aug 03, 2017 10:54 am

Defining new languages for listings package

Post by thomasb »

The complete solution :

Code: Select all

\documentclass{article}

\usepackage{listings}

\usepackage{color}
 
\definecolor{codegreen}{rgb}{0,0.6,0}
\definecolor{codegray}{rgb}{0.5,0.5,0.5}
\definecolor{codepurple}{rgb}{0.58,0,0.82}
\definecolor{backcolour}{rgb}{0.95,0.95,0.92}
 
\lstloadlanguages{Python}

\lstdefinestyle{mystyle}{
  language=Python,
  backgroundcolor=\color{backcolour},   
  commentstyle=\color{codegreen},
  keywordstyle=\color{magenta},
  numberstyle=\tiny\color{codegray},
  stringstyle=\color{codepurple},
  basicstyle=\footnotesize,
  breakatwhitespace=false,         
  breaklines=true,                 
  captionpos=b,                    
  keepspaces=true,                 
  numbers=left,                    
  numbersep=5pt,                  
  showspaces=false,                
  showstringspaces=false,
  showtabs=false,                  
  tabsize=2,
  morekeywords = {boolean},
  morekeywords = [2]{myboolean},
  keywordstyle = [2]\color{codegreen}
}
 
\lstdefinestyle{mystyleforbooleanonly}{
  language=Python,
  keywordstyle=\color{codegreen},
  morekeywords = {boolean},
}

\begin{document}
The next code will not be directly imported from a file

\lstset{style=mystyle}

\begin{lstlisting}[escapechar=!]
  import numpy as np
  
  def incmatrix(genl1,genl2):
  m = len(genl1)
  n = len(genl2)
  M = None #to become the incidence matrix
  VT = np.zeros((n*m,1), int)  #dummy variable
  
  #compute the bitwise xor matrix
  M1 = bitxormatrix(genl1)
  M2 = np.triu(bitxormatrix(genl2),1) 
  
  for i in range(m-1):
  for j in range(i+1, m):
  [r,c] = np.where(M2 == M1[i,j])
  for k in range(len(r)):
  VT[(i)*n + r[k]] = 1;
  VT[(i)*n + c[k]] = 1;
  VT[(j)*n + r[k]] = 1;
  VT[(j)*n + c[k]] = 1;
  
  if M is None:
  M = np.copy(VT)
  else:
  M = np.concatenate((M, VT), 1)
  
  VT = np.zeros((n*m,1), int)
  
  return M

  boolean b;
  myboolean c;
  !\color{codegreen}{boolean}! c;

\end{lstlisting}

\begin{lstlisting} 				%%%%%%%%%%% the part of interest %%%%%%%%%%
  boolean b; 					% magenta boolean
\end{lstlisting}				% close for a green boolean
\lstset{style=mystyleforbooleanonly} 		% switch style
\vspace{-\baselineskip}				% join the numbered lines
\begin{lstlisting}[firstnumber=last,name=asdf]	% give the name "asdf" to the listing and resume numbering
  boolean b;					% green boolean
\end{lstlisting}				% close the lstlisting to return to principal style
\lstset{style=mystyle}				% switch style
\vspace{-\baselineskip}				% join the numbered lines
\begin{lstlisting}[name=asdf]			% give the name "asdf" to the listing
  boolean b;					% magenta boolean
\end{lstlisting}				% close the lstlisting for a green boolean
\lstset{style=mystyleforbooleanonly}		% switch style
\vspace{-\baselineskip}				% join the numbered lines
\begin{lstlisting}[name=asdf]			% give the name "asdf" to the listing
  boolean b;					% green boolean
\end{lstlisting}				% close the lstlisting
\end{document}					%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
ebigunso
Posts: 9
Joined: Sat Jul 29, 2017 5:04 pm

Defining new languages for listings package

Post by ebigunso »

Seems like a good enough solution, but on Overleaf, it gives the following error "Package Listings Warning: Text dropped after begin of listing on input line 94." and the part of interest is not shown in the final result.
Also it seems a bit too complicated to use every time I want to color function names blue.

So, to me it seems the other solution with the escapechar works quite well. Not automatic, but still simple enough to use. Thanks for all the help you gave me, it was a big help!

I'll try it out and come back if anything else goes wrong.
thomasb
Posts: 134
Joined: Thu Aug 03, 2017 10:54 am

Defining new languages for listings package

Post by thomasb »

Thanks too, you taught me a lot with your listing things, come back whenever you want...
Post Reply