HN 日本語サマリー

← 一覧へ戻る
プログラミング

IntelliJからの脱却: Emacs EglotでのScalaおよびKotlin LSP

Escape IntelliJ: Scala and Kotlin LSPs on Emacs Eglot (jointhefreeworld.org)

109 pointsby jjba2390 コメント

要約

この記事は、EmacsのEglotクライアントを使用してScalaやKotlinといったJVM言語の開発環境をIntelliJ IDEAから移行する方法について解説しています。Eglotの軽量さとEmacs Lispによるカスタマイズ性を活用し、言語サーバーの設定や高度なワークアラウンドを駆使することで、IntelliJに匹敵する、あるいはそれを超える開発体験を実現する方法が紹介されています。

全文翻訳

Emacs Eglot for Scala and Kotlin (JVM)

Emacs 29でeglotが組み込みのデフォルトLanguage Server Protocol (LSP) クライアントになったとき、多くの人が歓喜しました。

軽量で高速、Emacsの哲学に厳密に従っており、車輪の再発明を試みません。

しかし、ミニマルであるということは、LSPサーバーが逸脱したり、奇妙な動作をしたりした場合、eglotはすぐに修正するためのカスタマイズ可能なトグルを無数に提供しないということです。代わりに、Emacs Lispの力を活用することを期待しています。

この記事では、Scala、Kotlin(および一部のJava)の開発で日常的に使用している、本番環境対応のeglotセットアップ(私のheks-emacs設定の一部)を分解します。

参考として、私の完全なEglot設定はこちらで見ることができます: https://codeberg.org/jjba23/heks-emacs/src/branch/trunk/src/modules/eglot.el

基本的な言語セットアップ、特殊なワークスペース設定の処理、そしてScala(Metals)とKotlinのための高度なJSON-RPCおよびアドバイスベースの回避策について深く掘り下げ、Emacsからの開発を真にシームレスにし、IntelliJから解放します☺️。

完璧ではありませんが、私に言わせればほぼ完璧に近く、それが可能にする開発者体験と速度は驚異的です。Emacs、GNU、Eglotに感謝します!🐂


コードを見る前に、なぜこれを行うのかについて話しましょう。長年、JVM言語、特にScalaやKotlinを書くなら、IntelliJ IDEAを使わなければならないという従来の考え方がありました。これらの言語は標準的なテキストエディタには複雑すぎるという言説がありました。

しかし、IntelliJで実際に得られるものは何でしょうか?頻繁に8GB以上のRAMを消費し、「indexing pre-built binaries」中にシステムをロックし、閉鎖的なプロプライエタリなエコシステムに閉じ込められる、巨大でモノリシックなJavaアプリケーションです。

Emacsは、3つのコアな強みによってこのパラダイムを覆します:

  • LSPのUnix哲学:コンパイル、インデックス作成、コードのレンダリングを同時に行う単一のIDEの代わりに、Emacsはこれらのタスクを分割します。Eglotは、JSON-RPC経由で専用の言語サーバーと通信する、軽量でプロトコル優先のトランスポートレイヤーとして機能します。
  • 無限のハック可能性:IntelliJにKotlinコードの自動補完のバグがあった場合、JetBrainsがパッチを発行するのを待つしかありません。Emacsでは、10行のアドバイス関数を書いてネットワークペイロードをインターセプトし、エディタバッファでライブにバグを修正できます。
  • 統一されたインターフェース:Nix式を調整する場合でも、Markdownファイルを編集する場合でも、大規模なScalaサービスをリファクタリングする場合でも、同じテキスト操作ユーティリティ、テキストジャンプツール(xref)、補完フレームワーク(corfu、companyなど)を使用します。

フック、キーバインディング、初期設定 #

eglotの初期化方法から始めましょう。Elpacaとuse-packageを使用して設定を管理し、組み込みであるため外部パッケージをダウンロードしないようにします(:ensure nil)。その後、特定のモードで言語サーバーを自動的に開始するためのフックを追加します。

(use-package eglot
  :ensure nil
  :hook ((scala-ts-mode . eglot-ensure)
         (sh-mode . eglot-ensure)
         (markdown-mode . eglot-ensure)
         (markdown-ts-mode . eglot-ensure)
         (nix-ts-mode . eglot-ensure)
         (html-mode . eglot-ensure)
         (css-mode . eglot-ensure)
         (css-ts-mode . eglot-ensure)
         (html-ts-mode . eglot-ensure)
         (js-mode . eglot-ensure)
         (js-ts-mode . eglot-ensure)
         (kotlin-ts-mode . eglot-ensure)
         (yaml-mode . eglot-ensure)
         (yaml-ts-mode . eglot-ensure)
                  (before-save . eglot-format-buffer))
      )
  • あらゆる場所でのEglot-Ensure: 使用するほぼすべてのプログラミングモードにeglot-ensureをフックし、クラシックモードとモダンなTree-sitter(*-ts-mode)の両方に対応させます。
  • 自動フォーマット: before-saveにeglot-format-bufferを追加することで、ファイルがディスクに保存されるたびにコードスタイルコンプライアンスが自動的に保証されます。

