Ace Editor を表示してテーマや言語モードを変更する方法

Ace Editor は ブラウザで動作するコードエディタです。MITライセンスで使用できます。 このブログでも、コードを表示する際は Ace Editor を使用しています。

この記事では、Ace Editor の使用方法について説明します。

CDNを使用した Ace Editor の表示方法

    <!DOCTYPE html>
    <html lang="ja">
    <head>
      <meta charset="UTF-8">
      <title>Ace Editor sample</title>
    </head>
    <body>
      <div id="editor" style="height: 600px">console.log("hello world");</div>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.0/ace.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.2.0/ext-language_tools.js"></script>
      <script>
        var editor = ace.edit("editor");
        editor.$blockScrolling = Infinity;
        editor.setOptions({
          enableBasicAutocompletion: true,
          enableSnippets: true,
          enableLiveAutocompletion: true
        });
        editor.setTheme("ace/theme/monokai");
        editor.getSession().setMode("ace/mode/javascript");
        editor.setFontSize(20)
      </script>
    </body>
    </html>

ブラウザで表示すると、以下のように Acce Editor が表示されます。

この例では、

  • テーマ:monokai
  • 言語モード:javascript
  • フォントサイズ:20

としています。

div#editorの中のテキストが Ace Editor の中にコードとして表示されます。

Javascript から Ace Editor の中に表示するコードを変更するには

    var editor = ace.edit("editor");

    editor.setValue(CodeValue);

このように、setValueメソッドを使用します。

テーマを変更するには

editor.setTheme メソッドを使用して変更します。

指定可能なテーマは Ace Kitchen Sink を 参照ください。

言語モードを変更するには

editor.getSession().setMode メソッドを使用します。

指定可能なモードは同じく Ace Kitchen Sink の Mode を参照ください。

フォントサイズを変更するには

editor.setFontSize メソッドを使用します。フォントサイズを数値で指定します。

コメント

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