LoginSignup
1
1

More than 1 year has passed since last update.

Aceエディターにキーボードイベントを追加する

Last updated at Posted at 2021-08-11

今までMonacoエディターを使っていたのですが、シンタックスハイライトがAceの方が充実しているのでAceに乗り換えることに。

Monacoの場合

キーボードイベントを追加したい場合、MonacoだとonKeyDownというメソッドがあったので、キーボードイベントをすぐ登録できたのですが、Aceにはない。

let = editor = monaco.editor.create(<options>); // IStandaloneCodeEditor
editor.onKeyDown((e) => {
    <commands>
});

Aceの場合

Aceの場合は以下のように登録できる(なぜかAPI Docsに乗ってないがeditor.hasOwnProperty("commands")はtrueになる)。

let editor = ace.edit("<element id>");
editor.commands.addCommand({
  name: "<command name>",
  exec: () => {<commands>},
  bindKey: {mac: "<key>", win: "<key>"} // e.g. {mac: "cmd-p", win: "ctrl-p"}
});

しかし上の方法で登録するとデフォの入力ができなくなってしまう(そうしたい場合はいいのだが)。結局

window.onload = () => {
  editorElement = document.getElementById("<element id>")
  editorElement.addEventListener("keydown", <command name>}

let <command name> = (e) => {
  <commands>
//  e.g.
//  if (e.ctrlKey && e.key == "p") {    
//    console.log(e.key)
//  }
}

のようにする。

メモ

VueでAceを使うときsessionをVueのdataに代入するとマルチカーソル使ったときにバグる。uiのエディターとsessionの同期がVueで阻害される?

1
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
1
1