[Tex/LaTex] comment.sty and UTF8 encoding

commentsunicode

I noted that if I use comment.sty and a there is a block of text containing UTF8 characters inside a comment environment, the compilation aborts!

Minimal Example

\documentclass{article}
\usepackage[T1]{fontenc}
\RequirePackage[utf8]{inputenc}%this file is stored as UTF8 file!
\RequirePackage{comment}
\specialcomment{privateSolution}
    {\begingroup\itshape\noindent\textbf{Solution}\\}
    {\endgroup}
%\excludecomment{privateSolution}%Use it to remove solutions!

\begin{document}
\title{Comment.sty and UTF8 test file}
\maketitle
\section{UTF8 character test}
In which alphabet characters àìùòè are common?
\begin{privateSolution}
    The Italian alphabet contains àìùòè.
\end{privateSolution}

\begin{comment}
    The Italian one! It contains àìùòè.
\end{comment}
\end{document}

Has anyone the same problem?
Any workaround?

Thanks in advance.

Best Answer

The problem is in how comments.sty writes out files; when you input à, it is interpreted during a \write and it becomes the character corresponding to à in the T1 encoding.

Solution: modify \ThisComment to write out uninterpreted commands.

\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}%this file is stored as UTF8 file!
\usepackage{comment}

\renewcommand\ThisComment[1]{%
  \immediate\write\CommentStream{\unexpanded{#1}}%
}

\specialcomment{privateSolution}
    {\itshape\noindent\textbf{Solution}\\}
    {}
%\excludecomment{privateSolution}%Use it to remove solutions!

\begin{document}
\title{Comment.sty and UTF8 test file}
\maketitle
\section{UTF8 character test}
In which alphabet characters àìùòè are common?
\begin{privateSolution}
    The Italian alphabet contains àìùòè.
\end{privateSolution}

\begin{comment}
    The Italian one! It contains àìùòè.
\end{comment}
\end{document}

A completely different solution using environ:

\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}%this file is stored as UTF8 file!
\usepackage{environ}

\newif\ifsolution
\NewEnviron{privateSolution}{%
  \ifsolution
    \par\noindent\textbf{\textit{Solution}}\\
    \BODY
  \fi
}
%\solutiontrue % Uncomment it to print solutions!

\begin{document}
\title{Comment.sty and UTF8 test file}
\maketitle
\section{UTF8 character test}
In which alphabet characters àìùòè are common?
\begin{privateSolution}
    The Italian alphabet contains àìùòè.
\end{privateSolution}

\end{document}
Related Question