[Tex/LaTex] Problem with special characters in listings

characterslistings

I'm having problems with my TeX document. I'm trying to import my java file in listings to get syntax colouring and stuff. My java files contains comments in Danish, which means they contain special characters (æ, ø and å). I managed to view those by adding \lstset{inputencoding=utf8, extendchars=\true} to my premable. even though I can see the characters in my document, it still isn't right. The syntax colouring isn't applied to the special characters and they aren't in the right place in the words. You can see an example here:

enter image description here

It's supposed to say "…du fortsætte med at åbne programmet?…"

It's like the special characters jump to the beginning of the word and then the syntax colouring isn't applied.

Hope someone is able to help.. Thanks..

EDIT

I got it working by using ansinew charset in stead of using UTF8 as inputenc.
This is exactly how I did:

\documentclass[a4paper,oneside]{memoir}
\usepackage{ucs}
\usepackage[utf8]{inputenc}
\usepackage[danish]{babel}
\usepackage[T1]{fontenc} 
\usepackage{listings}
\lstset{literate=%
{æ}{{\ae}}1
{å}{{\aa}}1
{ø}{{\o}}1
{Æ}{{\AE}}1
{Å}{{\AA}}1
{Ø}{{\O}}1
}
\lstset{extendedchars=\true}
\lstset{inputencoding=ansinew}

\begin{document}
\begin{lstlisting}
public class Main
{
    public Main(String args[])
    {
        // Java logic
    }
}
\end{lstlisting}
\end{document}

Best Answer

This thread at stackoverflow should help. Assuming you can't convert the document away from UTF-8, the simplest method appears to be treating the UTF-8 characters as literate programming.

There's also a listingsutf8 package, but that will only work for external files pulled in through \lstinputlisting, not for code defined directly in the .tex file.

Related Question