Your problem is not really listing related; you’ll get the error outside of a listing as well. The point is that Latex simply does not understand how to display the unicode characters.
With math characters, this would be easy to solve, however, because of the moreverb
environment, you cannot use math directly inside the listing. Luckily, the inputenc
package gives you a way out. You need to explicitly tell Latex, how it should render unknown utf8 characters.
\documentclass[11pt]{article}
\usepackage[utf8]{inputenc}
\usepackage{amsmath}
\usepackage{verbatim}
\usepackage{moreverb}
\DeclareUnicodeCharacter{03A3}{\ensuremath{\Sigma}}
\DeclareUnicodeCharacter{2208}{\ensuremath{\in}}
%% or simply use the newunicodechar package
%% which does the same without the need of remembering numbers:
% \usepackage{newunicodechar}
% \newunicodechar{Σ}{\ensuremath{\Sigma}}
% \newunicodechar{∈}{\ensuremath{\in}}
\begin{document}
∈ Σ
\begin{listing}{1}
test = 2 ∈ s
\end{listing}
\begin{listing}{1}
sum = Σ(s)
\end{listing}
\end{document}
Edit: Changed to use \ensuremath
instead of $..$
Edit 2: Added code for the newunicodechar package
Note: You are not restricted to use math mode. You may as well change to another font which includes the needed character somewhere and use it directly.
One way to get around this limitation of listings
is to use the option extendedchars=true
and then to use the literate
option for each accents you're going to be using (it's a bit tedious to do, but once you've done all the accents of your language, you never have to worry about them again). The syntax is
literate={á}{{\'a}}1 {ã}{{\~a}}1 {é}{{\'e}}1
For each accent you must put the real character inside braces (e.g. {á}
) then you put what you want this character to be inside double braces (e.g. {{\'a}}
) and finally you put the number one (1
); between two entries, you can put a space for clarity.
Here's your example modified to use this:
\documentclass[12pt,a4paper]{scrbook}
\KOMAoptions{twoside=false,open=any,chapterprefix=on,parskip=full,fontsize=14pt}
\usepackage[portuguese]{babel}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{listings}
\usepackage{xcolor}
\usepackage{inconsolata}
\lstset{
language=bash, %% Troque para PHP, C, Java, etc... bash é o padrão
basicstyle=\ttfamily\small,
numberstyle=\footnotesize,
numbers=left,
backgroundcolor=\color{gray!10},
frame=single,
tabsize=2,
rulecolor=\color{black!30},
title=\lstname,
escapeinside={\%*}{*)},
breaklines=true,
breakatwhitespace=true,
framextopmargin=2pt,
framexbottommargin=2pt,
inputencoding=utf8,
extendedchars=true,
literate={á}{{\'a}}1 {ã}{{\~a}}1 {é}{{\'e}}1,
}
\begin{document}
\begin{lstlisting}
<?php
echo 'Olá mundo!';
print 'áãé';
\end{lstlisting}
\end{document}
Best Answer
I see nothing strange with
The input
produces