最終更新日 2025-04-15

HmTextToHtml (テキスト変換のミニマムサンプル)

概要

最新(2025年)の秀丸では、テキストの変換と画面への反映が非常に早くなっています。

秀丸で編集中のテキスト内容を「HTML ESCape」して範囲。

gettotaltext()で全体のテキストを取得 → テキスト整形 → settotaltext(...)で全体のテキストを上書き

全体のテキストを取得するには、gettotaltext()を使用します。
全体のテキストを上書きするには、settotaltext(...)を使用します。

テキスト整形は、秀丸の関数は原則利用せず、JavaScriptの replace等、正規表現等で行います。

実はこれこそが、これが高速変換・高速表示の黄金パターンです。

getselectedtext()で選択中のテキストを取得 → テキスト整形 → insert(...)で選択中のテキストを上書き

選択中のテキストの場合は、getselectedtext() と insert(...) を対で使うのが王道です。

加工にGUI操作を入れるべきではない

文字列を加工するのに、GUIの操作(カーソルが次へ行ったり、下に行ったり、次の検索語をサーチしたり)といったことはやめましょう。
異常に動作が遅くなります。
disabledraw 程度では解決しません。
文字列加工は「文字列」としてプログラムするべきであって、秀丸の編集エリアの操作で加工するものではありません。

HmTextToHtml.mac
jsmode "WebView2\\" + currentmacrofilename;

js {

function escapeHtml(text) {
    const escapeMap = {
        '&': '&',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#039;'
    };

    // エスケープ対象の文字をキーとして持つ正規表現を自動生成
    const escapeChars = Object.keys(escapeMap).join('');
    const escapeRegex = new RegExp(`[${escapeChars}]`, 'g');

    let count = 0;

    const escapedText = text.replace(escapeRegex, (match) => {
        count++;
        return escapeMap[match];
    });

    return {
        escapedText,
        count
    };
}

// エラーメッセージ用
function writeOutputPane(msg) {
    let dll = loaddll("HmOutputPane.dll");
    dll.dllFunc.Output(hidemaru.getCurrentWindowHandle(), msg + "\r\n");
}

function main() {
    if (selecting()) {
        const targetText = getselectedtext();
        if (targetText) {
            let escapedHtmlObj = escapeHtml(targetText);

            insert(escapedHtmlObj.escapedText);
            writeOutputPane(escapedHtmlObj.count + "個を置き替えました。");
        }
    } else {
        const targetText = gettotaltext();
        if (targetText) {
            let {escapedText, count} = escapeHtml(targetText);

            settotaltext(escapedHtmlObj.escapedText);
            writeOutputPane(escapedHtmlObj.count + "個を置き替えました。");
        }
    }
}

main();
}