살아가는 이야기

LaTeX의 lstlisting 환경에서 한글 쓰기 본문

컴퓨터, 풀어그림

LaTeX의 lstlisting 환경에서 한글 쓰기

우균 2020. 12. 4. 03:59

LaTeX의 lstlisting 환경은 그야말로 삽입 코드 작성의 최강자라고 할 수 있다. \usepackage{courier}와 함께 쓰면 정말 예쁜 코드를 LaTeX에서 쓸 수 있다. 그러나 한 가지 단점은 한글이 원활하지 않다는 점이다.

현재 lstlisting 환경에서 한글을 쓰려면 lstlisting 환경에서 다시 LaTeX 환경으로 잠시 나갔다 들어오는 방법밖에는 없다. 다행히 나감문자(escape character)를 마음대로 정할 수 있는데, 자신의 코드에서 연산자로 사용하지 않는 코드를 쓰면 된다. 예를 들어, 다음 코드는 역따옴표(backquote, `)를 나감문자로 활용한 예이다.

\begin{lstlisting}[escapeinside=``]
import java.util.Scanner;

// This is a program caclulating a share `평균 계산 프로그램`
public class Share {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        double share = 1.0 / a;
        System.out.printf("%.2f%n", share);
        sc.close();
    }
}
\end{lstlisting}

실행한 결과는 아래 그림과 같다.

lstlisting에서 나감문자를 활용하여 한글을 입력한 결과

아쉽게도 커멘트의 색상과 달라지는 한계가 있다. 위 결과는 프리앰블에 pgreen 색상을 다음과 같이 정의하고

\usepackage{color}
\definecolor{pblue}{rgb}{0.13,0.13,1}
\definecolor{pgreen}{rgb}{0,0.5,0}
\definecolor{pred}{rgb}{0.9,0,0}

이를 lstlisting에서 사용하도록 다음과 같이 설정한 결과이다.

\usepackage{listings}
\lstset{language=Java,
	numbers=left, numberstyle=\small, numbersep=8pt, 
	frame=single,
	showspaces=false, showstringspaces=false,
	showtabs=false, breaklines=true, showlines=true
	showstringspaces=false,
	breakatwhitespace=true,
	commentstyle=\color{pgreen},
	keywordstyle=\color{pblue},
	stringstyle=\color{pred},
	basicstyle=\ttfamily\footnotesize
}

그런데 단순히 나감문자만 활용하면 이러한 색상이 반영되지 않는다는 한계가 있다.

이를 해결하려면 색상까지 반영되도록 명령어를 써야 한다. 즉 다음과 같이 작성하면 된다.

\begin{lstlisting}[escapeinside=``]
import java.util.Scanner;

// This is a program caclulating a share `\textcolor{pgreen}{평균 계산 프로그램}`
public class Share {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        double share = 1.0 / a;
        System.out.printf("%.2f%n", share);
        sc.close();
    }
}
\end{lstlisting}

그럼 다음과 같이 주위와 어울리는 한글이 나오는 것을 확인할 수 있다.

lstlisting에서 나감문자와 더불어 \textcolor를 활용하여 한글을 입력한 결과

번거롭지만 lstlisting이 바뀔 때까지는 이렇게 쓰는 방법뿐인 듯하다. 

Comments