0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Crystalの構文彩色を使ってみる

0
Last updated at Posted at 2026-12-01

ふふ、今の私は余裕があるので何と……年末に記事を二つも書いちゃいます!1

この記事では、Crystalの標準ライブラリにあるCrystal::SyntaxHighlighterを使って構文彩色(シンタックスハイライト)してみます。

SyntaxHighlighterとは

SyntaxHighlighterは抽象クラスで、それ自体を使うものではありません。配下にColorizeとHTMLがあって、前者は端末での綺麗な表示が、後者はHTMLでの色が塗られた表示が手に入ります。たぶん、Crystalの対話的なプロンプトや、CrystalのAPI文書生成に使われていそうな気がします。

試しにCololizeの方を使ってみます。

require "crystal/syntax_highlighter/colorize"

code = File.read("src/getexecpath.cr")
colorized = Crystal::SyntaxHighlighter::Colorize.highlight(code)
puts colorized

ここで使っているのは前日の記事で実装したものです。
これをcrystal run ascii.crとすると、以下のような表示になります。イイネ。

cry.jpg

同様にHTMLの方も使ってみましょう。

require "crystal/syntax_highlighter/html"

code = File.read("src/getexecpath.cr")
html = Crystal::SyntaxHighlighter::HTML.highlight(code)
puts <<-END_HTML
<style>
.c {
  font-style: italic;
  color: gray;
}
.k { font-weight: bold }
.t { color: purple }
.s { color: green }
</style>
<pre><code>#{html}</code></pre>
END_HTML

構文彩色する対象がspanタグで囲まれ、それぞれのタグにcやらkやらのクラス属性が付いています。そのため、CSSをこれらのクラスにあててやればよいわけです。.highlightの出力は<pre><code>の中身にするぶんのみ含まれるため、それで包んでやります。

ヒアドキュメントの書き方に注意。どうやら始めの印は<<-で固定っぽいです。

出力結果の一部
<pre><code><span class="c"># MIT License</span>
<span class="c">#</span>
<span class="c"># Copyright (c) 2026 gemmaro &lt;gemmaro.dev@gmail.com&gt;</span>
[...]
<span class="c"># SOFTWARE.</span>

<span class="k">module</span> <span class="t">Getexecpath</span>
  <span class="t">VERSION</span> <span class="o">=</span> <span class="s">&quot;0.1.0&quot;</span>
  <span class="t">PATH_MAX</span> <span class="o">=</span> <span class="n">1024</span> <span class="c"># see &lt;sys/syslimits.h&gt;</span>
[...]

これも実行してHTMLファイルに保存し、ローカルサーバでも立てて見てみれば次の通り。ええやん。

html.png

LaTeX経由、PDF行き

さて、ここでめでたくしてしまっていいのですが……。

せっかくなのでColorizeやHTMLがどう実装されているのか見てみます。HTMLの方を見てみますと、SyntaxHighlighter抽象クラスから継承して具体的な実装をしているようです。必須のメソッドはrenderから始まるもののようです2。

ではHTMLの見様見真似でLaTeX用の出力を書いてみましょう。書いたものがこちらです(お手軽3分コーディング)。

require "crystal/syntax_highlighter"

