Tuesday, April 20, 2010

LaTeX: Lstinline and Hyphenations

I really like the LaTeX listing package. However, there is one serious problem: Hyphenations are not supported (Option breakline does not break words)! Fortunately I found a solution which is not 100% perfect, but almost (let's say 99% ;-) ). The idea is to use the replacement feature of listings in combination with the discretionary command. Actually, this is not my idea, its Andrei Alexandrescu's idea. I slightly modified his solution. So, here it is. Actually I define a new command for inline Java code -- you may do this using a style, but I prefer this one:
newcommand{\lstJava}[1]{\lstinline[language=Java,breaklines=true,mathescape,literate={\-}{}{0\discretionary{-}{}{}}]§#1§}
As '§' is rarely used in Java, I use this character as code delimiter in lstinline. Also, '$' is seldom found in Java code, so I activate mathescape by default as I use it from time to time (that is, more often then '$' in Java). Now, the trick is the literate option. It is used to replace a string in the code with another given string. So, the well known \- - command (telling LaTeX where to hyphenate a word) is replaced here! And it is replaced by the \discretionary command. This one tells LaTeX, how to hyphenate a word, which is especially useful in German writings, where "ck" becomes "k-k". We use this command here to output the hyphen only when necessary. With this command, hyphenation is working within lstinline -- however you will have to mark it manually.
Let's have a look at a rather long Java class, called \lstJava{ThisIsA\-VeryLong\-ClassName}.

1 comment:

Jan said...

Thx a lot. This is exactly what I've searched for.