This answer (and other answers on this page) applies to pdflatex engine only. For other engines, see the linked question above.
This method is not really recommended for non-TeX-expert. In other words if you don't understand what this solution does, use the other solutions for clarity.
Recall that in pdflatex, the purpose of inputenc (utf8) package is to provide a mapping such as á
→ \'a
. It would be rather redundant to provide it manually.
Instead, it's possible to access the mapping defined by utf8
inside the mapping itself.
The trivial way, specify value such as {á}{{á}}1
does not work because listings
package redefines the meaning of the active characters in range 128-255 to do other things.
Instead, we can access the internal place that inputenc stores the definition: the control sequence named \u8:⟨the character in UTF8 encoding⟩
. (note that this is internal implementation detail of the package, as such it's subject to change; nevertheless this particular part of the code is rather unlikely to change)
Example
\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}
\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=
{á}{{\csname u8:\detokenize{á}\endcsname}}1
{ã}{{\csname u8:\detokenize{ã}\endcsname}}1
{é}{{\csname u8:\detokenize{é}\endcsname}}1
,
}
\begin{document}
\begin{lstlisting}
<?php
echo 'Olá mundo!';
print 'áãé';
\end{lstlisting}
\end{document}
I don't think the algorithm that the listings
package use is efficient enough to handle every Unicode characters defined by LaTeX, so stick with defining only used characters. (Pre-parsing the whole file to see which Unicode characters are used is also an option.)
One disadvantage of this method is that it will silently ignore Unicode characters that LaTeX does not define.
listings
manual (page 14) : Similarly, if you are using UTF-8 extended characters in a listing, they must be placed within an escape to LATEX.