본 게시글은 Latex에 코드 블럭을 삽입하는 코드에 대해 소개한다.
이 게시글은 Latex를 overleaf 상에서 사용하고 있으며, 삽입하고자 하는 코드는 R로 작성된 언어이다.
하지만, R 처럼 커스텀만 했을 뿐 다른 프로그래밍 언어에도 모두 적용 가능하다.
1. package 추가 및 mystyle 설정
필수적으로 필요한 package는 "listings"와 "color"이다.
아래의 코드를 통해, Latex에서 삽입한 코드 블럭이 R과 비슷하게 되도록 설정해 보았다.
\usepackage{listings}
\usepackage{color}
\definecolor{codegreen}{rgb}{0,0.6,0} % 프로그래밍시 볼 수 있는 그 초록색입니다.
% Define a custom style
\lstdefinestyle{mystyle}{
backgroundcolor=\color{white}, % 배경색 지정 (흰색 선호)
commentstyle=\color{codegreen}, % 주석의 글자 색 지정
keywordstyle=\color{blue}, % 키워드의 글자 색 지정
stringstyle=\color{codegreen}, % 문자열의 글자 색
basicstyle=\ttfamily\footnotesize, % 글자 스타일 (작고 굵어짐)
breaklines=true, % 자동 line breaking
captionpos=b, % 코드 블럭의 제목 위치
numbers=left, % 코드 줄 넘버 표시 (왼쪽)
keepspaces=true }
\lstset{style=mystyle}
단, 키워드의 경우 Latex에서 인식하는 키워드와 R에서 인식하는 키워드 사이의 차이가 있는 것을 확인할 수 있다.
필요에 따라 아래 두 옵션을 사용해 키워드 인식에서 삭제하고자 단어를 입력하거나, 새롭게 인식할 키워드를 추가할 수 있다.
deletekeywords={...}
morekeywords={*,...}
본문에서 다루지 않은 상세 옵션은 아래의 문서를 참고할 수 있다.
LaTeX/Source Code Listings - Wikibooks, open books for an open world
From Wikibooks, open books for an open world Jump to navigation Jump to search There are many packages providing code listings and highlighting, below are most popular: listings considered slightly outdated due to lacking maintenance, but still very useful
en.wikibooks.org
2. 본문에 코드 블럭 삽입
lstlsting을 통해, 코드 블럭을 원하는 자리에 삽입할 수 있다.
caption은 제목, label은 해당 코드블럭을 참조할 때 사용가능 한 이름 (\ref {lst:R_example}로 참조 가능), language가 설정 가능하다.
\begin{} ~ \end{} 사이에 삽입하고자 하는 코드를 입력하면 된다.
\begin{lstlisting}[caption=R example, label={lst:R_example}, language=R]
# Figure 3.1 and Example 3.10
par(mfrow=c(2,2))
x <- c(0.88,1.07,1.27,1.54,1.91,2.27,3.84,4.5,4.64,9.41)
n<- length(x)
# likelihood function
mu <- seq(0.1, 7, length=500)
sigma <- seq(0.1, 6, length=500)
loglik <- function(mu,sigma){
a<- -n/2*log(sigma^2) - (sum(x^2) - 2*mu*sum(x) + n*mu^2)/(2*sigma^2)
return( -a )
}
\end{lstlisting}
3. 최종 출력 확인
최종 출력물은 다음과 같다.
'For Graduate Student > Latex' 카테고리의 다른 글
[Latex] 참고문헌 관리 bibtex 사용법 1. Bib파일 자동 생성 (1) | 2023.12.20 |
---|---|
Overleaf Professional Plan 무료로 사용하기 - IEEE 연결, 협업 (2) | 2023.10.02 |