私のキーバインディングはC-c iプレフィックスの下にネストされており、覚えやすく、言語間で一貫性があります。ニーモニックキーワードは「IDE」です。

:bind (("C-c i i" . eglot-find-implementation)
       ("C-c i e" . eglot)
       ("C-c i k" . eglot-shutdown-all)
       ("C-c i r" . eglot-rename)
       ("C-c i x" . eglot-reconnect)
       ("C-c i a" . eglot-code-actions)
       ("C-c i m" . eglot-menu)
       ("C-c i f" . eglot-format-buffer)
       ("C-c i h" . eglot-inlay-hints-mode))
:init
(setq eglot-autoshutdown t
      eglot-confirm-server-edits nil
      eglot-report-progress t
      eglot-extend-to-xref t
      eglot-sync-connect 1
      eglot-connect-timeout 60
      eglot-autoreconnect t)

そして、これらの:init設定により:

  • eglot-autoshutdownは、それによって管理されている最後のバッファが閉じられるとすぐに言語サーバープロセスをクリーンアップします。
  • eglot-extend-to-xrefにより、Emacsのクロスリファレンスコマンドがワークスペースディレクトリ外の外部ライブラリファイルにスムーズに移行できます。

サーバー定義とワークスペースの微調整 #

:configブロックの下で、特定の言語サーバーの最適化を開始します。例えば、デフォルトの設定を削除してからカスタムエントリを再追加することで、競合を防ぎます。

