0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

LuaLaTeXで特定のテキスト(マクロ)の文字数を自動カウントして変数に格納・再利用する方法

0
Posted at

概要

LaTeXでレポートや論文を書く際、「特定の章や指定したテキストの文字数を自動カウントし、その数値を別のマクロの引数として渡したい」というケースがあります。
従来の pdfLaTeXpLaTeX でこれをやろうとすると、日本語(マルチバイト文字)のカウントがバイト単位になってしまったり、補助ファイル(.aux)を経由する必要があったりと非常に面倒です。

この記事では、LuaLaTeX のLuaエンジンを活用し、日本語の文字数を正確にカウントしてLaTeXのマクロ(変数)に動的に格納するスマートな方法を紹介します。

テスト

Screenshot 2026-06-19 at 20.15.46.png

実装コード

\documentclass{ltjsarticle}
\usepackage{luacode}

% -----------------------------------------------------------------
% 1. Lua側の処理:文字数をカウントしてLaTeXマクロに保存する
% -----------------------------------------------------------------
\begin{luacode*}
function count_and_store(text, macro_name)
    -- utf8.len で日本語(UTF-8)の文字数を正確にカウント
    local len = utf8.len(text)
    -- カウントした数値を、指定された名前のLaTeXマクロとして定義
    token.set_macro(macro_name, tostring(len))
end
\end{luacode*}

% -----------------------------------------------------------------
% 2. LaTeX側のインターフェース
% -----------------------------------------------------------------
\newcommand{\CountWords}[2]{%
    % #1: カウントしたいテキスト(マクロも可)
    % #2: 格納するマクロ名(バックスラッシュなし)
    
    % \edef を使って、引数のマクロを完全に展開してからLuaに渡すのがポイント
    \edef\expandedtext{#1}%
    \directlua{count_and_store([=[\expandedtext]=], "#2")}%
}

% -----------------------------------------------------------------
% 3. カウントした数値を引数として受け取るマクロ(例)
% -----------------------------------------------------------------
\newcommand{\MyTargetMacro}[2]{%
    % #1: 文字数(変数), #2: 本文テキスト
    \noindent\textbf{[文字数: #1字]}\\[0.5em]
    #2
}

% -----------------------------------------------------------------
% 本文
% -----------------------------------------------------------------
\begin{document}

% カウントしたいテキストをマクロに格納
\newcommand{\mytext}{これはテストの文章です。文字数を自動でカウントします。}

% \mytext の文字数をカウントし、「MyCount」というマクロに結果を格納
\CountWords{\mytext}{MyCount}

% 格納した \MyCount を引数として別のマクロに渡す
\MyTargetMacro{\MyCount}{\mytext}

\end{document}
0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?