「Highlighting Code Block」にDart言語を追加する方法

業務効率化

WordPressのプラグイン「Highlighting Code Block」にデフォルト以外の言語を追加する方法をご紹介します。コードにカラーリングしてくれる非常に便利なプラグインで、設定画面も日本語なので利用する価値があります。このサイトでも「Highlighting Code Block」を利用させていただいています。感謝!

Highlighting Code Blockとは?

プログラミング言語のコードをカラーリングするためのWordpressのプラグインです。開発は株式会社LOOSさんで日本の会社です。国産なので日本語対応バッチリです。

同じくコードをカラーリングする「Crayon Syntax Highlighter」や「Enlighter」などがありますが、このプラグインが日本語でなじみやすいかと思います。

インストール方法等は色んなサイトで詳細に書かれているので別途参照してください。

対応しているデフォルトの言語は

  • HTML
  • CSS
  • SCSS
  • JavaScript
  • TypeScript
  • PHP
  • Ruby
  • Python
  • Swift
  • C
  • C#
  • C++
  • Objective-C
  • SQL
  • JSON
  • Bash
  • Git

ですが、自身で使いたい言語を追加で設定可能です。
今回はDart言語を追加していきます。他の言語も同様の手順で追加できるので参考にしてみてください。

Dart言語に対応させよう

WordPress管理画面で「Highlighting Code Block 設定」画面を開きます。「設定」>「[HCB]設定」で開けます。このページの一番下に下記のような「独自prism.js」を設定する箇所があります。

独自prism.js

この「Highlighting Code Block」はprism.jsを使用しているので、自前で用意したprism.jsで対応言語を拡張することが可能です。

そもそもprism.jsって何か?

知っている人は読み飛ばしてください。
prism.js」って何ぞ?ですが、簡単に言うと軽量なシンタックスハイライトライブラリです。
え、Highlighting Code Blockがコードをカラーリングしてるんじゃないの?ってなるかもしれませんが、Coreの部分はこのprism.jsによって動作しています(Highlighting Code Blockのソース見てないので間違っていたらゴメンナサイ)。

じゃ、初めからprism.js使えばいいじゃん、となりますが、Highlighting Code BlockはあくまでWordpressのプラグインで、prism.jsで記述しなくてはいけないClass名などを自動補完してくれるものです。Wordpressの管理画面からの投稿を効率的に行うためにHighlighting Code Blockを使っているのです。

WordPressの投稿の際にコード編集モードで<pre></pre>タグで囲って、Class名に言語指定して、行数の有無も指定して……ってやってると面倒だし、かなり非効率です。そのようなHTMLの記述を自動的に行ってくれるのがこのプラグインの役目になります。

例えばこのプラグインを使わずにprism.jsだけ読み込んで投稿画面に書こうとすると次のように自力で記述する必要があります。

<pre><code class="language-css">p { color: red; }</code></pre>

このclass=”language-css”の部分とかいちいち書いてるとイライラしてきます。それを解消してくれるのがこのプラグインになります。
WordPressのブロック編集で入力した箇所をChromeのデベロッパーツールで確認すると、

language-〇〇が指定されている

このようにlanguage-dartとClassを自動で付与してくれるのです。めんどくさがりの僕はプラグインを使うことを選びました。おそらく他の処理もプラグインで補完してくれているのでかなりの効率化になります。

Dart言語の設定の仕方

話が飛躍してしまいました。では実際にDart言語に対応できるようにしていきましょう。
大まかな手順は、

  1. prism.js(prism.css*)の取得・ダウンロード
  2. prism.js(prism.css*)のアップロード
  3. 管理画面での登録・使用する言語セットの登録

(*: テーマの変更が不要であれば、CSSは必要ありません)
このような流れになります。

1.prism.js、prism.cssの取得は、prism.js公式のページで、ご自身に合った言語を選択&テーマカラー等を選択して、一番下にあるダウンロードボタンを押すだけです。(なんて簡単……)

2.ダウンロードしたファイルを/wp-content/themes/(自分が使っているテーマ)/配下にFTPでアップロードします。

3.アップロードしたら登録画面の「独自prism.js」欄に 「prism.js」と入力。もしCSSにCSSも変更したい場合は、先ほどダウンロードしたprism.cssを「独自カラーリングファイル」に入力します。
(注意)こちらでCSSファイルの中身を確認したところ、Dart言語用独自や各言語独自のCSSは含まれなかったので特段に追加する必要はなく、Highlighting Code BlockデフォルトのCSSのままで良いでしょう。

prism.jsの記載が終わったら「使用する言語セット」の設定をしましょう。

dart: “Dart”, を追記

末尾に「,(カンマ)」を付けるのを忘れないでください。一番下に追加する場合も末尾に「,」が必要なようです。各言語の対応変数はhttps://prismjs.com/#supported-languagesに書かれていますので、確認して記入してください。例えば「F#」言語であれば「fsharp」、「React TSX」であれば「tsx」となります。「fsharp: “F#”,」「tsx: “”React TSX,」という風になりますね。

全部記入が終わったら設定画面の一番下にある「変更を保存」を押して完了です!

実際に使ってみよう

Dart言語をHighlighting Code Blockに追加して、Wordpressのブロックエディタで入力したところ以下のようにきちんと表示されました!Flutterのメインとなるmain.dartを入れてみます。

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(
          // Column is also a layout widget. It takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          //
          // Invoke "debug painting" (press "p" in the console, choose the
          // "Toggle Debug Paint" action from the Flutter Inspector in Android
          // Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
          // to see the wireframe for each widget.
          //
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

うん、綺麗でGood!てか、コメント多っっ。
以上、皆さんもうまくいったら幸いです。

タイトルとURLをコピーしました