class Crystal::SyntaxHighlighter::LaTeX < Crystal::SyntaxHighlighter
  def self.highlight(io : IO, code : String)
    new(io).highlight(code)
  end

  def self.highlight(code : String)
    String.build do |io|
      highlight(io, code)
    end
  end

  def initialize(@io : IO)
  end

  def render(type : TokenType, value : String)
    case type
    when .comment?
      span "c" { ::LaTeX.escape(value, @io) }
    when .number?
      span "n", &.print value
    when .char?
      span "s" { ::LaTeX.escape(value, @io) }
    when .symbol?
      span "n" { ::LaTeX.escape(value, @io) }
    when .const?
      span "t" { ::LaTeX.escape(value, @io) }
    when .string?
      span "s" { ::LaTeX.escape(value, @io) }
    when .ident?
      span "m" { ::LaTeX.escape(value, @io) }
    when .keyword?, .self?
      span "k", &.print value
    when .primitive_literal?
      span "n", &.print value
    when .operator?
      span "o" { ::LaTeX.escape(value, @io) }
    else
      ::LaTeX.escape(value, @io)
    end
  end

  def render_delimiter(&)
    span "s" do
      yield
    end
  end

  def render_interpolation(&)
    span_end
    span "i", &.print "\\\#{"
    yield
    span "i", &.print "}"
    span_start "s"
  end

  def render_string_array(&)
    span "s" do
      yield
    end
  end

  private def span(klass, &)
    span_start klass
    yield @io
    span_end
  end

  private def span_start(klass)
    @io << %(\\highlight#{klass}{)
  end

  private def span_end
    @io << "}"
  end
end

module LaTeX
  def self.escape(value, io)
    value.each_char do |char|
      io << ({'#' => "\\#", '_' => "\\_", ' ' => "\\hspace*{1em}"}[char]? || char.to_s)
    end
  end
end

code = File.read("src/getexecpath.cr")
latex = Crystal::SyntaxHighlighter::LaTeX.highlight(code)
puts latex

メソッドに&を取れるのは現代的なRubyにもある要素ですが、case ... whenの.comment?などが面白い見た目。TokenTypeにわらわらインスタンスメソッドが生えているので、そういうことなんですね(完全理解)。
なお、メソッド定義のパラメータのところでインスタンス変数を設定できることはけっこう前から知ってました。

LaTeXのエスケープは、今回必要なものだけ応急処置しています。本当はかなり面倒です3。それ以外はだいたいHTML版の引き写しといって差し支えないでしょう。

細かいところですが、{...}[char]?のようにしているところは、Hashの[]?インスタンスメソッドを使っています。[]だとキーが存在せず、かつ既定値が設定されていなければKeyErrorになる仕様のためです。

これを実行すると部分的なLaTeXの原稿が吐き出されます。次のような感じです。

\highlightc{\#\hspace*{1em}MIT\hspace*{1em}License}
\highlightc{\#}
\highlightc{\#\hspace*{1em}Copyright\hspace*{1em}(c)\hspace*{1em}2026\hspace*{1em}gemmaro\hspace*{1em}<gemmaro.dev@gmail.com>}
\highlightc{\#}
\highlightc{\#\hspace*{1em}Permission\hspace*{1em}is\hspace*{1em}hereby\hspace*{1em}granted,\hspace*{1em}free\hspace*{1em}of\hspace*{1em}charge,\hspace*{1em}to\hspace*{1em}any\hspace*{1em}person\hspace*{1em}obtaining\hspace*{1em}a\hspace*{1em}copy}
\highlightc{\#\hspace*{1em}of\hspace*{1em}this\hspace*{1em}software\hspace*{1em}and\hspace*{1em}associated\hspace*{1em}documentation\hspace*{1em}files\hspace*{1em}(the\hspace*{1em}"Software"),\hspace*{1em}to\hspace*{1em}deal}
[...]
\highlightc{\#\hspace*{1em}SOFTWARE.}

\highlightk{module}\hspace*{1em}\highlightt{Getexecpath}
\hspace*{1em}\hspace*{1em}\highlightt{VERSION}\hspace*{1em}\highlighto{=}\hspace*{1em}\highlights{"0.1.0"}
\hspace*{1em}\hspace*{1em}\highlightt{PATH\_MAX}\hspace*{1em}\highlighto{=}\hspace*{1em}\highlightn{1024}\hspace*{1em}\highlightc{\#\hspace*{1em}see\hspace*{1em}<sys/syslimits.h>}
[...]

力技で空白をエスケープしていて、いかつい見てくれですが致し方なし。\highlightホニャララのコマンドが見た目を変えるべき区域です。

これを本体の原稿index.texから取り込んでやります。
※\obeylinesは引っ張りだしてきたTeXBookから拾ってきたら動いたものです。それで\obeyspacesも使ってみようとしましたが、字下げにならなかったので、しぶしぶ上の\hspaceにしたという次第です。

\documentclass[paper=a4paper]{jlreq}
\newcommand{\highlightc}[1]{\textit{#1}}
\newcommand{\highlightk}[1]{\textbf{#1}}
\newcommand{\highlightt}[1]{#1}
\newcommand{\highlighto}[1]{#1}
\newcommand{\highlightn}[1]{#1}
\newcommand{\highlights}[1]{#1}
\newcommand{\highlighti}[1]{#1}
\newcommand{\highlightm}[1]{#1}
\setlength{\baselineskip}{2pt}
\begin{document}
\begingroup\ttfamily\obeylines
\include{code}
\endgroup
\end{document}

ここではコメントとキーワードだけ見た目を変えて、横着しています。それでもコンパイルした結果はそれっぽいものです。おお。

tex.jpg

ここが某動画サイトなら「ちょうど切らしてた」「卒論に使う」とか流れてるでしょうね4。卒論でCrystalを使う猛者は、はたしているのでしょうか……?

以上

この記事は以上です。

使用許諾

Copyright (C) 2026 gemmaro

Copying and distribution of this file, with or without modification,
are permitted in any medium without royalty provided the copyright
notice and this notice are preserved. This file is offered as-is,
without any warranty.

  1. 二つも!? ↩

  2. すっぽかしてrender_delimiterなどを横着しようとしたらコンパイラに止められました。 ↩

  3. 今年、Ren'PyのファイルからLaTeX経由でPDFを生成する必要があったのですが、これがまあまあ手間でした。 ↩

  4. まあ、(定番のlistingsパッケージにはないようですが)pygmentsにCrystalの定義はあるのでmintedパッケージで対応できそうですが。 ↩

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?