最終更新日 2025-02-18

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) {
    let count = 0;

    const escapeChar = (chr) => {
        switch (chr) {
            case '&': count++; return "&";
            case '<': count++; return "&lt;";
            case '>': count++; return "&gt;";
            case '"': count++; return "&quot;";
            case "'": count++; return "&#039;";
            default: return chr;
        }
    };

    let escapedText = text.split('').map(escapeChar).join('');

    return {
        escapedText,
        count
    };
}

if (selecting()) {
    const targetText = getselectedtext(); // 取得
    if (targetText) {
        let escapedHtmlObj = escapeHtml(targetText); // 加工

        insert(escapedHtmlObj.escapedText); // 上書き
        writeOutputPane(escapedHtmlObj.count + "個を置き替えました。");
    }
} else {
    const targetText = gettotaltext(); // 取得
    if (targetText) {
        let escapedHtmlObj = escapeHtml(targetText); // 加工

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

}

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



}