Generalcustomizing a code listing environment

LaTeX specific issues not fitting into one of the other forums of this category.
Post Reply
SmithWillSuffice
Posts: 15
Joined: Fri Feb 23, 2007 9:29 am

customizing a code listing environment

Post by SmithWillSuffice »

There was no discussion I could find about numbered environments, so i thought i'd share some experience.

Here's the PROBLEM:
You want a nice looking "Code List" numbered environment, with numbering of the chapter and then the code list, a bit like theorem numbering in AMSLaTeX. You look up CTAN and find a number of nice fancy verbatim style environments, like morevrb, alltt, fancyvrb, and listings. It looks like the listings package is really cool. It is language-aware, so you can have it format C/C++, Perl, Fortran or whatever, using the language keywords and comment syntax to apply special styles, just like your favourite programmers editor would.

The problem is that the caption and numbering used by the listings package is too much like Table numbering. You really want it to be more distinctive. What to do? You could hack a solution perhaps.

SOLUTION 1:
Since I was writing a manual that uses C++, Perl and bash scripts I initially tried the listings package as follows:

Code: Select all

%%
%% My Code List environment (for listing verbatim C++ code)
%%
\usepackage{listings}
\lstloadlanguages{[GNU]C++,Perl,sh}
\lstnewenvironment{listing}[2][]{ \vspace{1ex}\noindent
  \lstset{ basicstyle=\ttfamily, 
           frame=tb, 
           columns=fullflexible,
           framexrightmargin=-.2\textwidth,
           breaklines=true,
           prebreak=/,
           caption=#1,
           label=#2
          } }{ }
