dotemacs

My Emacs configuration
git clone git://git.entf.net/dotemacs
Log | Files | Refs | LICENSE

eglot.texi (65713B)


      1 \input texinfo  @c -*-texinfo-*-
      2 @c %**start of header
      3 @setfilename ../../eglot.info
      4 @settitle Eglot: The Emacs Client for the Language Server Protocol
      5 @include docstyle.texi
      6 @syncodeindex vr cp
      7 @syncodeindex fn cp
      8 @c %**end of header
      9 
     10 @copying
     11 This manual is for Eglot, the Emacs LSP client.
     12 
     13 Copyright @copyright{} 2022--2024 Free Software Foundation, Inc.
     14 
     15 @quotation
     16 Permission is granted to copy, distribute and/or modify this document
     17 under the terms of the GNU Free Documentation License, Version 1.3 or
     18 any later version published by the Free Software Foundation; with no
     19 Invariant Sections, with the Front-Cover Texts being ``A GNU Manual'',
     20 and with the Back-Cover Texts as in (a) below.  A copy of the license
     21 is included in the section entitled ``GNU Free Documentation License''.
     22 
     23 (a) The FSF's Back-Cover Text is: ``You have the freedom to copy and
     24 modify this GNU manual.''
     25 @end quotation
     26 @end copying
     27 
     28 @dircategory Emacs misc features
     29 @direntry
     30 * Eglot: (eglot).             Language Server Protocol client for Emacs.
     31 @end direntry
     32 
     33 @titlepage
     34 @sp 4
     35 @c The title is printed in a large font.
     36 @center @titlefont{User's Guide}
     37 @sp 1
     38 @center @titlefont{to}
     39 @sp 1
     40 @center @titlefont{Eglot: The Emacs LSP Client}
     41 @ignore
     42 @sp 2
     43 @center release 1.8
     44 @c -release-
     45 @end ignore
     46 @sp 3
     47 @center Jo@~ao T@'avora & Eli Zaretskii
     48 @c -date-
     49 
     50 @page
     51 @vskip 0pt plus 1filll
     52 @insertcopying
     53 @end titlepage
     54 
     55 @contents
     56 
     57 @ifnottex
     58 @node Top
     59 @top Eglot
     60 
     61 @cindex LSP
     62 @cindex language server protocol
     63 Eglot is the Emacs client for the @dfn{Language Server Protocol}
     64 (@acronym{LSP}).  The name ``Eglot'' is an acronym that stands for
     65 @ifhtml
     66 ``@emph{E}macs Poly@emph{glot}''.
     67 @end ifhtml
     68 @ifnothtml
     69 ``Emacs polyGLOT''.
     70 @end ifnothtml
     71 @footnote{
     72 A @dfn{polyglot} is a
     73 person who is able to use several languages.
     74 } Eglot provides infrastructure and a set of commands for enriching
     75 the source code editing capabilities of Emacs via LSP@.  LSP is a
     76 standardized communications protocol between source code editors (such
     77 as Emacs) and language servers---programs external to Emacs which
     78 analyze the source code on behalf of Emacs.  The protocol allows Emacs
     79 to receive various source code services from the server, such as
     80 description and location of function calls, types of variables, class
     81 definitions, syntactic errors, etc.  This way, Emacs doesn't need to
     82 implement the language-specific parsing and analysis capabilities in
     83 its own code, but is still capable of providing sophisticated editing
     84 features that rely on such capabilities, such as automatic code
     85 completion, go-to definition of function/class, documentation of
     86 symbol at-point, refactoring, on-the-fly diagnostics, and more.
     87 
     88 Eglot itself is completely language-agnostic, but it can support any
     89 programming language for which there is a language server and an Emacs
     90 major mode.
     91 
     92 This manual documents how to configure, use, and customize Eglot.
     93 
     94 @insertcopying
     95 
     96 @menu
     97 * Quick Start::                 For the impatient.
     98 * Eglot and LSP Servers::       How to work with language servers.
     99 * Using Eglot::                 Important Eglot commands and variables.
    100 * Customizing Eglot::           Eglot customization and advanced features.
    101 * Advanced server configuration::  Fine-tune a specific language server
    102 * Extending Eglot::             Writing Eglot extensions in Elisp
    103 * Troubleshooting Eglot::       Troubleshooting and reporting bugs.
    104 * GNU Free Documentation License::  The license for this manual.
    105 * Index::
    106 @end menu
    107 @end ifnottex
    108 
    109 @node Quick Start
    110 @chapter Quick Start
    111 @cindex quick start
    112 
    113 This chapter provides concise instructions for setting up and using
    114 Eglot with your programming project in common usage scenarios.  For
    115 more detailed instructions regarding Eglot setup, @pxref{Eglot and LSP
    116 Servers}.  @xref{Using Eglot}, for detailed description of using Eglot,
    117 and see @ref{Customizing Eglot}, for adapting Eglot to less common use
    118 patterns.
    119 
    120 Here's how to start using Eglot with your programming project:
    121 
    122 @enumerate
    123 @item
    124 Select and install a language server.
    125 
    126 Eglot comes pre-configured with many popular language servers, see the
    127 value of @code{eglot-server-programs}.  If the server(s) mentioned
    128 there satisfy your needs for the programming language(s) with which
    129 you want to use Eglot, you just need to make sure those servers are
    130 installed on your system.  Alternatively, install one or more servers
    131 of your choice and add them to the value of
    132 @code{eglot-server-programs}, as described in @ref{Setting Up LSP
    133 Servers}.
    134 
    135 @item
    136 Turn on Eglot for your project.
    137 
    138 To start using Eglot for a project, type @kbd{M-x eglot @key{RET}} in
    139 a buffer visiting any file that belongs to the project.  This starts
    140 the language server configured for the programming language of that
    141 buffer, and causes Eglot to start @dfn{managing} file-visiting buffers
    142 related to that programming language.  This includes files that are
    143 already visited at the time the @code{eglot} command is invoked, as
    144 well as any files visited after this invocation.
    145 
    146 The notion of a ``project'' used by Eglot is the same Emacs uses
    147 (@pxref{Projects,,, emacs, GNU Emacs Manual}): in the simplest case,
    148 the ``project'' is the single file you are editing, but it can also be
    149 all the files in a single directory or a directory tree under some
    150 version control system, such as Git.
    151 
    152 There are alternate ways of starting Eglot; see @ref{Starting Eglot}
    153 for details.
    154 
    155 @item
    156 Use Eglot.
    157 
    158 Most Eglot facilities are integrated into Emacs features, such as
    159 ElDoc, Flymake, Xref, and Imenu.  However, Eglot also provides
    160 commands of its own, mainly to perform tasks by the language server,
    161 such as @kbd{M-x eglot-rename} (to rename an identifier across the
    162 entire project), @kbd{M-x eglot-format} (to reformat and reindent
    163 code), and some others.  @xref{Eglot Commands}, for the detailed list
    164 of Eglot commands.
    165 
    166 @item
    167 That's it!
    168 @end enumerate
    169 
    170 @node Eglot and LSP Servers
    171 @chapter Eglot and LSP Servers
    172 
    173 This chapter describes how to set up Eglot for your needs, and how to
    174 start it.
    175 
    176 @menu
    177 * Setting Up LSP Servers::   How to configure LSP servers for your needs.
    178 * Starting Eglot::              Ways of starting Eglot for your project.
    179 * Shutting Down LSP Servers::
    180 @end menu
    181 
    182 @node Setting Up LSP Servers
    183 @section Setting Up LSP Servers
    184 @cindex setting up LSP server for Eglot
    185 @cindex LSP server for Eglot, setting up
    186 @cindex language server for Eglot
    187 
    188 For Eglot to be useful, it must first be combined with a suitable
    189 language server.  Usually, that means running the server program
    190 locally as a child process of Emacs (@pxref{Processes,,, elisp, GNU
    191 Emacs Lisp Reference Manual}) and communicating with it via the
    192 standard input and output streams.
    193 
    194 The language server program must be installed separately, and is not
    195 further discussed in this manual; refer to the documentation of the
    196 particular server(s) you want to install.
    197 
    198 To use a language server, Eglot must know how to start it and which
    199 programming languages each server supports.  This information is
    200 provided by the variable @code{eglot-server-programs}.
    201 
    202 @defvar eglot-server-programs
    203 This variable associates major modes with names and command-line
    204 arguments of the language server programs corresponding to the
    205 programming language of each major mode.  It provides all the
    206 information that Eglot needs to know about the programming language of
    207 the source you are editing.
    208 
    209 The value of the variable is an alist, whose elements are of the form
    210 @w{@code{(@var{major-mode} . @var{server})}}.
    211 
    212 The @var{major-mode} of the alist elements can be either a symbol of
    213 an Emacs major mode or a list of the form @w{@code{(@var{mode}
    214 :language-id @var{id})}}, with @var{mode} being a major-mode symbol
    215 and @var{id} a string that identifies the language to the server (if
    216 Eglot cannot by itself convert the major-mode to the language
    217 identifier string required by the server).  In addition,
    218 @var{major-mode} can be a list of several major modes specified in one
    219 of the above forms -- this means a running instance of the associated
    220 server is responsible for files of multiple major modes or languages
    221 in the project.
    222 
    223 The @var{server} part of the alist elements can be one of the
    224 following:
    225 
    226 @table @code
    227 @item (@var{program} @var{args}@dots{})
    228 This says to invoke @var{program} with zero or more arguments
    229 @var{args}; the program is expected to communicate with Emacs via the
    230 standard input and standard output streams.
    231 
    232 @item (@var{program} @var{args}@dots{} :initializationOptions @var{options}@dots{})
    233 @var{program} is invoked with @var{args} but @var{options} specifies
    234 how to construct the @samp{:initializationOptions} JSON object to pass
    235 the server on during the LSP handshake (@pxref{Advanced server
    236 configuration}).
    237 
    238 @item (@var{host} @var{port} @var{args}@dots{})
    239 Here @var{host} is a string and @var{port} is a positive integer
    240 specifying a TCP connection to a remote server.  The @var{args} are
    241 passed to @code{open-network-stream}, e.g.@: if the connection needs
    242 to use encryption or other non-default parameters (@pxref{Network,,,
    243 elisp, GNU Emacs Lisp Reference Manual}).
    244 
    245 @item (@var{program} @var{args}@dots{} :autoport @var{moreargs}@dots{})
    246 @var{program} is started with a command line constructed from
    247 @var{args} followed by an available server port and the rest of
    248 arguments in @var{moreargs}; Eglot then establishes a TCP connection
    249 with the server via that port on the local host.
    250 
    251 @item @var{function}
    252 This should be a function of a single argument: non-@code{nil} if the
    253 connection was requested interactively (e.g., by the @code{eglot}
    254 command), otherwise @code{nil}.  The function should return a value of
    255 any of the forms described above.  This allows interaction with the
    256 user for determining the program to start and its command-line
    257 arguments.
    258 @end table
    259 
    260 @end defvar
    261 
    262 Eglot comes with a fairly complete set of associations of major-modes
    263 to popular language servers predefined.  If you need to add server
    264 associations to the default list, use @code{add-to-list}.  For
    265 example, if there is a hypothetical language server program
    266 @command{fools} for the language @code{Foo} which is supported by an
    267 Emacs major-mode @code{foo-mode}, you can add it to the alist like
    268 this:
    269 
    270 @lisp
    271 (with-eval-after-load 'eglot
    272   (add-to-list 'eglot-server-programs
    273                '(foo-mode . ("fools" "--stdio"))))
    274 @end lisp
    275 
    276 This will invoke the program @command{fools} with the command-line
    277 argument @option{--stdio} in support of editing source files for which
    278 Emacs turns on @code{foo-mode}, and will communicate with the program
    279 via the standard streams.  As usual with invoking programs, the
    280 executable file @file{fools} should be in one of the directories
    281 mentioned by the @code{exec-path} variable (@pxref{Subprocess
    282 Creation,,, elisp, GNU Emacs Lisp Reference Manual}), for Eglot to be
    283 able to find it.
    284 
    285 Sometimes, multiple servers are acceptable alternatives for handling a
    286 given major-mode.  In those cases, you may combine the helper function
    287 @code{eglot-alternatives} with the functional form of
    288 @code{eglot-server-programs}.
    289 
    290 @lisp
    291 (with-eval-after-load 'eglot
    292   (add-to-list 'eglot-server-programs
    293                `(foo-mode . ,(eglot-alternatives
    294                                '(("fools" "--stdio")
    295                                  ("phewls" "--fast"))))))
    296 @end lisp
    297 
    298 If you have @command{fools} and @command{phewls} installed, the
    299 function produced by @code{eglot-alternatives} will prompt for the
    300 server to use in @code{foo-mode} buffers.  Else it will use whichever
    301 is available.
    302 
    303 @node Starting Eglot
    304 @section Starting Eglot
    305 @cindex starting Eglot
    306 @cindex activating Eglot for a project
    307 
    308 @findex eglot
    309 The most common way to start Eglot is to simply visit a source file of
    310 a given language and use the command @kbd{M-x eglot}.  This starts the
    311 language server suitable for the visited file's major-mode, and
    312 attempts to connect to it.  If the connection to the language server
    313 is successful, you will see the @code{[eglot:@var{project}]} indicator
    314 on the mode line which reflects the server that was started.  If the
    315 server program couldn't be started or connection to it failed, you
    316 will see an error message; in that case, try to troubleshoot the
    317 problem as described in @ref{Troubleshooting Eglot}.  Once a language
    318 server was successfully started and Eglot connected to it, you can
    319 immediately start using the Emacs features supported by Eglot, as
    320 described in @ref{Eglot Features}.
    321 
    322 A single Eglot session for a certain major-mode usually serves all the
    323 buffers under that mode which visit files from the same project, so
    324 you don't need to invoke @kbd{M-x eglot} again when you visit another
    325 file from the same project which is edited using the same major-mode.
    326 This is because Eglot uses the Emacs project infrastructure, as
    327 described in @ref{Eglot and Buffers}, and this knows about files that
    328 belong to the same project.  Thus, after starting an Eglot session for
    329 some buffer, that session is automatically reused when visiting files
    330 in the same project with the same major-mode.
    331 
    332 @findex eglot-ensure
    333 Alternatively, you could configure Eglot to start automatically for
    334 one or more major-modes from the respective mode hooks.  Here's an
    335 example for a hypothetical @code{foo-mode}:
    336 
    337 @lisp
    338  (add-hook 'foo-mode-hook 'eglot-ensure)
    339 @end lisp
    340 
    341 @noindent
    342 The function @code{eglot-ensure} will start an Eglot session for each
    343 buffer in which @code{foo-mode} is turned on, if there isn't already
    344 an Eglot session that handles the buffer.  Note that this variant of
    345 starting an Eglot session is non-interactive, so it should be used
    346 only when you are confident that Eglot can be started reliably for any
    347 file which may be visited with the major-mode in question.
    348 
    349 Note that it's often difficult to establish this confidence fully, so
    350 it may be wise to use the interactive command @code{eglot} instead.
    351 You only need to invoke it once per project, as all other files
    352 visited within the same project will automatically be managed with no
    353 further user intervention needed.
    354 
    355 When Eglot connects to a language server for the first time in an
    356 Emacs session, it runs the hook @code{eglot-connect-hook}
    357 (@pxref{Eglot Variables}).
    358 
    359 @node Shutting Down LSP Servers
    360 @section Shutting Down LSP Servers
    361 @cindex shutting down LSP server
    362 
    363 When Eglot is turned on, it arranges for turning itself off
    364 automatically if the language server process terminates.  Turning off
    365 Eglot means that it shuts down the server connection, ceases its
    366 management of all the buffers that use the server connection which was
    367 terminated, deactivates its minor mode, and restores the original
    368 values of the Emacs variables that Eglot changed when it was turned
    369 on.  @xref{Eglot and Buffers}, for more details of what Eglot
    370 management of a buffer entails.
    371 
    372 @findex eglot-shutdown
    373 You can also shut down a language server manually, by using the
    374 command @kbd{M-x eglot-shutdown}.  This prompts for the server (unless
    375 there's only one connection and it's used in the current buffer), and
    376 then shuts it down.  By default, it also kills the server's events
    377 buffer (@pxref{Troubleshooting Eglot}), but a prefix argument prevents
    378 that.
    379 
    380 Alternatively, you can customize the variable
    381 @code{eglot-autoshutdown} to a non-@code{nil} value, in which case
    382 Eglot will automatically shut down the language server process when
    383 the last buffer served by that language server is killed.  The default
    384 of this variable is @code{nil}, so that visiting another file would
    385 automatically activate Eglot even when the project which started Eglot
    386 with the server no longer has any buffer associated with it.  This
    387 default allows you to start a server only once in each Emacs session.
    388 
    389 @node Using Eglot
    390 @chapter Using Eglot
    391 
    392 This chapter describes in detail the features that Eglot provides and
    393 how it does that.  It also provides reference sections for Eglot
    394 commands and variables.
    395 
    396 @menu
    397 * Eglot Features::
    398 * Eglot and Buffers::
    399 * Eglot Commands::
    400 * Eglot Variables::
    401 @end menu
    402 
    403 @node Eglot Features
    404 @section Eglot Features
    405 @cindex features in buffers supported by Eglot
    406 
    407 While Eglot is enabled in a buffer, it is said to be @dfn{managing}
    408 it, using LSP and the specific capabilities of the language server to
    409 activate and enhance modern IDE features in Emacs.  Some of these
    410 features are provided via other Emacs packages, and some via Eglot
    411 directly (@pxref{Eglot Commands}).
    412 
    413 Here's an overview of the main features that Eglot provides:
    414 
    415 @itemize @bullet
    416 @item
    417 At-point documentation: when point is at or near a symbol or an
    418 identifier, the information about the symbol/identifier, such as the
    419 signature of a function or class method and server-generated
    420 diagnostics, is made available via the ElDoc package
    421 (@pxref{Programming Language Doc,,, emacs, GNU Emacs Manual}).  This
    422 allows major modes to provide extensive help and documentation about
    423 the program identifiers.
    424 
    425 @item
    426 On-the-fly diagnostic annotations, via the Flymake package
    427 (@pxref{Top,,, flymake, GNU Flymake manual}).  Eglot's Flymake backend
    428 replaces other Flymake backends while it is managing a buffer, and
    429 enhances diagnostics with interactive server-suggested fixes
    430 (so-called @dfn{code actions}, @pxref{Eglot Commands})
    431 
    432 @item
    433 Finding definitions and uses of identifiers, via Xref (@pxref{Xref,,,
    434 emacs, GNU Emacs Manual}).  Eglot provides a backend for the Xref
    435 capabilities which uses the language-server understanding of the
    436 program source.  In particular, it eliminates the need to generate
    437 tags tables (@pxref{Tags tables,,, emacs, GNU Emacs Manual}) for
    438 languages which are only supported by the @code{etags} backend.
    439 
    440 @item
    441 Buffer navigation by name of function, class, method, etc., via Imenu
    442 (@pxref{Imenu,,, emacs, GNU Emacs Manual}).  Eglot provides its own
    443 variant of @code{imenu-create-index-function}, which generates the
    444 index for the buffer based on language-server program source analysis.
    445 
    446 @item
    447 Enhanced completion of symbol at point by the
    448 @code{completion-at-point} command (@pxref{Symbol Completion,,, emacs,
    449 GNU Emacs Manual}).  This uses the language-server's parser data for
    450 the completion candidates.
    451 
    452 @item
    453 Automatic reformatting of source code as you type it.  This is similar
    454 to what the @code{eglot-format} command does (see below), but is
    455 activated automatically as you type.
    456 
    457 @item
    458 If a completion package such as @code{company-mode}, a popular
    459 third-party completion package (or any other completion package), is
    460 installed, Eglot enhances it by providing completion candidates based
    461 on the language-server analysis of the source code.
    462 (@code{company-mode} can be installed from GNU ELPA.)
    463 
    464 @item
    465 If @code{yasnippet}, a popular third-party package for automatic
    466 insertion of code templates (snippets), is installed, and the language
    467 server supports snippet completion candidates, Eglot arranges for the
    468 completion package to instantiate these snippets using
    469 @code{yasnippet}.  (@code{yasnippet} can be installed from GNU ELPA.)
    470 
    471 @item
    472 If the popular third-party package @code{markdown-mode} is installed,
    473 and the server provides at-point documentation formatted as Markdown
    474 in addition to plain text, Eglot arranges for the ElDoc package to
    475 enrich this text with fontifications and other nice formatting before
    476 displaying it to the user.  This makes the documentation shown by
    477 ElDoc look nicer on display.
    478 
    479 @item
    480 In addition to enabling and enhancing other features and packages,
    481 Eglot also provides a number of user commands based on the
    482 capabilities of language servers.  Examples include renaming symbols
    483 with @kbd{eglot-rename} and asking to automatically correct problems
    484 with @kbd{eglot-code-actions}.  @xref{Eglot Commands}.
    485 @end itemize
    486 
    487 Not all servers support the full set of LSP capabilities, but most of
    488 them support enough to enable the basic set of features mentioned
    489 above.
    490 
    491 Conversely, some servers offer capabilities for which no equivalent
    492 Emacs package exists yet, and so Eglot cannot (yet) expose these
    493 capabilities to Emacs users.  However, @xref{Extending Eglot}.
    494 
    495 Finally, it's worth noting that, by default, Eglot generally turns on
    496 all features that it @emph{can} turn on.  It's possible to opt out of
    497 some features via user options (@pxref{Customizing Eglot}) and a hook
    498 that runs after Eglot starts managing a buffer (@pxref{Eglot and
    499 Buffers}).
    500 
    501 @node Eglot and Buffers
    502 @section Buffers, Projects, and Eglot
    503 @cindex buffers managed by Eglot
    504 @cindex projects and Eglot
    505 
    506 @cindex workspace
    507 One of the main strong points of using a language server is that a
    508 language server has a broad view of the program: it considers more
    509 than just the single source file you are editing.  Ideally, the
    510 language server should know about all the source files of your program
    511 which are written in the language supported by the server.  In the
    512 language-server parlance, the set of the source files of a program is
    513 known as a @dfn{workspace}.  The Emacs equivalent of a workspace is a
    514 @dfn{project} (@pxref{Projects,,, emacs, GNU Emacs Manual}).  Eglot
    515 fully supports Emacs projects, and considers the file in whose buffer
    516 Eglot is turned on as belonging to a project.  In the simplest case,
    517 that file is the entire project, i.e.@: your project consists of a
    518 single file.  But there are other more complex projects:
    519 
    520 @itemize @bullet
    521 @item
    522 A single-directory project: several source files in a single common
    523 directory.
    524 
    525 @item
    526 A VC project: source files in a directory hierarchy under some VCS,
    527 e.g.@: a VCS repository (@pxref{Version Control,,, emacs, GNU Emacs
    528 Manual}).
    529 
    530 @item
    531 An EDE project: source files in a directory hierarchy managed via the
    532 Emacs Development Environment (@pxref{EDE,,, emacs, GNU Emacs
    533 Manual}).
    534 @end itemize
    535 
    536 Eglot uses Emacs's project management infrastructure to figure out
    537 which files and buffers belong to what project, so any kind of project
    538 supported by that infrastructure is automatically supported by Eglot.
    539 
    540 When Eglot starts a server program, it does so in the project's root
    541 directory, which is usually the top-level directory of the project's
    542 directory hierarchy.  This ensures the language server has the same
    543 comprehensive view of the project's files as you do.
    544 
    545 For example, if you visit the file @file{~/projects/fooey/lib/x.foo}
    546 and @file{x.foo} belongs to a project rooted at
    547 @file{~/projects/fooey} (perhaps because a @file{.git} directory
    548 exists there), then @kbd{M-x eglot} causes the server program to start
    549 with that root as the current working directory.  The server then will
    550 analyze not only the file @file{lib/x.foo} you visited, but likely
    551 also all the other @file{*.foo} files under the
    552 @file{~/projects/fooey} directory.
    553 
    554 In some cases, additional information specific to a given project will
    555 need to be provided to the language server when starting it.  The
    556 variable @code{eglot-workspace-configuration} (@pxref{Customizing
    557 Eglot}) exists for that purpose.  It specifies the parameters and
    558 their values to communicate to each language server which needs that.
    559 
    560 When Eglot is active for a project, it performs several background
    561 activities on behalf of the project and its buffers:
    562 
    563 @itemize @bullet
    564 @cindex mode-line indication of language server
    565 @cindex mouse clicks on mode-line, and Eglot
    566 @vindex eglot-menu
    567 @item
    568 All of the project's file-visiting buffers under the same major-mode
    569 are served by a single language-server connection.  (If the project
    570 uses several programming languages, there will usually be a separate
    571 server connection for each group of files written in the same language
    572 and using the same Emacs major-mode.)  Eglot adds the
    573 @samp{[eglot:@var{project}]} indication to the mode line of
    574 each such buffer, where @var{server} is the name of the server and
    575 @var{project} identifies the project by its root directory.  Clicking
    576 the mouse on the Eglot mode-line indication activates a menu with
    577 server-specific items.
    578 
    579 @item
    580 For each buffer in which Eglot is active, it notifies the language
    581 server that Eglot is @dfn{managing} the file visited by that buffer.
    582 This tells the language server that the file's contents on disk may no
    583 longer be up-to-date due to unsaved edits.  Eglot reports to the
    584 server any changes in the text of each managed buffer, to make the
    585 server aware of unsaved changes.  This includes your editing of the
    586 buffer and also changes done automatically by other Emacs features and
    587 commands.  Killing a buffer relinquishes its management by Eglot and
    588 notifies the server that the file on disk is up-to-date.
    589 
    590 @vindex eglot-managed-mode-hook
    591 @vindex eglot-managed-p
    592 @item
    593 Eglot turns on a special minor mode in each buffer it manages.  This
    594 minor mode ensures the server is notified about files Eglot manages,
    595 and also arranges for other Emacs features supported by Eglot
    596 (@pxref{Eglot Features}) to receive information from the language
    597 server, by changing the settings of these features.  Unlike other
    598 minor-modes, this special minor mode is not activated manually by the
    599 user, but automatically, as the result of starting an Eglot session
    600 for the buffer.  However, this minor mode provides a hook variable
    601 @code{eglot-managed-mode-hook} that can be used to customize the Eglot
    602 management of the buffer.  This hook is run both when the minor mode
    603 is turned on and when it's turned off; use the variable
    604 @code{eglot-managed-p} to tell if current buffer is still being
    605 managed or not.  When Eglot stops managing the buffer, this minor mode
    606 is turned off, and all the settings that Eglot changed are restored to
    607 their original values.
    608 
    609 @item
    610 When you visit a file under the same project, whether an existing or a
    611 new file, its buffer is automatically added to the set of buffers
    612 managed by Eglot, and the server which supports the buffer's
    613 major-mode is notified about that.  Thus, visiting a non-existent file
    614 @file{/home/joe/projects/fooey/lib/y.foo} in the above example will
    615 notify the server of the @file{*.foo} files' language that a new file
    616 was added to the project, even before the file appears on disk.  The
    617 special Eglot minor mode is also turned on automatically in the buffer
    618 visiting the file.
    619 @end itemize
    620 
    621 @node Eglot Commands
    622 @section Eglot Commands
    623 @cindex commands, Eglot
    624 
    625 This section provides a reference for the most commonly used Eglot
    626 commands:
    627 
    628 @ftable @code
    629 @item M-x eglot
    630 This command adds the current buffer and the file it visits to the
    631 group of buffers and files managed by Eglot on behalf of a suitable
    632 language server.  If a language server for the buffer's
    633 @code{major-mode} (@pxref{Major Modes,,, emacs, GNU Emacs Manual}) is
    634 not yet running, it will be started; otherwise the buffer and its file
    635 will be added to those managed by an existing server session.
    636 
    637 The command attempts to figure out the buffer's major mode and the
    638 suitable language server; in case it fails, it might prompt for the
    639 major mode to use and for the server program to start.  If invoked
    640 with @kbd{C-u}, it always prompts for the server program, and if
    641 invoked with @kbd{C-u C-u}, it also prompts for the major mode.
    642 
    643 If the language server is successfully started and contacted, this
    644 command arranges for any other buffers belonging to the same project
    645 and using the same major mode to use the same language-server session.
    646 That includes any buffers created by visiting files after this command
    647 succeeds to connect to a language server.
    648 
    649 All the Emacs features that are capable of using Eglot services
    650 (@pxref{Eglot Features}) are automatically configured by this command
    651 to start using the language server via Eglot.  To customize which
    652 Emacs features will be configured to use Eglot, use the
    653 @code{eglot-stay-out-of} option (@pxref{Customizing Eglot}).
    654 
    655 @item M-x eglot-reconnect
    656 This command shuts down the current connection to the language
    657 server and immediately restarts it using the same options used
    658 originally.  This can sometimes be useful to unclog a partially
    659 malfunctioning server connection.
    660 
    661 @item M-x eglot-shutdown
    662 This command shuts down a language server.  It prompts for a language
    663 server to shut down (unless there's only one server session, and it
    664 manages the current buffer).  Then the command shuts down the server
    665 and stops managing the buffers the server was used for.  Emacs
    666 features (@pxref{Eglot Features}) that Eglot configured to work with
    667 the language server are restored back to their original configuration.
    668 
    669 Normally, this command kills the buffers used for communicating with
    670 the language server, but if invoked with a prefix argument @kbd{C-u},
    671 the command doesn't kill those buffers, allowing them to be used for
    672 diagnostics and problem reporting (@pxref{Troubleshooting Eglot}).
    673 
    674 @item M-x eglot-shutdown-all
    675 This command shuts down all the language servers active in the current
    676 Emacs session.  As with @code{eglot-shutdown}, invoking this command
    677 with a prefix argument avoids killing the buffers used for
    678 communications with the language servers.
    679 
    680 @item M-x eglot-rename
    681 This command renames the program symbol (a.k.a.@: @dfn{identifier}) at
    682 point to another name.  It prompts for the new name of the symbol, and
    683 then modifies all the files in the project which are managed by the
    684 language server of the current buffer to implement the renaming.
    685 
    686 @item M-x eglot-format
    687 This command reformats the active region according to the
    688 language-server rules.  If no region is active, it reformats the
    689 entire current buffer.
    690 
    691 @item M-x eglot-format-buffer
    692 This command reformats the current buffer, in the same manner as
    693 @code{eglot-format} does.
    694 
    695 @cindex code actions
    696 @item M-x eglot-code-actions
    697 @itemx M-x eglot-code-action-organize-imports
    698 @itemx M-x eglot-code-action-quickfix
    699 @itemx M-x eglot-code-action-extract
    700 @itemx M-x eglot-code-action-inline
    701 @itemx M-x eglot-code-action-rewrite
    702 These commands allow you to invoke the so-called @dfn{code actions}:
    703 requests for the language server to provide editing commands for
    704 correcting, refactoring or beautifying your code.  These commands may
    705 affect more than one visited file belonging to the project.
    706 
    707 The command @code{eglot-code-actions} asks the server if there are any
    708 code actions for any point in the buffer or contained in the active
    709 region.  If there are, you have the choice to execute one of them via
    710 the minibuffer.
    711 
    712 A common use of code actions is fixing the Flymake error diagnostics
    713 issued by Eglot (@pxref{Top,,, flymake, GNU Flymake manual}).
    714 Clicking on a diagnostic with @kbd{mouse-2} invokes
    715 @code{eglot-code-actions-at-mouse} which pops up a menu of available
    716 code actions.  The variable @code{eglot-diagnostics-map} can be used
    717 to control the mouse binding.
    718 
    719 Other commands execute a specific code action.  For example,
    720 @code{eglot-code-action-organize-imports} rearranges the program's
    721 @dfn{imports}---declarations of modules whose capabilities the program
    722 uses.
    723 
    724 @cindex inlay hints
    725 @item M-x eglot-inlay-hints-mode
    726 This command toggles LSP @dfn{inlay hints} on and off for the current
    727 buffer.  Inlay hints are small text annotations to specific parts of
    728 the whole buffer, not unlike diagnostics, but designed to help
    729 readability instead of indicating problems.  For example, a C++
    730 language server can serve hints about positional parameter names in
    731 function calls and a variable's automatically deduced type.  Inlay
    732 hints help the user not have to remember these things by heart.
    733 @end ftable
    734 
    735 The following Eglot commands are used less commonly, mostly for
    736 diagnostic and troubleshooting purposes:
    737 
    738 @ftable @code
    739 @item M-x eglot-events-buffer
    740 This command pops up the events buffer used for communication with the
    741 language server of the current buffer.
    742 
    743 @item M-x eglot-stderr-buffer
    744 This command pops up the buffer with the debug info printed by the
    745 language server to its standard error stream.
    746 
    747 @item M-x eglot-forget-pending-continuations
    748 Forget pending requests for the server of the current buffer.
    749 @c FIXME: Better description of the need.
    750 
    751 @item M-x eglot-signal-didChangeConfiguration
    752 This command updates the language server configuration according to
    753 the current value of the variable @code{eglot-workspace-configuration}
    754 (@pxref{Customizing Eglot}).
    755 
    756 @item M-x eglot-clear-status
    757 Clear the last JSONRPC error for the server of the current buffer.
    758 Eglot keeps track of erroneous situations encountered by the server in
    759 its mode-line indication so that the user may inspect the
    760 communication leading up to it (@pxref{Troubleshooting Eglot}).  If
    761 the situation is deemed uninteresting or temporary, this command can
    762 be used to ``forget'' the error.  Note that the command @code{M-x
    763 eglot-reconnect} can sometimes be used to unclog a temporarily
    764 malfunctioning server.
    765 @end ftable
    766 
    767 As described in @ref{Eglot Features} most features associated with
    768 Eglot are actually provided by other Emacs packages and features, and
    769 Eglot only enhances them by allowing them to use the information
    770 coming from the language servers.  For completeness, here's the list
    771 of commands of those other packages that are very commonly used in
    772 Eglot-managed buffers:
    773 
    774 @c Not @ftable, because the index entries should mention Eglot
    775 @table @code
    776 @cindex eldoc, and Eglot
    777 @cindex documentation using Eglot
    778 @item M-x eldoc
    779 Ask the ElDoc system for help at point.
    780 
    781 @cindex flymake, and Eglot
    782 @cindex on-the-fly diagnostics using Eglot
    783 @item M-x flymake-show-buffer-diagnostics
    784 Ask Flymake system to display diagnostics for the current buffer.
    785 
    786 @item M-x flymake-show-project-diagnostics
    787 Ask Flymake to list diagnostics for all the files in the current
    788 project.
    789 
    790 @cindex xref, and Eglot
    791 @cindex finding definitions of identifiers using Eglot
    792 @item M-x xref-find-definitions
    793 Ask Xref to go the definition of the identifier at point.
    794 
    795 @cindex imenu navigation using Eglot
    796 @item M-x imenu
    797 Let the user navigate the program source code using buffer index,
    798 categorizing program elements by syntactic class (class, method,
    799 variable, etc.) and offering completion.
    800 
    801 @cindex symbol completion using Eglot
    802 @item M-x completion-at-point
    803 Request completion of the symbol at point.
    804 @end table
    805 
    806 @node Eglot Variables
    807 @section Eglot Variables
    808 @cindex variables, Eglot
    809 
    810 This section provides a reference for the Eglot user options.
    811 
    812 @vtable @code
    813 @item eglot-autoreconnect
    814 This option controls the ability to reconnect automatically to the
    815 language server when Eglot detects that the server process terminated
    816 unexpectedly.  The default value @code{3} means to attempt reconnection only
    817 if the previous successful connection lasted for more than that number
    818 of seconds; a different positive value changes the minimal length of
    819 the connection to trigger reconnection.  A value of @code{t} means
    820 always reconnect automatically, and @code{nil} means never reconnect
    821 (in which case you will need to reconnect manually using @kbd{M-x
    822 eglot}).
    823 
    824 @item eglot-connect-timeout
    825 This specifies the number of seconds before connection attempt to a
    826 language server times out.  The value of @code{nil} means never time
    827 out.  The default is 30 seconds.
    828 
    829 @item eglot-sync-connect
    830 This setting is mainly important for connections which are slow to
    831 establish.  Whereas the variable @code{eglot-connect-timeout} controls
    832 how long to wait for, this variable controls whether to block Emacs's
    833 user interface while waiting.  The default value is @code{3}; a positive
    834 value means block for that many seconds, then wait for the connection
    835 in the background.  The value of @code{t} means block during the whole
    836 waiting period.  The value of @code{nil} or @code{0} means don't block at
    837 all during the waiting period.
    838 
    839 @item eglot-events-buffer-config
    840 This configures the size and format of the Eglot events buffer.
    841 @xref{Eglot Commands, eglot-events-buffer}, for how to access that
    842 buffer.  If the value is changed, the connection should be restarted
    843 using @kbd{M-x eglot-reconnect} for the new value to take effect.
    844 @c FIXME: Shouldn't the defcustom do this by itself using the :set
    845 @c attribute?  Maybe not because reconnecting is a complex task.
    846 @xref{Troubleshooting Eglot}, for when this could be useful.
    847 
    848 @item eglot-autoshutdown
    849 If this is non-@code{nil}, Eglot shuts down a language server when the
    850 last buffer managed by it is killed.  @xref{Shutting Down LSP Servers}.
    851 The default is @code{nil}; if you want to shut down a server, use
    852 @kbd{M-x eglot-shutdown} (@pxref{Eglot Commands}).
    853 
    854 @item eglot-confirm-server-edits
    855 Various Eglot commands and code actions result in the language server
    856 sending editing commands to Emacs.  If this option's value is
    857 non-@code{nil}, Eglot will ask for confirmation before performing
    858 edits proposed by the language server.  This option's value can be
    859 crafted to require this confirmation for specific commands or only
    860 when the edit affects files not yet visited by the user.  Consult this
    861 option's docstring for more information.
    862 
    863 @item eglot-ignored-server-capabilities
    864 This variable's value is a list of language server capabilities that
    865 Eglot should not use.  The default is @code{nil}: Eglot uses all of
    866 the capabilities supported by each server.
    867 
    868 @item eglot-extend-to-xref
    869 If this is non-@code{nil}, and @kbd{M-.}
    870 (@code{xref-find-definitions}) lands you in a file outside of your
    871 project, such as a system-installed library or header file,
    872 transiently consider that file as managed by the same language server.
    873 That file is still outside your project (i.e. @code{project-find-file}
    874 won't find it), but Eglot and the server will consider it to be part
    875 of the workspace.  The default is @code{nil}.
    876 
    877 @item eglot-mode-map
    878 This variable is the keymap for binding Eglot-related command.  It is
    879 in effect only as long as the buffer is managed by Eglot.  By default,
    880 it is empty, with the single exception: @kbd{C-h .} is remapped to
    881 invoke @code{eldoc-doc-buffer}.  You can bind additional commands in
    882 this map.  For example:
    883 
    884 @lisp
    885   (define-key eglot-mode-map (kbd "C-c r") 'eglot-rename)
    886   (define-key eglot-mode-map (kbd "C-c o") 'eglot-code-action-organize-imports)
    887   (define-key eglot-mode-map (kbd "C-c h") 'eldoc)
    888   (define-key eglot-mode-map (kbd "<f6>") 'xref-find-definitions)
    889 @end lisp
    890 
    891 @end vtable
    892 
    893 Additional variables, which are relevant for customizing the server
    894 connections, are documented in @ref{Customizing Eglot}.
    895 
    896 @node Customizing Eglot
    897 @chapter Customizing Eglot
    898 @cindex customizing Eglot
    899 
    900 Eglot itself has a relatively small number of customization options.
    901 A large part of customizing Eglot to your needs and preferences should
    902 actually be done via options of the Emacs packages and features which
    903 Eglot supports and enhances (@pxref{Eglot Features}).  For example:
    904 
    905 @itemize @bullet
    906 @item
    907 To configure the face used for server-derived errors and warnings,
    908 customize the Flymake faces @code{flymake-error} and
    909 @code{flymake-warning}.
    910 
    911 @item
    912 To configure the amount of space taken up by documentation in the
    913 echo area, customize the ElDoc variable
    914 @code{eldoc-echo-area-use-multiline-p}.
    915 
    916 @item
    917 To completely change how ElDoc displays the at-point documentation
    918 destination, customize the ElDoc variable
    919 @code{eldoc-display-functions}.
    920 @end itemize
    921 
    922 For this reason, this manual describes only how to customize
    923 Eglot's own operation, which mainly has to do with the server
    924 connections and the server features to be used by Eglot.
    925 
    926 @c @table, not @vtable, because some of the variables are indexed
    927 @c elsewhere
    928 @table @code
    929 @item eglot-server-programs
    930 This variable determines which language server to start for each
    931 supported major mode, and how to invoke that server's program.
    932 @xref{Setting Up LSP Servers}, for the details.
    933 
    934 @vindex eglot-strict-mode
    935 @item eglot-strict-mode
    936 This is @code{nil} by default, meaning that Eglot is generally lenient
    937 about non-conforming servers.  If you need to debug a server, set this
    938 to @w{@code{(disallow-non-standard-keys enforce-required-keys)}}.
    939 
    940 @vindex eglot-server-initialized-hook
    941 @item eglot-server-initialized-hook
    942 A hook run after the server object is successfully initialized.
    943 
    944 @vindex eglot-connect-hook
    945 @item eglot-connect-hook
    946 A hook run after connection to the server is successfully
    947 established.  @xref{Starting Eglot}.
    948 
    949 @item eglot-managed-mode-hook
    950 A hook run after Eglot started or stopped managing a buffer.
    951 @xref{Eglot and Buffers}, for details of its usage.
    952 
    953 @vindex eglot-stay-out-of
    954 @item eglot-stay-out-of
    955 This variable's value lists Emacs features that Eglot shouldn't
    956 automatically try to manage on the user's behalf.  It is useful, for
    957 example, when you need to use non-LSP Flymake or Company back-ends.
    958 To have Eglot stay away from some Emacs feature, add that feature's
    959 symbol or a regexp that will match a symbol's name to the list: for
    960 example, the symbol @code{xref} to leave Xref alone, or the string
    961 @samp{company} to stay away from your Company customizations.  Here's an
    962 example:
    963 
    964 @lisp
    965 (add-to-list 'eglot-stay-out-of 'flymake)
    966 @end lisp
    967 
    968 Note that you can still configure the excluded Emacs features manually
    969 to use Eglot in your @code{eglot-managed-mode-hook} or via some other
    970 mechanism.
    971 
    972 @vindex eglot-report-progress
    973 @cindex progress
    974 @item eglot-report-progress
    975 Set this variable to true if you'd like progress notifications coming
    976 from the language server to be handled as Emacs's progress reporting
    977 facilities.
    978 @end table
    979 
    980 @node Advanced server configuration
    981 @chapter Advanced server configuration
    982 
    983 Though many language servers work well out-of-the-box, most allow
    984 fine-grained control of their operation via specific configuration
    985 options that are transmitted over the LSP protocol and vary from
    986 server to server.  A small number of servers require such special
    987 configuration to work acceptably, or even to work at all.
    988 
    989 After having setup a server executable program in
    990 @code{eglot-server-programs} (@pxref{Setting Up LSP Servers}) and
    991 ensuring Eglot can invoke it, you may want to take advantage of some
    992 of these options.  You should first distinguish two main kinds of
    993 server configuration:
    994 
    995 @itemize @bullet
    996 @item
    997 Project-specific, applying to a specific project;
    998 
    999 @item
   1000 User-specific, applying to all projects the server is used for.
   1001 @end itemize
   1002 
   1003 When you have decided which kind you need, the following sections
   1004 teach how Eglot's user variables can be used to achieve it:
   1005 
   1006 @menu
   1007 * Project-specific configuration::
   1008 * User-specific configuration::
   1009 * JSONRPC objects in Elisp::
   1010 @end menu
   1011 
   1012 It's important to note that not all servers allow both kinds of
   1013 configuration, nor is it guaranteed that user options can be copied
   1014 over to project options, and vice-versa.  When in doubt, consult your
   1015 language server's documentation.
   1016 
   1017 It's also worth noting that some language servers can read these
   1018 settings from configuration files in the user's @code{HOME} directory
   1019 or in a project's directory.  For example, the @command{pylsp} Python
   1020 server reads the file @file{~/.config/pycodestyle} for user
   1021 configuration.  The @command{clangd} C/C++ server reads both
   1022 @file{~/.config/clangd/config.yaml} for user configuration and
   1023 @file{.clangd} for project configuration.  It may be advantageous to
   1024 use these mechanisms instead of Eglot's, as this will probably work
   1025 with other LSP clients and may be easier to debug than options riding
   1026 on the LSP wire.
   1027 
   1028 @node Project-specific configuration
   1029 @section Project-specific configuration
   1030 @vindex eglot-workspace-configuration
   1031 @cindex workspace configuration
   1032 
   1033 To set project-specific settings, which the LSP specification calls
   1034 @dfn{workspace configuration}, the variable
   1035 @code{eglot-workspace-configuration} may be used.
   1036 
   1037 This variable is a directory-local variable (@pxref{Directory
   1038 Variables, , Per-directory Local Variables, emacs, The GNU Emacs
   1039 Manual}).  It's important to recognize that this variable really only
   1040 makes sense when set directory-locally.  It usually does not make
   1041 sense to set it file-locally or in a major-mode hook.
   1042 
   1043 The most common way to set @code{eglot-workspace-configuration } is
   1044 using a @file{.dir-locals.el} file in the root of your project.  If
   1045 you can't do that, you may also set it from Elisp code via the
   1046 @code{dir-locals-set-class-variables} function.  (@pxref{Directory
   1047 Local Variables,,, elisp, GNU Emacs Lisp Reference Manual}).
   1048 
   1049 However you choose to set it, the variable's value is a plist
   1050 (@pxref{Property Lists,,, elisp, GNU Emacs Lisp Reference Manual}) with
   1051 the following format:
   1052 
   1053 @lisp
   1054  (@var{:server1} @var{plist1} @var{:server2} @var{plist2} @dots{})
   1055 @end lisp
   1056 
   1057 @noindent
   1058 Here, @var{:server1} and @var{:server2} are keywords whose names
   1059 identify the LSP language servers to target.  Consult server
   1060 documentation to find out what name to use.  @var{plist1} and
   1061 @var{plist2} are plists of options, possibly nesting other plists.
   1062 
   1063 @findex eglot-show-workspace-configuration
   1064 When experimenting with workspace settings, you can use the command
   1065 @kbd{M-x eglot-show-workspace-configuration} to inspect and debug the
   1066 value of this variable in its final JSON form, ready to be sent to the
   1067 server (@pxref{JSONRPC objects in Elisp}).  This helper command works
   1068 even before actually connecting to the server.
   1069 
   1070 These variable's value doesn't take effect immediately.  That happens
   1071 upon establishing the connection, in response to an explicit query
   1072 from the server, or when issuing the command @kbd{M-x
   1073 eglot-signal-didChangeConfiguration} which notifies the server during
   1074 an ongoing Eglot session.
   1075 
   1076 @subsection Examples
   1077 
   1078 For some users, setting @code{eglot-workspace-configuration} is a
   1079 somewhat daunting task.  One of the reasons is having to manage the
   1080 general Elisp syntax of per-mode directory-local variables, which uses
   1081 alists (@pxref{Association Lists,,, elisp, GNU Emacs Lisp Reference
   1082 Manual}), and the specific syntax of Eglot's variable, which uses
   1083 plists.  Some examples are useful.
   1084 
   1085 Let's say you want to configure two language servers to be used in a
   1086 project written in a combination of the Python and Go languages.  You
   1087 want to use the @command{pylsp} and @command{gopls} languages
   1088 servers.  In the documentation of the servers in question (or in some
   1089 other editor's configuration file, or in some blog article), you find
   1090 the following configuration options in informal dotted-notation
   1091 syntax:
   1092 
   1093 @example
   1094 pylsp.plugins.jedi_completion.include_params: true
   1095 pylsp.plugins.jedi_completion.fuzzy: true
   1096 pylsp.pylint.enabled: false
   1097 gopls.usePlaceholders: true
   1098 @end example
   1099 
   1100 To apply this to Eglot, and assuming you chose the
   1101 @file{.dir-locals.el} file method, the contents of that file could be:
   1102 
   1103 @lisp
   1104 ((nil
   1105   . ((eglot-workspace-configuration
   1106       . (:pylsp (:plugins (:jedi_completion (:include_params t
   1107                                              :fuzzy t)
   1108                            :pylint (:enabled :json-false)))
   1109          :gopls (:usePlaceholders t)))))
   1110  (python-base-mode . ((indent-tabs-mode . nil)))
   1111  (go-mode          . ((indent-tabs-mode . t))))
   1112 @end lisp
   1113 
   1114 @noindent
   1115 This sets the value of @code{eglot-workspace-configuration} in all the
   1116 buffers inside the project; each server will use only the section of
   1117 the parameters intended for that server, and ignore the rest.  Note
   1118 how alists are used for associating Emacs mode names with alists
   1119 associating variable names with variable values.  Then notice how
   1120 plists are used inside the value of
   1121 @code{eglot-workspace-configuration}.
   1122 
   1123 This following form may also be used:
   1124 
   1125 @lisp
   1126 ((python-base-mode
   1127   . ((eglot-workspace-configuration
   1128       . (:pylsp (:plugins (:jedi_completion (:include_params t
   1129                                              :fuzzy t)
   1130                            :pylint (:enabled :json-false)))))
   1131      (indent-tabs-mode . nil)))
   1132  (go-mode
   1133   . ((eglot-workspace-configuration
   1134       . (:gopls (:usePlaceholders t)))
   1135      (indent-tabs-mode . t))))
   1136 @end lisp
   1137 
   1138 @noindent
   1139 This sets up the value of @code{eglot-workspace-configuration}
   1140 separately depending on the major mode of each of that project's
   1141 buffers.  @code{python-base-mode} buffers will have the variable set to
   1142 @code{(:pylsp (:plugins ...))}.  @code{go-mode} buffers will have the
   1143 variable set to @code{(:gopls (:usePlaceholders t))}.
   1144 
   1145 Some servers will issue workspace configuration for specific files
   1146 inside your project.  For example, if you know @code{gopls} is asking
   1147 about specific files in the @code{src/imported} subdirectory and you
   1148 want to set a different option for @code{gopls.usePlaceholders} , you
   1149 may use something like:
   1150 
   1151 @lisp
   1152 ((python-base-mode
   1153   . ((eglot-workspace-configuration
   1154       . (:pylsp (:plugins (:jedi_completion (:include_params t
   1155                                              :fuzzy t)
   1156                            :pylint (:enabled :json-false)))))
   1157      (indent-tabs-mode nil)))
   1158  (go-mode
   1159   . ((eglot-workspace-configuration
   1160       . (:gopls (:usePlaceholders t)))
   1161      (indent-tabs-mode t)))
   1162  ("src/imported"
   1163    . ((eglot-workspace-configuration
   1164       . (:gopls (:usePlaceholders nil))))))
   1165 @end lisp
   1166 
   1167 Finally, if one needs to determine the workspace configuration based
   1168 on some dynamic context, @code{eglot-workspace-configuration} can be
   1169 set to a function.  The function is called with the
   1170 @code{eglot-lsp-server} instance of the connected server (if any) and
   1171 with @code{default-directory} set to the root of the project.  The
   1172 function should return a plist suitable for use as the variable's
   1173 value.
   1174 
   1175 @node User-specific configuration
   1176 @section User-specific configuration
   1177 @cindex initializationOptions
   1178 @cindex command-line arguments
   1179 
   1180 This kind of configuration applies to all projects the server is used
   1181 for.  Here, there are a number of ways to do this inside Eglot.
   1182 
   1183 A common way is to pass command-line options to the server invocation
   1184 via @code{eglot-server-programs}.  Let's say we want to configure
   1185 where the @command{clangd} server reads its
   1186 @code{compile_commands.json} from.  This can be done like so:
   1187 
   1188 @lisp
   1189 (with-eval-after-load 'eglot
   1190   (add-to-list 'eglot-server-programs
   1191                `(c++-mode . ("clangd" "--compile-commands-dir=/tmp"))))
   1192 
   1193 @end lisp
   1194 
   1195 @noindent
   1196 Another way is to have Eglot pass a JSON object to the server during
   1197 the LSP handshake.  This is done using the
   1198 @code{:initializationOptions} syntax of @code{eglot-server-programs}:
   1199 
   1200 @lisp
   1201 (with-eval-after-load 'eglot
   1202   (add-to-list 'eglot-server-programs
   1203                `(c++-mode . ("clangd" :initializationOptions
   1204                                       (:compilationDatabasePath "/tmp")))))
   1205 @end lisp
   1206 
   1207 @noindent
   1208 The argument @code{(:compilationDatabasePath "/tmp")} is Emacs's
   1209 representation in plist format of a simple JSON object
   1210 @code{@{"compilationDatabasePath": "/tmp"@}}.  To learn how to
   1211 represent more deeply nested options in this format, @pxref{JSONRPC
   1212 objects in Elisp}.
   1213 
   1214 In this case, the two examples achieve exactly the same, but notice
   1215 how the option's name has changed between them.
   1216 
   1217 @vindex eglot-workspace-configuration
   1218 Finally there is another way to do user-specific configuration of
   1219 language servers, which may be used if the methods above are not
   1220 supported.  It consists of @emph{globally} setting
   1221 @code{eglot-workspace-configuration}, a variable originally intended
   1222 for project-specific configuration.  This has the same effect as
   1223 giving all your projects a certain default configuration, as described
   1224 in @ref{Project-specific configuration}.  Here is an example:
   1225 
   1226 @lisp
   1227 (setq-default eglot-workspace-configuration
   1228               '(:pylsp (:plugins (:jedi_completion (:include_params t
   1229                                                     :fuzzy t)
   1230                                   :pylint (:enabled :json-false)))
   1231                 :gopls (:usePlaceholders t)))
   1232 @end lisp
   1233 
   1234 Note that the global value of @code{eglot-workspace-configuration} is
   1235 always overridden if a directory-local value is detected.
   1236 
   1237 @node JSONRPC objects in Elisp
   1238 @section JSONRPC objects in Elisp
   1239 
   1240 Emacs's preferred way of representing JSON is via Lisp lists.  In
   1241 Eglot, the syntax of this list is the simplest possible (the one with
   1242 fewer parenthesis), a plist (@pxref{Property Lists,,, elisp, GNU Emacs
   1243 Lisp Reference Manual}).
   1244 
   1245 The plist may be arbitrarily complex, and generally containing other
   1246 keyword-value property sub-plists corresponding to JSON sub-objects.
   1247 
   1248 For representing the JSON leaf values @code{true}, @code{false},
   1249 @code{null} and @code{@{@}}, you can use the Lisp values @code{t},
   1250 @code{:json-false}, @code{nil}, and @code{eglot-@{@}}, respectively.
   1251 JSON arrays are represented as Elisp vectors surrounded by square brackets
   1252 (@pxref{Vectors,,,elisp,GNU Emacs Lisp Reference Manual}).
   1253 
   1254 For example, the plist
   1255 
   1256 @lisp
   1257 (:pylsp (:plugins (:jedi_completion (:include_params t
   1258                                      :fuzzy t
   1259                                      :cache_for ["pandas" "numpy"])
   1260                    :pylint (:enabled :json-false)))
   1261  :gopls (:usePlaceholders t))
   1262 @end lisp
   1263 
   1264 @noindent
   1265 is serialized by Eglot to the following JSON text:
   1266 
   1267 @example
   1268 @{
   1269   "pylsp": @{
   1270     "plugins": @{
   1271       "jedi_completion": @{
   1272         "include_params": true,
   1273         "fuzzy": true,
   1274         "cache_for": [ "pandas", "numpy" ]
   1275       @},
   1276       "pylint": @{
   1277         "enabled": false
   1278       @}
   1279     @}
   1280   @},
   1281   "gopls": @{
   1282     "usePlaceholders": true
   1283   @}
   1284 @}
   1285 @end example
   1286 
   1287 @node Extending Eglot
   1288 @chapter Extending Eglot
   1289 
   1290 Sometimes it may be useful to extend existing Eglot functionality
   1291 using Elisp its public methods.  A good example of when this need may
   1292 arise is adding support for a custom LSP protocol extension only
   1293 implemented by a specific server.
   1294 
   1295 The best source of documentation for this is probably Eglot source
   1296 code itself, particularly the section marked ``API''.
   1297 
   1298 Most of the functionality is implemented with Common-Lisp style
   1299 generic functions (@pxref{Generics,,,eieio,EIEIO}) that can be easily
   1300 extended or overridden.  The Eglot code itself is an example on how to
   1301 do this.
   1302 
   1303 The following is a relatively simple example that adds support for the
   1304 @code{inactiveRegions} experimental feature introduced in version 17
   1305 of the @command{clangd} C/C++ language server++.
   1306 
   1307 Summarily, the feature works by first having the server detect the
   1308 Eglot's advertisement of the @code{inactiveRegions} client capability
   1309 during startup, whereupon the language server will report a list of
   1310 regions of inactive code for each buffer.  This is usually code
   1311 surrounded by C/C++ @code{#ifdef} macros that the preprocessor removes
   1312 based on compile-time information.
   1313 
   1314 The language server reports the regions by periodically sending a
   1315 @code{textDocument/inactiveRegions} notification for each managed
   1316 buffer (@pxref{Eglot and Buffers}). Normally, unknown server
   1317 notifications are ignored by Eglot, but we're going change that.
   1318 
   1319 Both the announcement of the client capability and the handling of the
   1320 new notification is done by adding methods to generic functions.
   1321 
   1322 @itemize @bullet
   1323 @item
   1324 The first method extends @code{eglot-client-capabilities} using a
   1325 simple heuristic to detect if current server is @command{clangd} and
   1326 enables the @code{inactiveRegion} capability.
   1327 
   1328 @lisp
   1329 (cl-defmethod eglot-client-capabilities :around (server)
   1330   (let ((base (cl-call-next-method)))
   1331     (when (cl-find "clangd" (process-command
   1332                               (jsonrpc--process server))
   1333                    :test #'string-match)
   1334       (setf (cl-getf (cl-getf base :textDocument)
   1335                      :inactiveRegionsCapabilities)
   1336             '(:inactiveRegions t)))
   1337     base))
   1338 @end lisp
   1339 
   1340 Notice we use an internal function of the @code{jsonrpc.el} library,
   1341 and a regexp search to detect @command{clangd}.  An alternative would
   1342 be to define a new EIEIO subclass of @code{eglot-lsp-server}, maybe
   1343 called @code{eglot-clangd}, so that the method would be simplified:
   1344 
   1345 @lisp
   1346 (cl-defmethod eglot-client-capabilities :around ((_s eglot-clangd))
   1347   (let ((base (cl-call-next-method)))
   1348     (setf (cl-getf (cl-getf base :textDocument)
   1349                      :inactiveRegionsCapabilities)
   1350             '(:inactiveRegions t))))
   1351 @end lisp
   1352 
   1353 However, this would require that users tweak
   1354 @code{eglot-server-program} to tell Eglot instantiate such sub-classes
   1355 instead of the generic @code{eglot-lsp-server} (@pxref{Setting Up LSP
   1356 Servers}). For the purposes of this particular demonstration, we're
   1357 going to use the more hacky regexp route which doesn't require that.
   1358 
   1359 Note, however, that detecting server versions before announcing new
   1360 capabilities is generally not needed, as both server and client are
   1361 required by LSP to ignore unknown capabilities advertised by their
   1362 counterparts.
   1363 
   1364 @item
   1365 The second method implements @code{eglot-handle-notification} to
   1366 process the server notification for the LSP method
   1367 @code{textDocument/inactiveRegions}.  For each region received it
   1368 creates an overlay applying the @code{shadow} face to the region.
   1369 Overlays are recreated every time a new notification of this kind is
   1370 received.
   1371 
   1372 To learn about how @command{clangd}'s special JSONRPC notification
   1373 message is structured in detail you could consult that server's
   1374 documentation.  Another possibility is to evaluate the first
   1375 capability-announcing method, reconnect to the server and peek in the
   1376 events buffer (@pxref{Eglot Commands, eglot-events-buffer}).  You
   1377 could find something like:
   1378 
   1379 @lisp
   1380 [server-notification] Mon Sep  4 01:10:04 2023:
   1381 (:jsonrpc "2.0" :method "textDocument/inactiveRegions" :params
   1382           (:textDocument
   1383            (:uri "file:///path/to/file.cpp")
   1384            :regions
   1385            [(:start (:character 0 :line 18)
   1386              :end (:character 58 :line 19))
   1387             (:start (:character 0 :line 36)
   1388              :end (:character 1 :line 38))]))
   1389 @end lisp
   1390 
   1391 This reveals that the @code{textDocument/inactiveRegions} notification
   1392 contains a @code{:textDocument} property to designate the managed
   1393 buffer and an array of LSP regions under the @code{:regions} property.
   1394 Notice how the message (originally in JSON format), is represented as
   1395 Elisp plists (@pxref{JSONRPC objects in Elisp}).
   1396 
   1397 The Eglot generic function machinery will automatically destructure
   1398 the incoming message, so these two properties can simply be added to
   1399 the new method's lambda list as @code{&key} arguments.  Also, the
   1400 @code{eglot-uri-to-path} and @code{eglot-range-region} may be used to
   1401 easily parse the LSP @code{:uri} and @code{:start ... :end ...}
   1402 objects to obtain Emacs objects for file names and positions.
   1403 
   1404 The remainder of the implementation consists of standard Elisp
   1405 techniques to loop over arrays, manage buffers and overlays.
   1406 
   1407 @lisp
   1408 (cl-defmethod eglot-handle-notification
   1409   (_server (_method (eql textDocument/inactiveRegions))
   1410            &key regions textDocument &allow-other-keys)
   1411   (if-let* ((path (expand-file-name (eglot-uri-to-path
   1412                                      (cl-getf textDocument :uri))))
   1413             (buffer (find-buffer-visiting path)))
   1414       (with-current-buffer buffer
   1415         (remove-overlays nil nil 'inactive-code t)
   1416         (cl-loop
   1417          for r across regions
   1418          for (beg . end) = (eglot-range-region r)
   1419          for ov = (make-overlay beg end)
   1420          do
   1421          (overlay-put ov 'face 'shadow)
   1422          (overlay-put ov 'inactive-code t)))))
   1423 @end lisp
   1424 
   1425 @end itemize
   1426 
   1427 After evaluating these two additions and reconnecting to the
   1428 @command{clangd} language server (version 17), the result will be that
   1429 all the inactive code in the buffer will be nicely grayed out using
   1430 the LSP server knowledge about current compile time preprocessor
   1431 defines.
   1432 
   1433 @node Troubleshooting Eglot
   1434 @chapter Troubleshooting Eglot
   1435 @cindex troubleshooting Eglot
   1436 
   1437 This chapter documents commands and variables that can be used to
   1438 troubleshoot Eglot problems.  It also provides guidelines for
   1439 reporting Eglot bugs in a way that facilitates their resolution.
   1440 
   1441 When you encounter problems with Eglot, try first using the commands
   1442 @kbd{M-x eglot-events-buffer} and @kbd{M-x eglot-stderr-buffer}.  They
   1443 pop up special buffers that can be used to inspect the communications
   1444 between the Eglot and language server.  In many cases, this will
   1445 indicate the problems or at least provide a hint.
   1446 
   1447 @menu
   1448 * Performance::
   1449 * Getting the latest version::
   1450 * Reporting bugs::
   1451 @end menu
   1452 
   1453 @node Performance
   1454 @section Performance
   1455 @cindex performance problems, with Eglot
   1456 A common and easy-to-fix cause of performance problems in Eglot
   1457 (especially in older versions) is its events buffer, since it
   1458 represents additional work that Eglot must do (@pxref{Eglot Commands,
   1459 eglot-events-buffer}).  If you find Eglot is operating correctly but
   1460 slowly, try to customize the variable
   1461 @code{eglot-events-buffer-config} (@pxref{Eglot Variables}) and set
   1462 its @code{:size} property to 0.  This will disable recording any
   1463 events and may speed things up.
   1464 
   1465 In other situations, the cause of poor performance lies in the
   1466 language server itself.  Servers use aggressive caching and other
   1467 techniques to improve their performance.  Often, this can be tweaked
   1468 by changing the server configuration (@pxref{Advanced server
   1469 configuration}).
   1470 
   1471 @node Getting the latest version
   1472 @section Getting the latest version
   1473 @cindex upgrading Eglot
   1474 
   1475 To install the latest Eglot in an Emacs version that does not bundle
   1476 Eglot, use @kbd{M-x package-install}.
   1477 
   1478 Often, a newer Eglot version exists that has fixed a longstanding bug,
   1479 has more LSP features, or just better supports a particular language
   1480 server.  Recent Eglot versions can self-update via the command
   1481 @kbd{M-x eglot-upgrade-eglot}.  This will replace any currently
   1482 installed version with the newest one available from the ELPA archives
   1483 configured in @code{package-archives}.
   1484 
   1485 You can also update Eglot through other methods, such as
   1486 @code{use-package} (@pxref{Installing packages,,, use-package,
   1487 use-package User Manual}), @code{package-install},
   1488 @code{list-packages} or the newer @code{package-upgrade}
   1489 (@pxref{Packages,,, emacs, GNU Emacs Manual}).  However, do read the
   1490 docstrings of the command you intend to use before you use it, as some
   1491 of them may not work in exactly the same way across Emacs versions,
   1492 meaning your configuration may be not portable.
   1493 
   1494 @node Reporting bugs
   1495 @section Reporting bugs
   1496 @cindex bug reports
   1497 
   1498 If you think you have found a bug, we want to hear about it.  Before
   1499 reporting a bug, keep in mind that interaction with language servers
   1500 represents a large quantity of unknown variables.  Therefore, it is
   1501 generally both @emph{difficult} and @emph{absolutely essential} that
   1502 the maintainers reproduce bugs exactly as they happened to you, the
   1503 user.
   1504 
   1505 To report an Eglot bug, send e-mail to @email{bug-gnu-emacs@@gnu.org}.
   1506 
   1507 To understand how to write this email, get acquainted with Emacs's bug
   1508 reporting guidelines (@pxref{Bugs,,, emacs, GNU Emacs Manual}).  Then,
   1509 follow this Eglot-specific checklist:
   1510 
   1511 @enumerate
   1512 @item
   1513 Include the transcript of JSONRPC events obtained from the buffer
   1514 popped up by @kbd{M-x eglot-events-buffer}.  You may narrow down the
   1515 transcript if you are sure of where the problematic exchange is, but
   1516 it's safer to include the whole transcript, either attached or inline.
   1517 
   1518 @item
   1519 If Emacs signaled an error (an error message was seen or heard), make
   1520 sure to repeat the process after turning on @code{debug-on-error} via
   1521 @kbd{M-x toggle-debug-on-error}.  This normally produces a backtrace
   1522 of the error that should also be attached to the bug report.
   1523 
   1524 @item
   1525 Include a description of how the maintainer should obtain, install,
   1526 and configure the language server you used.  Maintainers usually have
   1527 access to GNU/Linux systems, though not necessarily the distribution
   1528 that you may be using.  If possible, try to replicate the problem with
   1529 the C/C@t{++} or Python servers, as these are very easy to install.
   1530 
   1531 @item
   1532 Describe how to setup a @emph{minimal} project directory where Eglot
   1533 should be started for the problem to happen.  Describe each file's
   1534 name and its contents.  Alternatively, you can supply the address of a
   1535 public Git repository.
   1536 
   1537 @item
   1538 Include versions of the software used.  The Emacs version can be
   1539 obtained with @kbd{M-x emacs-version}.
   1540 
   1541 We welcome bug reports about all Eglot versions, but it is helpful to
   1542 first check if the problem isn't already fixed in the latest version
   1543 (@pxref{Getting the latest version}).
   1544 
   1545 It's also essential to include the version of ELPA packages that are
   1546 explicitly or implicitly loaded.  The optional but popular Company or
   1547 Markdown packages are distributed as GNU ELPA packages, not to mention
   1548 Eglot itself in some situations.  Some major modes (Go, Rust, etc.)
   1549 are provided by ELPA packages.  It's sometimes easy to miss these,
   1550 since they are usually implicitly loaded when visiting a file in that
   1551 language.
   1552 
   1553 ELPA packages usually live in @code{~/.emacs.d/elpa} (or what is in
   1554 @code{package-user-dir}).  Including a listing of files in that
   1555 directory is a way to tell the maintainers about ELPA package
   1556 versions.
   1557 
   1558 @item
   1559 Include a recipe to replicate the problem with @emph{a clean Emacs
   1560 run}.  The invocation @code{emacs -Q -f package-initialize} starts
   1561 Emacs with no configuration and initializes the ELPA packages.  A very
   1562 minimal @file{.emacs} initialization file (10 lines or less) is also
   1563 acceptable and good means to describe changes to variables.
   1564 
   1565 There is usually no need to include @code{require} statements in the
   1566 recipe, as Eglot's functionality uses autoloads.
   1567 
   1568 Likewise, there is rarely the need to use things like
   1569 @code{use-package} or @code{eglot-ensure}.  This just makes the recipe
   1570 harder to follow.  Prefer setting variables with @code{setq} and
   1571 adding to hooks with @code{add-hook}.  Prefer starting Eglot with
   1572 @code{M-x eglot}.
   1573 
   1574 @item
   1575 Make sure to double check all the above elements and re-run the recipe
   1576 to see that the problem is reproducible.  Following the recipe should
   1577 produce event transcript and error backtraces that are very similar to
   1578 the ones you included.  If the problem only happens sometimes, mention
   1579 this in your report.
   1580 @end enumerate
   1581 
   1582 Please keep in mind that some problems reported against Eglot may
   1583 actually be bugs in the language server or the Emacs feature/package
   1584 that used Eglot to communicate with the language server.  Eglot is, in
   1585 many cases, just a frontend to that functionality.
   1586 
   1587 @node GNU Free Documentation License
   1588 @appendix GNU Free Documentation License
   1589 @include doclicense.texi
   1590 
   1591 @node Index
   1592 @unnumbered Index
   1593 @printindex cp
   1594 
   1595 @bye