I need to add a JSON snippet that contains a few Japanese characters to my document. I'm able to use Japanese characters using CJK package and highlight my code using minted or lstlistings, but is there any way to use Japanese characters inside the highlighted code?
Asked
Active
Viewed 767 times
1 Answers
4
Pygments support Unicode well, you don't need special settings for that. Anyway, you should know how to use Japanese in LaTeX first. See How to write Japanese with LaTeX?
Both luatexja and (racent version of) xeCJK support listings package well. But with old CJK package, listings is much more difficult to use and is only partially supported.
BTW, there is no javascript language predefined in listings package. A previous question language option supported in listings may help. In the following examples I use Java instead for simplicity.
LuaLaTeX
LuaLaTeX with luatexja package is preferred.

% !TeX program = LuaLaTeX
% !TeX encoding = UTF-8
\documentclass{article}
\usepackage{xcolor}
\usepackage{luatexja-fontspec}
\setmainjfont{IPAexMincho} % A high quality Japanese font preinstalled in TeX Live
\usepackage{listings}
\lstset{
basicstyle=\ttfamily,
keywordstyle=\color{blue},
stringstyle=\color{purple},
}
\begin{document}
\begin{lstlisting}[language=Java]
if (b == true)
s = "日本語";
\end{lstlisting}
\end{document}
XeLaTeX
% !TeX program = XeLaTeX
% !TeX encoding = UTF-8
\documentclass{article}
\usepackage{xcolor}
\usepackage{xeCJK}
\setCJKmainfont{IPAexMincho}
\usepackage{listings}
\lstset{
basicstyle=\ttfamily,
keywordstyle=\color{blue},
stringstyle=\color{purple},
}
\begin{document}
\begin{lstlisting}[language=Java]
if (b == true)
s = "日本語";
\end{lstlisting}
\end{document}
pdfLaTeX
Using CJK package, we can use Japanese characters properly in the code if we escape to LaTeX.
% !TeX program = pdfLaTeX
% !TeX encoding = UTF-8
\documentclass{article}
\usepackage{xcolor}
\usepackage{CJKutf8}
\usepackage{listings}
\lstset{
extendedchars=false,
basicstyle=\ttfamily,
keywordstyle=\color{blue},
stringstyle=\color{purple},
}
\begin{document}
\begin{CJK*}{UTF8}{ipxm}
\begin{lstlisting}[language=Java,escapechar=\#]
if (b == true)
s = "#日本語#"; // No syntax highlighting anyway
\end{lstlisting}
\clearpage\end{CJK*}
\end{document}
-
Thanks! I tried doing the pdflatex escape thing before but it didn't work, but your example works. Not sure what I was doing wrong. Thanks a lot! – stan May 17 '14 at 19:28