Try it, it works! (Oh, you might have to put the #1 or #2 in curly brackets, I forget what I did.) You have these optional arguments for captioning and a label. The label is used for cross referencing using \ref{<label>} as usual for numbered environments. The "framexrightmargin=-.2\textwidth," applies a horizontal rule line up to 1/5 less than the textwidth, you can use a full textwidth or not have a rule line if you desire. It's highly customizable, and I've only shown a few of the listings options. The documentation for the package does a great job in explaining all of the options.

The problems I had with this solution was that (a) I decided I did not much like the syntax highlighting after all (no big problem really, I could just disable it as above with my "basicstyle=\ttfamily," option), and (b) more seriously, I just did not like the look of the captioning. What I really wanted was a distinct looking caption, more like a theorem or definition environment.

SOLUTION 2.:
I decided to just use the AMSLaTeX theorem environments. I defined my custom Code List environment in the peamble just after my theorem, conjecture and definition definitions as follows,

Code: Select all

%
% Theorem-like environments for AMS style packages
%
\newtheorem{theorem}{Theorem}
\newtheorem{conjecture}{Conjecture}
\theoremstyle{definition}
\newtheorem{definition}{Definition}[chapter]
\newtheorem{codelist}{Code Listing}[chapter]
You do not need all of these, just the "\theoremstyle{definition}" and the "\newtheorem{codelist}{Code Listing}[chapter]" lines will suffice for code listing work. To use this definition I just add an extra "\begin{verbatim}...\end{verbatim}" inside my "\begin{codelisting}...\end{codelisting}" environment. I use \label and \ref as usual. Here's an example:

Code: Select all

\begin{codelisting}
\label{c_hellobash}
\begin{verbatim}
#!/bin/bash
# Simple example bash script
echo "Hello $@"
exit
\end{verbatim}
\end{codelisting}
 
So what's the problem now? Well, there's no nice hrule demarcating the code list environment from the main text, and there is no programming language-aware syntax highlighting (if you want it). To remedy this, I used SOLUTION 3.

SOLUTION 3:
(The nice thing about LaTeX is that sometimes TIMTOWODI :-)
What I decided upon was to combine the above use of the AMSLaTeX definition environment with the listings package as my auxiliary verbatim style portion. (Did you know that listings, and I think also alltt and fancyvrb allow word wrapping?) So I used the above "\newtheorem{codelist}{Code Listing}[chapter]" command in the preamble, as well as the above "\lstnewenvironment{listing}[2][]{ \vspace{1ex}\noindent ...." stuff, only to retain the AMSLaTeX captioning style I just deleted the use of the optional arguments for the ""\lstnewenvironment{listing}", thus,

Code: Select all

\newcommand{\singledollar}{$}

\theoremstyle{definition}
\newtheorem{codelist}{Code Listing}[chapter]

\usepackage{listings}
\lstloadlanguages{[GNU]C++,Perl,sh}
\lstnewenvironment{listing}[][]{ \vspace{1ex}\noindent
  \lstset{ basicstyle=\ttfamily, 
           frame=tb, 
           columns=fullflexible,
           framexrightmargin=-.2\textwidth,
           breaklines=true,
           prebreak=/          } }{ }
does the job as far as I'm concerned.

Ideally I'd like to play around a bit more with the language-aware syntax highlighting inside the listings environment. I could use coloring for example. "breaklines=true," and "prebreak=/ " by the way, specify wrapping of long lines and insertion of the "/" character at the end of the broken line, a bit like some automatic code documentation parsers and textbook or code manual typesetters.

Here's the final usage (see Code List~\ref{c_runmyapp}:

Code: Select all

\begin{codelist}[A script for starting an application that uses obscure shared libraries]
\label{c_runmyapp}
\begin{listing}
#!/bin/bash
#
# Bash script to run "myapp" safely with cmd line argument
#
export LD_LIBRARY_PATH=$HOME/lib/myapp
. $HOME/bin/myapp $@
exit
\end{listing}\phantom{$\singledollar} % This just resets my Kile or Emacs editor syntax highlighting
\end{codelist}
OK, one last note. Why the weird "\phantom{$\singledollar}" command???? Can you guess?

Well, I use Kile, which gives me LaTeX/TeX aware syntax highlighting. But the odd number of "$" characters in my non-verbatim "listing" environment stuffs up the syntax highlighting, since Kile is not that smart that it knows about the rules for this obscure listings package, i.e., Kile (and probably your emacs, or vi,or Kate, or Alpha, or other LaTeX editor) will get tripped up because it doesn't know that a \begin{listing}...\end{listing} environment should have verbatim style highlighting. I guess if I knew how to configure Kile correctly i could fix this by making Kile aware of how to highlight the new "listing" environment. But I haven't looked into that yet, so the \phantom" command is just a kludge to get an extra invisible "$" character so that at least outside the "listing" environment I recover nice Kile editor highlighting for my sanity. If I can't configure Kile I know I can configure emacs, it's just a pain to read up on how to do it.

That's all for today. If I can figure out how to tailor Kile syntax highlighting I'll post it to the forum's "LaTeX Editors->Kile" board, unless someone beats me to it (please do!).
Support Free Software---It's Made for Everyone

Recommended reading 2024:

LaTeXguide.org • LaTeX-Cookbook.net • TikZ.org
LaTeX Beginner's Guide LaTeX Cookbook LaTeX TikZ graphics TikZによるLaTeXグラフィックス
SmithWillSuffice
Posts: 15
Joined: Fri Feb 23, 2007 9:29 am

customizing a code listing environment

Post by SmithWillSuffice »

okeedokee, that was painless!

Here's how to avoid the annoying prior necessity for the "\phantom{$\singledollar}" command used in the previous post to reset Kile syntax highlighting after using an odd number of "$" characters inside a quasi-verbatim style custom environment.

Find your "latex.xml" syntax highlighting rules for Kile. On my system they were located in my Kate highlighting rules directory:

Code: Select all

$HOME/.kde/share/apps/katepart/syntax/latex.xml
open that file and do a search on "verbatim". In fact do a search&replace: e.g., in vi do,

Code: Select all

:g/verbatim|/s//verbatim|listing|/g
you should of course substitute the environment name of your own custom environment inherited from listings. I named my environment "listing" which is why I replaced "verbatim|" with "verbatim|listing|"

The "|" is of course an "OR" operator, the changes should just tell Kate or Kile to use the same syntax highlighting for my "\begin{listing}...\end{listing}" blocks as it does for "\begin{verbatim}...\end{verbatim}". Now can remove the annoying \phantom command, and all is fine in my editor. I guess it'll fix KWrite as well, thanks KDE folks, you're the best!

PS.
You'll have to repeat the custom syntax highlighting if you subsequently decide to update you syntax highlighting rules from http://www.kde.org, since they'll presummably overwrite your local edits to your "latex.xml" file!!!

I also assume something very similar is possible using the Lisp code customizations for emacs. I do not know about vi, who's using vi to edit LaTeX anyway? :-)
Last edited by SmithWillSuffice on Fri Apr 13, 2007 9:45 am, edited 1 time in total.
Support Free Software---It's Made for Everyone
SmithWillSuffice
Posts: 15
Joined: Fri Feb 23, 2007 9:29 am

customizing a code listing environment

Post by SmithWillSuffice »

ADDENDUM:
Recent KDE installations may have "boxedverbatim" environment syntax highlighting, so the above vi replacement will give a spurious extra "boxedverbatim|listing" piece of text. Either remove it afterward or change the search&replace command accordingly so that it is not so indiscriminate.
Support Free Software---It's Made for Everyone
Post Reply