:config
(setopt eglot-code-action-indications nil) 
(setq eglot-server-programs (assq-delete-all 'scala-mode eglot-server-programs))
(setq eglot-server-programs (assq-delete-all 'scala-ts-mode eglot-server-programs))
(setq eglot-server-programs (assoc-delete-all 'scala-ts-mode eglot-server-programs))

(add-to-list 'eglot-server-programs `(scala-ts-mode . ("metals"
                                                       "-Xmx4G"
                                                       "-XX:+UseZGC"
                                                       "-Dmetals.http=true"
                                                       :initializationOptions (:isHttpEnabled t))))

(setq eglot-server-programs (assoc-delete-all 'kotlin-ts-mode eglot-server-programs))
(add-to-list 'eglot-server-programs '(kotlin-ts-mode . ("intellij-server" "--stdio")))

これらの変更の理由:

  • Scala (Metals): Metalsに直接JVMチューニングフラグを渡します(快適な4GBヒープを割り当て、低遅延のためにZガベージコレクタを使用)。また、初期化オプションでMetalsのHTTP通信を有効にすることで、必要に応じて特殊なUI機能にフックできます。
  • Kotlin: 標準オプションをIntelliJベースのKotlin Language Server(intellij-server --stdio)に切り替えます。

グローバルワークスペース設定 #

eglot-workspace-configurationを使用すると、カスタマイズされた変数を言語サーバーに下流で渡すことができます。私の設定のこのセクションは、ユニバーサルなsettings.jsonのようなものです:

(setq-default eglot-workspace-configuration
              '(
                :metals ( :autoImportBuild "all"
                          :isHttpEnabled t
                          :superMethodLensesEnabled t
                          :showInferredType t
                          :enableSemanticHighlighting t
                          :inlayHints ( :inferredTypes (:enable t )
                                        :implicitArguments (:enable nil)
                                        :implicitConversions (:enable nil )
                                        :typeParameters (:enable t )
                                        :hintsInPatternMatch (:enable nil ))
                          :bloopJvmProperties ["-Xmx4G"])
                :haskell (:formattingProvider "ormolu")
                :typescript (:format (:baseIndentSize 0
                                                      :convertTabsToSpaces t
                                                      :indentSize 2
                                                      :semicolons "remove"
                                                      :tabSize 2))
                :javascript (:format (:baseIndentSize 0
                                                      :convertTabsToSpaces t
                                                      :indentSize 2
                                                      :semicolons "remove"
                                                      :tabSize 2))
                :rust-analyzer (:check (:command "clippy")
                                       :cargo (:sysroot "discover"
                                                        :features "all"
                                                        :buildScripts (:enable t))
                                       :diagnostics (:disabled ["macro-error"])
                                       :procMacro (:enable t))

                :yaml ( :format (:enable t) 
                        :validate t
                        :hover t
                        :completion t
                        :schemas (
                                  https://codeberg.org/jjba23/pop-test/raw/branch/trunk/resources/json-schema/pop-test.json ["golden-test.yaml" "golden-test.yml" "pop-test.yaml" "pop-test.yml"]
                                  https://raw.githubusercontent.com/Vandebron/gh-mpyl/refs/heads/main/src/mpyl/schema/project.schema.yml ["project.yml"]
                                  https://json.schemastore.org/yamllint.json ["/*.yml"])
                        :schemaStore (:enable t))
                :nil (:formatting (:command ["nixfmt"]))))

注目すべき設定:

  • Metals: 推論された型と型パラメータに対して、明示的な変換をミュートしてバッファを読みやすく保つように、きめ細かなインレイヒントが有効になっています。(その他のオプションはこちら: https://scalameta.org/metals/docs/editors/user-configuration/)
  • YAMLスキーママッピング: 異なるインターネットホストのJSONスキーマを、YAMLファイルのパターンに自動的にマッピングします。

詳細: 回避策 #

ここで物事が面白くなります。サーバーが標準のLSPの期待に違反することがあり、ギャップを埋めるためにカスタムEmacs Lispロジックが必要になります。

Eldocの過負荷の修正 #

デフォルトでは、eldocはさまざまなフィードバックメカニズムによって簡単に氾濫する可能性があります。このブロックは、一般的なホバーデータよりも構造的なコード診断を優先します:

(add-hook 'eglot-managed-mode-hook
          (lambda ()
                        (setq eldoc-documentation-functions
                  (cons #'flymake-eldoc-function
                        (remove #'flymake-eldoc-function eldoc-documentation-functions))) 
                        (setq eldoc-documentation-strategy #'eldoc-documentation-compose)))
Kotlinソースナビゲーション(JAR URI変換) #

Kotlinで依存ライブラリにドリルダウンする際、サーバーはjar:///path/to/library.jar!/File.ktという形式のファイル参照を返します。Emacsはこれを標準では直接解決できず、定義へジャンプしようとするとエラーが発生します。

EglotのURIトランスレータをアドバイスでラップすることで、このカスタムスキームをEmacsが理解できるものにマッピングできます(特にjarchiveのようなコンパニオン拡張と連携する場合):

(defun heks/eglot-uri-to-path-kotlin (orig-fn uri &rest args)
  (if (and (stringp uri) (string-prefix-p "jar:///" uri))
      (apply orig-fn (replace-regexp-in-string "^jar:///" "jar:file:///" uri) args)
    (apply orig-fn uri args)))

(defun heks/eglot-path-to-uri-kotlin (orig-fn path &rest args)
  (if (and (stringp path) (string-prefix-p "jar:file:///" path))
      (replace-regexp-in-string "^jar:file:///" "jar:///" path)
    (apply orig-fn path args)))

(if (fboundp 'eglot-uri-to-path)
    (progn
      (advice-add 'eglot-uri-to-path :around #'heks/eglot-uri-to-path-kotlin)
      (advice-add 'eglot-path-to-uri :around #'heks/eglot-path-to-uri-kotlin))
  (progn
    (advice-add 'eglot--uri-to-path :around #'heks/eglot-uri-to-path-kotlin)
    (advice-add 'eglot--path-to-uri :around #'heks/eglot-path-to-uri-kotlin)))
Kotlinの空のnewText自動補完バグのインターセプト #

一部のKotlin LSPリリースにおける悪名高い問題は、自動補完中に発生します。サーバーは一致する候補を報告しますが、誤って空文字列(newText: "")を含むtextEditフィールドを添付してしまいます。これにより、Eglotは補完中の単語を完全に消去してしまいます。

これを解決するために、同期および非同期の着信JSON-RPCペイロードをインターセプトします。Kotlinの補完候補が空文字列の編集を返す場合、textEdit属性を完全に削除し、Eglotを標準のプレフィックスマッチングに優雅にフォールバックさせます。

(defun my-jsonrpc-request-kotlin-fix (orig-fn connection method params &rest args)
  "Fix kotlin-lsp empty newText bug by removing textEdit to trigger Eglot fallback."
  (let ((result (apply orig-fn connection method params args)))
    (when (and (eq method :textDocument/completion)
               (derived-mode-p 'kotlin-mode 'kotlin-ts-mode)
               result)
      (let ((items (if (vectorp result) result (plist-get result :items))))
        (seq-do (lambda (item)
                  (let ((text-edit (plist-get item :textEdit))) 
                                                            (when (and text-edit (equal (plist-get text-edit :newText) ""))
                      (plist-put item :textEdit nil))))
                items)))
    result))

(defun my-jsonrpc-async-request-kotlin-fix (orig-fn connection method params &rest args)
  "Fix kotlin-lsp empty newText bug in asynchronous Eglot requests."
  (if (and (eq method :textDocument/completion)
           (derived-mode-p 'kotlin-mode 'kotlin-ts-mode))
      (let* ((orig-success (plist-get args :success-fn))
             (new-success (lambda (result)
                            (let ((items (if (vectorp result) result (plist-get result :items))))
                              (seq-do (lambda (item)
                                        (let ((text-edit (plist-get item :textEdit))) 
                                          (when (and text-edit (equal (plist-get text-edit :newText) ""))
                                            (plist-put item :textEdit nil))))
                                      items))
                            (funcall orig-success result)))
             (new-args (plist-put (copy-sequence args) :success-fn new-success)))
        (apply orig-fn connection method params new-args))
    (apply orig-fn connection method params args)))

(advice-add 'jsonrpc-request :around #'my-jsonrpc-request-kotlin-fix)
(advice-add 'jsonrpc-async-request :around #'my-jsonrpc-async-request-kotlin-fix)
Metalsのセマンティックリフレッシュのちらつきを抑制 #

Scala Metalsは、フルバッファのセマンティックトークンリフレッシュを積極的に強制します。大規模なプロジェクトでは、これは視覚的なレイアウトのちらつきと不要なCPU負荷につながります。これを無効にすることで、Metalsの起動時の問題も解決できます。

(defun my/eglot-disable-metals-semantic-refresh (orig-fn server)
  (let* ((caps (funcall orig-fn server))
         (workspace (plist-get caps :workspace))
         (tokens (plist-get workspace :semanticTokens)))
    (when tokens
      (plist-put tokens :refreshSupport :json-false))
    caps))

(advice-add 'eglot-client-capabilities :around #'my/eglot-disable-metals-semantic-refresh)

コンパニオンパッケージ: Javaと圧縮アーカイブ #

セットアップを完了するために、Eglotのコアファイル外で補完的なマイナーモードをロードし、Javaの円滑な操作とパックされたJARの深いナビゲーションを保証します:

(use-package eglot-java
  :ensure t
  :after (eglot)
  :hook ((java-mode . eglot-java-mode)
         (java-ts-mode . eglot-java-mode)))

(use-package jarchive
  :ensure t
  :config
  (jarchive-mode))
  • eglot-java: Eclipse JDT LSのために、適切なワークスペース設定をシームレスにプロビジョニングします。
  • jarchive: KotlinのJAR-URI変換ハックと調和して動作し、ジップされたソースコンテナを通常の表示可能なEmacsバッファとして開きます。

再現性に関する私の好み #

私は一般的にシステム全体のJDKインストールを使用せず、Nix flakesで分離された開発環境を使用します。

最終的にはGuixに移行するかもしれませんが、現時点ではJVMの世界でのパッケージの利用可能性が十分ではないため、Nixを使用しています。

これにより、同じマシン上で多くの環境やプロジェクト(例: 異なるJavaバージョン)を簡単に作業でき、SDKManやバージョンマネージャーは不要で、クリーンで分離されたプロジェクトごとの再現可能なビルドが可能です。

そこで、flake.nixを作成してGitに追加します。

Kotlin開発用flake(TODO: Nix経由でintellij-serverを統合):

{
  inputs = {
    nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
    systems.url = "github:nix-systems/default";
  };
  outputs = { systems, nixpkgs, ... }:
    let
      eachSystem = f:
        nixpkgs.lib.genAttrs (import systems)
        (system: f nixpkgs.legacyPackages.${system});
    in {
      devShells = eachSystem (pkgs: {
        default = pkgs.mkShell {
          buildInputs = with pkgs; [
            ktfmt
            ktlint
            kotlin
            jdk25
            nil
            just
            yaml-language-server
          ];
        };
      });
    };
}

Scala開発用flake。

{
  inputs = {
    nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
    systems.url = "github:nix-systems/default";
  };
  outputs = { systems, nixpkgs, ... }:
    let
      eachSystem = f:
        nixpkgs.lib.genAttrs (import systems)
        (system: f nixpkgs.legacyPackages.${system});
    in {
      devShells = eachSystem (pkgs: {
        default = pkgs.mkShell {
          buildInputs = with pkgs; [
            scala_2_13
            jdk25
            metals
            sbt
            scalafmt
            scalafix
            scala-cli
            yaml-language-server
            coursier
          ];
        };
      });
    };
}

そして、direnvでflakeをロードするため、.envrcファイルを作成します。

use flake

このように、Emacs内でemacs-direnvを使用して、Emacs LSP内で動的にコンテキストを切り替え、複数のLSPを同時に実行することもできます。

また、direnvをBashシェル設定にもプラグインし、開発環境を完成させます。

結論 #

Eglotのミニマルで組み込みのデザインは、劣悪な言語サーバーの動作に甘んじる必要があることを意味しません。結局のところ、Emacsを使用しているのですから、その力は無限です!

advice-addを介してJSON-RPCレベルで通信をインターセプトすることで、クライアントとサーバーの動作を好みに合わせて正確に調整できます。

ハッピーハッキング!✨