2
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?

Smartyのデリミタを<( ゚Д゚) コード ( ゚Д゚)>に設定してVSCodeに適応する

2
Last updated at Posted at 2026-01-18

はじめに

Smartyテンプレートエンジンでは、デリミタ(区切り文字)をカスタマイズできます。

デフォルトは { } ですが、JavaScriptやCSSと競合するため、<!--{ }-->{{ }}などに変更するプロジェクトも多いですよね。しかし、Smartyで設定を変更してもエディタ側で設定された内容を反映できず開発効率が下がってしまいます。

そこで、VSCodeの拡張機能を作成して、開発の効率化を図ろうと思います。
本記事ではSmartyのデリミタを設定し、VSCodeの Ctrl+/ でコメントを挿入できるようにします。

今回は、デリミタを顔文字にしてみようと思います。

<( ゚Д゚)* これはコメントです *( ゚Д゚)>

Smartyでのデリミタの設定

Smarty側の設定は簡単です。

<?php
$smarty = new Smarty();

$smarty->left_delimiter  = '<( ゚Д゚)';
$smarty->right_delimiter = '( ゚Д゚)>';

$smarty->display('template.tpl');

VSCodeの設定

VSCodeで Ctrl+/ を押したときに、設定したデリミタでコメントを挿入できるようにします。

拡張機能の作成

拡張機能は下記のディレクトリに手動で作成します。

OS パス
Windows %USERPROFILE%\.vscode\extensions\
macOS / Linux ~/.vscode/extensions/

フォルダ構成は以下になります。

smarty-custom-comment/
├── package.json
├── extension.js
└── language-configuration.json

package.json

package.json
{
  "name": "smarty-custom-comment",
  "displayName": "Smarty Custom Comment",
  "description": "Custom comment delimiters for Smarty",
  "version": "1.0.0",
  "engines": {
    "vscode": "^1.60.0"
  },
  "categories": ["Programming Languages"],
  "activationEvents": ["onStartupFinished"],
  "main": "./extension.js",
  "contributes": {
    "languages": [
      {
        "id": "smarty-custom",
        "aliases": ["Smarty Custom"],
        "extensions": [".tpl"],
        "configuration": "./language-configuration.json"
      }
    ],
    "configuration": {
      "title": "Smarty Custom Comment",
      "properties": {
        "smartyCustom.leftDelimiter": {
          "type": "string",
          "default": "{",
          "description": "Left delimiter for Smarty tags"
        },
        "smartyCustom.rightDelimiter": {
          "type": "string",
          "default": "}",
          "description": "Right delimiter for Smarty tags"
        }
      }
    },
    "commands": [
      {
        "command": "smartyCustom.applyDelimiters",
        "title": "Smarty: Apply Custom Delimiters"
      }
    ]
  }
}

extension.js

settings.json の設定を読み取り、language-configuration.json を動的に生成します。

コメントデリミタは leftDelimiter + "*""*" + rightDelimiter で自動導出します。

extension.js
const vscode = require('vscode');
const fs = require('fs');
const path = require('path');

function getDelimiters() {
    const config = vscode.workspace.getConfiguration('smartyCustom');
    const left = config.get('leftDelimiter') || '{';
    const right = config.get('rightDelimiter') || '}';
    return {
        commentStart: left + '*',
        commentEnd: '*' + right
    };
}

function writeConfigFile(context) {
    const delimiters = getDelimiters();
    const configPath = path.join(context.extensionPath, 'language-configuration.json');
    
    const config = {
        "comments": {
            "blockComment": [delimiters.commentStart, delimiters.commentEnd]
        }
    };
    
    fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
    return delimiters;
}

function activate(context) {
    // 起動時に設定を適用
    try {
        writeConfigFile(context);
    } catch (e) {
        console.error('Failed to write config:', e);
    }

    // コマンド登録
    const applyCommand = vscode.commands.registerCommand('smartyCustom.applyDelimiters', async () => {
        try {
            writeConfigFile(context);
            const action = await vscode.window.showInformationMessage(
                'Delimiters updated. Reload window to apply.',
                'Reload Now'
            );
            if (action === 'Reload Now') {
                vscode.commands.executeCommand('workbench.action.reloadWindow');
            }
        } catch (e) {
            vscode.window.showErrorMessage('Failed to update: ' + e.message);
        }
    });

    // 設定変更を監視
    const configWatcher = vscode.workspace.onDidChangeConfiguration(e => {
        if (e.affectsConfiguration('smartyCustom')) {
            vscode.window.showInformationMessage(
                'Settings changed. Run "Smarty: Apply Custom Delimiters" to apply.',
                'Apply Now'
            ).then(action => {
                if (action === 'Apply Now') {
                    vscode.commands.executeCommand('smartyCustom.applyDelimiters');
                }
            });
        }
    });

    context.subscriptions.push(applyCommand, configWatcher);
}

function deactivate() {}

module.exports = { activate, deactivate };

language-configuration.json

初期ファイルです(拡張機能起動時に上書きされます)。

language-configuration.json
{
  "comments": {
    "blockComment": ["{*", "*}"]
  }
}

開発プロジェクトの.vscode/settings.jsonを設定する

VSCodeの settings.json に以下を追加します。

settings.json
{
  "files.associations": {
    "*.tpl": "smarty-custom"
  },
  "smartyCustom.leftDelimiter": "<( ゚Д゚)",
  "smartyCustom.rightDelimiter": "( ゚Д゚)>"
}

コメントデリミタは自動で <( ゚Д゚)**( ゚Д゚)> になります。

設定後、コマンドパレット(Ctrl+Shift+P)から「Smarty: Apply Custom Delimiters」を実行し、ウィンドウをリロードします。

拡張機能のファイルを更新した場合は、VSCodeを再起動してください。「Reload Window」では反映されないことがあります。

これで .tpl ファイルを開いて Ctrl+/ を押すと...

顔文字コメントが挿入されます!

Animation1.gif

実用的な設定例

settings.json でデリミタを変更するだけで、任意のコメント形式に対応できます。
実際にはこんな設定になると思います。

settings.json
{
  "files.associations": {
    "*.tpl": "smarty-custom"
  },
  "smartyCustom.leftDelimiter": "{{",
  "smartyCustom.rightDelimiter": "}}"
}
settings.json
{
  "files.associations": {
    "*.tpl": "smarty-custom"
  },
  "smartyCustom.leftDelimiter": "<!--{",
  "smartyCustom.rightDelimiter": "}-->"
}

おわりに

今回は、VSCodeでデリミタを変更する拡張機能を作ってみました。

チームメンバーに顔文字デリミタを提案するかどうかは、自己責任でお願いします。

今回はSmartyのコメントアウト挿入についての内容でしたが、下記プロジェクトでシンタックスハイライトなどを盛り込んだ高機能版を作成中です。興味があればぜひ見てみてください。

ここまで読んで頂きありがとうございました。

2
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
2
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?