commit 04f9fc96abec04370a10d658ad7b43103a725488 parent 4121075d11ac98d787a2485f54bab4ab7b871a61 Author: dwrz <dwrz@dwrz.net> Date: Sun, 6 Oct 2024 16:23:55 +0000 Update Emacs packages Diffstat:
376 files changed, 74758 insertions(+), 19115 deletions(-)
diff --git a/emacs/elpa/archives/gnu/archive-contents b/emacs/elpa/archives/gnu/archive-contents @@ -206,14 +206,14 @@ ("John Wiegley" . "jwiegley@gmail.com")) (:commit . "f317b0c9c3e60a959f45d035ed5e31a78f1263ac"))]) (auctex . - [(14 0 6) + [(14 0 7) ((emacs (27 1))) "Integrated environment for *TeX*" tar ((:url . "https://www.gnu.org/software/auctex/") (:keywords "tex" "latex" "texinfo" "context" "doctex" "preview-latex") (:maintainer nil . "auctex-devel@gnu.org") - (:commit . "be36aa96c813125a1f3849e13223fc68cd09e847"))]) + (:commit . "3bdc30d3c91c6b84d7592f19959cdbe25a497fbc"))]) (auctex-cont-latexmk . [(0 2) ((emacs @@ -1279,14 +1279,14 @@ (:url . "https://elpa.gnu.org/packages/ebdb-i18n-chn.html") (:commit . "b8c1f7c21204bda9c130ce21a75d69358d1bc49a"))]) (ediprolog . - [(2 2) + [(2 3) nil "Emacs Does Interactive Prolog" tar ((:url . "https://www.metalevel.at/ediprolog/") (:keywords "languages" "processes") (:maintainer "Markus Triska" . "triska@metalevel.at") (:authors ("Markus Triska" . "triska@metalevel.at")) - (:commit . "cfcdf9e42821d246b7fbc84877aa4ecacc184a1c"))]) + (:commit . "ea8710335eec483b576c7a800c92b8fd214aa6dd"))]) (eev . [(20241002) ((emacs @@ -1630,13 +1630,13 @@ (:url . "https://elpa.gnu.org/packages/external-completion.html") (:commit . "4bc9c8972ac0a3dfa237a9c5704de89ef24ad82b"))]) (exwm . - [(0 31) + [(0 32) ((emacs (27 1)) (xelb - (0 19)) + (0 20)) (compat - (29 1))) + (30))) "Emacs X Window Manager" tar ((:url . "https://github.com/emacs-exwm/exwm") (:keywords "unix") @@ -1646,7 +1646,7 @@ ("Daniel Mendler" . "mail@daniel-mendler.de")) (:authors ("Chris Feng" . "chris.w.feng@gmail.com")) - (:commit . "512d0f0ef9f02211a463fdae04e6732de80bb5de"))]) + (:commit . "1485fcf064cee1766444472b09a681654c68636e"))]) (f90-interface-browser . [(1 1) nil "Parse and browse f90 interfaces" single @@ -4472,7 +4472,7 @@ (:url . "https://elpa.gnu.org/packages/transcribe.html") (:commit . "89832e4cdc1e6d8262a4a2c9d1ff70f398b8faf0"))]) (transient . - [(0 7 6) + [(0 7 7) ((emacs (26 1)) (compat @@ -4485,7 +4485,7 @@ (:maintainer "Jonas Bernoulli" . "emacs.transient@jonas.bernoulli.dev") (:authors ("Jonas Bernoulli" . "emacs.transient@jonas.bernoulli.dev")) - (:commit . "c06015cd6750f8625081f4184c68c94350eb0217"))]) + (:commit . "fc03c0b75826aa771b682137aa3f4e24130a9e3c"))]) (transient-cycles . [(1 0) ((emacs diff --git a/emacs/elpa/archives/gnu/archive-contents.signed b/emacs/elpa/archives/gnu/archive-contents.signed @@ -1 +1 @@ -Good signature from 645357D2883A0966 GNU ELPA Signing Agent (2023) <elpasign@elpa.gnu.org> (trust undefined) created at 2024-10-03T09:05:02+0000 using EDDSA -\ No newline at end of file +Good signature from 645357D2883A0966 GNU ELPA Signing Agent (2023) <elpasign@elpa.gnu.org> (trust undefined) created at 2024-10-06T09:05:05+0000 using EDDSA +\ No newline at end of file diff --git a/emacs/elpa/archives/melpa/archive-contents b/emacs/elpa/archives/melpa/archive-contents @@ -155,7 +155,7 @@ (apache-mode . [(20210519 1931) nil "Major mode for editing Apache httpd configuration files" tar ((:url . "https://github.com/emacs-php/apache-mode") (:commit . "f2c11aac2f5fc598123e04f4604bea248689a117") (:revdesc . "f2c11aac2f5f") (:keywords "languages" "faces") (:authors ("Karl Chen" . "quarl@nospam.quarl.org")) (:maintainers ("USAMI Kenta" . "tadsan@zonu.me")) (:maintainer "USAMI Kenta" . "tadsan@zonu.me"))]) (apdl-mode . [(20211023 1831) ((emacs (25 1))) "Major mode for the APDL programming language" tar ((:url . "https://github.com/dieter-wilhelm/apdl-mode") (:commit . "ba756eaa1d229c9bf6936fb8d2d4126ad073d488") (:revdesc . "ba756eaa1d22") (:keywords "languages" "convenience" "tools" "ansys" "apdl") (:authors ("H. Dieter Wilhelm" . "dieter@duenenhof-wilhelm.de")))]) (apel . [(20221214 1337) ((emacs (24 5))) "A Portable Emacs Library provides support for portable Emacs Lisp programs" tar ((:url . "https://github.com/wanderlust/apel") (:commit . "1a6fd3bab2cc6b0a450c2d801f77a1c9da0f72fb") (:revdesc . "1a6fd3bab2cc"))]) - (apheleia . [(20240926 228) ((emacs (27))) "Reformat buffer stably" tar ((:url . "https://github.com/radian-software/apheleia") (:commit . "302a41c86c5ffe1e8f50cbe156e0f7b21835c02c") (:revdesc . "302a41c86c5f") (:keywords "tools") (:authors ("Radian LLC" . "contact+apheleia@radian.codes")) (:maintainers ("Radian LLC" . "contact+apheleia@radian.codes")) (:maintainer "Radian LLC" . "contact+apheleia@radian.codes"))]) + (apheleia . [(20241006 142) ((emacs (27))) "Reformat buffer stably" tar ((:url . "https://github.com/radian-software/apheleia") (:commit . "d6f520752a77923a420f2ef894a6f2d26d29d7d0") (:revdesc . "d6f520752a77") (:keywords "tools") (:authors ("Radian LLC" . "contact+apheleia@radian.codes")) (:maintainers ("Radian LLC" . "contact+apheleia@radian.codes")) (:maintainer "Radian LLC" . "contact+apheleia@radian.codes"))]) (apib-mode . [(20200101 1017) ((markdown-mode (2 1))) "Major mode for API Blueprint files" tar ((:url . "https://github.com/w-vi/apib-mode") (:commit . "c6dd05201f6eb9295736d8668a79a7510d11159e") (:revdesc . "c6dd05201f6e") (:keywords "tools" "api-blueprint") (:authors ("Vilibald Wanča" . "vilibald@wvi.cz")) (:maintainers ("Vilibald Wanča" . "vilibald@wvi.cz")) (:maintainer "Vilibald Wanča" . "vilibald@wvi.cz"))]) (apiwrap . [(20180602 2231) ((emacs (25))) "Api-wrapping macros" tar ((:url . "https://github.com/vermiculus/apiwrap.el") (:commit . "e4c9c57d6620a788ec8a715ff1bb50542edea3a6") (:revdesc . "e4c9c57d6620") (:keywords "tools" "maint" "convenience") (:authors ("Sean Allred" . "code@seanallred.com")) (:maintainers ("Sean Allred" . "code@seanallred.com")) (:maintainer "Sean Allred" . "code@seanallred.com"))]) (app-monochrome-themes . [(20240611 1623) ((emacs (24 4))) "Low contrast monochrome themes" tar ((:url . "https://github.com/Greybeard-Entertainment/app-monochrome") (:commit . "e319fcfeb56d0fe28bbda7fc813537593c2f368d") (:revdesc . "e319fcfeb56d") (:authors ("Aleksandr Petrosyan" . "appetrosan3@gmail.com")) (:maintainers ("Aleksandr Petrosyan" . "appetrosan3@gmail.com")) (:maintainer "Aleksandr Petrosyan" . "appetrosan3@gmail.com"))]) @@ -189,7 +189,7 @@ (astute . [(20240910 1312) ((emacs (25 1))) "A minor mode to redisplay `smart' typography" tar ((:url . "https://github.com/rnkn/astute") (:commit . "54ed0a94b1f0ce03becf91847a026403c697d2b6") (:revdesc . "54ed0a94b1f0") (:keywords "faces" "wp") (:authors ("Paul W. Rankin" . "rnkn@rnkn.xyz")) (:maintainers ("Paul W. Rankin" . "rnkn@rnkn.xyz")) (:maintainer "Paul W. Rankin" . "rnkn@rnkn.xyz"))]) (astyle . [(20200328 616) ((emacs (24 4)) (reformatter (0 3))) "Astyle formatter functions" tar ((:url . "https://github.com/storvik/emacs-astyle") (:commit . "04ff2941f08c4b731fe6a18ee1697436d1ca1cc0") (:revdesc . "04ff2941f08c") (:keywords "astyle" "c" "c++" "cpp" "reformatter"))]) (asx . [(20191024 1100) ((emacs (26 1))) "Ask StackExchange/StackOverflow" tar ((:url . "https://github.com/ragone/asx") (:commit . "5ca12cc51bb02b5926adf9a7976ba9ca08a1ea21") (:revdesc . "5ca12cc51bb0") (:keywords "convenience") (:authors ("Alex Ragone" . "ragonedk@gmail.com")) (:maintainers ("Alex Ragone" . "ragonedk@gmail.com")) (:maintainer "Alex Ragone" . "ragonedk@gmail.com"))]) - (async . [(20240821 253) ((emacs (24 4))) "Asynchronous processing in Emacs" tar ((:url . "https://github.com/jwiegley/emacs-async") (:commit . "f317b0c9c3e60a959f45d035ed5e31a78f1263ac") (:revdesc . "f317b0c9c3e6") (:keywords "async") (:authors ("John Wiegley" . "jwiegley@gmail.com")) (:maintainers ("Thierry Volpiatto" . "thievol@posteo.net")) (:maintainer "Thierry Volpiatto" . "thievol@posteo.net"))]) + (async . [(20241005 1824) ((emacs (24 4))) "Asynchronous processing in Emacs" tar ((:url . "https://github.com/jwiegley/emacs-async") (:commit . "af47d6f930f93d4fdc4ca46e19e17547bf486c4c") (:revdesc . "af47d6f930f9") (:keywords "async") (:authors ("John Wiegley" . "jwiegley@gmail.com")) (:maintainers ("Thierry Volpiatto" . "thievol@posteo.net")) (:maintainer "Thierry Volpiatto" . "thievol@posteo.net"))]) (async-await . [(20220827 437) ((emacs (25 1)) (promise (1 1)) (iter2 (0 9 10))) "Async/Await" tar ((:url . "https://github.com/chuntaro/emacs-async-await") (:commit . "e0d15e8057ed7520100bc50c5552278292ebcb07") (:revdesc . "e0d15e8057ed") (:keywords "async" "await" "convenience") (:authors ("chuntaro" . "chuntaro@sakura-games.jp")) (:maintainers ("chuntaro" . "chuntaro@sakura-games.jp")) (:maintainer "chuntaro" . "chuntaro@sakura-games.jp"))]) (async-backup . [(20230412 1534) ((emacs (24 4))) "Backup on each save without freezing Emacs" tar ((:url . "https://codeberg.org/contrapunctus/async-backup") (:commit . "d07a7bd4a5c3332a8a585680d67925385c595927") (:revdesc . "d07a7bd4a5c3") (:keywords "files") (:authors ("contrapunctus" . "xmpp:contrapunctus@jabjab.de")) (:maintainers ("contrapunctus" . "xmpp:contrapunctus@jabjab.de")) (:maintainer "contrapunctus" . "xmpp:contrapunctus@jabjab.de"))]) (async-job-queue . [(20230427 2122) ((async (1 4)) (emacs (25 1)) (queue (0 2))) "Dispatch queue of async jobs to a fixed number of slots" tar ((:url . "https://github.com/owinebar/emacs-async-job-queue") (:commit . "eeafcce7f960305666b2a51aec55cc6333f6af1b") (:revdesc . "eeafcce7f960") (:keywords "extensions" "lisp"))]) @@ -346,7 +346,7 @@ (bind-chord . [(20221117 1610) ((emacs (24 3)) (bind-key (1 0)) (key-chord (0 6))) "Key-chord binding helper for use-package-chords" tar ((:url . "https://github.com/jwiegley/use-package") (:commit . "9090080b15486c3e337be254226efe7e5fde4c99") (:revdesc . "9090080b1548") (:keywords "convenience" "tools" "extensions") (:authors ("Justin Talbott" . "justin@waymondo.com")) (:maintainers ("Justin Talbott" . "justin@waymondo.com")) (:maintainer "Justin Talbott" . "justin@waymondo.com"))]) (bind-key . [(20230203 2004) ((emacs (24 3))) "A simple way to manage personal keybindings" tar ((:url . "https://github.com/jwiegley/use-package") (:commit . "77945e002f11440eae72d8730d3de218163d551e") (:revdesc . "77945e002f11") (:keywords "keys" "keybinding" "config" "dotemacs" "extensions") (:authors ("John Wiegley" . "johnw@newartisans.com")) (:maintainers ("John Wiegley" . "johnw@newartisans.com")) (:maintainer "John Wiegley" . "johnw@newartisans.com"))]) (bind-map . [(20240308 2050) ((emacs (24 3))) "Bind personal keymaps in multiple locations" tar ((:url . "https://github.com/justbur/emacs-bind-map") (:commit . "d7b0e42b78f708669ec368ebbd1f503094ceee22") (:revdesc . "d7b0e42b78f7") (:authors ("Justin Burkett" . "justin@burkett.cc")) (:maintainers ("Justin Burkett" . "justin@burkett.cc")) (:maintainer "Justin Burkett" . "justin@burkett.cc"))]) - (binder . [(20241003 51) ((emacs (24 4)) (seq (2 20))) "Global minor mode to facilitate multi-file writing projects" tar ((:url . "https://github.com/rnkn/binder") (:commit . "5c668cba1dc768aa25e5b2a2b446a2ad4babf8bb") (:revdesc . "5c668cba1dc7") (:keywords "files" "outlines" "wp" "text") (:authors ("Paul W. Rankin" . "rnkn@rnkn.xyz")) (:maintainers ("Divya Ranjan" . "divya@subvertising.org")) (:maintainer "Divya Ranjan" . "divya@subvertising.org"))]) + (binder . [(20241002 1408) ((emacs (24 4)) (seq (2 20))) "Global minor mode to facilitate multi-file writing projects" tar ((:url . "https://codeberg.org/divyaranjan/binder") (:commit . "0a86e1e60c04b525c9017b0479c1135044273f32") (:revdesc . "0a86e1e60c04") (:keywords "files" "outlines" "wp" "text") (:authors ("Paul W. Rankin" . "rnkn@rnkn.xyz")) (:maintainers ("Paul W. Rankin" . "rnkn@rnkn.xyz")) (:maintainer "Paul W. Rankin" . "rnkn@rnkn.xyz"))]) (bing-dict . [(20200216 110) nil "Minimalists' English-Chinese Bing dictionary" tar ((:url . "https://github.com/cute-jumper/bing-dict.el") (:commit . "1d581aaa9622b34f8fb83af5579fa252aa24cfef") (:revdesc . "1d581aaa9622") (:keywords "extensions") (:authors ("Junpeng Qiu" . "qjpchmail@gmail.com")) (:maintainers ("Junpeng Qiu" . "qjpchmail@gmail.com")) (:maintainer "Junpeng Qiu" . "qjpchmail@gmail.com"))]) (binky . [(20240525 715) ((emacs (29 1)) (dash (2 19 1))) "Jump between points like a rabbit" tar ((:url . "https://github.com/liuyinz/binky.el") (:commit . "39c1a1e78aea36f79104fdc256949901e3d3d2c0") (:revdesc . "39c1a1e78aea") (:keywords "convenience") (:authors ("liuyinz" . "liuyinz95@gmail.com")) (:maintainers ("liuyinz" . "liuyinz95@gmail.com")) (:maintainer "liuyinz" . "liuyinz95@gmail.com"))]) (biome . [(20240519 1037) ((emacs (27 1)) (transient (0 3 7)) (ct (0 2)) (request (0 3 3)) (compat (29 1 4 1))) "Bountiful Interface to Open Meteo for Emacs" tar ((:url . "https://github.com/SqrtMinusOne/biome") (:commit . "6c5d786219741e10332304566d4a18db3eddae2b") (:revdesc . "6c5d78621974") (:authors ("Korytov Pavel" . "thexcloud@gmail.com")) (:maintainers ("Korytov Pavel" . "thexcloud@gmail.com")) (:maintainer "Korytov Pavel" . "thexcloud@gmail.com"))]) @@ -474,7 +474,7 @@ (camcorder . [(20190317 2138) ((emacs (24)) (names (20150000)) (cl-lib (0 5))) "Record screencasts in gif or other formats" tar ((:url . "https://github.com/Malabarba/camcorder.el") (:commit . "b11ca61491a27681bb3131b72b51c105fd996bed") (:revdesc . "b11ca61491a2") (:keywords "multimedia" "screencast") (:authors ("Artur Malabarba" . "bruce.connor.am@gmail.com")) (:maintainers ("Artur Malabarba" . "bruce.connor.am@gmail.com")) (:maintainer "Artur Malabarba" . "bruce.connor.am@gmail.com"))]) (caml . [(20231011 328) ((emacs (24 4))) "Caml mode for GNU Emacs" tar ((:url . "https://github.com/ocaml/caml-mode") (:commit . "47defafa2b08fb680e89bfee9cb9ce82bd9e3bcf") (:revdesc . "47defafa2b08") (:keywords "ocaml") (:authors ("Jacques Garrigue" . "garrigue@kurims.kyoto-u.ac.jp") ("Ian T Zimmerman" . "itz@rahul.net") ("Damien Doligez" . "damien.doligez@inria.fr")) (:maintainers ("Christophe Troestler" . "Christophe.Troestler@umons.ac.be")) (:maintainer "Christophe Troestler" . "Christophe.Troestler@umons.ac.be"))]) (cangjie . [(20230219 1150) ((emacs (24 4)) (s (1 12 0)) (dash (2 14 1)) (f (0 2 0))) "Retrieve cangjie code for han characters" tar ((:url . "https://github.com/kisaragi-hiu/cangjie.el") (:commit . "d6882e15f47fdde37e9f739dde604d77d25f11db") (:revdesc . "d6882e15f47f") (:keywords "convenience" "writing"))]) - (cape . [(20240926 918) ((emacs (28 1)) (compat (30))) "Completion At Point Extensions" tar ((:url . "https://github.com/minad/cape") (:commit . "2734e4ea0631f0e2944eac1aed79a55951157f55") (:revdesc . "2734e4ea0631") (:keywords "abbrev" "convenience" "matching" "completion" "text") (:authors ("Daniel Mendler" . "mail@daniel-mendler.de")) (:maintainers ("Daniel Mendler" . "mail@daniel-mendler.de")) (:maintainer "Daniel Mendler" . "mail@daniel-mendler.de"))]) + (cape . [(20241004 614) ((emacs (28 1)) (compat (30))) "Completion At Point Extensions" tar ((:url . "https://github.com/minad/cape") (:commit . "63ab1490a14f5a6cbfec29eb5af5ffd12ee49180") (:revdesc . "63ab1490a14f") (:keywords "abbrev" "convenience" "matching" "completion" "text") (:authors ("Daniel Mendler" . "mail@daniel-mendler.de")) (:maintainers ("Daniel Mendler" . "mail@daniel-mendler.de")) (:maintainer "Daniel Mendler" . "mail@daniel-mendler.de"))]) (capnp-mode . [(20210707 2310) nil "Major mode for editing Capn' Proto Files" tar ((:url . "https://github.com/capnproto/capnproto") (:commit . "f7fccad7d737f77896211bec1173117497634143") (:revdesc . "f7fccad7d737") (:authors ("Brian Taylor" . "el.wubo@gmail.com")) (:maintainers ("Brian Taylor" . "el.wubo@gmail.com")) (:maintainer "Brian Taylor" . "el.wubo@gmail.com"))]) (capture . [(20130828 1644) nil "Screencasting with \"avconv\" or \"ffmpeg\"" tar ((:url . "https://github.com/pashinin/capture.el") (:commit . "9140c207b48b3520a2f06674b3e1bee2fc92b80c") (:revdesc . "9140c207b48b") (:authors ("Sergey Pashinin" . "sergeyatpashinindotcom")) (:maintainers ("Sergey Pashinin" . "sergeyatpashinindotcom")) (:maintainer "Sergey Pashinin" . "sergeyatpashinindotcom"))]) (carbon-now-sh . [(20220701 332) ((emacs (24 4))) "Https://carbon.now.sh integration" tar ((:url . "https://github.com/veelenga/carbon-now-sh.el") (:commit . "e66f2e43e288f35ad9075f5fc84d59ad348efc88") (:revdesc . "e66f2e43e288") (:keywords "convenience"))]) @@ -540,7 +540,7 @@ (chapel-mode . [(20210513 457) ((emacs (25 1)) (hydra (0 15 0))) "A major mode for the Chapel programming language" tar ((:url . "https://github.com/damon-kwok/chapel-mode") (:commit . "39fd24bb7cf44808200354ac0496be4fc4fddd9a") (:revdesc . "39fd24bb7cf4") (:keywords "chapel" "chpl" "programming" "languages"))]) (char-menu . [(20210321 1657) ((emacs (24 3)) (avy-menu (0 1))) "Create your own menu for fast insertion of arbitrary symbols" tar ((:url . "https://github.com/mrkkrp/char-menu") (:commit . "d77c4d64fc8acc386a0fb9727d346c838e75f011") (:revdesc . "d77c4d64fc8a") (:keywords "convenience" "editing") (:authors ("Mark Karpov" . "markkarpov92@gmail.com")) (:maintainers ("Mark Karpov" . "markkarpov92@gmail.com")) (:maintainer "Mark Karpov" . "markkarpov92@gmail.com"))]) (charmap . [(20200616 1418) nil "Unicode table for Emacs" tar ((:url . "https://github.com/lateau/charmap") (:commit . "feac50b87d2a596c5e5b7b82b79ddd65b6dedd8c") (:revdesc . "feac50b87d2a") (:keywords "unicode" "character" "ucs") (:authors ("Anan Mikami" . "lateau@gmail.com")) (:maintainers ("Anan Mikami" . "lateau@gmail.com")) (:maintainer "Anan Mikami" . "lateau@gmail.com"))]) - (chatgpt-shell . [(20240916 1625) ((emacs (27 1)) (shell-maker (0 53 1))) "ChatGPT shell + buffer insert commands" tar ((:url . "https://github.com/xenodium/chatgpt-shell") (:commit . "b7515ec406b9595365cca246f3ee18909995539f") (:revdesc . "b7515ec406b9"))]) + (chatgpt-shell . [(20241006 1012) ((emacs (27 1)) (shell-maker (0 53 1))) "ChatGPT shell + buffer insert commands" tar ((:url . "https://github.com/xenodium/chatgpt-shell") (:commit . "b76dcd4c15e98e3da98f9d5b1f0a0666a6165d5c") (:revdesc . "b76dcd4c15e9"))]) (chatu . [(20240518 615) ((org (9 6 6)) (emacs (29 1)) (plantuml-mode (1 2 9))) "Convert and insert any images to org-mode or markdown buffer" tar ((:url . "https://github.com/kimim/chatu") (:commit . "f813f0bc926346fbd8151d2ae7079119d4657abb") (:revdesc . "f813f0bc9263") (:keywords "multimedia" "convenience") (:authors ("Kimi Ma" . "kimi.im@outlook.com")) (:maintainers ("Kimi Ma" . "kimi.im@outlook.com")) (:maintainer "Kimi Ma" . "kimi.im@outlook.com"))]) (chatwork . [(20240910 1531) nil "ChatWork client for Emacs" tar ((:url . "https://github.com/ataka/chatwork") (:commit . "5abbf07bd6063c922191cc645f5771a943e3043c") (:revdesc . "5abbf07bd606") (:keywords "web") (:authors ("Masayuki Ataka" . "masayuki.ataka@gmail.com")) (:maintainers ("Masayuki Ataka" . "masayuki.ataka@gmail.com")) (:maintainer "Masayuki Ataka" . "masayuki.ataka@gmail.com"))]) (cheat-sh . [(20210607 1307) ((emacs (25 1))) "Interact with cheat.sh" tar ((:url . "https://github.com/davep/cheat-sh.el") (:commit . "33bae22feae8d3375739c6bdef08d0dcdf47ee42") (:revdesc . "33bae22feae8") (:keywords "docs" "help") (:authors ("Dave Pearson" . "davep@davep.org")) (:maintainers ("Dave Pearson" . "davep@davep.org")) (:maintainer "Dave Pearson" . "davep@davep.org"))]) @@ -777,7 +777,7 @@ (comware-router-mode . [(20240103 907) ((dash (2 16 0)) (emacs (24 3))) "Major mode for editing Comware configuration files" tar ((:url . "https://github.com/daviderestivo/comware-router-mode") (:commit . "e1671efe5e0ade2dcbea0c17697d460cd8f0ba67") (:revdesc . "e1671efe5e0a") (:keywords "convenience" "faces") (:authors ("Davide Restivo" . "davide.restivo@yahoo.it")) (:maintainers ("Davide Restivo" . "davide.restivo@yahoo.it")) (:maintainer "Davide Restivo" . "davide.restivo@yahoo.it"))]) (conan . [(20231016 830) ((emacs (29 1)) (s (1 7 0)) (f (0 20 0))) "Generate flags for c++ using conan 2.0" tar ((:url . "https://github.com/Carl2/conan-elisp") (:commit . "80d17373cb6c3dc7952c538efd9f94a7f564ffec") (:revdesc . "80d17373cb6c") (:keywords "tools"))]) (concurrent . [(20170601 435) ((emacs (24 3)) (deferred (0 5 0))) "Concurrent utility functions for emacs lisp" tar ((:url . "https://github.com/kiwanami/emacs-deferred") (:commit . "d012a1ab50edcc2c44e3e49006f054dbff47cb6c") (:revdesc . "d012a1ab50ed") (:keywords "deferred" "async" "concurrent") (:authors ("SAKURAI Masashi" . "m.sakuraiatkiwanami.net")) (:maintainers ("SAKURAI Masashi" . "m.sakuraiatkiwanami.net")) (:maintainer "SAKURAI Masashi" . "m.sakuraiatkiwanami.net"))]) - (conda . [(20240708 2135) ((emacs (25 1)) (pythonic (0 1 0)) (dash (2 13 0)) (s (1 11 0)) (f (0 18 2))) "Work with your conda environments" tar ((:url . "https://github.com/necaris/conda.el") (:commit . "ce748a53f9c7d7a7d112632d32c848d6e5482e18") (:revdesc . "ce748a53f9c7") (:keywords "languages" "local" "tools" "python" "environment" "conda") (:authors ("Rami Chowdhury" . "rami.chowdhury@gmail.com")) (:maintainers ("Rami Chowdhury" . "rami.chowdhury@gmail.com")) (:maintainer "Rami Chowdhury" . "rami.chowdhury@gmail.com"))]) + (conda . [(20241005 2057) ((emacs (25 1)) (pythonic (0 1 0)) (dash (2 13 0)) (s (1 11 0)) (f (0 18 2))) "Work with your conda environments" tar ((:url . "https://github.com/necaris/conda.el") (:commit . "05de0c8f0cf336d90c044446aaa066ee13001b83") (:revdesc . "05de0c8f0cf3") (:keywords "languages" "local" "tools" "python" "environment" "conda") (:authors ("Rami Chowdhury" . "rami.chowdhury@gmail.com")) (:maintainers ("Rami Chowdhury" . "rami.chowdhury@gmail.com")) (:maintainer "Rami Chowdhury" . "rami.chowdhury@gmail.com"))]) (config-general-mode . [(20171024 1840) nil "Config::General config file mode" tar ((:url . "https://github.com/TLINDEN/config-general-mode") (:commit . "b4a8e6ba0bb027a77e4a0f701409f3e57bb2e4c0") (:revdesc . "b4a8e6ba0bb0") (:keywords "files") (:authors ("T.v.Dein" . "tlinden@cpan.org")) (:maintainers ("T.v.Dein" . "tlinden@cpan.org")) (:maintainer "T.v.Dein" . "tlinden@cpan.org"))]) (config-parser . [(20160426 1219) ((emacs (24 4))) "A library for parsing config file" tar ((:url . "https://github.com/lujun9972/el-config-parser") (:commit . "85d559e7889d8f5b98b8794b79426ae25ec3caa5") (:revdesc . "85d559e7889d") (:keywords "convenience" "config") (:authors ("DarkSun" . "lujun9972@gmail.com")) (:maintainers ("DarkSun" . "lujun9972@gmail.com")) (:maintainer "DarkSun" . "lujun9972@gmail.com"))]) (conkeror-minor-mode . [(20150114 1604) nil "Mode for editing conkeror javascript files" tar ((:url . "https://github.com/Malabarba/conkeror-minor-mode") (:commit . "476e81c27b056e21c192391fe674a2bf875466b0") (:revdesc . "476e81c27b05") (:keywords "programming" "tools") (:authors ("Artur Malabarba" . "bruce.connor.am@gmail.com")) (:maintainers ("Artur Malabarba" . "bruce.connor.am@gmail.com")) (:maintainer "Artur Malabarba" . "bruce.connor.am@gmail.com"))]) @@ -1012,7 +1012,7 @@ (desktop-registry . [(20140119 2143) nil "Keep a central registry of desktop files" tar ((:url . "https://github.com/ryuslash/desktop-registry") (:commit . "244c2e7f9f0a1050aa8a47ad0b38f4e4584682dd") (:revdesc . "244c2e7f9f0a") (:keywords "convenience") (:authors ("Tom Willemse" . "tom@ryuslash.org")) (:maintainers ("Tom Willemse" . "tom@ryuslash.org")) (:maintainer "Tom Willemse" . "tom@ryuslash.org"))]) (detached . [(20221129 1430) ((emacs (27 1))) "A package to launch, and manage, detached processes" tar ((:url . "https://git.sr.ht/~niklaseklund/detached.el") (:commit . "6b64d4d8064cee781e071e825857b442ea96c3d9") (:revdesc . "6b64d4d8064c") (:keywords "convenience" "processes") (:authors ("Niklas Eklund" . "niklas.eklund@posteo.net")) (:maintainers ("detached.el Development" . "~niklaseklund/detached.el@lists.sr.ht")) (:maintainer "detached.el Development" . "~niklaseklund/detached.el@lists.sr.ht"))]) (detour . [(20181122 2138) ((emacs (24 4))) "Take a quick detour and return" tar ((:url . "https://github.com/ska2342/detour") (:commit . "f41f17cf1cf4f3db41563ff011786b6567596fb4") (:revdesc . "f41f17cf1cf4") (:keywords "convenience" "abbrev") (:authors ("Stefan Kamphausen" . "www.skamphausen.de")) (:maintainers ("Stefan Kamphausen" . "www.skamphausen.de")) (:maintainer "Stefan Kamphausen" . "www.skamphausen.de"))]) - (devdocs . [(20240428 711) ((emacs (27 1))) "Emacs viewer for DevDocs" tar ((:url . "https://github.com/astoff/devdocs.el") (:commit . "c14d1306648d3ae09ee3a3b3f45592334943cfeb") (:revdesc . "c14d1306648d") (:keywords "help") (:authors ("Augusto Stoffel" . "arstoffel@gmail.com")) (:maintainers ("Augusto Stoffel" . "arstoffel@gmail.com")) (:maintainer "Augusto Stoffel" . "arstoffel@gmail.com"))]) + (devdocs . [(20241006 51) ((emacs (27 1)) (compat (29 1))) "Emacs viewer for DevDocs" tar ((:url . "https://github.com/astoff/devdocs.el") (:commit . "98518166efe18c2f2dd9a1c4c89430b83fdbbe3c") (:revdesc . "98518166efe1") (:keywords "help") (:authors ("Augusto Stoffel" . "arstoffel@gmail.com")) (:maintainers ("Augusto Stoffel" . "arstoffel@gmail.com")) (:maintainer "Augusto Stoffel" . "arstoffel@gmail.com"))]) (devdocs-browser . [(20240909 1711) ((emacs (27 1))) "Browse devdocs.io documents using EWW" tar ((:url . "https://github.com/blahgeek/emacs-devdocs-browser") (:commit . "3de7b1f013cbecebedeeeb16d5fec532ef56c2e2") (:revdesc . "3de7b1f013cb") (:keywords "docs" "help" "tools") (:authors ("blahgeek" . "i@blahgeek.com")) (:maintainers ("blahgeek" . "i@blahgeek.com")) (:maintainer "blahgeek" . "i@blahgeek.com"))]) (devil . [(20240107 2149) ((emacs (24 4))) "Minor mode for translating key sequences" tar ((:url . "https://github.com/susam/devil") (:commit . "dd29681fe07f37c4acbff32a5767bddcbf3b5b80") (:revdesc . "dd29681fe07f") (:keywords "convenience" "abbrev") (:authors ("Susam Pal" . "susam@susam.net")) (:maintainers ("Susam Pal" . "susam@susam.net")) (:maintainer "Susam Pal" . "susam@susam.net"))]) (dfmt . [(20170728 1023) nil "Emacs Interface to D indenting/formatting tool dfmt" tar ((:url . "https://github.com/qsimpleq/elisp-dfmt") (:commit . "21b9094e907b7ac53f5ecb4ff4539613a9d12434") (:revdesc . "21b9094e907b") (:keywords "tools" "convenience" "languages" "dlang") (:maintainers ("Kirill Babikhin" . "qsimpleq")) (:maintainer "Kirill Babikhin" . "qsimpleq"))]) @@ -1405,7 +1405,7 @@ (emamux . [(20200315 1220) ((emacs (24 3))) "Interact with tmux" tar ((:url . "https://github.com/emacsorphanage/emamux") (:commit . "6172131d78038f0b1490e24bac60534bf4ad3b30") (:revdesc . "6172131d7803") (:authors ("Syohei YOSHIDA" . "syohex@gmail.com")) (:maintainers ("Syohei YOSHIDA" . "syohex@gmail.com")) (:maintainer "Syohei YOSHIDA" . "syohex@gmail.com"))]) (emamux-ruby-test . [(20130812 1639) ((emamux (0 1)) (projectile (0 9 1))) "Ruby test with emamux" tar ((:url . "https://github.com/emacsorphanage/emamux-ruby-test") (:commit . "785bfd44d097a46bb2ebe1e62ac7595fd4dc9ab5") (:revdesc . "785bfd44d097"))]) (emaps . [(20200508 1759) ((dash (2 17 0)) (emacs (24))) "Utilities for working with keymaps" tar ((:url . "https://github.com/GuiltyDolphin/emaps") (:commit . "7c561f3ded2015ed3774e5784059d6601082743e") (:revdesc . "7c561f3ded20") (:keywords "convenience" "keyboard" "keymap" "utility") (:authors ("Ben Moon" . "software@guiltydolphin.com")) (:maintainers ("Ben Moon" . "software@guiltydolphin.com")) (:maintainer "Ben Moon" . "software@guiltydolphin.com"))]) - (embark . [(20240919 1831) ((emacs (28 1)) (compat (30))) "Conveniently act on minibuffer completions" tar ((:url . "https://github.com/oantolin/embark") (:commit . "718f0f293440b2d5e951c6c4a88ee548180af016") (:revdesc . "718f0f293440") (:keywords "convenience") (:authors ("Omar Antolín Camarena" . "omar@matem.unam.mx")) (:maintainers ("Omar Antolín Camarena" . "omar@matem.unam.mx")) (:maintainer "Omar Antolín Camarena" . "omar@matem.unam.mx"))]) + (embark . [(20241003 1953) ((emacs (28 1)) (compat (30))) "Conveniently act on minibuffer completions" tar ((:url . "https://github.com/oantolin/embark") (:commit . "d2daad08e04090391b3221fa95000492a1f8aabe") (:revdesc . "d2daad08e040") (:keywords "convenience") (:authors ("Omar Antolín Camarena" . "omar@matem.unam.mx")) (:maintainers ("Omar Antolín Camarena" . "omar@matem.unam.mx")) (:maintainer "Omar Antolín Camarena" . "omar@matem.unam.mx"))]) (embark-consult . [(20240919 1831) ((emacs (28 1)) (compat (30)) (embark (1 1)) (consult (1 8))) "Consult integration for Embark" tar ((:url . "https://github.com/oantolin/embark") (:commit . "718f0f293440b2d5e951c6c4a88ee548180af016") (:revdesc . "718f0f293440") (:keywords "convenience") (:authors ("Omar Antolín Camarena" . "omar@matem.unam.mx")) (:maintainers ("Omar Antolín Camarena" . "omar@matem.unam.mx")) (:maintainer "Omar Antolín Camarena" . "omar@matem.unam.mx"))]) (embark-org-roam . [(20240303 335) ((emacs (27 1)) (embark (0 23)) (org-roam (2 2 0))) "Embark export buffer for org roam nodes" tar ((:url . "https://github.com/bramadams/embark-org-roam") (:commit . "5bc9efc33e74eb47becbc2f6467141864cb6ecea") (:revdesc . "5bc9efc33e74") (:keywords "outlines" "hypermedia") (:authors ("Bram Adams" . "bram.adams@queensu.ca")) (:maintainers ("Bram Adams" . "bram.adams@queensu.ca")) (:maintainer "Bram Adams" . "bram.adams@queensu.ca"))]) (embark-vc . [(20230212 1920) ((emacs (27 1)) (embark (0 21 1)) (forge (0 3)) (compat (29 1 3 0))) "Embark actions for various version control integrations" tar ((:url . "https://github.com/elken/embark-vc") (:commit . "070666b0de8fc2832aa2510b9ba492565cb5e35e") (:revdesc . "070666b0de8f") (:keywords "convenience" "matching" "terminals" "tools" "unix" "vc") (:authors ("Ellis Kenyő" . "https://github.com/elken")) (:maintainers ("Ellis Kenyő" . "me@elken.dev")) (:maintainer "Ellis Kenyő" . "me@elken.dev"))]) @@ -1431,7 +1431,7 @@ (emojify . [(20210108 1111) ((seq (1 11)) (ht (2 0)) (emacs (24 3))) "Display emojis in Emacs" tar ((:url . "https://github.com/iqbalansari/emacs-emojify") (:commit . "cfa00865388809363df3f884b4dd554a5d44f835") (:revdesc . "cfa008653888") (:keywords "multimedia" "convenience") (:authors ("Iqbal Ansari" . "iqbalansari02@yahoo.com")) (:maintainers ("Iqbal Ansari" . "iqbalansari02@yahoo.com")) (:maintainer "Iqbal Ansari" . "iqbalansari02@yahoo.com"))]) (emojify-logos . [(20180814 917) ((emojify (0 4))) "Add logos to emojify" tar ((:url . "https://github.com/mxgoldstein/emojify-logos") (:commit . "a3e78bcbdf863092d4c9b026ac08bf7d1c7c0e8b") (:revdesc . "a3e78bcbdf86") (:authors ("mxgoldstein" . "m_goldstein@gmx.net")) (:maintainers ("mxgoldstein" . "m_goldstein@gmx.net")) (:maintainer "mxgoldstein" . "m_goldstein@gmx.net"))]) (empos . [(20151011 1916) nil "Locate bibtex citations from within emacs" tar ((:url . "https://github.com/dimalik/empos") (:commit . "7b99ad30e56937adb7e6349777e5a2045597d564") (:revdesc . "7b99ad30e569") (:keywords "citations" "reference" "bibtex" "reftex") (:authors ("Dimitris Alikaniotis" . "da352[at]cam.ac.uk")) (:maintainers ("Dimitris Alikaniotis" . "da352[at]cam.ac.uk")) (:maintainer "Dimitris Alikaniotis" . "da352[at]cam.ac.uk"))]) - (empv . [(20240916 1801) ((emacs (28 1)) (s (1 13 0)) (compat (29 1 4 4))) "A multimedia player/manager, YouTube interface" tar ((:url . "https://github.com/isamert/empv.el") (:commit . "7177a3fba0c1fe2a04f23c50840d7dec19958454") (:revdesc . "7177a3fba0c1") (:authors ("Isa Mert Gurbuz" . "isamertgurbuz@gmail.com")) (:maintainers ("Isa Mert Gurbuz" . "isamertgurbuz@gmail.com")) (:maintainer "Isa Mert Gurbuz" . "isamertgurbuz@gmail.com"))]) + (empv . [(20241006 1234) ((emacs (28 1)) (s (1 13 0)) (compat (29 1 4 4))) "A multimedia player/manager, YouTube interface" tar ((:url . "https://github.com/isamert/empv.el") (:commit . "ed38218885b99ddccbafb8a37482228a61d87d65") (:revdesc . "ed38218885b9") (:authors ("Isa Mert Gurbuz" . "isamertgurbuz@gmail.com")) (:maintainers ("Isa Mert Gurbuz" . "isamertgurbuz@gmail.com")) (:maintainer "Isa Mert Gurbuz" . "isamertgurbuz@gmail.com"))]) (emr . [(20220108 548) ((s (1 3 1)) (dash (1 2 0)) (cl-lib (0 2)) (popup (0 5 0)) (emacs (24 1)) (list-utils (0 3 0)) (paredit (24 0 0)) (projectile (0 9 1)) (clang-format (0 0 1)) (iedit (0 97))) "Emacs refactoring system" tar ((:url . "https://github.com/Wilfred/emacs-refactor") (:commit . "cac1b52932926f56d7f6d2923732d20bbd20670d") (:revdesc . "cac1b5293292") (:keywords "tools" "convenience" "refactoring") (:authors ("Chris Barrett" . "chris.d.barrett@me.com")) (:maintainers ("Chris Barrett" . "chris.d.barrett@me.com")) (:maintainer "Chris Barrett" . "chris.d.barrett@me.com"))]) (enclose . [(20121008 1614) nil "Enclose cursor within punctuation pairs" tar ((:url . "https://github.com/rejeep/enclose.el") (:commit . "2fff3d4fcc1089f87647042d7164ba04282766ae") (:revdesc . "2fff3d4fcc10") (:keywords "speed" "convenience") (:authors ("Johan Andersson" . "johan.rejeep@gmail.com")) (:maintainers ("Johan Andersson" . "johan.rejeep@gmail.com")) (:maintainer "Johan Andersson" . "johan.rejeep@gmail.com"))]) (encourage-mode . [(20151128 905) ((emacs (24 4))) "Encourages you in your work. :D" tar ((:url . "https://github.com/halbtuerke/encourage-mode.el") (:commit . "ca411e6bfd3d0edffe95852127bd995730b942e3") (:revdesc . "ca411e6bfd3d") (:keywords "fun") (:authors ("Patrick Mosby" . "patrick@schreiblogade.de")) (:maintainers ("Patrick Mosby" . "patrick@schreiblogade.de")) (:maintainer "Patrick Mosby" . "patrick@schreiblogade.de"))]) @@ -1481,7 +1481,7 @@ (ergoemacs-status . [(20160318 538) ((powerline (2 3)) (mode-icons (0 1 0))) "Adaptive Status Bar / Mode Line" tar ((:url . "https://github.com/ergoemacs/ergoemacs-status") (:commit . "d952cc2361adf6eb4d6af60950ad4ab699c81320") (:revdesc . "d952cc2361ad"))]) (eri . [(20240220 2129) nil "Enhanced relative indentation (eri)" tar ((:url . "https://github.com/agda/agda") (:commit . "d4ac6d038e25bb8d4912da7a4c5df91a856e1c9c") (:revdesc . "d4ac6d038e25"))]) (erk . [(20231227 1449) ((emacs (28 1)) (auto-compile (1 2 0)) (dash (2 18 0)) (license-templates (0 1 3))) "Elisp (GitHub) Repository Kit" tar ((:url . "https://github.com/positron-solutions/elisp-repo-kit") (:commit . "0d9906415a649caff2df7b4b1b3f8f6cc337032a") (:revdesc . "0d9906415a64") (:keywords "convenience" "programming") (:authors ("Positron Solutions" . "contact@positron.solutions")) (:maintainers ("Positron Solutions" . "contact@positron.solutions")) (:maintainer "Positron Solutions" . "contact@positron.solutions"))]) - (erlang . [(20240924 1319) ((emacs (24 1))) "Erlang major mode" tar ((:url . "https://github.com/erlang/otp") (:commit . "5ee148b1a1b9e2f698c76718c55f7361965acfe1") (:revdesc . "5ee148b1a1b9") (:keywords "erlang" "languages" "processes"))]) + (erlang . [(20241004 914) ((emacs (24 1))) "Erlang major mode" tar ((:url . "https://github.com/erlang/otp") (:commit . "088d904d0abdc68f031fa3e17b1aa67d903bfc7f") (:revdesc . "088d904d0abd") (:keywords "erlang" "languages" "processes"))]) (erlstack-mode . [(20230608 909) ((emacs (25 1)) (dash (2 12 0))) "Minor mode for analysing Erlang stacktraces" tar ((:url . "https://github.com/k32/erlstack-mode") (:commit . "51e3cd10a2fe77eb8eb60643aba6f8178374b069") (:revdesc . "51e3cd10a2fe") (:keywords "tools" "erlang"))]) (eros . [(20230309 615) ((emacs (24 4))) "Evaluation Result OverlayS for Emacs Lisp" tar ((:url . "https://github.com/xiongtx/eros") (:commit . "a9a92bdc6be0521a6a06eb464be55ed61946639c") (:revdesc . "a9a92bdc6be0") (:keywords "convenience" "lisp") (:authors ("Tianxiang Xiong" . "tianxiang.xiong@gmail.com")) (:maintainers ("Tianxiang Xiong" . "tianxiang.xiong@gmail.com")) (:maintainer "Tianxiang Xiong" . "tianxiang.xiong@gmail.com"))]) (eros-inspector . [(20240923 613) ((emacs (24 4)) (eros (0 1 0)) (inspector (0 38))) "Glue between eros and inspector" tar ((:url . "https://github.com/port19x/eros-inspector") (:commit . "c1625f553ec944883867f0975bff08f10dd3086f") (:revdesc . "c1625f553ec9") (:keywords "convenience" "lisp" "tool" "debugging" "development") (:authors ("port19" . "port19@port19.xyz")) (:maintainers ("port19" . "port19@port19.xyz")) (:maintainer "port19" . "port19@port19.xyz"))]) @@ -1559,7 +1559,7 @@ (evil-avy . [(20150908 748) ((emacs (24 1)) (cl-lib (0 5)) (avy (0 3 0)) (evil (1 2 3))) "Set-based completion" tar ((:url . "https://github.com/louy2/evil-avy") (:commit . "2dd955cc3ecaa7ddeb67b295298abdc6d16dd3a5") (:revdesc . "2dd955cc3eca") (:keywords "point" "location" "evil" "vim") (:authors ("Yufan Lou" . "loganlyf@gmail.com")) (:maintainers ("Yufan Lou" . "loganlyf@gmail.com")) (:maintainer "Yufan Lou" . "loganlyf@gmail.com"))]) (evil-better-visual-line . [(20200123 2045) ((evil (1 2 13))) "Gj and gk visual line mode fix" tar ((:url . "https://github.com/YourFin/evil-better-visual-line") (:commit . "7a65dfb17ab93857eb4c7a39d4018d9399705293") (:revdesc . "7a65dfb17ab9") (:keywords "evil" "vim" "motion") (:authors (nil . "nuckollspatgmail.com")) (:maintainers (nil . "nuckollspatgmail.com")) (:maintainer nil . "nuckollspatgmail.com"))]) (evil-cleverparens . [(20240529 1025) ((evil (1 0)) (paredit (1)) (smartparens (1 6 1)) (emacs (24 4)) (dash (2 12 0))) "Evil friendly minor-mode for editing lisp" tar ((:url . "https://github.com/emacs-evil/evil-cleverparens") (:commit . "6637717af0bdac55f97eef98433d53a10395cf77") (:revdesc . "6637717af0bd") (:keywords "convenience" "emulations") (:authors ("Olli Piepponen" . "opieppo@gmail.com")) (:maintainers ("Olli Piepponen" . "opieppo@gmail.com")) (:maintainer "Olli Piepponen" . "opieppo@gmail.com"))]) - (evil-colemak-basics . [(20221230 1443) ((emacs (24 3)) (evil (1 2 12)) (evil-snipe (2 0 3))) "Basic Colemak key bindings for evil-mode" tar ((:url . "https://github.com/wbolster/emacs-evil-colemak-basics") (:commit . "ea519b962f051cabced8aadaf6ed0134b861225c") (:revdesc . "ea519b962f05") (:keywords "convenience" "emulations" "colemak" "evil") (:authors ("Wouter Bolsterlee" . "wouter@bolsterl.ee")) (:maintainers ("Wouter Bolsterlee" . "wouter@bolsterl.ee")) (:maintainer "Wouter Bolsterlee" . "wouter@bolsterl.ee"))]) + (evil-colemak-basics . [(20241004 1613) ((emacs (24 3)) (evil (1 2 12)) (evil-snipe (2 0 3))) "Basic Colemak key bindings for evil-mode" tar ((:url . "https://github.com/wbolster/emacs-evil-colemak-basics") (:commit . "9465c8da35fe7dd0f66184e671e357ec91faa3fe") (:revdesc . "9465c8da35fe") (:keywords "convenience" "emulations" "colemak" "evil") (:authors ("Wouter Bolsterlee" . "wouter@bolsterl.ee")) (:maintainers ("Wouter Bolsterlee" . "wouter@bolsterl.ee")) (:maintainer "Wouter Bolsterlee" . "wouter@bolsterl.ee"))]) (evil-colemak-minimal . [(20171006 1317) ((emacs (24)) (evil (1 2 12))) "Minimal Colemak key bindings for evil-mode" tar ((:url . "https://github.com/bmallred/evil-colemak-minimal") (:commit . "6d98b6da60f414524a0d718f76024c26dce742b3") (:revdesc . "6d98b6da60f4") (:keywords "colemak" "evil") (:authors ("Bryan Allred" . "bryan@revolvingcow.com")) (:maintainers ("Bryan Allred" . "bryan@revolvingcow.com")) (:maintainer "Bryan Allred" . "bryan@revolvingcow.com"))]) (evil-collection . [(20240827 1102) ((emacs (26 3)) (evil (1 2 13)) (annalist (1 0))) "A set of keybindings for Evil mode" tar ((:url . "https://github.com/emacs-evil/evil-collection") (:commit . "6365e7c8ae728f7a26294db261b6778d089a6263") (:revdesc . "6365e7c8ae72") (:keywords "evil" "tools") (:authors ("James Nguyen" . "james@jojojames.com")) (:maintainers ("James Nguyen" . "james@jojojames.com")) (:maintainer "James Nguyen" . "james@jojojames.com"))]) (evil-commentary . [(20230610 1006) ((evil (1 0 0))) "Comment stuff out. A port of vim-commentary" tar ((:url . "https://github.com/linktohack/evil-commentary") (:commit . "c5945f28ce47644c828aac1f5f6ec335478d17fb") (:revdesc . "c5945f28ce47") (:keywords "evil" "comment" "commentary" "evil-commentary") (:authors ("Quang Linh LE" . "linktohack@gmail.com")) (:maintainers ("Quang Linh LE" . "linktohack@gmail.com")) (:maintainer "Quang Linh LE" . "linktohack@gmail.com"))]) @@ -2025,7 +2025,7 @@ (fuo . [(20190812 927) ((emacs (24 4))) "Feeluown client" tar ((:url . "https://github.com/feeluown/emacs-fuo") (:commit . "0e4122f94a336a50c02bc96652d25ac3d74bedeb") (:revdesc . "0e4122f94a33") (:keywords "feeluown" "multimedia" "unix") (:authors ("cosven" . "yinshaowen241@gmail.com")) (:maintainers ("cosven" . "yinshaowen241@gmail.com")) (:maintainer "cosven" . "yinshaowen241@gmail.com"))]) (furl . [(20150509 316) nil "Friendly URL retrieval" tar ((:url . "https://github.com/nex3/furl-el") (:commit . "014438271e0ef27333dfcd599cb247f12a20d870") (:revdesc . "014438271e0e") (:authors ("Natalie Weizenbaum" . "nweiz@google.com")) (:maintainers ("Natalie Weizenbaum" . "nweiz@google.com")) (:maintainer "Natalie Weizenbaum" . "nweiz@google.com"))]) (fussy . [(20240607 2153) ((emacs (27 2)) (flx (0 5))) "Fuzzy completion style using `flx'" tar ((:url . "https://github.com/jojojames/fussy") (:commit . "21f4ac6b971f61890d46308d7ac5db64c20228e6") (:revdesc . "21f4ac6b971f") (:keywords "matching") (:authors ("James Nguyen" . "james@jojojames.com")) (:maintainers ("James Nguyen" . "james@jojojames.com")) (:maintainer "James Nguyen" . "james@jojojames.com"))]) - (futhark-mode . [(20240923 1033) ((emacs (24 3)) (cl-lib (0 5))) "Major mode for editing Futhark source files" tar ((:url . "https://github.com/diku-dk/futhark-mode") (:commit . "2020883d6c0ab27313879c51e2bcf217de239417") (:revdesc . "2020883d6c0a") (:keywords "languages"))]) + (futhark-mode . [(20241003 1821) ((emacs (24 3)) (cl-lib (0 5)) (reformatter (0 4))) "Major mode for editing Futhark source files" tar ((:url . "https://github.com/diku-dk/futhark-mode") (:commit . "54246aa75867d72648effd9cbb8d8b41a4d448e4") (:revdesc . "54246aa75867") (:keywords "languages"))]) (fuz . [(20200104 524) ((emacs (25 1))) "Fast and precise fuzzy scoring/matching utils" tar ((:url . "https://github.com/rustify-emacs/fuz.el") (:commit . "0b6b64cebde5675be3a28520ee16234db48d3b8b") (:revdesc . "0b6b64cebde5") (:keywords "lisp") (:authors ("Zhu Zihao" . "all_but_last@163.com")) (:maintainers ("Zhu Zihao" . "all_but_last@163.com")) (:maintainer "Zhu Zihao" . "all_but_last@163.com"))]) (fuzzy . [(20240101 830) ((emacs (24 3))) "Fuzzy Matching" tar ((:url . "https://github.com/auto-complete/fuzzy-el") (:commit . "295140da741ac02c1bd3dec69ccf7f6268d60ec5") (:revdesc . "295140da741a") (:keywords "convenience") (:authors ("Tomohiro Matsuyama" . "m2ym.pub@gmail.com")) (:maintainers ("Tomohiro Matsuyama" . "m2ym.pub@gmail.com")) (:maintainer "Tomohiro Matsuyama" . "m2ym.pub@gmail.com"))]) (fuzzy-finder . [(20210906 217) ((emacs (24 4))) "Fuzzy Finder App Integration" tar ((:url . "https://github.com/10sr/fuzzy-finder-el") (:commit . "915a281fc8e50df84dcc205f9357e8314d60fa54") (:revdesc . "915a281fc8e5") (:keywords "matching") (:authors ("10sr" . "8.slashes@gmail.com")) (:maintainers ("10sr" . "8.slashes@gmail.com")) (:maintainer "10sr" . "8.slashes@gmail.com"))]) @@ -2158,7 +2158,7 @@ (gnome-calendar . [(20161110 1256) nil "Integration with the GNOME Shell calendar" tar ((:url . "https://github.com/NicolasPetton/gnome-calendar.el") (:commit . "668591bec95c23934c5e1ef100cec4824e7cb25d") (:revdesc . "668591bec95c") (:keywords "gnome" "calendar") (:authors ("Nicolas Petton" . "nicolas@petton.fr")) (:maintainers ("Nicolas Petton" . "nicolas@petton.fr")) (:maintainer "Nicolas Petton" . "nicolas@petton.fr"))]) (gnome-screencast . [(20210125 2001) ((emacs (25))) "Use Gnome screen recording functionality using elisp" tar ((:url . "https://github.com/juergenhoetzel/emacs-gnome-screencast") (:commit . "1f4ef60fe9d452320dc02f89e289bac04ef2ad1c") (:revdesc . "1f4ef60fe9d4") (:keywords "tools" "multimedia") (:authors ("Jürgen Hötzel" . "juergen@hoetzel.info")) (:maintainers ("Jürgen Hötzel" . "juergen@hoetzel.info")) (:maintainer "Jürgen Hötzel" . "juergen@hoetzel.info"))]) (gnomenm . [(20150316 1918) ((s (1 9 0)) (dash (2 3 0)) (kv (0 0 19))) "Emacs interface to Gnome nmcli command" tar ((:url . "https://github.com/nicferrier/emacs-nm") (:commit . "9065cda44ffc9e06239b8189a0154d31314c3b4d") (:revdesc . "9065cda44ffc") (:keywords "processes" "hardware") (:authors ("Nic Ferrier" . "nferrier@ferrier.me.uk")) (:maintainers ("Nic Ferrier" . "nferrier@ferrier.me.uk")) (:maintainer "Nic Ferrier" . "nferrier@ferrier.me.uk"))]) - (gnosis . [(20240906 1228) ((emacs (27 2)) (emacsql (4 0 1)) (compat (29 1 4 2)) (transient (0 7 2))) "Spaced Repetition System" tar ((:url . "https://git.thanosapollo.org/gnosis") (:commit . "40f63788afdb74fa71177abd882e852177829881") (:revdesc . "40f63788afdb") (:keywords "extensions") (:authors ("Thanos Apollo" . "public@thanosapollo.org")) (:maintainers ("Thanos Apollo" . "public@thanosapollo.org")) (:maintainer "Thanos Apollo" . "public@thanosapollo.org"))]) + (gnosis . [(20241006 536) ((emacs (27 2)) (emacsql (4 0 1)) (compat (29 1 4 2)) (transient (0 7 2))) "Spaced Repetition System" tar ((:url . "https://git.thanosapollo.org/gnosis") (:commit . "4f437a3b23090d2591eb36a26c146ff3595a6256") (:revdesc . "4f437a3b2309") (:keywords "extensions") (:authors ("Thanos Apollo" . "public@thanosapollo.org")) (:maintainers ("Thanos Apollo" . "public@thanosapollo.org")) (:maintainer "Thanos Apollo" . "public@thanosapollo.org"))]) (gntp . [(20141025 250) nil "Growl Notification Protocol for Emacs" tar ((:url . "https://github.com/tekai/gntp.el") (:commit . "767571135e2c0985944017dc59b0be79af222ef5") (:revdesc . "767571135e2c") (:authors ("Engelke Eschner" . "tekai@gmx.li")) (:maintainers ("Engelke Eschner" . "tekai@gmx.li")) (:maintainer "Engelke Eschner" . "tekai@gmx.li"))]) (gnu-apl-mode . [(20220404 341) ((emacs (27))) "Integrate GNU APL with Emacs" tar ((:url . "https://github.com/lokedhs/gnu-apl-mode") (:commit . "c8695b0d55b5167263a843252ffd21a589018427") (:revdesc . "c8695b0d55b5") (:keywords "languages") (:authors ("Elias Mårtenson" . "lokedhs@gmail.com")) (:maintainers ("Elias Mårtenson" . "lokedhs@gmail.com")) (:maintainer "Elias Mårtenson" . "lokedhs@gmail.com"))]) (gnu-indent . [(20221127 2112) ((emacs (25 1))) "Indent your code with GNU Indent" tar ((:url . "https://codeberg.org/akib/emacs-gnu-indent") (:commit . "f31dbe60478b6270bb57b6b05998df8eec56f801") (:revdesc . "f31dbe60478b") (:keywords "tools" "c") (:authors ("Akib Azmain Turja" . "akib@disroot.org")) (:maintainers ("Akib Azmain Turja" . "akib@disroot.org")) (:maintainer "Akib Azmain Turja" . "akib@disroot.org"))]) @@ -2681,7 +2681,7 @@ (imakado . [(20141024 923) nil "Imakado's usefull macros and functions" tar ((:url . "https://github.com/imakado/emacs-imakado") (:commit . "00a1e7eea2cb9e9066343a23927d6c747707902f") (:revdesc . "00a1e7eea2cb") (:keywords "convenience") (:authors ("imakado" . "ken.imakado_at_gmail.com")))]) (imake . [(20241001 1019) ((emacs (26 1)) (compat (30 0 0 0))) "Simple, opinionated make target runner" tar ((:url . "https://github.com/tarsius/imake") (:commit . "21951b7081e4b36641bf87793b064e06670943d1") (:revdesc . "21951b7081e4") (:keywords "convenience") (:authors ("Jonas Bernoulli" . "emacs.imake@jonas.bernoulli.dev")) (:maintainers ("Jonas Bernoulli" . "emacs.imake@jonas.bernoulli.dev")) (:maintainer "Jonas Bernoulli" . "emacs.imake@jonas.bernoulli.dev"))]) (imapfilter . [(20180318 2222) nil "Run the imapfilter executable" tar ((:url . "https://github.com/tarsius/imapfilter") (:commit . "79bbbe918319bc1e8f42a0bef53dc7c77fe868ea") (:revdesc . "79bbbe918319") (:keywords "mail") (:authors ("Jonas Bernoulli" . "jonas@bernoul.li")) (:maintainers ("Jonas Bernoulli" . "jonas@bernoul.li")) (:maintainer "Jonas Bernoulli" . "jonas@bernoul.li"))]) - (imbot . [(20240120 1331) ((emacs (25 1))) "Automatic system input method switcher" tar ((:url . "https://github.com/QiangF/imbot") (:commit . "32be46c7a8bd759945ae34f19c0c6f09935a7e64") (:revdesc . "32be46c7a8bd") (:keywords "convenience"))]) + (imbot . [(20241003 1252) ((emacs (25 1))) "Automatic system input method switcher" tar ((:url . "https://github.com/QiangF/imbot") (:commit . "833777daf76761997687149af688cda51c0c45f5") (:revdesc . "833777daf767") (:keywords "convenience"))]) (imenu-anywhere . [(20210201 1704) ((cl-lib (0 5)) (emacs (25))) "Ido/ivy/helm imenu across same mode/project/etc buffers" tar ((:url . "https://github.com/vspinu/imenu-anywhere") (:commit . "06ec33d79e33edf01b9118aead1eabeae8ee08b1") (:revdesc . "06ec33d79e33") (:keywords "ido" "imenu" "tags") (:authors ("Vitalie Spinu" . "spinuvit.list[aaattt]gmail[dot]com")) (:maintainers ("Vitalie Spinu" . "spinuvit.list[aaattt]gmail[dot]com")) (:maintainer "Vitalie Spinu" . "spinuvit.list[aaattt]gmail[dot]com"))]) (imenu-extra . [(20201229 1035) ((emacs (25 1))) "Add extra items into existing imenu items" tar ((:url . "https://github.com/redguardtoo/imenu-extra") (:commit . "68b0aaaefc18b267e4e383df36a8dfb7448bc83c") (:revdesc . "68b0aaaefc18") (:keywords "convenience") (:authors ("Chen Bin" . "chenbinDOTshATgmailDOTcom")) (:maintainers ("Chen Bin" . "chenbinDOTshATgmailDOTcom")) (:maintainer "Chen Bin" . "chenbinDOTshATgmailDOTcom"))]) (imenu-list . [(20210420 1200) ((emacs (24 3))) "Show imenu entries in a separate buffer" tar ((:url . "https://github.com/bmag/imenu-list") (:commit . "76f2335ee6f2f066d87fe4e4729219d70c9bc70d") (:revdesc . "76f2335ee6f2"))]) @@ -2916,7 +2916,7 @@ (jump-to-line . [(20130122 1653) nil "Jump to line number at point" tar ((:url . "https://github.com/ongaeshi/jump-to-line") (:commit . "01ef8c3529d85e6c59cc20840acbc4a8e8325bc8") (:revdesc . "01ef8c3529d8") (:keywords "jump" "line" "back" "file" "ruby" "csharp" "python" "perl"))]) (jump-tree . [(20171014 1551) nil "Treat position history as a tree" tar ((:url . "https://github.com/yangwen0228/jump-tree") (:commit . "282267dc6305889e31d46b405b7ad4dfe5923b66") (:revdesc . "282267dc6305") (:keywords "convenience" "position" "jump" "tree") (:authors ("Wen Yang" . "yangwen0228@foxmail.com")) (:maintainers ("Wen Yang" . "yangwen0228@foxmail.com")) (:maintainer "Wen Yang" . "yangwen0228@foxmail.com"))]) (jumplist . [(20151120 345) ((cl-lib (0 5))) "Jump like vim jumplist or ex jumplist" tar ((:url . "https://github.com/ganmacs/jumplist") (:commit . "c482d137d95bc5e1bcd790cdbde25b7f729b2502") (:revdesc . "c482d137d95b") (:keywords "jumplist" "vim") (:authors ("ganmacs" . "ganmacs_at_gmail.com")) (:maintainers ("ganmacs" . "ganmacs_at_gmail.com")) (:maintainer "ganmacs" . "ganmacs_at_gmail.com"))]) - (jupyter . [(20240716 2028) ((emacs (26)) (cl-lib (0 5)) (org (9 1 6)) (zmq (0 10 10)) (simple-httpd (1 5 0)) (websocket (1 9))) "Jupyter" tar ((:url . "https://github.com/emacs-jupyter/jupyter") (:commit . "f97f4b5d8c83e0b901020f835183dde8a2bf649e") (:revdesc . "f97f4b5d8c83") (:authors ("Nathaniel Nicandro" . "nathanielnicandro@gmail.com")) (:maintainers ("Nathaniel Nicandro" . "nathanielnicandro@gmail.com")) (:maintainer "Nathaniel Nicandro" . "nathanielnicandro@gmail.com"))]) + (jupyter . [(20241004 241) ((emacs (26)) (cl-lib (0 5)) (org (9 1 6)) (zmq (0 10 10)) (simple-httpd (1 5 0)) (websocket (1 9))) "Jupyter" tar ((:url . "https://github.com/emacs-jupyter/jupyter") (:commit . "674af0481a94f2ce56c62aa7668a966254ef26ef") (:revdesc . "674af0481a94") (:authors ("Nathaniel Nicandro" . "nathanielnicandro@gmail.com")) (:maintainers ("Nathaniel Nicandro" . "nathanielnicandro@gmail.com")) (:maintainer "Nathaniel Nicandro" . "nathanielnicandro@gmail.com"))]) (just-mode . [(20240424 1809) ((emacs (26 1))) "Justfile editing mode" tar ((:url . "https://github.com/leon-barrett/just-mode.el") (:commit . "4c0df4cc4b8798f1a7e99fb78b79c4bf7eec12c1") (:revdesc . "4c0df4cc4b87") (:keywords "files" "languages" "tools") (:authors ("Leon Barrett" . "(leon@barrettnexus.com)")) (:maintainers ("Leon Barrett" . "(leon@barrettnexus.com)")) (:maintainer "Leon Barrett" . "(leon@barrettnexus.com)"))]) (justl . [(20240925 455) ((transient (0 1 0)) (emacs (27 1)) (s (1 2 0)) (f (0 20 0)) (inheritenv (0 2))) "Major mode for driving just files" tar ((:url . "https://github.com/psibi/justl.el") (:commit . "a46b95425c8f55d5ebfa674f09d606a6321e51e9") (:revdesc . "a46b95425c8f") (:keywords "just" "justfile" "tools" "processes"))]) (jvm-mode . [(20150422 708) ((dash (2 6 0)) (emacs (24))) "Monitor and manage your JVMs" tar ((:url . "https://github.com/martintrojer/jvm-mode.el") (:commit . "3355dbaf5b0185aadfbad24160399abb32c5bea0") (:revdesc . "3355dbaf5b01") (:keywords "convenience") (:authors ("Martin Trojer" . "martin.trojer@gmail.com")) (:maintainers ("Martin Trojer" . "martin.trojer@gmail.com")) (:maintainer "Martin Trojer" . "martin.trojer@gmail.com"))]) @@ -2970,7 +2970,7 @@ (kfg . [(20140909 538) ((f (0 17 1))) "An emacs configuration system" tar ((:url . "https://github.com/czipperz/kfg") (:commit . "ffc35b77f227d4c64a1271ec30d31333ffeb0013") (:revdesc . "ffc35b77f227") (:authors ("Austin Bingham" . "austin.bingham@gmail.com")) (:maintainers ("Austin Bingham" . "austin.bingham@gmail.com")) (:maintainer "Austin Bingham" . "austin.bingham@gmail.com"))]) (khalel . [(20240527 527) ((emacs (27 1))) "Import, edit and create calendar events through khal" tar ((:url . "https://gitlab.com/hperrey/khalel") (:commit . "14ef50352394cd1d62b80bc17ab14f4f801f47cd") (:revdesc . "14ef50352394") (:keywords "event" "calendar" "ics" "khal") (:authors ("Hanno Perrey" . "http://gitlab.com/hperrey")) (:maintainers ("Hanno Perrey" . "hanno@hoowl.se")) (:maintainer "Hanno Perrey" . "hanno@hoowl.se"))]) (khardel . [(20231126 1502) ((emacs (27 1)) (yaml-mode (0 0 13))) "Integrate with khard" tar ((:url . "https://github.com/DamienCassou/khardel") (:commit . "205e374b36252183a146a7a8f857bcf95a77edc3") (:revdesc . "205e374b3625") (:authors ("Damien Cassou" . "damien@cassou.me")) (:maintainers ("Damien Cassou" . "damien@cassou.me")) (:maintainer "Damien Cassou" . "damien@cassou.me"))]) - (khoj . [(20240929 1156) ((emacs (27 1)) (transient (0 3 0)) (dash (2 19 1))) "Your Second Brain" tar ((:url . "https://github.com/khoj-ai/khoj") (:commit . "dd44933515c7354f6dc238fbe019f6c55d6986af") (:revdesc . "dd44933515c7") (:keywords "search" "chat" "ai" "org-mode" "outlines" "markdown" "pdf" "image") (:authors ("Debanjum Singh Solanky" . "debanjum@khoj.dev") ("Saba Imran" . "saba@khoj.dev")) (:maintainers ("Debanjum Singh Solanky" . "debanjum@khoj.dev") ("Saba Imran" . "saba@khoj.dev")) (:maintainer "Debanjum Singh Solanky" . "debanjum@khoj.dev"))]) + (khoj . [(20241003 2021) ((emacs (27 1)) (transient (0 3 0)) (dash (2 19 1))) "Your Second Brain" tar ((:url . "https://github.com/khoj-ai/khoj") (:commit . "27c7e54695415a29200900d7d9c5e1f7e10058e5") (:revdesc . "27c7e5469541") (:keywords "search" "chat" "ai" "org-mode" "outlines" "markdown" "pdf" "image") (:authors ("Debanjum Singh Solanky" . "debanjum@khoj.dev") ("Saba Imran" . "saba@khoj.dev")) (:maintainers ("Debanjum Singh Solanky" . "debanjum@khoj.dev") ("Saba Imran" . "saba@khoj.dev")) (:maintainer "Debanjum Singh Solanky" . "debanjum@khoj.dev"))]) (kibit-helper . [(20150508 1533) ((s (0 8)) (emacs (24))) "Conveniently use the Kibit Leiningen plugin from Emacs" tar ((:url . "https://github.com/brunchboy/kibit-helper") (:commit . "ec5f154db3bb0c838e86f527353f08644cede926") (:revdesc . "ec5f154db3bb") (:keywords "languages" "clojure" "kibit") (:authors ("James Elliott" . "james@brunchboy.com")) (:maintainers ("James Elliott" . "james@brunchboy.com")) (:maintainer "James Elliott" . "james@brunchboy.com"))]) (kill-file-path . [(20230306 1041) ((emacs (26))) "Copy file name into kill ring" tar ((:url . "https://github.com/chyla/kill-file-path") (:commit . "5dcbce69cbae17665216a32dd20f27de54c62972") (:revdesc . "5dcbce69cbae") (:keywords "files") (:authors ("Adam Chyła" . "adam@chyla.org")) (:maintainers ("Adam Chyła" . "adam@chyla.org")) (:maintainer "Adam Chyła" . "adam@chyla.org"))]) (kill-or-bury-alive . [(20230606 1503) ((emacs (24 4))) "Precise control over buffer killing" tar ((:url . "https://github.com/mrkkrp/kill-or-bury-alive") (:commit . "16c393db6ad0c7e184af0a24d26b637e23543b1f") (:revdesc . "16c393db6ad0") (:keywords "convenience") (:authors ("Mark Karpov" . "markkarpov92@gmail.com")) (:maintainers ("Mark Karpov" . "markkarpov92@gmail.com")) (:maintainer "Mark Karpov" . "markkarpov92@gmail.com"))]) @@ -3011,7 +3011,7 @@ (kv . [(20140108 1534) nil "Key/value data structure functions" tar ((:url . "https://github.com/nicferrier/emacs-kv") (:commit . "721148475bce38a70e0b678ba8aa923652e8900e") (:revdesc . "721148475bce") (:keywords "lisp") (:authors ("Nic Ferrier" . "nferrier@ferrier.me.uk")) (:maintainers ("Nic Ferrier" . "nferrier@ferrier.me.uk")) (:maintainer "Nic Ferrier" . "nferrier@ferrier.me.uk"))]) (kwin . [(20220120 2125) nil "Communicatewith the KWin window manager" tar ((:url . "https://github.com/reactormonk/kwin-minor-mode") (:commit . "20fac6508e5535a26df783ba05f04d1800b7382c") (:revdesc . "20fac6508e55"))]) (laas . [(20230331 1806) ((emacs (26 3)) (auctex (11 88)) (aas (1 1))) "A bundle of as-you-type LaTeX snippets" tar ((:url . "https://github.com/tecosaur/LaTeX-auto-activating-snippets") (:commit . "a00f0aba237b85b3e5fd60cf84de5759d1bf5d48") (:revdesc . "a00f0aba237b") (:keywords "tools" "tex") (:maintainers ("Yoav Marco" . "yoavm448@gmail.com")) (:maintainer "Yoav Marco" . "yoavm448@gmail.com"))]) - (lab . [(20240930 1525) ((emacs (27 1)) (memoize (1 1)) (request (0 3 2)) (s (1 10 0)) (f (0 20 0)) (compat (29 1 4 4)) (promise (1 1)) (async-await (1 1))) "An interface for GitLab" tar ((:url . "https://github.com/isamert/lab.el") (:commit . "9bf5740dc95e8f4ae952f4d16b2edb1f315036d4") (:revdesc . "9bf5740dc95e") (:authors ("Isa Mert Gurbuz" . "isamertgurbuz@gmail.com")) (:maintainers ("Isa Mert Gurbuz" . "isamertgurbuz@gmail.com")) (:maintainer "Isa Mert Gurbuz" . "isamertgurbuz@gmail.com"))]) + (lab . [(20241004 818) ((emacs (27 1)) (memoize (1 1)) (request (0 3 2)) (s (1 10 0)) (f (0 20 0)) (compat (29 1 4 4)) (promise (1 1)) (async-await (1 1)) (auth-source (23 1))) "An interface for GitLab" tar ((:url . "https://github.com/isamert/lab.el") (:commit . "193eb6b74f4c60c455cae276d3881668383b21fc") (:revdesc . "193eb6b74f4c") (:authors ("Isa Mert Gurbuz" . "isamertgurbuz@gmail.com")) (:maintainers ("Isa Mert Gurbuz" . "isamertgurbuz@gmail.com")) (:maintainer "Isa Mert Gurbuz" . "isamertgurbuz@gmail.com"))]) (lab-themes . [(20200815 2104) ((emacs (24))) "A custom theme carefully constructed in the LAB space" tar ((:url . "https://github.com/MetroWind/lab-theme") (:commit . "9d7deb9635959d3a50ccb1082eb1207275f4b3e8") (:revdesc . "9d7deb963595") (:keywords "lisp") (:authors ("MetroWind" . "chris.corsair@gmail.com")) (:maintainers ("MetroWind" . "chris.corsair@gmail.com")) (:maintainer "MetroWind" . "chris.corsair@gmail.com"))]) (labburn-theme . [(20221208 1611) nil "A lab color space zenburn theme" tar ((:url . "https://github.com/ksjogo/labburn-theme") (:commit . "bd0de2fdcf285d981f32e3e5ebc56fe3c9b589a5") (:revdesc . "bd0de2fdcf28") (:keywords "theme" "zenburn"))]) (lacquer . [(20230824 725) ((emacs (25 2))) "Switch theme/font by selecting from a cache" tar ((:url . "https://github.com/zakudriver/lacquer") (:commit . "c8a0fb81f18001b3d510f545ba253ed4f9a50f5b") (:revdesc . "c8a0fb81f180") (:keywords "tools") (:authors ("zakudriver" . "zy.hua1122@gmail.com")) (:maintainers ("zakudriver" . "zy.hua1122@gmail.com")) (:maintainer "zakudriver" . "zy.hua1122@gmail.com"))]) @@ -3136,7 +3136,7 @@ (livescript-mode . [(20221015 1316) ((emacs (24 3))) "Major mode for editing LiveScript files" tar ((:url . "https://github.com/yhisamatsu/livescript-mode") (:commit . "e71a82a400e9d451c966c397bb8fa7887d35637b") (:revdesc . "e71a82a400e9") (:keywords "languages" "livescript") (:authors ("Hisamatsu Yasuyuki" . "yas@null.net")) (:maintainers ("Hisamatsu Yasuyuki" . "yas@null.net")) (:maintainer "Hisamatsu Yasuyuki" . "yas@null.net"))]) (livid-mode . [(20131116 1344) ((skewer-mode (1 5 3)) (s (1 8 0))) "Live browser eval of JavaScript every time a buffer changes" tar ((:url . "https://github.com/pandeiro/livid-mode") (:commit . "dfe5212fa64738bc4138bfebf349fbc8bc237c26") (:revdesc . "dfe5212fa647"))]) (ll-debug . [(20211002 1031) ((emacs (24 3))) "Low level debug tools" tar ((:url . "https://github.com/replrep/ll-debug") (:commit . "a2cfeab46e5100c348b35987fae34f9ea76d7c0b") (:revdesc . "a2cfeab46e51") (:keywords "abbrev" "convenience" "tools" "c" "lisp") (:authors ("Claus Brunzema" . "mail@cbrunzema.de")) (:maintainers ("Claus Brunzema" . "mail@cbrunzema.de")) (:maintainer "Claus Brunzema" . "mail@cbrunzema.de"))]) - (llama . [(20240920 2052) ((emacs (26 1))) "Compact syntax for short lambda" tar ((:url . "https://github.com/tarsius/llama") (:commit . "e23b81b153683895e3dea2acbfa4f157e077a647") (:revdesc . "e23b81b15368") (:keywords "extensions"))]) + (llama . [(20241003 1906) ((emacs (26 1))) "Compact syntax for short lambda" tar ((:url . "https://github.com/tarsius/llama") (:commit . "8fdcde4aafbd6d5768fa135d9e2a7bc1ae95b23a") (:revdesc . "8fdcde4aafbd") (:keywords "extensions"))]) (llama-cpp . [(20240511 1039) ((emacs (27 1)) (dash (2 19 1))) "A client for llama-cpp server" tar ((:url . "https://github.com/kurnevsky/llama-cpp.el") (:commit . "5cea3698aa63921b21888f126cae4f3ebc1baa39") (:revdesc . "5cea3698aa63") (:keywords "tools") (:authors ("Evgeny Kurnevsky" . "kurnevsky@gmail.com")) (:maintainers ("Evgeny Kurnevsky" . "kurnevsky@gmail.com")) (:maintainer "Evgeny Kurnevsky" . "kurnevsky@gmail.com"))]) (llvm-ts-mode . [(20231120 1251) ((emacs (29 1))) "LLVM major mode using tree-sitter" tar ((:url . "https://github.com/nverno/llvm-ts-mode") (:commit . "9974601dcddbeffc4ad47598d63d3c1a83bb6fb9") (:revdesc . "9974601dcddb") (:keywords "languages" "tree-sitter" "llvm") (:authors ("Noah Peart" . "noah.v.peart@gmail.com")) (:maintainers ("Noah Peart" . "noah.v.peart@gmail.com")) (:maintainer "Noah Peart" . "noah.v.peart@gmail.com"))]) (lms . [(20210820 2200) ((emacs (25 1))) "Squeezebox / Logitech Media Server frontend" tar ((:url . "https://hg.serna.eu/emacs/lms") (:commit . "29593b4c18a570dfb2e60b196f24d407a1277daa") (:revdesc . "29593b4c18a570dfb2e60b196f24d407a1277daa") (:keywords "multimedia") (:authors ("Iñigo Serna" . "inigoserna@gmx.com")) (:maintainers ("Iñigo Serna" . "inigoserna@gmx.com")) (:maintainer "Iñigo Serna" . "inigoserna@gmx.com"))]) @@ -3186,7 +3186,7 @@ (lsp-latex . [(20240803 1436) ((emacs (27 1)) (lsp-mode (6 0)) (consult (0 35))) "LSP-mode client for LaTeX, on texlab" tar ((:url . "https://github.com/ROCKTAKEY/lsp-latex") (:commit . "2f45606dce911ebc45a42cbbaa01973b8caff4ec") (:revdesc . "2f45606dce91") (:keywords "languages" "tex") (:authors ("ROCKTAKEY" . "rocktakey@gmail.com")) (:maintainers ("ROCKTAKEY" . "rocktakey@gmail.com")) (:maintainer "ROCKTAKEY" . "rocktakey@gmail.com"))]) (lsp-ltex . [(20240425 2049) ((emacs (27 1)) (lsp-mode (6 1))) "LSP Clients for LTEX" tar ((:url . "https://github.com/emacs-languagetool/lsp-ltex") (:commit . "c473ed37aa0f2769bb0b4c344cc28f95975dbc17") (:revdesc . "c473ed37aa0f") (:keywords "convenience" "lsp" "languagetool" "checker") (:authors ("Jen-Chieh" . "jcs090218@gmail.com")) (:maintainers ("Jen-Chieh" . "jcs090218@gmail.com")) (:maintainer "Jen-Chieh" . "jcs090218@gmail.com"))]) (lsp-metals . [(20240821 1959) ((emacs (27 1)) (scala-mode (0 23)) (lsp-mode (7 0)) (lsp-treemacs (0 2)) (dap-mode (0 3)) (dash (2 18 0)) (f (0 20 0)) (ht (2 0)) (treemacs (3 1)) (posframe (1 4 1))) "Scala Client settings" tar ((:url . "https://github.com/emacs-lsp/lsp-metals") (:commit . "0dc938be1190d147e7013e3dce08ac8bff5d1662") (:revdesc . "0dc938be1190") (:keywords "languages" "extensions") (:authors ("Ross A. Baker" . "ross@rossabaker.com") ("Evgeny Kurnevsky" . "kurnevsky@gmail.com")) (:maintainers ("Ross A. Baker" . "ross@rossabaker.com") ("Evgeny Kurnevsky" . "kurnevsky@gmail.com")) (:maintainer "Ross A. Baker" . "ross@rossabaker.com"))]) - (lsp-mode . [(20241003 636) ((emacs (27 1)) (dash (2 18 0)) (f (0 20 0)) (ht (2 3)) (spinner (1 7 3)) (markdown-mode (2 3)) (lv (0)) (eldoc (1 11))) "LSP mode" tar ((:url . "https://github.com/emacs-lsp/lsp-mode") (:commit . "52de586352de237951ee4cdd4a1351fa97e10c63") (:revdesc . "52de586352de") (:keywords "languages"))]) + (lsp-mode . [(20241004 151) ((emacs (27 1)) (dash (2 18 0)) (f (0 20 0)) (ht (2 3)) (spinner (1 7 3)) (markdown-mode (2 3)) (lv (0)) (eldoc (1 11))) "LSP mode" tar ((:url . "https://github.com/emacs-lsp/lsp-mode") (:commit . "3a952ca135bd508e7dee4650a195b7ec5886a0ea") (:revdesc . "3a952ca135bd") (:keywords "languages"))]) (lsp-mssql . [(20230510 1124) ((emacs (25 1)) (lsp-mode (6 2)) (dash (2 14 1)) (f (0 20 0)) (ht (2 0)) (lsp-treemacs (0 1))) "MSSQL LSP bindings" tar ((:url . "https://github.com/emacs-lsp/lsp-mssql") (:commit . "a0dba8f86a2ace7e800a9dc8f814767625a509af") (:revdesc . "a0dba8f86a2a") (:keywords "data" "languages") (:authors ("Ivan Yonchovski" . "yyoncho@gmail.com")) (:maintainers ("Ivan Yonchovski" . "yyoncho@gmail.com")) (:maintainer "Ivan Yonchovski" . "yyoncho@gmail.com"))]) (lsp-origami . [(20230815 704) ((emacs (27 1)) (origami (1 0)) (lsp-mode (6 1))) "Origami.el support for lsp-mode" tar ((:url . "https://github.com/emacs-lsp/lsp-origami") (:commit . "86aa06517910141c3d5054eea5f7723461fce6a6") (:revdesc . "86aa06517910") (:keywords "languages" "lsp-mode"))]) (lsp-p4 . [(20190127 1049) ((lsp-mode (3 0))) "P4 support for lsp-mode" tar ((:url . "https://github.com/dmakarov/p4ls") (:commit . "084e33a5782f9153502d9b03e63d9cbbe81cdaeb") (:revdesc . "084e33a5782f") (:keywords "lsp" "p4"))]) @@ -3226,7 +3226,7 @@ (magic-filetype . [(20240130 1805) ((emacs (24 3)) (s (1 9 0))) "Enhance filetype major mode" tar ((:url . "https://github.com/emacs-php/magic-filetype.el") (:commit . "3979ddbd8066d7390e31bde2b35f997c5f5f4516") (:revdesc . "3979ddbd8066") (:keywords "emulations" "vim" "ft" "file" "magic-mode") (:authors ("USAMI Kenta" . "tadsan@zonu.me")) (:maintainers ("USAMI Kenta" . "tadsan@zonu.me")) (:maintainer "USAMI Kenta" . "tadsan@zonu.me"))]) (magic-latex-buffer . [(20210306 422) ((cl-lib (0 5)) (emacs (25 1))) "Magically enhance LaTeX-mode font-locking for semi-WYSIWYG editing" tar ((:url . "https://github.com/zk-phi/magic-latex-buffer") (:commit . "903ec91872760e47c0e5715795f8465173615098") (:revdesc . "903ec9187276"))]) (magik-mode . [(20240930 1146) ((emacs (24 4)) (compat (28 1))) "Emacs major mode for Smallworld Magik files" tar ((:url . "https://github.com/roadrunner1776/magik") (:commit . "abcf2c75c9843aa815ec77572b45d14a2069d572") (:revdesc . "abcf2c75c984") (:keywords "languages"))]) - (magit . [(20241001 2052) ((emacs (26 1)) (compat (30 0 0 0)) (dash (2 19 1)) (magit-section (4 1 1)) (seq (2 24)) (transient (0 7 6)) (with-editor (3 4 2))) "A Git porcelain inside Emacs" tar ((:url . "https://github.com/magit/magit") (:commit . "93e86ceca7bf5b0ff9023d7f138e5f06990fc276") (:revdesc . "93e86ceca7bf") (:keywords "git" "tools" "vc") (:authors ("Marius Vollmer" . "marius.vollmer@gmail.com") ("Jonas Bernoulli" . "emacs.magit@jonas.bernoulli.dev")) (:maintainers ("Jonas Bernoulli" . "emacs.magit@jonas.bernoulli.dev") ("Kyle Meyer" . "kyle@kyleam.com")) (:maintainer "Jonas Bernoulli" . "emacs.magit@jonas.bernoulli.dev"))]) + (magit . [(20241004 917) ((emacs (26 1)) (compat (30 0 0 0)) (dash (2 19 1)) (magit-section (4 1 1)) (seq (2 24)) (transient (0 7 6)) (with-editor (3 4 2))) "A Git porcelain inside Emacs" tar ((:url . "https://github.com/magit/magit") (:commit . "2b6516e04431c339a41887b27ce6a1193df6e9c3") (:revdesc . "2b6516e04431") (:keywords "git" "tools" "vc") (:authors ("Marius Vollmer" . "marius.vollmer@gmail.com") ("Jonas Bernoulli" . "emacs.magit@jonas.bernoulli.dev")) (:maintainers ("Jonas Bernoulli" . "emacs.magit@jonas.bernoulli.dev") ("Kyle Meyer" . "kyle@kyleam.com")) (:maintainer "Jonas Bernoulli" . "emacs.magit@jonas.bernoulli.dev"))]) (magit-annex . [(20240811 1850) ((emacs (26 1)) (magit (4 0 0))) "Control git-annex from Magit" tar ((:url . "https://github.com/magit/magit-annex") (:commit . "9db0bc61461f222106c7ae3d8cd6d3de1f1b143f") (:revdesc . "9db0bc61461f") (:keywords "vc" "tools") (:authors ("Kyle Meyer" . "kyle@kyleam.com") ("Rémi Vanicat" . "vanicat@debian.org")) (:maintainers ("Kyle Meyer" . "kyle@kyleam.com") ("Rémi Vanicat" . "vanicat@debian.org")) (:maintainer "Kyle Meyer" . "kyle@kyleam.com"))]) (magit-commit-mark . [(20240421 931) ((emacs (29 1)) (magit (3 3 0))) "Support marking commits as read" tar ((:url . "https://codeberg.org/ideasman42/emacs-magit-commit-mark") (:commit . "d09d0df6f8a697446e9fac77428b32997b94c59e") (:revdesc . "d09d0df6f8a6") (:authors ("Campbell Barton" . "ideasman42@gmail.com")) (:maintainers ("Campbell Barton" . "ideasman42@gmail.com")) (:maintainer "Campbell Barton" . "ideasman42@gmail.com"))]) (magit-delta . [(20220125 50) ((emacs (25 1)) (magit (20200426)) (xterm-color (2 0))) "Use Delta when displaying diffs in Magit" tar ((:url . "https://github.com/dandavison/magit-delta") (:commit . "5fc7dbddcfacfe46d3fd876172ad02a9ab6ac616") (:revdesc . "5fc7dbddcfac") (:authors ("Dan Davison" . "dandavison7@gmail.com")) (:maintainers ("Dan Davison" . "dandavison7@gmail.com")) (:maintainer "Dan Davison" . "dandavison7@gmail.com"))]) @@ -3333,7 +3333,7 @@ (memoize . [(20200103 2036) nil "Memoization functions" tar ((:url . "https://github.com/skeeto/emacs-memoize") (:commit . "51b075935ca7070f62fae1d69fe0ff7d8fa56fdd") (:revdesc . "51b075935ca7") (:authors ("Christopher Wellons" . "mosquitopsu@gmail.com")) (:maintainers ("Christopher Wellons" . "mosquitopsu@gmail.com")) (:maintainer "Christopher Wellons" . "mosquitopsu@gmail.com"))]) (memolist . [(20150804 1721) ((markdown-mode (22 0)) (ag (0 45))) "Memolist.el is Emacs port of memolist.vim" tar ((:url . "https://github.com/mikanfactory/memolist.el") (:commit . "60c296e202a71e9dcf1c3936d47b5c4b95c5839f") (:revdesc . "60c296e202a7") (:keywords "markdown" "memo") (:authors ("mikanfactory" . "k952i4j14x17_at_gmail.com")))]) (mentor . [(20230103 1146) ((emacs (25 1)) (xml-rpc (1 6 15)) (seq (1 11)) (async (1 9 3)) (url-scgi (0 8))) "Frontend for the rTorrent bittorrent client" tar ((:url . "https://github.com/skangas/mentor") (:commit . "f51dd4f3f87c54b7cc92189924b9d873a53f5a75") (:revdesc . "f51dd4f3f87c") (:keywords "comm" "processes" "bittorrent") (:authors ("Stefan Kangas" . "stefankangas@gmail.com")) (:maintainers ("Stefan Kangas" . "stefankangas@gmail.com")) (:maintainer "Stefan Kangas" . "stefankangas@gmail.com"))]) - (meow . [(20241002 1728) ((emacs (27 1))) "Yet Another modal editing" tar ((:url . "https://github.com/meow-edit/meow") (:commit . "99fe8318a8edcd7cbd349d125b8a32ec273223b0") (:revdesc . "99fe8318a8ed") (:keywords "convenience" "modal-editing"))]) + (meow . [(20241005 728) ((emacs (27 1))) "Yet Another modal editing" tar ((:url . "https://github.com/meow-edit/meow") (:commit . "675cd12028fd49a7d0aecef1374befecc3a321b1") (:revdesc . "675cd12028fd") (:keywords "convenience" "modal-editing"))]) (meow-tree-sitter . [(20240701 1422) ((emacs (29 1)) (meow (1 2 0))) "Tree-sitter powered motions for Meow" tar ((:url . "https://github.com/skissue/meow-tree-sitter") (:commit . "d8dce964fac631a6d44b650a733075e14854159c") (:revdesc . "d8dce964fac6") (:keywords "convenience" "files" "languages" "tools") (:authors ("Ad" . "me@skissue.xyz")) (:maintainers ("Ad" . "me@skissue.xyz")) (:maintainer "Ad" . "me@skissue.xyz"))]) (merlin . [(20240925 900) ((emacs (25 1))) "Mode for Merlin, an assistant for OCaml" tar ((:url . "https://github.com/ocaml/merlin") (:commit . "80e919cf32a62acdaee95a5dab9b4bc18a8b4034") (:revdesc . "80e919cf32a6") (:keywords "ocaml" "languages") (:authors ("Frédéric Bour" . "frederic.bourlakaban.net")) (:maintainers ("Frédéric Bour" . "frederic.bourlakaban.net")) (:maintainer "Frédéric Bour" . "frederic.bourlakaban.net"))]) (merlin-ac . [(20221123 1408) ((emacs (25 1)) (merlin (3)) (auto-complete (1 5))) "Merlin and auto-complete integration" tar ((:url . "https://github.com/ocaml/merlin") (:commit . "8bcab034a680f57ddf58092fda6288dc4caddd2a") (:revdesc . "8bcab034a680") (:keywords "ocaml" "languages") (:authors ("Simon Castellan" . "simon.castellaniuwt.fr") ("Frédéric Bour" . "frederic.bourlakaban.net") ("Thomas Refis" . "thomas.refisgmail.com")) (:maintainers ("Simon Castellan" . "simon.castellaniuwt.fr") ("Frédéric Bour" . "frederic.bourlakaban.net") ("Thomas Refis" . "thomas.refisgmail.com")) (:maintainer "Simon Castellan" . "simon.castellaniuwt.fr"))]) @@ -3419,7 +3419,7 @@ (modern-sh . [(20211101 1001) ((emacs (25 1)) (hydra (0 15 0)) (eval-in-repl (0 9 7))) "Minor mode for editing shell script" tar ((:url . "https://github.com/damon-kwok/modern-sh") (:commit . "8ebebe77304aa8170f7af809e7564c79d3bd45da") (:revdesc . "8ebebe77304a") (:keywords "languages" "programming"))]) (modtime-skip-mode . [(20140128 2201) nil "Minor mode for disabling modtime and supersession checks on files" tar ((:url . "https://github.com/jordonbiondo/modtime-skip-mode") (:commit . "c0e49523aa26b2263a8693691ac775988015f592") (:revdesc . "c0e49523aa26") (:authors ("Jordon Biondo" . "biondoj@mail.gvsu.edu")) (:maintainers ("Jordon Biondo" . "biondoj@mail.gvsu.edu")) (:maintainer "Jordon Biondo" . "biondoj@mail.gvsu.edu"))]) (modular-config . [(20210726 1614) ((emacs (25 1))) "Organize your config into small and loadable modules" tar ((:url . "https://github.com/SidharthArya/modular-config.el") (:commit . "043907d96efff70dfaea1e721de90bd35970e8bd") (:revdesc . "043907d96eff") (:keywords "startup" "lisp" "tools") (:authors ("Sidharth Arya" . "sidhartharya10@gmail.com")) (:maintainers ("Sidharth Arya" . "sidhartharya10@gmail.com")) (:maintainer "Sidharth Arya" . "sidhartharya10@gmail.com"))]) - (modus-themes . [(20241002 1231) ((emacs (27 1))) "Elegant, highly legible and customizable themes" tar ((:url . "https://github.com/protesilaos/modus-themes") (:commit . "0c4a9973e0f26cbbb54e9e323e1b284289d9364f") (:revdesc . "0c4a9973e0f2") (:keywords "faces" "theme" "accessibility") (:authors ("Protesilaos Stavrou" . "info@protesilaos.com")) (:maintainers ("Protesilaos Stavrou" . "info@protesilaos.com")) (:maintainer "Protesilaos Stavrou" . "info@protesilaos.com"))]) + (modus-themes . [(20241004 748) ((emacs (27 1))) "Elegant, highly legible and customizable themes" tar ((:url . "https://github.com/protesilaos/modus-themes") (:commit . "4932dfc3492ba4aaaca122f9abc37048ab7cc3d1") (:revdesc . "4932dfc3492b") (:keywords "faces" "theme" "accessibility") (:authors ("Protesilaos Stavrou" . "info@protesilaos.com")) (:maintainers ("Protesilaos Stavrou" . "info@protesilaos.com")) (:maintainer "Protesilaos Stavrou" . "info@protesilaos.com"))]) (moe-theme . [(20240716 854) nil "A colorful eye-candy theme. Moe, moe, kyun!" tar ((:url . "https://github.com/kuanyui/moe-theme.el") (:commit . "4b3642157bfe9a9268310d321cfe67c8c236b5e1") (:revdesc . "4b3642157bfe") (:keywords "themes") (:authors ("kuanyui" . "azazabc123@gmail.com")) (:maintainers ("kuanyui" . "azazabc123@gmail.com")) (:maintainer "kuanyui" . "azazabc123@gmail.com"))]) (molar-mass . [(20220922 1752) ((emacs (24 3))) "Calculates molar mass of a molecule" tar ((:url . "https://github.com/sergiruiztrepat/molar-mass") (:commit . "c3b686c4b621b45fa4b17857b4934eb4487d74f5") (:revdesc . "c3b686c4b621") (:keywords "convenience" "chemistry"))]) (molecule . [(20180527 743) ((emacs (25 1))) "Simple wrapper for molecule" tar ((:url . "https://gitlab.com/drymerisnothere/molecule-el") (:commit . "2ef72b81d9aa24ea782b71a061a3abdad6cae162") (:revdesc . "2ef72b81d9aa") (:keywords ":" "languages" "terminals") (:authors ("drymer" . "drymer[AT]autistici.org")) (:maintainers ("drymer" . "drymer[AT]autistici.org")) (:maintainer "drymer" . "drymer[AT]autistici.org"))]) @@ -3904,8 +3904,8 @@ (org-multiple-keymap . [(20191017 1920) ((org (8 2 4)) (emacs (24)) (cl-lib (0 5))) "Set keymap to elements, such as timestamp and priority" tar ((:url . "https://github.com/emacsattic/org-multiple-keymap") (:commit . "4eb8aa0aada012b2346cc7f0c55e07783141a2c3") (:revdesc . "4eb8aa0aada0") (:keywords "convenience" "org-mode") (:authors ("myuhe" . "yuhei.maeda_at_gmail.com")))]) (org-newtab . [(20240227 155) ((emacs (27 1)) (websocket (1 14)) (async (1 9 7))) "Supercharge your browser's new tab page" tar ((:url . "https://github.com/Zweihander-Main/org-newtab") (:commit . "eca494a43e242558bd8db24d321ad62a8ec86c02") (:revdesc . "eca494a43e24") (:keywords "outlines") (:authors ("Zweihänder" . "zweidev@zweihander.me")) (:maintainers ("Zweihänder" . "zweidev@zweihander.me")) (:maintainer "Zweihänder" . "zweidev@zweihander.me"))]) (org-nix-shell . [(20240603 859) ((emacs (27 1)) (org (9 4))) "Org local nix-shell" tar ((:url . "https://github.com/AntonHakansson/org-nix-shell") (:commit . "f359d9e1053fadee86dd668f4789ae2e700d8e8a") (:revdesc . "f359d9e1053f") (:keywords "processes" "outlines") (:maintainers ("Anton Hakansson" . "anton@hakanssn.com")) (:maintainer "Anton Hakansson" . "anton@hakanssn.com"))]) - (org-node . [(20241003 956) ((emacs (28 1)) (compat (30)) (llama (0))) "Link org-id entries into a network" tar ((:url . "https://github.com/meedstrom/org-node") (:commit . "665d0b5116eba1604f0bb57bbae3f442eb500011") (:revdesc . "665d0b5116eb") (:keywords "org" "hypermedia") (:authors ("Martin Edström" . "meedstrom91@gmail.com")) (:maintainers ("Martin Edström" . "meedstrom91@gmail.com")) (:maintainer "Martin Edström" . "meedstrom91@gmail.com"))]) - (org-node-fakeroam . [(20241003 942) ((emacs (28 1)) (compat (30)) (org-node (1 3 7)) (org-roam (2 2 2)) (emacsql (4 0 3))) "Stand-ins for org-roam-autosync-mode" tar ((:url . "https://github.com/meedstrom/org-node-fakeroam") (:commit . "167ef6b2c284816c28ef42e2aea7ec93a3d3c85f") (:revdesc . "167ef6b2c284") (:keywords "org" "hypermedia") (:authors ("Martin Edström" . "meedstrom91@gmail.com")) (:maintainers ("Martin Edström" . "meedstrom91@gmail.com")) (:maintainer "Martin Edström" . "meedstrom91@gmail.com"))]) + (org-node . [(20241005 844) ((emacs (28 1)) (compat (30)) (llama (0))) "Link org-id entries into a network" tar ((:url . "https://github.com/meedstrom/org-node") (:commit . "dc158e434728f26ea9cc66a23069074c3c2457e6") (:revdesc . "dc158e434728") (:keywords "org" "hypermedia") (:authors ("Martin Edström" . "meedstrom91@gmail.com")) (:maintainers ("Martin Edström" . "meedstrom91@gmail.com")) (:maintainer "Martin Edström" . "meedstrom91@gmail.com"))]) + (org-node-fakeroam . [(20241005 1718) ((emacs (28 1)) (compat (30)) (org-node (1 5 0)) (org-roam (2 2 2)) (emacsql (4 0 3))) "Stand-ins for org-roam-autosync-mode" tar ((:url . "https://github.com/meedstrom/org-node-fakeroam") (:commit . "3e84dee8641191c87cc5a9e74999b2396db92972") (:revdesc . "3e84dee86411") (:keywords "org" "hypermedia") (:authors ("Martin Edström" . "meedstrom91@gmail.com")) (:maintainers ("Martin Edström" . "meedstrom91@gmail.com")) (:maintainer "Martin Edström" . "meedstrom91@gmail.com"))]) (org-notebook . [(20170322 452) ((emacs (24)) (org (8)) (cl-lib (0 5))) "Ease the use of org-mode as a notebook" tar ((:url . "https://github.com/Rahi374/org-notebook") (:commit . "d90c4aeca2442161e6dd89de175561af85aace03") (:revdesc . "d90c4aeca244") (:keywords "convenience" "tools") (:authors ("Paul Elder" . "paul.elder@amanokami.net")) (:maintainers ("Paul Elder" . "paul.elder@amanokami.net")) (:maintainer "Paul Elder" . "paul.elder@amanokami.net"))]) (org-noter . [(20240918 1703) ((emacs (24 4)) (cl-lib (0 6)) (org (9 4))) "A synchronized, Org-mode, document annotator" tar ((:url . "https://github.com/org-noter/org-noter") (:commit . "691efc3ed4a2828d791a148e53851365c2eb380f") (:revdesc . "691efc3ed4a2") (:keywords "lisp" "pdf" "interleave" "annotate" "external" "sync" "notes" "documents" "org-mode") (:authors ("Gonçalo Santos" . "in@bsentia") ("Maintainer Dmitry M" . "dmitrym@gmail.com")) (:maintainers ("Peter Mao" . "peter.mao@gmail.com") ("Dmitry M" . "dmitrym@gmail.com")) (:maintainer "Peter Mao" . "peter.mao@gmail.com"))]) (org-noter-pdftools . [(20230725 1433) ((emacs (26 1)) (org (9 4)) (pdf-tools (0 8)) (org-pdftools (1 0)) (org-noter (1 4 1))) "Integration between org-pdftools and org-noter" tar ((:url . "https://github.com/fuxialexander/org-pdftools") (:commit . "4e420233a153a9c4ab3d1a7e1d7d3211c836f0ac") (:revdesc . "4e420233a153") (:keywords "convenience") (:authors ("Alexander Fu Xi" . "fuxialexander@gmail.com")) (:maintainers ("Alexander Fu Xi" . "fuxialexnader@gmail.com")) (:maintainer "Alexander Fu Xi" . "fuxialexnader@gmail.com"))]) @@ -4032,7 +4032,7 @@ (orthodox-christian-new-calendar-holidays . [(20210830 1657) nil "Feasts (NS)" tar ((:url . "https://github.com/cmchittom/orthodox-christian-new-calendar-holidays") (:commit . "6869024ecd45eefd0ec648979c6a59d7c79770e0") (:revdesc . "6869024ecd45") (:keywords "calendar") (:authors ("Carson Chittom" . "carson@wistly.net")) (:maintainers ("Carson Chittom" . "carson@wistly.net")) (:maintainer "Carson Chittom" . "carson@wistly.net"))]) (osa . [(20200522 2103) ((emacs (25 1))) "OSA (JavaScript / AppleScript) bridge" tar ((:url . "https://github.com/atomontage/osa") (:commit . "615ca9eef4131a23d9971691fa0d0f20fe59d01b") (:revdesc . "615ca9eef413") (:keywords "extensions") (:authors ("xristos" . "xristos@sdf.org")) (:maintainers ("xristos" . "xristos@sdf.org")) (:maintainer "xristos" . "xristos@sdf.org"))]) (osa-chrome . [(20230515 237) ((emacs (25 1)) (osa (1 0))) "Google Chrome remote tab control" tar ((:url . "https://github.com/atomontage/osa-chrome") (:commit . "981c35136102eeca77d0e1a41e7c95e8486a1dce") (:revdesc . "981c35136102") (:keywords "comm") (:authors ("xristos" . "xristos@sdf.org")) (:maintainers ("xristos" . "xristos@sdf.org")) (:maintainer "xristos" . "xristos@sdf.org"))]) - (osm . [(20240929 642) ((emacs (28 1)) (compat (30))) "OpenStreetMap viewer" tar ((:url . "https://github.com/minad/osm") (:commit . "2ba02faed5d57da97c1f6e13df36091d68ddefee") (:revdesc . "2ba02faed5d5") (:keywords "network" "multimedia" "hypermedia" "mouse") (:authors ("Daniel Mendler" . "mail@daniel-mendler.de")) (:maintainers ("Daniel Mendler" . "mail@daniel-mendler.de")) (:maintainer "Daniel Mendler" . "mail@daniel-mendler.de"))]) + (osm . [(20241006 13) ((emacs (28 1)) (compat (30))) "OpenStreetMap viewer" tar ((:url . "https://github.com/minad/osm") (:commit . "e9db7161f62459d61518888bb7d4aadea15c7b1c") (:revdesc . "e9db7161f624") (:keywords "network" "multimedia" "hypermedia" "mouse") (:authors ("Daniel Mendler" . "mail@daniel-mendler.de")) (:maintainers ("Daniel Mendler" . "mail@daniel-mendler.de")) (:maintainer "Daniel Mendler" . "mail@daniel-mendler.de"))]) (osx-browse . [(20140508 2041) ((string-utils (0 3 2)) (browse-url-dwim (0 6 6))) "Web browsing helpers for OS X" tar ((:url . "https://github.com/rolandwalker/osx-browse") (:commit . "838b81625853e04919fbb56fd21f387762b2e3f5") (:revdesc . "838b81625853") (:keywords "hypermedia" "external") (:authors ("Roland Walker" . "walker@pobox.com")) (:maintainers ("Roland Walker" . "walker@pobox.com")) (:maintainer "Roland Walker" . "walker@pobox.com"))]) (osx-clipboard . [(20141012 717) nil "Use the OS X clipboard from terminal Emacs" tar ((:url . "https://github.com/joddie/osx-clipboard-mode") (:commit . "e46dd31327a3f92f77b013b4c9b1e5fdd0e5c73d") (:revdesc . "e46dd31327a3") (:authors ("Jon Oddie" . "jonxfieldatgmail.com")) (:maintainers ("Jon Oddie" . "jonxfieldatgmail.com")) (:maintainer "Jon Oddie" . "jonxfieldatgmail.com"))]) (osx-dictionary . [(20240330 942) ((cl-lib (0 5))) "Interface for OSX Dictionary.app" tar ((:url . "https://github.com/xuchunyang/osx-dictionary.el") (:commit . "6abfd6908b0dc773020466225c908000870b383b") (:revdesc . "6abfd6908b0d") (:keywords "mac" "dictionary") (:authors ("Chunyang Xu" . "mail@xuchunyang.me")) (:maintainers ("Chunyang Xu" . "mail@xuchunyang.me")) (:maintainer "Chunyang Xu" . "mail@xuchunyang.me"))]) @@ -4553,7 +4553,7 @@ (read-only-cfg . [(20210717 205) ((emacs (24 3))) "Make files read-only based on user config" tar ((:url . "https://github.com/pfchen/read-only-cfg") (:commit . "fa16d6018a5a29f26adf6007b6b76ea1b3c0bfce") (:revdesc . "fa16d6018a5a") (:keywords "tools" "convenience") (:authors ("pfchen" . "pfchen31@gmail.com")) (:maintainers ("pfchen" . "pfchen31@gmail.com")) (:maintainer "pfchen" . "pfchen31@gmail.com"))]) (readable-numbers . [(20220711 911) ((emacs (24 1))) "Visually separate long integers" tar ((:url . "https://github.com/Titan-C/cardano.el") (:commit . "a3ebdcdd91d32f044b68541a00e162396e4acb38") (:revdesc . "a3ebdcdd91d3") (:authors ("Oscar Najera" . "https://oscarnajera.com")) (:maintainers ("Oscar Najera" . "hi@oscarnajera.com")) (:maintainer "Oscar Najera" . "hi@oscarnajera.com"))]) (readline-complete . [(20150708 1437) nil "Offers completions in shell mode" tar ((:url . "https://github.com/monsanto/readline-complete.el") (:commit . "30c020c37b2741160cc37e656e13c85d826a0ebf") (:revdesc . "30c020c37b27") (:authors ("Christopher Monsanto" . "chris@monsan.to")) (:maintainers ("Christopher Monsanto" . "chris@monsan.to")) (:maintainer "Christopher Monsanto" . "chris@monsan.to"))]) - (ready-player . [(20241003 727) ((emacs (28 1))) "Open media files in ready-player major mode" tar ((:url . "https://github.com/xenodium/ready-player") (:commit . "62a44bde9744fee43c050de3e4c0cab2686cf1f9") (:revdesc . "62a44bde9744"))]) + (ready-player . [(20241004 1537) ((emacs (28 1))) "Open media files in ready-player major mode" tar ((:url . "https://github.com/xenodium/ready-player") (:commit . "4b11f29afbd146b07203af1128cab6012bda4057") (:revdesc . "4b11f29afbd1"))]) (real-auto-save . [(20200505 1537) ((emacs (24 4))) "Automatically save your buffers/files at regular intervals" tar ((:url . "https://github.com/ChillarAnand/real-auto-save") (:commit . "8e51241e5ba7b07b91d8188c14cf193017640292") (:revdesc . "8e51241e5ba7") (:authors ("Chaoji Li" . "lichaojiATgmailDOTcom") ("Anand Reddy Pandikunta" . "anand21nandaATgmailDOTcom")) (:maintainers ("Chaoji Li" . "lichaojiATgmailDOTcom") ("Anand Reddy Pandikunta" . "anand21nandaATgmailDOTcom")) (:maintainer "Chaoji Li" . "lichaojiATgmailDOTcom"))]) (realgud . [(20231113 1910) ((load-relative (1 3 1)) (loc-changes (1 2)) (test-simple (1 3 0)) (emacs (25))) "A modular front-end for interacting with external debuggers" tar ((:url . "https://github.com/realgud/realgud") (:commit . "365063ea8ce8ec6a852cb388088d84147421c3c2") (:revdesc . "365063ea8ce8") (:keywords "debugger" "gdb" "python" "perl" "go" "bash" "zsh" "bashdb" "zshdb" "remake" "trepan" "perldb" "pdb") (:authors ("Rocky Bernstein" . "rocky@gnu.org")) (:maintainers ("Rocky Bernstein" . "rocky@gnu.org")) (:maintainer "Rocky Bernstein" . "rocky@gnu.org"))]) (realgud-byebug . [(20190520 1140) ((realgud (1 4 5)) (load-relative (1 2)) (cl-lib (0 5)) (emacs (24))) "Realgud front-end to the Ruby byebug debugger" tar ((:url . "https://github.com/realgud/realgud-byebug") (:commit . "f8f20b92c6b13f75cc9797921c0e28d3def48b1c") (:revdesc . "f8f20b92c6b1"))]) @@ -4654,7 +4654,7 @@ (right-click-context . [(20210519 1713) ((emacs (24 3)) (popup (0 5)) (ordinal (0 0 1))) "Right Click Context menu" tar ((:url . "https://github.com/zonuexe/right-click-context") (:commit . "c3c9d36ffbc9fb2bc7c2c4b75291dbcdb1c5f531") (:revdesc . "c3c9d36ffbc9") (:keywords "mouse" "menu" "rightclick") (:authors ("USAMI Kenta" . "tadsan@zonu.me")) (:maintainers ("USAMI Kenta" . "tadsan@zonu.me")) (:maintainer "USAMI Kenta" . "tadsan@zonu.me"))]) (rigid-tabs . [(20230905 940) ((emacs (24 3))) "Fix TAB alignment in diff buffers" tar ((:url . "https://gitlab.com/wavexx/rigid-tabs.el") (:commit . "9553118e76fcbc1d8f0bcb960de13c7e3f07b9df") (:revdesc . "9553118e76fc") (:keywords "diff" "whitespace" "version control" "magit") (:authors ("Yuri D'Elia" . "wavexx@thregr.org")) (:maintainers ("Yuri D'Elia" . "wavexx@thregr.org")) (:maintainer "Yuri D'Elia" . "wavexx@thregr.org"))]) (rii . [(20210317 1330) ((emacs (24 3))) "Reversible input interface for multiple input" tar ((:url . "https://github.com/ROCKTAKEY/rii") (:commit . "9df603a5c63ae38ec776e27dc93d3618e2b0fabe") (:revdesc . "9df603a5c63a") (:keywords "extensions" "tools") (:authors ("ROCKTAKEY" . "rocktakey@gmail.com")) (:maintainers ("ROCKTAKEY" . "rocktakey@gmail.com")) (:maintainer "ROCKTAKEY" . "rocktakey@gmail.com"))]) - (rime . [(20240130 1427) ((emacs (26 3)) (dash (2 17 0)) (cl-lib (0 6 1)) (popup (0 5 3)) (posframe (0 1 0))) "Rime input method" tar ((:url . "https://github.com/DogLooksGood/emacs-rime") (:commit . "d8c0a99b0282d3e0aca53146789f6864181228e7") (:revdesc . "d8c0a99b0282") (:keywords "convenience" "input-method"))]) + (rime . [(20241003 1750) ((emacs (26 3)) (dash (2 17 0)) (cl-lib (0 6 1)) (popup (0 5 3)) (posframe (0 1 0))) "Rime input method" tar ((:url . "https://github.com/DogLooksGood/emacs-rime") (:commit . "e5c5ffb57088aa7ec6b82a6ca3f9499294124954") (:revdesc . "e5c5ffb57088") (:keywords "convenience" "input-method"))]) (rimero-theme . [(20180901 1348) ((emacs (24))) "Theme with a dark background suitable for UI and terminal usage" tar ((:url . "https://github.com/yveszoundi/emacs-rimero-theme") (:commit . "a2e706c2b34f749019979a133f08a2d94a1104b3") (:revdesc . "a2e706c2b34f") (:keywords "faces" "theme" "dark" "light colors") (:authors ("Yves Zoundi" . "yveszoundi@users.sf.net")) (:maintainers ("Yves Zoundi" . "yveszoundi@users.sf.net")) (:maintainer "Yves Zoundi" . "yveszoundi@users.sf.net"))]) (rinari . [(20150709 640) ((ruby-mode (1 0)) (inf-ruby (2 2 5)) (ruby-compilation (0 16)) (jump (2 0))) "Rinari Is Not A Rails IDE" tar ((:url . "https://github.com/eschulte/rinari") (:commit . "be07b0f42aefa24c5d36c441d1f3f72e64fffaa4") (:revdesc . "be07b0f42aef") (:keywords "ruby" "rails" "project" "convenience" "web"))]) (ring-mode . [(20221226 1159) ((emacs (24 3))) "A major mode for the Ring programming language" tar ((:url . "https://github.com/thechampagne/ring-mode") (:commit . "4e38dd5ca374d7d40fd1eeed1e83ef935efd387a") (:revdesc . "4e38dd5ca374") (:keywords "files" "ring"))]) @@ -5017,7 +5017,7 @@ (sparkline . [(20150101 1319) ((cl-lib (0 3))) "Make sparkline images from a list of numbers" tar ((:url . "https://github.com/woudshoo/sparkline") (:commit . "a2b5d817d272d6363b67ed8f8cc75499a19fa8d2") (:revdesc . "a2b5d817d272") (:keywords "extensions") (:authors ("Willem Rein Oudshoorn" . "woudshoo@xs4all.nl")) (:maintainers ("Willem Rein Oudshoorn" . "woudshoo@xs4all.nl")) (:maintainer "Willem Rein Oudshoorn" . "woudshoo@xs4all.nl"))]) (sparql-mode . [(20230104 1113) ((cl-lib (0 5)) (emacs (24 3))) "Edit and interactively evaluate SPARQL queries" tar ((:url . "https://github.com/ljos/sparql-mode") (:commit . "1f6196094ec6626722c6e03a13f6844c68f62703") (:revdesc . "1f6196094ec6") (:authors ("Craig Andera" . "canderaatwangderadotcom")) (:maintainers ("Bjarte Johansen" . "BjartedotJohansenatgmaildotcom")) (:maintainer "Bjarte Johansen" . "BjartedotJohansenatgmaildotcom"))]) (spatial-navigate . [(20240421 908) ((emacs (29 1))) "Directional navigation between white-space blocks" tar ((:url . "https://codeberg.org/ideasman42/emacs-spatial-navigate") (:commit . "4f85fe3ae4d240a35d3d7edd8b865612024f9dda") (:revdesc . "4f85fe3ae4d2") (:authors ("Campbell Barton" . "ideasman42@gmail.com")) (:maintainers ("Campbell Barton" . "ideasman42@gmail.com")) (:maintainer "Campbell Barton" . "ideasman42@gmail.com"))]) - (spdx . [(20240924 118) ((emacs (24 4))) "Insert SPDX license and copyright headers" tar ((:url . "https://github.com/condy0919/spdx.el") (:commit . "29607860edabefeff1b9fe058ccaea8dfe493fe9") (:revdesc . "29607860edab") (:keywords "license" "tools") (:authors ("Zhiwei Chen" . "condy0919@gmail.com")) (:maintainers ("Zhiwei Chen" . "condy0919@gmail.com")) (:maintainer "Zhiwei Chen" . "condy0919@gmail.com"))]) + (spdx . [(20241005 117) ((emacs (24 4))) "Insert SPDX license and copyright headers" tar ((:url . "https://github.com/condy0919/spdx.el") (:commit . "49dcd6e62afcb9a89618ab53b1e35b21d2794d73") (:revdesc . "49dcd6e62afc") (:keywords "license" "tools") (:authors ("Zhiwei Chen" . "condy0919@gmail.com")) (:maintainers ("Zhiwei Chen" . "condy0919@gmail.com")) (:maintainer "Zhiwei Chen" . "condy0919@gmail.com"))]) (speech-tagger . [(20170728 1829) ((cl-lib (0 5))) "Tag parts of speech using coreNLP" tar ((:url . "https://github.com/cosmicexplorer/speech-tagger") (:commit . "61955b40d4e8b09e66a3e8033e82893f81657c06") (:revdesc . "61955b40d4e8") (:keywords "speech" "tag" "nlp" "language" "corenlp" "parsing" "natural") (:authors ("Danny McClanahan" . "danieldmcclanahan@gmail.com")) (:maintainers ("Danny McClanahan" . "danieldmcclanahan@gmail.com")) (:maintainer "Danny McClanahan" . "danieldmcclanahan@gmail.com"))]) (speechd-el . [(20240513 1716) nil "Client to speech synthesizers and Braille displays" tar ((:url . "https://github.com/brailcom/speechd-el") (:commit . "ac7497e394bf7d46e0b2c27570f5507f6a50a157") (:revdesc . "ac7497e394bf") (:authors ("Milan Zamazal" . "pdm@zamazal.org")) (:maintainers ("Milan Zamazal" . "pdm@zamazal.org")) (:maintainer "Milan Zamazal" . "pdm@zamazal.org"))]) (speed-type . [(20230926 838) ((emacs (26 1)) (compat (29 1 3))) "Practice touch and speed typing" tar ((:url . "https://github.com/dakra/speed-type") (:commit . "28b8e8c1cc24511758168f30bcac18d8fb93706d") (:revdesc . "28b8e8c1cc24") (:keywords "games") (:maintainers ("Daniel Kraus" . "daniel@kraus.my")) (:maintainer "Daniel Kraus" . "daniel@kraus.my"))]) @@ -5192,7 +5192,7 @@ (tangotango-theme . [(20220714 2034) nil "Tango Palette color theme for Emacs 24" tar ((:url . "https://github.com/juba/color-theme-tangotango") (:commit . "9036c4978965149ae9837bc0ad691b2ba9269052") (:revdesc . "9036c4978965") (:keywords "tango" "palette" "color" "theme" "emacs") (:authors ("Julien Barnier" . "julien@nozav.org")) (:maintainers ("Julien Barnier" . "julien@nozav.org")) (:maintainer "Julien Barnier" . "julien@nozav.org"))]) (tao-theme . [(20240615 517) nil "This package provides two parametrized uncoloured color themes for Emacs: tao-yin and tao-yang" tar ((:url . "https://github.com/11111000000/tao-theme-emacs") (:commit . "cd8ac4aee9fff55bc092ce78d93bd40517fa2c2a") (:revdesc . "cd8ac4aee9ff") (:authors ("Peter Kosov" . "11111000000@email.com")) (:maintainers ("Peter Kosov" . "11111000000@email.com")) (:maintainer "Peter Kosov" . "11111000000@email.com"))]) (tardis-theme . [(20230212 2152) ((emacs (25 1))) "Quantum Country Theme" tar ((:url . "https://github.com/antonhibl/tardis-theme") (:commit . "352b1579d13e99cff9367b08208c1e241d76c89e") (:revdesc . "352b1579d13e") (:keywords "convenience") (:authors ("Anton Hibl" . "antonhibl11@gmail.com")) (:maintainers ("Anton Hibl" . "antonhibl11@gmail.com")) (:maintainer "Anton Hibl" . "antonhibl11@gmail.com"))]) - (taskpaper-mode . [(20241002 1219) ((emacs (25 1))) "Major mode for working with TaskPaper files" tar ((:url . "https://github.com/saf-dmitry/taskpaper-mode") (:commit . "e3f3ee512d44caacd4a6c4be9d081b014119e774") (:revdesc . "e3f3ee512d44") (:keywords "outlines" "notetaking" "task management" "productivity" "taskpaper") (:authors ("Dmitry Safronov" . "saf.dmitry@gmail.com")) (:maintainers ("Dmitry Safronov" . "saf.dmitry@gmail.com")) (:maintainer "Dmitry Safronov" . "saf.dmitry@gmail.com"))]) + (taskpaper-mode . [(20241006 1447) ((emacs (25 1))) "Major mode for working with TaskPaper files" tar ((:url . "https://github.com/saf-dmitry/taskpaper-mode") (:commit . "90aac56a6dc078f788dddeaa5a5f2cfa3620aaff") (:revdesc . "90aac56a6dc0") (:keywords "outlines" "notetaking" "task management" "productivity" "taskpaper") (:authors ("Dmitry Safronov" . "saf.dmitry@gmail.com")) (:maintainers ("Dmitry Safronov" . "saf.dmitry@gmail.com")) (:maintainer "Dmitry Safronov" . "saf.dmitry@gmail.com"))]) (taskrunner . [(20190916 1608) ((emacs (25 1)) (projectile (2 0 0)) (async (1 9 3))) "Retrieve build system/taskrunner tasks" tar ((:url . "https://github.com/emacs-taskrunner/emacs-taskrunner") (:commit . "716323aff410b4d864d137c9ebe4bbb5b8587f5e") (:revdesc . "716323aff410") (:keywords "build-system" "taskrunner" "build" "task-runner" "tasks" "convenience") (:authors ("Yavor Konstantinov" . "ykonstantinov1ATgmailDOTcom")) (:maintainers ("Yavor Konstantinov" . "ykonstantinov1ATgmailDOTcom")) (:maintainer "Yavor Konstantinov" . "ykonstantinov1ATgmailDOTcom"))]) (tawny-mode . [(20231117 1644) ((cider (0 12)) (emacs (25))) "Ontology Editing with Tawny-OWL" tar ((:url . "https://github.com/phillord/tawny-owl") (:commit . "b2708d693400a2010370df040d7571bc30fa4d75") (:revdesc . "b2708d693400") (:authors ("Phillip Lord" . "phillip.lord@newcastle.ac.uk")) (:maintainers ("Phillip Lord" . "phillip.lord@newcastle.ac.uk")) (:maintainer "Phillip Lord" . "phillip.lord@newcastle.ac.uk"))]) (tblui . [(20231201 1100) ((dash (2 12 1)) (magit-popup (2 6 0)) (tablist (0 70)) (cl-lib (0 5))) "Define tabulated list UI easily" tar ((:url . "https://github.com/Yuki-Inoue/tblui.el") (:commit . "62ab5f62982c061a902fd3e54d94a68a4706572c") (:revdesc . "62ab5f62982c") (:authors ("Yuki Inoue" . "inouetakahiroki_at_gmail.com")) (:maintainers ("Yuki Inoue" . "inouetakahiroki_at_gmail.com")) (:maintainer "Yuki Inoue" . "inouetakahiroki_at_gmail.com"))]) @@ -5332,7 +5332,7 @@ (tramp-term . [(20220725 1441) nil "Automatic setup of directory tracking in ssh sessions" tar ((:url . "https://github.com/cuspymd/tramp-term.el") (:commit . "ed75189122737d301f716a30a8013205aa3736f1") (:revdesc . "ed7518912273") (:keywords "comm" "terminals") (:authors ("Randy Morris" . "randy.morris@archlinux.us")) (:maintainers ("Randy Morris" . "randy.morris@archlinux.us")) (:maintainer "Randy Morris" . "randy.morris@archlinux.us"))]) (transducers . [(20240308 843) ((emacs (28 1))) "Ergonomic, efficient data processing" tar ((:url . "https://github.com/fosskers/transducers.el") (:commit . "2d452e4cdc3b5cfa29ee3d7a645ff53d4e993384") (:revdesc . "2d452e4cdc3b") (:keywords "lisp") (:authors ("Colin Woodbury" . "colin@fosskers.ca")) (:maintainers ("Colin Woodbury" . "colin@fosskers.ca")) (:maintainer "Colin Woodbury" . "colin@fosskers.ca"))]) (transfer-sh . [(20200601 1708) ((emacs (24 3)) (async (1 0))) "Simple interface for sending buffer contents to transfer.sh" tar ((:url . "https://gitlab.com/tuedachu/transfer-sh.el") (:commit . "0621a66d00ec91a209a542c10b158095088bd44d") (:revdesc . "0621a66d00ec") (:keywords "comm" "convenience" "files"))]) - (transient . [(20241001 1031) ((emacs (26 1)) (compat (30 0 0 0)) (seq (2 24))) "Transient commands" tar ((:url . "https://github.com/magit/transient") (:commit . "c06015cd6750f8625081f4184c68c94350eb0217") (:revdesc . "c06015cd6750") (:keywords "extensions") (:authors ("Jonas Bernoulli" . "emacs.transient@jonas.bernoulli.dev")) (:maintainers ("Jonas Bernoulli" . "emacs.transient@jonas.bernoulli.dev")) (:maintainer "Jonas Bernoulli" . "emacs.transient@jonas.bernoulli.dev"))]) + (transient . [(20241004 1739) ((emacs (26 1)) (compat (30 0 0 0)) (seq (2 24))) "Transient commands" tar ((:url . "https://github.com/magit/transient") (:commit . "fc03c0b75826aa771b682137aa3f4e24130a9e3c") (:revdesc . "fc03c0b75826") (:keywords "extensions") (:authors ("Jonas Bernoulli" . "emacs.transient@jonas.bernoulli.dev")) (:maintainers ("Jonas Bernoulli" . "emacs.transient@jonas.bernoulli.dev")) (:maintainer "Jonas Bernoulli" . "emacs.transient@jonas.bernoulli.dev"))]) (transient-dwim . [(20221225 1630) ((emacs (26 1)) (transient (0 1))) "Useful preset transient commands" tar ((:url . "https://github.com/conao3/transient-dwim.el") (:commit . "cb5e0d35729fc6448553b7a17fc5c843f00e8c1d") (:revdesc . "cb5e0d35729f") (:keywords "tools") (:authors ("Naoya Yamashita" . "conao3@gmail.com")) (:maintainers ("Naoya Yamashita" . "conao3@gmail.com")) (:maintainer "Naoya Yamashita" . "conao3@gmail.com"))]) (transient-extras . [(20230721 839) ((emacs (28 1))) "Extra features for transient" tar ((:url . "https://github.com/haji-ali/transient-extras") (:commit . "ca0d5c597382615f0ee8300ff8718f54f8214359") (:revdesc . "ca0d5c597382") (:keywords "convenience") (:authors ("Al Haji-Ali" . "abdo.haji.ali@gmail.com") ("Samuel W. Flint" . "swflint@flintfam.org")) (:maintainers ("Al Haji-Ali" . "abdo.haji.ali@gmail.com") ("Samuel W. Flint" . "swflint@flintfam.org")) (:maintainer "Al Haji-Ali" . "abdo.haji.ali@gmail.com"))]) (transient-extras-a2ps . [(20230303 1511) ((emacs (28 1)) (transient-extras (1 0 0))) "A transient interface to a2ps" tar ((:url . "https://github.com/haji-ali/transient-extras") (:commit . "e91a1cddb1f0cb8b99d2bd30db64d467e5fa7ea8") (:revdesc . "e91a1cddb1f0") (:keywords "convenience") (:authors ("Samuel W. Flint" . "swflint@flintfam.org")) (:maintainers ("Samuel W. Flint" . "swflint@flintfam.org")) (:maintainer "Samuel W. Flint" . "swflint@flintfam.org"))]) @@ -5352,7 +5352,7 @@ (tree-sitter-ess-r . [(20221012 855) ((emacs (26 1)) (ess (18 10 1)) (tree-sitter (0 12 1)) (tree-sitter-langs (0 12 0))) "R with tree-sitter" tar ((:url . "https://github.com/ShuguangSun/tree-sitter-ess-r") (:commit . "9669c00f3d3463e6769725af74c392891e269eed") (:revdesc . "9669c00f3d34") (:keywords "tools") (:authors ("Shuguang Sun" . "shuguang79@qq.com")) (:maintainers ("Shuguang Sun" . "shuguang79@qq.com")) (:maintainer "Shuguang Sun" . "shuguang79@qq.com"))]) (tree-sitter-indent . [(20220411 1439) ((emacs (26 1)) (tree-sitter (0 12 1)) (seq (2 20))) "Provide indentation with a Tree-sitter backend" tar ((:url . "https://codeberg.org/FelipeLema/tree-sitter-indent.el") (:commit . "4ef246db3e4ff99f672fe5e4b416c890f885c09e") (:revdesc . "4ef246db3e4f") (:keywords "convenience" "internal") (:authors ("Felipe Lema" . "felipelema@mortemale.org")) (:maintainers ("Felipe Lema" . "felipelema@mortemale.org")) (:maintainer "Felipe Lema" . "felipelema@mortemale.org"))]) (tree-sitter-ispell . [(20240610 2252) ((emacs (26 1)) (tree-sitter (0 15 0))) "Run ispell on tree-sitter text nodes" tar ((:url . "https://github.com/erickgnavar/tree-sitter-ispell.el") (:commit . "a06eff00affff85992d2a8ad0019034747ffeb70") (:revdesc . "a06eff00afff") (:authors ("Erick Navarro" . "erick@navarro.io")) (:maintainers ("Erick Navarro" . "erick@navarro.io")) (:maintainer "Erick Navarro" . "erick@navarro.io"))]) - (tree-sitter-langs . [(20241002 346) ((emacs (25 1)) (tree-sitter (0 15 0))) "Grammar bundle for tree-sitter" tar ((:url . "https://github.com/emacs-tree-sitter/tree-sitter-langs") (:commit . "c1b972988706bdc7159bca5239239cf44ea54927") (:revdesc . "c1b972988706") (:keywords "languages" "tools" "parsers" "tree-sitter") (:authors ("Tuấn-Anh Nguyễn" . "ubolonton@gmail.com")) (:maintainers ("Tuấn-Anh Nguyễn" . "ubolonton@gmail.com")) (:maintainer "Tuấn-Anh Nguyễn" . "ubolonton@gmail.com"))]) + (tree-sitter-langs . [(20241006 953) ((emacs (25 1)) (tree-sitter (0 15 0))) "Grammar bundle for tree-sitter" tar ((:url . "https://github.com/emacs-tree-sitter/tree-sitter-langs") (:commit . "62e169d3122658761581105c91d8a6aad103fed5") (:revdesc . "62e169d31226") (:keywords "languages" "tools" "parsers" "tree-sitter") (:authors ("Tuấn-Anh Nguyễn" . "ubolonton@gmail.com")) (:maintainers ("Tuấn-Anh Nguyễn" . "ubolonton@gmail.com")) (:maintainer "Tuấn-Anh Nguyễn" . "ubolonton@gmail.com"))]) (treebundel . [(20240531 2321) ((emacs (27 1)) (compat (29 1 4 2))) "Bundle related git-worktrees together" tar ((:url . "https://github.com/purplg/treebundel") (:commit . "b0a5d1bf924d8cadde5bae50b8d9ac131279b828") (:revdesc . "b0a5d1bf924d") (:keywords "convenience" "vc"))]) (treefactor . [(20200516 1631) ((emacs (26 1)) (dash (2 16 0)) (f (0 20 0)) (org (9 2 6)) (avy (0 5 0))) "Restructure your messy Org documents" tar ((:url . "https://github.com/cyberthal/treefactor") (:commit . "75357757022a4399ab772ff0d92065bd114dabe9") (:revdesc . "75357757022a") (:keywords "outlines" "files" "convenience") (:authors ("Leo Littlebook" . "Leo.Littlebook@gmail.com")) (:maintainers ("Leo Littlebook" . "Leo.Littlebook@gmail.com")) (:maintainer "Leo Littlebook" . "Leo.Littlebook@gmail.com"))]) (treemacs . [(20240815 1227) ((emacs (26 1)) (cl-lib (0 5)) (dash (2 11 0)) (s (1 12 0)) (ace-window (0 9 0)) (pfuture (1 7)) (hydra (0 13 2)) (ht (2 2)) (cfrs (1 3 2))) "A tree style file explorer package" tar ((:url . "https://github.com/Alexander-Miller/treemacs") (:commit . "488dfc0a3aa7c1d35802d4f89be058e761578663") (:revdesc . "488dfc0a3aa7") (:authors ("Alexander Miller" . "alexanderm@web.de")) (:maintainers ("Alexander Miller" . "alexanderm@web.de")) (:maintainer "Alexander Miller" . "alexanderm@web.de"))]) @@ -5516,7 +5516,7 @@ (versuri . [(20211104 1301) ((emacs (26 1)) (dash (2 16 0)) (request (0 3 0)) (anaphora (1 0 4)) (esxml (0 1 0)) (s (1 12 0)) (esqlite (0 3 1))) "The lyrics package" tar ((:url . "https://github.com/mihaiolteanu/versuri") (:commit . "c8ea562304194f3379ed8f9c6a785ce8ee72898e") (:revdesc . "c8ea56230419") (:keywords "multimedia") (:authors ("Mihai Olteanu" . "mihai_olteanu@fastmail.fm")) (:maintainers ("Mihai Olteanu" . "mihai_olteanu@fastmail.fm")) (:maintainer "Mihai Olteanu" . "mihai_olteanu@fastmail.fm"))]) (vertica . [(20131217 1511) ((sql (3 0))) "Vertica SQL mode extension" tar ((:url . "https://github.com/r0man/vertica-el") (:commit . "3c9647b425c5c13c30bf0cba483646af18196588") (:revdesc . "3c9647b425c5") (:keywords "sql" "vertica") (:authors ("Roman Scherer" . "roman@burningswell.com")) (:maintainers ("Roman Scherer" . "roman@burningswell.com")) (:maintainer "Roman Scherer" . "roman@burningswell.com"))]) (vertica-snippets . [(20240917 1129) ((yasnippet (0 6 1))) "Yasnippets for Vertica" tar ((:url . "https://github.com/baron42bba/vertica-snippets") (:commit . "1b6f234c81aaf1b0f0e445d1ad91a7580a4c8630") (:revdesc . "1b6f234c81aa") (:keywords "convenience" "snippets") (:authors ("Andreas Gerler" . "baron@bundesbrandschatzamt.de")) (:maintainers ("Andreas Gerler" . "baron@bundesbrandschatzamt.de")) (:maintainer "Andreas Gerler" . "baron@bundesbrandschatzamt.de"))]) - (vertico . [(20240926 924) ((emacs (28 1)) (compat (30))) "VERTical Interactive COmpletion" tar ((:url . "https://github.com/minad/vertico") (:commit . "7741da042ddf4102d2f87a8110028363f36bc9e8") (:revdesc . "7741da042ddf") (:keywords "convenience" "files" "matching" "completion") (:authors ("Daniel Mendler" . "mail@daniel-mendler.de")) (:maintainers ("Daniel Mendler" . "mail@daniel-mendler.de")) (:maintainer "Daniel Mendler" . "mail@daniel-mendler.de"))]) + (vertico . [(20241004 1350) ((emacs (28 1)) (compat (30))) "VERTical Interactive COmpletion" tar ((:url . "https://github.com/minad/vertico") (:commit . "e826dfcb14af5e2cfd88ed110d0208ddc2d37788") (:revdesc . "e826dfcb14af") (:keywords "convenience" "files" "matching" "completion") (:authors ("Daniel Mendler" . "mail@daniel-mendler.de")) (:maintainers ("Daniel Mendler" . "mail@daniel-mendler.de")) (:maintainer "Daniel Mendler" . "mail@daniel-mendler.de"))]) (vertico-prescient . [(20240803 2320) ((emacs (27 1)) (prescient (6 1 0)) (vertico (0 28)) (compat (29 1))) "Prescient.el + Vertico" tar ((:url . "https://github.com/radian-software/prescient.el") (:commit . "2b8a8b41228bddb2e11eb1c200e98a9edd04797c") (:revdesc . "2b8a8b41228b") (:keywords "extensions") (:authors ("Radian LLC" . "contact+prescient@radian.codes")) (:maintainers ("Radian LLC" . "contact+prescient@radian.codes")) (:maintainer "Radian LLC" . "contact+prescient@radian.codes"))]) (vertigo . [(20211224 1256) ((dash (2 11 0))) "Jump across lines using the home row" tar ((:url . "https://github.com/noctuid/vertigo.el") (:commit . "280b30518529242ee36cd436bd2349c34c35abb0") (:revdesc . "280b30518529") (:keywords "vim" "vertigo") (:authors ("Fox Kiester" . "noct@posteo.net")) (:maintainers ("Fox Kiester" . "noct@posteo.net")) (:maintainer "Fox Kiester" . "noct@posteo.net"))]) (vhdl-capf . [(20160221 1734) nil "Completion at point function (capf) for vhdl-mode" tar ((:url . "https://github.com/sh-ow/vhdl-capf") (:commit . "290abe217050f33532bc9ccb04f894123402f414") (:revdesc . "290abe217050") (:keywords "convenience" "usability" "vhdl" "completion") (:authors ("sh-ow" . "sh-ow@users.noreply.github.com")) (:maintainers ("sh-ow" . "sh-ow@users.noreply.github.com")) (:maintainer "sh-ow" . "sh-ow@users.noreply.github.com"))]) @@ -5801,8 +5801,8 @@ (zim-wiki-mode . [(20240613 8) ((emacs (25 1)) (helm-ag (0 58)) (helm-projectile (0 14 0)) (dokuwiki-mode (0 1 1)) (link-hint (0 1)) (pretty-hydra (0 2 2))) "Zim Desktop Wiki edit mode" tar ((:url . "https://github.com/WillForan/zim-wiki-mode") (:commit . "11e077afbe21f2dd33fe7eae39c2a8345bb0b806") (:revdesc . "11e077afbe21") (:keywords "outlines") (:authors ("Will Foran" . "willforan+zim-wiki-mode@gmail.com")) (:maintainers ("Will Foran" . "willforan+zim-wiki-mode@gmail.com")) (:maintainer "Will Foran" . "willforan+zim-wiki-mode@gmail.com"))]) (zimports . [(20211011 2059) ((emacs (26 1)) (projectile (2 1 0))) "Reformat python imports with zimports" tar ((:url . "https://github.com/schmir/zimports.el") (:commit . "76cf76bdc871cb0454a6fc555aeb1aa94f1b6e57") (:revdesc . "76cf76bdc871"))]) (zk . [(20240926 1826) ((emacs (25 1))) "Functions for working with Zettelkasten-style linked notes" tar ((:url . "https://github.com/localauthor/zk") (:commit . "8e361577b8cf01f20a65222ca4ce90720a3d74a6") (:revdesc . "8e361577b8cf") (:authors ("Grant Rosson" . "https://github.com/localauthor")) (:maintainers ("Grant Rosson" . "https://github.com/localauthor")) (:maintainer "Grant Rosson" . "https://github.com/localauthor"))]) - (zk-desktop . [(20240926 1826) ((emacs (27 1)) (zk (0 6)) (zk-index (0 9))) "Desktop environment for zk" tar ((:url . "https://github.com/localauthor/zk") (:commit . "8e361577b8cf01f20a65222ca4ce90720a3d74a6") (:revdesc . "8e361577b8cf") (:authors ("Grant Rosson" . "https://github.com/localauthor")) (:maintainers ("Grant Rosson" . "https://github.com/localauthor")) (:maintainer "Grant Rosson" . "https://github.com/localauthor"))]) - (zk-index . [(20240926 1826) ((emacs (27 1)) (zk (0 7))) "Index for zk" tar ((:url . "https://github.com/localauthor/zk") (:commit . "8e361577b8cf01f20a65222ca4ce90720a3d74a6") (:revdesc . "8e361577b8cf") (:authors ("Grant Rosson" . "https://github.com/localauthor")) (:maintainers ("Grant Rosson" . "https://github.com/localauthor")) (:maintainer "Grant Rosson" . "https://github.com/localauthor"))]) + (zk-desktop . [(20241006 1334) ((emacs (27 1)) (zk (0 6)) (zk-index (0 9))) "Desktop environment for zk" tar ((:url . "https://github.com/localauthor/zk") (:commit . "297ebd0df13c957f4ba9700cafc5466dafacc5cb") (:revdesc . "297ebd0df13c") (:authors ("Grant Rosson" . "https://github.com/localauthor")) (:maintainers ("Grant Rosson" . "https://github.com/localauthor")) (:maintainer "Grant Rosson" . "https://github.com/localauthor"))]) + (zk-index . [(20241006 1334) ((emacs (27 1)) (zk (0 7))) "Index for zk" tar ((:url . "https://github.com/localauthor/zk") (:commit . "297ebd0df13c957f4ba9700cafc5466dafacc5cb") (:revdesc . "297ebd0df13c") (:authors ("Grant Rosson" . "https://github.com/localauthor")) (:maintainers ("Grant Rosson" . "https://github.com/localauthor")) (:maintainer "Grant Rosson" . "https://github.com/localauthor"))]) (zk-luhmann . [(20240926 1827) ((emacs (25 1)) (zk (0 7)) (zk-index (0 10))) "Support for Luhmann-style IDs in zk" tar ((:url . "https://github.com/localauthor/zk-luhmann") (:commit . "fef5cace6ac12a86ba9a8d4abc80e87699966f8c") (:revdesc . "fef5cace6ac1") (:authors ("Grant Rosson" . "https://github.com/localauthor")) (:maintainers ("Grant Rosson" . "https://github.com/localauthor")) (:maintainer "Grant Rosson" . "https://github.com/localauthor"))]) (zlc . [(20151011 157) nil "Provides zsh like completion system to Emacs" tar ((:url . "https://github.com/mooz/emacs-zlc") (:commit . "4dd2ba267ecdeac845a7cbb3147294ee7daa25f4") (:revdesc . "4dd2ba267ecd") (:keywords "matching" "convenience") (:authors ("mooz" . "stillpedant@gmail.com")) (:maintainers ("mooz" . "stillpedant@gmail.com")) (:maintainer "mooz" . "stillpedant@gmail.com"))]) (zmq . [(20240716 2000) ((cl-lib (0 5)) (emacs (26))) "ZMQ bindings in Emacs-Lisp" tar ((:url . "https://github.com/nnicandro/emacs-zmq") (:commit . "1d9d5a3b46cfd1a90a45ff777f200eb4d5d6fd9e") (:revdesc . "1d9d5a3b46cf") (:keywords "comm") (:authors ("Nathaniel Nicandro" . "nathanielnicandro@gmail.com")) (:maintainers ("Nathaniel Nicandro" . "nathanielnicandro@gmail.com")) (:maintainer "Nathaniel Nicandro" . "nathanielnicandro@gmail.com"))]) @@ -5822,7 +5822,7 @@ (zotra . [(20231014 2139) ((emacs (27 1))) "Import bibliographic data from (almost) everywhere" tar ((:url . "https://github.com/mpedramfar/zotra") (:commit . "fe9093b226a1678fc6c2fadd31a09d5a22ecdcf1") (:revdesc . "fe9093b226a1") (:authors ("Mohammad Pedramfar" . "https://github.com/mpedramfar")) (:maintainers ("Mohammad Pedramfar" . "https://github.com/mpedramfar")) (:maintainer "Mohammad Pedramfar" . "https://github.com/mpedramfar"))]) (zotxt . [(20240203 647) ((request (0 3 2)) (deferred (0 5 1))) "Tools to integrate emacs with Zotero via the zotxt plugin" tar ((:url . "https://gitlab.com/egh/zotxt-emacs") (:commit . "7eae5196dbe6fa3045b31412538ce4a81204abc4") (:revdesc . "7eae5196dbe6") (:keywords "bib") (:authors ("Erik Hetzner" . "egh@e6h.org")) (:maintainers ("Erik Hetzner" . "egh@e6h.org")) (:maintainer "Erik Hetzner" . "egh@e6h.org"))]) (zoutline . [(20220102 835) nil "Simple outline library" tar ((:url . "https://github.com/abo-abo/zoutline") (:commit . "32857c6c4b9b0bcbed14d825a10b91a98d5fed0a") (:revdesc . "32857c6c4b9b") (:keywords "outline") (:authors ("Oleh Krehel" . "ohwoeowho@gmail.com")) (:maintainers ("Oleh Krehel" . "ohwoeowho@gmail.com")) (:maintainer "Oleh Krehel" . "ohwoeowho@gmail.com"))]) - (zoxide . [(20230912 2359) ((emacs (25 1))) "Find file by zoxide" tar ((:url . "https://git.sr.ht/~vonfry/zoxide.el") (:commit . "c4b72681b139f40ba82f43d9c93adbd37da7b238") (:revdesc . "c4b72681b139") (:keywords "converience" "matching") (:authors ("Ruoyu Feng" . "emacs@vonfry.name")) (:maintainers ("Ruoyu Feng" . "emacs@vonfry.name")) (:maintainer "Ruoyu Feng" . "emacs@vonfry.name"))]) + (zoxide . [(20241003 1103) ((emacs (25 1))) "Find file by zoxide" tar ((:url . "https://git.sr.ht/~vonfry/zoxide.el") (:commit . "6de851de46db51253350edd67f329dbc0587b97c") (:revdesc . "6de851de46db") (:keywords "converience" "matching") (:authors ("Ruoyu Feng" . "emacs@vonfry.name")) (:maintainers ("Ruoyu Feng" . "emacs@vonfry.name")) (:maintainer "Ruoyu Feng" . "emacs@vonfry.name"))]) (zpl-mode . [(20180906 1059) ((emacs (24 3))) "ZIMPL major mode" tar ((:url . "https://github.com/ax487/zpl-mode") (:commit . "35e7e23c6baf31b5e65dd7405c8ab9b13c70637e") (:revdesc . "35e7e23c6baf"))]) (zpresent . [(20201207 732) ((emacs (25 1)) (org-parser (0 4)) (dash (2 12 0)) (request (0 3 0))) "Simple presentation mode based on org files" tar ((:url . "https://hg.sr.ht/~zck/zpresent") (:commit . "341d1a4a91a8acff5be6b81f95695e17c79c5309") (:revdesc . "341d1a4a91a8acff5be6b81f95695e17c79c5309") (:keywords "comm"))]) (zprint-format . [(20210602 146) ((emacs (24)) (reformatter (0 3))) "Reformat Clojure code using zprint" tar ((:url . "https://github.com/dpassen/zprint-format") (:commit . "fa575c17a40033189f2f23f1a5b27b88c399d200") (:revdesc . "fa575c17a400") (:keywords "clojure" "zprint" "tools" "languages") (:authors ("Derek Passen" . "dpassen1@gmail.com")) (:maintainers ("Derek Passen" . "dpassen1@gmail.com")) (:maintainer "Derek Passen" . "dpassen1@gmail.com"))]) diff --git a/emacs/elpa/archives/nongnu/archive-contents b/emacs/elpa/archives/nongnu/archive-contents @@ -1032,7 +1032,7 @@ ("Jonas Bernoulli" . "emacs.git-modes@jonas.bernoulli.dev")) (:commit . "f99010bbeb8b6d8a0819fac0195a2ef0159d08f0"))]) (gnosis . - [(0 4 3) + [(0 4 4) ((emacs (27 2)) (emacsql @@ -1047,7 +1047,7 @@ (:maintainer "Thanos Apollo" . "public@thanosapollo.org") (:authors ("Thanos Apollo" . "public@thanosapollo.org")) - (:commit . "40f63788afdb74fa71177abd882e852177829881"))]) + (:commit . "fd1315830e3aedf5d7cedc8410ec4f4bc2b781f0"))]) (gnu-apl-mode . [(1 5 1) nil "Emacs mode for GNU APL" tar diff --git a/emacs/elpa/archives/nongnu/archive-contents.signed b/emacs/elpa/archives/nongnu/archive-contents.signed @@ -1 +1 @@ -Good signature from 645357D2883A0966 GNU ELPA Signing Agent (2023) <elpasign@elpa.gnu.org> (trust undefined) created at 2024-10-03T09:05:04+0000 using EDDSA -\ No newline at end of file +Good signature from 645357D2883A0966 GNU ELPA Signing Agent (2023) <elpasign@elpa.gnu.org> (trust undefined) created at 2024-10-06T09:05:08+0000 using EDDSA +\ No newline at end of file diff --git a/emacs/elpa/cape-20240926.918/cape-autoloads.el b/emacs/elpa/cape-20240926.918/cape-autoloads.el @@ -1,238 +0,0 @@ -;;; cape-autoloads.el --- automatically extracted autoloads (do not edit) -*- lexical-binding: t -*- -;; Generated by the `loaddefs-generate' function. - -;; This file is part of GNU Emacs. - -;;; Code: - -(add-to-list 'load-path (or (and load-file-name (directory-file-name (file-name-directory load-file-name))) (car load-path))) - - - -;;; Generated autoloads from cape.el - -(autoload 'cape-history "cape" "\ -Complete from Eshell, Comint or minibuffer history. -See also `consult-history' for a more flexible variant based on -`completing-read'. If INTERACTIVE is nil the function acts like a Capf. - -(fn &optional INTERACTIVE)" t) -(autoload 'cape-file "cape" "\ -Complete file name at point. -See the user option `cape-file-directory-must-exist'. -If INTERACTIVE is nil the function acts like a Capf. - -(fn &optional INTERACTIVE)" t) -(autoload 'cape-elisp-symbol "cape" "\ -Complete Elisp symbol at point. -If INTERACTIVE is nil the function acts like a Capf. - -(fn &optional INTERACTIVE)" t) -(autoload 'cape-elisp-block "cape" "\ -Complete Elisp in Org or Markdown code block. -This Capf is particularly useful for literate Emacs configurations. -If INTERACTIVE is nil the function acts like a Capf. - -(fn &optional INTERACTIVE)" t) -(autoload 'cape-dabbrev "cape" "\ -Complete with Dabbrev at point. - -If INTERACTIVE is nil the function acts like a Capf. In case you -observe a performance issue with auto-completion and `cape-dabbrev' -it is strongly recommended to disable scanning in other buffers. -See the user options `cape-dabbrev-min-length' and -`cape-dabbrev-check-other-buffers'. - -(fn &optional INTERACTIVE)" t) -(autoload 'cape-dict "cape" "\ -Complete word from dictionary at point. -This completion function works best if the dictionary is sorted -by frequency. See the custom option `cape-dict-file'. If -INTERACTIVE is nil the function acts like a Capf. - -(fn &optional INTERACTIVE)" t) -(autoload 'cape-abbrev "cape" "\ -Complete abbreviation at point. -If INTERACTIVE is nil the function acts like a Capf. - -(fn &optional INTERACTIVE)" t) -(autoload 'cape-line "cape" "\ -Complete current line from other lines. -The buffers returned by `cape-line-buffer-function' are scanned for lines. -If INTERACTIVE is nil the function acts like a Capf. - -(fn &optional INTERACTIVE)" t) -(autoload 'cape-company-to-capf "cape" "\ -Convert Company BACKEND function to Capf. -VALID is a function taking the old and new input string. It should -return nil if the cached candidates became invalid. The default value -for VALID is `string-prefix-p' such that the candidates are only fetched -again if the input prefix changed. - -(fn BACKEND &optional VALID)") -(autoload 'cape-interactive "cape" "\ -Complete interactively with the given CAPFS. - -(fn &rest CAPFS)") -(autoload 'cape-capf-interactive "cape" "\ -Create interactive completion function from CAPF. - -(fn CAPF)") -(autoload 'cape-wrap-super "cape" "\ -Call CAPFS and return merged completion result. -The CAPFS list can contain the keyword `:with' to mark the Capfs -afterwards as auxiliary One of the non-auxiliary Capfs before -`:with' must return non-nil for the super Capf to set in and -return a non-nil result. Such behavior is useful when listing -multiple super Capfs in the `completion-at-point-functions': - - (setq completion-at-point-functions - (list (cape-capf-super \\='eglot-completion-at-point - :with \\='tempel-complete) - (cape-capf-super \\='cape-dabbrev - :with \\='tempel-complete))) - -(fn &rest CAPFS)") -(autoload 'cape-wrap-debug "cape" "\ -Call CAPF and return a completion table which prints trace messages. -If CAPF is an anonymous lambda, pass the Capf NAME explicitly for -meaningful debugging output. - -(fn CAPF &optional NAME)") -(autoload 'cape-wrap-buster "cape" "\ -Call CAPF and return a completion table with cache busting. -This function can be used as an advice around an existing Capf. -The cache is busted when the input changes. The argument VALID -can be a function taking the old and new input string. It should -return nil if the new input requires that the completion table is -refreshed. The default value for VALID is `equal', such that the -completion table is refreshed on every input change. - -(fn CAPF &optional VALID)") -(autoload 'cape-wrap-passthrough "cape" "\ -Call CAPF and make sure that no completion style filtering takes place. - -(fn CAPF)") -(autoload 'cape-wrap-properties "cape" "\ -Call CAPF and add additional completion PROPERTIES. -Completion properties include for example :exclusive, :annotation-function and -the various :company-* extensions. Furthermore a boolean :sort flag and a -completion :category symbol can be specified. - -(fn CAPF &rest PROPERTIES)") -(autoload 'cape-wrap-nonexclusive "cape" "\ -Call CAPF and ensure that it is marked as non-exclusive. -This function can be used as an advice around an existing Capf. - -(fn CAPF)") -(autoload 'cape-wrap-predicate "cape" "\ -Call CAPF and add an additional candidate PREDICATE. -The PREDICATE is passed the candidate symbol or string. - -(fn CAPF PREDICATE)") -(autoload 'cape-wrap-silent "cape" "\ -Call CAPF and silence it (no messages, no errors). -This function can be used as an advice around an existing Capf. - -(fn CAPF)") -(autoload 'cape-wrap-case-fold "cape" "\ -Call CAPF and return a case-insensitive completion table. -If NOFOLD is non-nil return a case sensitive table instead. This -function can be used as an advice around an existing Capf. - -(fn CAPF &optional NOFOLD)") -(autoload 'cape-wrap-noninterruptible "cape" "\ -Call CAPF and return a non-interruptible completion table. -This function can be used as an advice around an existing Capf. - -(fn CAPF)") -(autoload 'cape-wrap-prefix-length "cape" "\ -Call CAPF and ensure that prefix length is greater or equal than LENGTH. -If the prefix is long enough, enforce auto completion. - -(fn CAPF LENGTH)") -(autoload 'cape-wrap-inside-faces "cape" "\ -Call CAPF only if inside FACES. -This function can be used as an advice around an existing Capf. - -(fn CAPF &rest FACES)") -(autoload 'cape-wrap-inside-code "cape" "\ -Call CAPF only if inside code, not inside a comment or string. -This function can be used as an advice around an existing Capf. - -(fn CAPF)") -(autoload 'cape-wrap-inside-comment "cape" "\ -Call CAPF only if inside comment. -This function can be used as an advice around an existing Capf. - -(fn CAPF)") -(autoload 'cape-wrap-inside-string "cape" "\ -Call CAPF only if inside string. -This function can be used as an advice around an existing Capf. - -(fn CAPF)") -(autoload 'cape-wrap-purify "cape" "\ -Call CAPF and ensure that it does not illegally modify the buffer. -This function can be used as an advice around an existing -Capf. It has been introduced mainly to fix the broken -`pcomplete-completions-at-point' function in Emacs versions < 29. - -(fn CAPF)") -(autoload 'cape-wrap-accept-all "cape" "\ -Call CAPF and return a completion table which accepts every input. -This function can be used as an advice around an existing Capf. - -(fn CAPF)") - (autoload 'cape-capf-accept-all "cape") - (autoload 'cape-capf-buster "cape") - (autoload 'cape-capf-case-fold "cape") - (autoload 'cape-capf-debug "cape") - (autoload 'cape-capf-inside-code "cape") - (autoload 'cape-capf-inside-comment "cape") - (autoload 'cape-capf-inside-faces "cape") - (autoload 'cape-capf-inside-string "cape") - (autoload 'cape-capf-nonexclusive "cape") - (autoload 'cape-capf-noninterruptible "cape") - (autoload 'cape-capf-passthrough "cape") - (autoload 'cape-capf-predicate "cape") - (autoload 'cape-capf-prefix-length "cape") - (autoload 'cape-capf-properties "cape") - (autoload 'cape-capf-purify "cape") - (autoload 'cape-capf-silent "cape") - (autoload 'cape-capf-super "cape") - (autoload 'cape-prefix-map "cape" nil t 'keymap) -(register-definition-prefixes "cape" '("cape-")) - - -;;; Generated autoloads from cape-char.el - - (autoload 'cape-tex "cape-char" nil t) - (autoload 'cape-sgml "cape-char" nil t) - (autoload 'cape-rfc1345 "cape-char" nil t) - (when (> emacs-major-version 28) (autoload 'cape-emoji "cape-char" nil t)) -(register-definition-prefixes "cape-char" '("cape-char--")) - - -;;; Generated autoloads from cape-keyword.el - -(autoload 'cape-keyword "cape-keyword" "\ -Complete programming language keyword at point. -See the variable `cape-keyword-list'. -If INTERACTIVE is nil the function acts like a capf. - -(fn &optional INTERACTIVE)" t) -(register-definition-prefixes "cape-keyword" '("cape-")) - -;;; End of scraped data - -(provide 'cape-autoloads) - -;; Local Variables: -;; version-control: never -;; no-byte-compile: t -;; no-update-autoloads: t -;; no-native-compile: t -;; coding: utf-8-emacs-unix -;; End: - -;;; cape-autoloads.el ends here diff --git a/emacs/elpa/cape-20240926.918/cape-pkg.el b/emacs/elpa/cape-20240926.918/cape-pkg.el @@ -1,11 +0,0 @@ -;; -*- no-byte-compile: t; lexical-binding: nil -*- -(define-package "cape" "20240926.918" - "Completion At Point Extensions." - '((emacs "28.1") - (compat "30")) - :url "https://github.com/minad/cape" - :commit "2734e4ea0631f0e2944eac1aed79a55951157f55" - :revdesc "2734e4ea0631" - :keywords '("abbrev" "convenience" "matching" "completion" "text") - :authors '(("Daniel Mendler" . "mail@daniel-mendler.de")) - :maintainers '(("Daniel Mendler" . "mail@daniel-mendler.de"))) diff --git a/emacs/elpa/cape-20240926.918/cape.el b/emacs/elpa/cape-20240926.918/cape.el @@ -1,1299 +0,0 @@ -;;; cape.el --- Completion At Point Extensions -*- lexical-binding: t -*- - -;; Copyright (C) 2021-2024 Free Software Foundation, Inc. - -;; Author: Daniel Mendler <mail@daniel-mendler.de> -;; Maintainer: Daniel Mendler <mail@daniel-mendler.de> -;; Created: 2021 -;; Package-Version: 20240926.918 -;; Package-Revision: 2734e4ea0631 -;; Package-Requires: ((emacs "28.1") (compat "30")) -;; URL: https://github.com/minad/cape -;; Keywords: abbrev, convenience, matching, completion, text - -;; This file is part of GNU Emacs. - -;; This program is free software: you can redistribute it and/or modify -;; it under the terms of the GNU General Public License as published by -;; the Free Software Foundation, either version 3 of the License, or -;; (at your option) any later version. - -;; This program is distributed in the hope that it will be useful, -;; but WITHOUT ANY WARRANTY; without even the implied warranty of -;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -;; GNU General Public License for more details. - -;; You should have received a copy of the GNU General Public License -;; along with this program. If not, see <https://www.gnu.org/licenses/>. - -;;; Commentary: - -;; Let your completions fly! This package provides additional completion -;; backends in the form of Capfs (completion-at-point-functions). -;; -;; `cape-abbrev': Complete abbreviation (add-global-abbrev, add-mode-abbrev). -;; `cape-dabbrev': Complete word from current buffers. -;; `cape-dict': Complete word from dictionary file. -;; `cape-elisp-block': Complete Elisp in Org or Markdown code block. -;; `cape-elisp-symbol': Complete Elisp symbol. -;; `cape-emoji': Complete Emoji. -;; `cape-file': Complete file name. -;; `cape-history': Complete from Eshell, Comint or minibuffer history. -;; `cape-keyword': Complete programming language keyword. -;; `cape-line': Complete entire line from file. -;; `cape-rfc1345': Complete Unicode char using RFC 1345 mnemonics. -;; `cape-sgml': Complete Unicode char from SGML entity, e.g., &alpha. -;; `cape-tex': Complete Unicode char from TeX command, e.g. \hbar. - -;;; Code: - -(require 'compat) -(eval-when-compile - (require 'cl-lib) - (require 'subr-x)) - -;;;; Customization - -(defgroup cape nil - "Completion At Point Extensions." - :link '(info-link :tag "Info Manual" "(cape)") - :link '(url-link :tag "Website" "https://github.com/minad/cape") - :link '(emacs-library-link :tag "Library Source" "cape.el") - :group 'convenience - :group 'tools - :group 'matching - :prefix "cape-") - -(defcustom cape-dict-limit 100 - "Maximal number of completion candidates returned by `cape-dict'." - :type '(choice (const nil) natnum)) - -(defcustom cape-dict-file "/usr/share/dict/words" - "Path to dictionary word list file. -This variable can also be a list of paths or -a function returning a single or more paths." - :type '(choice string (repeat string) function)) - -(defcustom cape-dict-case-replace 'case-replace - "Preserve case of input. -See `dabbrev-case-replace' for details." - :type '(choice (const :tag "off" nil) - (const :tag "use `case-replace'" case-replace) - (other :tag "on" t))) - -(defcustom cape-dict-case-fold 'case-fold-search - "Case fold search during search. -See `dabbrev-case-fold-search' for details." - :type '(choice (const :tag "off" nil) - (const :tag "use `case-fold-search'" case-fold-search) - (other :tag "on" t))) - -(defcustom cape-dabbrev-min-length 4 - "Minimum length of Dabbrev expansions. -This setting ensures that words which are too short -are not offered as completion candidates, such that -auto completion does not pop up too aggressively." - :type 'natnum) - -(defcustom cape-dabbrev-check-other-buffers t - "Buffers to check for Dabbrev. - -If t, check all other buffers, subject to Dabbrev ignore rules. -If a function, only search the buffers returned by this function. -Any other non-nil value only checks some other buffers, as per -`dabbrev-select-buffers-function'." - :type `(choice (const :tag "off" nil) - (const :tag "same-mode buffers" ,#'cape--buffers-major-mode) - (function :tag "function") - (const :tag "some" some) - (other :tag "all" t))) - -(defcustom cape-file-directory nil - "Base directory used by `cape-file." - :type '(choice (const nil) string function)) - -(defcustom cape-file-prefix "file:" - "File completion trigger prefixes. -The value can be a string or a list of strings. The default -`file:' is the prefix of Org file links which work in arbitrary -buffers via `org-open-at-point-global'." - :type '(choice string (repeat string))) - -(defcustom cape-file-directory-must-exist t - "The parent directory must exist for file completion." - :type 'boolean) - -(defcustom cape-line-buffer-function #'cape--buffers-major-mode - "Function which returns list of buffers. -The buffers are scanned for completion candidates by `cape-line'." - :type '(choice (const :tag "Current buffer" current-buffer) - (const :tag "All buffers" buffer-list) - (const :tag "Buffers with same major mode" cape--buffers-major-mode) - (function :tag "Custom function"))) - -(defcustom cape-elisp-symbol-wrapper - '((org-mode ?~ ?~) - (markdown-mode ?` ?`) - (emacs-lisp-mode ?` ?') - (rst-mode "``" "``") - (log-edit-mode "`" "'") - (change-log-mode "`" "'") - (message-mode "`" "'") - (rcirc-mode "`" "'")) - "Wrapper characters for symbols." - :type '(alist :key-type symbol :value-type (list (choice character string) - (choice character string)))) - -;;;; Helpers - -(defun cape--case-fold-p (fold) - "Return non-nil if case folding is enabled for FOLD." - (if (eq fold 'case-fold-search) case-fold-search fold)) - -(defun cape--case-replace-list (flag input strs) - "Replace case of STRS depending on INPUT and FLAG." - (if (and (if (eq flag 'case-replace) case-replace flag) - (let (case-fold-search) (string-match-p "\\`[[:upper:]]" input))) - (mapcar (apply-partially #'cape--case-replace flag input) strs) - strs)) - -(defun cape--case-replace (flag input str) - "Replace case of STR depending on INPUT and FLAG." - (or (and (if (eq flag 'case-replace) case-replace flag) - (string-prefix-p input str t) - (let (case-fold-search) (string-match-p "\\`[[:upper:]]" input)) - (save-match-data - ;; Ensure that single character uppercase input does not lead to an - ;; all uppercase result. - (when (and (= (length input) 1) (> (length str) 1)) - (setq input (concat input (substring str 1 2)))) - (and (string-match input input) - (replace-match str nil nil input)))) - str)) - -(defun cape--separator-p (str) - "Return non-nil if input STR has a separator character. -Separator characters are used by completion styles like Orderless -to split filter words. In Corfu, the separator is configurable -via the variable `corfu-separator'." - (string-search (string ;; Support `corfu-separator' and Orderless - (or (and (bound-and-true-p corfu-mode) - (bound-and-true-p corfu-separator)) - ?\s)) - str)) - -(defmacro cape--silent (&rest body) - "Silence BODY." - (declare (indent 0)) - `(cl-letf ((inhibit-message t) - (message-log-max nil) - ((symbol-function #'minibuffer-message) #'ignore)) - (ignore-errors ,@body))) - -(defun cape--bounds (thing) - "Return bounds of THING." - (or (bounds-of-thing-at-point thing) (cons (point) (point)))) - -(defmacro cape--wrapped-table (wrap body) - "Create wrapped completion table, handle `completion--unquote'. -WRAP is the wrapper function. -BODY is the wrapping expression." - (declare (indent 1)) - `(lambda (str pred action) - (,@body - (let ((result (complete-with-action action table str pred))) - (when (and (eq action 'completion--unquote) (functionp (cadr result))) - (cl-callf ,wrap (cadr result))) - result)))) - -(defun cape--accept-all-table (table) - "Create completion TABLE which accepts all input." - (cape--wrapped-table cape--accept-all-table - (or (eq action 'lambda)))) - -(defun cape--passthrough-table (table) - "Create completion TABLE disabling any filtering." - (cape--wrapped-table cape--passthrough-table - (let (completion-ignore-case completion-regexp-list (_ (setq str "")))))) - -(defun cape--noninterruptible-table (table) - "Create non-interruptible completion TABLE." - (cape--wrapped-table cape--noninterruptible-table - (let (throw-on-input)))) - -(defun cape--silent-table (table) - "Create a new completion TABLE which is silent (no messages, no errors)." - (cape--wrapped-table cape--silent-table - (cape--silent))) - -(defun cape--nonessential-table (table) - "Mark completion TABLE as `non-essential'." - (let ((dir default-directory)) - (cape--wrapped-table cape--nonessential-table - (let ((default-directory dir) - (non-essential t)))))) - -(defvar cape--debug-length 5 - "Length of printed lists in `cape--debug-print'.") - -(defvar cape--debug-id 0 - "Completion table identifier.") - -(defun cape--debug-message (&rest msg) - "Print debug MSG." - (let ((inhibit-message t)) - (apply #'message msg))) - -(defun cape--debug-print (obj &optional full) - "Print OBJ as string, truncate lists if FULL is nil." - (cond - ((symbolp obj) (symbol-name obj)) - ((functionp obj) "#<function>") - ((proper-list-p obj) - (concat - "(" - (string-join - (mapcar #'cape--debug-print - (if full obj (take cape--debug-length obj))) - " ") - (if (and (not full) (length> obj cape--debug-length)) " ...)" ")"))) - (t (let ((print-level 2)) - (prin1-to-string obj))))) - -(defun cape--debug-table (table name beg end) - "Create completion TABLE with debug messages. -NAME is the name of the Capf, BEG and END are the input markers." - (lambda (str pred action) - (let ((result (complete-with-action action table str pred))) - (if (and (eq action 'completion--unquote) (functionp (cadr result))) - ;; See `cape--wrapped-table' - (cl-callf cape--debug-table (cadr result) name beg end) - (cape--debug-message - "%s(action=%S input=%s:%s:%S prefix=%S ignore-case=%S%s%s) => %s" - name - (pcase action - ('nil 'try) - ('t 'all) - ('lambda 'test) - (_ action)) - (+ beg 0) (+ end 0) (buffer-substring-no-properties beg end) - str completion-ignore-case - (if completion-regexp-list - (format " regexp=%s" (cape--debug-print completion-regexp-list t)) - "") - (if pred - (format " predicate=%s" (cape--debug-print pred)) - "") - (cape--debug-print result))) - result))) - -(cl-defun cape--properties-table (table &key category (sort t) &allow-other-keys) - "Create completion TABLE with properties. -CATEGORY is the optional completion category. -SORT should be nil to disable sorting." - ;; The metadata will be overridden if the category is non-nil, if the table is - ;; a function table or if sorting should be disabled for a non-nil - ;; non-function table. - (if (or category (functionp table) (and (not sort) table)) - (let ((metadata `(metadata - ,@(and category `((category . ,category))) - ,@(and (not sort) '((display-sort-function . identity) - (cycle-sort-function . identity)))))) - (lambda (str pred action) - (if (eq action 'metadata) - metadata - (complete-with-action action table str pred)))) - table)) - -(defun cape--dynamic-table (beg end fun) - "Create dynamic completion table from FUN with caching. -BEG and END are the input bounds. FUN is the function which -computes the candidates. FUN must return a pair of a predicate -function function and the list of candidates. The predicate is -passed new input and must return non-nil if the candidates are -still valid. - -It is only necessary to use this function if the set of -candidates is computed dynamically based on the input and not -statically determined. The behavior is similar but slightly -different to `completion-table-dynamic'. - -The difference to the builtins `completion-table-dynamic' and -`completion-table-with-cache' is that this function does not use -the prefix argument of the completion table to compute the -candidates. Instead it uses the input in the buffer between BEG -and END to FUN to compute the candidates. This way the dynamic -candidate computation is compatible with non-prefix completion -styles like `substring' or `orderless', which pass the empty -string as first argument to the completion table." - (let ((beg (copy-marker beg)) - (end (copy-marker end t)) - valid table) - (lambda (str pred action) - ;; Bail out early for `metadata' and `boundaries'. This is a pointless - ;; move because of caching, but we do it anyway in the hope that the - ;; profiler report looks less confusing, since the weight of the expensive - ;; FUN computation is moved to the `all-completions' action. Computing - ;; `all-completions' must surely be most expensive, so nobody will suspect - ;; a thing. - (unless (or (eq action 'metadata) (eq (car-safe action) 'boundaries)) - (let ((input (buffer-substring-no-properties beg end))) - (unless (and valid - (or (cape--separator-p input) - (funcall valid input))) - (let* (;; Reset in case `all-completions' is used inside FUN - completion-ignore-case completion-regexp-list - ;; Retrieve new state by calling FUN - (new (funcall fun input)) - ;; No interrupt during state update - throw-on-input) - (setq valid (car new) table (cdr new))))) - (complete-with-action action table str pred))))) - -;;;; Capfs - -;;;;; cape-history - -(declare-function ring-elements "ring") -(declare-function eshell-bol "eshell") -(declare-function comint-line-beginning-position "comint") -(defvar eshell-history-ring) -(defvar comint-input-ring) - -(defvar cape--history-properties - (list :company-kind (lambda (_) 'text) - :exclusive 'no) - "Completion extra properties for `cape-history'.") - -;;;###autoload -(defun cape-history (&optional interactive) - "Complete from Eshell, Comint or minibuffer history. -See also `consult-history' for a more flexible variant based on -`completing-read'. If INTERACTIVE is nil the function acts like a Capf." - (interactive (list t)) - (if interactive - (cape-interactive #'cape-history) - (let (history bol) - (cond - ((derived-mode-p 'eshell-mode) - (setq history eshell-history-ring - bol (static-if (< emacs-major-version 30) - (save-excursion (eshell-bol) (point)) - (line-beginning-position)))) - ((derived-mode-p 'comint-mode) - (setq history comint-input-ring - bol (comint-line-beginning-position))) - ((and (minibufferp) (not (eq minibuffer-history-variable t))) - (setq history (symbol-value minibuffer-history-variable) - bol (line-beginning-position)))) - (when (ring-p history) - (setq history (ring-elements history))) - (when history - `(,bol ,(point) - ,(cape--properties-table history :sort nil) - ,@cape--history-properties))))) - -;;;;; cape-file - -(defvar comint-unquote-function) -(defvar comint-requote-function) - -(defvar cape--file-properties - (list :annotation-function (lambda (s) (if (string-suffix-p "/" s) " Dir" " File")) - :company-kind (lambda (s) (if (string-suffix-p "/" s) 'folder 'file)) - :exclusive 'no) - "Completion extra properties for `cape-file'.") - -;;;###autoload -(defun cape-file (&optional interactive) - "Complete file name at point. -See the user option `cape-file-directory-must-exist'. -If INTERACTIVE is nil the function acts like a Capf." - (interactive (list t)) - (if interactive - (cape-interactive '(cape-file-directory-must-exist) #'cape-file) - (pcase-let* ((default-directory (pcase cape-file-directory - ('nil default-directory) - ((pred stringp) cape-file-directory) - (_ (funcall cape-file-directory)))) - (prefix (and cape-file-prefix - (looking-back - (concat - (regexp-opt (ensure-list cape-file-prefix) t) - "[^ \n\t]*") - (pos-bol)) - (match-end 1))) - (`(,beg . ,end) (if prefix - (cons prefix (point)) - (cape--bounds 'filename))) - (non-essential t) - (file (buffer-substring-no-properties beg end))) - (when (or prefix - (not cape-file-directory-must-exist) - (and (string-search "/" file) - (file-exists-p (file-name-directory file)))) - `(,beg ,end - ,(cape--nonessential-table - (if (or (derived-mode-p 'comint-mode) (derived-mode-p 'eshell-mode)) - (completion-table-with-quoting - #'read-file-name-internal - comint-unquote-function - comint-requote-function) - #'read-file-name-internal)) - ,@(when (or prefix (string-match-p "./" file)) - '(:company-prefix-length t)) - ,@cape--file-properties))))) - -;;;;; cape-elisp-symbol - -(autoload 'elisp--company-kind "elisp-mode") -(autoload 'elisp--company-doc-buffer "elisp-mode") -(autoload 'elisp--company-doc-string "elisp-mode") -(autoload 'elisp--company-location "elisp-mode") - -(defvar cape--elisp-symbol-properties - (list :annotation-function #'cape--elisp-symbol-annotation - :exit-function #'cape--elisp-symbol-exit - :predicate #'cape--elisp-symbol-predicate - :company-kind #'elisp--company-kind - :company-doc-buffer #'elisp--company-doc-buffer - :company-docsig #'elisp--company-doc-string - :company-location #'elisp--company-location - :exclusive 'no) - "Completion extra properties for `cape-elisp-symbol'.") - -(defun cape--elisp-symbol-predicate (sym) - "Return t if SYM is bound, fbound or propertized." - (or (fboundp sym) (boundp sym) (symbol-plist sym))) - -(defun cape--elisp-symbol-exit (sym status) - "Wrap symbol SYM with `cape-elisp-symbol-wrapper' buffers. -STATUS is the exit status." - (when-let (((not (eq status 'exact))) - (c (cl-loop for (m . c) in cape-elisp-symbol-wrapper - if (derived-mode-p m) return c)) - ((or (not (derived-mode-p 'emacs-lisp-mode)) - ;; Inside comment or string - (let ((s (syntax-ppss))) (or (nth 3 s) (nth 4 s))))) - (x (if (stringp (car c)) (car c) (string (car c)))) - (y (if (stringp (cadr c)) (cadr c) (string (cadr c))))) - (save-excursion - (backward-char (length sym)) - (unless (save-excursion - (and (ignore-errors (or (backward-char (length x)) t)) - (looking-at-p (regexp-quote x)))) - (insert x))) - (unless (looking-at-p (regexp-quote y)) - (insert y)))) - -(defun cape--elisp-symbol-annotation (sym) - "Return kind of SYM." - (setq sym (intern-soft sym)) - (cond - ((special-form-p sym) " Special") - ((macrop sym) " Macro") - ((commandp sym) " Command") - ((fboundp sym) " Function") - ((custom-variable-p sym) " Custom") - ((boundp sym) " Variable") - ((featurep sym) " Feature") - ((facep sym) " Face") - (t " Symbol"))) - -;;;###autoload -(defun cape-elisp-symbol (&optional interactive) - "Complete Elisp symbol at point. -If INTERACTIVE is nil the function acts like a Capf." - (interactive (list t)) - (if interactive - ;; No cycling since it breaks the :exit-function. - (let (completion-cycle-threshold) - (cape-interactive #'cape-elisp-symbol)) - (pcase-let ((`(,beg . ,end) (cape--bounds 'symbol))) - (when (eq (char-after beg) ?') - (setq beg (1+ beg) end (max beg end))) - `(,beg ,end - ,(cape--properties-table obarray :category 'symbol) - ,@cape--elisp-symbol-properties)))) - -;;;;; cape-elisp-block - -(declare-function org-element-context "org-element") -(declare-function markdown-code-block-lang "ext:markdown-mode") - -(defun cape--inside-block-p (&rest langs) - "Return non-nil if inside LANGS code block." - (when-let ((face (get-text-property (point) 'face)) - (lang (or (and (if (listp face) - (memq 'org-block face) - (eq 'org-block face)) - (plist-get (cadr (org-element-context)) :language)) - (and (if (listp face) - (memq 'markdown-code-face face) - (eq 'markdown-code-face face)) - (save-excursion - (markdown-code-block-lang)))))) - (member lang langs))) - -;;;###autoload -(defun cape-elisp-block (&optional interactive) - "Complete Elisp in Org or Markdown code block. -This Capf is particularly useful for literate Emacs configurations. -If INTERACTIVE is nil the function acts like a Capf." - (interactive (list t)) - (cond - (interactive - ;; No code block check. Always complete Elisp when command was - ;; explicitly invoked interactively. - (cape-interactive #'elisp-completion-at-point)) - ((cape--inside-block-p "elisp" "emacs-lisp") - (elisp-completion-at-point)))) - -;;;;; cape-dabbrev - -(defvar cape--dabbrev-properties - (list :annotation-function (lambda (_) " Dabbrev") - :company-kind (lambda (_) 'text) - :exclusive 'no) - "Completion extra properties for `cape-dabbrev'.") - -(defvar dabbrev-case-replace) -(defvar dabbrev-case-fold-search) -(defvar dabbrev-abbrev-char-regexp) -(defvar dabbrev-abbrev-skip-leading-regexp) -(declare-function dabbrev--find-all-expansions "dabbrev") -(declare-function dabbrev--reset-global-variables "dabbrev") - -(defun cape--dabbrev-list (input) - "Find all Dabbrev expansions for INPUT." - (cape--silent - (let* ((chk cape-dabbrev-check-other-buffers) - (funp (and (not (memq chk '(nil t some))) (functionp chk)))) - (dlet ((dabbrev-check-other-buffers (and chk (not funp))) - (dabbrev-check-all-buffers (eq chk t)) - (dabbrev-search-these-buffers-only (and funp (funcall chk)))) - (dabbrev--reset-global-variables) - (cons - (apply-partially #'string-prefix-p input) - (cl-loop with min-len = (+ cape-dabbrev-min-length (length input)) - with ic = (cape--case-fold-p dabbrev-case-fold-search) - for w in (dabbrev--find-all-expansions input ic) - if (>= (length w) min-len) collect - (cape--case-replace (and ic dabbrev-case-replace) input w))))))) - -(defun cape--dabbrev-bounds () - "Return bounds of abbreviation." - (unless (boundp 'dabbrev-abbrev-char-regexp) - (require 'dabbrev)) - (let ((re (or dabbrev-abbrev-char-regexp "\\sw\\|\\s_")) - (limit (minibuffer-prompt-end))) - (when (or (looking-at re) - (and (> (point) limit) - (save-excursion (forward-char -1) (looking-at re)))) - (cons (save-excursion - (while (and (> (point) limit) - (save-excursion (forward-char -1) (looking-at re))) - (forward-char -1)) - (when dabbrev-abbrev-skip-leading-regexp - (while (looking-at dabbrev-abbrev-skip-leading-regexp) - (forward-char 1))) - (point)) - (save-excursion - (while (looking-at re) - (forward-char 1)) - (point)))))) - -;;;###autoload -(defun cape-dabbrev (&optional interactive) - "Complete with Dabbrev at point. - -If INTERACTIVE is nil the function acts like a Capf. In case you -observe a performance issue with auto-completion and `cape-dabbrev' -it is strongly recommended to disable scanning in other buffers. -See the user options `cape-dabbrev-min-length' and -`cape-dabbrev-check-other-buffers'." - (interactive (list t)) - (if interactive - (cape-interactive '((cape-dabbrev-min-length 0)) #'cape-dabbrev) - (when-let ((bounds (cape--dabbrev-bounds))) - `(,(car bounds) ,(cdr bounds) - ,(cape--properties-table - (completion-table-case-fold - (cape--dynamic-table (car bounds) (cdr bounds) #'cape--dabbrev-list) - (not (cape--case-fold-p dabbrev-case-fold-search))) - :category 'cape-dabbrev) - ,@cape--dabbrev-properties)))) - -;;;;; cape-dict - -(defvar cape--dict-properties - (list :annotation-function (lambda (_) " Dict") - :company-kind (lambda (_) 'text) - :exclusive 'no) - "Completion extra properties for `cape-dict'.") - -(defun cape--dict-list (input) - "Return all words from `cape-dict-file' matching INPUT." - (unless (equal input "") - (let* ((inhibit-message t) - (message-log-max nil) - (default-directory - (if (and (not (file-remote-p default-directory)) - (file-directory-p default-directory)) - default-directory - user-emacs-directory)) - (files (mapcar #'expand-file-name - (ensure-list - (if (functionp cape-dict-file) - (funcall cape-dict-file) - cape-dict-file)))) - (words - (apply #'process-lines-ignore-status - "grep" - (concat "-Fh" - (and (cape--case-fold-p cape-dict-case-fold) "i") - (and cape-dict-limit (format "m%d" cape-dict-limit))) - input files))) - (cons - (apply-partially - (if (and cape-dict-limit (length= words cape-dict-limit)) - #'equal #'string-search) - input) - (cape--case-replace-list cape-dict-case-replace input words))))) - -;;;###autoload -(defun cape-dict (&optional interactive) - "Complete word from dictionary at point. -This completion function works best if the dictionary is sorted -by frequency. See the custom option `cape-dict-file'. If -INTERACTIVE is nil the function acts like a Capf." - (interactive (list t)) - (if interactive - (cape-interactive #'cape-dict) - (pcase-let ((`(,beg . ,end) (cape--bounds 'word))) - `(,beg ,end - ,(cape--properties-table - (completion-table-case-fold - (cape--dynamic-table beg end #'cape--dict-list) - (not (cape--case-fold-p cape-dict-case-fold))) - :sort nil ;; Presorted word list (by frequency) - :category 'cape-dict) - ,@cape--dict-properties)))) - -;;;;; cape-abbrev - -(defun cape--abbrev-list () - "Abbreviation list." - (delete "" (cl-loop for x in (abbrev--suggest-get-active-tables-including-parents) - nconc (all-completions "" x)))) - -(defun cape--abbrev-annotation (abbrev) - "Annotate ABBREV with expansion." - (concat " " - (truncate-string-to-width - (format - "%s" - (symbol-value - (cl-loop for x in (abbrev--suggest-get-active-tables-including-parents) - thereis (abbrev--symbol abbrev x)))) - 30 0 nil t))) - -(defun cape--abbrev-exit (_str status) - "Expand expansion if STATUS is not exact." - (unless (eq status 'exact) - (expand-abbrev))) - -(defvar cape--abbrev-properties - (list :annotation-function #'cape--abbrev-annotation - :exit-function #'cape--abbrev-exit - :company-kind (lambda (_) 'snippet) - :exclusive 'no) - "Completion extra properties for `cape-abbrev'.") - -;;;###autoload -(defun cape-abbrev (&optional interactive) - "Complete abbreviation at point. -If INTERACTIVE is nil the function acts like a Capf." - (interactive (list t)) - (if interactive - ;; No cycling since it breaks the :exit-function. - (let (completion-cycle-threshold) - (cape-interactive #'cape-abbrev)) - (when-let (abbrevs (cape--abbrev-list)) - (let ((bounds (cape--bounds 'symbol))) - `(,(car bounds) ,(cdr bounds) - ,(cape--properties-table abbrevs :category 'cape-abbrev) - ,@cape--abbrev-properties))))) - -;;;;; cape-line - -(defvar cape--line-properties nil - "Completion extra properties for `cape-line'.") - -(defun cape--buffers-major-mode () - "Return buffers with same major mode as current buffer." - (cl-loop for buf in (buffer-list) - if (eq major-mode (buffer-local-value 'major-mode buf)) - collect buf)) - -(defun cape--line-list () - "Return all lines from buffer." - (let ((ht (make-hash-table :test #'equal)) - (curr-buf (current-buffer)) - (buffers (funcall cape-line-buffer-function)) - lines) - (dolist (buf (ensure-list buffers)) - (with-current-buffer buf - (let ((beg (point-min)) - (max (point-max)) - (pt (if (eq curr-buf buf) (point) -1)) - end) - (save-excursion - (while (< beg max) - (goto-char beg) - (setq end (pos-eol)) - (unless (<= beg pt end) - (let ((line (buffer-substring-no-properties beg end))) - (unless (or (string-blank-p line) (gethash line ht)) - (puthash line t ht) - (push line lines)))) - (setq beg (1+ end))))))) - (nreverse lines))) - -;;;###autoload -(defun cape-line (&optional interactive) - "Complete current line from other lines. -The buffers returned by `cape-line-buffer-function' are scanned for lines. -If INTERACTIVE is nil the function acts like a Capf." - (interactive (list t)) - (if interactive - (cape-interactive #'cape-line) - `(,(pos-bol) ,(point) - ,(cape--properties-table (cape--line-list) :sort nil) - ,@cape--line-properties))) - -;;;; Capf combinators - -(defun cape--company-call (&rest app) - "Apply APP and handle future return values." - ;; Backends are non-interruptible. Disable interrupts! - (let ((toi throw-on-input) - (throw-on-input nil)) - (pcase (apply app) - ;; Handle async future return values. - (`(:async . ,fetch) - (let ((res 'cape--waiting)) - (if toi - (unwind-protect - (progn - (funcall fetch - (lambda (arg) - (when (eq res 'cape--waiting) - (push 'cape--done unread-command-events) - (setq res arg)))) - (when (eq res 'cape--waiting) - (let ((ev (let ((input-method-function nil) - (echo-keystrokes 0)) - (read-event nil t)))) - (unless (eq ev 'cape--done) - (push (cons t ev) unread-command-events) - (setq res 'cape--cancelled) - (throw toi t))))) - (setq unread-command-events - (delq 'cape--done unread-command-events))) - (funcall fetch (lambda (arg) (setq res arg))) - ;; Force synchronization, not interruptible! We use polling - ;; here and ignore pending input since we don't use - ;; `sit-for'. This is the same method used by Company itself. - (while (eq res 'cape--waiting) - (sleep-for 0.01))) - res)) - ;; Plain old synchronous return value. - (res res)))) - -(defvar-local cape--company-init nil) - -;;;###autoload -(defun cape-company-to-capf (backend &optional valid) - "Convert Company BACKEND function to Capf. -VALID is a function taking the old and new input string. It should -return nil if the cached candidates became invalid. The default value -for VALID is `string-prefix-p' such that the candidates are only fetched -again if the input prefix changed." - (lambda () - (when (and (symbolp backend) (not (fboundp backend))) - (ignore-errors (require backend nil t))) - (when (bound-and-true-p company-mode) - (error "`cape-company-to-capf' should not be used with `company-mode', use the Company backend directly instead")) - (when (and (symbolp backend) (not (alist-get backend cape--company-init))) - (funcall backend 'init) - (put backend 'company-init t) - (setf (alist-get backend cape--company-init) t)) - (when-let ((prefix (cape--company-call backend 'prefix)) - (initial-input (if (stringp prefix) prefix (car-safe prefix)))) - (let* ((end (point)) (beg (- end (length initial-input))) - (valid (if (cape--company-call backend 'no-cache initial-input) - #'equal (or valid #'string-prefix-p))) - restore-props) - (list beg end - (funcall - (if (cape--company-call backend 'ignore-case) - #'completion-table-case-fold - #'identity) - (cape--properties-table - (cape--dynamic-table - beg end - (lambda (input) - (let ((cands (cape--company-call backend 'candidates input))) - ;; The candidate string including text properties should be - ;; restored in the :exit-function, unless the UI guarantees - ;; this itself, like Corfu. - (unless (bound-and-true-p corfu-mode) - (setq restore-props cands)) - (cons (apply-partially valid input) cands)))) - :category backend - :sort (not (cape--company-call backend 'sorted)))) - :exclusive 'no - :company-prefix-length (cdr-safe prefix) - :company-doc-buffer (lambda (x) (cape--company-call backend 'doc-buffer x)) - :company-location (lambda (x) (cape--company-call backend 'location x)) - :company-docsig (lambda (x) (cape--company-call backend 'meta x)) - :company-deprecated (lambda (x) (cape--company-call backend 'deprecated x)) - :company-kind (lambda (x) (cape--company-call backend 'kind x)) - :annotation-function (lambda (x) - (when-let (ann (cape--company-call backend 'annotation x)) - (concat " " (string-trim ann)))) - :exit-function (lambda (x _status) - ;; Restore the candidate string including - ;; properties if restore-props is non-nil. See - ;; the comment above. - (setq x (or (car (member x restore-props)) x)) - (cape--company-call backend 'post-completion x))))))) - -;;;###autoload -(defun cape-interactive (&rest capfs) - "Complete interactively with the given CAPFS." - (let* ((ctx (and (consp (car capfs)) (car capfs))) - (capfs (if ctx (cdr capfs) capfs)) - (completion-at-point-functions - (if ctx - (mapcar (lambda (f) `(lambda () (let ,ctx (funcall ',f)))) capfs) - capfs))) - (unless (completion-at-point) - (user-error "%s: No completions" - (mapconcat (lambda (fun) - (if (symbolp fun) - (symbol-name fun) - "anonymous-capf")) - capfs ", "))))) - -;;;###autoload -(defun cape-capf-interactive (capf) - "Create interactive completion function from CAPF." - (lambda (&optional interactive) - (interactive (list t)) - (if interactive (cape-interactive capf) (funcall capf)))) - -;;;###autoload -(defun cape-wrap-super (&rest capfs) - "Call CAPFS and return merged completion result. -The CAPFS list can contain the keyword `:with' to mark the Capfs -afterwards as auxiliary One of the non-auxiliary Capfs before -`:with' must return non-nil for the super Capf to set in and -return a non-nil result. Such behavior is useful when listing -multiple super Capfs in the `completion-at-point-functions': - - (setq completion-at-point-functions - (list (cape-capf-super \\='eglot-completion-at-point - :with \\='tempel-complete) - (cape-capf-super \\='cape-dabbrev - :with \\='tempel-complete)))" - (when-let ((results (cl-loop for capf in capfs until (eq capf :with) - for res = (funcall capf) - if res collect (cons t res)))) - (pcase-let* ((results (nconc results - (cl-loop for capf in (cdr (memq :with capfs)) - for res = (funcall capf) - if res collect (cons nil res)))) - (`((,_main ,beg ,end . ,_)) results) - (cand-ht nil) - (tables nil) - (exclusive nil) - (prefix-len nil) - (cand-functions - '(:company-docsig :company-location :company-kind - :company-doc-buffer :company-deprecated - :annotation-function :exit-function))) - (cl-loop for (main beg2 end2 table . plist) in results do - ;; Note: `cape-capf-super' currently cannot merge Capfs which - ;; trigger at different beginning positions. In order to support - ;; this, take the smallest BEG value and then normalize all - ;; candidates by prefixing them such that they all start at the - ;; smallest BEG position. - (when (= beg beg2) - (push (list main (plist-get plist :predicate) table - ;; Plist attached to the candidates - (mapcan (lambda (f) - (when-let ((v (plist-get plist f))) - (list f v))) - cand-functions)) - tables) - ;; The resulting merged Capf is exclusive if one of the main - ;; Capfs is exclusive. - (when (and main (not (eq (plist-get plist :exclusive) 'no))) - (setq exclusive t)) - (setq end (max end end2)) - (let ((plen (plist-get plist :company-prefix-length))) - (cond - ((eq plen t) - (setq prefix-len t)) - ((and (not prefix-len) (integerp plen)) - (setq prefix-len plen)) - ((and (integerp prefix-len) (integerp plen)) - (setq prefix-len (max prefix-len plen))))))) - (setq tables (nreverse tables)) - `(,beg ,end - ,(lambda (str pred action) - (pcase action - (`(boundaries . ,_) nil) - ('metadata - '(metadata (category . cape-super) - (display-sort-function . identity) - (cycle-sort-function . identity))) - ('t ;; all-completions - (let ((ht (make-hash-table :test #'equal)) - (candidates nil)) - (cl-loop for (main table-pred table cand-plist) in tables do - (let* ((pr (if (and table-pred pred) - (lambda (x) (and (funcall table-pred x) (funcall pred x))) - (or table-pred pred))) - (md (completion-metadata "" table pr)) - (sort (or (completion-metadata-get md 'display-sort-function) - #'identity)) - ;; Always compute candidates of the main Capf - ;; tables, which come first in the tables - ;; list. For the :with Capfs only compute - ;; candidates if we've already determined that - ;; main candidates are available. - (cands (when (or main (or exclusive cand-ht candidates)) - (funcall sort (all-completions str table pr))))) - ;; Handle duplicates with a hash table. - (cl-loop - for cand in-ref cands - for dup = (gethash cand ht t) do - (cond - ((eq dup t) - ;; Candidate does not yet exist. - (puthash cand cand-plist ht)) - ((not (equal dup cand-plist)) - ;; Duplicate candidate. Candidate plist is - ;; different, therefore disambiguate the - ;; candidates. - (setf cand (propertize cand 'cape-capf-super - (cons cand cand-plist)))))) - (when cands (push cands candidates)))) - (when (or cand-ht candidates) - (setq candidates (apply #'nconc (nreverse candidates)) - cand-ht ht) - candidates))) - (_ ;; try-completion and test-completion - (cl-loop for (_main table-pred table _cand-plist) in tables thereis - (complete-with-action - action table str - (if (and table-pred pred) - (lambda (x) (and (funcall table-pred x) (funcall pred x))) - (or table-pred pred))))))) - :company-prefix-length ,prefix-len - ,@(and (not exclusive) '(:exclusive no)) - ,@(mapcan - (lambda (prop) - (list prop - (lambda (cand &rest args) - (if-let ((ref (get-text-property 0 'cape-capf-super cand))) - (when-let ((fun (plist-get (cdr ref) prop))) - (apply fun (car ref) args)) - (when-let ((plist (and cand-ht (gethash cand cand-ht))) - (fun (plist-get plist prop))) - (apply fun cand args)))))) - cand-functions))))) - -;;;###autoload -(defun cape-wrap-debug (capf &optional name) - "Call CAPF and return a completion table which prints trace messages. -If CAPF is an anonymous lambda, pass the Capf NAME explicitly for -meaningful debugging output." - (unless name - (setq name (if (symbolp capf) capf "capf"))) - (setq name (format "%s@%s" name (cl-incf cape--debug-id))) - (pcase (funcall capf) - (`(,beg ,end ,table . ,plist) - (let* ((limit (1+ cape--debug-length)) - (pred (plist-get plist :predicate)) - (cands - ;; Reset regexps for `all-completions' - (let (completion-ignore-case completion-regexp-list) - (all-completions - "" table - (lambda (&rest args) - (and (or (not pred) (apply pred args)) (>= (cl-decf limit) 0)))))) - (plist-str "") - (plist-elt plist)) - (while (cdr plist-elt) - (setq plist-str (format "%s %s=%s" plist-str - (substring (symbol-name (car plist-elt)) 1) - (cape--debug-print (cadr plist-elt))) - plist-elt (cddr plist-elt))) - (cape--debug-message - "%s => input=%s:%s:%S table=%s%s" - name (+ beg 0) (+ end 0) (buffer-substring-no-properties beg end) - (cape--debug-print cands) - plist-str)) - `(,beg ,end ,(cape--debug-table - table name (copy-marker beg) (copy-marker end t)) - ,@(when-let ((exit (plist-get plist :exit-function))) - (list :exit-function - (lambda (cand status) - (cape--debug-message "%s:exit(candidate=%S status=%s)" - name cand status) - (funcall exit cand status)))) - . ,plist)) - (result - (cape--debug-message "%s() => %s (No completion)" - name (cape--debug-print result))))) - -;;;###autoload -(defun cape-wrap-buster (capf &optional valid) - "Call CAPF and return a completion table with cache busting. -This function can be used as an advice around an existing Capf. -The cache is busted when the input changes. The argument VALID -can be a function taking the old and new input string. It should -return nil if the new input requires that the completion table is -refreshed. The default value for VALID is `equal', such that the -completion table is refreshed on every input change." - (setq valid (or valid #'equal)) - (pcase (funcall capf) - (`(,beg ,end ,table . ,plist) - (setq plist `(:cape--buster t . ,plist)) - `(,beg ,end - ,(let* ((beg (copy-marker beg)) - (end (copy-marker end t)) - (input (buffer-substring-no-properties beg end))) - (lambda (str pred action) - (let ((new-input (buffer-substring-no-properties beg end))) - (unless (or (not (eq action t)) - (cape--separator-p new-input) - (funcall valid input new-input)) - (pcase - ;; Reset in case `all-completions' is used inside CAPF - (let (completion-ignore-case completion-regexp-list) - (funcall capf)) - ((and `(,new-beg ,new-end ,new-table . ,new-plist) - (guard (and (= beg new-beg) (= end new-end)))) - (let (throw-on-input) ;; No interrupt during state update - (setf table new-table - input new-input - (cddr plist) new-plist)))))) - (complete-with-action action table str pred))) - ,@plist)))) - -;;;###autoload -(defun cape-wrap-passthrough (capf) - "Call CAPF and make sure that no completion style filtering takes place." - (pcase (funcall capf) - (`(,beg ,end ,table . ,plist) - `(,beg ,end ,(cape--passthrough-table table) ,@plist)))) - -;;;###autoload -(defun cape-wrap-properties (capf &rest properties) - "Call CAPF and add additional completion PROPERTIES. -Completion properties include for example :exclusive, :annotation-function and -the various :company-* extensions. Furthermore a boolean :sort flag and a -completion :category symbol can be specified." - (pcase (funcall capf) - (`(,beg ,end ,table . ,plist) - `(,beg ,end - ,(apply #'cape--properties-table table properties) - ,@properties ,@plist)))) - -;;;###autoload -(defun cape-wrap-nonexclusive (capf) - "Call CAPF and ensure that it is marked as non-exclusive. -This function can be used as an advice around an existing Capf." - (cape-wrap-properties capf :exclusive 'no)) - -;;;###autoload -(defun cape-wrap-predicate (capf predicate) - "Call CAPF and add an additional candidate PREDICATE. -The PREDICATE is passed the candidate symbol or string." - (pcase (funcall capf) - (`(,beg ,end ,table . ,plist) - `(,beg ,end ,table - :predicate - ,(if-let (pred (plist-get plist :predicate)) - ;; First argument is key, second is value for hash tables. - ;; The first argument can be a cons cell for alists. Then - ;; the candidate itself is either a string or a symbol. We - ;; normalize the calling convention here such that PREDICATE - ;; always receives a string or a symbol. - (lambda (&rest args) - (when (apply pred args) - (setq args (car args)) - (funcall predicate (if (consp args) (car args) args)))) - (lambda (key &optional _val) - (funcall predicate (if (consp key) (car key) key)))) - ,@plist)))) - -;;;###autoload -(defun cape-wrap-silent (capf) - "Call CAPF and silence it (no messages, no errors). -This function can be used as an advice around an existing Capf." - (pcase (cape--silent (funcall capf)) - (`(,beg ,end ,table . ,plist) - `(,beg ,end ,(cape--silent-table table) ,@plist)))) - -;;;###autoload -(defun cape-wrap-case-fold (capf &optional nofold) - "Call CAPF and return a case-insensitive completion table. -If NOFOLD is non-nil return a case sensitive table instead. This -function can be used as an advice around an existing Capf." - (pcase (funcall capf) - (`(,beg ,end ,table . ,plist) - `(,beg ,end ,(completion-table-case-fold table nofold) ,@plist)))) - -;;;###autoload -(defun cape-wrap-noninterruptible (capf) - "Call CAPF and return a non-interruptible completion table. -This function can be used as an advice around an existing Capf." - (pcase (let (throw-on-input) (funcall capf)) - (`(,beg ,end ,table . ,plist) - `(,beg ,end ,(cape--noninterruptible-table table) ,@plist)))) - -;;;###autoload -(defun cape-wrap-prefix-length (capf length) - "Call CAPF and ensure that prefix length is greater or equal than LENGTH. -If the prefix is long enough, enforce auto completion." - (pcase (funcall capf) - (`(,beg ,end ,table . ,plist) - (when (>= (- end beg) length) - `(,beg ,end ,table - :company-prefix-length t - ,@plist))))) - -;;;###autoload -(defun cape-wrap-inside-faces (capf &rest faces) - "Call CAPF only if inside FACES. -This function can be used as an advice around an existing Capf." - (when-let (((> (point) (point-min))) - (fs (get-text-property (1- (point)) 'face)) - ((if (listp fs) - (cl-loop for f in fs thereis (memq f faces)) - (memq fs faces)))) - (funcall capf))) - -;;;###autoload -(defun cape-wrap-inside-code (capf) - "Call CAPF only if inside code, not inside a comment or string. -This function can be used as an advice around an existing Capf." - (let ((s (syntax-ppss))) - (and (not (nth 3 s)) (not (nth 4 s)) (funcall capf)))) - -;;;###autoload -(defun cape-wrap-inside-comment (capf) - "Call CAPF only if inside comment. -This function can be used as an advice around an existing Capf." - (and (nth 4 (syntax-ppss)) (funcall capf))) - -;;;###autoload -(defun cape-wrap-inside-string (capf) - "Call CAPF only if inside string. -This function can be used as an advice around an existing Capf." - (and (nth 3 (syntax-ppss)) (funcall capf))) - -;;;###autoload -(defun cape-wrap-purify (capf) - "Call CAPF and ensure that it does not illegally modify the buffer. -This function can be used as an advice around an existing -Capf. It has been introduced mainly to fix the broken -`pcomplete-completions-at-point' function in Emacs versions < 29." - ;; bug#50470: Fix Capfs which illegally modify the buffer or which illegally - ;; call `completion-in-region'. The workaround here was proposed by - ;; @jakanakaevangeli and is used in his capf-autosuggest package. In Emacs 29 - ;; the purity bug of Pcomplete has been fixed, such that make - ;; `cape-wrap-purify' is not necessary anymore. - (catch 'cape--illegal-completion-in-region - (condition-case nil - (let ((buffer-read-only t) - (inhibit-read-only nil) - (completion-in-region-function - (lambda (beg end coll pred) - (throw 'cape--illegal-completion-in-region - (list beg end coll :predicate pred))))) - (funcall capf)) - (buffer-read-only nil)))) - -;;;###autoload -(defun cape-wrap-accept-all (capf) - "Call CAPF and return a completion table which accepts every input. -This function can be used as an advice around an existing Capf." - (pcase (funcall capf) - (`(,beg ,end ,table . ,plist) - `(,beg ,end ,(cape--accept-all-table table) . ,plist)))) - -;;;###autoload (autoload 'cape-capf-accept-all "cape") -;;;###autoload (autoload 'cape-capf-buster "cape") -;;;###autoload (autoload 'cape-capf-case-fold "cape") -;;;###autoload (autoload 'cape-capf-debug "cape") -;;;###autoload (autoload 'cape-capf-inside-code "cape") -;;;###autoload (autoload 'cape-capf-inside-comment "cape") -;;;###autoload (autoload 'cape-capf-inside-faces "cape") -;;;###autoload (autoload 'cape-capf-inside-string "cape") -;;;###autoload (autoload 'cape-capf-nonexclusive "cape") -;;;###autoload (autoload 'cape-capf-noninterruptible "cape") -;;;###autoload (autoload 'cape-capf-passthrough "cape") -;;;###autoload (autoload 'cape-capf-predicate "cape") -;;;###autoload (autoload 'cape-capf-prefix-length "cape") -;;;###autoload (autoload 'cape-capf-properties "cape") -;;;###autoload (autoload 'cape-capf-purify "cape") -;;;###autoload (autoload 'cape-capf-silent "cape") -;;;###autoload (autoload 'cape-capf-super "cape") - -(dolist (wrapper (list #'cape-wrap-accept-all #'cape-wrap-buster - #'cape-wrap-case-fold #'cape-wrap-debug - #'cape-wrap-inside-code #'cape-wrap-inside-comment - #'cape-wrap-inside-faces #'cape-wrap-inside-string - #'cape-wrap-nonexclusive #'cape-wrap-noninterruptible - #'cape-wrap-passthrough #'cape-wrap-predicate - #'cape-wrap-prefix-length #'cape-wrap-properties - #'cape-wrap-purify #'cape-wrap-silent #'cape-wrap-super)) - (let ((name (string-remove-prefix "cape-wrap-" (symbol-name wrapper)))) - (defalias (intern (format "cape-capf-%s" name)) - (lambda (capf &rest args) (lambda () (apply wrapper capf args))) - (format "Create a %s Capf from CAPF. -The Capf calls `%s' with CAPF and ARGS as arguments." name wrapper)))) - -(defvar-keymap cape-prefix-map - :doc "Keymap used as completion entry point. -The keymap should be installed globally under a prefix." - "p" #'completion-at-point - "t" #'complete-tag - "d" #'cape-dabbrev - "h" #'cape-history - "f" #'cape-file - "s" #'cape-elisp-symbol - "e" #'cape-elisp-block - "a" #'cape-abbrev - "l" #'cape-line - "w" #'cape-dict - "k" 'cape-keyword - ":" 'cape-emoji - "\\" 'cape-tex - "_" 'cape-tex - "^" 'cape-tex - "&" 'cape-sgml - "r" 'cape-rfc1345) - -;;;###autoload (autoload 'cape-prefix-map "cape" nil t 'keymap) -(defalias 'cape-prefix-map cape-prefix-map) - -(provide 'cape) -;;; cape.el ends here diff --git a/emacs/elpa/cape-20240926.918/cape.elc b/emacs/elpa/cape-20240926.918/cape.elc Binary files differ. diff --git a/emacs/elpa/cape-20241004.614/cape-autoloads.el b/emacs/elpa/cape-20241004.614/cape-autoloads.el @@ -0,0 +1,239 @@ +;;; cape-autoloads.el --- automatically extracted autoloads (do not edit) -*- lexical-binding: t -*- +;; Generated by the `loaddefs-generate' function. + +;; This file is part of GNU Emacs. + +;;; Code: + +(add-to-list 'load-path (or (and load-file-name (directory-file-name (file-name-directory load-file-name))) (car load-path))) + + + +;;; Generated autoloads from cape.el + +(autoload 'cape-history "cape" "\ +Complete from Eshell, Comint or minibuffer history. +See also `consult-history' for a more flexible variant based on +`completing-read'. If INTERACTIVE is nil the function acts like a Capf. + +(fn &optional INTERACTIVE)" t) +(autoload 'cape-file "cape" "\ +Complete file name at point. +See the user option `cape-file-directory-must-exist'. +If INTERACTIVE is nil the function acts like a Capf. + +(fn &optional INTERACTIVE)" t) +(autoload 'cape-elisp-symbol "cape" "\ +Complete Elisp symbol at point. +If INTERACTIVE is nil the function acts like a Capf. + +(fn &optional INTERACTIVE)" t) +(autoload 'cape-elisp-block "cape" "\ +Complete Elisp in Org or Markdown code block. +This Capf is particularly useful for literate Emacs configurations. +If INTERACTIVE is nil the function acts like a Capf. + +(fn &optional INTERACTIVE)" t) +(autoload 'cape-dabbrev "cape" "\ +Complete with Dabbrev at point. + +If INTERACTIVE is nil the function acts like a Capf. In case you +observe a performance issue with auto-completion and `cape-dabbrev' +it is strongly recommended to disable scanning in other buffers. +See the user options `cape-dabbrev-min-length' and +`cape-dabbrev-check-other-buffers'. + +(fn &optional INTERACTIVE)" t) +(autoload 'cape-dict "cape" "\ +Complete word from dictionary at point. +This completion function works best if the dictionary is sorted +by frequency. See the custom option `cape-dict-file'. If +INTERACTIVE is nil the function acts like a Capf. + +(fn &optional INTERACTIVE)" t) +(autoload 'cape-abbrev "cape" "\ +Complete abbreviation at point. +If INTERACTIVE is nil the function acts like a Capf. + +(fn &optional INTERACTIVE)" t) +(autoload 'cape-line "cape" "\ +Complete current line from other lines. +The buffers returned by `cape-line-buffer-function' are scanned for lines. +If INTERACTIVE is nil the function acts like a Capf. + +(fn &optional INTERACTIVE)" t) +(autoload 'cape-company-to-capf "cape" "\ +Convert Company BACKEND function to Capf. +VALID is a function taking the old and new input string. It should +return nil if the cached candidates became invalid. The default value +for VALID is `string-prefix-p' such that the candidates are only fetched +again if the input prefix changed. + +(fn BACKEND &optional VALID)") +(autoload 'cape-interactive "cape" "\ +Complete interactively with the given CAPFS. + +(fn &rest CAPFS)") +(autoload 'cape-capf-interactive "cape" "\ +Create interactive completion function from CAPF. + +(fn CAPF)") +(autoload 'cape-wrap-super "cape" "\ +Call CAPFS and return merged completion result. +The CAPFS list can contain the keyword `:with' to mark the Capfs +afterwards as auxiliary One of the non-auxiliary Capfs before +`:with' must return non-nil for the super Capf to set in and +return a non-nil result. Such behavior is useful when listing +multiple super Capfs in the `completion-at-point-functions': + + (setq completion-at-point-functions + (list (cape-capf-super \\='eglot-completion-at-point + :with \\='tempel-complete) + (cape-capf-super \\='cape-dabbrev + :with \\='tempel-complete))) + +(fn &rest CAPFS)") +(autoload 'cape-wrap-debug "cape" "\ +Call CAPF and return a completion table which prints trace messages. +If CAPF is an anonymous lambda, pass the Capf NAME explicitly for +meaningful debugging output. + +(fn CAPF &optional NAME)") +(autoload 'cape-wrap-buster "cape" "\ +Call CAPF and return a completion table with cache busting. +This function can be used as an advice around an existing Capf. +The cache is busted when the input changes. The argument VALID +can be a function taking the old and new input string. It should +return nil if the new input requires that the completion table is +refreshed. The default value for VALID is `equal', such that the +completion table is refreshed on every input change. + +(fn CAPF &optional VALID)") +(autoload 'cape-wrap-passthrough "cape" "\ +Call CAPF and make sure that no completion style filtering takes place. + +(fn CAPF)") +(autoload 'cape-wrap-properties "cape" "\ +Call CAPF and strip or add completion PROPERTIES. +Completion properties include for example :exclusive, +:annotation-function and the various :company-* extensions. Furthermore +a boolean :sort flag and a completion :category symbol can be specified. +The boolean :strip flag means to strip all completion properties. + +(fn CAPF &rest PROPERTIES)") +(autoload 'cape-wrap-nonexclusive "cape" "\ +Call CAPF and ensure that it is marked as non-exclusive. +This function can be used as an advice around an existing Capf. + +(fn CAPF)") +(autoload 'cape-wrap-predicate "cape" "\ +Call CAPF and add an additional candidate PREDICATE. +The PREDICATE is passed the candidate symbol or string. + +(fn CAPF PREDICATE)") +(autoload 'cape-wrap-silent "cape" "\ +Call CAPF and silence it (no messages, no errors). +This function can be used as an advice around an existing Capf. + +(fn CAPF)") +(autoload 'cape-wrap-case-fold "cape" "\ +Call CAPF and return a case-insensitive completion table. +If NOFOLD is non-nil return a case sensitive table instead. This +function can be used as an advice around an existing Capf. + +(fn CAPF &optional NOFOLD)") +(autoload 'cape-wrap-noninterruptible "cape" "\ +Call CAPF and return a non-interruptible completion table. +This function can be used as an advice around an existing Capf. + +(fn CAPF)") +(autoload 'cape-wrap-prefix-length "cape" "\ +Call CAPF and ensure that prefix length is greater or equal than LENGTH. +If the prefix is long enough, enforce auto completion. + +(fn CAPF LENGTH)") +(autoload 'cape-wrap-inside-faces "cape" "\ +Call CAPF only if inside FACES. +This function can be used as an advice around an existing Capf. + +(fn CAPF &rest FACES)") +(autoload 'cape-wrap-inside-code "cape" "\ +Call CAPF only if inside code, not inside a comment or string. +This function can be used as an advice around an existing Capf. + +(fn CAPF)") +(autoload 'cape-wrap-inside-comment "cape" "\ +Call CAPF only if inside comment. +This function can be used as an advice around an existing Capf. + +(fn CAPF)") +(autoload 'cape-wrap-inside-string "cape" "\ +Call CAPF only if inside string. +This function can be used as an advice around an existing Capf. + +(fn CAPF)") +(autoload 'cape-wrap-purify "cape" "\ +Call CAPF and ensure that it does not illegally modify the buffer. +This function can be used as an advice around an existing +Capf. It has been introduced mainly to fix the broken +`pcomplete-completions-at-point' function in Emacs versions < 29. + +(fn CAPF)") +(autoload 'cape-wrap-accept-all "cape" "\ +Call CAPF and return a completion table which accepts every input. +This function can be used as an advice around an existing Capf. + +(fn CAPF)") + (autoload 'cape-capf-accept-all "cape") + (autoload 'cape-capf-buster "cape") + (autoload 'cape-capf-case-fold "cape") + (autoload 'cape-capf-debug "cape") + (autoload 'cape-capf-inside-code "cape") + (autoload 'cape-capf-inside-comment "cape") + (autoload 'cape-capf-inside-faces "cape") + (autoload 'cape-capf-inside-string "cape") + (autoload 'cape-capf-nonexclusive "cape") + (autoload 'cape-capf-noninterruptible "cape") + (autoload 'cape-capf-passthrough "cape") + (autoload 'cape-capf-predicate "cape") + (autoload 'cape-capf-prefix-length "cape") + (autoload 'cape-capf-properties "cape") + (autoload 'cape-capf-purify "cape") + (autoload 'cape-capf-silent "cape") + (autoload 'cape-capf-super "cape") + (autoload 'cape-prefix-map "cape" nil t 'keymap) +(register-definition-prefixes "cape" '("cape-")) + + +;;; Generated autoloads from cape-char.el + + (autoload 'cape-tex "cape-char" nil t) + (autoload 'cape-sgml "cape-char" nil t) + (autoload 'cape-rfc1345 "cape-char" nil t) + (when (> emacs-major-version 28) (autoload 'cape-emoji "cape-char" nil t)) +(register-definition-prefixes "cape-char" '("cape-char--")) + + +;;; Generated autoloads from cape-keyword.el + +(autoload 'cape-keyword "cape-keyword" "\ +Complete programming language keyword at point. +See the variable `cape-keyword-list'. +If INTERACTIVE is nil the function acts like a capf. + +(fn &optional INTERACTIVE)" t) +(register-definition-prefixes "cape-keyword" '("cape-")) + +;;; End of scraped data + +(provide 'cape-autoloads) + +;; Local Variables: +;; version-control: never +;; no-byte-compile: t +;; no-update-autoloads: t +;; no-native-compile: t +;; coding: utf-8-emacs-unix +;; End: + +;;; cape-autoloads.el ends here diff --git a/emacs/elpa/cape-20240926.918/cape-char.el b/emacs/elpa/cape-20241004.614/cape-char.el diff --git a/emacs/elpa/cape-20240926.918/cape-char.elc b/emacs/elpa/cape-20241004.614/cape-char.elc Binary files differ. diff --git a/emacs/elpa/cape-20240926.918/cape-keyword.el b/emacs/elpa/cape-20241004.614/cape-keyword.el diff --git a/emacs/elpa/cape-20240926.918/cape-keyword.elc b/emacs/elpa/cape-20241004.614/cape-keyword.elc Binary files differ. diff --git a/emacs/elpa/cape-20241004.614/cape-pkg.el b/emacs/elpa/cape-20241004.614/cape-pkg.el @@ -0,0 +1,11 @@ +;; -*- no-byte-compile: t; lexical-binding: nil -*- +(define-package "cape" "20241004.614" + "Completion At Point Extensions." + '((emacs "28.1") + (compat "30")) + :url "https://github.com/minad/cape" + :commit "63ab1490a14f5a6cbfec29eb5af5ffd12ee49180" + :revdesc "63ab1490a14f" + :keywords '("abbrev" "convenience" "matching" "completion" "text") + :authors '(("Daniel Mendler" . "mail@daniel-mendler.de")) + :maintainers '(("Daniel Mendler" . "mail@daniel-mendler.de"))) diff --git a/emacs/elpa/cape-20241004.614/cape.el b/emacs/elpa/cape-20241004.614/cape.el @@ -0,0 +1,1303 @@ +;;; cape.el --- Completion At Point Extensions -*- lexical-binding: t -*- + +;; Copyright (C) 2021-2024 Free Software Foundation, Inc. + +;; Author: Daniel Mendler <mail@daniel-mendler.de> +;; Maintainer: Daniel Mendler <mail@daniel-mendler.de> +;; Created: 2021 +;; Package-Version: 20241004.614 +;; Package-Revision: 63ab1490a14f +;; Package-Requires: ((emacs "28.1") (compat "30")) +;; URL: https://github.com/minad/cape +;; Keywords: abbrev, convenience, matching, completion, text + +;; This file is part of GNU Emacs. + +;; This program is free software: you can redistribute it and/or modify +;; it under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. + +;; This program is distributed in the hope that it will be useful, +;; but WITHOUT ANY WARRANTY; without even the implied warranty of +;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +;; GNU General Public License for more details. + +;; You should have received a copy of the GNU General Public License +;; along with this program. If not, see <https://www.gnu.org/licenses/>. + +;;; Commentary: + +;; Let your completions fly! This package provides additional completion +;; backends in the form of Capfs (completion-at-point-functions). +;; +;; `cape-abbrev': Complete abbreviation (add-global-abbrev, add-mode-abbrev). +;; `cape-dabbrev': Complete word from current buffers. +;; `cape-dict': Complete word from dictionary file. +;; `cape-elisp-block': Complete Elisp in Org or Markdown code block. +;; `cape-elisp-symbol': Complete Elisp symbol. +;; `cape-emoji': Complete Emoji. +;; `cape-file': Complete file name. +;; `cape-history': Complete from Eshell, Comint or minibuffer history. +;; `cape-keyword': Complete programming language keyword. +;; `cape-line': Complete entire line from file. +;; `cape-rfc1345': Complete Unicode char using RFC 1345 mnemonics. +;; `cape-sgml': Complete Unicode char from SGML entity, e.g., &alpha. +;; `cape-tex': Complete Unicode char from TeX command, e.g. \hbar. + +;;; Code: + +(require 'compat) +(eval-when-compile + (require 'cl-lib) + (require 'subr-x)) + +;;;; Customization + +(defgroup cape nil + "Completion At Point Extensions." + :link '(info-link :tag "Info Manual" "(cape)") + :link '(url-link :tag "Website" "https://github.com/minad/cape") + :link '(emacs-library-link :tag "Library Source" "cape.el") + :group 'convenience + :group 'tools + :group 'matching + :prefix "cape-") + +(defcustom cape-dict-limit 100 + "Maximal number of completion candidates returned by `cape-dict'." + :type '(choice (const nil) natnum)) + +(defcustom cape-dict-file "/usr/share/dict/words" + "Path to dictionary word list file. +This variable can also be a list of paths or +a function returning a single or more paths." + :type '(choice string (repeat string) function)) + +(defcustom cape-dict-case-replace 'case-replace + "Preserve case of input. +See `dabbrev-case-replace' for details." + :type '(choice (const :tag "off" nil) + (const :tag "use `case-replace'" case-replace) + (other :tag "on" t))) + +(defcustom cape-dict-case-fold 'case-fold-search + "Case fold search during search. +See `dabbrev-case-fold-search' for details." + :type '(choice (const :tag "off" nil) + (const :tag "use `case-fold-search'" case-fold-search) + (other :tag "on" t))) + +(defcustom cape-dabbrev-min-length 4 + "Minimum length of Dabbrev expansions. +This setting ensures that words which are too short +are not offered as completion candidates, such that +auto completion does not pop up too aggressively." + :type 'natnum) + +(defcustom cape-dabbrev-check-other-buffers t + "Buffers to check for Dabbrev. + +If t, check all other buffers, subject to Dabbrev ignore rules. +If a function, only search the buffers returned by this function. +Any other non-nil value only checks some other buffers, as per +`dabbrev-select-buffers-function'." + :type `(choice (const :tag "off" nil) + (const :tag "same-mode buffers" ,#'cape--buffers-major-mode) + (function :tag "function") + (const :tag "some" some) + (other :tag "all" t))) + +(defcustom cape-file-directory nil + "Base directory used by `cape-file." + :type '(choice (const nil) string function)) + +(defcustom cape-file-prefix "file:" + "File completion trigger prefixes. +The value can be a string or a list of strings. The default +`file:' is the prefix of Org file links which work in arbitrary +buffers via `org-open-at-point-global'." + :type '(choice string (repeat string))) + +(defcustom cape-file-directory-must-exist t + "The parent directory must exist for file completion." + :type 'boolean) + +(defcustom cape-line-buffer-function #'cape--buffers-major-mode + "Function which returns list of buffers. +The buffers are scanned for completion candidates by `cape-line'." + :type '(choice (const :tag "Current buffer" current-buffer) + (const :tag "All buffers" buffer-list) + (const :tag "Buffers with same major mode" cape--buffers-major-mode) + (function :tag "Custom function"))) + +(defcustom cape-elisp-symbol-wrapper + '((org-mode ?~ ?~) + (markdown-mode ?` ?`) + (emacs-lisp-mode ?` ?') + (rst-mode "``" "``") + (log-edit-mode "`" "'") + (change-log-mode "`" "'") + (message-mode "`" "'") + (rcirc-mode "`" "'")) + "Wrapper characters for symbols." + :type '(alist :key-type symbol :value-type (list (choice character string) + (choice character string)))) + +;;;; Helpers + +(defun cape--case-fold-p (fold) + "Return non-nil if case folding is enabled for FOLD." + (if (eq fold 'case-fold-search) case-fold-search fold)) + +(defun cape--case-replace-list (flag input strs) + "Replace case of STRS depending on INPUT and FLAG." + (if (and (if (eq flag 'case-replace) case-replace flag) + (let (case-fold-search) (string-match-p "\\`[[:upper:]]" input))) + (mapcar (apply-partially #'cape--case-replace flag input) strs) + strs)) + +(defun cape--case-replace (flag input str) + "Replace case of STR depending on INPUT and FLAG." + (or (and (if (eq flag 'case-replace) case-replace flag) + (string-prefix-p input str t) + (let (case-fold-search) (string-match-p "\\`[[:upper:]]" input)) + (save-match-data + ;; Ensure that single character uppercase input does not lead to an + ;; all uppercase result. + (when (and (= (length input) 1) (> (length str) 1)) + (setq input (concat input (substring str 1 2)))) + (and (string-match input input) + (replace-match str nil nil input)))) + str)) + +(defun cape--separator-p (str) + "Return non-nil if input STR has a separator character. +Separator characters are used by completion styles like Orderless +to split filter words. In Corfu, the separator is configurable +via the variable `corfu-separator'." + (string-search (string ;; Support `corfu-separator' and Orderless + (or (and (bound-and-true-p corfu-mode) + (bound-and-true-p corfu-separator)) + ?\s)) + str)) + +(defmacro cape--silent (&rest body) + "Silence BODY." + (declare (indent 0)) + `(cl-letf ((inhibit-message t) + (message-log-max nil) + ((symbol-function #'minibuffer-message) #'ignore)) + (ignore-errors ,@body))) + +(defun cape--bounds (thing) + "Return bounds of THING." + (or (bounds-of-thing-at-point thing) (cons (point) (point)))) + +(defmacro cape--wrapped-table (wrap body) + "Create wrapped completion table, handle `completion--unquote'. +WRAP is the wrapper function. +BODY is the wrapping expression." + (declare (indent 1)) + `(lambda (str pred action) + (,@body + (let ((result (complete-with-action action table str pred))) + (when (and (eq action 'completion--unquote) (functionp (cadr result))) + (cl-callf ,wrap (cadr result))) + result)))) + +(defun cape--accept-all-table (table) + "Create completion TABLE which accepts all input." + (cape--wrapped-table cape--accept-all-table + (or (eq action 'lambda)))) + +(defun cape--passthrough-table (table) + "Create completion TABLE disabling any filtering." + (cape--wrapped-table cape--passthrough-table + (let (completion-ignore-case completion-regexp-list (_ (setq str "")))))) + +(defun cape--noninterruptible-table (table) + "Create non-interruptible completion TABLE." + (cape--wrapped-table cape--noninterruptible-table + (let (throw-on-input)))) + +(defun cape--silent-table (table) + "Create a new completion TABLE which is silent (no messages, no errors)." + (cape--wrapped-table cape--silent-table + (cape--silent))) + +(defun cape--nonessential-table (table) + "Mark completion TABLE as `non-essential'." + (let ((dir default-directory)) + (cape--wrapped-table cape--nonessential-table + (let ((default-directory dir) + (non-essential t)))))) + +(defvar cape--debug-length 5 + "Length of printed lists in `cape--debug-print'.") + +(defvar cape--debug-id 0 + "Completion table identifier.") + +(defun cape--debug-message (&rest msg) + "Print debug MSG." + (let ((inhibit-message t)) + (apply #'message msg))) + +(defun cape--debug-print (obj &optional full) + "Print OBJ as string, truncate lists if FULL is nil." + (cond + ((symbolp obj) (symbol-name obj)) + ((functionp obj) "#<function>") + ((proper-list-p obj) + (concat + "(" + (string-join + (mapcar #'cape--debug-print + (if full obj (take cape--debug-length obj))) + " ") + (if (and (not full) (length> obj cape--debug-length)) " ...)" ")"))) + (t (let ((print-level 2)) + (prin1-to-string obj))))) + +(defun cape--debug-table (table name beg end) + "Create completion TABLE with debug messages. +NAME is the name of the Capf, BEG and END are the input markers." + (lambda (str pred action) + (let ((result (complete-with-action action table str pred))) + (if (and (eq action 'completion--unquote) (functionp (cadr result))) + ;; See `cape--wrapped-table' + (cl-callf cape--debug-table (cadr result) name beg end) + (cape--debug-message + "%s(action=%S input=%s:%s:%S prefix=%S ignore-case=%S%s%s) => %s" + name + (pcase action + ('nil 'try) + ('t 'all) + ('lambda 'test) + (_ action)) + (+ beg 0) (+ end 0) (buffer-substring-no-properties beg end) + str completion-ignore-case + (if completion-regexp-list + (format " regexp=%s" (cape--debug-print completion-regexp-list t)) + "") + (if pred + (format " predicate=%s" (cape--debug-print pred)) + "") + (cape--debug-print result))) + result))) + +(cl-defun cape--properties-table (table &key category (sort t) strip &allow-other-keys) + "Create completion TABLE with properties. +CATEGORY is the optional completion category. +SORT should be nil to disable sorting. +STRIP means to strip all metadata." + ;; The metadata will be overridden if the category is non-nil, if the table is + ;; a function table or if sorting should be disabled for a non-nil + ;; non-function table. + (if (or category (functionp table) (and (not sort) table)) + (let ((metadata (and (not strip) + `(metadata + ,@(and category `((category . ,category))) + ,@(and (not sort) '((display-sort-function . identity) + (cycle-sort-function . identity))))))) + (lambda (str pred action) + (if (eq action 'metadata) + metadata + (complete-with-action action table str pred)))) + table)) + +(defun cape--dynamic-table (beg end fun) + "Create dynamic completion table from FUN with caching. +BEG and END are the input bounds. FUN is the function which +computes the candidates. FUN must return a pair of a predicate +function function and the list of candidates. The predicate is +passed new input and must return non-nil if the candidates are +still valid. + +It is only necessary to use this function if the set of +candidates is computed dynamically based on the input and not +statically determined. The behavior is similar but slightly +different to `completion-table-dynamic'. + +The difference to the builtins `completion-table-dynamic' and +`completion-table-with-cache' is that this function does not use +the prefix argument of the completion table to compute the +candidates. Instead it uses the input in the buffer between BEG +and END to FUN to compute the candidates. This way the dynamic +candidate computation is compatible with non-prefix completion +styles like `substring' or `orderless', which pass the empty +string as first argument to the completion table." + (let ((beg (copy-marker beg)) + (end (copy-marker end t)) + valid table) + (lambda (str pred action) + ;; Bail out early for `metadata' and `boundaries'. This is a pointless + ;; move because of caching, but we do it anyway in the hope that the + ;; profiler report looks less confusing, since the weight of the expensive + ;; FUN computation is moved to the `all-completions' action. Computing + ;; `all-completions' must surely be most expensive, so nobody will suspect + ;; a thing. + (unless (or (eq action 'metadata) (eq (car-safe action) 'boundaries)) + (let ((input (buffer-substring-no-properties beg end))) + (unless (and valid + (or (cape--separator-p input) + (funcall valid input))) + (let* (;; Reset in case `all-completions' is used inside FUN + completion-ignore-case completion-regexp-list + ;; Retrieve new state by calling FUN + (new (funcall fun input)) + ;; No interrupt during state update + throw-on-input) + (setq valid (car new) table (cdr new))))) + (complete-with-action action table str pred))))) + +;;;; Capfs + +;;;;; cape-history + +(declare-function ring-elements "ring") +(declare-function eshell-bol "eshell") +(declare-function comint-line-beginning-position "comint") +(defvar eshell-history-ring) +(defvar comint-input-ring) + +(defvar cape--history-properties + (list :company-kind (lambda (_) 'text) + :exclusive 'no) + "Completion extra properties for `cape-history'.") + +;;;###autoload +(defun cape-history (&optional interactive) + "Complete from Eshell, Comint or minibuffer history. +See also `consult-history' for a more flexible variant based on +`completing-read'. If INTERACTIVE is nil the function acts like a Capf." + (interactive (list t)) + (if interactive + (cape-interactive #'cape-history) + (let (history bol) + (cond + ((derived-mode-p 'eshell-mode) + (setq history eshell-history-ring + bol (static-if (< emacs-major-version 30) + (save-excursion (eshell-bol) (point)) + (line-beginning-position)))) + ((derived-mode-p 'comint-mode) + (setq history comint-input-ring + bol (comint-line-beginning-position))) + ((and (minibufferp) (not (eq minibuffer-history-variable t))) + (setq history (symbol-value minibuffer-history-variable) + bol (line-beginning-position)))) + (when (ring-p history) + (setq history (ring-elements history))) + (when history + `(,bol ,(point) + ,(cape--properties-table history :sort nil) + ,@cape--history-properties))))) + +;;;;; cape-file + +(defvar comint-unquote-function) +(defvar comint-requote-function) + +(defvar cape--file-properties + (list :annotation-function (lambda (s) (if (string-suffix-p "/" s) " Dir" " File")) + :company-kind (lambda (s) (if (string-suffix-p "/" s) 'folder 'file)) + :exclusive 'no) + "Completion extra properties for `cape-file'.") + +;;;###autoload +(defun cape-file (&optional interactive) + "Complete file name at point. +See the user option `cape-file-directory-must-exist'. +If INTERACTIVE is nil the function acts like a Capf." + (interactive (list t)) + (if interactive + (cape-interactive '(cape-file-directory-must-exist) #'cape-file) + (pcase-let* ((default-directory (pcase cape-file-directory + ('nil default-directory) + ((pred stringp) cape-file-directory) + (_ (funcall cape-file-directory)))) + (prefix (and cape-file-prefix + (looking-back + (concat + (regexp-opt (ensure-list cape-file-prefix) t) + "[^ \n\t]*") + (pos-bol)) + (match-end 1))) + (`(,beg . ,end) (if prefix + (cons prefix (point)) + (cape--bounds 'filename))) + (non-essential t) + (file (buffer-substring-no-properties beg end))) + (when (or prefix + (not cape-file-directory-must-exist) + (and (string-search "/" file) + (file-exists-p (file-name-directory file)))) + `(,beg ,end + ,(cape--nonessential-table + (if (or (derived-mode-p 'comint-mode) (derived-mode-p 'eshell-mode)) + (completion-table-with-quoting + #'read-file-name-internal + comint-unquote-function + comint-requote-function) + #'read-file-name-internal)) + ,@(when (or prefix (string-match-p "./" file)) + '(:company-prefix-length t)) + ,@cape--file-properties))))) + +;;;;; cape-elisp-symbol + +(autoload 'elisp--company-kind "elisp-mode") +(autoload 'elisp--company-doc-buffer "elisp-mode") +(autoload 'elisp--company-doc-string "elisp-mode") +(autoload 'elisp--company-location "elisp-mode") + +(defvar cape--elisp-symbol-properties + (list :annotation-function #'cape--elisp-symbol-annotation + :exit-function #'cape--elisp-symbol-exit + :predicate #'cape--elisp-symbol-predicate + :company-kind #'elisp--company-kind + :company-doc-buffer #'elisp--company-doc-buffer + :company-docsig #'elisp--company-doc-string + :company-location #'elisp--company-location + :exclusive 'no) + "Completion extra properties for `cape-elisp-symbol'.") + +(defun cape--elisp-symbol-predicate (sym) + "Return t if SYM is bound, fbound or propertized." + (or (fboundp sym) (boundp sym) (symbol-plist sym))) + +(defun cape--elisp-symbol-exit (sym status) + "Wrap symbol SYM with `cape-elisp-symbol-wrapper' buffers. +STATUS is the exit status." + (when-let (((not (eq status 'exact))) + (c (cl-loop for (m . c) in cape-elisp-symbol-wrapper + if (derived-mode-p m) return c)) + ((or (not (derived-mode-p 'emacs-lisp-mode)) + ;; Inside comment or string + (let ((s (syntax-ppss))) (or (nth 3 s) (nth 4 s))))) + (x (if (stringp (car c)) (car c) (string (car c)))) + (y (if (stringp (cadr c)) (cadr c) (string (cadr c))))) + (save-excursion + (backward-char (length sym)) + (unless (save-excursion + (and (ignore-errors (or (backward-char (length x)) t)) + (looking-at-p (regexp-quote x)))) + (insert x))) + (unless (looking-at-p (regexp-quote y)) + (insert y)))) + +(defun cape--elisp-symbol-annotation (sym) + "Return kind of SYM." + (setq sym (intern-soft sym)) + (cond + ((special-form-p sym) " Special") + ((macrop sym) " Macro") + ((commandp sym) " Command") + ((fboundp sym) " Function") + ((custom-variable-p sym) " Custom") + ((boundp sym) " Variable") + ((featurep sym) " Feature") + ((facep sym) " Face") + (t " Symbol"))) + +;;;###autoload +(defun cape-elisp-symbol (&optional interactive) + "Complete Elisp symbol at point. +If INTERACTIVE is nil the function acts like a Capf." + (interactive (list t)) + (if interactive + ;; No cycling since it breaks the :exit-function. + (let (completion-cycle-threshold) + (cape-interactive #'cape-elisp-symbol)) + (pcase-let ((`(,beg . ,end) (cape--bounds 'symbol))) + (when (eq (char-after beg) ?') + (setq beg (1+ beg) end (max beg end))) + `(,beg ,end + ,(cape--properties-table obarray :category 'symbol) + ,@cape--elisp-symbol-properties)))) + +;;;;; cape-elisp-block + +(declare-function org-element-context "org-element") +(declare-function markdown-code-block-lang "ext:markdown-mode") + +(defun cape--inside-block-p (&rest langs) + "Return non-nil if inside LANGS code block." + (when-let ((face (get-text-property (point) 'face)) + (lang (or (and (if (listp face) + (memq 'org-block face) + (eq 'org-block face)) + (plist-get (cadr (org-element-context)) :language)) + (and (if (listp face) + (memq 'markdown-code-face face) + (eq 'markdown-code-face face)) + (save-excursion + (markdown-code-block-lang)))))) + (member lang langs))) + +;;;###autoload +(defun cape-elisp-block (&optional interactive) + "Complete Elisp in Org or Markdown code block. +This Capf is particularly useful for literate Emacs configurations. +If INTERACTIVE is nil the function acts like a Capf." + (interactive (list t)) + (cond + (interactive + ;; No code block check. Always complete Elisp when command was + ;; explicitly invoked interactively. + (cape-interactive #'elisp-completion-at-point)) + ((cape--inside-block-p "elisp" "emacs-lisp") + (elisp-completion-at-point)))) + +;;;;; cape-dabbrev + +(defvar cape--dabbrev-properties + (list :annotation-function (lambda (_) " Dabbrev") + :company-kind (lambda (_) 'text) + :exclusive 'no) + "Completion extra properties for `cape-dabbrev'.") + +(defvar dabbrev-case-replace) +(defvar dabbrev-case-fold-search) +(defvar dabbrev-abbrev-char-regexp) +(defvar dabbrev-abbrev-skip-leading-regexp) +(declare-function dabbrev--find-all-expansions "dabbrev") +(declare-function dabbrev--reset-global-variables "dabbrev") + +(defun cape--dabbrev-list (input) + "Find all Dabbrev expansions for INPUT." + (cape--silent + (let* ((chk cape-dabbrev-check-other-buffers) + (funp (and (not (memq chk '(nil t some))) (functionp chk)))) + (dlet ((dabbrev-check-other-buffers (and chk (not funp))) + (dabbrev-check-all-buffers (eq chk t)) + (dabbrev-search-these-buffers-only (and funp (funcall chk)))) + (dabbrev--reset-global-variables) + (cons + (apply-partially #'string-prefix-p input) + (cl-loop with min-len = (+ cape-dabbrev-min-length (length input)) + with ic = (cape--case-fold-p dabbrev-case-fold-search) + for w in (dabbrev--find-all-expansions input ic) + if (>= (length w) min-len) collect + (cape--case-replace (and ic dabbrev-case-replace) input w))))))) + +(defun cape--dabbrev-bounds () + "Return bounds of abbreviation." + (unless (boundp 'dabbrev-abbrev-char-regexp) + (require 'dabbrev)) + (let ((re (or dabbrev-abbrev-char-regexp "\\sw\\|\\s_")) + (limit (minibuffer-prompt-end))) + (when (or (looking-at re) + (and (> (point) limit) + (save-excursion (forward-char -1) (looking-at re)))) + (cons (save-excursion + (while (and (> (point) limit) + (save-excursion (forward-char -1) (looking-at re))) + (forward-char -1)) + (when dabbrev-abbrev-skip-leading-regexp + (while (looking-at dabbrev-abbrev-skip-leading-regexp) + (forward-char 1))) + (point)) + (save-excursion + (while (looking-at re) + (forward-char 1)) + (point)))))) + +;;;###autoload +(defun cape-dabbrev (&optional interactive) + "Complete with Dabbrev at point. + +If INTERACTIVE is nil the function acts like a Capf. In case you +observe a performance issue with auto-completion and `cape-dabbrev' +it is strongly recommended to disable scanning in other buffers. +See the user options `cape-dabbrev-min-length' and +`cape-dabbrev-check-other-buffers'." + (interactive (list t)) + (if interactive + (cape-interactive '((cape-dabbrev-min-length 0)) #'cape-dabbrev) + (when-let ((bounds (cape--dabbrev-bounds))) + `(,(car bounds) ,(cdr bounds) + ,(cape--properties-table + (completion-table-case-fold + (cape--dynamic-table (car bounds) (cdr bounds) #'cape--dabbrev-list) + (not (cape--case-fold-p dabbrev-case-fold-search))) + :category 'cape-dabbrev) + ,@cape--dabbrev-properties)))) + +;;;;; cape-dict + +(defvar cape--dict-properties + (list :annotation-function (lambda (_) " Dict") + :company-kind (lambda (_) 'text) + :exclusive 'no) + "Completion extra properties for `cape-dict'.") + +(defun cape--dict-list (input) + "Return all words from `cape-dict-file' matching INPUT." + (unless (equal input "") + (let* ((inhibit-message t) + (message-log-max nil) + (default-directory + (if (and (not (file-remote-p default-directory)) + (file-directory-p default-directory)) + default-directory + user-emacs-directory)) + (files (mapcar #'expand-file-name + (ensure-list + (if (functionp cape-dict-file) + (funcall cape-dict-file) + cape-dict-file)))) + (words + (apply #'process-lines-ignore-status + "grep" + (concat "-Fh" + (and (cape--case-fold-p cape-dict-case-fold) "i") + (and cape-dict-limit (format "m%d" cape-dict-limit))) + input files))) + (cons + (apply-partially + (if (and cape-dict-limit (length= words cape-dict-limit)) + #'equal #'string-search) + input) + (cape--case-replace-list cape-dict-case-replace input words))))) + +;;;###autoload +(defun cape-dict (&optional interactive) + "Complete word from dictionary at point. +This completion function works best if the dictionary is sorted +by frequency. See the custom option `cape-dict-file'. If +INTERACTIVE is nil the function acts like a Capf." + (interactive (list t)) + (if interactive + (cape-interactive #'cape-dict) + (pcase-let ((`(,beg . ,end) (cape--bounds 'word))) + `(,beg ,end + ,(cape--properties-table + (completion-table-case-fold + (cape--dynamic-table beg end #'cape--dict-list) + (not (cape--case-fold-p cape-dict-case-fold))) + :sort nil ;; Presorted word list (by frequency) + :category 'cape-dict) + ,@cape--dict-properties)))) + +;;;;; cape-abbrev + +(defun cape--abbrev-list () + "Abbreviation list." + (delete "" (cl-loop for x in (abbrev--suggest-get-active-tables-including-parents) + nconc (all-completions "" x)))) + +(defun cape--abbrev-annotation (abbrev) + "Annotate ABBREV with expansion." + (concat " " + (truncate-string-to-width + (format + "%s" + (symbol-value + (cl-loop for x in (abbrev--suggest-get-active-tables-including-parents) + thereis (abbrev--symbol abbrev x)))) + 30 0 nil t))) + +(defun cape--abbrev-exit (_str status) + "Expand expansion if STATUS is not exact." + (unless (eq status 'exact) + (expand-abbrev))) + +(defvar cape--abbrev-properties + (list :annotation-function #'cape--abbrev-annotation + :exit-function #'cape--abbrev-exit + :company-kind (lambda (_) 'snippet) + :exclusive 'no) + "Completion extra properties for `cape-abbrev'.") + +;;;###autoload +(defun cape-abbrev (&optional interactive) + "Complete abbreviation at point. +If INTERACTIVE is nil the function acts like a Capf." + (interactive (list t)) + (if interactive + ;; No cycling since it breaks the :exit-function. + (let (completion-cycle-threshold) + (cape-interactive #'cape-abbrev)) + (when-let (abbrevs (cape--abbrev-list)) + (let ((bounds (cape--bounds 'symbol))) + `(,(car bounds) ,(cdr bounds) + ,(cape--properties-table abbrevs :category 'cape-abbrev) + ,@cape--abbrev-properties))))) + +;;;;; cape-line + +(defvar cape--line-properties nil + "Completion extra properties for `cape-line'.") + +(defun cape--buffers-major-mode () + "Return buffers with same major mode as current buffer." + (cl-loop for buf in (buffer-list) + if (eq major-mode (buffer-local-value 'major-mode buf)) + collect buf)) + +(defun cape--line-list () + "Return all lines from buffer." + (let ((ht (make-hash-table :test #'equal)) + (curr-buf (current-buffer)) + (buffers (funcall cape-line-buffer-function)) + lines) + (dolist (buf (ensure-list buffers)) + (with-current-buffer buf + (let ((beg (point-min)) + (max (point-max)) + (pt (if (eq curr-buf buf) (point) -1)) + end) + (save-excursion + (while (< beg max) + (goto-char beg) + (setq end (pos-eol)) + (unless (<= beg pt end) + (let ((line (buffer-substring-no-properties beg end))) + (unless (or (string-blank-p line) (gethash line ht)) + (puthash line t ht) + (push line lines)))) + (setq beg (1+ end))))))) + (nreverse lines))) + +;;;###autoload +(defun cape-line (&optional interactive) + "Complete current line from other lines. +The buffers returned by `cape-line-buffer-function' are scanned for lines. +If INTERACTIVE is nil the function acts like a Capf." + (interactive (list t)) + (if interactive + (cape-interactive #'cape-line) + `(,(pos-bol) ,(point) + ,(cape--properties-table (cape--line-list) :sort nil) + ,@cape--line-properties))) + +;;;; Capf combinators + +(defun cape--company-call (&rest app) + "Apply APP and handle future return values." + ;; Backends are non-interruptible. Disable interrupts! + (let ((toi throw-on-input) + (throw-on-input nil)) + (pcase (apply app) + ;; Handle async future return values. + (`(:async . ,fetch) + (let ((res 'cape--waiting)) + (if toi + (unwind-protect + (progn + (funcall fetch + (lambda (arg) + (when (eq res 'cape--waiting) + (push 'cape--done unread-command-events) + (setq res arg)))) + (when (eq res 'cape--waiting) + (let ((ev (let ((input-method-function nil) + (echo-keystrokes 0)) + (read-event nil t)))) + (unless (eq ev 'cape--done) + (push (cons t ev) unread-command-events) + (setq res 'cape--cancelled) + (throw toi t))))) + (setq unread-command-events + (delq 'cape--done unread-command-events))) + (funcall fetch (lambda (arg) (setq res arg))) + ;; Force synchronization, not interruptible! We use polling + ;; here and ignore pending input since we don't use + ;; `sit-for'. This is the same method used by Company itself. + (while (eq res 'cape--waiting) + (sleep-for 0.01))) + res)) + ;; Plain old synchronous return value. + (res res)))) + +(defvar-local cape--company-init nil) + +;;;###autoload +(defun cape-company-to-capf (backend &optional valid) + "Convert Company BACKEND function to Capf. +VALID is a function taking the old and new input string. It should +return nil if the cached candidates became invalid. The default value +for VALID is `string-prefix-p' such that the candidates are only fetched +again if the input prefix changed." + (lambda () + (when (and (symbolp backend) (not (fboundp backend))) + (ignore-errors (require backend nil t))) + (when (bound-and-true-p company-mode) + (error "`cape-company-to-capf' should not be used with `company-mode', use the Company backend directly instead")) + (when (and (symbolp backend) (not (alist-get backend cape--company-init))) + (funcall backend 'init) + (put backend 'company-init t) + (setf (alist-get backend cape--company-init) t)) + (when-let ((prefix (cape--company-call backend 'prefix)) + (initial-input (if (stringp prefix) prefix (car-safe prefix)))) + (let* ((end (point)) (beg (- end (length initial-input))) + (valid (if (cape--company-call backend 'no-cache initial-input) + #'equal (or valid #'string-prefix-p))) + restore-props) + (list beg end + (funcall + (if (cape--company-call backend 'ignore-case) + #'completion-table-case-fold + #'identity) + (cape--properties-table + (cape--dynamic-table + beg end + (lambda (input) + (let ((cands (cape--company-call backend 'candidates input))) + ;; The candidate string including text properties should be + ;; restored in the :exit-function, unless the UI guarantees + ;; this itself, like Corfu. + (unless (bound-and-true-p corfu-mode) + (setq restore-props cands)) + (cons (apply-partially valid input) cands)))) + :category backend + :sort (not (cape--company-call backend 'sorted)))) + :exclusive 'no + :company-prefix-length (cdr-safe prefix) + :company-doc-buffer (lambda (x) (cape--company-call backend 'doc-buffer x)) + :company-location (lambda (x) (cape--company-call backend 'location x)) + :company-docsig (lambda (x) (cape--company-call backend 'meta x)) + :company-deprecated (lambda (x) (cape--company-call backend 'deprecated x)) + :company-kind (lambda (x) (cape--company-call backend 'kind x)) + :annotation-function (lambda (x) + (when-let (ann (cape--company-call backend 'annotation x)) + (concat " " (string-trim ann)))) + :exit-function (lambda (x _status) + ;; Restore the candidate string including + ;; properties if restore-props is non-nil. See + ;; the comment above. + (setq x (or (car (member x restore-props)) x)) + (cape--company-call backend 'post-completion x))))))) + +;;;###autoload +(defun cape-interactive (&rest capfs) + "Complete interactively with the given CAPFS." + (let* ((ctx (and (consp (car capfs)) (car capfs))) + (capfs (if ctx (cdr capfs) capfs)) + (completion-at-point-functions + (if ctx + (mapcar (lambda (f) `(lambda () (let ,ctx (funcall ',f)))) capfs) + capfs))) + (unless (completion-at-point) + (user-error "%s: No completions" + (mapconcat (lambda (fun) + (if (symbolp fun) + (symbol-name fun) + "anonymous-capf")) + capfs ", "))))) + +;;;###autoload +(defun cape-capf-interactive (capf) + "Create interactive completion function from CAPF." + (lambda (&optional interactive) + (interactive (list t)) + (if interactive (cape-interactive capf) (funcall capf)))) + +;;;###autoload +(defun cape-wrap-super (&rest capfs) + "Call CAPFS and return merged completion result. +The CAPFS list can contain the keyword `:with' to mark the Capfs +afterwards as auxiliary One of the non-auxiliary Capfs before +`:with' must return non-nil for the super Capf to set in and +return a non-nil result. Such behavior is useful when listing +multiple super Capfs in the `completion-at-point-functions': + + (setq completion-at-point-functions + (list (cape-capf-super \\='eglot-completion-at-point + :with \\='tempel-complete) + (cape-capf-super \\='cape-dabbrev + :with \\='tempel-complete)))" + (when-let ((results (cl-loop for capf in capfs until (eq capf :with) + for res = (funcall capf) + if res collect (cons t res)))) + (pcase-let* ((results (nconc results + (cl-loop for capf in (cdr (memq :with capfs)) + for res = (funcall capf) + if res collect (cons nil res)))) + (`((,_main ,beg ,end . ,_)) results) + (cand-ht nil) + (tables nil) + (exclusive nil) + (prefix-len nil) + (cand-functions + '(:company-docsig :company-location :company-kind + :company-doc-buffer :company-deprecated + :annotation-function :exit-function))) + (cl-loop for (main beg2 end2 table . plist) in results do + ;; Note: `cape-capf-super' currently cannot merge Capfs which + ;; trigger at different beginning positions. In order to support + ;; this, take the smallest BEG value and then normalize all + ;; candidates by prefixing them such that they all start at the + ;; smallest BEG position. + (when (= beg beg2) + (push (list main (plist-get plist :predicate) table + ;; Plist attached to the candidates + (mapcan (lambda (f) + (when-let ((v (plist-get plist f))) + (list f v))) + cand-functions)) + tables) + ;; The resulting merged Capf is exclusive if one of the main + ;; Capfs is exclusive. + (when (and main (not (eq (plist-get plist :exclusive) 'no))) + (setq exclusive t)) + (setq end (max end end2)) + (let ((plen (plist-get plist :company-prefix-length))) + (cond + ((eq plen t) + (setq prefix-len t)) + ((and (not prefix-len) (integerp plen)) + (setq prefix-len plen)) + ((and (integerp prefix-len) (integerp plen)) + (setq prefix-len (max prefix-len plen))))))) + (setq tables (nreverse tables)) + `(,beg ,end + ,(lambda (str pred action) + (pcase action + (`(boundaries . ,_) nil) + ('metadata + '(metadata (category . cape-super) + (display-sort-function . identity) + (cycle-sort-function . identity))) + ('t ;; all-completions + (let ((ht (make-hash-table :test #'equal)) + (candidates nil)) + (cl-loop for (main table-pred table cand-plist) in tables do + (let* ((pr (if (and table-pred pred) + (lambda (x) (and (funcall table-pred x) (funcall pred x))) + (or table-pred pred))) + (md (completion-metadata "" table pr)) + (sort (or (completion-metadata-get md 'display-sort-function) + #'identity)) + ;; Always compute candidates of the main Capf + ;; tables, which come first in the tables + ;; list. For the :with Capfs only compute + ;; candidates if we've already determined that + ;; main candidates are available. + (cands (when (or main (or exclusive cand-ht candidates)) + (funcall sort (all-completions str table pr))))) + ;; Handle duplicates with a hash table. + (cl-loop + for cand in-ref cands + for dup = (gethash cand ht t) do + (cond + ((eq dup t) + ;; Candidate does not yet exist. + (puthash cand cand-plist ht)) + ((not (equal dup cand-plist)) + ;; Duplicate candidate. Candidate plist is + ;; different, therefore disambiguate the + ;; candidates. + (setf cand (propertize cand 'cape-capf-super + (cons cand cand-plist)))))) + (when cands (push cands candidates)))) + (when (or cand-ht candidates) + (setq candidates (apply #'nconc (nreverse candidates)) + cand-ht ht) + candidates))) + (_ ;; try-completion and test-completion + (cl-loop for (_main table-pred table _cand-plist) in tables thereis + (complete-with-action + action table str + (if (and table-pred pred) + (lambda (x) (and (funcall table-pred x) (funcall pred x))) + (or table-pred pred))))))) + :company-prefix-length ,prefix-len + ,@(and (not exclusive) '(:exclusive no)) + ,@(mapcan + (lambda (prop) + (list prop + (lambda (cand &rest args) + (if-let ((ref (get-text-property 0 'cape-capf-super cand))) + (when-let ((fun (plist-get (cdr ref) prop))) + (apply fun (car ref) args)) + (when-let ((plist (and cand-ht (gethash cand cand-ht))) + (fun (plist-get plist prop))) + (apply fun cand args)))))) + cand-functions))))) + +;;;###autoload +(defun cape-wrap-debug (capf &optional name) + "Call CAPF and return a completion table which prints trace messages. +If CAPF is an anonymous lambda, pass the Capf NAME explicitly for +meaningful debugging output." + (unless name + (setq name (if (symbolp capf) capf "capf"))) + (setq name (format "%s@%s" name (cl-incf cape--debug-id))) + (pcase (funcall capf) + (`(,beg ,end ,table . ,plist) + (let* ((limit (1+ cape--debug-length)) + (pred (plist-get plist :predicate)) + (cands + ;; Reset regexps for `all-completions' + (let (completion-ignore-case completion-regexp-list) + (all-completions + "" table + (lambda (&rest args) + (and (or (not pred) (apply pred args)) (>= (cl-decf limit) 0)))))) + (plist-str "") + (plist-elt plist)) + (while (cdr plist-elt) + (setq plist-str (format "%s %s=%s" plist-str + (substring (symbol-name (car plist-elt)) 1) + (cape--debug-print (cadr plist-elt))) + plist-elt (cddr plist-elt))) + (cape--debug-message + "%s => input=%s:%s:%S table=%s%s" + name (+ beg 0) (+ end 0) (buffer-substring-no-properties beg end) + (cape--debug-print cands) + plist-str)) + `(,beg ,end ,(cape--debug-table + table name (copy-marker beg) (copy-marker end t)) + ,@(when-let ((exit (plist-get plist :exit-function))) + (list :exit-function + (lambda (cand status) + (cape--debug-message "%s:exit(candidate=%S status=%s)" + name cand status) + (funcall exit cand status)))) + . ,plist)) + (result + (cape--debug-message "%s() => %s (No completion)" + name (cape--debug-print result))))) + +;;;###autoload +(defun cape-wrap-buster (capf &optional valid) + "Call CAPF and return a completion table with cache busting. +This function can be used as an advice around an existing Capf. +The cache is busted when the input changes. The argument VALID +can be a function taking the old and new input string. It should +return nil if the new input requires that the completion table is +refreshed. The default value for VALID is `equal', such that the +completion table is refreshed on every input change." + (setq valid (or valid #'equal)) + (pcase (funcall capf) + (`(,beg ,end ,table . ,plist) + (setq plist `(:cape--buster t . ,plist)) + `(,beg ,end + ,(let* ((beg (copy-marker beg)) + (end (copy-marker end t)) + (input (buffer-substring-no-properties beg end))) + (lambda (str pred action) + (let ((new-input (buffer-substring-no-properties beg end))) + (unless (or (not (eq action t)) + (cape--separator-p new-input) + (funcall valid input new-input)) + (pcase + ;; Reset in case `all-completions' is used inside CAPF + (let (completion-ignore-case completion-regexp-list) + (funcall capf)) + ((and `(,new-beg ,new-end ,new-table . ,new-plist) + (guard (and (= beg new-beg) (= end new-end)))) + (let (throw-on-input) ;; No interrupt during state update + (setf table new-table + input new-input + (cddr plist) new-plist)))))) + (complete-with-action action table str pred))) + ,@plist)))) + +;;;###autoload +(defun cape-wrap-passthrough (capf) + "Call CAPF and make sure that no completion style filtering takes place." + (pcase (funcall capf) + (`(,beg ,end ,table . ,plist) + `(,beg ,end ,(cape--passthrough-table table) ,@plist)))) + +;;;###autoload +(defun cape-wrap-properties (capf &rest properties) + "Call CAPF and strip or add completion PROPERTIES. +Completion properties include for example :exclusive, +:annotation-function and the various :company-* extensions. Furthermore +a boolean :sort flag and a completion :category symbol can be specified. +The boolean :strip flag means to strip all completion properties." + (pcase (funcall capf) + (`(,beg ,end ,table . ,plist) + `(,beg ,end + ,(apply #'cape--properties-table table properties) + ,@(and (not (plist-get properties :strip)) + (append properties plist)))))) + +;;;###autoload +(defun cape-wrap-nonexclusive (capf) + "Call CAPF and ensure that it is marked as non-exclusive. +This function can be used as an advice around an existing Capf." + (cape-wrap-properties capf :exclusive 'no)) + +;;;###autoload +(defun cape-wrap-predicate (capf predicate) + "Call CAPF and add an additional candidate PREDICATE. +The PREDICATE is passed the candidate symbol or string." + (pcase (funcall capf) + (`(,beg ,end ,table . ,plist) + `(,beg ,end ,table + :predicate + ,(if-let (pred (plist-get plist :predicate)) + ;; First argument is key, second is value for hash tables. + ;; The first argument can be a cons cell for alists. Then + ;; the candidate itself is either a string or a symbol. We + ;; normalize the calling convention here such that PREDICATE + ;; always receives a string or a symbol. + (lambda (&rest args) + (when (apply pred args) + (setq args (car args)) + (funcall predicate (if (consp args) (car args) args)))) + (lambda (key &optional _val) + (funcall predicate (if (consp key) (car key) key)))) + ,@plist)))) + +;;;###autoload +(defun cape-wrap-silent (capf) + "Call CAPF and silence it (no messages, no errors). +This function can be used as an advice around an existing Capf." + (pcase (cape--silent (funcall capf)) + (`(,beg ,end ,table . ,plist) + `(,beg ,end ,(cape--silent-table table) ,@plist)))) + +;;;###autoload +(defun cape-wrap-case-fold (capf &optional nofold) + "Call CAPF and return a case-insensitive completion table. +If NOFOLD is non-nil return a case sensitive table instead. This +function can be used as an advice around an existing Capf." + (pcase (funcall capf) + (`(,beg ,end ,table . ,plist) + `(,beg ,end ,(completion-table-case-fold table nofold) ,@plist)))) + +;;;###autoload +(defun cape-wrap-noninterruptible (capf) + "Call CAPF and return a non-interruptible completion table. +This function can be used as an advice around an existing Capf." + (pcase (let (throw-on-input) (funcall capf)) + (`(,beg ,end ,table . ,plist) + `(,beg ,end ,(cape--noninterruptible-table table) ,@plist)))) + +;;;###autoload +(defun cape-wrap-prefix-length (capf length) + "Call CAPF and ensure that prefix length is greater or equal than LENGTH. +If the prefix is long enough, enforce auto completion." + (pcase (funcall capf) + (`(,beg ,end ,table . ,plist) + (when (>= (- end beg) length) + `(,beg ,end ,table + :company-prefix-length t + ,@plist))))) + +;;;###autoload +(defun cape-wrap-inside-faces (capf &rest faces) + "Call CAPF only if inside FACES. +This function can be used as an advice around an existing Capf." + (when-let (((> (point) (point-min))) + (fs (get-text-property (1- (point)) 'face)) + ((if (listp fs) + (cl-loop for f in fs thereis (memq f faces)) + (memq fs faces)))) + (funcall capf))) + +;;;###autoload +(defun cape-wrap-inside-code (capf) + "Call CAPF only if inside code, not inside a comment or string. +This function can be used as an advice around an existing Capf." + (let ((s (syntax-ppss))) + (and (not (nth 3 s)) (not (nth 4 s)) (funcall capf)))) + +;;;###autoload +(defun cape-wrap-inside-comment (capf) + "Call CAPF only if inside comment. +This function can be used as an advice around an existing Capf." + (and (nth 4 (syntax-ppss)) (funcall capf))) + +;;;###autoload +(defun cape-wrap-inside-string (capf) + "Call CAPF only if inside string. +This function can be used as an advice around an existing Capf." + (and (nth 3 (syntax-ppss)) (funcall capf))) + +;;;###autoload +(defun cape-wrap-purify (capf) + "Call CAPF and ensure that it does not illegally modify the buffer. +This function can be used as an advice around an existing +Capf. It has been introduced mainly to fix the broken +`pcomplete-completions-at-point' function in Emacs versions < 29." + ;; bug#50470: Fix Capfs which illegally modify the buffer or which illegally + ;; call `completion-in-region'. The workaround here was proposed by + ;; @jakanakaevangeli and is used in his capf-autosuggest package. In Emacs 29 + ;; the purity bug of Pcomplete has been fixed, such that make + ;; `cape-wrap-purify' is not necessary anymore. + (catch 'cape--illegal-completion-in-region + (condition-case nil + (let ((buffer-read-only t) + (inhibit-read-only nil) + (completion-in-region-function + (lambda (beg end coll pred) + (throw 'cape--illegal-completion-in-region + (list beg end coll :predicate pred))))) + (funcall capf)) + (buffer-read-only nil)))) + +;;;###autoload +(defun cape-wrap-accept-all (capf) + "Call CAPF and return a completion table which accepts every input. +This function can be used as an advice around an existing Capf." + (pcase (funcall capf) + (`(,beg ,end ,table . ,plist) + `(,beg ,end ,(cape--accept-all-table table) . ,plist)))) + +;;;###autoload (autoload 'cape-capf-accept-all "cape") +;;;###autoload (autoload 'cape-capf-buster "cape") +;;;###autoload (autoload 'cape-capf-case-fold "cape") +;;;###autoload (autoload 'cape-capf-debug "cape") +;;;###autoload (autoload 'cape-capf-inside-code "cape") +;;;###autoload (autoload 'cape-capf-inside-comment "cape") +;;;###autoload (autoload 'cape-capf-inside-faces "cape") +;;;###autoload (autoload 'cape-capf-inside-string "cape") +;;;###autoload (autoload 'cape-capf-nonexclusive "cape") +;;;###autoload (autoload 'cape-capf-noninterruptible "cape") +;;;###autoload (autoload 'cape-capf-passthrough "cape") +;;;###autoload (autoload 'cape-capf-predicate "cape") +;;;###autoload (autoload 'cape-capf-prefix-length "cape") +;;;###autoload (autoload 'cape-capf-properties "cape") +;;;###autoload (autoload 'cape-capf-purify "cape") +;;;###autoload (autoload 'cape-capf-silent "cape") +;;;###autoload (autoload 'cape-capf-super "cape") + +(dolist (wrapper (list #'cape-wrap-accept-all #'cape-wrap-buster + #'cape-wrap-case-fold #'cape-wrap-debug + #'cape-wrap-inside-code #'cape-wrap-inside-comment + #'cape-wrap-inside-faces #'cape-wrap-inside-string + #'cape-wrap-nonexclusive #'cape-wrap-noninterruptible + #'cape-wrap-passthrough #'cape-wrap-predicate + #'cape-wrap-prefix-length #'cape-wrap-properties + #'cape-wrap-purify #'cape-wrap-silent #'cape-wrap-super)) + (let ((name (string-remove-prefix "cape-wrap-" (symbol-name wrapper)))) + (defalias (intern (format "cape-capf-%s" name)) + (lambda (capf &rest args) (lambda () (apply wrapper capf args))) + (format "Create a %s Capf from CAPF. +The Capf calls `%s' with CAPF and ARGS as arguments." name wrapper)))) + +(defvar-keymap cape-prefix-map + :doc "Keymap used as completion entry point. +The keymap should be installed globally under a prefix." + "p" #'completion-at-point + "t" #'complete-tag + "d" #'cape-dabbrev + "h" #'cape-history + "f" #'cape-file + "s" #'cape-elisp-symbol + "e" #'cape-elisp-block + "a" #'cape-abbrev + "l" #'cape-line + "w" #'cape-dict + "k" 'cape-keyword + ":" 'cape-emoji + "\\" 'cape-tex + "_" 'cape-tex + "^" 'cape-tex + "&" 'cape-sgml + "r" 'cape-rfc1345) + +;;;###autoload (autoload 'cape-prefix-map "cape" nil t 'keymap) +(defalias 'cape-prefix-map cape-prefix-map) + +(provide 'cape) +;;; cape.el ends here diff --git a/emacs/elpa/cape-20241004.614/cape.elc b/emacs/elpa/cape-20241004.614/cape.elc Binary files differ. diff --git a/emacs/elpa/embark-20240919.1831/embark-pkg.el b/emacs/elpa/embark-20240919.1831/embark-pkg.el @@ -1,11 +0,0 @@ -;; -*- no-byte-compile: t; lexical-binding: nil -*- -(define-package "embark" "20240919.1831" - "Conveniently act on minibuffer completions." - '((emacs "28.1") - (compat "30")) - :url "https://github.com/oantolin/embark" - :commit "718f0f293440b2d5e951c6c4a88ee548180af016" - :revdesc "718f0f293440" - :keywords '("convenience") - :authors '(("Omar Antolín Camarena" . "omar@matem.unam.mx")) - :maintainers '(("Omar Antolín Camarena" . "omar@matem.unam.mx"))) diff --git a/emacs/elpa/embark-20240919.1831/embark.el b/emacs/elpa/embark-20240919.1831/embark.el @@ -1,4592 +0,0 @@ -;;; embark.el --- Conveniently act on minibuffer completions -*- lexical-binding: t; -*- - -;; Copyright (C) 2021-2023 Free Software Foundation, Inc. - -;; Author: Omar Antolín Camarena <omar@matem.unam.mx> -;; Maintainer: Omar Antolín Camarena <omar@matem.unam.mx> -;; Keywords: convenience -;; Package-Version: 20240919.1831 -;; Package-Revision: 718f0f293440 -;; Homepage: https://github.com/oantolin/embark -;; Package-Requires: ((emacs "28.1") (compat "30")) - -;; This file is part of GNU Emacs. - -;; This program is free software; you can redistribute it and/or modify -;; it under the terms of the GNU General Public License as published by -;; the Free Software Foundation, either version 3 of the License, or -;; (at your option) any later version. - -;; This program is distributed in the hope that it will be useful, -;; but WITHOUT ANY WARRANTY; without even the implied warranty of -;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -;; GNU General Public License for more details. - -;; You should have received a copy of the GNU General Public License -;; along with this program. If not, see <https://www.gnu.org/licenses/>. - -;;; Commentary: - -;; This package provides a sort of right-click contextual menu for -;; Emacs, accessed through the `embark-act' command (which you should -;; bind to a convenient key), offering you relevant actions to use on -;; a target determined by the context: - -;; - In the minibuffer, the target is the current best completion -;; candidate. -;; - In the `*Completions*' buffer the target is the completion at point. -;; - In a regular buffer, the target is the region if active, or else the -;; file, symbol or url at point. - -;; The type of actions offered depend on the type of the target: - -;; - For files you get offered actions like deleting, copying, -;; renaming, visiting in another window, running a shell command on the -;; file, etc. -;; - For buffers the actions include switching to or killing the buffer. -;; - For package names the actions include installing, removing or -;; visiting the homepage. - -;; Everything is easily configurable: determining the current target, -;; classifying it, and deciding with actions are offered for each type -;; in the classification. The above introduction just mentions part of -;; the default configuration. - -;; Configuring which actions are offered for a type is particularly -;; easy and requires no programming: the `embark-keymap-alist' -;; variable associates target types with variable containing keymaps, -;; and those keymaps containing binds for the actions. For example, -;; in the default configuration the type `file' is associated with the -;; symbol `embark-file-map'. That symbol names a keymap with -;; single-letter key bindings for common Emacs file commands, for -;; instance `c' is bound to `copy-file'. This means that if while you -;; are in the minibuffer after running a command that prompts for a -;; file, such as `find-file' or `rename-file', you can copy a file by -;; running `embark-act' and then pressing `c'. - -;; These action keymaps are very convenient but not strictly necessary -;; when using `embark-act': you can use any command that reads from the -;; minibuffer as an action and the target of the action will be inserted -;; at the first minibuffer prompt. After running `embark-act' all of your -;; key bindings and even `execute-extended-command' can be used to run a -;; command. The action keymaps are normal Emacs keymaps and you should -;; feel free to bind in them whatever commands you find useful as actions. - -;; The actions in `embark-general-map' are available no matter what -;; type of completion you are in the middle of. By default this -;; includes bindings to save the current candidate in the kill ring -;; and to insert the current candidate in the previously selected -;; buffer (the buffer that was current when you executed a command -;; that opened up the minibuffer). - -;; You can read about the Embark GitHub project wiki: -;; https://github.com/oantolin/embark/wiki/Default-Actions - -;; Besides acting individually on targets, Embark lets you work -;; collectively on a set of target candidates. For example, while -;; you are in the minibuffer the candidates are simply the possible -;; completions of your input. Embark provides three commands to work -;; on candidate sets: - -;; - The `embark-act-all' command runs the same action on each of the -;; current candidates. It is just like using `embark-act' on each -;; candidate in turn. - -;; - The `embark-collect' command produces a buffer listing all -;; candidates, for you to peruse and run actions on at your leisure. -;; The candidates are displayed as a list showing additional -;; annotations. - -;; - The `embark-export' command tries to open a buffer in an -;; appropriate major mode for the set of candidates. If the -;; candidates are files export produces a Dired buffer; if they are -;; buffers, you get an Ibuffer buffer; and if they are packages you -;; get a buffer in package menu mode. - -;; These are always available as "actions" (although they do not act -;; on just the current target but on all candidates) for embark-act -;; and are bound to A, S (for "snapshot") and E, respectively, in -;; embark-general-map. This means that you do not have to bind your -;; own key bindings for these (although you can, of course), just a -;; key binding for `embark-act'. - -;;; Code: - -(require 'compat) -(eval-when-compile (require 'subr-x)) - -(require 'ffap) ; used to recognize file and url targets - -;;; User facing options - -(defgroup embark nil - "Emacs Mini-Buffer Actions Rooted in Keymaps." - :link '(info-link :tag "Info Manual" "(embark)") - :link '(url-link :tag "Homepage" "https://github.com/oantolin/embark") - :link '(emacs-library-link :tag "Library Source" "embark.el") - :group 'minibuffer - :prefix "embark-") - -(defcustom embark-keymap-alist - '((file embark-file-map) - (library embark-library-map) - (environment-variables embark-file-map) ; they come up in file completion - (url embark-url-map) - (email embark-email-map) - (buffer embark-buffer-map) - (tab embark-tab-map) - (expression embark-expression-map) - (identifier embark-identifier-map) - (defun embark-defun-map) - (symbol embark-symbol-map) - (face embark-face-map) - (command embark-command-map) - (variable embark-variable-map) - (function embark-function-map) - (minor-mode embark-command-map) - (unicode-name embark-unicode-name-map) - (package embark-package-map) - (bookmark embark-bookmark-map) - (region embark-region-map) - (sentence embark-sentence-map) - (paragraph embark-paragraph-map) - (kill-ring embark-kill-ring-map) - (heading embark-heading-map) - (flymake embark-flymake-map) - (smerge smerge-basic-map embark-general-map) - (t embark-general-map)) - "Alist of action types and corresponding keymaps. -The special key t is associated with the default keymap to use. -Each value can be either a single symbol whose value is a keymap, -or a list of such symbols." - :type '(alist :key-type (symbol :tag "Target type") - :value-type (choice (variable :tag "Keymap") - (repeat :tag "Keymaps" variable)))) - -(defcustom embark-target-finders - '(embark-target-top-minibuffer-candidate - embark-target-active-region - embark-target-collect-candidate - embark-target-completion-list-candidate - embark-target-text-heading-at-point - embark-target-bug-reference-at-point - embark-target-flymake-at-point - embark-target-smerge-at-point - embark-target-package-at-point - embark-target-email-at-point - embark-target-url-at-point - embark-target-file-at-point - embark-target-custom-variable-at-point - embark-target-identifier-at-point - embark-target-guess-file-at-point - embark-target-expression-at-point - embark-target-sentence-at-point - embark-target-paragraph-at-point - embark-target-defun-at-point - embark-target-prog-heading-at-point) - "List of functions to determine the target in current context. -Each function should take no arguments and return one of: - -1. a cons (TYPE . TARGET) where TARGET is a string and TYPE is a - symbol (which is looked up in `embark-keymap-alist' to - determine which additional keybindings for actions to setup); - -2. a dotted list of the form (TYPE TARGET START . END), where - START and END are the buffer positions bounding TARGET, used - for highlighting; or - -3. a possibly empty list of targets, each of type 1 or 2 (in - particular if a target finder does not find any targets, it - should return nil)." - :type 'hook) - -(defcustom embark-transformer-alist - '((minor-mode . embark--lookup-lighter-minor-mode) - (embark-keybinding . embark--keybinding-command) - (project-file . embark--project-file-full-path) - (package . embark--remove-package-version) - (multi-category . embark--refine-multi-category) - (file . embark--simplify-path)) - "Alist associating type to functions for transforming targets. -Each function should take a type and a target string and return a -pair of the form a `cons' of the new type and the new target." - :type '(alist :key-type symbol :value-type function)) - -(defcustom embark-become-keymaps - '(embark-become-help-map - embark-become-file+buffer-map - embark-become-shell-command-map - embark-become-match-map) - "List of keymaps for `embark-become'. -Each keymap groups a set of related commands that can -conveniently become one another." - :type '(repeat variable)) - -(defcustom embark-prompter 'embark-keymap-prompter - "Function used to prompt the user for actions. -This should be set to a function that prompts the use for an -action and returns the symbol naming the action command. The -default value, `embark-keymap-prompter' activates the type -specific action keymap given in `embark-keymap-alist'. -There is also `embark-completing-read-prompter' which -prompts for an action with completion." - :type '(choice (const :tag "Use action keymaps" embark-keymap-prompter) - (const :tag "Read action with completion" - embark-completing-read-prompter) - (function :tag "Other"))) - -(defcustom embark-keymap-prompter-key "@" - "Key to switch to the keymap prompter from `embark-completing-read-prompter'. - -The key must be either nil or a string. The -string must be accepted by `key-valid-p'." - :type '(choice key (const :tag "None" nil))) - -(defcustom embark-cycle-key nil - "Key used for `embark-cycle'. - -If the key is set to nil it defaults to the global binding of -`embark-act'. The key must be a string which is accepted by -`key-valid-p'." - :type '(choice key (const :tag "Use embark-act key" nil))) - -(defcustom embark-help-key "C-h" - "Key used for help. - -The key must be either nil or a string. The -string must be accepted by `key-valid-p'." - :type '(choice (const "C-h") - (const "?") - (const :tag "None" nil) - key)) - -(defcustom embark-keybinding-repeat - (propertize "*" 'face 'embark-keybinding-repeat) - "Indicator string for repeatable keybindings. -Keybindings are formatted by the `completing-read' prompter and -the verbose indicator." - :type 'string) - -(defface embark-keybinding-repeat - '((t :inherit font-lock-builtin-face)) - "Face used to indicate keybindings as repeatable.") - -(defface embark-keybinding '((t :inherit success)) - "Face used to display key bindings. -Used by `embark-completing-read-prompter' and `embark-keymap-help'.") - -(defface embark-keymap '((t :slant italic)) - "Face used to display keymaps. -Used by `embark-completing-read-prompter' and `embark-keymap-help'.") - -(defface embark-target '((t :inherit highlight)) - "Face used to highlight the target at point during `embark-act'.") - -(defcustom embark-quit-after-action t - "Should `embark-act' quit the minibuffer? -This controls whether calling `embark-act' without a prefix -argument quits the minibuffer or not. You can always get the -opposite behavior to that indicated by this variable by calling -`embark-act' with \\[universal-argument]. - -Note that `embark-act' can also be called from outside the -minibuffer and this variable is irrelevant in that case. - -In addition to t or nil this variable can also be set to an -alist to specify the minibuffer quitting behavior per command. -In the alist case one can additionally use the key t to -prescribe a default for commands not used as alist keys." - :type '(choice (const :tag "Always quit" t) - (const :tag "Never quit" nil) - (alist :tag "Configure per action" - :key-type (choice (function :tag "Action") - (const :tag "All other actions" t)) - :value-type (choice (const :tag "Quit" t) - (const :tag "Do not quit" nil))))) - -(defcustom embark-confirm-act-all t - "Should `embark-act-all' prompt the user for confirmation? -Even if this variable is nil you may still be prompted to confirm -some uses of `embark-act-all', namely, for those actions whose -entry in `embark-pre-action-hooks' includes `embark--confirm'." - :type 'boolean) - -(defcustom embark-default-action-overrides nil - "Alist associating target types with overriding default actions. -When the source of a target is minibuffer completion, the default -action for it is usually the command that opened the minibuffer -in the first place but this can be overridden for a given type by -an entry in this list. - -For example, if you run `delete-file' the default action for its -completion candidates is `delete-file' itself. You may prefer to -make `find-file' the default action for all files, even if they -were obtained from a `delete-file' prompt. In that case you can -configure that by adding an entry to this variable pairing `file' -with `find-file'. - -In addition to target types, you can also use as keys in this alist, -pairs of a target type and a command name. Such a pair indicates that -the override only applies if the target was obtained from minibuffer -completion from that command. For example adding an -entry (cons (cons \\='file \\='delete-file) \\='find-file) to this alist would -indicate that for files at the prompt of the `delete-file' command, -`find-file' should be used as the default action." - :type '(alist :key-type (choice (symbol :tag "Type") - (cons (symbol :tag "Type") - (symbol :tag "Command"))) - :value-type (function :tag "Default action"))) - -(defcustom embark-target-injection-hooks - '((async-shell-command embark--allow-edit embark--shell-prep) - (shell-command embark--allow-edit embark--shell-prep) - (pp-eval-expression embark--eval-prep) - (eval-expression embark--eval-prep) - (package-delete embark--force-complete) - ;; commands evaluating code found in the buffer, which may in turn prompt - (embark-pp-eval-defun embark--ignore-target) - (eval-defun embark--ignore-target) - (eval-last-sexp embark--ignore-target) - (embark-eval-replace embark--ignore-target) - ;; commands which prompt for something that is *not* the target - (write-region embark--ignore-target) - (append-to-file embark--ignore-target) - (append-to-buffer embark--ignore-target) - (shell-command-on-region embark--ignore-target) - (format-encode-region embark--ignore-target) - (format-decode-region embark--ignore-target) - (xref-find-definitions embark--ignore-target) - (xref-find-references embark--ignore-target) - (sort-regexp-fields embark--ignore-target) - (align-regexp embark--ignore-target)) - "Alist associating commands with post-injection setup hooks. -For commands appearing as keys in this alist, run the -corresponding value as a setup hook after injecting the target -into in the minibuffer and before acting on it. The hooks must -accept arbitrary keyword arguments. The :action command, the -:target string and target :type are always present. For actions -at point the target :bounds are passed too. The default pre-action -hook is specified by the entry with key t. Furthermore, hooks with -the key :always are executed always." - :type '(alist :key-type - (choice symbol - (const :tag "Default" t) - (const :tag "Always" :always)) - :value-type hook)) - -(defcustom embark-pre-action-hooks - `(;; commands that need to position point at the beginning or end - (eval-last-sexp embark--end-of-target) - (indent-pp-sexp embark--beginning-of-target) - (backward-up-list embark--beginning-of-target) - (backward-list embark--beginning-of-target) - (forward-list embark--end-of-target) - (forward-sexp embark--end-of-target) - (backward-sexp embark--beginning-of-target) - (raise-sexp embark--beginning-of-target) - (kill-sexp embark--beginning-of-target) - (mark-sexp embark--beginning-of-target) - (transpose-sexps embark--end-of-target) - (transpose-sentences embark--end-of-target) - (transpose-paragraphs embark--end-of-target) - (forward-sentence embark--end-of-target) - (backward-sentence embark--beginning-of-target) - (backward-paragraph embark--beginning-of-target) - (embark-insert embark--end-of-target) - ;; commands we want to be able to jump back from - ;; (embark-find-definition achieves this by calling - ;; xref-find-definitions which pushes the markers itself) - (find-library embark--xref-push-marker) - ;; commands which prompt the user for confirmation before running - (delete-file embark--confirm) - (delete-directory embark--confirm) - (kill-buffer embark--confirm) - (embark-kill-buffer-and-window embark--confirm) - (bookmark-delete embark--confirm) - (package-delete embark--confirm) - (,'tab-bar-close-tab-by-name embark--confirm) ;; Avoid package-lint warning - ;; search for region contents outside said region - (embark-isearch-forward embark--unmark-target) - (embark-isearch-backward embark--unmark-target) - (occur embark--unmark-target) - (query-replace embark--beginning-of-target embark--unmark-target) - (query-replace-regexp embark--beginning-of-target embark--unmark-target) - (replace-string embark--beginning-of-target embark--unmark-target) - (replace-regexp embark--beginning-of-target embark--unmark-target) - ;; mark pseudo-action - (mark embark--mark-target) - ;; shells in new buffers - (shell embark--universal-argument) - (eshell embark--universal-argument)) - "Alist associating commands with pre-action hooks. -The hooks are run right before an action is embarked upon. See -`embark-target-injection-hooks' for information about the hook -arguments and more details." - :type '(alist :key-type - (choice symbol - (const :tag "Default" t) - (const :tag "Always" :always)) - :value-type hook)) - -(defcustom embark-post-action-hooks - `((bookmark-delete embark--restart) - (bookmark-rename embark--restart) - (delete-file embark--restart) - (embark-kill-ring-remove embark--restart) - (embark-recentf-remove embark--restart) - (embark-history-remove embark--restart) - (rename-file embark--restart) - (copy-file embark--restart) - (delete-directory embark--restart) - (make-directory embark--restart) - (kill-buffer embark--restart) - (embark-rename-buffer embark--restart) - (,'tab-bar-rename-tab-by-name embark--restart) ;; Avoid package-lint warning - (,'tab-bar-close-tab-by-name embark--restart) - (package-delete embark--restart)) - "Alist associating commands with post-action hooks. -The hooks are run after an embarked upon action concludes. See -`embark-target-injection-hooks' for information about the hook -arguments and more details." - :type '(alist :key-type - (choice symbol - (const :tag "Default" t) - (const :tag "Always" :always)) - :value-type hook)) - -(defcustom embark-around-action-hooks - '(;; use directory of target as default-directory - (shell embark--cd) - (eshell embark--cd) - ;; mark the target preserving point and previous mark - (kill-region embark--mark-target) - (kill-ring-save embark--mark-target) - (indent-region embark--mark-target) - (ispell-region embark--mark-target) - (fill-region embark--mark-target) - (upcase-region embark--mark-target) - (downcase-region embark--mark-target) - (capitalize-region embark--mark-target) - (count-words-region embark--mark-target) - (count-words embark--mark-target) - (delete-duplicate-lines embark--mark-target) - (shell-command-on-region embark--mark-target) - (delete-region embark--mark-target) - (format-encode-region embark--mark-target) - (format-decode-region embark--mark-target) - (write-region embark--mark-target) - (append-to-file embark--mark-target) - (append-to-buffer embark--mark-target) - (shell-command-on-region embark--mark-target) - (embark-eval-replace embark--mark-target) - (delete-indentation embark--mark-target) - (comment-dwim embark--mark-target) - (insert-parentheses embark--mark-target) - (insert-pair embark--mark-target) - (org-emphasize embark--mark-target) - ;; do the actual work of selecting & deselecting targets - (embark-select embark--select)) - "Alist associating commands with post-action hooks. -The hooks are run instead of the embarked upon action. The hook -can decide whether or not to run the action or it can run it -in some special environment, like inside a let-binding or inside -`save-excursion'. Each hook is called with keyword argument :run -providing a function encapsulating the following around hooks and -the action; the hook additionally receives the keyword arguments -used for other types of action hooks, for more details see -`embark-target-injection-hooks'." - :type '(alist :key-type - (choice symbol - (const :tag "Default" t) - (const :tag "Always" :always)) - :value-type hook)) - -(static-if (< emacs-major-version 29) - ;; narrow to target for duration of action - (setf (alist-get 'repunctuate-sentences embark-around-action-hooks) - '(embark--narrow-to-target))) - -(defcustom embark-multitarget-actions '(embark-insert embark-copy-as-kill) - "Commands for which `embark-act-all' should pass a list of targets. -Normally `embark-act-all' runs the same action on each candidate -separately, but when a command included in this variable's value -is used as an action, `embark-act-all' will instead call it -non-interactively with a single argument: the list of all -candidates. For commands on this list `embark-act' behaves -similarly: it calls them non-interactively with a single -argument: a one element list containing the target." - :type '(repeat function)) - -(defcustom embark-repeat-actions - '((mark . region) - ;; outline commands - outline-next-visible-heading outline-previous-visible-heading - outline-forward-same-level outline-backward-same-level - outline-demote outline-promote - outline-show-subtree (outline-mark-subtree . region) - outline-move-subtree-up outline-move-subtree-down - outline-up-heading outline-hide-subtree outline-cycle - ;; org commands (remapped outline commands) - org-forward-heading-same-level org-backward-heading-same-level - org-next-visible-heading org-previous-visible-heading - org-demote-subtree org-promote-subtree - org-show-subtree (org-mark-subtree . region) - org-move-subtree-up org-move-subtree-down - ;; transpose commands - transpose-sexps transpose-sentences transpose-paragraphs - ;; navigation commands - flymake-goto-next-error flymake-goto-prev-error - embark-next-symbol embark-previous-symbol - backward-up-list backward-list forward-list forward-sexp - backward-sexp forward-sentence backward-sentence - forward-paragraph backward-paragraph - ;; smerge commands - smerge-refine smerge-combine-with-next smerge-prev smerge-next) - "List of repeatable actions. -When you use a command on this list as an Embark action from -outside the minibuffer, `embark-act' does not exit but instead -lets you act again on the possibly new target you reach. - -By default, after using one of these actions, when `embark-act' -looks for targets again, it will start the target cycle at the -same type as the previously acted upon target; that is, you -\"don't loose your place in the target cycle\". - -Sometimes, however, you'll want to prioritize a different type of -target to continue acting on. The main example of this that if -you use a marking command as an action, you almost always want to -act on the region next. For those cases, in addition to -commands, you can also place on this list a pair of a command and -the desired starting type for the target cycle for the next -action." - :type '(repeat (choice function - (cons function - (symbol :tag "Next target type"))))) - -;;; Overlay properties - -;; high priority to override both bug reference and the lazy -;; isearch highlights in embark-isearch-highlight-indicator -(put 'embark-target-overlay 'face 'embark-target) -(put 'embark-target-overlay 'priority 1001) -(put 'embark-selected-overlay 'face 'embark-selected) -(put 'embark-selected-overlay 'priority 1001) - -;;; Stashing information for actions in buffer local variables - -(defvar-local embark--type nil - "Cache for the completion type, meant to be set buffer-locally.") - -(defvar-local embark--target-buffer nil - "Cache for the previous buffer, meant to be set buffer-locally.") - -(defvar-local embark--target-window nil - "Cache for the previous window, meant to be set buffer-locally. -Since windows can be reused to display different buffers, this -window should only be used if it displays the buffer stored in -the variable `embark--target-buffer'.") - -(defvar-local embark--command nil - "Command that started the completion session.") - -(defvar-local embark--toggle-quit nil - "Should we toggle the default quitting behavior for the next action?") - -(defun embark--minibuffer-point () - "Return length of minibuffer contents." - (max 0 (- (point) (minibuffer-prompt-end)))) - -(defun embark--default-directory () - "Guess a reasonable default directory for the current candidates." - (if (and (minibufferp) minibuffer-completing-file-name) - (let ((end (minibuffer-prompt-end)) - (contents (minibuffer-contents))) - (expand-file-name - (substitute-in-file-name - (buffer-substring - end - (+ end - (or (cdr - (last - (completion-all-completions - contents - minibuffer-completion-table - minibuffer-completion-predicate - (embark--minibuffer-point)))) - (cl-position ?/ contents :from-end t) - 0)))))) - default-directory)) - -(defun embark--target-buffer () - "Return buffer that should be targeted by Embark actions." - (cond - ((and (minibufferp) minibuffer-completion-table (minibuffer-selected-window)) - (window-buffer (minibuffer-selected-window))) - ((and embark--target-buffer (buffer-live-p embark--target-buffer)) - embark--target-buffer) - (t (current-buffer)))) - -(defun embark--target-window (&optional display) - "Return window which should be selected when Embark actions run. -If DISPLAY is non-nil, call `display-buffer' to produce the -window if necessary." - (cond - ((and (minibufferp) minibuffer-completion-table (minibuffer-selected-window)) - (minibuffer-selected-window)) - ((and embark--target-window - (window-live-p embark--target-window) - (or (not (buffer-live-p embark--target-buffer)) - (eq (window-buffer embark--target-window) embark--target-buffer))) - embark--target-window) - ((and embark--target-buffer (buffer-live-p embark--target-buffer)) - (or (get-buffer-window embark--target-buffer) - (when display (display-buffer embark--target-buffer)))) - (display (selected-window)))) - -(defun embark--cache-info (buffer) - "Cache information needed for actions in variables local to BUFFER. -BUFFER defaults to the current buffer." - (let ((cmd embark--command) - (dir (embark--default-directory)) - (target-buffer (embark--target-buffer)) - (target-window (embark--target-window))) - (with-current-buffer buffer - (setq embark--command cmd - default-directory dir - embark--target-buffer target-buffer - embark--target-window target-window)))) - -(defun embark--cache-info--completion-list () - "Cache information needed for actions in a *Completions* buffer. -Meant to be be added to `completion-setup-hook'." - ;; when completion-setup-hook hook runs, the *Completions* buffer is - ;; available in the variable standard-output - (embark--cache-info standard-output) - (with-current-buffer standard-output - (when (minibufferp completion-reference-buffer) - (setq embark--type - (completion-metadata-get - (with-current-buffer completion-reference-buffer - (embark--metadata)) - 'category))))) - -;; We have to add this *after* completion-setup-function because that's -;; when the buffer is put in completion-list-mode and turning the mode -;; on kills all local variables! So we use a depth of 5. -(add-hook 'completion-setup-hook #'embark--cache-info--completion-list 5) - -;;;###autoload -(progn - (defun embark--record-this-command () - "Record command which opened the minibuffer. -We record this because it will be the default action. -This function is meant to be added to `minibuffer-setup-hook'." - (setq-local embark--command this-command)) - (add-hook 'minibuffer-setup-hook #'embark--record-this-command)) - -;;; Internal variables - -(defvar embark--prompter-history nil - "History used by the `embark-completing-read-prompter'.") - -;;; Core functionality - -(defconst embark--verbose-indicator-buffer " *Embark Actions*") - -(defvar embark--minimal-indicator-overlay nil) - -(defun embark--metadata () - "Return current minibuffer completion metadata." - (completion-metadata - (buffer-substring-no-properties - (minibuffer-prompt-end) - (max (minibuffer-prompt-end) (point))) - minibuffer-completion-table - minibuffer-completion-predicate)) - -(defun embark-target-active-region () - "Target the region if active." - (when (use-region-p) - (let ((start (region-beginning)) - (end (region-end))) - `(region ,(buffer-substring start end) . (,start . ,end))))) - -(autoload 'dired-get-filename "dired") -(declare-function image-dired-original-file-name "image-dired") - -(defun embark-target-guess-file-at-point () - "Target the file guessed by `ffap' at point." - (when-let ((tap-file (thing-at-point 'filename)) - ((not (ffap-url-p tap-file))) ; no URLs, those have a target finder - (bounds (bounds-of-thing-at-point 'filename)) - (file (ffap-file-at-point))) - ;; ffap doesn't make bounds available, so we use - ;; thingatpt bounds, which might be a little off - ;; adjust bounds if thingatpt gobbled punctuation around file - (when (or (string-match (regexp-quote file) tap-file) - (string-match (regexp-quote (file-name-base file)) tap-file)) - (setq bounds (cons (+ (car bounds) (match-beginning 0)) - (- (cdr bounds) (- (length tap-file) - (match-end 0)))))) - `(file ,(abbreviate-file-name (expand-file-name file)) ,@bounds))) - -(defun embark-target-file-at-point () - "Target file at point. -This function mostly relies on `ffap-file-at-point', with the -following exceptions: - -- In `dired-mode', it uses `dired-get-filename' instead. - -- In `imaged-dired-thumbnail-mode', it uses - `image-dired-original-file-name' instead." - (let (file bounds) - (or (and (derived-mode-p 'dired-mode) - (setq file (dired-get-filename t 'no-error-if-not-filep)) - (setq bounds - (cons - (save-excursion (dired-move-to-filename) (point)) - (save-excursion (dired-move-to-end-of-filename) (point))))) - (and (derived-mode-p 'image-dired-thumbnail-mode) - (setq file (image-dired-original-file-name)) - (setq bounds (cons (point) (1+ (point))))) - (when-let ((tap-file (thing-at-point 'filename)) - ((not (equal (file-name-base tap-file) tap-file))) - (guess (embark-target-guess-file-at-point))) - (setq file (cadr guess) bounds (cddr guess)))) - (when file - `(file ,(abbreviate-file-name (expand-file-name file)) ,@bounds)))) - -(defun embark-target-package-at-point () - "Target the package on the current line in a packages buffer." - (when (derived-mode-p 'package-menu-mode) - (when-let ((pkg (get-text-property (point) 'tabulated-list-id))) - `(package ,(symbol-name (package-desc-name pkg)) - ,(line-beginning-position) . ,(line-end-position))))) - -(defun embark-target-email-at-point () - "Target the email address at point." - (when-let ((email (thing-at-point 'email))) - (when (string-prefix-p "mailto:" email) - (setq email (string-remove-prefix "mailto:" email))) - `(email ,email . ,(bounds-of-thing-at-point 'email)))) - -(defun embark-target-url-at-point () - "Target the URL at point." - (if-let ((url (or (get-text-property (point) 'shr-url) - (get-text-property (point) 'image-url)))) - `(url ,url - ,(previous-single-property-change - (min (1+ (point)) (point-max)) 'mouse-face nil (point-min)) - . ,(next-single-property-change - (point) 'mouse-face nil (point-max))) - (when-let ((url (thing-at-point 'url))) - `(url ,url . ,(thing-at-point-bounds-of-url-at-point t))))) - -(declare-function widget-at "wid-edit") - -(defun embark-target-custom-variable-at-point () - "Target the variable corresponding to the customize widget at point." - (when (derived-mode-p 'Custom-mode) - (save-excursion - (beginning-of-line) - (when-let* ((widget (widget-at (point))) - (var (and (eq (car widget) 'custom-visibility) - (plist-get (cdr widget) :parent))) - (sym (and (eq (car var) 'custom-variable) - (plist-get (cdr var) :value)))) - `(variable - ,(symbol-name sym) - ,(point) - . ,(progn - (re-search-forward ":" (line-end-position) 'noerror) - (point))))))) - -;; NOTE: There is also (thing-at-point 'list), however it does -;; not work on strings and requires the point to be inside the -;; parentheses. This version here is slightly more general. -(defun embark-target-expression-at-point () - "Target expression at point." - (cl-flet ((syntax-p (class &optional (delta 0)) - (and (<= (point-min) (+ (point) delta) (point-max)) - (eq (pcase class - ('open 4) ('close 5) ('prefix 6) ('string 7)) - (syntax-class (syntax-after (+ (point) delta))))))) - (when-let - ((start - (pcase-let ((`(_ ,open _ ,string _ _ _ _ ,start _ _) (syntax-ppss))) - (ignore-errors ; set start=nil if delimiters are unbalanced - (cond - (string start) - ((or (syntax-p 'open) (syntax-p 'prefix)) - (save-excursion (backward-prefix-chars) (point))) - ((syntax-p 'close -1) - (save-excursion - (backward-sexp) (backward-prefix-chars) (point))) - ((syntax-p 'string) (point)) - ((syntax-p 'string -1) (scan-sexps (point) -1)) - (t open))))) - (end (ignore-errors (scan-sexps start 1)))) - (unless (eq start (car (bounds-of-thing-at-point 'defun))) - `(expression ,(buffer-substring start end) ,start . ,end))))) - -(defmacro embark-define-overlay-target (name prop &optional pred type target) - "Define a target finder for NAME that targets overlays with property PROP. -The function defined is named embark-target-NAME-at-point and it -returns Embark targets based on the overlays around point. An -overlay provides a target if its property named PROP is non-nil. - -If the optional PRED argument is given, it should be an -expression and it further restricts the targets to only those -overlays for which PRED evaluates to non-nil. - -The target finder returns target type NAME or optional symbol -TYPE if given. - -The target finder returns the substring of the buffer covered by -the overlay as the target string or the result of evaluating the -optional TARGET expression if given. - -PRED and TARGET are expressions (not functions) and when evaluated the -symbols `%o' and `%p' are bound to the overlay and the overlay's -property respectively." - `(defun ,(intern (format "embark-target-%s-at-point" name)) () - ,(format "Target %s at point." name) - (when-let ((%o (seq-find - (lambda (%o) - (when-let ((%p (overlay-get %o ',prop))) - (ignore %p) - ,(or pred t))) - (overlays-in (max (point-min) (1- (point))) - (min (point-max) (1+ (point)))))) - (%p (overlay-get %o ',prop))) - (ignore %p) - (cons ',(or type name) - (cons ,(or target `(buffer-substring-no-properties - (overlay-start %o) (overlay-end %o))) - (cons (overlay-start %o) (overlay-end %o))))))) - -(embark-define-overlay-target flymake flymake-diagnostic) -(embark-define-overlay-target bug-reference bug-reference-url nil url %p) -(embark-define-overlay-target smerge smerge (eq %p 'conflict)) - -(defmacro embark-define-thingatpt-target (thing &rest modes) - "Define a target finder for THING using the thingatpt library. -The function defined is named embark-target-NAME-at-point and it -uses (thing-at-point \\='THING) to find its targets. - -If any MODES are given, the target finder only applies to buffers -in one of those major modes." - (declare (indent 1)) - `(defun ,(intern (format "embark-target-%s-at-point" thing)) () - ,(format "Target %s at point." thing) - (when ,(if modes `(derived-mode-p ,@(mapcar (lambda (m) `',m) modes)) t) - (when-let (bounds (bounds-of-thing-at-point ',thing)) - (cons ',thing (cons - (buffer-substring (car bounds) (cdr bounds)) - bounds)))))) - -(embark-define-thingatpt-target defun) -(embark-define-thingatpt-target sentence - text-mode help-mode Info-mode man-common) -(embark-define-thingatpt-target paragraph - text-mode help-mode Info-mode man-common) - -(defmacro embark-define-regexp-target - (name regexp &optional type target bounds limit) - "Define a target finder for matches of REGEXP around point. -The function defined is named embark-target-NAME-at-point and it -uses (thing-at-point-looking-at REGEXP) to find its targets. - -The target finder returns target type NAME or optional symbol -TYPE if given. - -The target finder returns the substring of the buffer matched by -REGEXP as the target string or the result of evaluating the -optional TARGET expression if given. In the expression TARGET -you can use `match-string' to recover the match of the REGEXP or -of any sub-expressions it has. - -BOUNDS is an optional expression to compute the bounds of the -target and defaults to (cons (match-beginning 0) (match-end 0)). - -The optional LIMIT is the number of characters before and after -point to limit the search to. If LIMIT is nil, search a little -more than the current line (more precisely, the smallest interval -centered at point that includes the current line)." - `(defun ,(intern (format "embark-target-%s-at-point" name)) () - ,(format "Target %s at point." name) - (save-match-data - (when (thing-at-point-looking-at - ,regexp - ,(or limit '(max (- (pos-eol) (point)) (- (point) (pos-bol))))) - (cons ',(or type name) - (cons ,(or target '(match-string 0)) - ,(or bounds - '(cons (match-beginning 0) (match-end 0))))))))) - -(defun embark--identifier-types (identifier) - "Return list of target types appropriate for IDENTIFIER." - (let ((symbol (intern-soft identifier))) - (if (not - (or (derived-mode-p 'emacs-lisp-mode 'inferior-emacs-lisp-mode) - (and (not (derived-mode-p 'prog-mode)) - symbol - (or (boundp symbol) (fboundp symbol) (symbol-plist symbol))))) - '(identifier) - (let* ((library (ffap-el-mode identifier)) - (types - (append - (and (commandp symbol) '(command)) - (and symbol (boundp symbol) (not (keywordp symbol)) '(variable)) - (and (fboundp symbol) (not (commandp symbol)) '(function)) - (and (facep symbol) '(face)) - (and library '(library)) - (and (featurep 'package) (embark--package-desc symbol) - '(package))))) - (when (and library - (looking-back "\\(?:require\\|use-package\\).*" - (line-beginning-position))) - (setq types (embark--rotate types (cl-position 'library types)))) - (or types '(symbol)))))) - -(defun embark-target-identifier-at-point () - "Target identifier at point. - -In Emacs Lisp and IELM buffers the identifier is promoted to a -symbol, for which more actions are available. Identifiers are -also promoted to symbols if they are interned Emacs Lisp symbols -and found in a buffer in a major mode that is not derived from -`prog-mode' (this is intended for when you might be reading or -writing about Emacs). - -As a convenience, in Org Mode an initial ' or surrounding == or -~~ are removed." - (when-let (bounds (bounds-of-thing-at-point 'symbol)) - (let ((name (buffer-substring (car bounds) (cdr bounds)))) - (when (derived-mode-p 'org-mode) - (cond ((string-prefix-p "'" name) - (setq name (substring name 1)) - (cl-incf (car bounds))) - ((string-match-p "^\\([=~]\\).*\\1$" name) - (setq name (substring name 1 -1)) - (cl-incf (car bounds)) - (cl-decf (cdr bounds))))) - (mapcar (lambda (type) `(,type ,name . ,bounds)) - (embark--identifier-types name))))) - -(defun embark-target-heading-at-point () - "Target the outline heading at point." - (let ((beg (line-beginning-position)) - (end (line-end-position))) - (when (save-excursion - (goto-char beg) - (and (bolp) - (looking-at - ;; default definition from outline.el - (or (bound-and-true-p outline-regexp) "[*\^L]+")))) - (require 'outline) ;; Ensure that outline commands are available - `(heading ,(buffer-substring beg end) ,beg . ,end)))) - -(defun embark-target-text-heading-at-point () - "Target the outline heading at point in text modes." - (when (derived-mode-p 'text-mode) - (embark-target-heading-at-point))) - -(defun embark-target-prog-heading-at-point () - "Target the outline heading at point in programming modes." - (when (derived-mode-p 'prog-mode) - (embark-target-heading-at-point))) - -(defun embark-target-top-minibuffer-candidate () - "Target the top completion candidate in the minibuffer. -Return the category metadatum as the type of the target. - -This target finder is meant for the default completion UI and -completion UI highly compatible with it, like Icomplete. -Many completion UIs can still work with Embark but will need -their own target finder. See for example -`embark--vertico-selected'." - (when (and (minibufferp) minibuffer-completion-table) - (pcase-let* ((`(,category . ,candidates) (embark-minibuffer-candidates)) - (contents (minibuffer-contents)) - (top (if (test-completion contents - minibuffer-completion-table - minibuffer-completion-predicate) - contents - (let ((completions (completion-all-sorted-completions))) - (if (null completions) - contents - (concat - (substring contents - 0 (or (cdr (last completions)) 0)) - (car completions))))))) - (cons category (or (car (member top candidates)) top))))) - -(defun embark-target-collect-candidate () - "Target the collect candidate at point." - (when (derived-mode-p 'embark-collect-mode) - (when-let ((button - (pcase (get-text-property (point) 'tabulated-list-column-name) - ("Candidate" (button-at (point))) - ("Annotation" (previous-button (point))))) - (start (button-start button)) - (end (button-end button)) - (candidate (tabulated-list-get-id))) - `(,embark--type - ,(if (eq embark--type 'file) - (abbreviate-file-name (expand-file-name candidate)) - candidate) - ,start . ,end)))) - -(defun embark-target-completion-list-candidate () - "Return the completion candidate at point in a completions buffer." - (when (derived-mode-p 'completion-list-mode) - (if (not (get-text-property (point) 'mouse-face)) - (user-error "No completion here") - ;; this fairly delicate logic is taken from `choose-completion' - (let (beg end) - (cond - ((and (not (eobp)) (get-text-property (point) 'mouse-face)) - (setq end (point) beg (1+ (point)))) - ((and (not (bobp)) - (get-text-property (1- (point)) 'mouse-face)) - (setq end (1- (point)) beg (point))) - (t (user-error "No completion here"))) - (setq beg (previous-single-property-change beg 'mouse-face)) - (setq end (or (next-single-property-change end 'mouse-face) - (point-max))) - (let ((raw (or (get-text-property beg 'completion--string) - (buffer-substring beg end)))) - `(,embark--type - ,(if (eq embark--type 'file) - (abbreviate-file-name (expand-file-name raw)) - raw) - ,beg . ,end)))))) - -(defun embark--cycle-key () - "Return the key to use for `embark-cycle'." - (if embark-cycle-key - (if (key-valid-p embark-cycle-key) - (key-parse embark-cycle-key) - (error "`embark-cycle-key' is invalid")) - (car (where-is-internal #'embark-act)))) - -(defun embark--raw-action-keymap (type) - "Return raw action map for targets of given TYPE. -This does not take into account the default action, help key or -cycling bindings, just what's registered in -`embark-keymap-alist'." - (make-composed-keymap - (mapcar #'symbol-value - (let ((actions (or (alist-get type embark-keymap-alist) - (alist-get t embark-keymap-alist)))) - (ensure-list actions))))) - -(defun embark--action-keymap (type cycle) - "Return action keymap for targets of given TYPE. -If CYCLE is non-nil bind `embark-cycle'." - (make-composed-keymap - (let ((map (make-sparse-keymap)) - (default-action (embark--default-action type))) - (define-key map [13] default-action) - (when-let ((cycle-key (and cycle (embark--cycle-key)))) - (define-key map cycle-key #'embark-cycle)) - (when embark-help-key - (keymap-set map embark-help-key #'embark-keymap-help)) - map) - (embark--raw-action-keymap type))) - -(defun embark--truncate-target (target) - "Truncate TARGET string." - (unless (stringp target) - (setq target (format "%s" target))) - (if-let (pos (string-match-p "\n" target)) - (concat (car (split-string target "\n" 'omit-nulls "\\s-*")) "…") - target)) - -;;;###autoload -(defun embark-eldoc-first-target (report &rest _) - "Eldoc function reporting the first Embark target at point. -This function uses the eldoc REPORT callback and is meant to be -added to `eldoc-documentation-functions'." - (when-let (((not (minibufferp))) - (target (car (embark--targets)))) - (funcall report - (format "Embark on %s ‘%s’" - (plist-get target :type) - (embark--truncate-target (plist-get target :target)))))) - -;;;###autoload -(defun embark-eldoc-target-types (report &rest _) - "Eldoc function reporting the types of all Embark targets at point. -This function uses the eldoc REPORT callback and is meant to be -added to `eldoc-documentation-functions'." - (when-let (((not (minibufferp))) - (targets (embark--targets))) - (funcall report - (format "Embark target types: %s" - (mapconcat - (lambda (target) (symbol-name (plist-get target :type))) - targets - ", "))))) - -(defun embark--format-targets (target shadowed-targets rep) - "Return a formatted string indicating the TARGET of an action. - -This is used internally by the minimal indicator and for the -targets section of the verbose indicator. The string will also -mention any SHADOWED-TARGETS. A non-nil REP indicates we are in -a repeating sequence of actions." - (let ((act (propertize - (cond - ((plist-get target :multi) "∀ct") - (rep "Rep") - (t "Act")) - 'face 'highlight))) - (cond - ((eq (plist-get target :type) 'embark-become) - (propertize "Become" 'face 'highlight)) - ((and (minibufferp) - (not (eq 'embark-keybinding - (completion-metadata-get - (embark--metadata) - 'category)))) - ;; we are in a minibuffer but not from the - ;; completing-read prompter, use just "Act" - act) - ((plist-get target :multi) - (format "%s on %s %ss" - act - (plist-get target :multi) - (plist-get target :type))) - (t (format - "%s on %s%s ‘%s’" - act - (plist-get target :type) - (if shadowed-targets - (format (propertize "(%s)" 'face 'shadow) - (mapconcat - (lambda (target) (symbol-name (plist-get target :type))) - shadowed-targets - ", ")) - "") - (embark--truncate-target (plist-get target :target))))))) - -(defun embark-minimal-indicator () - "Minimal indicator, appearing in the minibuffer prompt or echo area. -This indicator displays a message showing the types of all -targets, starting with the current target, and the value of the -current target. The message is displayed in the echo area, or if -the minibuffer is open, the message is added to the prompt." - (lambda (&optional keymap targets _prefix) - (if (null keymap) - (when embark--minimal-indicator-overlay - (delete-overlay embark--minimal-indicator-overlay) - (setq-local embark--minimal-indicator-overlay nil)) - (let ((indicator (embark--format-targets - (car targets) (cdr targets) - (eq (lookup-key keymap [13]) #'embark-done)))) - (if (not (minibufferp)) - (message "%s" indicator) - (unless embark--minimal-indicator-overlay - (setq-local embark--minimal-indicator-overlay - (make-overlay (point-min) (point-min) - (current-buffer) t t))) - (overlay-put embark--minimal-indicator-overlay - 'before-string (concat indicator - (if (<= (length indicator) - (* 0.4 (frame-width))) - " " - "\n")))))))) - -(defun embark--read-key-sequence (update) - "Read key sequence, call UPDATE function with prefix keys." - (let (timer prefix) - (unwind-protect - (progn - (when (functionp update) - (setq timer (run-at-time - 0.05 0.05 - (lambda () - (let ((new-prefix (this-single-command-keys))) - (unless (equal prefix new-prefix) - (setq prefix new-prefix) - (when (/= (length prefix) 0) - (funcall update prefix)))))))) - (read-key-sequence-vector nil nil nil t 'cmd-loop)) - (when timer - (cancel-timer timer))))) - -(defvar embark-indicators) ; forward declaration - -(defun embark-keymap-prompter (keymap update) - "Let the user choose an action using the bindings in KEYMAP. -Besides the bindings in KEYMAP, the user is free to use all their -key bindings and even \\[execute-extended-command] to select a command. -UPDATE is the indicator update function." - (let* ((keys (let ((overriding-terminal-local-map keymap)) - (embark--read-key-sequence update))) - (cmd (let ((overriding-terminal-local-map keymap)) - (key-binding keys 'accept-default)))) - ;; Set last-command-event as it would be from the command loop. - ;; Previously we only set it locally for digit-argument and for - ;; the mouse scroll commands handled in this function. But other - ;; commands can need it too! For example, electric-pair-mode users - ;; may wish to bind ( to self-insert-command in embark-region-map. - ;; Also, as described in issue #402, there are circumstances where - ;; you might run consult-narrow through the embark-keymap-prompter. - (setq last-command-event (aref keys (1- (length keys)))) - (pcase cmd - ((or 'embark-keymap-help - (and 'nil ; cmd is nil but last key is help-char - (guard (eq help-char (aref keys (1- (length keys))))))) - (let ((embark-indicators - (cl-set-difference embark-indicators - '(embark-verbose-indicator - embark-mixed-indicator))) - (prefix-map - (if (eq cmd 'embark-keymap-help) - keymap - (let ((overriding-terminal-local-map keymap)) - (key-binding (seq-take keys (1- (length keys))) - 'accept-default)))) - (prefix-arg prefix-arg)) ; preserve prefix arg - (when-let ((win (get-buffer-window embark--verbose-indicator-buffer - 'visible))) - (quit-window 'kill-buffer win)) - (embark-completing-read-prompter prefix-map update))) - ((or 'universal-argument 'universal-argument-more - 'negative-argument 'digit-argument 'embark-toggle-quit) - ;; prevent `digit-argument' from modifying the overriding map - (let ((overriding-terminal-local-map overriding-terminal-local-map)) - (command-execute cmd)) - (embark-keymap-prompter - (make-composed-keymap universal-argument-map keymap) - update)) - ((or 'minibuffer-keyboard-quit 'abort-recursive-edit 'abort-minibuffers) - nil) - ((guard (let ((def (lookup-key keymap keys))) ; if directly - ; bound, then obey - (and def (not (numberp def))))) ; number means "invalid prefix" - cmd) - ((and (pred symbolp) - (guard (string-suffix-p "self-insert-command" (symbol-name cmd)))) - (minibuffer-message "Not an action") - (embark-keymap-prompter keymap update)) - ((or 'scroll-other-window 'scroll-other-window-down) - (let ((minibuffer-scroll-window - ;; NOTE: Here we special case the verbose indicator! - (or (get-buffer-window embark--verbose-indicator-buffer 'visible) - minibuffer-scroll-window))) - (ignore-errors (command-execute cmd))) - (embark-keymap-prompter keymap update)) - ((or 'scroll-bar-toolkit-scroll 'mwheel-scroll - 'mac-mwheel-scroll 'pixel-scroll-precision) - (funcall cmd last-command-event) - (embark-keymap-prompter keymap update)) - ('execute-extended-command - (let ((prefix-arg prefix-arg)) ; preserve prefix arg - (intern-soft (read-extended-command)))) - ((or 'keyboard-quit 'keyboard-escape-quit) - nil) - (_ cmd)))) - -(defun embark--command-name (cmd) - "Return an appropriate name for CMD. -If CMD is a symbol, use its symbol name; for lambdas, use the -first line of the documentation string; for keyboard macros use -`key-description'; otherwise use the word \"unnamed\"." - (concat ; fresh copy, so we can freely add text properties - (cond - ((or (stringp cmd) (vectorp cmd)) (key-description cmd)) - ((stringp (car-safe cmd)) (car cmd)) - ((eq (car-safe cmd) 'menu-item) (eval (cadr cmd))) - ((keymapp cmd) - (propertize (if (symbolp cmd) (format "+%s" cmd) "<keymap>") - 'face 'embark-keymap)) - ((symbolp cmd) - (let ((name (symbol-name cmd))) - (if (string-prefix-p "embark-action--" name) ; direct action mode - (format "(%s)" (string-remove-prefix "embark-action--" name)) - name))) - ((when-let (doc (and (functionp cmd) (ignore-errors (documentation cmd)))) - (save-match-data - (when (string-match "^\\(.*\\)$" doc) - (match-string 1 doc))))) - (t "<unnamed>")))) - -;; Taken from Marginalia, needed by the verbose indicator. -;; We cannot use the completion annotators in this case. -(defconst embark--advice-regexp - (rx bos - (1+ (seq (? "This function has ") - (or ":before" ":after" ":around" ":override" - ":before-while" ":before-until" ":after-while" - ":after-until" ":filter-args" ":filter-return") - " advice: " (0+ nonl) "\n")) - "\n") - "Regexp to match lines about advice in function documentation strings.") - -;; Taken from Marginalia, needed by the verbose indicator. -;; We cannot use the completion annotators in this case. -(defun embark--function-doc (sym) - "Documentation string of function SYM." - (let ((vstr (and (symbolp sym) (keymapp sym) (boundp sym) - (eq (symbol-function sym) (symbol-value sym)) - (documentation-property sym 'variable-documentation)))) - (when-let (str (or (ignore-errors (documentation sym)) vstr)) - ;; Replace standard description with variable documentation - (when (and vstr (string-match-p "\\`Prefix command" str)) - (setq str vstr)) - (save-match-data - (if (string-match embark--advice-regexp str) - (substring str (match-end 0)) - str))))) - -(defun embark--action-repeatable-p (action) - "Is ACTION repeatable? -When the return value is non-nil it will be the desired starting -point of the next target cycle or t to indicate the default, -namely that the target cycle for the next action should begin at -the type of the current target." - (or (cdr (assq action embark-repeat-actions)) - (and (memq action embark-repeat-actions) t))) - -(defun embark--formatted-bindings (keymap &optional nested) - "Return the formatted keybinding of KEYMAP. -The keybindings are returned in their order of appearance. -If NESTED is non-nil subkeymaps are not flattened." - (let* ((commands - (cl-loop for (key . def) in (embark--all-bindings keymap nested) - for name = (embark--command-name def) - for cmd = (keymap--menu-item-binding def) - unless (memq cmd '(nil embark-keymap-help - negative-argument digit-argument)) - collect (list name cmd key - (concat - (if (eq (car-safe def) 'menu-item) - "menu-item" - (key-description key)))))) - (width (cl-loop for (_name _cmd _key desc) in commands - maximize (length desc))) - (default) - (candidates - (cl-loop for item in commands - for (name cmd key desc) = item - for desc-rep = - (concat - (propertize desc 'face 'embark-keybinding) - (and (embark--action-repeatable-p cmd) - embark-keybinding-repeat)) - for formatted = - (propertize - (concat desc-rep - (make-string (- width (length desc-rep) -1) ?\s) - name) - 'embark-command cmd) - when (equal key [13]) - do (setq default formatted) - collect (cons formatted item)))) - (cons candidates default))) - -(defun embark--with-category (category candidates) - "Return completion table for CANDIDATES of CATEGORY with sorting disabled." - (lambda (string predicate action) - (if (eq action 'metadata) - `(metadata (display-sort-function . identity) - (cycle-sort-function . identity) - (category . ,category)) - (complete-with-action - action candidates string predicate)))) - -(defun embark-completing-read-prompter (keymap update &optional no-default) - "Prompt via completion for a command bound in KEYMAP. -If NO-DEFAULT is t, no default value is passed to`completing-read'. - -UPDATE is the indicator update function. It is not used directly -here, but if the user switches to `embark-keymap-prompter', the -UPDATE function is passed to it." - (let* ((candidates+def (embark--formatted-bindings keymap)) - (candidates (car candidates+def)) - (def (and (not no-default) (cdr candidates+def))) - (buf (current-buffer)) - (choice - (catch 'choice - (minibuffer-with-setup-hook - (lambda () - (let ((map (make-sparse-keymap))) - (define-key map "\M-q" - (lambda () - (interactive) - (with-current-buffer buf - (embark-toggle-quit)))) - (when-let (cycle (embark--cycle-key)) - ;; Rebind `embark-cycle' in order allow cycling - ;; from the `completing-read' prompter. Additionally - ;; `embark-cycle' can be selected via - ;; `completing-read'. The downside is that this breaks - ;; recursively acting on the candidates of type - ;; embark-keybinding in the `completing-read' prompter. - (define-key map cycle - (cond - ((eq (lookup-key keymap cycle) 'embark-cycle) - (lambda () - (interactive) - (throw 'choice 'embark-cycle))) - ((null embark-cycle-key) - (lambda () - (interactive) - (minibuffer-message - "No cycling possible; press `%s' again to act." - (key-description cycle)) - (define-key map cycle #'embark-act)))))) - (when embark-keymap-prompter-key - (keymap-set map embark-keymap-prompter-key - (lambda () - (interactive) - (message "Press key binding") - (let ((cmd (embark-keymap-prompter keymap update))) - (if (null cmd) - (user-error "Unknown key") - (throw 'choice cmd)))))) - (use-local-map - (make-composed-keymap map (current-local-map))))) - (completing-read - "Command: " - (embark--with-category 'embark-keybinding candidates) - nil nil nil 'embark--prompter-history def))))) - (pcase (assoc choice candidates) - (`(,_formatted ,_name ,cmd ,key ,_desc) - ;; Set last-command-event as it would be from the command loop. - (setq last-command-event (aref key (1- (length key)))) - cmd) - ('nil (intern-soft choice))))) - -;;; Verbose action indicator - -(defgroup embark-indicators nil - "Indicators display information about actions and targets." - :group 'embark) - -(defcustom embark-indicators - '(embark-mixed-indicator - embark-highlight-indicator - embark-isearch-highlight-indicator) - "Indicator functions to use when acting or becoming. -The indicator functions are called from both `embark-act' and -from `embark-become' and should display information about this to -the user, such as: which of those two commands is running; a -description of the key bindings that are available for actions or -commands to become; and, in the case of `embark-act', the type -and value of the targets, and whether other targets are available -via `embark-cycle'. The indicator function is free to display as -much or as little of this information as desired and can use any -Emacs interface elements to do so. - -Embark comes with five such indicators: - -- `embark-minimal-indicator', which does not display any - information about keybindings, but does display types and - values of action targets in the echo area or minibuffer prompt, - -- `embark-verbose-indicator', which pops up a buffer containing - detailed information including key bindings and the first line - of the docstring of the commands they run, and - -- `embark-mixed-indicator', which combines the minimal and the - verbose indicator: the minimal indicator is shown first and the - verbose popup is shown after `embark-mixed-indicator-delay' - seconds. - -- `embark-highlight-indicator', which highlights the target - at point. - -- `embark-isearch-highlight-indicator', which when the target at - point is an identifier or symbol, lazily highlights all - occurrences of it. - -The protocol for indicator functions is as follows: - -When called from `embark-act', an indicator function is called -without arguments. The indicator function should then return a -closure, which captures the indicator state. The returned -closure must accept up to three optional arguments, the action -keymap, the targets (plists as returned by `embark--targets') and -the prefix keys typed by the user so far. The keymap, targets -and prefix keys may be updated when cycling targets at point -resulting in multiple calls to the closure. When called from -`embark-become', the indicator closure will be called with the -keymap of commands to become, a fake target list containing a -single target of type `embark-become' and whose value is the -minibuffer input, and the prefix set to nil. Note, in -particular, that if an indicator function wishes to distinguish -between `embark-act' and `embark-become' it should check whether -the `car' of the first target is `embark-become'. - -After the action has been performed the indicator closure is -called without arguments, such that the indicator can perform the -necessary cleanup work. For example, if the indicator adds -overlays, it should remove these overlays. The indicator should -be written in a way that it is safe to call it for cleanup more -than once, in fact, it should be able to handle any sequence of -update and cleanup calls ending in a call for cleanup. - -NOTE: Experience shows that the indicator calling convention may -change again in order to support more action features. The -calling convention should currently be considered unstable. -Please keep this in mind when writing a custom indicator -function, or when using the `which-key' indicator function from -the wiki." - :type '(repeat - (choice - (const :tag "Verbose indicator" embark-verbose-indicator) - (const :tag "Minimal indicator" embark-minimal-indicator) - (const :tag "Mixed indicator" embark-mixed-indicator) - (const :tag "Highlight target" embark-highlight-indicator) - (const :tag "Highlight all occurrences" - embark-isearch-highlight-indicator) - (function :tag "Other")))) - -(defface embark-verbose-indicator-documentation - '((t :inherit completions-annotations)) - "Face used by the verbose action indicator to display binding descriptions. -Used by `embark-verbose-indicator'.") - -(defface embark-verbose-indicator-title '((t :height 1.1 :weight bold)) - "Face used by the verbose action indicator for the title. -Used by `embark-verbose-indicator'.") - -(defface embark-verbose-indicator-shadowed '((t :inherit shadow)) - "Face used by the verbose action indicator for the shadowed targets. -Used by `embark-verbose-indicator'.") - -(defcustom embark-verbose-indicator-display-action - '(display-buffer-reuse-window) - "Parameters added to `display-buffer-alist' to show the actions buffer. -See the docstring of `display-buffer' for information on what -display actions and parameters are available." - :type `(choice - (const :tag "Reuse some window" - (display-buffer-reuse-window)) - (const :tag "Below target buffer" - (display-buffer-below-selected - (window-height . fit-window-to-buffer))) - (const :tag "Bottom of frame (fixed-size)" - (display-buffer-at-bottom)) - (const :tag "Bottom of frame (resizes during cycling)" - (display-buffer-at-bottom - (window-height . fit-window-to-buffer))) - (const :tag "Side window on the right" - (display-buffer-in-side-window (side . right))) - (const :tag "Side window on the left" - (display-buffer-in-side-window (side . left))) - (sexp :tag "Other"))) - -(defcustom embark-verbose-indicator-excluded-actions nil - "Commands not displayed by `embark-verbose-indicator'. -This variable should be set to a list of symbols and regexps. -The verbose indicator will exclude from its listing any commands -matching an element of this list." - :type '(choice - (const :tag "Exclude nothing" nil) - (const :tag "Exclude Embark general actions" - (embark-collect embark-live embark-export - embark-cycle embark-act-all embark-keymap-help - embark-become embark-isearch-forward - embark-isearch-backward)) - (repeat :tag "Other" (choice regexp symbol)))) - -(defcustom embark-verbose-indicator-buffer-sections - `(target "\n" shadowed-targets " " cycle "\n" bindings) - "List of sections to display in the verbose indicator buffer, in order. -You can use either a symbol designating a concrete section (one -of the keywords below, but without the colon), a string literal -or a function returning a string or list of strings to insert and -that accepts the following keyword arguments: - -- `:target', the target as a cons of type and value, -- `:shadowed-targets', a list of conses for the other targets, -- `:bindings' a list returned by `embark--formatted-bindings', and -- `:cycle', a string describing the key binding of `embark-cycle'." - :type '(repeat - (choice (const :tag "Current target name" target) - (const :tag "List of other shadowed targets" shadowed-targets) - (const :tag "Key bindings" bindings) - (const :tag "Cycle indicator" cycle) - (string :tag "Literal string") - (function :tag "Custom function")))) - -(defcustom embark-verbose-indicator-nested t - "Whether the verbose indicator should use nested keymap navigation. -When this variable is non-nil the actions buffer displayed by -`embark-verbose-indicator' will include any prefix keys found in -the keymap it is displaying, and will update to show what is -bound under the prefix if the prefix is pressed. If this -variable is nil, then the actions buffer will contain a flat list -of all full key sequences bound in the keymap." - :type 'boolean) - -(defun embark--verbose-indicator-excluded-p (cmd) - "Return non-nil if CMD should be excluded from the verbose indicator." - (seq-find (lambda (x) - (if (symbolp x) - (eq cmd x) - (string-match-p x (symbol-name cmd)))) - embark-verbose-indicator-excluded-actions)) - -(cl-defun embark--verbose-indicator-section-target - (&key targets bindings &allow-other-keys) - "Format the TARGETS section for the indicator buffer. -BINDINGS is the formatted list of keybindings." - (let ((result (embark--format-targets - (car targets) - nil ; the shadowed targets section deals with these - (cl-find 'embark-done bindings :key #'caddr :test #'eq)))) - (add-face-text-property 0 (length result) - 'embark-verbose-indicator-title - 'append - result) - result)) - -(cl-defun embark--verbose-indicator-section-cycle - (&key cycle shadowed-targets &allow-other-keys) - "Format the CYCLE key section for the indicator buffer. -SHADOWED-TARGETS is the list of other targets." - (concat - (and cycle (propertize (format "(%s to cycle)" cycle) - 'face 'embark-verbose-indicator-shadowed)) - (and shadowed-targets "\n"))) - -(cl-defun embark--verbose-indicator-section-shadowed-targets - (&key shadowed-targets &allow-other-keys) - "Format the SHADOWED-TARGETS section for the indicator buffer." - (when shadowed-targets - (propertize (format "Shadowed targets at point: %s" - (string-join shadowed-targets ", ")) - 'face 'embark-verbose-indicator-shadowed))) - -(cl-defun embark--verbose-indicator-section-bindings - (&key bindings &allow-other-keys) - "Format the BINDINGS section for the indicator buffer." - (let* ((max-width (apply #'max (cons 0 (mapcar (lambda (x) - (string-width (car x))) - bindings)))) - (fmt (format "%%-%ds" (1+ max-width))) - (result nil)) - (dolist (binding bindings (string-join (nreverse result))) - (let ((cmd (caddr binding))) - (unless (embark--verbose-indicator-excluded-p cmd) - (let ((keys (format fmt (car binding))) - (doc (embark--function-doc cmd))) - (push (format "%s%s\n" keys - (propertize - (car (split-string (or doc "") "\n")) - 'face 'embark-verbose-indicator-documentation)) - result))))))) - -(defun embark--verbose-indicator-update (keymap targets) - "Update verbose indicator buffer. -The arguments are the new KEYMAP and TARGETS." - (with-current-buffer (get-buffer-create embark--verbose-indicator-buffer) - (let* ((inhibit-read-only t) - (bindings - (embark--formatted-bindings keymap embark-verbose-indicator-nested)) - (bindings (car bindings)) - (shadowed-targets (mapcar - (lambda (x) (symbol-name (plist-get x :type))) - (cdr targets))) - (cycle (let ((ck (where-is-internal #'embark-cycle keymap))) - (and ck (key-description (car ck)))))) - (setq-local cursor-type nil) - (setq-local truncate-lines t) - (setq-local buffer-read-only t) - (erase-buffer) - (dolist (section embark-verbose-indicator-buffer-sections) - (insert - (if (stringp section) - section - (or (funcall - (let ((prefixed (intern (format - "embark--verbose-indicator-section-%s" - section)))) - (cond - ((fboundp prefixed) prefixed) - ((fboundp section) section) - (t (error "Undefined verbose indicator section `%s'" - section)))) - :targets targets :shadowed-targets shadowed-targets - :bindings bindings :cycle cycle) - "")))) - (goto-char (point-min))))) - -(defun embark-verbose-indicator () - "Indicator that displays a table of key bindings in a buffer. -The default display includes the type and value of the current -target, the list of other target types, and a table of key -bindings, actions and the first line of their docstrings. - -The order and formatting of these items is completely -configurable through the variable -`embark-verbose-indicator-buffer-sections'. - -If the keymap being shown contains prefix keys, the table of key -bindings can either show just the prefixes and update once the -prefix is pressed, or it can contain a flat list of all full key -sequences bound in the keymap. This is controlled by the -variable `embark-verbose-indicator-nested'. - -To reduce clutter in the key binding table, one can set the -variable `embark-verbose-indicator-excluded-actions' to a list -of symbols and regexps matching commands to exclude from the -table. - -To configure how a window is chosen to display this buffer, see -the variable `embark-verbose-indicator-display-action'." - (lambda (&optional keymap targets prefix) - (if (not keymap) - (when-let ((win (get-buffer-window embark--verbose-indicator-buffer - 'visible))) - (quit-window 'kill-buffer win)) - (embark--verbose-indicator-update - (if (and prefix embark-verbose-indicator-nested) - ;; Lookup prefix keymap globally if not found in action keymap - (let ((overriding-terminal-local-map keymap)) - (key-binding prefix 'accept-default)) - keymap) - targets) - (let ((display-buffer-alist - `(,@display-buffer-alist - (,(regexp-quote embark--verbose-indicator-buffer) - ,@embark-verbose-indicator-display-action)))) - (display-buffer embark--verbose-indicator-buffer))))) - -(defcustom embark-mixed-indicator-delay 0.5 - "Time in seconds after which the verbose indicator is shown. -The mixed indicator starts by showing the minimal indicator and -after this delay shows the verbose indicator." - :type '(choice (const :tag "No delay" 0) - (number :tag "Delay in seconds"))) - -(defcustom embark-mixed-indicator-both nil - "Show both indicators, even after the verbose indicator appeared." - :type 'boolean) - -(defun embark-mixed-indicator () - "Mixed indicator showing keymap and targets. -The indicator shows the `embark-minimal-indicator' by default. -After `embark-mixed-indicator-delay' seconds, the -`embark-verbose-indicator' is shown. This which-key-like approach -ensures that Embark stays out of the way for quick actions. The -helpful keybinding reminder still pops up automatically without -further user intervention." - (let ((vindicator (embark-verbose-indicator)) - (mindicator (embark-minimal-indicator)) - vindicator-active - vtimer) - (lambda (&optional keymap targets prefix) - ;; Always cancel the timer. - ;; 1. When updating, cancel timer, since the user has pressed - ;; a key before the timer elapsed. - ;; 2. For cleanup, the timer must also be canceled. - (when vtimer - (cancel-timer vtimer) - (setq vtimer nil)) - (if (not keymap) - (progn - (funcall vindicator) - (when mindicator - (funcall mindicator))) - (when mindicator - (funcall mindicator keymap targets prefix)) - (if vindicator-active - (funcall vindicator keymap targets prefix) - (setq vtimer - (run-at-time - embark-mixed-indicator-delay nil - (lambda () - (when (and (not embark-mixed-indicator-both) mindicator) - (funcall mindicator) - (setq mindicator nil)) - (setq vindicator-active t) - (funcall vindicator keymap targets prefix))))))))) - -;;;###autoload -(defun embark-bindings-in-keymap (keymap) - "Explore command key bindings in KEYMAP with `completing-read'. -The selected command will be executed. Interactively, prompt the -user for a KEYMAP variable." - (interactive - (list - (symbol-value - (intern-soft - (completing-read - "Keymap: " - (embark--with-category - 'variable - (cl-loop for x being the symbols - if (and (boundp x) (keymapp (symbol-value x))) - collect (symbol-name x))) - nil t nil 'variable-name-history - (let ((major-mode-map - (concat (symbol-name major-mode) "-map"))) - (when (intern-soft major-mode-map) major-mode-map))))))) - (when-let (command (embark-completing-read-prompter keymap nil 'no-default)) - (call-interactively command))) - -;;;###autoload -(defun embark-bindings (global) - "Explore current command key bindings with `completing-read'. -The selected command will be executed. - -This shows key bindings from minor mode maps and the local -map (usually set by the major mode), but also less common keymaps -such as those from a text property or overlay, or the overriding -maps: `overriding-terminal-local-map' and `overriding-local-map'. - -Additionally, if GLOBAL is non-nil (interactively, if called with -a prefix argument), this command includes global key bindings." - (interactive "P") - (embark-bindings-in-keymap - (make-composed-keymap - (let ((all-maps (current-active-maps t))) - (if global all-maps (remq global-map all-maps)))))) - -;;;###autoload -(defun embark-bindings-at-point () - "Explore all key bindings at point with `completing-read'. -The selected command will be executed. - -This command lists key bindings found in keymaps specified by the -text properties `keymap' or `local-map', from either buffer text -or an overlay. These are not widely used in Emacs, and when they -are used can be somewhat hard to discover. Examples of locations -that have such a keymap are links and images in `eww' buffers, -attachment links in `gnus' article buffers, and the stash line -in a `vc-dir' buffer." - (interactive) - (if-let ((keymaps (delq nil (list (get-char-property (point) 'keymap) - (get-char-property (point) 'local-map))))) - (embark-bindings-in-keymap (make-composed-keymap keymaps)) - (user-error "No key bindings found at point"))) - -;;;###autoload -(defun embark-prefix-help-command () - "Prompt for and run a command bound in the prefix used for this command. -The prefix described consists of all but the last event of the -key sequence that ran this command. This function is intended to -be used as a value for `prefix-help-command'. - -In addition to using completion to select a command, you can also -type @ and the key binding (without the prefix)." - (interactive) - (when-let ((keys (this-command-keys-vector)) - (prefix (seq-take keys (1- (length keys)))) - (keymap (key-binding prefix 'accept-default))) - (minibuffer-with-setup-hook - (lambda () - (let ((pt (- (minibuffer-prompt-end) 2))) - (overlay-put (make-overlay pt pt) 'before-string - (format " under %s" (key-description prefix))))) - (embark-bindings-in-keymap keymap)))) - -(defun embark--prompt (indicators keymap targets) - "Call the prompter with KEYMAP and INDICATORS. -The TARGETS are displayed for actions outside the minibuffer." - (mapc (lambda (i) (funcall i keymap targets)) indicators) - (condition-case nil - (minibuffer-with-setup-hook - (lambda () - ;; if the prompter opens its own minibuffer, show - ;; the indicator there too - (let ((inner-indicators (mapcar #'funcall embark-indicators))) - (mapc (lambda (i) (funcall i keymap targets)) inner-indicators) - (add-hook 'minibuffer-exit-hook - (lambda () (mapc #'funcall inner-indicators)) - nil t))) - (let ((enable-recursive-minibuffers t)) - (funcall embark-prompter keymap - (lambda (prefix) - (mapc (lambda (i) (funcall i keymap targets prefix)) - indicators))))) - (quit nil))) - -(defvar embark--run-after-command-functions nil - "Abnormal hook, used by `embark--run-after-command'.") - -(defun embark--run-after-command (fn &rest args) - "Call FN with ARGS after the current commands finishes. -If multiple functions are queued with this function during the -same command, they will be called in the order from the one -queued most recently to the one queued least recently." - ;; We don't simply add FN to `post-command-hook' because FN may recursively - ;; call this function. In that case, FN would modify `post-command-hook' - ;; from within post-command-hook, which doesn't behave properly in our case. - ;; We use our own abnormal hook and run it from PCH in a way that it is OK to - ;; modify it from within its own functions. - (unless embark--run-after-command-functions - (let (pch timer has-run) - (setq pch - (lambda () - (remove-hook 'post-command-hook pch) - (cancel-timer timer) - (unless has-run - (setq has-run t) - (while embark--run-after-command-functions - ;; The following funcall may recursively call - ;; `embark--run-after-command', modifying - ;; `embark--run-after-command-functions'. This is why this - ;; loop has to be implemented carefully. We have to pop the - ;; function off the hook before calling it. Using `dolist' - ;; on the hook would also be incorrect, because it wouldn't - ;; take modifications of this hook into account. - (with-demoted-errors "embark PCH: %S" - (condition-case nil - (funcall (pop embark--run-after-command-functions)) - (quit (message "Quit")))))))) - (add-hook 'post-command-hook pch 'append) - ;; Generally we prefer `post-command-hook' because it plays well with - ;; keyboard macros. In some cases, `post-command-hook' isn't run after - ;; exiting a recursive edit, so set up the following timer as a backup. - (setq timer (run-at-time 0 nil pch)))) - - ;; Keep the default-directory alive, since this is often overwritten, - ;; for example by Consult commands. - ;; TODO it might be necessary to add more dynamically bound variables - ;; here. What we actually want are functions `capture-dynamic-scope' - ;; and `eval-in-dynamic-scope', but this does not exist? - (let ((dir default-directory)) - (push (lambda () - (let ((default-directory dir)) - (apply fn args))) - embark--run-after-command-functions))) - -(defun embark--quit-and-run (fn &rest args) - "Quit the minibuffer and then call FN with ARGS. -If called outside the minibuffer, simply apply FN to ARGS." - (if (not (minibufferp)) - (apply fn args) - (apply #'embark--run-after-command fn args) - (embark--run-after-command #'set 'ring-bell-function ring-bell-function) - (setq ring-bell-function #'ignore) - (minibuffer-quit-recursive-edit))) - -(defun embark--run-action-hooks (hooks action target quit) - "Run HOOKS for ACTION. -The HOOKS argument must be alist. The keys t and :always are -treated specially. The :always hooks are executed always and the -t hooks are the default hooks, for when there are no -command-specific hooks for ACTION. The QUIT, ACTION and TARGET -arguments are passed to the hooks as keyword arguments." - (mapc (lambda (h) (apply h :action action :quit quit target)) - (or (alist-get action hooks) - (alist-get t hooks))) - (mapc (lambda (h) (apply h :action action :quit quit target)) - (alist-get :always hooks))) - -(defun embark--run-around-action-hooks - (action target quit &optional non-interactive) - "Run the `embark-around-action-hooks' for ACTION. -All the applicable around hooks are composed in the order they -are present in `embark-around-action-hooks'. The keys t and -:always in `embark-around-action-hooks' are treated specially. -The :always hooks are executed always (outermost) and the t hooks -are the default hooks, for when there are no command-specific -hooks for ACTION. The QUIT, ACTION and TARGET arguments are -passed to the hooks as keyword arguments. - -The optional argument NON-INTERACTIVE controls whether the action -is run with `command-execute' or with `funcall' passing the -target as argument." - (apply - (seq-reduce - (lambda (fn hook) - (lambda (&rest args) (apply hook (plist-put args :run fn)))) - (let ((hooks embark-around-action-hooks)) - (reverse - (append (or (alist-get action hooks) (alist-get t hooks)) - (alist-get :always hooks)))) - (if non-interactive - (lambda (&rest args) - (funcall (plist-get args :action) - (or (plist-get args :candidates) (plist-get args :target)))) - (lambda (&rest args) - (command-execute (plist-get args :action))))) - :action action :quit quit target)) - -(defun embark--act (action target &optional quit) - "Perform ACTION injecting the TARGET. -If called from a minibuffer with non-nil QUIT, quit the -minibuffer before executing the action." - (if (memq action '(embark-become ; these actions should run in - embark-collect ; the current buffer, not the - embark-live ; target buffer - embark-export - embark-select - embark-act-all)) - (progn - (embark--run-action-hooks embark-pre-action-hooks action target quit) - (unwind-protect (embark--run-around-action-hooks action target quit) - (embark--run-action-hooks embark-post-action-hooks - action target quit))) - (let* ((command embark--command) - (prefix prefix-arg) - (action-window (embark--target-window t)) - (directory default-directory) - (inject - (lambda () - (let ((contents (minibuffer-contents))) - (delete-minibuffer-contents) - (insert - (propertize - (substring-no-properties (plist-get target :target)) - 'embark--initial-input contents))) - (if (memq 'ivy--queue-exhibit post-command-hook) - ;; Ivy has special needs: (1) for file names - ;; ivy-immediate-done is not equivalent to - ;; exit-minibuffer, (2) it needs a chance to run - ;; its post command hook first, so use depth 10 - (add-hook 'post-command-hook 'ivy-immediate-done 10 t) - (add-hook 'post-command-hook #'exit-minibuffer nil t)) - (embark--run-action-hooks embark-target-injection-hooks - action target quit))) - (dedicate (and (derived-mode-p 'embark-collect-mode) - (not (window-dedicated-p)) - (selected-window))) - (multi (memq action embark-multitarget-actions)) - (run-action - (if (and (commandp action) (not multi)) - (lambda () - (let (final-window) - (when dedicate (set-window-dedicated-p dedicate t)) - (unwind-protect - (with-selected-window action-window - (let ((enable-recursive-minibuffers t) - (embark--command command) - (prefix-arg prefix) - ;; the next two avoid mouse dialogs - (use-dialog-box nil) - (last-nonmenu-event 13) - (default-directory directory)) - (embark--run-action-hooks embark-pre-action-hooks - action target quit) - (minibuffer-with-setup-hook inject - ;; pacify commands that use (this-command-keys) - (when (= (length (this-command-keys)) 0) - (set--this-command-keys - (if (characterp last-command-event) - (string last-command-event) - "\r"))) - (setq this-command action) - (embark--run-around-action-hooks - action target quit))) - (setq final-window (selected-window))) - (embark--run-action-hooks embark-post-action-hooks - action target quit) - (when dedicate (set-window-dedicated-p dedicate nil))) - (unless (eq final-window action-window) - (select-window final-window)))) - (let ((target - (if (and multi (null (plist-get target :candidates))) - (plist-put - target :candidates (list (plist-get target :target))) - target))) - (lambda () - (with-selected-window action-window - (embark--run-action-hooks embark-pre-action-hooks - action target quit) - (unwind-protect - (let ((current-prefix-arg prefix) - (default-directory directory)) - (embark--run-around-action-hooks - action target quit :non-interactive)) - (embark--run-action-hooks embark-post-action-hooks - action target quit)))))))) - (setq prefix-arg nil) - (if quit (embark--quit-and-run run-action) (funcall run-action))))) - -(defun embark--refine-multi-category (_type target) - "Refine `multi-category' TARGET to its actual type." - (or (let ((mc (get-text-property 0 'multi-category target))) - (cond - ;; The `cdr' of the `multi-category' property can be a buffer object. - ((and (eq (car mc) 'buffer) (buffer-live-p (cdr mc))) - (cons 'buffer (buffer-name (cdr mc)))) - ((stringp (cdr mc)) mc))) - (cons 'general target))) - -(defun embark--simplify-path (_type target) - "Simplify and '//' or '~/' in the TARGET file path." - (cons 'file (substitute-in-file-name target))) - -(defun embark--keybinding-command (_type target) - "Treat an `embark-keybinding' TARGET as a command." - (when-let ((cmd (get-text-property 0 'embark-command target))) - (cons 'command (format "%s" cmd)))) - -(defun embark--lookup-lighter-minor-mode (_type target) - "If TARGET is a lighter, look up its minor mode. - -The `describe-minor-mode' command has as completion candidates -both minor-modes and their lighters. This function replaces the -lighters by their minor modes, so actions expecting a function -work on them." - (cons 'minor-mode - (let ((symbol (intern-soft target))) - (if (and symbol (boundp symbol)) - target - (symbol-name (lookup-minor-mode-from-indicator target)))))) - -(declare-function project-current "project") -(declare-function project-root "project") - -(defun embark--project-file-full-path (_type target) - "Get full path of project file TARGET." - ;; TODO project-find-file can be called from outside all projects in - ;; which case it prompts for a project first; we don't support that - ;; case yet, since there is no current project. - (cons 'file - (if-let ((project (project-current)) - (root (project-root project))) - (expand-file-name target root) - target))) - -(defun embark--remove-package-version (_type target) - "Remove version number from a versioned package TARGET." - (cons 'package (replace-regexp-in-string "-[0-9.]+$" "" target))) - -(defun embark--targets () - "Retrieve current targets. - -An initial guess at the current targets and their types is -determined by running the functions in `embark-target-finders'. -Each function should either return nil, a pair of a type symbol -and target string or a triple of a type symbol, target string and -target bounds. - -In the minibuffer only the first target finder returning non-nil -is taken into account. When finding targets at point in other -buffers, all target finder functions are executed. - -For each target, the type is then looked up as a key in the -variable `embark-transformer-alist'. If there is a transformer -for the type, it is called with the type and target, and must -return a `cons' of the transformed type and transformed target. - -The return value of `embark--targets' is a list of plists. Each -plist concerns one target, and has keys `:type', `:target', -`:orig-type', `:orig-target' and `:bounds'." - (let (targets) - (run-hook-wrapped - 'embark-target-finders - (lambda (fun) - (dolist (found (when-let (result (funcall fun)) - (if (consp (car result)) result (list result)))) - (let* ((type (or (car found) 'general)) - (target+bounds (cdr found)) - (target (if (consp target+bounds) - (car target+bounds) - target+bounds)) - (bounds (and (consp target+bounds) (cdr target+bounds))) - (full-target - (append - (list :orig-type type :orig-target target :bounds bounds) - (if-let (transform (alist-get type embark-transformer-alist)) - (let ((trans (funcall transform type target))) - (list :type (car trans) :target (cdr trans))) - (list :type type :target target))))) - (push full-target targets))) - (and targets (minibufferp)))) - (nreverse - (cl-delete-duplicates ; keeps last duplicate, but we reverse - targets - :test (lambda (t1 t2) - (and (equal (plist-get t1 :target) (plist-get t2 :target)) - (eq (plist-get t1 :type) (plist-get t2 :type)))))))) - -(defun embark--default-action (type) - "Return default action for the given TYPE of target. -The most common case is that the target comes from minibuffer -completion, in which case the default action is the command that -opened the minibuffer in the first place. This can be overridden -by `embark-default-action-overrides'. - -For targets that do not come from minibuffer completion -\(typically some thing at point in a regular buffer) and whose -type is not listed in `embark-default-action-overrides', the -default action is given by whatever binding RET has in the action -keymap for the given type." - (or (alist-get (cons type embark--command) embark-default-action-overrides - nil nil #'equal) - (alist-get type embark-default-action-overrides) - (alist-get t embark-default-action-overrides) - embark--command - (lookup-key (embark--raw-action-keymap type) "\r"))) - -(defun embark--rotate (list k) - "Rotate LIST by K elements and return the rotated list." - (setq k (mod k (length list))) - (append (seq-drop list k) (seq-take list k))) - -(defun embark--orig-target (target) - "Convert TARGET to original target." - (plist-put - (plist-put - (copy-sequence target) - :target (plist-get target :orig-target)) - :type (plist-get target :orig-type))) - -(defun embark--quit-p (action) - "Determine whether to quit the minibuffer after ACTION. -This function consults `embark-quit-after-action' to decide -whether or not the user wishes to quit the minibuffer after -performing the ACTION, assuming this is done from a minibuffer." - (let* ((cfg embark-quit-after-action) - (quit (if (consp cfg) (alist-get action cfg (alist-get t cfg)) cfg))) - (when embark--toggle-quit (setq quit (not quit))) - (setq embark--toggle-quit nil) - quit)) - -;;;###autoload -(defun embark-act (&optional arg) - "Prompt the user for an action and perform it. -The targets of the action are chosen by `embark-target-finders'. -By default, if called from a minibuffer the target is the top -completion candidate. When called from a non-minibuffer buffer -there can multiple targets and you can cycle among them by using -`embark-cycle' (which is bound by default to the same key -binding `embark-act' is, but see `embark-cycle-key'). - -This command uses `embark-prompter' to ask the user to specify an -action, and calls it injecting the target at the first minibuffer -prompt. - -If you call this from the minibuffer, it can optionally quit the -minibuffer. The variable `embark-quit-after-action' controls -whether calling `embark-act' with nil ARG quits the minibuffer, -and if ARG is non-nil it will do the opposite. Interactively, -ARG is the prefix argument. - -If instead you call this from outside the minibuffer, the first -ARG targets are skipped over (if ARG is negative the skipping is -done by cycling backwards) and cycling starts from the following -target." - (interactive "P") - (let* ((targets (or (embark--targets) (user-error "No target found"))) - (indicators (mapcar #'funcall embark-indicators)) - (default-done nil)) - (when arg - (if (minibufferp) - (embark-toggle-quit) - (setq targets (embark--rotate targets (prefix-numeric-value arg))))) - (unwind-protect - (while - (let* ((target (car targets)) - (action - (or (embark--prompt - indicators - (let ((embark-default-action-overrides - (if default-done - `((t . ,default-done)) - embark-default-action-overrides))) - (embark--action-keymap (plist-get target :type) - (cdr targets))) - targets) - (user-error "Canceled"))) - (default-action (or default-done - (embark--default-action - (plist-get target :type))))) - (cond - ;; When acting twice in the minibuffer, do not restart - ;; `embark-act'. Otherwise the next `embark-act' will - ;; find a target in the original buffer. - ((eq action #'embark-act) - (message "Press an action key")) - ((eq action #'embark-cycle) - (setq targets (embark--rotate - targets (prefix-numeric-value prefix-arg)))) - (t - ;; if the action is non-repeatable, cleanup indicator now - (let ((repeat (embark--action-repeatable-p action))) - (unless repeat (mapc #'funcall indicators)) - (condition-case err - (embark--act - action - (if (and (eq action default-action) - (eq action embark--command) - (not (memq action embark-multitarget-actions))) - (embark--orig-target target) - target) - (embark--quit-p action)) - (user-error - (funcall (if repeat #'message #'user-error) - "%s" (cadr err)))) - (when-let (new-targets (and repeat (embark--targets))) - ;; Terminate repeated prompter on default action, - ;; when repeating. Jump to the region type if the - ;; region is active after the action, or else to the - ;; current type again. - (setq default-done #'embark-done - targets - (embark--rotate - new-targets - (or (cl-position-if - (let ((desired-type - (if (eq repeat t) - (plist-get (car targets) :type) - repeat))) - (lambda (x) - (eq (plist-get x :type) desired-type))) - new-targets) - 0))))))))) - (mapc #'funcall indicators)))) - -(defun embark--maybe-transform-candidates () - "Collect candidates and see if they all transform to the same type. -Return a plist with keys `:type', `:orig-type', `:candidates', and -`:orig-candidates'." - (pcase-let* ((`(,type . ,candidates) - (run-hook-with-args-until-success 'embark-candidate-collectors)) - (bounds (mapcar #'cdr-safe candidates))) - (setq candidates - (mapcar (lambda (x) (if (consp x) (car x) x)) candidates)) - (when (eq type 'file) - (let ((dir (embark--default-directory))) - (setq candidates - (mapcar (lambda (cand) - (abbreviate-file-name - (expand-file-name (substitute-in-file-name cand) dir))) - candidates)))) - ;; TODO more systematic approach to applying substitute-in-file-name - (append - (list :orig-type type :orig-candidates candidates :bounds bounds) - (or (when candidates - (when-let ((transformer (alist-get type embark-transformer-alist))) - (pcase-let* ((`(,new-type . ,first-cand) - (funcall transformer type (car candidates)))) - (let ((new-candidates (list first-cand))) - (when (cl-every - (lambda (cand) - (pcase-let ((`(,t-type . ,t-cand) - (funcall transformer type cand))) - (when (eq t-type new-type) - (push t-cand new-candidates) - t))) - (cdr candidates)) - (list :type new-type - :candidates (nreverse new-candidates))))))) - (list :type type :candidates candidates))))) - -;;;###autoload -(defun embark-act-all (&optional arg) - "Prompt the user for an action and perform it on each candidate. -The candidates are chosen by `embark-candidate-collectors'. By -default, if `embark-select' has been used to select some -candidates, then `embark-act-all' will act on those candidates; -otherwise, if the selection is empty and `embark-act-all' is -called from a minibuffer, then the candidates are the completion -candidates. - -This command uses `embark-prompter' to ask the user to specify an -action, and calls it injecting the target at the first minibuffer -prompt. - -If you call this from the minibuffer, it can optionally quit the -minibuffer. The variable `embark-quit-after-action' controls -whether calling `embark-act' with nil ARG quits the minibuffer, -and if ARG is non-nil it will do the opposite. Interactively, -ARG is the prefix argument." - (interactive "P") - (let* ((transformed (embark--maybe-transform-candidates)) - (type (plist-get transformed :type)) - (orig-type (plist-get transformed :orig-type)) - (candidates - (or (cl-mapcar - (lambda (cand orig-cand bounds) - (list :type type :target cand - :bounds (when bounds - (cons (copy-marker (car bounds)) - (copy-marker (cdr bounds)))) - :orig-type orig-type :orig-target orig-cand)) - (plist-get transformed :candidates) - (plist-get transformed :orig-candidates) - (plist-get transformed :bounds)) - (user-error "No candidates to act on"))) - (indicators (mapcar #'funcall embark-indicators))) - (when arg (embark-toggle-quit)) - (unwind-protect - (let* ((action - (or (embark--prompt - indicators (embark--action-keymap type nil) - (list (list :type type :multi (length candidates)))) - (user-error "Canceled"))) - (prefix prefix-arg) - (act (lambda (candidate) - (cl-letf (((symbol-function 'embark--restart) #'ignore) - ((symbol-function 'embark--confirm) #'ignore)) - (let ((prefix-arg prefix)) - (when-let ((bounds (plist-get candidate :bounds))) - (goto-char (car bounds))) - (embark--act action candidate))))) - (quit (embark--quit-p action))) - (when (and (eq action (embark--default-action type)) - (eq action embark--command)) - (setq candidates (mapcar #'embark--orig-target candidates))) - (when (or (not (or embark-confirm-act-all - (memq 'embark--confirm - (alist-get action embark-pre-action-hooks)))) - (y-or-n-p (format "Run %s on %d %ss? " - action (length candidates) type))) - (if (memq action embark-multitarget-actions) - (let ((prefix-arg prefix)) - (embark--act action transformed quit)) - (save-excursion - (if quit - (embark--quit-and-run #'mapc act candidates) - (mapc act candidates)))) - (when (and (not quit) - (memq 'embark--restart - (alist-get action embark-post-action-hooks))) - (embark--restart)))) - (dolist (cand candidates) - (when-let ((bounds (plist-get cand :bounds))) - (set-marker (car bounds) nil) ; yay, manual memory management! - (set-marker (cdr bounds) nil))) - (setq prefix-arg nil) - (mapc #'funcall indicators)))) - -(defun embark-highlight-indicator () - "Action indicator highlighting the target at point." - (let (overlay) - (lambda (&optional keymap targets _prefix) - (let ((bounds (plist-get (car targets) :bounds))) - (when (and overlay (or (not keymap) (not bounds))) - (delete-overlay overlay) - (setq overlay nil)) - (when bounds - (if overlay - (move-overlay overlay (car bounds) (cdr bounds)) - (setq overlay (make-overlay (car bounds) (cdr bounds))) - (overlay-put overlay 'category 'embark-target-overlay)) - (overlay-put overlay 'window (selected-window))))))) - -(defun embark-isearch-highlight-indicator () - "Action indicator highlighting all occurrences of the identifier at point. -This indicator only does something for targets which are -identifiers or symbols. For those it uses `isearch''s lazy -highlighting feature to highlight all occurrences of the target in -the buffer. This indicator is best used in conjunction with -`embark-highlight-indicator': by using them both you get the -target and the other occurrences of it highlighted in different -colors." - (lambda (&optional _keymap targets _prefix) - (if (and (not (minibufferp)) - (memq (plist-get (car targets) :orig-type) '(symbol identifier))) - (let ((isearch-string (plist-get (car targets) :target)) - (isearch-regexp-function #'isearch-symbol-regexp)) - (isearch-lazy-highlight-new-loop)) - (setq isearch-lazy-highlight-last-string nil) - (lazy-highlight-cleanup t)))) - -(defun embark-cycle (_arg) - "Cycle over the next ARG targets at point. -If ARG is negative, cycle backwards." - (interactive "p") - (user-error "Not meant to be called directly")) - -(defun embark-done () - "Terminate sequence of repeated actions." - (interactive)) - -;;;###autoload -(defun embark-dwim (&optional arg) - "Run the default action on the current target. -The target of the action is chosen by `embark-target-finders'. - -If the target comes from minibuffer completion, then the default -action is the command that opened the minibuffer in the first -place, unless overridden by `embark-default-action-overrides'. - -For targets that do not come from minibuffer completion -\(typically some thing at point in a regular buffer) and whose -type is not listed in `embark-default-action-overrides', the -default action is given by whatever binding RET has in the action -keymap for the target's type. - -See `embark-act' for the meaning of the prefix ARG." - (interactive "P") - (if-let ((targets (embark--targets))) - (let* ((target - (or (nth - (if (or (null arg) (minibufferp)) - 0 - (mod (prefix-numeric-value arg) (length targets))) - targets))) - (type (plist-get target :type)) - (default-action (embark--default-action type)) - (action (or (command-remapping default-action) default-action))) - (unless action - (user-error "No default action for %s targets" type)) - (when (and arg (minibufferp)) (setq embark--toggle-quit t)) - (embark--act action - (if (and (eq default-action embark--command) - (not (memq default-action - embark-multitarget-actions))) - (embark--orig-target target) - target) - (embark--quit-p action))) - (user-error "No target found"))) - -(defun embark--become-keymap () - "Return keymap of commands to become for current command." - (let ((map (make-composed-keymap - (cl-loop for keymap-name in embark-become-keymaps - for keymap = (symbol-value keymap-name) - when (where-is-internal embark--command (list keymap)) - collect keymap)))) - (when embark-help-key - (keymap-set map embark-help-key #'embark-keymap-help)) - map)) - -;;;###autoload -(defun embark-become (&optional full) - "Make current command become a different command. -Take the current minibuffer input as initial input for new -command. The new command can be run normally using key bindings or -\\[execute-extended-command], but if the current command is found in a keymap in -`embark-become-keymaps', that keymap is activated to provide -convenient access to the other commands in it. - -If FULL is non-nil (interactively, if called with a prefix -argument), the entire minibuffer contents are used as the initial -input of the new command. By default only the part of the -minibuffer contents between the current completion boundaries is -taken. What this means is fairly technical, but (1) usually -there is no difference: the completion boundaries include the -entire minibuffer contents, and (2) the most common case where -these notions differ is file completion, in which case the -completion boundaries single out the path component containing -point." - (interactive "P") - (unless (minibufferp) - (user-error "Not in a minibuffer")) - (let* ((target (embark--display-string ; remove invisible portions - (if full - (minibuffer-contents) - (pcase-let ((`(,beg . ,end) (embark--boundaries))) - (substring (minibuffer-contents) beg - (+ end (embark--minibuffer-point))))))) - (keymap (embark--become-keymap)) - (targets `((:type embark-become :target ,target))) - (indicators (mapcar #'funcall embark-indicators)) - (become (unwind-protect - (embark--prompt indicators keymap targets) - (mapc #'funcall indicators)))) - (unless become - (user-error "Canceled")) - (embark--become-command become target))) - -(defun embark--become-command (command input) - "Quit current minibuffer and start COMMAND with INPUT." - (embark--quit-and-run - (lambda () - (minibuffer-with-setup-hook - (lambda () - (delete-minibuffer-contents) - (insert input)) - (let ((use-dialog-box nil) ;; avoid mouse dialogs - (last-nonmenu-event 13)) - (setq this-command command) - (command-execute command)))))) - -;;; Embark collect - -(defgroup embark-collect nil - "Buffers for acting on collected Embark targets." - :group 'embark) - -(defcustom embark-candidate-collectors - '(embark-selected-candidates - embark-minibuffer-candidates - embark-completion-list-candidates - embark-dired-candidates - embark-ibuffer-candidates - embark-embark-collect-candidates - embark-custom-candidates) - "List of functions that collect all candidates in a given context. -These are used to fill an Embark Collect buffer. Each function -should return either nil (to indicate it found no candidates) or -a list whose first element is a symbol indicating the type of -candidates and whose `cdr' is the list of candidates, each of -which should be either a string or a dotted list of the -form (TARGET START . END), where START and END are the buffer -positions bounding the TARGET string." - :type 'hook) - -(defcustom embark-exporters-alist - '((buffer . embark-export-ibuffer) - (file . embark-export-dired) - (package . embark-export-list-packages) - (bookmark . embark-export-bookmarks) - (variable . embark-export-customize-variable) - (face . embark-export-customize-face) - (symbol . embark-export-apropos) - (minor-mode . embark-export-apropos) - (function . embark-export-apropos) - (command . embark-export-apropos) - (t . embark-collect)) - "Alist associating completion types to export functions. -Each function should take a list of strings which are candidates -for actions and make a buffer appropriate to manage them. For -example, the default is to make a Dired buffer for files, and an -ibuffer for buffers. - -The key t is also allowed in the alist, and the corresponding -value indicates the default function to use for other types. The -default is `embark-collect'" - :type '(alist :key-type symbol :value-type function)) - -(defcustom embark-after-export-hook nil - "Hook run after `embark-export' in the newly created buffer." - :type 'hook) - -(defface embark-collect-candidate '((t :inherit default)) - "Face for candidates in Embark Collect buffers.") - -(defface embark-collect-group-title - '((t :inherit shadow :slant italic)) - "Face for group titles in Embark Collect buffers.") - -(defface embark-collect-group-separator - '((t :inherit shadow :strike-through t italic)) - "Face for group titles in Embark Collect buffers.") - -(defcustom embark-collect-group-format - (concat - (propertize " " 'face 'embark-collect-group-separator) - (propertize " %s " 'face 'embark-collect-group-title) - (propertize " " 'face 'completions-group-separator - 'display '(space :align-to right))) - "Format string used for the group title in Embark Collect buffers." - :type 'string) - -(defface embark-collect-annotation '((t :inherit completions-annotations)) - "Face for annotations in Embark Collect. -This is only used for annotation that are not already fontified.") - -(defvar-local embark--rerun-function nil - "Function to rerun the collect or export that made the current buffer.") - -(autoload 'package-delete "package") -(declare-function package--from-builtin "package") -(declare-function package-desc-extras "package") -(declare-function package-desc-name "package") -(defvar package--builtins) -(defvar package-alist) -(defvar package-archive-contents) -(defvar package--initialized) - -(defun embark--package-desc (pkg) - "Return the description structure for package PKG." - (or ; found this in `describe-package-1' - (car (alist-get pkg package-alist)) - (if-let ((built-in (assq pkg package--builtins))) - (package--from-builtin built-in) - (car (alist-get pkg package-archive-contents))))) - -(defun embark-minibuffer-candidates () - "Return all current completion candidates from the minibuffer." - (when (minibufferp) - (let* ((all (completion-all-completions - (minibuffer-contents) - minibuffer-completion-table - minibuffer-completion-predicate - (embark--minibuffer-point))) - (last (last all))) - (when last (setcdr last nil)) - (cons - (completion-metadata-get (embark--metadata) 'category) - all)))) - -(defun embark-sorted-minibuffer-candidates () - "Return a sorted list of current minibuffer completion candidates. -This using the same sort order that `icomplete' and -`minibuffer-force-complete' use. The intended usage is that you -replace `embark-minibuffer-candidates' with this function in the -list `embark-candidate-collectors'." - (when (minibufferp) - (cons - (completion-metadata-get (embark--metadata) 'category) - (nconc (cl-copy-list (completion-all-sorted-completions)) nil)))) - -(declare-function dired-get-marked-files "dired") -(declare-function dired-move-to-filename "dired") -(declare-function dired-move-to-end-of-filename "dired") - -(defun embark-dired-candidates () - "Return marked or all files shown in Dired buffer. -If any buffer is marked, return marked buffers; otherwise, return -all buffers." - (when (derived-mode-p 'dired-mode) - (cons 'file - (or - ;; dired-get-marked-files returns the file on the current - ;; line if no marked files are found; and when the fourth - ;; argument is non-nil, the "no marked files" case is - ;; distinguished from the "single marked file" case by - ;; returning (list t marked-file) in the latter - (let ((marked (dired-get-marked-files t nil nil t))) - (and (cdr marked) - (if (eq (car marked) t) (cdr marked) marked))) - (save-excursion - (goto-char (point-min)) - (let (files) - (while (not (eobp)) - (when-let (file (dired-get-filename t t)) - (push `(,file - ,(progn (dired-move-to-filename) (point)) - . ,(progn (dired-move-to-end-of-filename t) (point))) - files)) - (forward-line)) - (nreverse files))))))) - -(autoload 'ibuffer-marked-buffer-names "ibuffer") -(declare-function ibuffer-map-lines-nomodify "ibuffer") - -(defun embark-ibuffer-candidates () - "Return marked or all buffers listed in ibuffer buffer. -If any buffer is marked, return marked buffers; otherwise, return -all buffers." - (when (derived-mode-p 'ibuffer-mode) - (cons 'buffer - (or (ibuffer-marked-buffer-names) - (let (buffers) - (ibuffer-map-lines-nomodify - (lambda (buffer _mark) - (push (buffer-name buffer) buffers))) - (nreverse buffers)))))) - -(defun embark-embark-collect-candidates () - "Return candidates in Embark Collect buffer. -This makes `embark-export' work in Embark Collect buffers." - (when (derived-mode-p 'embark-collect-mode) - (cons embark--type - (save-excursion - (goto-char (point-min)) - (let (all) - (when-let ((cand (embark-target-collect-candidate))) - (push (cdr cand) all)) - (while (forward-button 1 nil nil t) - (when-let ((cand (embark-target-collect-candidate))) - (push (cdr cand) all))) - (nreverse all)))))) - -(defun embark-completion-list-candidates () - "Return all candidates in a completions buffer." - (when (derived-mode-p 'completion-list-mode) - (cons - embark--type - (save-excursion - (goto-char (point-min)) - (next-completion 1) - (let (all) - (while (not (eobp)) - (push (cdr (embark-target-completion-list-candidate)) all) - (next-completion 1)) - (nreverse all)))))) - -(defun embark-custom-candidates () - "Return all variables and faces listed in this `Custom-mode' buffer." - (when (derived-mode-p 'Custom-mode) - (cons 'symbol ; gets refined to variable or face when acted upon - (save-excursion - (goto-char (point-min)) - (let (symbols) - (while (not (eobp)) - (when-let (widget (widget-at (point))) - (when (eq (car widget) 'custom-visibility) - (push - `(,(symbol-name - (plist-get (cdr (plist-get (cdr widget) :parent)) - :value)) - ,(point) - . ,(progn - (re-search-forward ":" (line-end-position) 'noerror) - (point))) - symbols))) - (forward-line)) - (nreverse symbols)))))) - - -(defun embark-collect--target () - "Return the Embark Collect candidate at point. -This takes into account `embark-transformer-alist'." - (let ((embark-target-finders '(embark-target-collect-candidate))) - (car (embark--targets)))) - -(defun embark--action-command (action) - "Turn an ACTION into a command to perform the action. -Returns the name of the command." - (let ((name (intern (format "embark-action--%s" - (embark--command-name action))))) - (fset name (lambda (arg) - (interactive "P") - (when-let (target (embark-collect--target)) - (let ((prefix-arg arg)) - (embark--act action target))))) - (when (fboundp action) - (put name 'function-documentation (documentation action))) - name)) - -(defun embark--all-bindings (keymap &optional nested) - "Return an alist of all bindings in KEYMAP. -If NESTED is non-nil subkeymaps are not flattened." - (let (bindings maps) - (map-keymap - (lambda (key def) - (cond - ((keymapp def) - (if nested - (push (cons (vector key) def) maps) - (dolist (bind (embark--all-bindings def)) - (push (cons (vconcat (vector key) (car bind)) (cdr bind)) - maps)))) - (def (push (cons (vector key) def) bindings)))) - (keymap-canonicalize keymap)) - (nconc (nreverse bindings) (nreverse maps)))) - -(defun embark-collect--direct-action-map (type) - "Return a direct action keymap for targets of given TYPE." - (let* ((actions (embark--action-keymap type nil)) - (map (make-sparse-keymap))) - (set-keymap-parent map button-map) - (pcase-dolist (`(,key . ,cmd) (embark--all-bindings actions)) - (unless (or (equal key [13]) - (memq cmd '(digit-argument negative-argument))) - (define-key map key (if (eq cmd 'embark-keymap-help) - #'embark-bindings-at-point - (embark--action-command cmd))))) - map)) - -(define-minor-mode embark-collect-direct-action-minor-mode - "Bind type-specific actions directly (without need for `embark-act')." - :init-value nil - :lighter " Act" - (unless (derived-mode-p 'embark-collect-mode) - (user-error "Not in an Embark Collect buffer")) - (save-excursion - (goto-char (point-min)) - (let ((inhibit-read-only t) maps) - (while (progn - (when (tabulated-list-get-id) - (put-text-property - (point) (button-end (point)) 'keymap - (if embark-collect-direct-action-minor-mode - (when-let ((target (embark-collect--target)) - (type (plist-get target :type))) - (or (alist-get type maps) - (setf (alist-get type maps) - (embark-collect--direct-action-map type))))))) - (forward-button 1 nil nil t)))))) - -(define-button-type 'embark-collect-entry - 'face 'embark-collect-candidate - 'action 'embark-collect-choose) - -(declare-function outline-toggle-children "outline") -(define-button-type 'embark-collect-group - 'face 'embark-collect-group-title - 'action (lambda (_) (outline-toggle-children))) - -(defun embark--boundaries () - "Get current minibuffer completion boundaries." - (let ((contents (minibuffer-contents)) - (pt (embark--minibuffer-point))) - (completion-boundaries - (substring contents 0 pt) - minibuffer-completion-table - minibuffer-completion-predicate - (substring contents pt)))) - -(defun embark-collect-choose (entry) - "Run default action on Embark Collect ENTRY." - (pcase-let ((`(,type ,text ,start . ,end) - (save-excursion - (goto-char entry) - (embark-target-collect-candidate)))) - (embark--act (embark--default-action type) - (list :target text - :type type - :bounds (cons start end))))) - -(defvar-keymap embark-collect-mode-map - :doc "Keymap for Embark collect mode." - :parent tabulated-list-mode-map - "a" #'embark-act - "A" #'embark-act-all - "M-a" #'embark-collect-direct-action-minor-mode - "E" #'embark-export - "s" #'isearch-forward - "n" #'forward-button - "p" #'backward-button - "}" 'outline-next-heading - "{" 'outline-previous-heading - "<remap> <forward-paragraph>" 'outline-next-heading - "<remap> <backward-paragraph>" 'outline-previous-heading - "<remap> <revert-buffer>" #'embark-rerun-collect-or-export) - -(defconst embark-collect--outline-string (string #x210000) - "Special string used for outline headings in Embark Collect buffers. -Chosen to be extremely unlikely to appear in a candidate.") - -(define-derived-mode embark-collect-mode tabulated-list-mode "Embark Collect" - "List of candidates to be acted on. -The command `embark-act' is bound `embark-collect-mode-map', but -you might prefer to change the key binding to match your other -key binding for it. Or alternatively you might want to enable the -embark collect direct action minor mode by adding the function -`embark-collect-direct-action-minor-mode' to -`embark-collect-mode-hook'. - -Reverting an Embark Collect buffer has slightly unusual behavior -if the buffer was obtained by running `embark-collect' from -within a minibuffer completion session. In that case reverting -just restarts the completion session, that is, the command that -opened the minibuffer is run again and the minibuffer contents -restored. You can then interact normally with the command, -perhaps editing the minibuffer contents, and, if you wish, you -can rerun `embark-collect' to get an updated buffer." - :interactive nil :abbrev-table nil :syntax-table nil) - -(defun embark-collect--metadatum (type metadatum) - "Get METADATUM for current buffer's candidates. -For non-minibuffers, assume candidates are of given TYPE." - (if (minibufferp) - (or (completion-metadata-get (embark--metadata) metadatum) - (plist-get completion-extra-properties - (intern (format ":%s" metadatum)))) - ;; otherwise fake some metadata for Marginalia users's benefit - (completion-metadata-get `((category . ,type)) metadatum))) - -(defun embark-collect--affixator (type) - "Get affixation function for current buffer's candidates. -For non-minibuffers, assume candidates are of given TYPE." - (or (embark-collect--metadatum type 'affixation-function) - (let ((annotator - (or (embark-collect--metadatum type 'annotation-function) - (lambda (_) "")))) - (lambda (candidates) - (mapcar (lambda (c) - (if-let (a (funcall annotator c)) (list c "" a) c)) - candidates))))) - -(defun embark--display-string (str) - ;; Note: Keep in sync with vertico--display-string - "Return display STR without display and invisible properties." - (let ((end (length str)) (pos 0) chunks) - (while (< pos end) - (let ((nextd (next-single-property-change pos 'display str end)) - (disp (get-text-property pos 'display str))) - (if (stringp disp) - (let ((face (get-text-property pos 'face str))) - (when face - (add-face-text-property - 0 (length disp) face t (setq disp (concat disp)))) - (setq pos nextd chunks (cons disp chunks))) - (while (< pos nextd) - (let ((nexti - (next-single-property-change pos 'invisible str nextd))) - (unless (or (get-text-property pos 'invisible str) - (and (= pos 0) (= nexti end))) ;; full=>no allocation - (push (substring str pos nexti) chunks)) - (setq pos nexti)))))) - (if chunks (apply #'concat (nreverse chunks)) str))) - -(defconst embark--hline - (propertize - (concat "\n" (propertize - " " 'display '(space :align-to right) - 'face '(:inherit completions-group-separator :height 0.01) - 'cursor-intangible t 'intangible t))) - "Horizontal line used to separate multiline collect entries.") - -(defun embark-collect--format-entries (candidates grouper) - "Format CANDIDATES for `tabulated-list-mode' grouped by GROUPER. -The GROUPER is either nil or a function like the `group-function' -completion metadatum, that is, a function of two arguments, the -first of which is a candidate and the second controls what is -computed: if nil, the title of the group the candidate belongs -to, and if non-nil, a rewriting of the candidate (useful to -simplify the candidate so it doesn't repeat the group title, for -example)." - (let ((max-width 0) - (transform - (if grouper (lambda (cand) (funcall grouper cand t)) #'identity))) - (setq - tabulated-list-entries - (mapcan - (lambda (group) - (let ((multiline (seq-some (lambda (x) (string-match-p "\n" (car x))) - candidates))) - (cons - `(nil [(,(concat (propertize embark-collect--outline-string - 'invisible t) - (format embark-collect-group-format (car group))) - type embark-collect-group) - ("" skip t)]) - (mapcar - (pcase-lambda (`(,cand ,prefix ,annotation)) - (let* ((display (embark--display-string (funcall transform cand))) - (length (length annotation)) - (faces (text-property-not-all - 0 length 'face nil annotation))) - (setq max-width (max max-width (+ (string-width prefix) - (string-width display)))) - (when faces - (add-face-text-property 0 length 'default t annotation)) - `(,cand - [(,(propertize - (if multiline (concat display embark--hline) display) - 'line-prefix prefix) - type embark-collect-entry) - (,annotation - skip t - ,@(unless faces - '(face embark-collect-annotation)))]))) - (cdr group))))) - (if grouper - (seq-group-by (lambda (item) (funcall grouper (car item) nil)) - candidates) - (list (cons "" candidates))))) - (if (null grouper) - (pop tabulated-list-entries) - (setq-local outline-regexp embark-collect--outline-string) - (outline-minor-mode)) - (setq tabulated-list-format - `[("Candidate" ,max-width t) ("Annotation" 0 t)]))) - -(defun embark-collect--update-candidates (buffer) - "Update candidates for Embark Collect BUFFER." - (let* ((transformed (embark--maybe-transform-candidates)) - (type (plist-get transformed :orig-type)) ; we need the originals for - (candidates (plist-get transformed :orig-candidates)) ; default action - (bounds (plist-get transformed :bounds)) - (affixator (embark-collect--affixator type)) - (grouper (embark-collect--metadatum type 'group-function))) - (when (eq type 'file) - (let ((dir (buffer-local-value 'default-directory buffer))) - (setq candidates - (mapcar (lambda (cand) - (let ((rel (file-relative-name cand dir))) - (if (string-prefix-p "../" rel) cand rel))) - candidates)))) - (if (seq-some #'identity bounds) - (cl-loop for cand in candidates and (start . _end) in bounds - when start - do (add-text-properties - 0 1 `(embark--location ,(copy-marker start)) cand))) - (setq candidates (funcall affixator candidates)) - (with-current-buffer buffer - (setq embark--type type) - (unless embark--command - (setq embark--command #'embark--goto)) - (embark-collect--format-entries candidates grouper)) - candidates)) - -(defun embark--goto (target) - "Jump to the original location of TARGET. -This function is used as a default action in Embark Collect -buffers when the candidates were a selection from a regular -buffer." - ;; TODO: ensure the location jumped to is visible - ;; TODO: remove duplication with embark-org-goto-heading - (when-let ((marker (get-text-property 0 'embark--location target))) - (pop-to-buffer (marker-buffer marker)) - (widen) - (goto-char marker) - (pulse-momentary-highlight-one-line))) - -(defun embark--collect (buffer-name) - "Create an Embark Collect buffer named BUFFER-NAME. - -The function `generate-new-buffer-name' is used to ensure the -buffer has a unique name." - (let ((buffer (generate-new-buffer buffer-name)) - (rerun (embark--rerun-function #'embark-collect))) - (with-current-buffer buffer - ;; we'll run the mode hooks once the buffer is displayed, so - ;; the hooks can make use of the window - (delay-mode-hooks (embark-collect-mode))) - - (embark--cache-info buffer) - (unless (embark-collect--update-candidates buffer) - (user-error "No candidates to collect")) - - (with-current-buffer buffer - (setq tabulated-list-use-header-line nil ; default to no header - header-line-format nil - tabulated-list--header-string nil) - (setq embark--rerun-function rerun)) - - (let ((window (display-buffer buffer))) - (with-selected-window window - (run-mode-hooks) - (tabulated-list-revert)) - (set-window-dedicated-p window t) - buffer))) - -(defun embark--descriptive-buffer-name (type) - "Return a descriptive name for an Embark collect or export buffer. -TYPE should be either `collect' or `export'." - (format "*Embark %s: %s*" - (capitalize (symbol-name type)) - (if (minibufferp) - (format "%s - %s" embark--command - (minibuffer-contents-no-properties)) - (buffer-name)))) - -;;;###autoload -(defun embark-collect () - "Create an Embark Collect buffer. - -To control the display, add an entry to `display-buffer-alist' -with key \"Embark Collect\". - -In Embark Collect buffers `revert-buffer' is remapped to -`embark-rerun-collect-or-export', which has slightly unusual -behavior if the buffer was obtained by running `embark-collect' -from within a minibuffer completion session. In that case -rerunning just restarts the completion session, that is, the -command that opened the minibuffer is run again and the -minibuffer contents restored. You can then interact normally with -the command, perhaps editing the minibuffer contents, and, if you -wish, you can rerun `embark-collect' to get an updated buffer." - (interactive) - (let ((buffer (embark--collect (embark--descriptive-buffer-name 'collect)))) - (when (minibufferp) - (embark--run-after-command #'pop-to-buffer buffer) - (embark--quit-and-run #'message nil)))) - -;;;###autoload -(defun embark-live () - "Create a live-updating Embark Collect buffer. - -To control the display, add an entry to `display-buffer-alist' -with key \"Embark Live\"." - (interactive) - (let ((live-buffer (embark--collect - (format "*Embark Live: %s*" - (if (minibufferp) - (format "M-x %s" embark--command) - (buffer-name))))) - (run-collect (make-symbol "run-collect")) - (stop-collect (make-symbol "stop-collect")) - timer) - (setf (symbol-function stop-collect) - (lambda () - (remove-hook 'change-major-mode-hook stop-collect t) - (remove-hook 'after-change-functions run-collect t))) - (setf (symbol-function run-collect) - (lambda (_1 _2 _3) - (unless timer - (setq timer - (run-with-idle-timer - 0.05 nil - (lambda () - (if (not (buffer-live-p live-buffer)) - (funcall stop-collect) - (embark-collect--update-candidates live-buffer) - (with-current-buffer live-buffer - ;; TODO figure out why I can't restore point - (tabulated-list-print t t)) - (setq timer nil)))))))) - (add-hook 'after-change-functions run-collect nil t) - (when (minibufferp) - (add-hook 'change-major-mode-hook stop-collect nil t)))) - -(defun embark--rerun-function (kind) - "Return a rerun function for an export or collect buffer in this context. -The parameter KIND should be either `embark-export' or `embark-collect'." - (let ((buffer (or embark--target-buffer (embark--target-buffer))) - (command embark--command)) - (cl-flet ((rerunner (action) - (lambda (&rest _) - (quit-window 'kill-buffer) - (with-current-buffer - (if (buffer-live-p buffer) buffer (current-buffer)) - (let ((embark--command command)) - (funcall action)))))) - (if (minibufferp) - (rerunner - (let ((input (minibuffer-contents-no-properties))) - (lambda () - (minibuffer-with-setup-hook - (lambda () - (delete-minibuffer-contents) - (insert input)) - (setq this-command embark--command) - (command-execute embark--command))))) - (rerunner kind))))) - -(defun embark-rerun-collect-or-export () - "Rerun the `embark-collect' or `embark-export' that created this buffer." - (interactive) - (if embark--rerun-function - (funcall embark--rerun-function) - (user-error "No function to rerun collect or export found"))) - -;;;###autoload -(defun embark-export () - "Create a type-specific buffer to manage current candidates. -The variable `embark-exporters-alist' controls how to make the -buffer for each type of completion. - -In Embark Export buffers `revert-buffer' is remapped to -`embark-rerun-collect-or-export', which has slightly unusual -behavior if the buffer was obtained by running `embark-export' -from within a minibuffer completion session. In that case -reverting just restarts the completion session, that is, the -command that opened the minibuffer is run again and the -minibuffer contents restored. You can then interact normally -with the command, perhaps editing the minibuffer contents, and, -if you wish, you can rerun `embark-export' to get an updated -buffer." - (interactive) - (let* ((transformed (embark--maybe-transform-candidates)) - (candidates (or (plist-get transformed :candidates) - (user-error "No candidates for export"))) - (type (plist-get transformed :type))) - (let ((exporter (or (alist-get type embark-exporters-alist) - (alist-get t embark-exporters-alist)))) - (if (eq exporter 'embark-collect) - (embark-collect) - (let* ((after embark-after-export-hook) - (cmd embark--command) - (name (embark--descriptive-buffer-name 'export)) - (rerun (embark--rerun-function #'embark-export)) - (buffer (save-excursion - (funcall exporter candidates) - (rename-buffer name t) - (current-buffer)))) - (embark--quit-and-run - (lambda () - (pop-to-buffer buffer) - (setq embark--rerun-function rerun) - (use-local-map - (make-composed-keymap - '(keymap - (remap keymap - (revert-buffer . embark-rerun-collect-or-export))) - (current-local-map))) - (let ((embark-after-export-hook after) - (embark--command cmd)) - (run-hooks 'embark-after-export-hook))))))))) - -(defmacro embark--export-rename (buffer title &rest body) - "Run BODY and rename BUFFER to Embark export buffer with TITLE." - (declare (indent 2)) - (let ((saved (make-symbol "saved"))) - `(let ((,saved (embark-rename-buffer - ,buffer " *Embark Saved*" t))) - ,@body - (set-buffer (embark-rename-buffer - ,buffer ,(format "*Embark Export %s*" title) t)) - (when ,saved (embark-rename-buffer ,saved ,buffer))))) - -(defun embark--export-customize (items type pred) - "Create a customization buffer listing ITEMS. -TYPE is the items type. -PRED is a predicate function used to filter the items." - (custom-buffer-create - (cl-loop for item in items - for sym = (intern-soft item) - when (and sym (funcall pred sym)) collect `(,sym ,type)))) - -(autoload 'apropos-parse-pattern "apropos") -(autoload 'apropos-symbols-internal "apropos") -(defun embark-export-apropos (symbols) - "Create apropos buffer listing SYMBOLS." - (embark--export-rename "*Apropos*" "Apropos" - (apropos-parse-pattern "") ;; Initialize apropos pattern - ;; HACK: Ensure that order of exported symbols is kept. - (cl-letf (((symbol-function #'sort) (lambda (list _pred) (nreverse list)))) - (apropos-symbols-internal - (delq nil (mapcar #'intern-soft symbols)) - (bound-and-true-p apropos-do-all))))) - -(defun embark-export-customize-face (faces) - "Create a customization buffer listing FACES." - (embark--export-customize faces 'custom-face #'facep)) - -(defun embark-export-customize-variable (variables) - "Create a customization buffer listing VARIABLES." - ;; The widget library serializes/deserializes the values. We advise - ;; the serialization in order to avoid errors for nonserializable - ;; variables. - (cl-letf* ((ht (make-hash-table :test #'equal)) - (orig-read (symbol-function #'read)) - (orig-write (symbol-function 'widget-sexp-value-to-internal)) - ((symbol-function #'read) - (lambda (&optional str) - (condition-case nil - (funcall orig-read str) - (error (gethash str ht))))) - ((symbol-function 'widget-sexp-value-to-internal) - (lambda (widget val) - (let ((str (funcall orig-write widget val))) - (puthash str val ht) - str)))) - (embark--export-customize variables 'custom-variable #'boundp))) - -(defun embark-export-ibuffer (buffers) - "Create an ibuffer buffer listing BUFFERS." - (ibuffer t "*Embark Export Ibuffer*" - `((predicate . (member (buffer-name) ',buffers))))) - -(autoload 'dired-check-switches "dired") -(declare-function dired-unadvertise "dired") -(defvar dired-directory) - -(defun embark-export-dired (files) - "Create a Dired buffer listing FILES." - (setq files (mapcar #'directory-file-name - (cl-remove-if-not #'file-exists-p files))) - (when (dired-check-switches dired-listing-switches "A" "almost-all") - (setq files (cl-remove-if - (lambda (path) - (let ((file (file-name-nondirectory path))) - (or (string= file ".") (string= file "..")))) - files))) - (cl-letf* ((dir (or (file-name-directory (try-completion "" files)) "")) - ;; Prevent reusing existing Dired buffer. - ((symbol-function 'dired-find-buffer-nocreate) #'ignore) - (buf (dired-noselect - (cons (expand-file-name dir) - (mapcar (lambda (file) (string-remove-prefix dir file)) - files))))) - (with-current-buffer buf - ;; Unadvertise to prevent the new buffer from being reused. - (dired-unadvertise default-directory) - (rename-buffer (format "*Embark Export Dired %s*" default-directory))) - (pop-to-buffer buf))) - -(autoload 'package-menu-mode "package") -(autoload 'package-menu--generate "package") - -(defun embark-export-list-packages (packages) - "Create a package menu mode buffer listing PACKAGES." - (let ((buf (generate-new-buffer "*Embark Export Packages*"))) - (with-current-buffer buf - (package-menu-mode) - (package-menu--generate nil (mapcar #'intern packages))) - (pop-to-buffer buf))) - -(defvar bookmark-alist) - -(defun embark-export-bookmarks (bookmarks) - "Create a `bookmark-bmenu-mode' buffer listing BOOKMARKS." - (embark--export-rename "*Bookmark List*" "Bookmarks" - (let ((bookmark-alist - (cl-remove-if-not - (lambda (bmark) - (member (car bmark) bookmarks)) - bookmark-alist))) - (bookmark-bmenu-list)))) - -;;; Multiple target selection - -(defface embark-selected '((t (:inherit match))) - "Face for selected candidates.") - -(defcustom embark-selection-indicator - #(" Embark:%s " 1 12 (face (embark-selected bold))) - "Mode line indicator used for selected candidates." - :type '(choice string (const nil))) - -(defvar-local embark--selection nil - "Buffer local list of selected targets. -Add or remove elements to this list using the `embark-select' -action.") - -(defun embark--selection-indicator () - "Mode line indicator showing number of selected items." - (when-let ((sel - (buffer-local-value - 'embark--selection - (or (when-let ((win (active-minibuffer-window))) - (window-buffer win)) - (current-buffer))))) - (format embark-selection-indicator (length sel)))) - -(cl-defun embark--select - (&key orig-target orig-type bounds &allow-other-keys) - "Add or remove ORIG-TARGET of given ORIG-TYPE to the selection. -If BOUNDS are given, also highlight the target when selecting it." - (cl-flet ((multi-type (x) (car (get-text-property 0 'multi-category x)))) - (if-let* ((existing (seq-find - (pcase-lambda (`(,cand . ,ov)) - (and - (equal cand orig-target) - (if (and bounds ov) - (and (= (car bounds) (overlay-start ov)) - (= (cdr bounds) (overlay-end ov))) - (let ((cand-type (multi-type cand))) - (or (eq cand-type orig-type) - (eq cand-type (multi-type orig-target))))))) - embark--selection))) - (progn - (when (cdr existing) (delete-overlay (cdr existing))) - (setq embark--selection (delq existing embark--selection))) - (let ((target (copy-sequence orig-target)) overlay) - (when bounds - (setq overlay (make-overlay (car bounds) (cdr bounds))) - (overlay-put overlay 'category 'embark-selected-overlay)) - (add-text-properties 0 (length orig-target) - `(multi-category ,(cons orig-type orig-target)) - target) - (push (cons target overlay) embark--selection)))) - (when embark-selection-indicator - (add-to-list 'mode-line-misc-info '(:eval (embark--selection-indicator))) - (force-mode-line-update t))) - -;;;###autoload -(defun embark-select () - "Add or remove the target from the current buffer's selection. -You can act on all selected targets at once with `embark-act-all'. -When called from outside `embark-act' this command will select -the first target at point." - (interactive) - (if-let ((target (car (embark--targets)))) - (apply #'embark--select target) - (user-error "No target to select"))) - -(defun embark-selected-candidates () - "Return currently selected candidates in the buffer." - (when embark--selection - (cl-flet ((unwrap (x) (get-text-property 0 'multi-category x))) - (let* ((first-type (car (unwrap (caar embark--selection)))) - (same (cl-every (lambda (item) - (eq (car (unwrap (car item))) first-type)) - embark--selection)) - (extract (if same - (pcase-lambda (`(,cand . ,overlay)) - (cons (cdr (unwrap cand)) overlay)) - #'identity))) - (cons - (if same first-type 'multi-category) - (nreverse - (mapcar - (lambda (item) - (pcase-let ((`(,cand . ,ov) (funcall extract item))) - (if ov `(,cand ,(overlay-start ov) . ,(overlay-end ov)) cand))) - embark--selection))))))) - -;;; Integration with external packages, mostly completion UIs - -;; marginalia - -;; Ensure that the Marginalia cache is reset, such that -;; `embark-toggle-variable-value' updates the display (See #540). -(with-eval-after-load 'marginalia - (push 'marginalia--cache-reset (alist-get :always embark-post-action-hooks))) - -;; vertico - -(declare-function vertico--candidate "ext:vertico") -(declare-function vertico--update "ext:vertico") -(defvar vertico--input) -(defvar vertico--candidates) -(defvar vertico--base) - -(defun embark--vertico-selected () - "Target the currently selected item in Vertico. -Return the category metadatum as the type of the target." - (when vertico--input - ;; Force candidate computation, if candidates are not yet available. - (vertico--update) - (cons (completion-metadata-get (embark--metadata) 'category) - (vertico--candidate)))) - -(defun embark--vertico-candidates () - "Collect the current Vertico candidates. -Return the category metadatum as the type of the candidates." - (when vertico--input - ;; Force candidate computation, if candidates are not yet available. - (vertico--update) - (cons (completion-metadata-get (embark--metadata) 'category) - vertico--candidates))) - -(defun embark--vertico-indicator () - "Embark indicator highlighting the current Vertico candidate." - (let ((fr face-remapping-alist)) - (lambda (&optional keymap _targets _prefix) - (when vertico--input - (setq-local face-remapping-alist - (if keymap - (cons '(vertico-current . embark-target) fr) - fr)))))) - -(with-eval-after-load 'vertico - (cl-defmethod vertico--format-candidate - :around (cand prefix suffix index start &context (embark--selection cons)) - (when (cl-find (concat vertico--base (nth index vertico--candidates)) - embark--selection - :test #'equal :key #'car) - (setq cand (copy-sequence cand)) - (add-face-text-property 0 (length cand) 'embark-selected t cand)) - (cl-call-next-method cand prefix suffix index start)) - (add-hook 'embark-indicators #'embark--vertico-indicator) - (add-hook 'embark-target-finders #'embark--vertico-selected) - (add-hook 'embark-candidate-collectors #'embark--vertico-candidates) - (remove-hook 'embark-candidate-collectors #'embark-selected-candidates) - (add-hook 'embark-candidate-collectors #'embark-selected-candidates)) - -;; ivy - -(declare-function ivy--expand-file-name "ext:ivy") -(declare-function ivy-state-current "ext:ivy") -(defvar ivy-text) -(defvar ivy-last) -(defvar ivy--old-cands) ; this stores the current candidates :) -(defvar ivy--length) - -(defun embark--ivy-selected () - "Target the currently selected item in Ivy. -Return the category metadatum as the type of the target." - ;; my favorite way of detecting Ivy - (when (memq 'ivy--queue-exhibit post-command-hook) - (cons - (completion-metadata-get (embark--metadata) 'category) - (ivy--expand-file-name - (if (and (> ivy--length 0) - (stringp (ivy-state-current ivy-last))) - (ivy-state-current ivy-last) - ivy-text))))) - -(defun embark--ivy-candidates () - "Return all current Ivy candidates." - ;; my favorite way of detecting Ivy - (when (memq 'ivy--queue-exhibit post-command-hook) - (cons - ;; swiper-isearch uses swiper-isearch-function as a completion - ;; table, but it doesn't understand metadata queries - (ignore-errors - (completion-metadata-get (embark--metadata) 'category)) - ivy--old-cands))) - -(with-eval-after-load 'ivy - (add-hook 'embark-target-finders #'embark--ivy-selected) - (add-hook 'embark-candidate-collectors #'embark--ivy-candidates) - (remove-hook 'embark-candidate-collectors #'embark-selected-candidates) - (add-hook 'embark-candidate-collectors #'embark-selected-candidates)) - -;;; Custom actions - -(defvar embark-separator-history nil - "Input history for the separators used by some embark commands. -The commands that prompt for a string separator are -`embark-insert' and `embark-copy-as-kill'.") - -(defun embark-keymap-help () - "Prompt for an action to perform or command to become and run it." - (interactive) - (user-error "Not meant to be called directly")) - -(defun embark-toggle-quit () - "Toggle whether the following action quits the minibuffer." - (interactive) - (when (minibufferp) - (setq embark--toggle-quit (not embark--toggle-quit)) - (if (consp embark-quit-after-action) - (message "Will %sobey embark-quit-after-action." - (if embark--toggle-quit "dis" "")) - (message - "Will %squit minibuffer after action" - (if (eq embark--toggle-quit embark-quit-after-action) "not " ""))))) - -(defun embark--separator (strings) - "Return a separator to join the STRINGS together. -With a prefix argument, prompt the user (unless STRINGS has 0 or -1 elements, in which case a separator is not needed)." - (if (and current-prefix-arg (cdr strings)) - (read-string "Separator: " nil 'embark-separator-history) - "\n")) - -(defun embark-copy-as-kill (strings) - "Join STRINGS and save on the `kill-ring'. -With a prefix argument, prompt for the separator to join the -STRINGS, which defaults to a newline." - (kill-new (string-join strings (embark--separator strings)))) - -(defun embark-insert (strings) - "Join STRINGS and insert the result at point. -With a prefix argument, prompt for the separator to join the -STRINGS, which defaults to a newline. - -Some whitespace is also inserted if necessary to avoid having the -inserted string blend into the existing buffer text. More -precisely: - -1. If the inserted string does not contain newlines, a space may -be added before or after it as needed to avoid inserting a word -constituent character next to an existing word constituent. - -2. For a multiline inserted string, newlines may be added before -or after as needed to ensure the inserted string is on lines of -its own." - (let* ((separator (embark--separator strings)) - (multiline - (or (and (cdr strings) (string-match-p "\n" separator)) - (and (null (cdr strings)) - (equal (buffer-substring (line-beginning-position) - (line-end-position)) - (car strings))) - (seq-some (lambda (s) (string-match-p "\n" s)) strings)))) - (cl-labels ((maybe-space () - (and (looking-at "\\w") (looking-back "\\w" 1) - (insert " "))) - (maybe-newline () - (or (looking-back "^[ \t]*" 40) (looking-at "\n") - (newline-and-indent))) - (maybe-whitespace () - (if multiline (maybe-newline) (maybe-space))) - (ins-string () - (let ((start (point))) - (insert - (mapconcat #'substring-no-properties strings separator)) - (save-excursion (goto-char start) (maybe-whitespace)) - (when (looking-back "\n" 1) (delete-char -1)) - (save-excursion (maybe-whitespace))))) - (if buffer-read-only - (with-selected-window (other-window-for-scrolling) - (ins-string)) - (ins-string))))) - -(defun embark-dired-jump (file &optional other-window) - "Open Dired buffer in directory containing FILE and move to its line. -When called with a prefix argument OTHER-WINDOW, open Dired in other window." - (interactive "fJump to Dired file: \nP") - (dired-jump other-window file)) - -(defun embark--read-from-history (prompt candidates &optional category) - "Read with completion from list of history CANDIDATES of CATEGORY. -Sorting and history are disabled. PROMPT is the prompt message." - (completing-read prompt - (embark--with-category category candidates) - nil t nil t)) - -(defun embark-kill-ring-remove (text) - "Remove TEXT from `kill-ring'." - (interactive (list (embark--read-from-history - "Remove from kill-ring: " kill-ring 'kill-ring))) - (embark-history-remove text) - (setq kill-ring (delete text kill-ring))) - -(defvar recentf-list) -(defun embark-recentf-remove (file) - "Remove FILE from the list of recent files." - (interactive (list (embark--read-from-history - "Remove recent file: " recentf-list 'file))) - (embark-history-remove (expand-file-name file)) - (embark-history-remove (abbreviate-file-name file)) - (when (and (boundp 'recentf-list) (fboundp 'recentf-expand-file-name)) - (setq recentf-list (delete (recentf-expand-file-name file) recentf-list)))) - -(defun embark-history-remove (str) - "Remove STR from `minibuffer-history-variable'. -Many completion UIs sort by history position. This command can be used -to remove entries from the history, such that they are not sorted closer -to the top." - (interactive (list (embark--read-from-history - "Remove history item: " - (if (eq minibuffer-history-variable t) - (user-error "No minibuffer history") - (symbol-value minibuffer-history-variable))))) - (unless (eq minibuffer-history-variable t) - (set minibuffer-history-variable - (delete str (symbol-value minibuffer-history-variable))))) - -(defvar xref-backend-functions) - -(defun embark-find-definition (symbol) - "Find definition of Emacs Lisp SYMBOL." - (interactive "sSymbol: ") - (let ((xref-backend-functions (lambda () 'elisp))) - (xref-find-definitions symbol))) - -(defun embark-info-lookup-symbol (symbol) - "Display the definition of SYMBOL, from the Elisp manual." - (interactive "SSymbol: ") - (info-lookup-symbol symbol 'emacs-lisp-mode)) - -(defun embark-rename-buffer (buffer newname &optional unique) - "Rename BUFFER to NEWNAME, optionally making it UNIQUE. -Interactively, you can set UNIQUE with a prefix argument. -Returns the new name actually used." - (interactive "bBuffer: \nBRename %s to: \nP") - (when-let ((buf (get-buffer buffer))) - (with-current-buffer buf - (rename-buffer newname unique)))) - -(defun embark--package-url (pkg) - "Return homepage for package PKG." - (when-let (desc (embark--package-desc pkg)) - (alist-get :url (package-desc-extras desc)))) - -(defun embark--prompt-for-package () - "Prompt user for a package name." - ;; this code is taken from the interactive spec of describe-package - (unless package--initialized - (package-initialize t)) - (intern - (completing-read "Package: " - (append (mapcar #'car package-alist) - (mapcar #'car package-archive-contents) - (mapcar #'car package--builtins))))) - -(defun embark-browse-package-url (pkg) - "Open homepage for package PKG with `browse-url'." - (interactive (list (embark--prompt-for-package))) - (if-let ((url (embark--package-url pkg))) - (browse-url url) - (user-error "No homepage found for `%s'" pkg))) - -(defun embark-save-package-url (pkg) - "Save URL of homepage for package PKG on the `kill-ring'." - (interactive (list (embark--prompt-for-package))) - (if-let ((url (embark--package-url pkg))) - (kill-new url) - (user-error "No homepage found for `%s'" pkg))) - -(defun embark-save-variable-value (var) - "Save value of VAR in the `kill-ring'." - (interactive "SVariable: ") - (kill-new (string-trim (pp-to-string (symbol-value var))))) - -(defun embark-insert-variable-value (var) - "Insert value of VAR." - (interactive "SVariable: ") - (embark-insert (list (string-trim (pp-to-string (symbol-value var)))))) - -(defun embark-toggle-variable (var &optional local) - "Toggle value of boolean variable VAR. -If prefix LOCAL is non-nil make variable local." - (interactive "SVariable: \nP") - (let ((val (symbol-value var))) - (unless (memq val '(nil t)) - (user-error "Not a boolean variable")) - (when local - (make-local-variable var)) - (funcall (or (get var 'custom-set) 'set) var (not val)))) - -(defun embark-insert-relative-path (file) - "Insert relative path to FILE. -The insert path is relative to `default-directory'." - (interactive "FFile: ") - (embark-insert (list (file-relative-name (substitute-in-file-name file))))) - -(defun embark-save-relative-path (file) - "Save the relative path to FILE in the kill ring. -The insert path is relative to `default-directory'." - (interactive "FFile: ") - (kill-new (file-relative-name (substitute-in-file-name file)))) - -(defun embark-shell-command-on-buffer (buffer command &optional replace) - "Run shell COMMAND on contents of BUFFER. -Called with \\[universal-argument], replace contents of buffer -with command output. For replacement behavior see -`shell-command-dont-erase-buffer' setting." - (interactive - (list - (read-buffer "Buffer: " nil t) - (read-shell-command "Shell command: ") - current-prefix-arg)) - (with-current-buffer buffer - (shell-command-on-region (point-min) (point-max) - command - (and replace (current-buffer))))) - -(defun embark-open-externally (file) - "Open FILE or url using system's default application." - (interactive "sOpen externally: ") - (unless (string-match-p "\\`[a-z]+://" file) - (setq file (expand-file-name file))) - (message "Opening `%s' externally..." file) - (if (and (eq system-type 'windows-nt) - (fboundp 'w32-shell-execute)) - (w32-shell-execute "open" file) - (call-process (pcase system-type - ('darwin "open") - ('cygwin "cygstart") - (_ "xdg-open")) - nil 0 nil file))) - -(declare-function bookmark-prop-get "bookmark") -(declare-function bookmark-completing-read "bookmark") - -(defun embark-bookmark-open-externally (bookmark) - "Open BOOKMARK in external application." - (interactive (list (bookmark-completing-read "Open externally: "))) - (embark-open-externally - (or (bookmark-prop-get bookmark 'location) - (bookmark-prop-get bookmark 'filename) - (user-error "Bookmark `%s' does not have a location" bookmark)))) - -(defun embark-bury-buffer (buf) - "Bury buffer BUF." - (interactive "bBuffer: ") - (if-let (win (get-buffer-window buf)) - (with-selected-window win - (bury-buffer)) - (bury-buffer))) - -(defun embark-kill-buffer-and-window (buf) - "Kill buffer BUF and delete its window." - (interactive "bBuffer: ") - (when-let (buf (get-buffer buf)) - (if-let (win (get-buffer-window buf)) - (with-selected-window win - (kill-buffer-and-window)) - (kill-buffer buf)))) - -(defun embark-save-unicode-character (char) - "Save Unicode character CHAR to kill ring." - (interactive - (list (read-char-by-name "Insert character (Unicode name or hex): "))) - (kill-new (format "%c" char))) - -(defun embark-isearch-forward () - "Prompt for string in the minibuffer and start isearch forwards. -Unlike isearch, this command reads the string from the -minibuffer, which means it can be used as an Embark action." - (interactive) - (isearch-mode t) - (isearch-edit-string)) - -(defun embark-isearch-backward () - "Prompt for string in the minibuffer and start isearch backwards. -Unlike isearch, this command reads the string from the -minibuffer, which means it can be used as an Embark action." - (interactive) - (isearch-mode nil) - (isearch-edit-string)) - -(defun embark-toggle-highlight () - "Toggle symbol highlighting using `highlight-symbol-at-point'." - (interactive) - (let ((regexp (find-tag-default-as-symbol-regexp)) - (highlighted (cl-find-if #'boundp - '(hi-lock-interactive-lighters - hi-lock-interactive-patterns)))) - (if (and highlighted (assoc regexp (symbol-value highlighted))) - (unhighlight-regexp regexp) - (highlight-symbol-at-point)))) - -(defun embark-next-symbol () - "Jump to next occurrence of symbol at point. -The search respects symbol boundaries." - (interactive) - (if-let ((symbol (thing-at-point 'symbol))) - (let ((regexp (format "\\_<%s\\_>" (regexp-quote symbol)))) - (when (looking-at regexp) - (forward-symbol 1)) - (unless (re-search-forward regexp nil t) - (user-error "Symbol `%s' not found" symbol))) - (user-error "No symbol at point"))) - -(defun embark-previous-symbol () - "Jump to previous occurrence of symbol at point. -The search respects symbol boundaries." - (interactive) - (if-let ((symbol (thing-at-point 'symbol))) - (let ((regexp (format "\\_<%s\\_>" (regexp-quote symbol)))) - (when (looking-back regexp (- (point) (length symbol))) - (forward-symbol -1)) - (unless (re-search-backward regexp nil t) - (user-error "Symbol `%s' not found" symbol))) - (user-error "No symbol at point"))) - -(defun embark-compose-mail (address) - "Compose email to ADDRESS." - ;; The only reason we cannot use compose-mail directly is its - ;; interactive specification, which just supplies nil for the - ;; address (and several other arguments). - (interactive "sTo: ") - (compose-mail address)) - -(autoload 'pp-display-expression "pp") - -(defun embark-pp-eval-defun (edebug) - "Run `eval-defun' and pretty print the result. -With a prefix argument EDEBUG, instrument the code for debugging." - (interactive "P") - (cl-letf (((symbol-function #'eval-expression-print-format) - (lambda (result) - (pp-display-expression result "*Pp Eval Output*")))) - (eval-defun edebug))) - -(defun embark-eval-replace (noquote) - "Evaluate region and replace with evaluated result. -If NOQUOTE is non-nil (interactively, if called with a prefix -argument), no quoting is used for strings." - (interactive "P") - (let ((beg (region-beginning)) - (end (region-end))) - (save-excursion - (goto-char end) - (insert (format (if noquote "%s" "%S") - (eval (read (buffer-substring beg end)) lexical-binding))) - (delete-region beg end)))) - -(static-if (< emacs-major-version 29) - (defun embark-elp-restore-package (prefix) - "Remove instrumentation from functions with names starting with PREFIX." - (interactive "SPrefix: ") - (when (fboundp 'elp-restore-list) - (elp-restore-list - (mapcar #'intern - (all-completions (symbol-name prefix) - obarray 'elp-profilable-p)))))) - -(defmacro embark--define-hash (algorithm) - "Define command which computes hash from a string. -ALGORITHM is the hash algorithm symbol understood by `secure-hash'." - `(defun ,(intern (format "embark-hash-%s" algorithm)) (str) - ,(format "Compute %s hash of STR and store it in the kill ring." algorithm) - (interactive "sString: ") - (let ((hash (secure-hash ',algorithm str))) - (kill-new hash) - (message "%s: %s" ',algorithm hash)))) - -(embark--define-hash md5) -(embark--define-hash sha1) -(embark--define-hash sha224) -(embark--define-hash sha256) -(embark--define-hash sha384) -(embark--define-hash sha512) - -(defun embark-encode-url (start end) - "Properly URI-encode the region between START and END in current buffer." - (interactive "r") - (let ((encoded (url-encode-url (buffer-substring-no-properties start end)))) - (delete-region start end) - (insert encoded))) - -(defun embark-decode-url (start end) - "Decode the URI-encoded region between START and END in current buffer. -It assumes the URL was encoded in UTF-8." - (interactive "r") - (let ((decoded (decode-coding-string - (url-unhex-string - (buffer-substring-no-properties start end)) - 'utf-8))) - (delete-region start end) - (insert decoded))) - -(defvar epa-replace-original-text) -(defun embark-epa-decrypt-region (start end) - "Decrypt region between START and END." - (interactive "r") - (let ((epa-replace-original-text t)) - (epa-decrypt-region start end))) - -(defvar eww-download-directory) -(autoload 'eww-download-callback "eww") - -(defun embark-download-url (url) - "Download URL to `eww-download-directory'." - (interactive "sDownload URL: ") - (let ((dir eww-download-directory)) - (when (functionp dir) (setq dir (funcall dir))) - (access-file dir "Download failed") - (url-retrieve url #'eww-download-callback (list url dir)))) - -;;; Setup and pre-action hooks - -(defun embark--restart (&rest _) - "Restart current command with current input. -Use this to refresh the list of candidates for commands that do -not handle that themselves." - (when (minibufferp) - (embark--become-command embark--command (minibuffer-contents)))) - -(defun embark--shell-prep (&rest _) - "Prepare target for use as argument for a shell command. -This quotes the spaces, inserts an extra space at the beginning -and leaves the point to the left of it." - (let ((contents (minibuffer-contents))) - (delete-minibuffer-contents) - (insert " " (shell-quote-wildcard-pattern contents)) - (goto-char (minibuffer-prompt-end)))) - -(defun embark--force-complete (&rest _) - "Select first minibuffer completion candidate matching target." - (minibuffer-force-complete)) - -(cl-defun embark--eval-prep (&key type &allow-other-keys) - "If target's TYPE is variable, skip edit; if function, wrap in ()." - (when (memq type '(command function)) - (embark--allow-edit) - (goto-char (minibuffer-prompt-end)) - (insert "(") - (goto-char (point-max)) - (insert ")") - (backward-char))) - -(cl-defun embark--beginning-of-target (&key bounds &allow-other-keys) - "Go to beginning of the target BOUNDS." - (when (number-or-marker-p (car bounds)) - (goto-char (car bounds)))) - -(cl-defun embark--end-of-target (&key bounds &allow-other-keys) - "Go to end of the target BOUNDS." - (when (number-or-marker-p (cdr bounds)) - (goto-char (cdr bounds)))) - -(cl-defun embark--mark-target (&rest rest &key run bounds &allow-other-keys) - "Mark the target if its BOUNDS are known. -After marking the target, call RUN with the REST of its arguments." - (cond - ((and bounds run) - (save-mark-and-excursion - (set-mark (cdr bounds)) - (goto-char (car bounds)) - (apply run :bounds bounds rest))) - (bounds ;; used as pre- or post-action hook - (set-mark (cdr bounds)) - (goto-char (car bounds))) - (run (apply run rest)))) - -(cl-defun embark--unmark-target (&rest _) - "Deactivate the region target." - (deactivate-mark t)) - -(cl-defun embark--narrow-to-target - (&rest rest &key run bounds &allow-other-keys) - "Narrow buffer to target if its BOUNDS are known. -Intended for use as an Embark around-action hook. This function -runs RUN with the buffer narrowed to given BOUNDS passing along -the REST of the arguments." - (if bounds - (save-excursion - (save-restriction - (narrow-to-region (car bounds) (cdr bounds)) - (goto-char (car bounds)) - (apply run :bounds bounds rest))) - (apply run rest))) - -(defun embark--allow-edit (&rest _) - "Allow editing the target." - (remove-hook 'post-command-hook #'exit-minibuffer t) - (remove-hook 'post-command-hook 'ivy-immediate-done t)) - -(defun embark--ignore-target (&rest _) - "Ignore the target." - (let ((contents - (get-text-property (minibuffer-prompt-end) 'embark--initial-input))) - (delete-minibuffer-contents) - (when contents (insert contents))) - (embark--allow-edit)) - -(autoload 'xref-push-marker-stack "xref") -(defun embark--xref-push-marker (&rest _) - "Push a marker onto the xref marker stack." - (xref-push-marker-stack)) - -(cl-defun embark--confirm (&key action target &allow-other-keys) - "Ask for confirmation before running the ACTION on the TARGET." - (unless (y-or-n-p (format "Run %s on %s? " action target)) - (user-error "Canceled"))) - -(defconst embark--associated-file-fn-alist - `((file . identity) - (buffer . ,(lambda (target) - (let ((buffer (get-buffer target))) - (or (buffer-file-name buffer) - (buffer-local-value 'default-directory buffer))))) - (bookmark . bookmark-location) - (library . locate-library)) - "Alist of functions that extract a file path from targets of a given type.") - -(defun embark--associated-directory (target type) - "Return directory associated to TARGET of given TYPE. -The supported values of TYPE are file, buffer, bookmark and -library, which have an obvious notion of associated directory." - (when-let ((file-fn (alist-get type embark--associated-file-fn-alist)) - (file (funcall file-fn target))) - (if (file-directory-p file) - (file-name-as-directory file) - (file-name-directory file)))) - -(cl-defun embark--cd (&rest rest &key run target type &allow-other-keys) - "Run action with `default-directory' set to the directory of TARGET. -The supported values of TYPE are file, buffer, bookmark and -library, which have an obvious notion of associated directory. -The REST of the arguments are also passed to RUN." - (let ((default-directory - (or (embark--associated-directory target type) default-directory))) - (apply run :target target :type type rest))) - -(cl-defun embark--save-excursion (&rest rest &key run &allow-other-keys) - "Run action without moving point. -This simply calls RUN with the REST of its arguments inside -`save-excursion'." - (save-excursion (apply run rest))) - -(defun embark--universal-argument (&rest _) - "Run action with a universal prefix argument." - (setq prefix-arg '(4))) - -;;; keymaps - -(defvar-keymap embark-meta-map - :doc "Keymap for non-action Embark functions." - "-" #'negative-argument - "0" #'digit-argument - "1" #'digit-argument - "2" #'digit-argument - "3" #'digit-argument - "4" #'digit-argument - "5" #'digit-argument - "6" #'digit-argument - "7" #'digit-argument - "8" #'digit-argument - "9" #'digit-argument) - -(defvar-keymap embark-general-map - :doc "Keymap for Embark general actions." - :parent embark-meta-map - "i" #'embark-insert - "w" #'embark-copy-as-kill - "q" #'embark-toggle-quit - "E" #'embark-export - "S" #'embark-collect - "L" #'embark-live - "B" #'embark-become - "A" #'embark-act-all - "C-s" #'embark-isearch-forward - "C-r" #'embark-isearch-backward - "C-SPC" #'mark - "DEL" #'delete-region - "SPC" #'embark-select) - -(defvar-keymap embark-encode-map - :doc "Keymap for Embark region encoding actions." - "r" #'rot13-region - "." #'morse-region - "-" #'unmorse-region - "s" #'studlify-region - "m" #'embark-hash-md5 - "1" #'embark-hash-sha1 - "2" #'embark-hash-sha256 - "3" #'embark-hash-sha384 - "4" #'embark-hash-sha224 - "5" #'embark-hash-sha512 - "f" #'format-encode-region - "F" #'format-decode-region - "b" #'base64-encode-region - "B" #'base64-decode-region - "u" #'embark-encode-url - "U" #'embark-decode-url - "c" #'epa-encrypt-region - "C" #'embark-epa-decrypt-region) - -(fset 'embark-encode-map embark-encode-map) - -(defvar-keymap embark-sort-map - :doc "Keymap for Embark actions that sort the region" - "l" #'sort-lines - "P" #'sort-pages - "f" #'sort-fields - "c" #'sort-columns - "p" #'sort-paragraphs - "r" #'sort-regexp-fields - "n" #'sort-numeric-fields) - -(fset 'embark-sort-map embark-sort-map) - -;; this has had an autoload cookie since at least Emacs 26 -;; but that autoload doesn't seem to work for me -(autoload 'org-table-convert-region "org-table" nil t) - -(defvar-keymap embark-region-map - :doc "Keymap for Embark actions on the active region." - :parent embark-general-map - "u" #'upcase-region - "l" #'downcase-region - "c" #'capitalize-region - "|" #'shell-command-on-region - "e" #'eval-region - "<" #'embark-eval-replace - "a" #'align - "A" #'align-regexp - "<left>" #'indent-rigidly - "<right>" #'indent-rigidly - "TAB" #'indent-region - "f" #'fill-region - "p" #'fill-region-as-paragraph - "$" #'ispell-region - "=" #'count-words-region - "F" #'whitespace-cleanup-region - "t" #'transpose-regions - "o" #'org-table-convert-region - ";" #'comment-or-uncomment-region - "W" #'write-region - "+" #'append-to-file - "m" #'apply-macro-to-region-lines - "n" #'narrow-to-region - "*" #'calc-grab-region - ":" #'calc-grab-sum-down - "_" #'calc-grab-sum-across - "r" #'reverse-region - "d" #'delete-duplicate-lines - "b" #'browse-url-of-region - "h" #'shr-render-region - "'" #'expand-region-abbrevs - "v" #'vc-region-history - "R" #'repunctuate-sentences - "s" 'embark-sort-map - ">" 'embark-encode-map) - -(defvar-keymap embark-vc-file-map - :doc "Keymap for Embark VC file actions." - "d" #'vc-delete-file - "r" #'vc-rename-file - "i" #'vc-ignore) - -(fset 'embark-vc-file-map embark-vc-file-map) - -(defvar-keymap embark-file-map - :doc "Keymap for Embark file actions." - :parent embark-general-map - "RET" #'find-file - "f" #'find-file - "F" #'find-file-literally - "o" #'find-file-other-window - "d" #'delete-file - "D" #'delete-directory - "r" #'rename-file - "c" #'copy-file - "s" #'make-symbolic-link - "j" #'embark-dired-jump - "!" #'shell-command - "&" #'async-shell-command - "$" #'eshell - "<" #'insert-file - "m" #'chmod - "=" #'ediff-files - "+" #'make-directory - "\\" #'embark-recentf-remove - "I" #'embark-insert-relative-path - "W" #'embark-save-relative-path - "x" #'embark-open-externally - "e" #'eww-open-file - "l" #'load-file - "b" #'byte-compile-file - "R" #'byte-recompile-directory - "v" 'embark-vc-file-map) - -(defvar-keymap embark-kill-ring-map - :doc "Keymap for `kill-ring' commands." - :parent embark-general-map - "\\" #'embark-kill-ring-remove) - -(defvar-keymap embark-url-map - :doc "Keymap for Embark url actions." - :parent embark-general-map - "RET" #'browse-url - "b" #'browse-url - "d" #'embark-download-url - "x" #'embark-open-externally - "e" #'eww) - -(defvar-keymap embark-email-map - :doc "Keymap for Embark email actions." - :parent embark-general-map - "RET" #'embark-compose-mail - "c" #'embark-compose-mail) - -(defvar-keymap embark-library-map - :doc "Keymap for operations on Emacs Lisp libraries." - :parent embark-general-map - "RET" #'find-library - "l" #'load-library - "f" #'find-library - "h" #'finder-commentary - "a" #'apropos-library - "L" #'locate-library - "m" #'info-display-manual - "$" #'eshell) - -(defvar-keymap embark-buffer-map - :doc "Keymap for Embark buffer actions." - :parent embark-general-map - "RET" #'switch-to-buffer - "k" #'kill-buffer - "b" #'switch-to-buffer - "o" #'switch-to-buffer-other-window - "z" #'embark-bury-buffer - "K" #'embark-kill-buffer-and-window - "r" #'embark-rename-buffer - "=" #'ediff-buffers - "|" #'embark-shell-command-on-buffer - "<" #'insert-buffer - "$" #'eshell) - -(defvar-keymap embark-tab-map - :doc "Keymap for actions for tab-bar tabs." - :parent embark-general-map - "RET" #'tab-bar-select-tab-by-name - "s" #'tab-bar-select-tab-by-name - "r" #'tab-bar-rename-tab-by-name - "k" #'tab-bar-close-tab-by-name) - -(defvar-keymap embark-identifier-map - :doc "Keymap for Embark identifier actions." - :parent embark-general-map - "RET" #'xref-find-definitions - "h" #'display-local-help - "H" #'embark-toggle-highlight - "d" #'xref-find-definitions - "r" #'xref-find-references - "a" #'xref-find-apropos - "s" #'info-lookup-symbol - "n" #'embark-next-symbol - "p" #'embark-previous-symbol - "'" #'expand-abbrev - "$" #'ispell-word - "o" #'occur) - -(defvar-keymap embark-expression-map - :doc "Keymap for Embark expression actions." - :parent embark-general-map - "RET" #'pp-eval-expression - "e" #'pp-eval-expression - "<" #'embark-eval-replace - "m" #'pp-macroexpand-expression - "TAB" #'indent-region - "r" #'raise-sexp - ";" #'comment-dwim - "t" #'transpose-sexps - "k" #'kill-region - "u" #'backward-up-list - "n" #'forward-list - "p" #'backward-list) - -(defvar-keymap embark-defun-map - :doc "Keymap for Embark defun actions." - :parent embark-expression-map - "RET" #'embark-pp-eval-defun - "e" #'embark-pp-eval-defun - "c" #'compile-defun - "D" #'edebug-defun - "o" #'checkdoc-defun - "N" #'narrow-to-defun) - -;; Use quoted symbols to avoid byte-compiler warnings. -(defvar-keymap embark-heading-map - :doc "Keymap for Embark heading actions." - :parent embark-general-map - "RET" 'outline-show-subtree - "TAB" 'outline-cycle - "C-SPC" 'outline-mark-subtree - "n" 'outline-next-visible-heading - "p" 'outline-previous-visible-heading - "f" 'outline-forward-same-level - "b" 'outline-backward-same-level - "^" 'outline-move-subtree-up - "v" 'outline-move-subtree-down - "u" 'outline-up-heading - "+" 'outline-show-subtree - "-" 'outline-hide-subtree - ">" 'outline-demote - "<" 'outline-promote) - -(defvar-keymap embark-symbol-map - :doc "Keymap for Embark symbol actions." - :parent embark-identifier-map - "RET" #'embark-find-definition - "h" #'describe-symbol - "s" #'embark-info-lookup-symbol - "d" #'embark-find-definition - "e" #'pp-eval-expression - "a" #'apropos - "\\" #'embark-history-remove) - -(defvar-keymap embark-face-map - :doc "Keymap for Embark face actions." - :parent embark-symbol-map - "h" #'describe-face - "c" #'customize-face - "+" #'make-face-bold - "-" #'make-face-unbold - "/" #'make-face-italic - "|" #'make-face-unitalic - "!" #'invert-face - "f" #'set-face-foreground - "b" #'set-face-background) - -(defvar-keymap embark-variable-map - :doc "Keymap for Embark variable actions." - :parent embark-symbol-map - "=" #'set-variable - "c" #'customize-set-variable - "u" #'customize-variable - "v" #'embark-save-variable-value - "<" #'embark-insert-variable-value - "t" #'embark-toggle-variable) - -(defvar-keymap embark-function-map - :doc "Keymap for Embark function actions." - :parent embark-symbol-map - "m" #'elp-instrument-function ;; m=measure - "M" 'elp-restore-function ;; quoted, not autoloaded - "k" #'debug-on-entry ;; breaKpoint (running out of letters, really) - "K" #'cancel-debug-on-entry - "t" #'trace-function - "T" 'untrace-function) ;; quoted, not autoloaded - -(defvar-keymap embark-command-map - :doc "Keymap for Embark command actions." - :parent embark-function-map - "x" #'execute-extended-command - "I" #'Info-goto-emacs-command-node - "b" #'where-is - "g" #'global-set-key - "l" #'local-set-key) - -(defvar-keymap embark-package-map - :doc "Keymap for Embark package actions." - :parent embark-general-map - "RET" #'describe-package - "h" #'describe-package - "i" #'package-install - "I" #'embark-insert - "d" #'package-delete - "r" #'package-reinstall - "u" #'embark-browse-package-url - "W" #'embark-save-package-url - "a" #'package-autoremove - "g" #'package-refresh-contents - "m" #'elp-instrument-package ;; m=measure - "M" (if (fboundp 'embark-elp-restore-package) - 'embark-elp-restore-package - 'elp-restore-package)) - -(defvar-keymap embark-bookmark-map - :doc "Keymap for Embark bookmark actions." - :parent embark-general-map - "RET" #'bookmark-jump - "s" #'bookmark-set - "d" #'bookmark-delete - "r" #'bookmark-rename - "R" #'bookmark-relocate - "l" #'bookmark-locate - "<" #'bookmark-insert - "j" #'bookmark-jump - "o" #'bookmark-jump-other-window - "f" #'bookmark-jump-other-frame - "a" 'bookmark-show-annotation - "e" 'bookmark-edit-annotation - "x" #'embark-bookmark-open-externally - "$" #'eshell) - -(defvar-keymap embark-unicode-name-map - :doc "Keymap for Embark Unicode name actions." - :parent embark-general-map - "RET" #'insert-char - "I" #'insert-char - "W" #'embark-save-unicode-character) - -(defvar-keymap embark-prose-map - :doc "Keymap for Embark actions for dealing with prose." - :parent embark-general-map - "$" #'ispell-region - "f" #'fill-region - "u" #'upcase-region - "l" #'downcase-region - "c" #'capitalize-region - "F" #'whitespace-cleanup-region - "=" #'count-words-region) - -(defvar-keymap embark-sentence-map - :doc "Keymap for Embark actions for dealing with sentences." - :parent embark-prose-map - "t" #'transpose-sentences - "n" #'forward-sentence - "p" #'backward-sentence) - -(defvar-keymap embark-paragraph-map - :doc "Keymap for Embark actions for dealing with paragraphs." - :parent embark-prose-map - "t" #'transpose-paragraphs - "n" #'forward-paragraph - "p" #'backward-paragraph - "R" #'repunctuate-sentences) - -(defvar-keymap embark-flymake-map - :doc "Keymap for Embark actions on Flymake diagnostics." - :parent embark-general-map - "RET" 'flymake-show-buffer-diagnostics - "n" 'flymake-goto-next-error - "p" 'flymake-goto-prev-error) - -(defvar-keymap embark-become-help-map - :doc "Keymap for Embark help actions." - :parent embark-meta-map - "V" #'apropos-variable - "U" #'apropos-user-option - "C" #'apropos-command - "v" #'describe-variable - "f" #'describe-function - "s" #'describe-symbol - "F" #'describe-face - "p" #'describe-package - "i" #'describe-input-method) - -(autoload 'recentf-open-files "recentf" nil t) - -(defvar-keymap embark-become-file+buffer-map - :doc "Embark become keymap for files and buffers." - :parent embark-meta-map - "f" #'find-file - "4 f" #'find-file-other-window - "." #'find-file-at-point - "p" #'project-find-file - "r" #'recentf-open-files - "b" #'switch-to-buffer - "4 b" #'switch-to-buffer-other-window - "l" #'locate - "L" #'find-library - "v" #'vc-dir) - -(defvar-keymap embark-become-shell-command-map - :doc "Embark become keymap for shell commands." - :parent embark-meta-map - "!" #'shell-command - "&" #'async-shell-command - "c" #'comint-run - "t" #'term) - -(defvar-keymap embark-become-match-map - :doc "Embark become keymap for search." - :parent embark-meta-map - "o" #'occur - "k" #'keep-lines - "f" #'flush-lines - "c" #'count-matches) - -(provide 'embark) - -;; Check that embark-consult is installed. If Embark is used in -;; combination with Consult, you should install the integration package, -;; such that features like embark-export from consult-grep work as -;; expected. - -(with-eval-after-load 'consult - (unless (require 'embark-consult nil 'noerror) - (warn "The package embark-consult should be installed if you use both Embark and Consult"))) - -(with-eval-after-load 'org - (require 'embark-org)) - -;;; embark.el ends here diff --git a/emacs/elpa/embark-20240919.1831/embark.elc b/emacs/elpa/embark-20240919.1831/embark.elc Binary files differ. diff --git a/emacs/elpa/embark-20240919.1831/dir b/emacs/elpa/embark-20241003.1953/dir diff --git a/emacs/elpa/embark-20240919.1831/embark-autoloads.el b/emacs/elpa/embark-20241003.1953/embark-autoloads.el diff --git a/emacs/elpa/embark-20240919.1831/embark-org.el b/emacs/elpa/embark-20241003.1953/embark-org.el diff --git a/emacs/elpa/embark-20240919.1831/embark-org.elc b/emacs/elpa/embark-20241003.1953/embark-org.elc Binary files differ. diff --git a/emacs/elpa/embark-20241003.1953/embark-pkg.el b/emacs/elpa/embark-20241003.1953/embark-pkg.el @@ -0,0 +1,11 @@ +;; -*- no-byte-compile: t; lexical-binding: nil -*- +(define-package "embark" "20241003.1953" + "Conveniently act on minibuffer completions." + '((emacs "28.1") + (compat "30")) + :url "https://github.com/oantolin/embark" + :commit "d2daad08e04090391b3221fa95000492a1f8aabe" + :revdesc "d2daad08e040" + :keywords '("convenience") + :authors '(("Omar Antolín Camarena" . "omar@matem.unam.mx")) + :maintainers '(("Omar Antolín Camarena" . "omar@matem.unam.mx"))) diff --git a/emacs/elpa/embark-20241003.1953/embark.el b/emacs/elpa/embark-20241003.1953/embark.el @@ -0,0 +1,4592 @@ +;;; embark.el --- Conveniently act on minibuffer completions -*- lexical-binding: t; -*- + +;; Copyright (C) 2021-2023 Free Software Foundation, Inc. + +;; Author: Omar Antolín Camarena <omar@matem.unam.mx> +;; Maintainer: Omar Antolín Camarena <omar@matem.unam.mx> +;; Keywords: convenience +;; Package-Version: 20241003.1953 +;; Package-Revision: d2daad08e040 +;; Homepage: https://github.com/oantolin/embark +;; Package-Requires: ((emacs "28.1") (compat "30")) + +;; This file is part of GNU Emacs. + +;; This program is free software; you can redistribute it and/or modify +;; it under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. + +;; This program is distributed in the hope that it will be useful, +;; but WITHOUT ANY WARRANTY; without even the implied warranty of +;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +;; GNU General Public License for more details. + +;; You should have received a copy of the GNU General Public License +;; along with this program. If not, see <https://www.gnu.org/licenses/>. + +;;; Commentary: + +;; This package provides a sort of right-click contextual menu for +;; Emacs, accessed through the `embark-act' command (which you should +;; bind to a convenient key), offering you relevant actions to use on +;; a target determined by the context: + +;; - In the minibuffer, the target is the current best completion +;; candidate. +;; - In the `*Completions*' buffer the target is the completion at point. +;; - In a regular buffer, the target is the region if active, or else the +;; file, symbol or url at point. + +;; The type of actions offered depend on the type of the target: + +;; - For files you get offered actions like deleting, copying, +;; renaming, visiting in another window, running a shell command on the +;; file, etc. +;; - For buffers the actions include switching to or killing the buffer. +;; - For package names the actions include installing, removing or +;; visiting the homepage. + +;; Everything is easily configurable: determining the current target, +;; classifying it, and deciding with actions are offered for each type +;; in the classification. The above introduction just mentions part of +;; the default configuration. + +;; Configuring which actions are offered for a type is particularly +;; easy and requires no programming: the `embark-keymap-alist' +;; variable associates target types with variable containing keymaps, +;; and those keymaps containing binds for the actions. For example, +;; in the default configuration the type `file' is associated with the +;; symbol `embark-file-map'. That symbol names a keymap with +;; single-letter key bindings for common Emacs file commands, for +;; instance `c' is bound to `copy-file'. This means that if while you +;; are in the minibuffer after running a command that prompts for a +;; file, such as `find-file' or `rename-file', you can copy a file by +;; running `embark-act' and then pressing `c'. + +;; These action keymaps are very convenient but not strictly necessary +;; when using `embark-act': you can use any command that reads from the +;; minibuffer as an action and the target of the action will be inserted +;; at the first minibuffer prompt. After running `embark-act' all of your +;; key bindings and even `execute-extended-command' can be used to run a +;; command. The action keymaps are normal Emacs keymaps and you should +;; feel free to bind in them whatever commands you find useful as actions. + +;; The actions in `embark-general-map' are available no matter what +;; type of completion you are in the middle of. By default this +;; includes bindings to save the current candidate in the kill ring +;; and to insert the current candidate in the previously selected +;; buffer (the buffer that was current when you executed a command +;; that opened up the minibuffer). + +;; You can read about the Embark GitHub project wiki: +;; https://github.com/oantolin/embark/wiki/Default-Actions + +;; Besides acting individually on targets, Embark lets you work +;; collectively on a set of target candidates. For example, while +;; you are in the minibuffer the candidates are simply the possible +;; completions of your input. Embark provides three commands to work +;; on candidate sets: + +;; - The `embark-act-all' command runs the same action on each of the +;; current candidates. It is just like using `embark-act' on each +;; candidate in turn. + +;; - The `embark-collect' command produces a buffer listing all +;; candidates, for you to peruse and run actions on at your leisure. +;; The candidates are displayed as a list showing additional +;; annotations. + +;; - The `embark-export' command tries to open a buffer in an +;; appropriate major mode for the set of candidates. If the +;; candidates are files export produces a Dired buffer; if they are +;; buffers, you get an Ibuffer buffer; and if they are packages you +;; get a buffer in package menu mode. + +;; These are always available as "actions" (although they do not act +;; on just the current target but on all candidates) for embark-act +;; and are bound to A, S (for "snapshot") and E, respectively, in +;; embark-general-map. This means that you do not have to bind your +;; own key bindings for these (although you can, of course), just a +;; key binding for `embark-act'. + +;;; Code: + +(require 'compat) +(eval-when-compile (require 'subr-x)) + +(require 'ffap) ; used to recognize file and url targets + +;;; User facing options + +(defgroup embark nil + "Emacs Mini-Buffer Actions Rooted in Keymaps." + :link '(info-link :tag "Info Manual" "(embark)") + :link '(url-link :tag "Homepage" "https://github.com/oantolin/embark") + :link '(emacs-library-link :tag "Library Source" "embark.el") + :group 'minibuffer + :prefix "embark-") + +(defcustom embark-keymap-alist + '((file embark-file-map) + (library embark-library-map) + (environment-variables embark-file-map) ; they come up in file completion + (url embark-url-map) + (email embark-email-map) + (buffer embark-buffer-map) + (tab embark-tab-map) + (expression embark-expression-map) + (identifier embark-identifier-map) + (defun embark-defun-map) + (symbol embark-symbol-map) + (face embark-face-map) + (command embark-command-map) + (variable embark-variable-map) + (function embark-function-map) + (minor-mode embark-command-map) + (unicode-name embark-unicode-name-map) + (package embark-package-map) + (bookmark embark-bookmark-map) + (region embark-region-map) + (sentence embark-sentence-map) + (paragraph embark-paragraph-map) + (kill-ring embark-kill-ring-map) + (heading embark-heading-map) + (flymake embark-flymake-map) + (smerge smerge-basic-map embark-general-map) + (t embark-general-map)) + "Alist of action types and corresponding keymaps. +The special key t is associated with the default keymap to use. +Each value can be either a single symbol whose value is a keymap, +or a list of such symbols." + :type '(alist :key-type (symbol :tag "Target type") + :value-type (choice (variable :tag "Keymap") + (repeat :tag "Keymaps" variable)))) + +(defcustom embark-target-finders + '(embark-target-top-minibuffer-candidate + embark-target-active-region + embark-target-collect-candidate + embark-target-completion-list-candidate + embark-target-text-heading-at-point + embark-target-bug-reference-at-point + embark-target-flymake-at-point + embark-target-smerge-at-point + embark-target-package-at-point + embark-target-email-at-point + embark-target-url-at-point + embark-target-file-at-point + embark-target-custom-variable-at-point + embark-target-identifier-at-point + embark-target-guess-file-at-point + embark-target-expression-at-point + embark-target-sentence-at-point + embark-target-paragraph-at-point + embark-target-defun-at-point + embark-target-prog-heading-at-point) + "List of functions to determine the target in current context. +Each function should take no arguments and return one of: + +1. a cons (TYPE . TARGET) where TARGET is a string and TYPE is a + symbol (which is looked up in `embark-keymap-alist' to + determine which additional keybindings for actions to setup); + +2. a dotted list of the form (TYPE TARGET START . END), where + START and END are the buffer positions bounding TARGET, used + for highlighting; or + +3. a possibly empty list of targets, each of type 1 or 2 (in + particular if a target finder does not find any targets, it + should return nil)." + :type 'hook) + +(defcustom embark-transformer-alist + '((minor-mode . embark--lookup-lighter-minor-mode) + (embark-keybinding . embark--keybinding-command) + (project-file . embark--project-file-full-path) + (package . embark--remove-package-version) + (multi-category . embark--refine-multi-category) + (file . embark--simplify-path)) + "Alist associating type to functions for transforming targets. +Each function should take a type and a target string and return a +pair of the form a `cons' of the new type and the new target." + :type '(alist :key-type symbol :value-type function)) + +(defcustom embark-become-keymaps + '(embark-become-help-map + embark-become-file+buffer-map + embark-become-shell-command-map + embark-become-match-map) + "List of keymaps for `embark-become'. +Each keymap groups a set of related commands that can +conveniently become one another." + :type '(repeat variable)) + +(defcustom embark-prompter 'embark-keymap-prompter + "Function used to prompt the user for actions. +This should be set to a function that prompts the use for an +action and returns the symbol naming the action command. The +default value, `embark-keymap-prompter' activates the type +specific action keymap given in `embark-keymap-alist'. +There is also `embark-completing-read-prompter' which +prompts for an action with completion." + :type '(choice (const :tag "Use action keymaps" embark-keymap-prompter) + (const :tag "Read action with completion" + embark-completing-read-prompter) + (function :tag "Other"))) + +(defcustom embark-keymap-prompter-key "@" + "Key to switch to the keymap prompter from `embark-completing-read-prompter'. + +The key must be either nil or a string. The +string must be accepted by `key-valid-p'." + :type '(choice key (const :tag "None" nil))) + +(defcustom embark-cycle-key nil + "Key used for `embark-cycle'. + +If the key is set to nil it defaults to the global binding of +`embark-act'. The key must be a string which is accepted by +`key-valid-p'." + :type '(choice key (const :tag "Use embark-act key" nil))) + +(defcustom embark-help-key "C-h" + "Key used for help. + +The key must be either nil or a string. The +string must be accepted by `key-valid-p'." + :type '(choice (const "C-h") + (const "?") + (const :tag "None" nil) + key)) + +(defcustom embark-keybinding-repeat + (propertize "*" 'face 'embark-keybinding-repeat) + "Indicator string for repeatable keybindings. +Keybindings are formatted by the `completing-read' prompter and +the verbose indicator." + :type 'string) + +(defface embark-keybinding-repeat + '((t :inherit font-lock-builtin-face)) + "Face used to indicate keybindings as repeatable.") + +(defface embark-keybinding '((t :inherit success)) + "Face used to display key bindings. +Used by `embark-completing-read-prompter' and `embark-keymap-help'.") + +(defface embark-keymap '((t :slant italic)) + "Face used to display keymaps. +Used by `embark-completing-read-prompter' and `embark-keymap-help'.") + +(defface embark-target '((t :inherit highlight)) + "Face used to highlight the target at point during `embark-act'.") + +(defcustom embark-quit-after-action t + "Should `embark-act' quit the minibuffer? +This controls whether calling `embark-act' without a prefix +argument quits the minibuffer or not. You can always get the +opposite behavior to that indicated by this variable by calling +`embark-act' with \\[universal-argument]. + +Note that `embark-act' can also be called from outside the +minibuffer and this variable is irrelevant in that case. + +In addition to t or nil this variable can also be set to an +alist to specify the minibuffer quitting behavior per command. +In the alist case one can additionally use the key t to +prescribe a default for commands not used as alist keys." + :type '(choice (const :tag "Always quit" t) + (const :tag "Never quit" nil) + (alist :tag "Configure per action" + :key-type (choice (function :tag "Action") + (const :tag "All other actions" t)) + :value-type (choice (const :tag "Quit" t) + (const :tag "Do not quit" nil))))) + +(defcustom embark-confirm-act-all t + "Should `embark-act-all' prompt the user for confirmation? +Even if this variable is nil you may still be prompted to confirm +some uses of `embark-act-all', namely, for those actions whose +entry in `embark-pre-action-hooks' includes `embark--confirm'." + :type 'boolean) + +(defcustom embark-default-action-overrides nil + "Alist associating target types with overriding default actions. +When the source of a target is minibuffer completion, the default +action for it is usually the command that opened the minibuffer +in the first place but this can be overridden for a given type by +an entry in this list. + +For example, if you run `delete-file' the default action for its +completion candidates is `delete-file' itself. You may prefer to +make `find-file' the default action for all files, even if they +were obtained from a `delete-file' prompt. In that case you can +configure that by adding an entry to this variable pairing `file' +with `find-file'. + +In addition to target types, you can also use as keys in this alist, +pairs of a target type and a command name. Such a pair indicates that +the override only applies if the target was obtained from minibuffer +completion from that command. For example adding an +entry (cons (cons \\='file \\='delete-file) \\='find-file) to this alist would +indicate that for files at the prompt of the `delete-file' command, +`find-file' should be used as the default action." + :type '(alist :key-type (choice (symbol :tag "Type") + (cons (symbol :tag "Type") + (symbol :tag "Command"))) + :value-type (function :tag "Default action"))) + +(defcustom embark-target-injection-hooks + '((async-shell-command embark--allow-edit embark--shell-prep) + (shell-command embark--allow-edit embark--shell-prep) + (pp-eval-expression embark--eval-prep) + (eval-expression embark--eval-prep) + (package-delete embark--force-complete) + ;; commands evaluating code found in the buffer, which may in turn prompt + (embark-pp-eval-defun embark--ignore-target) + (eval-defun embark--ignore-target) + (eval-last-sexp embark--ignore-target) + (embark-eval-replace embark--ignore-target) + ;; commands which prompt for something that is *not* the target + (write-region embark--ignore-target) + (append-to-file embark--ignore-target) + (append-to-buffer embark--ignore-target) + (shell-command-on-region embark--ignore-target) + (format-encode-region embark--ignore-target) + (format-decode-region embark--ignore-target) + (xref-find-definitions embark--ignore-target) + (xref-find-references embark--ignore-target) + (sort-regexp-fields embark--ignore-target) + (align-regexp embark--ignore-target)) + "Alist associating commands with post-injection setup hooks. +For commands appearing as keys in this alist, run the +corresponding value as a setup hook after injecting the target +into in the minibuffer and before acting on it. The hooks must +accept arbitrary keyword arguments. The :action command, the +:target string and target :type are always present. For actions +at point the target :bounds are passed too. The default pre-action +hook is specified by the entry with key t. Furthermore, hooks with +the key :always are executed always." + :type '(alist :key-type + (choice symbol + (const :tag "Default" t) + (const :tag "Always" :always)) + :value-type hook)) + +(defcustom embark-pre-action-hooks + `(;; commands that need to position point at the beginning or end + (eval-last-sexp embark--end-of-target) + (indent-pp-sexp embark--beginning-of-target) + (backward-up-list embark--beginning-of-target) + (backward-list embark--beginning-of-target) + (forward-list embark--end-of-target) + (forward-sexp embark--end-of-target) + (backward-sexp embark--beginning-of-target) + (raise-sexp embark--beginning-of-target) + (kill-sexp embark--beginning-of-target) + (mark-sexp embark--beginning-of-target) + (transpose-sexps embark--end-of-target) + (transpose-sentences embark--end-of-target) + (transpose-paragraphs embark--end-of-target) + (forward-sentence embark--end-of-target) + (backward-sentence embark--beginning-of-target) + (backward-paragraph embark--beginning-of-target) + (embark-insert embark--end-of-target) + ;; commands we want to be able to jump back from + ;; (embark-find-definition achieves this by calling + ;; xref-find-definitions which pushes the markers itself) + (find-library embark--xref-push-marker) + ;; commands which prompt the user for confirmation before running + (delete-file embark--confirm) + (delete-directory embark--confirm) + (kill-buffer embark--confirm) + (embark-kill-buffer-and-window embark--confirm) + (bookmark-delete embark--confirm) + (package-delete embark--confirm) + (,'tab-bar-close-tab-by-name embark--confirm) ;; Avoid package-lint warning + ;; search for region contents outside said region + (embark-isearch-forward embark--unmark-target) + (embark-isearch-backward embark--unmark-target) + (occur embark--unmark-target) + (query-replace embark--beginning-of-target embark--unmark-target) + (query-replace-regexp embark--beginning-of-target embark--unmark-target) + (replace-string embark--beginning-of-target embark--unmark-target) + (replace-regexp embark--beginning-of-target embark--unmark-target) + ;; mark pseudo-action + (mark embark--mark-target) + ;; shells in new buffers + (shell embark--universal-argument) + (eshell embark--universal-argument)) + "Alist associating commands with pre-action hooks. +The hooks are run right before an action is embarked upon. See +`embark-target-injection-hooks' for information about the hook +arguments and more details." + :type '(alist :key-type + (choice symbol + (const :tag "Default" t) + (const :tag "Always" :always)) + :value-type hook)) + +(defcustom embark-post-action-hooks + `((bookmark-delete embark--restart) + (bookmark-rename embark--restart) + (delete-file embark--restart) + (embark-kill-ring-remove embark--restart) + (embark-recentf-remove embark--restart) + (embark-history-remove embark--restart) + (rename-file embark--restart) + (copy-file embark--restart) + (delete-directory embark--restart) + (make-directory embark--restart) + (kill-buffer embark--restart) + (embark-rename-buffer embark--restart) + (,'tab-bar-rename-tab-by-name embark--restart) ;; Avoid package-lint warning + (,'tab-bar-close-tab-by-name embark--restart) + (package-delete embark--restart)) + "Alist associating commands with post-action hooks. +The hooks are run after an embarked upon action concludes. See +`embark-target-injection-hooks' for information about the hook +arguments and more details." + :type '(alist :key-type + (choice symbol + (const :tag "Default" t) + (const :tag "Always" :always)) + :value-type hook)) + +(defcustom embark-around-action-hooks + '(;; use directory of target as default-directory + (shell embark--cd) + (eshell embark--cd) + ;; mark the target preserving point and previous mark + (kill-region embark--mark-target) + (kill-ring-save embark--mark-target) + (indent-region embark--mark-target) + (ispell-region embark--mark-target) + (fill-region embark--mark-target) + (upcase-region embark--mark-target) + (downcase-region embark--mark-target) + (capitalize-region embark--mark-target) + (count-words-region embark--mark-target) + (count-words embark--mark-target) + (delete-duplicate-lines embark--mark-target) + (shell-command-on-region embark--mark-target) + (delete-region embark--mark-target) + (format-encode-region embark--mark-target) + (format-decode-region embark--mark-target) + (write-region embark--mark-target) + (append-to-file embark--mark-target) + (append-to-buffer embark--mark-target) + (shell-command-on-region embark--mark-target) + (embark-eval-replace embark--mark-target) + (delete-indentation embark--mark-target) + (comment-dwim embark--mark-target) + (insert-parentheses embark--mark-target) + (insert-pair embark--mark-target) + (org-emphasize embark--mark-target) + ;; do the actual work of selecting & deselecting targets + (embark-select embark--select)) + "Alist associating commands with post-action hooks. +The hooks are run instead of the embarked upon action. The hook +can decide whether or not to run the action or it can run it +in some special environment, like inside a let-binding or inside +`save-excursion'. Each hook is called with keyword argument :run +providing a function encapsulating the following around hooks and +the action; the hook additionally receives the keyword arguments +used for other types of action hooks, for more details see +`embark-target-injection-hooks'." + :type '(alist :key-type + (choice symbol + (const :tag "Default" t) + (const :tag "Always" :always)) + :value-type hook)) + +(static-if (< emacs-major-version 29) + ;; narrow to target for duration of action + (setf (alist-get 'repunctuate-sentences embark-around-action-hooks) + '(embark--narrow-to-target))) + +(defcustom embark-multitarget-actions '(embark-insert embark-copy-as-kill) + "Commands for which `embark-act-all' should pass a list of targets. +Normally `embark-act-all' runs the same action on each candidate +separately, but when a command included in this variable's value +is used as an action, `embark-act-all' will instead call it +non-interactively with a single argument: the list of all +candidates. For commands on this list `embark-act' behaves +similarly: it calls them non-interactively with a single +argument: a one element list containing the target." + :type '(repeat function)) + +(defcustom embark-repeat-actions + '((mark . region) + ;; outline commands + outline-next-visible-heading outline-previous-visible-heading + outline-forward-same-level outline-backward-same-level + outline-demote outline-promote + outline-show-subtree (outline-mark-subtree . region) + outline-move-subtree-up outline-move-subtree-down + outline-up-heading outline-hide-subtree outline-cycle + ;; org commands (remapped outline commands) + org-forward-heading-same-level org-backward-heading-same-level + org-next-visible-heading org-previous-visible-heading + org-demote-subtree org-promote-subtree + org-show-subtree (org-mark-subtree . region) + org-move-subtree-up org-move-subtree-down + ;; transpose commands + transpose-sexps transpose-sentences transpose-paragraphs + ;; navigation commands + flymake-goto-next-error flymake-goto-prev-error + embark-next-symbol embark-previous-symbol + backward-up-list backward-list forward-list forward-sexp + backward-sexp forward-sentence backward-sentence + forward-paragraph backward-paragraph + ;; smerge commands + smerge-refine smerge-combine-with-next smerge-prev smerge-next) + "List of repeatable actions. +When you use a command on this list as an Embark action from +outside the minibuffer, `embark-act' does not exit but instead +lets you act again on the possibly new target you reach. + +By default, after using one of these actions, when `embark-act' +looks for targets again, it will start the target cycle at the +same type as the previously acted upon target; that is, you +\"don't loose your place in the target cycle\". + +Sometimes, however, you'll want to prioritize a different type of +target to continue acting on. The main example of this that if +you use a marking command as an action, you almost always want to +act on the region next. For those cases, in addition to +commands, you can also place on this list a pair of a command and +the desired starting type for the target cycle for the next +action." + :type '(repeat (choice function + (cons function + (symbol :tag "Next target type"))))) + +;;; Overlay properties + +;; high priority to override both bug reference and the lazy +;; isearch highlights in embark-isearch-highlight-indicator +(put 'embark-target-overlay 'face 'embark-target) +(put 'embark-target-overlay 'priority 1001) +(put 'embark-selected-overlay 'face 'embark-selected) +(put 'embark-selected-overlay 'priority 1001) + +;;; Stashing information for actions in buffer local variables + +(defvar-local embark--type nil + "Cache for the completion type, meant to be set buffer-locally.") + +(defvar-local embark--target-buffer nil + "Cache for the previous buffer, meant to be set buffer-locally.") + +(defvar-local embark--target-window nil + "Cache for the previous window, meant to be set buffer-locally. +Since windows can be reused to display different buffers, this +window should only be used if it displays the buffer stored in +the variable `embark--target-buffer'.") + +(defvar-local embark--command nil + "Command that started the completion session.") + +(defvar-local embark--toggle-quit nil + "Should we toggle the default quitting behavior for the next action?") + +(defun embark--minibuffer-point () + "Return length of minibuffer contents." + (max 0 (- (point) (minibuffer-prompt-end)))) + +(defun embark--default-directory () + "Guess a reasonable default directory for the current candidates." + (if (and (minibufferp) minibuffer-completing-file-name) + (let ((end (minibuffer-prompt-end)) + (contents (minibuffer-contents))) + (expand-file-name + (substitute-in-file-name + (buffer-substring + end + (+ end + (or (cdr + (last + (completion-all-completions + contents + minibuffer-completion-table + minibuffer-completion-predicate + (embark--minibuffer-point)))) + (cl-position ?/ contents :from-end t) + 0)))))) + default-directory)) + +(defun embark--target-buffer () + "Return buffer that should be targeted by Embark actions." + (cond + ((and (minibufferp) minibuffer-completion-table (minibuffer-selected-window)) + (window-buffer (minibuffer-selected-window))) + ((and embark--target-buffer (buffer-live-p embark--target-buffer)) + embark--target-buffer) + (t (current-buffer)))) + +(defun embark--target-window (&optional display) + "Return window which should be selected when Embark actions run. +If DISPLAY is non-nil, call `display-buffer' to produce the +window if necessary." + (cond + ((and (minibufferp) minibuffer-completion-table (minibuffer-selected-window)) + (minibuffer-selected-window)) + ((and embark--target-window + (window-live-p embark--target-window) + (or (not (buffer-live-p embark--target-buffer)) + (eq (window-buffer embark--target-window) embark--target-buffer))) + embark--target-window) + ((and embark--target-buffer (buffer-live-p embark--target-buffer)) + (or (get-buffer-window embark--target-buffer) + (when display (display-buffer embark--target-buffer)))) + (display (selected-window)))) + +(defun embark--cache-info (buffer) + "Cache information needed for actions in variables local to BUFFER. +BUFFER defaults to the current buffer." + (let ((cmd embark--command) + (dir (embark--default-directory)) + (target-buffer (embark--target-buffer)) + (target-window (embark--target-window))) + (with-current-buffer buffer + (setq embark--command cmd + default-directory dir + embark--target-buffer target-buffer + embark--target-window target-window)))) + +(defun embark--cache-info--completion-list () + "Cache information needed for actions in a *Completions* buffer. +Meant to be be added to `completion-setup-hook'." + ;; when completion-setup-hook hook runs, the *Completions* buffer is + ;; available in the variable standard-output + (embark--cache-info standard-output) + (with-current-buffer standard-output + (when (minibufferp completion-reference-buffer) + (setq embark--type + (completion-metadata-get + (with-current-buffer completion-reference-buffer + (embark--metadata)) + 'category))))) + +;; We have to add this *after* completion-setup-function because that's +;; when the buffer is put in completion-list-mode and turning the mode +;; on kills all local variables! So we use a depth of 5. +(add-hook 'completion-setup-hook #'embark--cache-info--completion-list 5) + +;;;###autoload +(progn + (defun embark--record-this-command () + "Record command which opened the minibuffer. +We record this because it will be the default action. +This function is meant to be added to `minibuffer-setup-hook'." + (setq-local embark--command this-command)) + (add-hook 'minibuffer-setup-hook #'embark--record-this-command)) + +;;; Internal variables + +(defvar embark--prompter-history nil + "History used by the `embark-completing-read-prompter'.") + +;;; Core functionality + +(defconst embark--verbose-indicator-buffer " *Embark Actions*") + +(defvar embark--minimal-indicator-overlay nil) + +(defun embark--metadata () + "Return current minibuffer completion metadata." + (completion-metadata + (buffer-substring-no-properties + (minibuffer-prompt-end) + (max (minibuffer-prompt-end) (point))) + minibuffer-completion-table + minibuffer-completion-predicate)) + +(defun embark-target-active-region () + "Target the region if active." + (when (use-region-p) + (let ((start (region-beginning)) + (end (region-end))) + `(region ,(buffer-substring start end) . (,start . ,end))))) + +(autoload 'dired-get-filename "dired") +(declare-function image-dired-original-file-name "image-dired") + +(defun embark-target-guess-file-at-point () + "Target the file guessed by `ffap' at point." + (when-let ((tap-file (thing-at-point 'filename)) + ((not (ffap-url-p tap-file))) ; no URLs, those have a target finder + (bounds (bounds-of-thing-at-point 'filename)) + (file (ffap-file-at-point))) + ;; ffap doesn't make bounds available, so we use + ;; thingatpt bounds, which might be a little off + ;; adjust bounds if thingatpt gobbled punctuation around file + (when (or (string-match (regexp-quote file) tap-file) + (string-match (regexp-quote (file-name-base file)) tap-file)) + (setq bounds (cons (+ (car bounds) (match-beginning 0)) + (- (cdr bounds) (- (length tap-file) + (match-end 0)))))) + `(file ,(abbreviate-file-name (expand-file-name file)) ,@bounds))) + +(defun embark-target-file-at-point () + "Target file at point. +This function mostly relies on `ffap-file-at-point', with the +following exceptions: + +- In `dired-mode', it uses `dired-get-filename' instead. + +- In `imaged-dired-thumbnail-mode', it uses + `image-dired-original-file-name' instead." + (let (file bounds) + (or (and (derived-mode-p 'dired-mode) + (setq file (dired-get-filename t 'no-error-if-not-filep)) + (setq bounds + (cons + (save-excursion (dired-move-to-filename) (point)) + (save-excursion (dired-move-to-end-of-filename) (point))))) + (and (derived-mode-p 'image-dired-thumbnail-mode) + (setq file (image-dired-original-file-name)) + (setq bounds (cons (point) (1+ (point))))) + (when-let ((tap-file (thing-at-point 'filename)) + ((not (equal (file-name-base tap-file) tap-file))) + (guess (embark-target-guess-file-at-point))) + (setq file (cadr guess) bounds (cddr guess)))) + (when file + `(file ,(abbreviate-file-name (expand-file-name file)) ,@bounds)))) + +(defun embark-target-package-at-point () + "Target the package on the current line in a packages buffer." + (when (derived-mode-p 'package-menu-mode) + (when-let ((pkg (get-text-property (point) 'tabulated-list-id))) + `(package ,(symbol-name (package-desc-name pkg)) + ,(line-beginning-position) . ,(line-end-position))))) + +(defun embark-target-email-at-point () + "Target the email address at point." + (when-let ((email (thing-at-point 'email))) + (when (string-prefix-p "mailto:" email) + (setq email (string-remove-prefix "mailto:" email))) + `(email ,email . ,(bounds-of-thing-at-point 'email)))) + +(defun embark-target-url-at-point () + "Target the URL at point." + (if-let ((url (or (get-text-property (point) 'shr-url) + (get-text-property (point) 'image-url)))) + `(url ,url + ,(previous-single-property-change + (min (1+ (point)) (point-max)) 'mouse-face nil (point-min)) + . ,(next-single-property-change + (point) 'mouse-face nil (point-max))) + (when-let ((url (thing-at-point 'url))) + `(url ,url . ,(thing-at-point-bounds-of-url-at-point t))))) + +(declare-function widget-at "wid-edit") + +(defun embark-target-custom-variable-at-point () + "Target the variable corresponding to the customize widget at point." + (when (derived-mode-p 'Custom-mode) + (save-excursion + (beginning-of-line) + (when-let* ((widget (widget-at (point))) + (var (and (eq (car widget) 'custom-visibility) + (plist-get (cdr widget) :parent))) + (sym (and (eq (car var) 'custom-variable) + (plist-get (cdr var) :value)))) + `(variable + ,(symbol-name sym) + ,(point) + . ,(progn + (re-search-forward ":" (line-end-position) 'noerror) + (point))))))) + +;; NOTE: There is also (thing-at-point 'list), however it does +;; not work on strings and requires the point to be inside the +;; parentheses. This version here is slightly more general. +(defun embark-target-expression-at-point () + "Target expression at point." + (cl-flet ((syntax-p (class &optional (delta 0)) + (and (<= (point-min) (+ (point) delta) (point-max)) + (eq (pcase class + ('open 4) ('close 5) ('prefix 6) ('string 7)) + (syntax-class (syntax-after (+ (point) delta))))))) + (when-let + ((start + (pcase-let ((`(_ ,open _ ,string _ _ _ _ ,start _ _) (syntax-ppss))) + (ignore-errors ; set start=nil if delimiters are unbalanced + (cond + (string start) + ((or (syntax-p 'open) (syntax-p 'prefix)) + (save-excursion (backward-prefix-chars) (point))) + ((syntax-p 'close -1) + (save-excursion + (backward-sexp) (backward-prefix-chars) (point))) + ((syntax-p 'string) (point)) + ((syntax-p 'string -1) (scan-sexps (point) -1)) + (t open))))) + (end (ignore-errors (scan-sexps start 1)))) + (unless (eq start (car (bounds-of-thing-at-point 'defun))) + `(expression ,(buffer-substring start end) ,start . ,end))))) + +(defmacro embark-define-overlay-target (name prop &optional pred type target) + "Define a target finder for NAME that targets overlays with property PROP. +The function defined is named embark-target-NAME-at-point and it +returns Embark targets based on the overlays around point. An +overlay provides a target if its property named PROP is non-nil. + +If the optional PRED argument is given, it should be an +expression and it further restricts the targets to only those +overlays for which PRED evaluates to non-nil. + +The target finder returns target type NAME or optional symbol +TYPE if given. + +The target finder returns the substring of the buffer covered by +the overlay as the target string or the result of evaluating the +optional TARGET expression if given. + +PRED and TARGET are expressions (not functions) and when evaluated the +symbols `%o' and `%p' are bound to the overlay and the overlay's +property respectively." + `(defun ,(intern (format "embark-target-%s-at-point" name)) () + ,(format "Target %s at point." name) + (when-let ((%o (seq-find + (lambda (%o) + (when-let ((%p (overlay-get %o ',prop))) + (ignore %p) + ,(or pred t))) + (overlays-in (max (point-min) (1- (point))) + (min (point-max) (1+ (point)))))) + (%p (overlay-get %o ',prop))) + (ignore %p) + (cons ',(or type name) + (cons ,(or target `(buffer-substring-no-properties + (overlay-start %o) (overlay-end %o))) + (cons (overlay-start %o) (overlay-end %o))))))) + +(embark-define-overlay-target flymake flymake-diagnostic) +(embark-define-overlay-target bug-reference bug-reference-url nil url %p) +(embark-define-overlay-target smerge smerge (eq %p 'conflict)) + +(defmacro embark-define-thingatpt-target (thing &rest modes) + "Define a target finder for THING using the thingatpt library. +The function defined is named embark-target-NAME-at-point and it +uses (thing-at-point \\='THING) to find its targets. + +If any MODES are given, the target finder only applies to buffers +in one of those major modes." + (declare (indent 1)) + `(defun ,(intern (format "embark-target-%s-at-point" thing)) () + ,(format "Target %s at point." thing) + (when ,(if modes `(derived-mode-p ,@(mapcar (lambda (m) `',m) modes)) t) + (when-let (bounds (bounds-of-thing-at-point ',thing)) + (cons ',thing (cons + (buffer-substring (car bounds) (cdr bounds)) + bounds)))))) + +(embark-define-thingatpt-target defun) +(embark-define-thingatpt-target sentence + text-mode help-mode Info-mode man-common) +(embark-define-thingatpt-target paragraph + text-mode help-mode Info-mode man-common) + +(defmacro embark-define-regexp-target + (name regexp &optional type target bounds limit) + "Define a target finder for matches of REGEXP around point. +The function defined is named embark-target-NAME-at-point and it +uses (thing-at-point-looking-at REGEXP) to find its targets. + +The target finder returns target type NAME or optional symbol +TYPE if given. + +The target finder returns the substring of the buffer matched by +REGEXP as the target string or the result of evaluating the +optional TARGET expression if given. In the expression TARGET +you can use `match-string' to recover the match of the REGEXP or +of any sub-expressions it has. + +BOUNDS is an optional expression to compute the bounds of the +target and defaults to (cons (match-beginning 0) (match-end 0)). + +The optional LIMIT is the number of characters before and after +point to limit the search to. If LIMIT is nil, search a little +more than the current line (more precisely, the smallest interval +centered at point that includes the current line)." + `(defun ,(intern (format "embark-target-%s-at-point" name)) () + ,(format "Target %s at point." name) + (save-match-data + (when (thing-at-point-looking-at + ,regexp + ,(or limit '(max (- (pos-eol) (point)) (- (point) (pos-bol))))) + (cons ',(or type name) + (cons ,(or target '(match-string 0)) + ,(or bounds + '(cons (match-beginning 0) (match-end 0))))))))) + +(defun embark--identifier-types (identifier) + "Return list of target types appropriate for IDENTIFIER." + (let ((symbol (intern-soft identifier))) + (if (not + (or (derived-mode-p 'emacs-lisp-mode 'inferior-emacs-lisp-mode) + (and (not (derived-mode-p 'prog-mode)) + symbol + (or (boundp symbol) (fboundp symbol) (symbol-plist symbol))))) + '(identifier) + (let* ((library (ffap-el-mode identifier)) + (types + (append + (and (commandp symbol) '(command)) + (and symbol (boundp symbol) (not (keywordp symbol)) '(variable)) + (and (fboundp symbol) (not (commandp symbol)) '(function)) + (and (facep symbol) '(face)) + (and library '(library)) + (and (featurep 'package) (embark--package-desc symbol) + '(package))))) + (when (and library + (looking-back "\\(?:require\\|use-package\\).*" + (line-beginning-position))) + (setq types (embark--rotate types (cl-position 'library types)))) + (or types '(symbol)))))) + +(defun embark-target-identifier-at-point () + "Target identifier at point. + +In Emacs Lisp and IELM buffers the identifier is promoted to a +symbol, for which more actions are available. Identifiers are +also promoted to symbols if they are interned Emacs Lisp symbols +and found in a buffer in a major mode that is not derived from +`prog-mode' (this is intended for when you might be reading or +writing about Emacs). + +As a convenience, in Org Mode an initial ' or surrounding == or +~~ are removed." + (when-let (bounds (bounds-of-thing-at-point 'symbol)) + (let ((name (buffer-substring (car bounds) (cdr bounds)))) + (when (derived-mode-p 'org-mode) + (cond ((string-prefix-p "'" name) + (setq name (substring name 1)) + (cl-incf (car bounds))) + ((string-match-p "^\\([=~]\\).*\\1$" name) + (setq name (substring name 1 -1)) + (cl-incf (car bounds)) + (cl-decf (cdr bounds))))) + (mapcar (lambda (type) `(,type ,name . ,bounds)) + (embark--identifier-types name))))) + +(defun embark-target-heading-at-point () + "Target the outline heading at point." + (let ((beg (line-beginning-position)) + (end (line-end-position))) + (when (save-excursion + (goto-char beg) + (and (bolp) + (looking-at + ;; default definition from outline.el + (or (bound-and-true-p outline-regexp) "[*\^L]+")))) + (require 'outline) ;; Ensure that outline commands are available + `(heading ,(buffer-substring beg end) ,beg . ,end)))) + +(defun embark-target-text-heading-at-point () + "Target the outline heading at point in text modes." + (when (derived-mode-p 'text-mode) + (embark-target-heading-at-point))) + +(defun embark-target-prog-heading-at-point () + "Target the outline heading at point in programming modes." + (when (derived-mode-p 'prog-mode) + (embark-target-heading-at-point))) + +(defun embark-target-top-minibuffer-candidate () + "Target the top completion candidate in the minibuffer. +Return the category metadatum as the type of the target. + +This target finder is meant for the default completion UI and +completion UI highly compatible with it, like Icomplete. +Many completion UIs can still work with Embark but will need +their own target finder. See for example +`embark--vertico-selected'." + (when (and (minibufferp) minibuffer-completion-table) + (pcase-let* ((`(,category . ,candidates) (embark-minibuffer-candidates)) + (contents (minibuffer-contents)) + (top (if (test-completion contents + minibuffer-completion-table + minibuffer-completion-predicate) + contents + (let ((completions (completion-all-sorted-completions))) + (if (null completions) + contents + (concat + (substring contents + 0 (or (cdr (last completions)) 0)) + (car completions))))))) + (cons category (or (car (member top candidates)) top))))) + +(defun embark-target-collect-candidate () + "Target the collect candidate at point." + (when (derived-mode-p 'embark-collect-mode) + (when-let ((button + (pcase (get-text-property (point) 'tabulated-list-column-name) + ("Candidate" (button-at (point))) + ("Annotation" (previous-button (point))))) + (start (button-start button)) + (end (button-end button)) + (candidate (tabulated-list-get-id))) + `(,embark--type + ,(if (eq embark--type 'file) + (abbreviate-file-name (expand-file-name candidate)) + candidate) + ,start . ,end)))) + +(defun embark-target-completion-list-candidate () + "Return the completion candidate at point in a completions buffer." + (when (derived-mode-p 'completion-list-mode) + (if (not (get-text-property (point) 'mouse-face)) + (user-error "No completion here") + ;; this fairly delicate logic is taken from `choose-completion' + (let (beg end) + (cond + ((and (not (eobp)) (get-text-property (point) 'mouse-face)) + (setq end (point) beg (1+ (point)))) + ((and (not (bobp)) + (get-text-property (1- (point)) 'mouse-face)) + (setq end (1- (point)) beg (point))) + (t (user-error "No completion here"))) + (setq beg (previous-single-property-change beg 'mouse-face)) + (setq end (or (next-single-property-change end 'mouse-face) + (point-max))) + (let ((raw (or (get-text-property beg 'completion--string) + (buffer-substring beg end)))) + `(,embark--type + ,(if (eq embark--type 'file) + (abbreviate-file-name (expand-file-name raw)) + raw) + ,beg . ,end)))))) + +(defun embark--cycle-key () + "Return the key to use for `embark-cycle'." + (if embark-cycle-key + (if (key-valid-p embark-cycle-key) + (key-parse embark-cycle-key) + (error "`embark-cycle-key' is invalid")) + (car (where-is-internal #'embark-act)))) + +(defun embark--raw-action-keymap (type) + "Return raw action map for targets of given TYPE. +This does not take into account the default action, help key or +cycling bindings, just what's registered in +`embark-keymap-alist'." + (make-composed-keymap + (mapcar #'symbol-value + (let ((actions (or (alist-get type embark-keymap-alist) + (alist-get t embark-keymap-alist)))) + (ensure-list actions))))) + +(defun embark--action-keymap (type cycle) + "Return action keymap for targets of given TYPE. +If CYCLE is non-nil bind `embark-cycle'." + (make-composed-keymap + (let ((map (make-sparse-keymap)) + (default-action (embark--default-action type))) + (define-key map [13] default-action) + (when-let ((cycle-key (and cycle (embark--cycle-key)))) + (define-key map cycle-key #'embark-cycle)) + (when embark-help-key + (keymap-set map embark-help-key #'embark-keymap-help)) + map) + (embark--raw-action-keymap type))) + +(defun embark--truncate-target (target) + "Truncate TARGET string." + (unless (stringp target) + (setq target (format "%s" target))) + (if-let (pos (string-match-p "\n" target)) + (concat (car (split-string target "\n" 'omit-nulls "\\s-*")) "…") + target)) + +;;;###autoload +(defun embark-eldoc-first-target (report &rest _) + "Eldoc function reporting the first Embark target at point. +This function uses the eldoc REPORT callback and is meant to be +added to `eldoc-documentation-functions'." + (when-let (((not (minibufferp))) + (target (car (embark--targets)))) + (funcall report + (format "Embark on %s ‘%s’" + (plist-get target :type) + (embark--truncate-target (plist-get target :target)))))) + +;;;###autoload +(defun embark-eldoc-target-types (report &rest _) + "Eldoc function reporting the types of all Embark targets at point. +This function uses the eldoc REPORT callback and is meant to be +added to `eldoc-documentation-functions'." + (when-let (((not (minibufferp))) + (targets (embark--targets))) + (funcall report + (format "Embark target types: %s" + (mapconcat + (lambda (target) (symbol-name (plist-get target :type))) + targets + ", "))))) + +(defun embark--format-targets (target shadowed-targets rep) + "Return a formatted string indicating the TARGET of an action. + +This is used internally by the minimal indicator and for the +targets section of the verbose indicator. The string will also +mention any SHADOWED-TARGETS. A non-nil REP indicates we are in +a repeating sequence of actions." + (let ((act (propertize + (cond + ((plist-get target :multi) "∀ct") + (rep "Rep") + (t "Act")) + 'face 'highlight))) + (cond + ((eq (plist-get target :type) 'embark-become) + (propertize "Become" 'face 'highlight)) + ((and (minibufferp) + (not (eq 'embark-keybinding + (completion-metadata-get + (embark--metadata) + 'category)))) + ;; we are in a minibuffer but not from the + ;; completing-read prompter, use just "Act" + act) + ((plist-get target :multi) + (format "%s on %s %ss" + act + (plist-get target :multi) + (plist-get target :type))) + (t (format + "%s on %s%s ‘%s’" + act + (plist-get target :type) + (if shadowed-targets + (format (propertize "(%s)" 'face 'shadow) + (mapconcat + (lambda (target) (symbol-name (plist-get target :type))) + shadowed-targets + ", ")) + "") + (embark--truncate-target (plist-get target :target))))))) + +(defun embark-minimal-indicator () + "Minimal indicator, appearing in the minibuffer prompt or echo area. +This indicator displays a message showing the types of all +targets, starting with the current target, and the value of the +current target. The message is displayed in the echo area, or if +the minibuffer is open, the message is added to the prompt." + (lambda (&optional keymap targets _prefix) + (if (null keymap) + (when embark--minimal-indicator-overlay + (delete-overlay embark--minimal-indicator-overlay) + (setq-local embark--minimal-indicator-overlay nil)) + (let ((indicator (embark--format-targets + (car targets) (cdr targets) + (eq (lookup-key keymap [13]) #'embark-done)))) + (if (not (minibufferp)) + (message "%s" indicator) + (unless embark--minimal-indicator-overlay + (setq-local embark--minimal-indicator-overlay + (make-overlay (point-min) (point-min) + (current-buffer) t t))) + (overlay-put embark--minimal-indicator-overlay + 'before-string (concat indicator + (if (<= (length indicator) + (* 0.4 (frame-width))) + " " + "\n")))))))) + +(defun embark--read-key-sequence (update) + "Read key sequence, call UPDATE function with prefix keys." + (let (timer prefix) + (unwind-protect + (progn + (when (functionp update) + (setq timer (run-at-time + 0.05 0.05 + (lambda () + (let ((new-prefix (this-single-command-keys))) + (unless (equal prefix new-prefix) + (setq prefix new-prefix) + (when (/= (length prefix) 0) + (funcall update prefix)))))))) + (read-key-sequence-vector nil nil nil t 'cmd-loop)) + (when timer + (cancel-timer timer))))) + +(defvar embark-indicators) ; forward declaration + +(defun embark-keymap-prompter (keymap update) + "Let the user choose an action using the bindings in KEYMAP. +Besides the bindings in KEYMAP, the user is free to use all their +key bindings and even \\[execute-extended-command] to select a command. +UPDATE is the indicator update function." + (let* ((keys (let ((overriding-terminal-local-map keymap)) + (embark--read-key-sequence update))) + (cmd (let ((overriding-terminal-local-map keymap)) + (key-binding keys 'accept-default)))) + ;; Set last-command-event as it would be from the command loop. + ;; Previously we only set it locally for digit-argument and for + ;; the mouse scroll commands handled in this function. But other + ;; commands can need it too! For example, electric-pair-mode users + ;; may wish to bind ( to self-insert-command in embark-region-map. + ;; Also, as described in issue #402, there are circumstances where + ;; you might run consult-narrow through the embark-keymap-prompter. + (setq last-command-event (aref keys (1- (length keys)))) + (pcase cmd + ((or 'embark-keymap-help + (and 'nil ; cmd is nil but last key is help-char + (guard (eq help-char (aref keys (1- (length keys))))))) + (let ((embark-indicators + (cl-set-difference embark-indicators + '(embark-verbose-indicator + embark-mixed-indicator))) + (prefix-map + (if (eq cmd 'embark-keymap-help) + keymap + (let ((overriding-terminal-local-map keymap)) + (key-binding (seq-take keys (1- (length keys))) + 'accept-default)))) + (prefix-arg prefix-arg)) ; preserve prefix arg + (when-let ((win (get-buffer-window embark--verbose-indicator-buffer + 'visible))) + (quit-window 'kill-buffer win)) + (embark-completing-read-prompter prefix-map update))) + ((or 'universal-argument 'universal-argument-more + 'negative-argument 'digit-argument 'embark-toggle-quit) + ;; prevent `digit-argument' from modifying the overriding map + (let ((overriding-terminal-local-map overriding-terminal-local-map)) + (command-execute cmd)) + (embark-keymap-prompter + (make-composed-keymap universal-argument-map keymap) + update)) + ((or 'minibuffer-keyboard-quit 'abort-recursive-edit 'abort-minibuffers) + nil) + ((guard (let ((def (lookup-key keymap keys))) ; if directly + ; bound, then obey + (and def (not (numberp def))))) ; number means "invalid prefix" + cmd) + ((and (pred symbolp) + (guard (string-suffix-p "self-insert-command" (symbol-name cmd)))) + (minibuffer-message "Not an action") + (embark-keymap-prompter keymap update)) + ((or 'scroll-other-window 'scroll-other-window-down) + (let ((minibuffer-scroll-window + ;; NOTE: Here we special case the verbose indicator! + (or (get-buffer-window embark--verbose-indicator-buffer 'visible) + minibuffer-scroll-window))) + (ignore-errors (command-execute cmd))) + (embark-keymap-prompter keymap update)) + ((or 'scroll-bar-toolkit-scroll 'mwheel-scroll + 'mac-mwheel-scroll 'pixel-scroll-precision) + (funcall cmd last-command-event) + (embark-keymap-prompter keymap update)) + ('execute-extended-command + (let ((prefix-arg prefix-arg)) ; preserve prefix arg + (intern-soft (read-extended-command)))) + ((or 'keyboard-quit 'keyboard-escape-quit) + nil) + (_ cmd)))) + +(defun embark--command-name (cmd) + "Return an appropriate name for CMD. +If CMD is a symbol, use its symbol name; for lambdas, use the +first line of the documentation string; for keyboard macros use +`key-description'; otherwise use the word \"unnamed\"." + (concat ; fresh copy, so we can freely add text properties + (cond + ((or (stringp cmd) (vectorp cmd)) (key-description cmd)) + ((stringp (car-safe cmd)) (car cmd)) + ((eq (car-safe cmd) 'menu-item) (eval (cadr cmd))) + ((keymapp cmd) + (propertize (if (symbolp cmd) (format "+%s" cmd) "<keymap>") + 'face 'embark-keymap)) + ((symbolp cmd) + (let ((name (symbol-name cmd))) + (if (string-prefix-p "embark-action--" name) ; direct action mode + (format "(%s)" (string-remove-prefix "embark-action--" name)) + name))) + ((when-let (doc (and (functionp cmd) (ignore-errors (documentation cmd)))) + (save-match-data + (when (string-match "^\\(.*\\)$" doc) + (match-string 1 doc))))) + (t "<unnamed>")))) + +;; Taken from Marginalia, needed by the verbose indicator. +;; We cannot use the completion annotators in this case. +(defconst embark--advice-regexp + (rx bos + (1+ (seq (? "This function has ") + (or ":before" ":after" ":around" ":override" + ":before-while" ":before-until" ":after-while" + ":after-until" ":filter-args" ":filter-return") + " advice: " (0+ nonl) "\n")) + "\n") + "Regexp to match lines about advice in function documentation strings.") + +;; Taken from Marginalia, needed by the verbose indicator. +;; We cannot use the completion annotators in this case. +(defun embark--function-doc (sym) + "Documentation string of function SYM." + (let ((vstr (and (symbolp sym) (keymapp sym) (boundp sym) + (eq (symbol-function sym) (symbol-value sym)) + (documentation-property sym 'variable-documentation)))) + (when-let (str (or (ignore-errors (documentation sym)) vstr)) + ;; Replace standard description with variable documentation + (when (and vstr (string-match-p "\\`Prefix command" str)) + (setq str vstr)) + (save-match-data + (if (string-match embark--advice-regexp str) + (substring str (match-end 0)) + str))))) + +(defun embark--action-repeatable-p (action) + "Is ACTION repeatable? +When the return value is non-nil it will be the desired starting +point of the next target cycle or t to indicate the default, +namely that the target cycle for the next action should begin at +the type of the current target." + (or (cdr (assq action embark-repeat-actions)) + (and (memq action embark-repeat-actions) t))) + +(defun embark--formatted-bindings (keymap &optional nested) + "Return the formatted keybinding of KEYMAP. +The keybindings are returned in their order of appearance. +If NESTED is non-nil subkeymaps are not flattened." + (let* ((commands + (cl-loop for (key . def) in (embark--all-bindings keymap nested) + for name = (embark--command-name def) + for cmd = (keymap--menu-item-binding def) + unless (memq cmd '(nil embark-keymap-help + negative-argument digit-argument)) + collect (list name cmd key + (concat + (if (eq (car-safe def) 'menu-item) + "menu-item" + (key-description key)))))) + (width (cl-loop for (_name _cmd _key desc) in commands + maximize (length desc))) + (default) + (candidates + (cl-loop for item in commands + for (name cmd key desc) = item + for desc-rep = + (concat + (propertize desc 'face 'embark-keybinding) + (and (embark--action-repeatable-p cmd) + embark-keybinding-repeat)) + for formatted = + (propertize + (concat desc-rep + (make-string (- width (length desc-rep) -1) ?\s) + name) + 'embark-command cmd) + when (equal key [13]) + do (setq default formatted) + collect (cons formatted item)))) + (cons candidates default))) + +(defun embark--with-category (category candidates) + "Return completion table for CANDIDATES of CATEGORY with sorting disabled." + (lambda (string predicate action) + (if (eq action 'metadata) + `(metadata (display-sort-function . identity) + (cycle-sort-function . identity) + (category . ,category)) + (complete-with-action + action candidates string predicate)))) + +(defun embark-completing-read-prompter (keymap update &optional no-default) + "Prompt via completion for a command bound in KEYMAP. +If NO-DEFAULT is t, no default value is passed to`completing-read'. + +UPDATE is the indicator update function. It is not used directly +here, but if the user switches to `embark-keymap-prompter', the +UPDATE function is passed to it." + (let* ((candidates+def (embark--formatted-bindings keymap)) + (candidates (car candidates+def)) + (def (and (not no-default) (cdr candidates+def))) + (buf (current-buffer)) + (choice + (catch 'choice + (minibuffer-with-setup-hook + (lambda () + (let ((map (make-sparse-keymap))) + (define-key map "\M-q" + (lambda () + (interactive) + (with-current-buffer buf + (embark-toggle-quit)))) + (when-let (cycle (embark--cycle-key)) + ;; Rebind `embark-cycle' in order allow cycling + ;; from the `completing-read' prompter. Additionally + ;; `embark-cycle' can be selected via + ;; `completing-read'. The downside is that this breaks + ;; recursively acting on the candidates of type + ;; embark-keybinding in the `completing-read' prompter. + (define-key map cycle + (cond + ((eq (lookup-key keymap cycle) 'embark-cycle) + (lambda () + (interactive) + (throw 'choice 'embark-cycle))) + ((null embark-cycle-key) + (lambda () + (interactive) + (minibuffer-message + "No cycling possible; press `%s' again to act." + (key-description cycle)) + (define-key map cycle #'embark-act)))))) + (when embark-keymap-prompter-key + (keymap-set map embark-keymap-prompter-key + (lambda () + (interactive) + (message "Press key binding") + (let ((cmd (embark-keymap-prompter keymap update))) + (if (null cmd) + (user-error "Unknown key") + (throw 'choice cmd)))))) + (use-local-map + (make-composed-keymap map (current-local-map))))) + (completing-read + "Command: " + (embark--with-category 'embark-keybinding candidates) + nil nil nil 'embark--prompter-history def))))) + (pcase (assoc choice candidates) + (`(,_formatted ,_name ,cmd ,key ,_desc) + ;; Set last-command-event as it would be from the command loop. + (setq last-command-event (aref key (1- (length key)))) + cmd) + ('nil (intern-soft choice))))) + +;;; Verbose action indicator + +(defgroup embark-indicators nil + "Indicators display information about actions and targets." + :group 'embark) + +(defcustom embark-indicators + '(embark-mixed-indicator + embark-highlight-indicator + embark-isearch-highlight-indicator) + "Indicator functions to use when acting or becoming. +The indicator functions are called from both `embark-act' and +from `embark-become' and should display information about this to +the user, such as: which of those two commands is running; a +description of the key bindings that are available for actions or +commands to become; and, in the case of `embark-act', the type +and value of the targets, and whether other targets are available +via `embark-cycle'. The indicator function is free to display as +much or as little of this information as desired and can use any +Emacs interface elements to do so. + +Embark comes with five such indicators: + +- `embark-minimal-indicator', which does not display any + information about keybindings, but does display types and + values of action targets in the echo area or minibuffer prompt, + +- `embark-verbose-indicator', which pops up a buffer containing + detailed information including key bindings and the first line + of the docstring of the commands they run, and + +- `embark-mixed-indicator', which combines the minimal and the + verbose indicator: the minimal indicator is shown first and the + verbose popup is shown after `embark-mixed-indicator-delay' + seconds. + +- `embark-highlight-indicator', which highlights the target + at point. + +- `embark-isearch-highlight-indicator', which when the target at + point is an identifier or symbol, lazily highlights all + occurrences of it. + +The protocol for indicator functions is as follows: + +When called from `embark-act', an indicator function is called +without arguments. The indicator function should then return a +closure, which captures the indicator state. The returned +closure must accept up to three optional arguments, the action +keymap, the targets (plists as returned by `embark--targets') and +the prefix keys typed by the user so far. The keymap, targets +and prefix keys may be updated when cycling targets at point +resulting in multiple calls to the closure. When called from +`embark-become', the indicator closure will be called with the +keymap of commands to become, a fake target list containing a +single target of type `embark-become' and whose value is the +minibuffer input, and the prefix set to nil. Note, in +particular, that if an indicator function wishes to distinguish +between `embark-act' and `embark-become' it should check whether +the `car' of the first target is `embark-become'. + +After the action has been performed the indicator closure is +called without arguments, such that the indicator can perform the +necessary cleanup work. For example, if the indicator adds +overlays, it should remove these overlays. The indicator should +be written in a way that it is safe to call it for cleanup more +than once, in fact, it should be able to handle any sequence of +update and cleanup calls ending in a call for cleanup. + +NOTE: Experience shows that the indicator calling convention may +change again in order to support more action features. The +calling convention should currently be considered unstable. +Please keep this in mind when writing a custom indicator +function, or when using the `which-key' indicator function from +the wiki." + :type '(repeat + (choice + (const :tag "Verbose indicator" embark-verbose-indicator) + (const :tag "Minimal indicator" embark-minimal-indicator) + (const :tag "Mixed indicator" embark-mixed-indicator) + (const :tag "Highlight target" embark-highlight-indicator) + (const :tag "Highlight all occurrences" + embark-isearch-highlight-indicator) + (function :tag "Other")))) + +(defface embark-verbose-indicator-documentation + '((t :inherit completions-annotations)) + "Face used by the verbose action indicator to display binding descriptions. +Used by `embark-verbose-indicator'.") + +(defface embark-verbose-indicator-title '((t :height 1.1 :weight bold)) + "Face used by the verbose action indicator for the title. +Used by `embark-verbose-indicator'.") + +(defface embark-verbose-indicator-shadowed '((t :inherit shadow)) + "Face used by the verbose action indicator for the shadowed targets. +Used by `embark-verbose-indicator'.") + +(defcustom embark-verbose-indicator-display-action + '(display-buffer-reuse-window) + "Parameters added to `display-buffer-alist' to show the actions buffer. +See the docstring of `display-buffer' for information on what +display actions and parameters are available." + :type `(choice + (const :tag "Reuse some window" + (display-buffer-reuse-window)) + (const :tag "Below target buffer" + (display-buffer-below-selected + (window-height . fit-window-to-buffer))) + (const :tag "Bottom of frame (fixed-size)" + (display-buffer-at-bottom)) + (const :tag "Bottom of frame (resizes during cycling)" + (display-buffer-at-bottom + (window-height . fit-window-to-buffer))) + (const :tag "Side window on the right" + (display-buffer-in-side-window (side . right))) + (const :tag "Side window on the left" + (display-buffer-in-side-window (side . left))) + (sexp :tag "Other"))) + +(defcustom embark-verbose-indicator-excluded-actions nil + "Commands not displayed by `embark-verbose-indicator'. +This variable should be set to a list of symbols and regexps. +The verbose indicator will exclude from its listing any commands +matching an element of this list." + :type '(choice + (const :tag "Exclude nothing" nil) + (const :tag "Exclude Embark general actions" + (embark-collect embark-live embark-export + embark-cycle embark-act-all embark-keymap-help + embark-become embark-isearch-forward + embark-isearch-backward)) + (repeat :tag "Other" (choice regexp symbol)))) + +(defcustom embark-verbose-indicator-buffer-sections + `(target "\n" shadowed-targets " " cycle "\n" bindings) + "List of sections to display in the verbose indicator buffer, in order. +You can use either a symbol designating a concrete section (one +of the keywords below, but without the colon), a string literal +or a function returning a string or list of strings to insert and +that accepts the following keyword arguments: + +- `:target', the target as a cons of type and value, +- `:shadowed-targets', a list of conses for the other targets, +- `:bindings' a list returned by `embark--formatted-bindings', and +- `:cycle', a string describing the key binding of `embark-cycle'." + :type '(repeat + (choice (const :tag "Current target name" target) + (const :tag "List of other shadowed targets" shadowed-targets) + (const :tag "Key bindings" bindings) + (const :tag "Cycle indicator" cycle) + (string :tag "Literal string") + (function :tag "Custom function")))) + +(defcustom embark-verbose-indicator-nested t + "Whether the verbose indicator should use nested keymap navigation. +When this variable is non-nil the actions buffer displayed by +`embark-verbose-indicator' will include any prefix keys found in +the keymap it is displaying, and will update to show what is +bound under the prefix if the prefix is pressed. If this +variable is nil, then the actions buffer will contain a flat list +of all full key sequences bound in the keymap." + :type 'boolean) + +(defun embark--verbose-indicator-excluded-p (cmd) + "Return non-nil if CMD should be excluded from the verbose indicator." + (seq-find (lambda (x) + (if (symbolp x) + (eq cmd x) + (string-match-p x (symbol-name cmd)))) + embark-verbose-indicator-excluded-actions)) + +(cl-defun embark--verbose-indicator-section-target + (&key targets bindings &allow-other-keys) + "Format the TARGETS section for the indicator buffer. +BINDINGS is the formatted list of keybindings." + (let ((result (embark--format-targets + (car targets) + nil ; the shadowed targets section deals with these + (cl-find 'embark-done bindings :key #'caddr :test #'eq)))) + (add-face-text-property 0 (length result) + 'embark-verbose-indicator-title + 'append + result) + result)) + +(cl-defun embark--verbose-indicator-section-cycle + (&key cycle shadowed-targets &allow-other-keys) + "Format the CYCLE key section for the indicator buffer. +SHADOWED-TARGETS is the list of other targets." + (concat + (and cycle (propertize (format "(%s to cycle)" cycle) + 'face 'embark-verbose-indicator-shadowed)) + (and shadowed-targets "\n"))) + +(cl-defun embark--verbose-indicator-section-shadowed-targets + (&key shadowed-targets &allow-other-keys) + "Format the SHADOWED-TARGETS section for the indicator buffer." + (when shadowed-targets + (propertize (format "Shadowed targets at point: %s" + (string-join shadowed-targets ", ")) + 'face 'embark-verbose-indicator-shadowed))) + +(cl-defun embark--verbose-indicator-section-bindings + (&key bindings &allow-other-keys) + "Format the BINDINGS section for the indicator buffer." + (let* ((max-width (apply #'max (cons 0 (mapcar (lambda (x) + (string-width (car x))) + bindings)))) + (fmt (format "%%-%ds" (1+ max-width))) + (result nil)) + (dolist (binding bindings (string-join (nreverse result))) + (let ((cmd (caddr binding))) + (unless (embark--verbose-indicator-excluded-p cmd) + (let ((keys (format fmt (car binding))) + (doc (embark--function-doc cmd))) + (push (format "%s%s\n" keys + (propertize + (car (split-string (or doc "") "\n")) + 'face 'embark-verbose-indicator-documentation)) + result))))))) + +(defun embark--verbose-indicator-update (keymap targets) + "Update verbose indicator buffer. +The arguments are the new KEYMAP and TARGETS." + (with-current-buffer (get-buffer-create embark--verbose-indicator-buffer) + (let* ((inhibit-read-only t) + (bindings + (embark--formatted-bindings keymap embark-verbose-indicator-nested)) + (bindings (car bindings)) + (shadowed-targets (mapcar + (lambda (x) (symbol-name (plist-get x :type))) + (cdr targets))) + (cycle (let ((ck (where-is-internal #'embark-cycle keymap))) + (and ck (key-description (car ck)))))) + (setq-local cursor-type nil) + (setq-local truncate-lines t) + (setq-local buffer-read-only t) + (erase-buffer) + (dolist (section embark-verbose-indicator-buffer-sections) + (insert + (if (stringp section) + section + (or (funcall + (let ((prefixed (intern (format + "embark--verbose-indicator-section-%s" + section)))) + (cond + ((fboundp prefixed) prefixed) + ((fboundp section) section) + (t (error "Undefined verbose indicator section `%s'" + section)))) + :targets targets :shadowed-targets shadowed-targets + :bindings bindings :cycle cycle) + "")))) + (goto-char (point-min))))) + +(defun embark-verbose-indicator () + "Indicator that displays a table of key bindings in a buffer. +The default display includes the type and value of the current +target, the list of other target types, and a table of key +bindings, actions and the first line of their docstrings. + +The order and formatting of these items is completely +configurable through the variable +`embark-verbose-indicator-buffer-sections'. + +If the keymap being shown contains prefix keys, the table of key +bindings can either show just the prefixes and update once the +prefix is pressed, or it can contain a flat list of all full key +sequences bound in the keymap. This is controlled by the +variable `embark-verbose-indicator-nested'. + +To reduce clutter in the key binding table, one can set the +variable `embark-verbose-indicator-excluded-actions' to a list +of symbols and regexps matching commands to exclude from the +table. + +To configure how a window is chosen to display this buffer, see +the variable `embark-verbose-indicator-display-action'." + (lambda (&optional keymap targets prefix) + (if (not keymap) + (when-let ((win (get-buffer-window embark--verbose-indicator-buffer + 'visible))) + (quit-window 'kill-buffer win)) + (embark--verbose-indicator-update + (if (and prefix embark-verbose-indicator-nested) + ;; Lookup prefix keymap globally if not found in action keymap + (let ((overriding-terminal-local-map keymap)) + (key-binding prefix 'accept-default)) + keymap) + targets) + (let ((display-buffer-alist + `(,@display-buffer-alist + (,(regexp-quote embark--verbose-indicator-buffer) + ,@embark-verbose-indicator-display-action)))) + (display-buffer embark--verbose-indicator-buffer))))) + +(defcustom embark-mixed-indicator-delay 0.5 + "Time in seconds after which the verbose indicator is shown. +The mixed indicator starts by showing the minimal indicator and +after this delay shows the verbose indicator." + :type '(choice (const :tag "No delay" 0) + (number :tag "Delay in seconds"))) + +(defcustom embark-mixed-indicator-both nil + "Show both indicators, even after the verbose indicator appeared." + :type 'boolean) + +(defun embark-mixed-indicator () + "Mixed indicator showing keymap and targets. +The indicator shows the `embark-minimal-indicator' by default. +After `embark-mixed-indicator-delay' seconds, the +`embark-verbose-indicator' is shown. This which-key-like approach +ensures that Embark stays out of the way for quick actions. The +helpful keybinding reminder still pops up automatically without +further user intervention." + (let ((vindicator (embark-verbose-indicator)) + (mindicator (embark-minimal-indicator)) + vindicator-active + vtimer) + (lambda (&optional keymap targets prefix) + ;; Always cancel the timer. + ;; 1. When updating, cancel timer, since the user has pressed + ;; a key before the timer elapsed. + ;; 2. For cleanup, the timer must also be canceled. + (when vtimer + (cancel-timer vtimer) + (setq vtimer nil)) + (if (not keymap) + (progn + (funcall vindicator) + (when mindicator + (funcall mindicator))) + (when mindicator + (funcall mindicator keymap targets prefix)) + (if vindicator-active + (funcall vindicator keymap targets prefix) + (setq vtimer + (run-at-time + embark-mixed-indicator-delay nil + (lambda () + (when (and (not embark-mixed-indicator-both) mindicator) + (funcall mindicator) + (setq mindicator nil)) + (setq vindicator-active t) + (funcall vindicator keymap targets prefix))))))))) + +;;;###autoload +(defun embark-bindings-in-keymap (keymap) + "Explore command key bindings in KEYMAP with `completing-read'. +The selected command will be executed. Interactively, prompt the +user for a KEYMAP variable." + (interactive + (list + (symbol-value + (intern-soft + (completing-read + "Keymap: " + (embark--with-category + 'variable + (cl-loop for x being the symbols + if (and (boundp x) (keymapp (symbol-value x))) + collect (symbol-name x))) + nil t nil 'variable-name-history + (let ((major-mode-map + (concat (symbol-name major-mode) "-map"))) + (when (intern-soft major-mode-map) major-mode-map))))))) + (when-let (command (embark-completing-read-prompter keymap nil 'no-default)) + (call-interactively command))) + +;;;###autoload +(defun embark-bindings (global) + "Explore current command key bindings with `completing-read'. +The selected command will be executed. + +This shows key bindings from minor mode maps and the local +map (usually set by the major mode), but also less common keymaps +such as those from a text property or overlay, or the overriding +maps: `overriding-terminal-local-map' and `overriding-local-map'. + +Additionally, if GLOBAL is non-nil (interactively, if called with +a prefix argument), this command includes global key bindings." + (interactive "P") + (embark-bindings-in-keymap + (make-composed-keymap + (let ((all-maps (current-active-maps t))) + (if global all-maps (remq global-map all-maps)))))) + +;;;###autoload +(defun embark-bindings-at-point () + "Explore all key bindings at point with `completing-read'. +The selected command will be executed. + +This command lists key bindings found in keymaps specified by the +text properties `keymap' or `local-map', from either buffer text +or an overlay. These are not widely used in Emacs, and when they +are used can be somewhat hard to discover. Examples of locations +that have such a keymap are links and images in `eww' buffers, +attachment links in `gnus' article buffers, and the stash line +in a `vc-dir' buffer." + (interactive) + (if-let ((keymaps (delq nil (list (get-char-property (point) 'keymap) + (get-char-property (point) 'local-map))))) + (embark-bindings-in-keymap (make-composed-keymap keymaps)) + (user-error "No key bindings found at point"))) + +;;;###autoload +(defun embark-prefix-help-command () + "Prompt for and run a command bound in the prefix used for this command. +The prefix described consists of all but the last event of the +key sequence that ran this command. This function is intended to +be used as a value for `prefix-help-command'. + +In addition to using completion to select a command, you can also +type @ and the key binding (without the prefix)." + (interactive) + (when-let ((keys (this-command-keys-vector)) + (prefix (seq-take keys (1- (length keys)))) + (keymap (key-binding prefix 'accept-default))) + (minibuffer-with-setup-hook + (lambda () + (let ((pt (- (minibuffer-prompt-end) 2))) + (overlay-put (make-overlay pt pt) 'before-string + (format " under %s" (key-description prefix))))) + (embark-bindings-in-keymap keymap)))) + +(defun embark--prompt (indicators keymap targets) + "Call the prompter with KEYMAP and INDICATORS. +The TARGETS are displayed for actions outside the minibuffer." + (mapc (lambda (i) (funcall i keymap targets)) indicators) + (condition-case nil + (minibuffer-with-setup-hook + (lambda () + ;; if the prompter opens its own minibuffer, show + ;; the indicator there too + (let ((inner-indicators (mapcar #'funcall embark-indicators))) + (mapc (lambda (i) (funcall i keymap targets)) inner-indicators) + (add-hook 'minibuffer-exit-hook + (lambda () (mapc #'funcall inner-indicators)) + nil t))) + (let ((enable-recursive-minibuffers t)) + (funcall embark-prompter keymap + (lambda (prefix) + (mapc (lambda (i) (funcall i keymap targets prefix)) + indicators))))) + (quit nil))) + +(defvar embark--run-after-command-functions nil + "Abnormal hook, used by `embark--run-after-command'.") + +(defun embark--run-after-command (fn &rest args) + "Call FN with ARGS after the current commands finishes. +If multiple functions are queued with this function during the +same command, they will be called in the order from the one +queued most recently to the one queued least recently." + ;; We don't simply add FN to `post-command-hook' because FN may recursively + ;; call this function. In that case, FN would modify `post-command-hook' + ;; from within post-command-hook, which doesn't behave properly in our case. + ;; We use our own abnormal hook and run it from PCH in a way that it is OK to + ;; modify it from within its own functions. + (unless embark--run-after-command-functions + (let (pch timer has-run) + (setq pch + (lambda () + (remove-hook 'post-command-hook pch) + (cancel-timer timer) + (unless has-run + (setq has-run t) + (while embark--run-after-command-functions + ;; The following funcall may recursively call + ;; `embark--run-after-command', modifying + ;; `embark--run-after-command-functions'. This is why this + ;; loop has to be implemented carefully. We have to pop the + ;; function off the hook before calling it. Using `dolist' + ;; on the hook would also be incorrect, because it wouldn't + ;; take modifications of this hook into account. + (with-demoted-errors "embark PCH: %S" + (condition-case nil + (funcall (pop embark--run-after-command-functions)) + (quit (message "Quit")))))))) + (add-hook 'post-command-hook pch 'append) + ;; Generally we prefer `post-command-hook' because it plays well with + ;; keyboard macros. In some cases, `post-command-hook' isn't run after + ;; exiting a recursive edit, so set up the following timer as a backup. + (setq timer (run-at-time 0 nil pch)))) + + ;; Keep the default-directory alive, since this is often overwritten, + ;; for example by Consult commands. + ;; TODO it might be necessary to add more dynamically bound variables + ;; here. What we actually want are functions `capture-dynamic-scope' + ;; and `eval-in-dynamic-scope', but this does not exist? + (let ((dir default-directory)) + (push (lambda () + (let ((default-directory dir)) + (apply fn args))) + embark--run-after-command-functions))) + +(defun embark--quit-and-run (fn &rest args) + "Quit the minibuffer and then call FN with ARGS. +If called outside the minibuffer, simply apply FN to ARGS." + (if (not (minibufferp)) + (apply fn args) + (apply #'embark--run-after-command fn args) + (embark--run-after-command #'set 'ring-bell-function ring-bell-function) + (setq ring-bell-function #'ignore) + (minibuffer-quit-recursive-edit))) + +(defun embark--run-action-hooks (hooks action target quit) + "Run HOOKS for ACTION. +The HOOKS argument must be alist. The keys t and :always are +treated specially. The :always hooks are executed always and the +t hooks are the default hooks, for when there are no +command-specific hooks for ACTION. The QUIT, ACTION and TARGET +arguments are passed to the hooks as keyword arguments." + (mapc (lambda (h) (apply h :action action :quit quit target)) + (or (alist-get action hooks) + (alist-get t hooks))) + (mapc (lambda (h) (apply h :action action :quit quit target)) + (alist-get :always hooks))) + +(defun embark--run-around-action-hooks + (action target quit &optional non-interactive) + "Run the `embark-around-action-hooks' for ACTION. +All the applicable around hooks are composed in the order they +are present in `embark-around-action-hooks'. The keys t and +:always in `embark-around-action-hooks' are treated specially. +The :always hooks are executed always (outermost) and the t hooks +are the default hooks, for when there are no command-specific +hooks for ACTION. The QUIT, ACTION and TARGET arguments are +passed to the hooks as keyword arguments. + +The optional argument NON-INTERACTIVE controls whether the action +is run with `command-execute' or with `funcall' passing the +target as argument." + (apply + (seq-reduce + (lambda (fn hook) + (lambda (&rest args) (apply hook (plist-put args :run fn)))) + (let ((hooks embark-around-action-hooks)) + (reverse + (append (or (alist-get action hooks) (alist-get t hooks)) + (alist-get :always hooks)))) + (if non-interactive + (lambda (&rest args) + (funcall (plist-get args :action) + (or (plist-get args :candidates) (plist-get args :target)))) + (lambda (&rest args) + (command-execute (plist-get args :action))))) + :action action :quit quit target)) + +(defun embark--act (action target &optional quit) + "Perform ACTION injecting the TARGET. +If called from a minibuffer with non-nil QUIT, quit the +minibuffer before executing the action." + (if (memq action '(embark-become ; these actions should run in + embark-collect ; the current buffer, not the + embark-live ; target buffer + embark-export + embark-select + embark-act-all)) + (progn + (embark--run-action-hooks embark-pre-action-hooks action target quit) + (unwind-protect (embark--run-around-action-hooks action target quit) + (embark--run-action-hooks embark-post-action-hooks + action target quit))) + (let* ((command embark--command) + (prefix prefix-arg) + (action-window (embark--target-window t)) + (directory default-directory) + (inject + (lambda () + (let ((contents (minibuffer-contents))) + (delete-minibuffer-contents) + (insert + (propertize + (substring-no-properties (plist-get target :target)) + 'embark--initial-input contents))) + (if (memq 'ivy--queue-exhibit post-command-hook) + ;; Ivy has special needs: (1) for file names + ;; ivy-immediate-done is not equivalent to + ;; exit-minibuffer, (2) it needs a chance to run + ;; its post command hook first, so use depth 10 + (add-hook 'post-command-hook 'ivy-immediate-done 10 t) + (add-hook 'post-command-hook #'exit-minibuffer nil t)) + (embark--run-action-hooks embark-target-injection-hooks + action target quit))) + (dedicate (and (derived-mode-p 'embark-collect-mode) + (not (window-dedicated-p)) + (selected-window))) + (multi (memq action embark-multitarget-actions)) + (run-action + (if (and (commandp action) (not multi)) + (lambda () + (let (final-window) + (when dedicate (set-window-dedicated-p dedicate t)) + (unwind-protect + (with-selected-window action-window + (let ((enable-recursive-minibuffers t) + (embark--command command) + (prefix-arg prefix) + ;; the next two avoid mouse dialogs + (use-dialog-box nil) + (last-nonmenu-event 13) + (default-directory directory)) + (embark--run-action-hooks embark-pre-action-hooks + action target quit) + (minibuffer-with-setup-hook inject + ;; pacify commands that use (this-command-keys) + (when (= (length (this-command-keys)) 0) + (set--this-command-keys + (if (characterp last-command-event) + (string last-command-event) + "\r"))) + (setq this-command action) + (embark--run-around-action-hooks + action target quit))) + (setq final-window (selected-window))) + (embark--run-action-hooks embark-post-action-hooks + action target quit) + (when dedicate (set-window-dedicated-p dedicate nil))) + (unless (eq final-window action-window) + (select-window final-window)))) + (let ((target + (if (and multi (null (plist-get target :candidates))) + (plist-put + target :candidates (list (plist-get target :target))) + target))) + (lambda () + (with-selected-window action-window + (embark--run-action-hooks embark-pre-action-hooks + action target quit) + (unwind-protect + (let ((current-prefix-arg prefix) + (default-directory directory)) + (embark--run-around-action-hooks + action target quit :non-interactive)) + (embark--run-action-hooks embark-post-action-hooks + action target quit)))))))) + (setq prefix-arg nil) + (if quit (embark--quit-and-run run-action) (funcall run-action))))) + +(defun embark--refine-multi-category (_type target) + "Refine `multi-category' TARGET to its actual type." + (or (let ((mc (get-text-property 0 'multi-category target))) + (cond + ;; The `cdr' of the `multi-category' property can be a buffer object. + ((and (eq (car mc) 'buffer) (buffer-live-p (cdr mc))) + (cons 'buffer (buffer-name (cdr mc)))) + ((stringp (cdr mc)) mc))) + (cons 'general target))) + +(defun embark--simplify-path (_type target) + "Simplify and '//' or '~/' in the TARGET file path." + (cons 'file (substitute-in-file-name target))) + +(defun embark--keybinding-command (_type target) + "Treat an `embark-keybinding' TARGET as a command." + (when-let ((cmd (get-text-property 0 'embark-command target))) + (cons 'command (format "%s" cmd)))) + +(defun embark--lookup-lighter-minor-mode (_type target) + "If TARGET is a lighter, look up its minor mode. + +The `describe-minor-mode' command has as completion candidates +both minor-modes and their lighters. This function replaces the +lighters by their minor modes, so actions expecting a function +work on them." + (cons 'minor-mode + (let ((symbol (intern-soft target))) + (if (and symbol (boundp symbol)) + target + (symbol-name (lookup-minor-mode-from-indicator target)))))) + +(declare-function project-current "project") +(declare-function project-root "project") + +(defun embark--project-file-full-path (_type target) + "Get full path of project file TARGET." + ;; TODO project-find-file can be called from outside all projects in + ;; which case it prompts for a project first; we don't support that + ;; case yet, since there is no current project. + (cons 'file + (if-let ((project (project-current)) + (root (project-root project))) + (expand-file-name target root) + target))) + +(defun embark--remove-package-version (_type target) + "Remove version number from a versioned package TARGET." + (cons 'package (replace-regexp-in-string "-[0-9.]+$" "" target))) + +(defun embark--targets () + "Retrieve current targets. + +An initial guess at the current targets and their types is +determined by running the functions in `embark-target-finders'. +Each function should either return nil, a pair of a type symbol +and target string or a triple of a type symbol, target string and +target bounds. + +In the minibuffer only the first target finder returning non-nil +is taken into account. When finding targets at point in other +buffers, all target finder functions are executed. + +For each target, the type is then looked up as a key in the +variable `embark-transformer-alist'. If there is a transformer +for the type, it is called with the type and target, and must +return a `cons' of the transformed type and transformed target. + +The return value of `embark--targets' is a list of plists. Each +plist concerns one target, and has keys `:type', `:target', +`:orig-type', `:orig-target' and `:bounds'." + (let (targets) + (run-hook-wrapped + 'embark-target-finders + (lambda (fun) + (dolist (found (when-let (result (funcall fun)) + (if (consp (car result)) result (list result)))) + (let* ((type (or (car found) 'general)) + (target+bounds (cdr found)) + (target (if (consp target+bounds) + (car target+bounds) + target+bounds)) + (bounds (and (consp target+bounds) (cdr target+bounds))) + (full-target + (append + (list :orig-type type :orig-target target :bounds bounds) + (if-let (transform (alist-get type embark-transformer-alist)) + (let ((trans (funcall transform type target))) + (list :type (car trans) :target (cdr trans))) + (list :type type :target target))))) + (push full-target targets))) + (and targets (minibufferp)))) + (nreverse + (cl-delete-duplicates ; keeps last duplicate, but we reverse + targets + :test (lambda (t1 t2) + (and (equal (plist-get t1 :target) (plist-get t2 :target)) + (eq (plist-get t1 :type) (plist-get t2 :type)))))))) + +(defun embark--default-action (type) + "Return default action for the given TYPE of target. +The most common case is that the target comes from minibuffer +completion, in which case the default action is the command that +opened the minibuffer in the first place. This can be overridden +by `embark-default-action-overrides'. + +For targets that do not come from minibuffer completion +\(typically some thing at point in a regular buffer) and whose +type is not listed in `embark-default-action-overrides', the +default action is given by whatever binding RET has in the action +keymap for the given type." + (or (alist-get (cons type embark--command) embark-default-action-overrides + nil nil #'equal) + (alist-get type embark-default-action-overrides) + (alist-get t embark-default-action-overrides) + embark--command + (lookup-key (embark--raw-action-keymap type) "\r"))) + +(defun embark--rotate (list k) + "Rotate LIST by K elements and return the rotated list." + (setq k (mod k (length list))) + (append (seq-drop list k) (seq-take list k))) + +(defun embark--orig-target (target) + "Convert TARGET to original target." + (plist-put + (plist-put + (copy-sequence target) + :target (plist-get target :orig-target)) + :type (plist-get target :orig-type))) + +(defun embark--quit-p (action) + "Determine whether to quit the minibuffer after ACTION. +This function consults `embark-quit-after-action' to decide +whether or not the user wishes to quit the minibuffer after +performing the ACTION, assuming this is done from a minibuffer." + (let* ((cfg embark-quit-after-action) + (quit (if (consp cfg) (alist-get action cfg (alist-get t cfg)) cfg))) + (when embark--toggle-quit (setq quit (not quit))) + (setq embark--toggle-quit nil) + quit)) + +;;;###autoload +(defun embark-act (&optional arg) + "Prompt the user for an action and perform it. +The targets of the action are chosen by `embark-target-finders'. +By default, if called from a minibuffer the target is the top +completion candidate. When called from a non-minibuffer buffer +there can multiple targets and you can cycle among them by using +`embark-cycle' (which is bound by default to the same key +binding `embark-act' is, but see `embark-cycle-key'). + +This command uses `embark-prompter' to ask the user to specify an +action, and calls it injecting the target at the first minibuffer +prompt. + +If you call this from the minibuffer, it can optionally quit the +minibuffer. The variable `embark-quit-after-action' controls +whether calling `embark-act' with nil ARG quits the minibuffer, +and if ARG is non-nil it will do the opposite. Interactively, +ARG is the prefix argument. + +If instead you call this from outside the minibuffer, the first +ARG targets are skipped over (if ARG is negative the skipping is +done by cycling backwards) and cycling starts from the following +target." + (interactive "P") + (let* ((targets (or (embark--targets) (user-error "No target found"))) + (indicators (mapcar #'funcall embark-indicators)) + (default-done nil)) + (when arg + (if (minibufferp) + (embark-toggle-quit) + (setq targets (embark--rotate targets (prefix-numeric-value arg))))) + (unwind-protect + (while + (let* ((target (car targets)) + (action + (or (embark--prompt + indicators + (let ((embark-default-action-overrides + (if default-done + `((t . ,default-done)) + embark-default-action-overrides))) + (embark--action-keymap (plist-get target :type) + (cdr targets))) + targets) + (user-error "Canceled"))) + (default-action (or default-done + (embark--default-action + (plist-get target :type))))) + (cond + ;; When acting twice in the minibuffer, do not restart + ;; `embark-act'. Otherwise the next `embark-act' will + ;; find a target in the original buffer. + ((eq action #'embark-act) + (message "Press an action key")) + ((eq action #'embark-cycle) + (setq targets (embark--rotate + targets (prefix-numeric-value prefix-arg)))) + (t + ;; if the action is non-repeatable, cleanup indicator now + (let ((repeat (embark--action-repeatable-p action))) + (unless repeat (mapc #'funcall indicators)) + (condition-case err + (embark--act + action + (if (and (eq action default-action) + (eq action embark--command) + (not (memq action embark-multitarget-actions))) + (embark--orig-target target) + target) + (embark--quit-p action)) + (user-error + (funcall (if repeat #'message #'user-error) + "%s" (cadr err)))) + (when-let (new-targets (and repeat (embark--targets))) + ;; Terminate repeated prompter on default action, + ;; when repeating. Jump to the region type if the + ;; region is active after the action, or else to the + ;; current type again. + (setq default-done #'embark-done + targets + (embark--rotate + new-targets + (or (cl-position-if + (let ((desired-type + (if (eq repeat t) + (plist-get (car targets) :type) + repeat))) + (lambda (x) + (eq (plist-get x :type) desired-type))) + new-targets) + 0))))))))) + (mapc #'funcall indicators)))) + +(defun embark--maybe-transform-candidates () + "Collect candidates and see if they all transform to the same type. +Return a plist with keys `:type', `:orig-type', `:candidates', and +`:orig-candidates'." + (pcase-let* ((`(,type . ,candidates) + (run-hook-with-args-until-success 'embark-candidate-collectors)) + (bounds (mapcar #'cdr-safe candidates))) + (setq candidates + (mapcar (lambda (x) (if (consp x) (car x) x)) candidates)) + (when (eq type 'file) + (let ((dir (embark--default-directory))) + (setq candidates + (mapcar (lambda (cand) + (abbreviate-file-name + (expand-file-name (substitute-in-file-name cand) dir))) + candidates)))) + ;; TODO more systematic approach to applying substitute-in-file-name + (append + (list :orig-type type :orig-candidates candidates :bounds bounds) + (or (when candidates + (when-let ((transformer (alist-get type embark-transformer-alist))) + (pcase-let* ((`(,new-type . ,first-cand) + (funcall transformer type (car candidates)))) + (let ((new-candidates (list first-cand))) + (when (cl-every + (lambda (cand) + (pcase-let ((`(,t-type . ,t-cand) + (funcall transformer type cand))) + (when (eq t-type new-type) + (push t-cand new-candidates) + t))) + (cdr candidates)) + (list :type new-type + :candidates (nreverse new-candidates))))))) + (list :type type :candidates candidates))))) + +;;;###autoload +(defun embark-act-all (&optional arg) + "Prompt the user for an action and perform it on each candidate. +The candidates are chosen by `embark-candidate-collectors'. By +default, if `embark-select' has been used to select some +candidates, then `embark-act-all' will act on those candidates; +otherwise, if the selection is empty and `embark-act-all' is +called from a minibuffer, then the candidates are the completion +candidates. + +This command uses `embark-prompter' to ask the user to specify an +action, and calls it injecting the target at the first minibuffer +prompt. + +If you call this from the minibuffer, it can optionally quit the +minibuffer. The variable `embark-quit-after-action' controls +whether calling `embark-act' with nil ARG quits the minibuffer, +and if ARG is non-nil it will do the opposite. Interactively, +ARG is the prefix argument." + (interactive "P") + (let* ((transformed (embark--maybe-transform-candidates)) + (type (plist-get transformed :type)) + (orig-type (plist-get transformed :orig-type)) + (candidates + (or (cl-mapcar + (lambda (cand orig-cand bounds) + (list :type type :target cand + :bounds (when bounds + (cons (copy-marker (car bounds)) + (copy-marker (cdr bounds)))) + :orig-type orig-type :orig-target orig-cand)) + (plist-get transformed :candidates) + (plist-get transformed :orig-candidates) + (plist-get transformed :bounds)) + (user-error "No candidates to act on"))) + (indicators (mapcar #'funcall embark-indicators))) + (when arg (embark-toggle-quit)) + (unwind-protect + (let* ((action + (or (embark--prompt + indicators (embark--action-keymap type nil) + (list (list :type type :multi (length candidates)))) + (user-error "Canceled"))) + (prefix prefix-arg) + (act (lambda (candidate) + (cl-letf (((symbol-function 'embark--restart) #'ignore) + ((symbol-function 'embark--confirm) #'ignore)) + (let ((prefix-arg prefix)) + (when-let ((bounds (plist-get candidate :bounds))) + (goto-char (car bounds))) + (embark--act action candidate))))) + (quit (embark--quit-p action))) + (when (and (eq action (embark--default-action type)) + (eq action embark--command)) + (setq candidates (mapcar #'embark--orig-target candidates))) + (when (or (not (or embark-confirm-act-all + (memq 'embark--confirm + (alist-get action embark-pre-action-hooks)))) + (y-or-n-p (format "Run %s on %d %ss? " + action (length candidates) type))) + (if (memq action embark-multitarget-actions) + (let ((prefix-arg prefix)) + (embark--act action transformed quit)) + (save-excursion + (if quit + (embark--quit-and-run #'mapc act candidates) + (mapc act candidates)))) + (when (and (not quit) + (memq 'embark--restart + (alist-get action embark-post-action-hooks))) + (embark--restart)))) + (dolist (cand candidates) + (when-let ((bounds (plist-get cand :bounds))) + (set-marker (car bounds) nil) ; yay, manual memory management! + (set-marker (cdr bounds) nil))) + (setq prefix-arg nil) + (mapc #'funcall indicators)))) + +(defun embark-highlight-indicator () + "Action indicator highlighting the target at point." + (let (overlay) + (lambda (&optional keymap targets _prefix) + (let ((bounds (plist-get (car targets) :bounds))) + (when (and overlay (or (not keymap) (not bounds))) + (delete-overlay overlay) + (setq overlay nil)) + (when bounds + (if overlay + (move-overlay overlay (car bounds) (cdr bounds)) + (setq overlay (make-overlay (car bounds) (cdr bounds))) + (overlay-put overlay 'category 'embark-target-overlay)) + (overlay-put overlay 'window (selected-window))))))) + +(defun embark-isearch-highlight-indicator () + "Action indicator highlighting all occurrences of the identifier at point. +This indicator only does something for targets which are +identifiers or symbols. For those it uses `isearch''s lazy +highlighting feature to highlight all occurrences of the target in +the buffer. This indicator is best used in conjunction with +`embark-highlight-indicator': by using them both you get the +target and the other occurrences of it highlighted in different +colors." + (lambda (&optional _keymap targets _prefix) + (if (and (not (minibufferp)) + (memq (plist-get (car targets) :orig-type) '(symbol identifier))) + (let ((isearch-string (plist-get (car targets) :target)) + (isearch-regexp-function #'isearch-symbol-regexp)) + (isearch-lazy-highlight-new-loop)) + (setq isearch-lazy-highlight-last-string nil) + (lazy-highlight-cleanup t)))) + +(defun embark-cycle (_arg) + "Cycle over the next ARG targets at point. +If ARG is negative, cycle backwards." + (interactive "p") + (user-error "Not meant to be called directly")) + +(defun embark-done () + "Terminate sequence of repeated actions." + (interactive)) + +;;;###autoload +(defun embark-dwim (&optional arg) + "Run the default action on the current target. +The target of the action is chosen by `embark-target-finders'. + +If the target comes from minibuffer completion, then the default +action is the command that opened the minibuffer in the first +place, unless overridden by `embark-default-action-overrides'. + +For targets that do not come from minibuffer completion +\(typically some thing at point in a regular buffer) and whose +type is not listed in `embark-default-action-overrides', the +default action is given by whatever binding RET has in the action +keymap for the target's type. + +See `embark-act' for the meaning of the prefix ARG." + (interactive "P") + (if-let ((targets (embark--targets))) + (let* ((target + (or (nth + (if (or (null arg) (minibufferp)) + 0 + (mod (prefix-numeric-value arg) (length targets))) + targets))) + (type (plist-get target :type)) + (default-action (embark--default-action type)) + (action (or (command-remapping default-action) default-action))) + (unless action + (user-error "No default action for %s targets" type)) + (when (and arg (minibufferp)) (setq embark--toggle-quit t)) + (embark--act action + (if (and (eq default-action embark--command) + (not (memq default-action + embark-multitarget-actions))) + (embark--orig-target target) + target) + (embark--quit-p action))) + (user-error "No target found"))) + +(defun embark--become-keymap () + "Return keymap of commands to become for current command." + (let ((map (make-composed-keymap + (cl-loop for keymap-name in embark-become-keymaps + for keymap = (symbol-value keymap-name) + when (where-is-internal embark--command (list keymap)) + collect keymap)))) + (when embark-help-key + (keymap-set map embark-help-key #'embark-keymap-help)) + map)) + +;;;###autoload +(defun embark-become (&optional full) + "Make current command become a different command. +Take the current minibuffer input as initial input for new +command. The new command can be run normally using key bindings or +\\[execute-extended-command], but if the current command is found in a keymap in +`embark-become-keymaps', that keymap is activated to provide +convenient access to the other commands in it. + +If FULL is non-nil (interactively, if called with a prefix +argument), the entire minibuffer contents are used as the initial +input of the new command. By default only the part of the +minibuffer contents between the current completion boundaries is +taken. What this means is fairly technical, but (1) usually +there is no difference: the completion boundaries include the +entire minibuffer contents, and (2) the most common case where +these notions differ is file completion, in which case the +completion boundaries single out the path component containing +point." + (interactive "P") + (unless (minibufferp) + (user-error "Not in a minibuffer")) + (let* ((target (embark--display-string ; remove invisible portions + (if full + (minibuffer-contents) + (pcase-let ((`(,beg . ,end) (embark--boundaries))) + (substring (minibuffer-contents) beg + (+ end (embark--minibuffer-point))))))) + (keymap (embark--become-keymap)) + (targets `((:type embark-become :target ,target))) + (indicators (mapcar #'funcall embark-indicators)) + (become (unwind-protect + (embark--prompt indicators keymap targets) + (mapc #'funcall indicators)))) + (unless become + (user-error "Canceled")) + (embark--become-command become target))) + +(defun embark--become-command (command input) + "Quit current minibuffer and start COMMAND with INPUT." + (embark--quit-and-run + (lambda () + (minibuffer-with-setup-hook + (lambda () + (delete-minibuffer-contents) + (insert input)) + (let ((use-dialog-box nil) ;; avoid mouse dialogs + (last-nonmenu-event 13)) + (setq this-command command) + (command-execute command)))))) + +;;; Embark collect + +(defgroup embark-collect nil + "Buffers for acting on collected Embark targets." + :group 'embark) + +(defcustom embark-candidate-collectors + '(embark-selected-candidates + embark-minibuffer-candidates + embark-completion-list-candidates + embark-dired-candidates + embark-ibuffer-candidates + embark-embark-collect-candidates + embark-custom-candidates) + "List of functions that collect all candidates in a given context. +These are used to fill an Embark Collect buffer. Each function +should return either nil (to indicate it found no candidates) or +a list whose first element is a symbol indicating the type of +candidates and whose `cdr' is the list of candidates, each of +which should be either a string or a dotted list of the +form (TARGET START . END), where START and END are the buffer +positions bounding the TARGET string." + :type 'hook) + +(defcustom embark-exporters-alist + '((buffer . embark-export-ibuffer) + (file . embark-export-dired) + (package . embark-export-list-packages) + (bookmark . embark-export-bookmarks) + (variable . embark-export-customize-variable) + (face . embark-export-customize-face) + (symbol . embark-export-apropos) + (minor-mode . embark-export-apropos) + (function . embark-export-apropos) + (command . embark-export-apropos) + (t . embark-collect)) + "Alist associating completion types to export functions. +Each function should take a list of strings which are candidates +for actions and make a buffer appropriate to manage them. For +example, the default is to make a Dired buffer for files, and an +ibuffer for buffers. + +The key t is also allowed in the alist, and the corresponding +value indicates the default function to use for other types. The +default is `embark-collect'" + :type '(alist :key-type symbol :value-type function)) + +(defcustom embark-after-export-hook nil + "Hook run after `embark-export' in the newly created buffer." + :type 'hook) + +(defface embark-collect-candidate '((t :inherit default)) + "Face for candidates in Embark Collect buffers.") + +(defface embark-collect-group-title + '((t :inherit shadow :slant italic)) + "Face for group titles in Embark Collect buffers.") + +(defface embark-collect-group-separator + '((t :inherit shadow :strike-through t :italic t)) + "Face for group titles in Embark Collect buffers.") + +(defcustom embark-collect-group-format + (concat + (propertize " " 'face 'embark-collect-group-separator) + (propertize " %s " 'face 'embark-collect-group-title) + (propertize " " 'face 'completions-group-separator + 'display '(space :align-to right))) + "Format string used for the group title in Embark Collect buffers." + :type 'string) + +(defface embark-collect-annotation '((t :inherit completions-annotations)) + "Face for annotations in Embark Collect. +This is only used for annotation that are not already fontified.") + +(defvar-local embark--rerun-function nil + "Function to rerun the collect or export that made the current buffer.") + +(autoload 'package-delete "package") +(declare-function package--from-builtin "package") +(declare-function package-desc-extras "package") +(declare-function package-desc-name "package") +(defvar package--builtins) +(defvar package-alist) +(defvar package-archive-contents) +(defvar package--initialized) + +(defun embark--package-desc (pkg) + "Return the description structure for package PKG." + (or ; found this in `describe-package-1' + (car (alist-get pkg package-alist)) + (if-let ((built-in (assq pkg package--builtins))) + (package--from-builtin built-in) + (car (alist-get pkg package-archive-contents))))) + +(defun embark-minibuffer-candidates () + "Return all current completion candidates from the minibuffer." + (when (minibufferp) + (let* ((all (completion-all-completions + (minibuffer-contents) + minibuffer-completion-table + minibuffer-completion-predicate + (embark--minibuffer-point))) + (last (last all))) + (when last (setcdr last nil)) + (cons + (completion-metadata-get (embark--metadata) 'category) + all)))) + +(defun embark-sorted-minibuffer-candidates () + "Return a sorted list of current minibuffer completion candidates. +This using the same sort order that `icomplete' and +`minibuffer-force-complete' use. The intended usage is that you +replace `embark-minibuffer-candidates' with this function in the +list `embark-candidate-collectors'." + (when (minibufferp) + (cons + (completion-metadata-get (embark--metadata) 'category) + (nconc (cl-copy-list (completion-all-sorted-completions)) nil)))) + +(declare-function dired-get-marked-files "dired") +(declare-function dired-move-to-filename "dired") +(declare-function dired-move-to-end-of-filename "dired") + +(defun embark-dired-candidates () + "Return marked or all files shown in Dired buffer. +If any buffer is marked, return marked buffers; otherwise, return +all buffers." + (when (derived-mode-p 'dired-mode) + (cons 'file + (or + ;; dired-get-marked-files returns the file on the current + ;; line if no marked files are found; and when the fourth + ;; argument is non-nil, the "no marked files" case is + ;; distinguished from the "single marked file" case by + ;; returning (list t marked-file) in the latter + (let ((marked (dired-get-marked-files t nil nil t))) + (and (cdr marked) + (if (eq (car marked) t) (cdr marked) marked))) + (save-excursion + (goto-char (point-min)) + (let (files) + (while (not (eobp)) + (when-let (file (dired-get-filename t t)) + (push `(,file + ,(progn (dired-move-to-filename) (point)) + . ,(progn (dired-move-to-end-of-filename t) (point))) + files)) + (forward-line)) + (nreverse files))))))) + +(autoload 'ibuffer-marked-buffer-names "ibuffer") +(declare-function ibuffer-map-lines-nomodify "ibuffer") + +(defun embark-ibuffer-candidates () + "Return marked or all buffers listed in ibuffer buffer. +If any buffer is marked, return marked buffers; otherwise, return +all buffers." + (when (derived-mode-p 'ibuffer-mode) + (cons 'buffer + (or (ibuffer-marked-buffer-names) + (let (buffers) + (ibuffer-map-lines-nomodify + (lambda (buffer _mark) + (push (buffer-name buffer) buffers))) + (nreverse buffers)))))) + +(defun embark-embark-collect-candidates () + "Return candidates in Embark Collect buffer. +This makes `embark-export' work in Embark Collect buffers." + (when (derived-mode-p 'embark-collect-mode) + (cons embark--type + (save-excursion + (goto-char (point-min)) + (let (all) + (when-let ((cand (embark-target-collect-candidate))) + (push (cdr cand) all)) + (while (forward-button 1 nil nil t) + (when-let ((cand (embark-target-collect-candidate))) + (push (cdr cand) all))) + (nreverse all)))))) + +(defun embark-completion-list-candidates () + "Return all candidates in a completions buffer." + (when (derived-mode-p 'completion-list-mode) + (cons + embark--type + (save-excursion + (goto-char (point-min)) + (next-completion 1) + (let (all) + (while (not (eobp)) + (push (cdr (embark-target-completion-list-candidate)) all) + (next-completion 1)) + (nreverse all)))))) + +(defun embark-custom-candidates () + "Return all variables and faces listed in this `Custom-mode' buffer." + (when (derived-mode-p 'Custom-mode) + (cons 'symbol ; gets refined to variable or face when acted upon + (save-excursion + (goto-char (point-min)) + (let (symbols) + (while (not (eobp)) + (when-let (widget (widget-at (point))) + (when (eq (car widget) 'custom-visibility) + (push + `(,(symbol-name + (plist-get (cdr (plist-get (cdr widget) :parent)) + :value)) + ,(point) + . ,(progn + (re-search-forward ":" (line-end-position) 'noerror) + (point))) + symbols))) + (forward-line)) + (nreverse symbols)))))) + + +(defun embark-collect--target () + "Return the Embark Collect candidate at point. +This takes into account `embark-transformer-alist'." + (let ((embark-target-finders '(embark-target-collect-candidate))) + (car (embark--targets)))) + +(defun embark--action-command (action) + "Turn an ACTION into a command to perform the action. +Returns the name of the command." + (let ((name (intern (format "embark-action--%s" + (embark--command-name action))))) + (fset name (lambda (arg) + (interactive "P") + (when-let (target (embark-collect--target)) + (let ((prefix-arg arg)) + (embark--act action target))))) + (when (fboundp action) + (put name 'function-documentation (documentation action))) + name)) + +(defun embark--all-bindings (keymap &optional nested) + "Return an alist of all bindings in KEYMAP. +If NESTED is non-nil subkeymaps are not flattened." + (let (bindings maps) + (map-keymap + (lambda (key def) + (cond + ((keymapp def) + (if nested + (push (cons (vector key) def) maps) + (dolist (bind (embark--all-bindings def)) + (push (cons (vconcat (vector key) (car bind)) (cdr bind)) + maps)))) + (def (push (cons (vector key) def) bindings)))) + (keymap-canonicalize keymap)) + (nconc (nreverse bindings) (nreverse maps)))) + +(defun embark-collect--direct-action-map (type) + "Return a direct action keymap for targets of given TYPE." + (let* ((actions (embark--action-keymap type nil)) + (map (make-sparse-keymap))) + (set-keymap-parent map button-map) + (pcase-dolist (`(,key . ,cmd) (embark--all-bindings actions)) + (unless (or (equal key [13]) + (memq cmd '(digit-argument negative-argument))) + (define-key map key (if (eq cmd 'embark-keymap-help) + #'embark-bindings-at-point + (embark--action-command cmd))))) + map)) + +(define-minor-mode embark-collect-direct-action-minor-mode + "Bind type-specific actions directly (without need for `embark-act')." + :init-value nil + :lighter " Act" + (unless (derived-mode-p 'embark-collect-mode) + (user-error "Not in an Embark Collect buffer")) + (save-excursion + (goto-char (point-min)) + (let ((inhibit-read-only t) maps) + (while (progn + (when (tabulated-list-get-id) + (put-text-property + (point) (button-end (point)) 'keymap + (if embark-collect-direct-action-minor-mode + (when-let ((target (embark-collect--target)) + (type (plist-get target :type))) + (or (alist-get type maps) + (setf (alist-get type maps) + (embark-collect--direct-action-map type))))))) + (forward-button 1 nil nil t)))))) + +(define-button-type 'embark-collect-entry + 'face 'embark-collect-candidate + 'action 'embark-collect-choose) + +(declare-function outline-toggle-children "outline") +(define-button-type 'embark-collect-group + 'face 'embark-collect-group-title + 'action (lambda (_) (outline-toggle-children))) + +(defun embark--boundaries () + "Get current minibuffer completion boundaries." + (let ((contents (minibuffer-contents)) + (pt (embark--minibuffer-point))) + (completion-boundaries + (substring contents 0 pt) + minibuffer-completion-table + minibuffer-completion-predicate + (substring contents pt)))) + +(defun embark-collect-choose (entry) + "Run default action on Embark Collect ENTRY." + (pcase-let ((`(,type ,text ,start . ,end) + (save-excursion + (goto-char entry) + (embark-target-collect-candidate)))) + (embark--act (embark--default-action type) + (list :target text + :type type + :bounds (cons start end))))) + +(defvar-keymap embark-collect-mode-map + :doc "Keymap for Embark collect mode." + :parent tabulated-list-mode-map + "a" #'embark-act + "A" #'embark-act-all + "M-a" #'embark-collect-direct-action-minor-mode + "E" #'embark-export + "s" #'isearch-forward + "n" #'forward-button + "p" #'backward-button + "}" 'outline-next-heading + "{" 'outline-previous-heading + "<remap> <forward-paragraph>" 'outline-next-heading + "<remap> <backward-paragraph>" 'outline-previous-heading + "<remap> <revert-buffer>" #'embark-rerun-collect-or-export) + +(defconst embark-collect--outline-string (string #x210000) + "Special string used for outline headings in Embark Collect buffers. +Chosen to be extremely unlikely to appear in a candidate.") + +(define-derived-mode embark-collect-mode tabulated-list-mode "Embark Collect" + "List of candidates to be acted on. +The command `embark-act' is bound `embark-collect-mode-map', but +you might prefer to change the key binding to match your other +key binding for it. Or alternatively you might want to enable the +embark collect direct action minor mode by adding the function +`embark-collect-direct-action-minor-mode' to +`embark-collect-mode-hook'. + +Reverting an Embark Collect buffer has slightly unusual behavior +if the buffer was obtained by running `embark-collect' from +within a minibuffer completion session. In that case reverting +just restarts the completion session, that is, the command that +opened the minibuffer is run again and the minibuffer contents +restored. You can then interact normally with the command, +perhaps editing the minibuffer contents, and, if you wish, you +can rerun `embark-collect' to get an updated buffer." + :interactive nil :abbrev-table nil :syntax-table nil) + +(defun embark-collect--metadatum (type metadatum) + "Get METADATUM for current buffer's candidates. +For non-minibuffers, assume candidates are of given TYPE." + (if (minibufferp) + (or (completion-metadata-get (embark--metadata) metadatum) + (plist-get completion-extra-properties + (intern (format ":%s" metadatum)))) + ;; otherwise fake some metadata for Marginalia users's benefit + (completion-metadata-get `((category . ,type)) metadatum))) + +(defun embark-collect--affixator (type) + "Get affixation function for current buffer's candidates. +For non-minibuffers, assume candidates are of given TYPE." + (or (embark-collect--metadatum type 'affixation-function) + (let ((annotator + (or (embark-collect--metadatum type 'annotation-function) + (lambda (_) "")))) + (lambda (candidates) + (mapcar (lambda (c) + (if-let (a (funcall annotator c)) (list c "" a) c)) + candidates))))) + +(defun embark--display-string (str) + ;; Note: Keep in sync with vertico--display-string + "Return display STR without display and invisible properties." + (let ((end (length str)) (pos 0) chunks) + (while (< pos end) + (let ((nextd (next-single-property-change pos 'display str end)) + (disp (get-text-property pos 'display str))) + (if (stringp disp) + (let ((face (get-text-property pos 'face str))) + (when face + (add-face-text-property + 0 (length disp) face t (setq disp (concat disp)))) + (setq pos nextd chunks (cons disp chunks))) + (while (< pos nextd) + (let ((nexti + (next-single-property-change pos 'invisible str nextd))) + (unless (or (get-text-property pos 'invisible str) + (and (= pos 0) (= nexti end))) ;; full=>no allocation + (push (substring str pos nexti) chunks)) + (setq pos nexti)))))) + (if chunks (apply #'concat (nreverse chunks)) str))) + +(defconst embark--hline + (propertize + (concat "\n" (propertize + " " 'display '(space :align-to right) + 'face '(:inherit completions-group-separator :height 0.01) + 'cursor-intangible t 'intangible t))) + "Horizontal line used to separate multiline collect entries.") + +(defun embark-collect--format-entries (candidates grouper) + "Format CANDIDATES for `tabulated-list-mode' grouped by GROUPER. +The GROUPER is either nil or a function like the `group-function' +completion metadatum, that is, a function of two arguments, the +first of which is a candidate and the second controls what is +computed: if nil, the title of the group the candidate belongs +to, and if non-nil, a rewriting of the candidate (useful to +simplify the candidate so it doesn't repeat the group title, for +example)." + (let ((max-width 0) + (transform + (if grouper (lambda (cand) (funcall grouper cand t)) #'identity))) + (setq + tabulated-list-entries + (mapcan + (lambda (group) + (let ((multiline (seq-some (lambda (x) (string-match-p "\n" (car x))) + candidates))) + (cons + `(nil [(,(concat (propertize embark-collect--outline-string + 'invisible t) + (format embark-collect-group-format (car group))) + type embark-collect-group) + ("" skip t)]) + (mapcar + (pcase-lambda (`(,cand ,prefix ,annotation)) + (let* ((display (embark--display-string (funcall transform cand))) + (length (length annotation)) + (faces (text-property-not-all + 0 length 'face nil annotation))) + (setq max-width (max max-width (+ (string-width prefix) + (string-width display)))) + (when faces + (add-face-text-property 0 length 'default t annotation)) + `(,cand + [(,(propertize + (if multiline (concat display embark--hline) display) + 'line-prefix prefix) + type embark-collect-entry) + (,annotation + skip t + ,@(unless faces + '(face embark-collect-annotation)))]))) + (cdr group))))) + (if grouper + (seq-group-by (lambda (item) (funcall grouper (car item) nil)) + candidates) + (list (cons "" candidates))))) + (if (null grouper) + (pop tabulated-list-entries) + (setq-local outline-regexp embark-collect--outline-string) + (outline-minor-mode)) + (setq tabulated-list-format + `[("Candidate" ,max-width t) ("Annotation" 0 t)]))) + +(defun embark-collect--update-candidates (buffer) + "Update candidates for Embark Collect BUFFER." + (let* ((transformed (embark--maybe-transform-candidates)) + (type (plist-get transformed :orig-type)) ; we need the originals for + (candidates (plist-get transformed :orig-candidates)) ; default action + (bounds (plist-get transformed :bounds)) + (affixator (embark-collect--affixator type)) + (grouper (embark-collect--metadatum type 'group-function))) + (when (eq type 'file) + (let ((dir (buffer-local-value 'default-directory buffer))) + (setq candidates + (mapcar (lambda (cand) + (let ((rel (file-relative-name cand dir))) + (if (string-prefix-p "../" rel) cand rel))) + candidates)))) + (if (seq-some #'identity bounds) + (cl-loop for cand in candidates and (start . _end) in bounds + when start + do (add-text-properties + 0 1 `(embark--location ,(copy-marker start)) cand))) + (setq candidates (funcall affixator candidates)) + (with-current-buffer buffer + (setq embark--type type) + (unless embark--command + (setq embark--command #'embark--goto)) + (embark-collect--format-entries candidates grouper)) + candidates)) + +(defun embark--goto (target) + "Jump to the original location of TARGET. +This function is used as a default action in Embark Collect +buffers when the candidates were a selection from a regular +buffer." + ;; TODO: ensure the location jumped to is visible + ;; TODO: remove duplication with embark-org-goto-heading + (when-let ((marker (get-text-property 0 'embark--location target))) + (pop-to-buffer (marker-buffer marker)) + (widen) + (goto-char marker) + (pulse-momentary-highlight-one-line))) + +(defun embark--collect (buffer-name) + "Create an Embark Collect buffer named BUFFER-NAME. + +The function `generate-new-buffer-name' is used to ensure the +buffer has a unique name." + (let ((buffer (generate-new-buffer buffer-name)) + (rerun (embark--rerun-function #'embark-collect))) + (with-current-buffer buffer + ;; we'll run the mode hooks once the buffer is displayed, so + ;; the hooks can make use of the window + (delay-mode-hooks (embark-collect-mode))) + + (embark--cache-info buffer) + (unless (embark-collect--update-candidates buffer) + (user-error "No candidates to collect")) + + (with-current-buffer buffer + (setq tabulated-list-use-header-line nil ; default to no header + header-line-format nil + tabulated-list--header-string nil) + (setq embark--rerun-function rerun)) + + (let ((window (display-buffer buffer))) + (with-selected-window window + (run-mode-hooks) + (tabulated-list-revert)) + (set-window-dedicated-p window t) + buffer))) + +(defun embark--descriptive-buffer-name (type) + "Return a descriptive name for an Embark collect or export buffer. +TYPE should be either `collect' or `export'." + (format "*Embark %s: %s*" + (capitalize (symbol-name type)) + (if (minibufferp) + (format "%s - %s" embark--command + (minibuffer-contents-no-properties)) + (buffer-name)))) + +;;;###autoload +(defun embark-collect () + "Create an Embark Collect buffer. + +To control the display, add an entry to `display-buffer-alist' +with key \"Embark Collect\". + +In Embark Collect buffers `revert-buffer' is remapped to +`embark-rerun-collect-or-export', which has slightly unusual +behavior if the buffer was obtained by running `embark-collect' +from within a minibuffer completion session. In that case +rerunning just restarts the completion session, that is, the +command that opened the minibuffer is run again and the +minibuffer contents restored. You can then interact normally with +the command, perhaps editing the minibuffer contents, and, if you +wish, you can rerun `embark-collect' to get an updated buffer." + (interactive) + (let ((buffer (embark--collect (embark--descriptive-buffer-name 'collect)))) + (when (minibufferp) + (embark--run-after-command #'pop-to-buffer buffer) + (embark--quit-and-run #'message nil)))) + +;;;###autoload +(defun embark-live () + "Create a live-updating Embark Collect buffer. + +To control the display, add an entry to `display-buffer-alist' +with key \"Embark Live\"." + (interactive) + (let ((live-buffer (embark--collect + (format "*Embark Live: %s*" + (if (minibufferp) + (format "M-x %s" embark--command) + (buffer-name))))) + (run-collect (make-symbol "run-collect")) + (stop-collect (make-symbol "stop-collect")) + timer) + (setf (symbol-function stop-collect) + (lambda () + (remove-hook 'change-major-mode-hook stop-collect t) + (remove-hook 'after-change-functions run-collect t))) + (setf (symbol-function run-collect) + (lambda (_1 _2 _3) + (unless timer + (setq timer + (run-with-idle-timer + 0.05 nil + (lambda () + (if (not (buffer-live-p live-buffer)) + (funcall stop-collect) + (embark-collect--update-candidates live-buffer) + (with-current-buffer live-buffer + ;; TODO figure out why I can't restore point + (tabulated-list-print t t)) + (setq timer nil)))))))) + (add-hook 'after-change-functions run-collect nil t) + (when (minibufferp) + (add-hook 'change-major-mode-hook stop-collect nil t)))) + +(defun embark--rerun-function (kind) + "Return a rerun function for an export or collect buffer in this context. +The parameter KIND should be either `embark-export' or `embark-collect'." + (let ((buffer (or embark--target-buffer (embark--target-buffer))) + (command embark--command)) + (cl-flet ((rerunner (action) + (lambda (&rest _) + (quit-window 'kill-buffer) + (with-current-buffer + (if (buffer-live-p buffer) buffer (current-buffer)) + (let ((embark--command command)) + (funcall action)))))) + (if (minibufferp) + (rerunner + (let ((input (minibuffer-contents-no-properties))) + (lambda () + (minibuffer-with-setup-hook + (lambda () + (delete-minibuffer-contents) + (insert input)) + (setq this-command embark--command) + (command-execute embark--command))))) + (rerunner kind))))) + +(defun embark-rerun-collect-or-export () + "Rerun the `embark-collect' or `embark-export' that created this buffer." + (interactive) + (if embark--rerun-function + (funcall embark--rerun-function) + (user-error "No function to rerun collect or export found"))) + +;;;###autoload +(defun embark-export () + "Create a type-specific buffer to manage current candidates. +The variable `embark-exporters-alist' controls how to make the +buffer for each type of completion. + +In Embark Export buffers `revert-buffer' is remapped to +`embark-rerun-collect-or-export', which has slightly unusual +behavior if the buffer was obtained by running `embark-export' +from within a minibuffer completion session. In that case +reverting just restarts the completion session, that is, the +command that opened the minibuffer is run again and the +minibuffer contents restored. You can then interact normally +with the command, perhaps editing the minibuffer contents, and, +if you wish, you can rerun `embark-export' to get an updated +buffer." + (interactive) + (let* ((transformed (embark--maybe-transform-candidates)) + (candidates (or (plist-get transformed :candidates) + (user-error "No candidates for export"))) + (type (plist-get transformed :type))) + (let ((exporter (or (alist-get type embark-exporters-alist) + (alist-get t embark-exporters-alist)))) + (if (eq exporter 'embark-collect) + (embark-collect) + (let* ((after embark-after-export-hook) + (cmd embark--command) + (name (embark--descriptive-buffer-name 'export)) + (rerun (embark--rerun-function #'embark-export)) + (buffer (save-excursion + (funcall exporter candidates) + (rename-buffer name t) + (current-buffer)))) + (embark--quit-and-run + (lambda () + (pop-to-buffer buffer) + (setq embark--rerun-function rerun) + (use-local-map + (make-composed-keymap + '(keymap + (remap keymap + (revert-buffer . embark-rerun-collect-or-export))) + (current-local-map))) + (let ((embark-after-export-hook after) + (embark--command cmd)) + (run-hooks 'embark-after-export-hook))))))))) + +(defmacro embark--export-rename (buffer title &rest body) + "Run BODY and rename BUFFER to Embark export buffer with TITLE." + (declare (indent 2)) + (let ((saved (make-symbol "saved"))) + `(let ((,saved (embark-rename-buffer + ,buffer " *Embark Saved*" t))) + ,@body + (set-buffer (embark-rename-buffer + ,buffer ,(format "*Embark Export %s*" title) t)) + (when ,saved (embark-rename-buffer ,saved ,buffer))))) + +(defun embark--export-customize (items type pred) + "Create a customization buffer listing ITEMS. +TYPE is the items type. +PRED is a predicate function used to filter the items." + (custom-buffer-create + (cl-loop for item in items + for sym = (intern-soft item) + when (and sym (funcall pred sym)) collect `(,sym ,type)))) + +(autoload 'apropos-parse-pattern "apropos") +(autoload 'apropos-symbols-internal "apropos") +(defun embark-export-apropos (symbols) + "Create apropos buffer listing SYMBOLS." + (embark--export-rename "*Apropos*" "Apropos" + (apropos-parse-pattern "") ;; Initialize apropos pattern + ;; HACK: Ensure that order of exported symbols is kept. + (cl-letf (((symbol-function #'sort) (lambda (list _pred) (nreverse list)))) + (apropos-symbols-internal + (delq nil (mapcar #'intern-soft symbols)) + (bound-and-true-p apropos-do-all))))) + +(defun embark-export-customize-face (faces) + "Create a customization buffer listing FACES." + (embark--export-customize faces 'custom-face #'facep)) + +(defun embark-export-customize-variable (variables) + "Create a customization buffer listing VARIABLES." + ;; The widget library serializes/deserializes the values. We advise + ;; the serialization in order to avoid errors for nonserializable + ;; variables. + (cl-letf* ((ht (make-hash-table :test #'equal)) + (orig-read (symbol-function #'read)) + (orig-write (symbol-function 'widget-sexp-value-to-internal)) + ((symbol-function #'read) + (lambda (&optional str) + (condition-case nil + (funcall orig-read str) + (error (gethash str ht))))) + ((symbol-function 'widget-sexp-value-to-internal) + (lambda (widget val) + (let ((str (funcall orig-write widget val))) + (puthash str val ht) + str)))) + (embark--export-customize variables 'custom-variable #'boundp))) + +(defun embark-export-ibuffer (buffers) + "Create an ibuffer buffer listing BUFFERS." + (ibuffer t "*Embark Export Ibuffer*" + `((predicate . (member (buffer-name) ',buffers))))) + +(autoload 'dired-check-switches "dired") +(declare-function dired-unadvertise "dired") +(defvar dired-directory) + +(defun embark-export-dired (files) + "Create a Dired buffer listing FILES." + (setq files (mapcar #'directory-file-name + (cl-remove-if-not #'file-exists-p files))) + (when (dired-check-switches dired-listing-switches "A" "almost-all") + (setq files (cl-remove-if + (lambda (path) + (let ((file (file-name-nondirectory path))) + (or (string= file ".") (string= file "..")))) + files))) + (cl-letf* ((dir (or (file-name-directory (try-completion "" files)) "")) + ;; Prevent reusing existing Dired buffer. + ((symbol-function 'dired-find-buffer-nocreate) #'ignore) + (buf (dired-noselect + (cons (expand-file-name dir) + (mapcar (lambda (file) (string-remove-prefix dir file)) + files))))) + (with-current-buffer buf + ;; Unadvertise to prevent the new buffer from being reused. + (dired-unadvertise default-directory) + (rename-buffer (format "*Embark Export Dired %s*" default-directory))) + (pop-to-buffer buf))) + +(autoload 'package-menu-mode "package") +(autoload 'package-menu--generate "package") + +(defun embark-export-list-packages (packages) + "Create a package menu mode buffer listing PACKAGES." + (let ((buf (generate-new-buffer "*Embark Export Packages*"))) + (with-current-buffer buf + (package-menu-mode) + (package-menu--generate nil (mapcar #'intern packages))) + (pop-to-buffer buf))) + +(defvar bookmark-alist) + +(defun embark-export-bookmarks (bookmarks) + "Create a `bookmark-bmenu-mode' buffer listing BOOKMARKS." + (embark--export-rename "*Bookmark List*" "Bookmarks" + (let ((bookmark-alist + (cl-remove-if-not + (lambda (bmark) + (member (car bmark) bookmarks)) + bookmark-alist))) + (bookmark-bmenu-list)))) + +;;; Multiple target selection + +(defface embark-selected '((t (:inherit match))) + "Face for selected candidates.") + +(defcustom embark-selection-indicator + #(" Embark:%s " 1 12 (face (embark-selected bold))) + "Mode line indicator used for selected candidates." + :type '(choice string (const nil))) + +(defvar-local embark--selection nil + "Buffer local list of selected targets. +Add or remove elements to this list using the `embark-select' +action.") + +(defun embark--selection-indicator () + "Mode line indicator showing number of selected items." + (when-let ((sel + (buffer-local-value + 'embark--selection + (or (when-let ((win (active-minibuffer-window))) + (window-buffer win)) + (current-buffer))))) + (format embark-selection-indicator (length sel)))) + +(cl-defun embark--select + (&key orig-target orig-type bounds &allow-other-keys) + "Add or remove ORIG-TARGET of given ORIG-TYPE to the selection. +If BOUNDS are given, also highlight the target when selecting it." + (cl-flet ((multi-type (x) (car (get-text-property 0 'multi-category x)))) + (if-let* ((existing (seq-find + (pcase-lambda (`(,cand . ,ov)) + (and + (equal cand orig-target) + (if (and bounds ov) + (and (= (car bounds) (overlay-start ov)) + (= (cdr bounds) (overlay-end ov))) + (let ((cand-type (multi-type cand))) + (or (eq cand-type orig-type) + (eq cand-type (multi-type orig-target))))))) + embark--selection))) + (progn + (when (cdr existing) (delete-overlay (cdr existing))) + (setq embark--selection (delq existing embark--selection))) + (let ((target (copy-sequence orig-target)) overlay) + (when bounds + (setq overlay (make-overlay (car bounds) (cdr bounds))) + (overlay-put overlay 'category 'embark-selected-overlay)) + (add-text-properties 0 (length orig-target) + `(multi-category ,(cons orig-type orig-target)) + target) + (push (cons target overlay) embark--selection)))) + (when embark-selection-indicator + (add-to-list 'mode-line-misc-info '(:eval (embark--selection-indicator))) + (force-mode-line-update t))) + +;;;###autoload +(defun embark-select () + "Add or remove the target from the current buffer's selection. +You can act on all selected targets at once with `embark-act-all'. +When called from outside `embark-act' this command will select +the first target at point." + (interactive) + (if-let ((target (car (embark--targets)))) + (apply #'embark--select target) + (user-error "No target to select"))) + +(defun embark-selected-candidates () + "Return currently selected candidates in the buffer." + (when embark--selection + (cl-flet ((unwrap (x) (get-text-property 0 'multi-category x))) + (let* ((first-type (car (unwrap (caar embark--selection)))) + (same (cl-every (lambda (item) + (eq (car (unwrap (car item))) first-type)) + embark--selection)) + (extract (if same + (pcase-lambda (`(,cand . ,overlay)) + (cons (cdr (unwrap cand)) overlay)) + #'identity))) + (cons + (if same first-type 'multi-category) + (nreverse + (mapcar + (lambda (item) + (pcase-let ((`(,cand . ,ov) (funcall extract item))) + (if ov `(,cand ,(overlay-start ov) . ,(overlay-end ov)) cand))) + embark--selection))))))) + +;;; Integration with external packages, mostly completion UIs + +;; marginalia + +;; Ensure that the Marginalia cache is reset, such that +;; `embark-toggle-variable-value' updates the display (See #540). +(with-eval-after-load 'marginalia + (push 'marginalia--cache-reset (alist-get :always embark-post-action-hooks))) + +;; vertico + +(declare-function vertico--candidate "ext:vertico") +(declare-function vertico--update "ext:vertico") +(defvar vertico--input) +(defvar vertico--candidates) +(defvar vertico--base) + +(defun embark--vertico-selected () + "Target the currently selected item in Vertico. +Return the category metadatum as the type of the target." + (when vertico--input + ;; Force candidate computation, if candidates are not yet available. + (vertico--update) + (cons (completion-metadata-get (embark--metadata) 'category) + (vertico--candidate)))) + +(defun embark--vertico-candidates () + "Collect the current Vertico candidates. +Return the category metadatum as the type of the candidates." + (when vertico--input + ;; Force candidate computation, if candidates are not yet available. + (vertico--update) + (cons (completion-metadata-get (embark--metadata) 'category) + vertico--candidates))) + +(defun embark--vertico-indicator () + "Embark indicator highlighting the current Vertico candidate." + (let ((fr face-remapping-alist)) + (lambda (&optional keymap _targets _prefix) + (when vertico--input + (setq-local face-remapping-alist + (if keymap + (cons '(vertico-current . embark-target) fr) + fr)))))) + +(with-eval-after-load 'vertico + (cl-defmethod vertico--format-candidate + :around (cand prefix suffix index start &context (embark--selection cons)) + (when (cl-find (concat vertico--base (nth index vertico--candidates)) + embark--selection + :test #'equal :key #'car) + (setq cand (copy-sequence cand)) + (add-face-text-property 0 (length cand) 'embark-selected t cand)) + (cl-call-next-method cand prefix suffix index start)) + (add-hook 'embark-indicators #'embark--vertico-indicator) + (add-hook 'embark-target-finders #'embark--vertico-selected) + (add-hook 'embark-candidate-collectors #'embark--vertico-candidates) + (remove-hook 'embark-candidate-collectors #'embark-selected-candidates) + (add-hook 'embark-candidate-collectors #'embark-selected-candidates)) + +;; ivy + +(declare-function ivy--expand-file-name "ext:ivy") +(declare-function ivy-state-current "ext:ivy") +(defvar ivy-text) +(defvar ivy-last) +(defvar ivy--old-cands) ; this stores the current candidates :) +(defvar ivy--length) + +(defun embark--ivy-selected () + "Target the currently selected item in Ivy. +Return the category metadatum as the type of the target." + ;; my favorite way of detecting Ivy + (when (memq 'ivy--queue-exhibit post-command-hook) + (cons + (completion-metadata-get (embark--metadata) 'category) + (ivy--expand-file-name + (if (and (> ivy--length 0) + (stringp (ivy-state-current ivy-last))) + (ivy-state-current ivy-last) + ivy-text))))) + +(defun embark--ivy-candidates () + "Return all current Ivy candidates." + ;; my favorite way of detecting Ivy + (when (memq 'ivy--queue-exhibit post-command-hook) + (cons + ;; swiper-isearch uses swiper-isearch-function as a completion + ;; table, but it doesn't understand metadata queries + (ignore-errors + (completion-metadata-get (embark--metadata) 'category)) + ivy--old-cands))) + +(with-eval-after-load 'ivy + (add-hook 'embark-target-finders #'embark--ivy-selected) + (add-hook 'embark-candidate-collectors #'embark--ivy-candidates) + (remove-hook 'embark-candidate-collectors #'embark-selected-candidates) + (add-hook 'embark-candidate-collectors #'embark-selected-candidates)) + +;;; Custom actions + +(defvar embark-separator-history nil + "Input history for the separators used by some embark commands. +The commands that prompt for a string separator are +`embark-insert' and `embark-copy-as-kill'.") + +(defun embark-keymap-help () + "Prompt for an action to perform or command to become and run it." + (interactive) + (user-error "Not meant to be called directly")) + +(defun embark-toggle-quit () + "Toggle whether the following action quits the minibuffer." + (interactive) + (when (minibufferp) + (setq embark--toggle-quit (not embark--toggle-quit)) + (if (consp embark-quit-after-action) + (message "Will %sobey embark-quit-after-action." + (if embark--toggle-quit "dis" "")) + (message + "Will %squit minibuffer after action" + (if (eq embark--toggle-quit embark-quit-after-action) "not " ""))))) + +(defun embark--separator (strings) + "Return a separator to join the STRINGS together. +With a prefix argument, prompt the user (unless STRINGS has 0 or +1 elements, in which case a separator is not needed)." + (if (and current-prefix-arg (cdr strings)) + (read-string "Separator: " nil 'embark-separator-history) + "\n")) + +(defun embark-copy-as-kill (strings) + "Join STRINGS and save on the `kill-ring'. +With a prefix argument, prompt for the separator to join the +STRINGS, which defaults to a newline." + (kill-new (string-join strings (embark--separator strings)))) + +(defun embark-insert (strings) + "Join STRINGS and insert the result at point. +With a prefix argument, prompt for the separator to join the +STRINGS, which defaults to a newline. + +Some whitespace is also inserted if necessary to avoid having the +inserted string blend into the existing buffer text. More +precisely: + +1. If the inserted string does not contain newlines, a space may +be added before or after it as needed to avoid inserting a word +constituent character next to an existing word constituent. + +2. For a multiline inserted string, newlines may be added before +or after as needed to ensure the inserted string is on lines of +its own." + (let* ((separator (embark--separator strings)) + (multiline + (or (and (cdr strings) (string-match-p "\n" separator)) + (and (null (cdr strings)) + (equal (buffer-substring (line-beginning-position) + (line-end-position)) + (car strings))) + (seq-some (lambda (s) (string-match-p "\n" s)) strings)))) + (cl-labels ((maybe-space () + (and (looking-at "\\w") (looking-back "\\w" 1) + (insert " "))) + (maybe-newline () + (or (looking-back "^[ \t]*" 40) (looking-at "\n") + (newline-and-indent))) + (maybe-whitespace () + (if multiline (maybe-newline) (maybe-space))) + (ins-string () + (let ((start (point))) + (insert + (mapconcat #'substring-no-properties strings separator)) + (save-excursion (goto-char start) (maybe-whitespace)) + (when (looking-back "\n" 1) (delete-char -1)) + (save-excursion (maybe-whitespace))))) + (if buffer-read-only + (with-selected-window (other-window-for-scrolling) + (ins-string)) + (ins-string))))) + +(defun embark-dired-jump (file &optional other-window) + "Open Dired buffer in directory containing FILE and move to its line. +When called with a prefix argument OTHER-WINDOW, open Dired in other window." + (interactive "fJump to Dired file: \nP") + (dired-jump other-window file)) + +(defun embark--read-from-history (prompt candidates &optional category) + "Read with completion from list of history CANDIDATES of CATEGORY. +Sorting and history are disabled. PROMPT is the prompt message." + (completing-read prompt + (embark--with-category category candidates) + nil t nil t)) + +(defun embark-kill-ring-remove (text) + "Remove TEXT from `kill-ring'." + (interactive (list (embark--read-from-history + "Remove from kill-ring: " kill-ring 'kill-ring))) + (embark-history-remove text) + (setq kill-ring (delete text kill-ring))) + +(defvar recentf-list) +(defun embark-recentf-remove (file) + "Remove FILE from the list of recent files." + (interactive (list (embark--read-from-history + "Remove recent file: " recentf-list 'file))) + (embark-history-remove (expand-file-name file)) + (embark-history-remove (abbreviate-file-name file)) + (when (and (boundp 'recentf-list) (fboundp 'recentf-expand-file-name)) + (setq recentf-list (delete (recentf-expand-file-name file) recentf-list)))) + +(defun embark-history-remove (str) + "Remove STR from `minibuffer-history-variable'. +Many completion UIs sort by history position. This command can be used +to remove entries from the history, such that they are not sorted closer +to the top." + (interactive (list (embark--read-from-history + "Remove history item: " + (if (eq minibuffer-history-variable t) + (user-error "No minibuffer history") + (symbol-value minibuffer-history-variable))))) + (unless (eq minibuffer-history-variable t) + (set minibuffer-history-variable + (delete str (symbol-value minibuffer-history-variable))))) + +(defvar xref-backend-functions) + +(defun embark-find-definition (symbol) + "Find definition of Emacs Lisp SYMBOL." + (interactive "sSymbol: ") + (let ((xref-backend-functions (lambda () 'elisp))) + (xref-find-definitions symbol))) + +(defun embark-info-lookup-symbol (symbol) + "Display the definition of SYMBOL, from the Elisp manual." + (interactive "SSymbol: ") + (info-lookup-symbol symbol 'emacs-lisp-mode)) + +(defun embark-rename-buffer (buffer newname &optional unique) + "Rename BUFFER to NEWNAME, optionally making it UNIQUE. +Interactively, you can set UNIQUE with a prefix argument. +Returns the new name actually used." + (interactive "bBuffer: \nBRename %s to: \nP") + (when-let ((buf (get-buffer buffer))) + (with-current-buffer buf + (rename-buffer newname unique)))) + +(defun embark--package-url (pkg) + "Return homepage for package PKG." + (when-let (desc (embark--package-desc pkg)) + (alist-get :url (package-desc-extras desc)))) + +(defun embark--prompt-for-package () + "Prompt user for a package name." + ;; this code is taken from the interactive spec of describe-package + (unless package--initialized + (package-initialize t)) + (intern + (completing-read "Package: " + (append (mapcar #'car package-alist) + (mapcar #'car package-archive-contents) + (mapcar #'car package--builtins))))) + +(defun embark-browse-package-url (pkg) + "Open homepage for package PKG with `browse-url'." + (interactive (list (embark--prompt-for-package))) + (if-let ((url (embark--package-url pkg))) + (browse-url url) + (user-error "No homepage found for `%s'" pkg))) + +(defun embark-save-package-url (pkg) + "Save URL of homepage for package PKG on the `kill-ring'." + (interactive (list (embark--prompt-for-package))) + (if-let ((url (embark--package-url pkg))) + (kill-new url) + (user-error "No homepage found for `%s'" pkg))) + +(defun embark-save-variable-value (var) + "Save value of VAR in the `kill-ring'." + (interactive "SVariable: ") + (kill-new (string-trim (pp-to-string (symbol-value var))))) + +(defun embark-insert-variable-value (var) + "Insert value of VAR." + (interactive "SVariable: ") + (embark-insert (list (string-trim (pp-to-string (symbol-value var)))))) + +(defun embark-toggle-variable (var &optional local) + "Toggle value of boolean variable VAR. +If prefix LOCAL is non-nil make variable local." + (interactive "SVariable: \nP") + (let ((val (symbol-value var))) + (unless (memq val '(nil t)) + (user-error "Not a boolean variable")) + (when local + (make-local-variable var)) + (funcall (or (get var 'custom-set) 'set) var (not val)))) + +(defun embark-insert-relative-path (file) + "Insert relative path to FILE. +The insert path is relative to `default-directory'." + (interactive "FFile: ") + (embark-insert (list (file-relative-name (substitute-in-file-name file))))) + +(defun embark-save-relative-path (file) + "Save the relative path to FILE in the kill ring. +The insert path is relative to `default-directory'." + (interactive "FFile: ") + (kill-new (file-relative-name (substitute-in-file-name file)))) + +(defun embark-shell-command-on-buffer (buffer command &optional replace) + "Run shell COMMAND on contents of BUFFER. +Called with \\[universal-argument], replace contents of buffer +with command output. For replacement behavior see +`shell-command-dont-erase-buffer' setting." + (interactive + (list + (read-buffer "Buffer: " nil t) + (read-shell-command "Shell command: ") + current-prefix-arg)) + (with-current-buffer buffer + (shell-command-on-region (point-min) (point-max) + command + (and replace (current-buffer))))) + +(defun embark-open-externally (file) + "Open FILE or url using system's default application." + (interactive "sOpen externally: ") + (unless (string-match-p "\\`[a-z]+://" file) + (setq file (expand-file-name file))) + (message "Opening `%s' externally..." file) + (if (and (eq system-type 'windows-nt) + (fboundp 'w32-shell-execute)) + (w32-shell-execute "open" file) + (call-process (pcase system-type + ('darwin "open") + ('cygwin "cygstart") + (_ "xdg-open")) + nil 0 nil file))) + +(declare-function bookmark-prop-get "bookmark") +(declare-function bookmark-completing-read "bookmark") + +(defun embark-bookmark-open-externally (bookmark) + "Open BOOKMARK in external application." + (interactive (list (bookmark-completing-read "Open externally: "))) + (embark-open-externally + (or (bookmark-prop-get bookmark 'location) + (bookmark-prop-get bookmark 'filename) + (user-error "Bookmark `%s' does not have a location" bookmark)))) + +(defun embark-bury-buffer (buf) + "Bury buffer BUF." + (interactive "bBuffer: ") + (if-let (win (get-buffer-window buf)) + (with-selected-window win + (bury-buffer)) + (bury-buffer))) + +(defun embark-kill-buffer-and-window (buf) + "Kill buffer BUF and delete its window." + (interactive "bBuffer: ") + (when-let (buf (get-buffer buf)) + (if-let (win (get-buffer-window buf)) + (with-selected-window win + (kill-buffer-and-window)) + (kill-buffer buf)))) + +(defun embark-save-unicode-character (char) + "Save Unicode character CHAR to kill ring." + (interactive + (list (read-char-by-name "Insert character (Unicode name or hex): "))) + (kill-new (format "%c" char))) + +(defun embark-isearch-forward () + "Prompt for string in the minibuffer and start isearch forwards. +Unlike isearch, this command reads the string from the +minibuffer, which means it can be used as an Embark action." + (interactive) + (isearch-mode t) + (isearch-edit-string)) + +(defun embark-isearch-backward () + "Prompt for string in the minibuffer and start isearch backwards. +Unlike isearch, this command reads the string from the +minibuffer, which means it can be used as an Embark action." + (interactive) + (isearch-mode nil) + (isearch-edit-string)) + +(defun embark-toggle-highlight () + "Toggle symbol highlighting using `highlight-symbol-at-point'." + (interactive) + (let ((regexp (find-tag-default-as-symbol-regexp)) + (highlighted (cl-find-if #'boundp + '(hi-lock-interactive-lighters + hi-lock-interactive-patterns)))) + (if (and highlighted (assoc regexp (symbol-value highlighted))) + (unhighlight-regexp regexp) + (highlight-symbol-at-point)))) + +(defun embark-next-symbol () + "Jump to next occurrence of symbol at point. +The search respects symbol boundaries." + (interactive) + (if-let ((symbol (thing-at-point 'symbol))) + (let ((regexp (format "\\_<%s\\_>" (regexp-quote symbol)))) + (when (looking-at regexp) + (forward-symbol 1)) + (unless (re-search-forward regexp nil t) + (user-error "Symbol `%s' not found" symbol))) + (user-error "No symbol at point"))) + +(defun embark-previous-symbol () + "Jump to previous occurrence of symbol at point. +The search respects symbol boundaries." + (interactive) + (if-let ((symbol (thing-at-point 'symbol))) + (let ((regexp (format "\\_<%s\\_>" (regexp-quote symbol)))) + (when (looking-back regexp (- (point) (length symbol))) + (forward-symbol -1)) + (unless (re-search-backward regexp nil t) + (user-error "Symbol `%s' not found" symbol))) + (user-error "No symbol at point"))) + +(defun embark-compose-mail (address) + "Compose email to ADDRESS." + ;; The only reason we cannot use compose-mail directly is its + ;; interactive specification, which just supplies nil for the + ;; address (and several other arguments). + (interactive "sTo: ") + (compose-mail address)) + +(autoload 'pp-display-expression "pp") + +(defun embark-pp-eval-defun (edebug) + "Run `eval-defun' and pretty print the result. +With a prefix argument EDEBUG, instrument the code for debugging." + (interactive "P") + (cl-letf (((symbol-function #'eval-expression-print-format) + (lambda (result) + (pp-display-expression result "*Pp Eval Output*")))) + (eval-defun edebug))) + +(defun embark-eval-replace (noquote) + "Evaluate region and replace with evaluated result. +If NOQUOTE is non-nil (interactively, if called with a prefix +argument), no quoting is used for strings." + (interactive "P") + (let ((beg (region-beginning)) + (end (region-end))) + (save-excursion + (goto-char end) + (insert (format (if noquote "%s" "%S") + (eval (read (buffer-substring beg end)) lexical-binding))) + (delete-region beg end)))) + +(static-if (< emacs-major-version 29) + (defun embark-elp-restore-package (prefix) + "Remove instrumentation from functions with names starting with PREFIX." + (interactive "SPrefix: ") + (when (fboundp 'elp-restore-list) + (elp-restore-list + (mapcar #'intern + (all-completions (symbol-name prefix) + obarray 'elp-profilable-p)))))) + +(defmacro embark--define-hash (algorithm) + "Define command which computes hash from a string. +ALGORITHM is the hash algorithm symbol understood by `secure-hash'." + `(defun ,(intern (format "embark-hash-%s" algorithm)) (str) + ,(format "Compute %s hash of STR and store it in the kill ring." algorithm) + (interactive "sString: ") + (let ((hash (secure-hash ',algorithm str))) + (kill-new hash) + (message "%s: %s" ',algorithm hash)))) + +(embark--define-hash md5) +(embark--define-hash sha1) +(embark--define-hash sha224) +(embark--define-hash sha256) +(embark--define-hash sha384) +(embark--define-hash sha512) + +(defun embark-encode-url (start end) + "Properly URI-encode the region between START and END in current buffer." + (interactive "r") + (let ((encoded (url-encode-url (buffer-substring-no-properties start end)))) + (delete-region start end) + (insert encoded))) + +(defun embark-decode-url (start end) + "Decode the URI-encoded region between START and END in current buffer. +It assumes the URL was encoded in UTF-8." + (interactive "r") + (let ((decoded (decode-coding-string + (url-unhex-string + (buffer-substring-no-properties start end)) + 'utf-8))) + (delete-region start end) + (insert decoded))) + +(defvar epa-replace-original-text) +(defun embark-epa-decrypt-region (start end) + "Decrypt region between START and END." + (interactive "r") + (let ((epa-replace-original-text t)) + (epa-decrypt-region start end))) + +(defvar eww-download-directory) +(autoload 'eww-download-callback "eww") + +(defun embark-download-url (url) + "Download URL to `eww-download-directory'." + (interactive "sDownload URL: ") + (let ((dir eww-download-directory)) + (when (functionp dir) (setq dir (funcall dir))) + (access-file dir "Download failed") + (url-retrieve url #'eww-download-callback (list url dir)))) + +;;; Setup and pre-action hooks + +(defun embark--restart (&rest _) + "Restart current command with current input. +Use this to refresh the list of candidates for commands that do +not handle that themselves." + (when (minibufferp) + (embark--become-command embark--command (minibuffer-contents)))) + +(defun embark--shell-prep (&rest _) + "Prepare target for use as argument for a shell command. +This quotes the spaces, inserts an extra space at the beginning +and leaves the point to the left of it." + (let ((contents (minibuffer-contents))) + (delete-minibuffer-contents) + (insert " " (shell-quote-wildcard-pattern contents)) + (goto-char (minibuffer-prompt-end)))) + +(defun embark--force-complete (&rest _) + "Select first minibuffer completion candidate matching target." + (minibuffer-force-complete)) + +(cl-defun embark--eval-prep (&key type &allow-other-keys) + "If target's TYPE is variable, skip edit; if function, wrap in ()." + (when (memq type '(command function)) + (embark--allow-edit) + (goto-char (minibuffer-prompt-end)) + (insert "(") + (goto-char (point-max)) + (insert ")") + (backward-char))) + +(cl-defun embark--beginning-of-target (&key bounds &allow-other-keys) + "Go to beginning of the target BOUNDS." + (when (number-or-marker-p (car bounds)) + (goto-char (car bounds)))) + +(cl-defun embark--end-of-target (&key bounds &allow-other-keys) + "Go to end of the target BOUNDS." + (when (number-or-marker-p (cdr bounds)) + (goto-char (cdr bounds)))) + +(cl-defun embark--mark-target (&rest rest &key run bounds &allow-other-keys) + "Mark the target if its BOUNDS are known. +After marking the target, call RUN with the REST of its arguments." + (cond + ((and bounds run) + (save-mark-and-excursion + (set-mark (cdr bounds)) + (goto-char (car bounds)) + (apply run :bounds bounds rest))) + (bounds ;; used as pre- or post-action hook + (set-mark (cdr bounds)) + (goto-char (car bounds))) + (run (apply run rest)))) + +(cl-defun embark--unmark-target (&rest _) + "Deactivate the region target." + (deactivate-mark t)) + +(cl-defun embark--narrow-to-target + (&rest rest &key run bounds &allow-other-keys) + "Narrow buffer to target if its BOUNDS are known. +Intended for use as an Embark around-action hook. This function +runs RUN with the buffer narrowed to given BOUNDS passing along +the REST of the arguments." + (if bounds + (save-excursion + (save-restriction + (narrow-to-region (car bounds) (cdr bounds)) + (goto-char (car bounds)) + (apply run :bounds bounds rest))) + (apply run rest))) + +(defun embark--allow-edit (&rest _) + "Allow editing the target." + (remove-hook 'post-command-hook #'exit-minibuffer t) + (remove-hook 'post-command-hook 'ivy-immediate-done t)) + +(defun embark--ignore-target (&rest _) + "Ignore the target." + (let ((contents + (get-text-property (minibuffer-prompt-end) 'embark--initial-input))) + (delete-minibuffer-contents) + (when contents (insert contents))) + (embark--allow-edit)) + +(autoload 'xref-push-marker-stack "xref") +(defun embark--xref-push-marker (&rest _) + "Push a marker onto the xref marker stack." + (xref-push-marker-stack)) + +(cl-defun embark--confirm (&key action target &allow-other-keys) + "Ask for confirmation before running the ACTION on the TARGET." + (unless (y-or-n-p (format "Run %s on %s? " action target)) + (user-error "Canceled"))) + +(defconst embark--associated-file-fn-alist + `((file . identity) + (buffer . ,(lambda (target) + (let ((buffer (get-buffer target))) + (or (buffer-file-name buffer) + (buffer-local-value 'default-directory buffer))))) + (bookmark . bookmark-location) + (library . locate-library)) + "Alist of functions that extract a file path from targets of a given type.") + +(defun embark--associated-directory (target type) + "Return directory associated to TARGET of given TYPE. +The supported values of TYPE are file, buffer, bookmark and +library, which have an obvious notion of associated directory." + (when-let ((file-fn (alist-get type embark--associated-file-fn-alist)) + (file (funcall file-fn target))) + (if (file-directory-p file) + (file-name-as-directory file) + (file-name-directory file)))) + +(cl-defun embark--cd (&rest rest &key run target type &allow-other-keys) + "Run action with `default-directory' set to the directory of TARGET. +The supported values of TYPE are file, buffer, bookmark and +library, which have an obvious notion of associated directory. +The REST of the arguments are also passed to RUN." + (let ((default-directory + (or (embark--associated-directory target type) default-directory))) + (apply run :target target :type type rest))) + +(cl-defun embark--save-excursion (&rest rest &key run &allow-other-keys) + "Run action without moving point. +This simply calls RUN with the REST of its arguments inside +`save-excursion'." + (save-excursion (apply run rest))) + +(defun embark--universal-argument (&rest _) + "Run action with a universal prefix argument." + (setq prefix-arg '(4))) + +;;; keymaps + +(defvar-keymap embark-meta-map + :doc "Keymap for non-action Embark functions." + "-" #'negative-argument + "0" #'digit-argument + "1" #'digit-argument + "2" #'digit-argument + "3" #'digit-argument + "4" #'digit-argument + "5" #'digit-argument + "6" #'digit-argument + "7" #'digit-argument + "8" #'digit-argument + "9" #'digit-argument) + +(defvar-keymap embark-general-map + :doc "Keymap for Embark general actions." + :parent embark-meta-map + "i" #'embark-insert + "w" #'embark-copy-as-kill + "q" #'embark-toggle-quit + "E" #'embark-export + "S" #'embark-collect + "L" #'embark-live + "B" #'embark-become + "A" #'embark-act-all + "C-s" #'embark-isearch-forward + "C-r" #'embark-isearch-backward + "C-SPC" #'mark + "DEL" #'delete-region + "SPC" #'embark-select) + +(defvar-keymap embark-encode-map + :doc "Keymap for Embark region encoding actions." + "r" #'rot13-region + "." #'morse-region + "-" #'unmorse-region + "s" #'studlify-region + "m" #'embark-hash-md5 + "1" #'embark-hash-sha1 + "2" #'embark-hash-sha256 + "3" #'embark-hash-sha384 + "4" #'embark-hash-sha224 + "5" #'embark-hash-sha512 + "f" #'format-encode-region + "F" #'format-decode-region + "b" #'base64-encode-region + "B" #'base64-decode-region + "u" #'embark-encode-url + "U" #'embark-decode-url + "c" #'epa-encrypt-region + "C" #'embark-epa-decrypt-region) + +(fset 'embark-encode-map embark-encode-map) + +(defvar-keymap embark-sort-map + :doc "Keymap for Embark actions that sort the region" + "l" #'sort-lines + "P" #'sort-pages + "f" #'sort-fields + "c" #'sort-columns + "p" #'sort-paragraphs + "r" #'sort-regexp-fields + "n" #'sort-numeric-fields) + +(fset 'embark-sort-map embark-sort-map) + +;; this has had an autoload cookie since at least Emacs 26 +;; but that autoload doesn't seem to work for me +(autoload 'org-table-convert-region "org-table" nil t) + +(defvar-keymap embark-region-map + :doc "Keymap for Embark actions on the active region." + :parent embark-general-map + "u" #'upcase-region + "l" #'downcase-region + "c" #'capitalize-region + "|" #'shell-command-on-region + "e" #'eval-region + "<" #'embark-eval-replace + "a" #'align + "A" #'align-regexp + "<left>" #'indent-rigidly + "<right>" #'indent-rigidly + "TAB" #'indent-region + "f" #'fill-region + "p" #'fill-region-as-paragraph + "$" #'ispell-region + "=" #'count-words-region + "F" #'whitespace-cleanup-region + "t" #'transpose-regions + "o" #'org-table-convert-region + ";" #'comment-or-uncomment-region + "W" #'write-region + "+" #'append-to-file + "m" #'apply-macro-to-region-lines + "n" #'narrow-to-region + "*" #'calc-grab-region + ":" #'calc-grab-sum-down + "_" #'calc-grab-sum-across + "r" #'reverse-region + "d" #'delete-duplicate-lines + "b" #'browse-url-of-region + "h" #'shr-render-region + "'" #'expand-region-abbrevs + "v" #'vc-region-history + "R" #'repunctuate-sentences + "s" 'embark-sort-map + ">" 'embark-encode-map) + +(defvar-keymap embark-vc-file-map + :doc "Keymap for Embark VC file actions." + "d" #'vc-delete-file + "r" #'vc-rename-file + "i" #'vc-ignore) + +(fset 'embark-vc-file-map embark-vc-file-map) + +(defvar-keymap embark-file-map + :doc "Keymap for Embark file actions." + :parent embark-general-map + "RET" #'find-file + "f" #'find-file + "F" #'find-file-literally + "o" #'find-file-other-window + "d" #'delete-file + "D" #'delete-directory + "r" #'rename-file + "c" #'copy-file + "s" #'make-symbolic-link + "j" #'embark-dired-jump + "!" #'shell-command + "&" #'async-shell-command + "$" #'eshell + "<" #'insert-file + "m" #'chmod + "=" #'ediff-files + "+" #'make-directory + "\\" #'embark-recentf-remove + "I" #'embark-insert-relative-path + "W" #'embark-save-relative-path + "x" #'embark-open-externally + "e" #'eww-open-file + "l" #'load-file + "b" #'byte-compile-file + "R" #'byte-recompile-directory + "v" 'embark-vc-file-map) + +(defvar-keymap embark-kill-ring-map + :doc "Keymap for `kill-ring' commands." + :parent embark-general-map + "\\" #'embark-kill-ring-remove) + +(defvar-keymap embark-url-map + :doc "Keymap for Embark url actions." + :parent embark-general-map + "RET" #'browse-url + "b" #'browse-url + "d" #'embark-download-url + "x" #'embark-open-externally + "e" #'eww) + +(defvar-keymap embark-email-map + :doc "Keymap for Embark email actions." + :parent embark-general-map + "RET" #'embark-compose-mail + "c" #'embark-compose-mail) + +(defvar-keymap embark-library-map + :doc "Keymap for operations on Emacs Lisp libraries." + :parent embark-general-map + "RET" #'find-library + "l" #'load-library + "f" #'find-library + "h" #'finder-commentary + "a" #'apropos-library + "L" #'locate-library + "m" #'info-display-manual + "$" #'eshell) + +(defvar-keymap embark-buffer-map + :doc "Keymap for Embark buffer actions." + :parent embark-general-map + "RET" #'switch-to-buffer + "k" #'kill-buffer + "b" #'switch-to-buffer + "o" #'switch-to-buffer-other-window + "z" #'embark-bury-buffer + "K" #'embark-kill-buffer-and-window + "r" #'embark-rename-buffer + "=" #'ediff-buffers + "|" #'embark-shell-command-on-buffer + "<" #'insert-buffer + "$" #'eshell) + +(defvar-keymap embark-tab-map + :doc "Keymap for actions for tab-bar tabs." + :parent embark-general-map + "RET" #'tab-bar-select-tab-by-name + "s" #'tab-bar-select-tab-by-name + "r" #'tab-bar-rename-tab-by-name + "k" #'tab-bar-close-tab-by-name) + +(defvar-keymap embark-identifier-map + :doc "Keymap for Embark identifier actions." + :parent embark-general-map + "RET" #'xref-find-definitions + "h" #'display-local-help + "H" #'embark-toggle-highlight + "d" #'xref-find-definitions + "r" #'xref-find-references + "a" #'xref-find-apropos + "s" #'info-lookup-symbol + "n" #'embark-next-symbol + "p" #'embark-previous-symbol + "'" #'expand-abbrev + "$" #'ispell-word + "o" #'occur) + +(defvar-keymap embark-expression-map + :doc "Keymap for Embark expression actions." + :parent embark-general-map + "RET" #'pp-eval-expression + "e" #'pp-eval-expression + "<" #'embark-eval-replace + "m" #'pp-macroexpand-expression + "TAB" #'indent-region + "r" #'raise-sexp + ";" #'comment-dwim + "t" #'transpose-sexps + "k" #'kill-region + "u" #'backward-up-list + "n" #'forward-list + "p" #'backward-list) + +(defvar-keymap embark-defun-map + :doc "Keymap for Embark defun actions." + :parent embark-expression-map + "RET" #'embark-pp-eval-defun + "e" #'embark-pp-eval-defun + "c" #'compile-defun + "D" #'edebug-defun + "o" #'checkdoc-defun + "N" #'narrow-to-defun) + +;; Use quoted symbols to avoid byte-compiler warnings. +(defvar-keymap embark-heading-map + :doc "Keymap for Embark heading actions." + :parent embark-general-map + "RET" 'outline-show-subtree + "TAB" 'outline-cycle + "C-SPC" 'outline-mark-subtree + "n" 'outline-next-visible-heading + "p" 'outline-previous-visible-heading + "f" 'outline-forward-same-level + "b" 'outline-backward-same-level + "^" 'outline-move-subtree-up + "v" 'outline-move-subtree-down + "u" 'outline-up-heading + "+" 'outline-show-subtree + "-" 'outline-hide-subtree + ">" 'outline-demote + "<" 'outline-promote) + +(defvar-keymap embark-symbol-map + :doc "Keymap for Embark symbol actions." + :parent embark-identifier-map + "RET" #'embark-find-definition + "h" #'describe-symbol + "s" #'embark-info-lookup-symbol + "d" #'embark-find-definition + "e" #'pp-eval-expression + "a" #'apropos + "\\" #'embark-history-remove) + +(defvar-keymap embark-face-map + :doc "Keymap for Embark face actions." + :parent embark-symbol-map + "h" #'describe-face + "c" #'customize-face + "+" #'make-face-bold + "-" #'make-face-unbold + "/" #'make-face-italic + "|" #'make-face-unitalic + "!" #'invert-face + "f" #'set-face-foreground + "b" #'set-face-background) + +(defvar-keymap embark-variable-map + :doc "Keymap for Embark variable actions." + :parent embark-symbol-map + "=" #'set-variable + "c" #'customize-set-variable + "u" #'customize-variable + "v" #'embark-save-variable-value + "<" #'embark-insert-variable-value + "t" #'embark-toggle-variable) + +(defvar-keymap embark-function-map + :doc "Keymap for Embark function actions." + :parent embark-symbol-map + "m" #'elp-instrument-function ;; m=measure + "M" 'elp-restore-function ;; quoted, not autoloaded + "k" #'debug-on-entry ;; breaKpoint (running out of letters, really) + "K" #'cancel-debug-on-entry + "t" #'trace-function + "T" 'untrace-function) ;; quoted, not autoloaded + +(defvar-keymap embark-command-map + :doc "Keymap for Embark command actions." + :parent embark-function-map + "x" #'execute-extended-command + "I" #'Info-goto-emacs-command-node + "b" #'where-is + "g" #'global-set-key + "l" #'local-set-key) + +(defvar-keymap embark-package-map + :doc "Keymap for Embark package actions." + :parent embark-general-map + "RET" #'describe-package + "h" #'describe-package + "i" #'package-install + "I" #'embark-insert + "d" #'package-delete + "r" #'package-reinstall + "u" #'embark-browse-package-url + "W" #'embark-save-package-url + "a" #'package-autoremove + "g" #'package-refresh-contents + "m" #'elp-instrument-package ;; m=measure + "M" (if (fboundp 'embark-elp-restore-package) + 'embark-elp-restore-package + 'elp-restore-package)) + +(defvar-keymap embark-bookmark-map + :doc "Keymap for Embark bookmark actions." + :parent embark-general-map + "RET" #'bookmark-jump + "s" #'bookmark-set + "d" #'bookmark-delete + "r" #'bookmark-rename + "R" #'bookmark-relocate + "l" #'bookmark-locate + "<" #'bookmark-insert + "j" #'bookmark-jump + "o" #'bookmark-jump-other-window + "f" #'bookmark-jump-other-frame + "a" 'bookmark-show-annotation + "e" 'bookmark-edit-annotation + "x" #'embark-bookmark-open-externally + "$" #'eshell) + +(defvar-keymap embark-unicode-name-map + :doc "Keymap for Embark Unicode name actions." + :parent embark-general-map + "RET" #'insert-char + "I" #'insert-char + "W" #'embark-save-unicode-character) + +(defvar-keymap embark-prose-map + :doc "Keymap for Embark actions for dealing with prose." + :parent embark-general-map + "$" #'ispell-region + "f" #'fill-region + "u" #'upcase-region + "l" #'downcase-region + "c" #'capitalize-region + "F" #'whitespace-cleanup-region + "=" #'count-words-region) + +(defvar-keymap embark-sentence-map + :doc "Keymap for Embark actions for dealing with sentences." + :parent embark-prose-map + "t" #'transpose-sentences + "n" #'forward-sentence + "p" #'backward-sentence) + +(defvar-keymap embark-paragraph-map + :doc "Keymap for Embark actions for dealing with paragraphs." + :parent embark-prose-map + "t" #'transpose-paragraphs + "n" #'forward-paragraph + "p" #'backward-paragraph + "R" #'repunctuate-sentences) + +(defvar-keymap embark-flymake-map + :doc "Keymap for Embark actions on Flymake diagnostics." + :parent embark-general-map + "RET" 'flymake-show-buffer-diagnostics + "n" 'flymake-goto-next-error + "p" 'flymake-goto-prev-error) + +(defvar-keymap embark-become-help-map + :doc "Keymap for Embark help actions." + :parent embark-meta-map + "V" #'apropos-variable + "U" #'apropos-user-option + "C" #'apropos-command + "v" #'describe-variable + "f" #'describe-function + "s" #'describe-symbol + "F" #'describe-face + "p" #'describe-package + "i" #'describe-input-method) + +(autoload 'recentf-open-files "recentf" nil t) + +(defvar-keymap embark-become-file+buffer-map + :doc "Embark become keymap for files and buffers." + :parent embark-meta-map + "f" #'find-file + "4 f" #'find-file-other-window + "." #'find-file-at-point + "p" #'project-find-file + "r" #'recentf-open-files + "b" #'switch-to-buffer + "4 b" #'switch-to-buffer-other-window + "l" #'locate + "L" #'find-library + "v" #'vc-dir) + +(defvar-keymap embark-become-shell-command-map + :doc "Embark become keymap for shell commands." + :parent embark-meta-map + "!" #'shell-command + "&" #'async-shell-command + "c" #'comint-run + "t" #'term) + +(defvar-keymap embark-become-match-map + :doc "Embark become keymap for search." + :parent embark-meta-map + "o" #'occur + "k" #'keep-lines + "f" #'flush-lines + "c" #'count-matches) + +(provide 'embark) + +;; Check that embark-consult is installed. If Embark is used in +;; combination with Consult, you should install the integration package, +;; such that features like embark-export from consult-grep work as +;; expected. + +(with-eval-after-load 'consult + (unless (require 'embark-consult nil 'noerror) + (warn "The package embark-consult should be installed if you use both Embark and Consult"))) + +(with-eval-after-load 'org + (require 'embark-org)) + +;;; embark.el ends here diff --git a/emacs/elpa/embark-20241003.1953/embark.elc b/emacs/elpa/embark-20241003.1953/embark.elc Binary files differ. diff --git a/emacs/elpa/embark-20240919.1831/embark.info b/emacs/elpa/embark-20241003.1953/embark.info diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-completion.el b/emacs/elpa/lsp-mode-20241003.636/lsp-completion.el @@ -1,841 +0,0 @@ -;;; lsp-completion.el --- LSP completion -*- lexical-binding: t; -*- -;; -;; Copyright (C) 2020 emacs-lsp maintainers -;; -;; This program is free software; you can redistribute it and/or modify -;; it under the terms of the GNU General Public License as published by -;; the Free Software Foundation, either version 3 of the License, or -;; (at your option) any later version. - -;; This program is distributed in the hope that it will be useful, -;; but WITHOUT ANY WARRANTY; without even the implied warranty of -;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -;; GNU General Public License for more details. - -;; You should have received a copy of the GNU General Public License -;; along with this program. If not, see <https://www.gnu.org/licenses/>. -;; -;;; Commentary: -;; -;; LSP completion -;; -;;; Code: - -(require 'lsp-mode) - -(defgroup lsp-completion nil - "LSP support for completion." - :prefix "lsp-completion-" - :group 'lsp-mode - :tag "LSP Completion") - -;;;###autoload -(define-obsolete-variable-alias 'lsp-prefer-capf - 'lsp-completion-provider "lsp-mode 7.0.1") - -(defcustom lsp-completion-provider :capf - "The completion backend provider." - :type '(choice - (const :tag "Use company-capf" :capf) - (const :tag "None" :none)) - :group 'lsp-completion - :package-version '(lsp-mode . "7.0.1")) - -;;;###autoload -(define-obsolete-variable-alias 'lsp-enable-completion-at-point - 'lsp-completion-enable "lsp-mode 7.0.1") - -(defcustom lsp-completion-enable t - "Enable `completion-at-point' integration." - :type 'boolean - :group 'lsp-completion) - -(defcustom lsp-completion-enable-additional-text-edit t - "Whether or not to apply additional text edit when performing completion. - -If set to non-nil, `lsp-mode' will apply additional text edits -from the server. Otherwise, the additional text edits are -ignored." - :type 'boolean - :group 'lsp-completion - :package-version '(lsp-mode . "6.3.2")) - -(defcustom lsp-completion-show-kind t - "Whether or not to show kind of completion candidates." - :type 'boolean - :group 'lsp-completion - :package-version '(lsp-mode . "7.0.1")) - -(defcustom lsp-completion-show-detail t - "Whether or not to show detail of completion candidates." - :type 'boolean - :group 'lsp-completion) - -(defcustom lsp-completion-show-label-description t - "Whether or not to show description of completion candidates." - :type 'boolean - :group 'lsp-completion - :package-version '(lsp-mode . "9.0.0")) - -(defcustom lsp-completion-no-cache nil - "Whether or not caching the returned completions from server." - :type 'boolean - :group 'lsp-completion - :package-version '(lsp-mode . "7.0.1")) - -(defcustom lsp-completion-filter-on-incomplete t - "Whether or not filter incomplete results." - :type 'boolean - :group 'lsp-completion - :package-version '(lsp-mode . "7.0.1")) - -(defcustom lsp-completion-sort-initial-results t - "Whether or not filter initial results from server." - :type 'boolean - :group 'lsp-completion - :package-version '(lsp-mode . "8.0.0")) - -(defcustom lsp-completion-use-last-result t - "Temporarily use last server result when interrupted by keyboard. -This will help minimize popup flickering issue in `company-mode'." - :type 'boolean - :group 'lsp-completion - :package-version '(lsp-mode . "8.0.0")) - -(defconst lsp-completion--item-kind - [nil - "Text" - "Method" - "Function" - "Constructor" - "Field" - "Variable" - "Class" - "Interface" - "Module" - "Property" - "Unit" - "Value" - "Enum" - "Keyword" - "Snippet" - "Color" - "File" - "Reference" - "Folder" - "EnumMember" - "Constant" - "Struct" - "Event" - "Operator" - "TypeParameter"]) - -(defvar yas-indent-line) -(defvar company-backends) -(defvar company-abort-on-unique-match) - -(defvar lsp-completion--no-reordering nil - "Dont do client-side reordering completion items when set.") - -(declare-function company-mode "ext:company") -(declare-function yas-expand-snippet "ext:yasnippet") - -(defun lsp-doc-buffer (&optional string) - "Return doc for STRING." - (with-current-buffer (get-buffer-create "*lsp-documentation*") - (erase-buffer) - (fundamental-mode) - (when string - (save-excursion - (insert string) - (visual-line-mode))) - (current-buffer))) - -(defun lsp-falsy? (val) - "Non-nil if VAL is falsy." - ;; https://developer.mozilla.org/en-US/docs/Glossary/Falsy - (or (not val) (equal val "") (equal val 0))) - -(cl-defun lsp-completion--make-item (item &key markers prefix) - "Make completion item from lsp ITEM and with MARKERS and PREFIX." - (-let (((&CompletionItem :label - :sort-text? - :_emacsStartPoint start-point) - item)) - (propertize label - 'lsp-completion-item item - 'lsp-sort-text sort-text? - 'lsp-completion-start-point start-point - 'lsp-completion-markers markers - 'lsp-completion-prefix prefix))) - -(defun lsp-completion--annotate (item) - "Annotate ITEM detail." - (-let (((&CompletionItem :detail? :kind? :label-details?) (plist-get (text-properties-at 0 item) - 'lsp-completion-item))) - (concat (when (and lsp-completion-show-detail detail?) - (concat " " (s-replace "\r" "" detail?))) - (when (and lsp-completion-show-label-description label-details?) - (when-let ((description (and label-details? (lsp:label-details-description label-details?)))) - (format " %s" description))) - (when lsp-completion-show-kind - (when-let ((kind-name (and kind? (aref lsp-completion--item-kind kind?)))) - (format " (%s)" kind-name)))))) - -(defun lsp-completion--looking-back-trigger-characterp (trigger-characters) - "Return character if text before point match any of the TRIGGER-CHARACTERS." - (unless (= (point) (line-beginning-position)) - (seq-some - (lambda (trigger-char) - (and (equal (buffer-substring-no-properties (- (point) (length trigger-char)) (point)) - trigger-char) - trigger-char)) - trigger-characters))) - -(defvar lsp-completion--cache nil - "Cached candidates for completion at point function. -In the form of plist (prefix-pos items :lsp-items :prefix ...). -When the completion is incomplete, `items' contains value of :incomplete.") - -(defvar lsp-completion--last-result nil - "Last completion result.") - -(defun lsp-completion--clear-cache (&optional keep-last-result) - "Clear completion caches. -KEEP-LAST-RESULT if specified." - (-some-> lsp-completion--cache - (cddr) - (plist-get :markers) - (cl-second) - (set-marker nil)) - (setq lsp-completion--cache nil) - (unless keep-last-result (setq lsp-completion--last-result nil))) - -(defcustom lsp-completion-default-behaviour :replace - "Default behaviour of `InsertReplaceEdit'." - :type '(choice - (const :insert :tag "Default completion inserts") - (const :replace :tag "Default completion replaces")) - :group 'lsp-mode - :package-version '(lsp-mode . "8.0.0")) - -(lsp-defun lsp-completion--guess-prefix ((item &as &CompletionItem :text-edit?)) - "Guess ITEM's prefix start point according to following heuristics: -- If `textEdit' exists, use insertion range start as prefix start point. -- Else, find the point before current point is longest prefix match of -`insertText' or `label'. And: - - The character before prefix is not word constitute -Return `nil' when fails to guess prefix." - (cond - ((lsp-insert-replace-edit? text-edit?) - (lsp--position-to-point (lsp:range-start (lsp:insert-replace-edit-insert text-edit?)))) - (text-edit? - (lsp--position-to-point (lsp:range-start (lsp:text-edit-range text-edit?)))) - (t - (-let* (((&CompletionItem :label :insert-text?) item) - (text (or (unless (lsp-falsy? insert-text?) insert-text?) label)) - (point (point)) - (start (max 1 (- point (length text)))) - (char-before (char-before start)) - start-point) - (while (and (< start point) (not start-point)) - (unless (or (and char-before (equal (char-syntax char-before) ?w)) - (not (string-prefix-p (buffer-substring-no-properties start point) - text))) - (setq start-point start)) - (cl-incf start) - (setq char-before (char-before start))) - start-point)))) - -(defun lsp-completion--to-internal (items) - "Convert ITEMS into internal form." - (--> items - (-map (-lambda ((item &as &CompletionItem - :label - :filter-text? - :_emacsStartPoint start-point - :score?)) - `( :label ,(or (unless (lsp-falsy? filter-text?) filter-text?) label) - :item ,item - :start-point ,start-point - :score ,score?)) - it))) - -(cl-defun lsp-completion--filter-candidates (items &key - lsp-items - markers - prefix - &allow-other-keys) - "List all possible completions in cached ITEMS with their prefixes. -We can pass LSP-ITEMS, which will be used when there's no cache. -The MARKERS and PREFIX value will be attached to each candidate." - (lsp--while-no-input - (->> - (if items - (--> (let (queries fuz-queries) - (-keep (-lambda ((cand &as &plist :label :start-point :score)) - (let* ((query (or (plist-get queries start-point) - (let ((s (buffer-substring-no-properties - start-point (point)))) - (setq queries (plist-put queries start-point s)) - s))) - (fuz-query (or (plist-get fuz-queries start-point) - (let ((s (lsp-completion--regex-fuz query))) - (setq fuz-queries - (plist-put fuz-queries start-point s)) - s))) - (label-len (length label))) - (when (string-match fuz-query label) - (put-text-property 0 label-len 'match-data (match-data) label) - (plist-put cand - :sort-score - (* (or (lsp-completion--fuz-score query label) 1e-05) - (or score 0.001))) - cand))) - items)) - (if lsp-completion--no-reordering - it - (sort it (lambda (o1 o2) - (> (plist-get o1 :sort-score) - (plist-get o2 :sort-score))))) - ;; TODO: pass additional function to sort the candidates - (-map (-rpartial #'plist-get :item) it)) - lsp-items) - (-map (lambda (item) (lsp-completion--make-item item - :markers markers - :prefix prefix)))))) - -(defconst lsp-completion--kind->symbol - '((1 . text) - (2 . method) - (3 . function) - (4 . constructor) - (5 . field) - (6 . variable) - (7 . class) - (8 . interface) - (9 . module) - (10 . property) - (11 . unit) - (12 . value) - (13 . enum) - (14 . keyword) - (15 . snippet) - (16 . color) - (17 . file) - (18 . reference) - (19 . folder) - (20 . enum-member) - (21 . constant) - (22 . struct) - (23 . event) - (24 . operator) - (25 . type-parameter))) - -(defun lsp-completion--candidate-kind (item) - "Return ITEM's kind." - (alist-get (lsp:completion-item-kind? (get-text-property 0 'lsp-completion-item item)) - lsp-completion--kind->symbol)) - -(defun lsp-completion--candidate-deprecated (item) - "Return if ITEM is deprecated." - (let ((completion-item (get-text-property 0 'lsp-completion-item item))) - (or (lsp:completion-item-deprecated? completion-item) - (seq-position (lsp:completion-item-tags? completion-item) - lsp/completion-item-tag-deprecated)))) - -(defun lsp-completion--company-match (candidate) - "Return highlight of typed prefix inside CANDIDATE." - (if-let ((md (cddr (plist-get (text-properties-at 0 candidate) 'match-data)))) - (let (matches start end) - (while (progn (setq start (pop md) end (pop md)) - (and start end)) - (setq matches (nconc matches `((,start . ,end))))) - matches) - (let* ((prefix (downcase - (buffer-substring-no-properties - ;; Put a safe guard to prevent staled cache from setting a wrong start point #4192 - (max (line-beginning-position) - (plist-get (text-properties-at 0 candidate) 'lsp-completion-start-point)) - (point)))) - (prefix-len (length prefix)) - (prefix-pos 0) - (label (downcase candidate)) - (label-len (length label)) - (label-pos 0) - matches start) - (while (and (not matches) - (< prefix-pos prefix-len)) - (while (and (< prefix-pos prefix-len) - (< label-pos label-len)) - (if (equal (aref prefix prefix-pos) (aref label label-pos)) - (progn - (unless start (setq start label-pos)) - (cl-incf prefix-pos)) - (when start - (setq matches (nconc matches `((,start . ,label-pos)))) - (setq start nil))) - (cl-incf label-pos)) - (when start (setq matches (nconc matches `((,start . ,label-pos))))) - ;; Search again when the whole prefix is not matched - (when (< prefix-pos prefix-len) - (setq matches nil)) - ;; Start search from next offset of prefix to find a match with label - (unless matches - (cl-incf prefix-pos) - (setq label-pos 0))) - matches))) - -(defun lsp-completion--get-documentation (item) - "Get doc comment for completion ITEM." - (unless (get-text-property 0 'lsp-completion-resolved item) - (let ((resolved-item - (-some->> item - (get-text-property 0 'lsp-completion-item) - (lsp-completion--resolve))) - (len (length item))) - (put-text-property 0 len 'lsp-completion-item resolved-item item) - (put-text-property 0 len 'lsp-completion-resolved t item))) - (-some->> item - (get-text-property 0 'lsp-completion-item) - (lsp:completion-item-documentation?) - (lsp--render-element))) - -(defun lsp-completion--get-context (trigger-characters same-session?) - "Get completion context with provided TRIGGER-CHARACTERS and SAME-SESSION?." - (let* ((triggered-by-char non-essential) - (trigger-char (when triggered-by-char - (lsp-completion--looking-back-trigger-characterp - trigger-characters))) - (trigger-kind (cond - (trigger-char - lsp/completion-trigger-kind-trigger-character) - ((and same-session? - (equal (cl-second lsp-completion--cache) :incomplete)) - lsp/completion-trigger-kind-trigger-for-incomplete-completions) - (t lsp/completion-trigger-kind-invoked)))) - (apply #'lsp-make-completion-context - (nconc - `(:trigger-kind ,trigger-kind) - (when trigger-char - `(:trigger-character? ,trigger-char)))))) - -(defun lsp-completion--sort-completions (completions) - "Sort COMPLETIONS." - (sort - completions - (-lambda ((&CompletionItem :sort-text? sort-text-left :label label-left) - (&CompletionItem :sort-text? sort-text-right :label label-right)) - (if (equal sort-text-left sort-text-right) - (string-lessp label-left label-right) - (string-lessp sort-text-left sort-text-right))))) - -;;;###autoload -(defun lsp-completion-at-point () - "Get lsp completions." - (when (or (--some (lsp--client-completion-in-comments? (lsp--workspace-client it)) - (lsp-workspaces)) - (not (nth 4 (syntax-ppss)))) - (let* ((trigger-chars (-> (lsp--capability-for-method "textDocument/completion") - (lsp:completion-options-trigger-characters?))) - (bounds-start (or (cl-first (bounds-of-thing-at-point 'symbol)) - (point))) - result done? - (candidates - (lambda () - (lsp--catch 'input - (let ((lsp--throw-on-input lsp-completion-use-last-result) - (same-session? (and lsp-completion--cache - ;; Special case for empty prefix and empty result - (or (cl-second lsp-completion--cache) - (not (string-empty-p - (plist-get (cddr lsp-completion--cache) :prefix)))) - (equal (cl-first lsp-completion--cache) bounds-start) - (s-prefix? - (plist-get (cddr lsp-completion--cache) :prefix) - (buffer-substring-no-properties bounds-start (point)))))) - (cond - ((or done? result) result) - ((and (not lsp-completion-no-cache) - same-session? - (listp (cl-second lsp-completion--cache))) - (setf result (apply #'lsp-completion--filter-candidates - (cdr lsp-completion--cache)))) - (t - (-let* ((resp (lsp-request-while-no-input - "textDocument/completion" - (plist-put (lsp--text-document-position-params) - :context (lsp-completion--get-context trigger-chars same-session?)))) - (completed (and resp - (not (and (lsp-completion-list? resp) - (lsp:completion-list-is-incomplete resp))))) - (items (lsp--while-no-input - (--> (cond - ((lsp-completion-list? resp) - (lsp:completion-list-items resp)) - (t resp)) - (if (or completed - (seq-some #'lsp:completion-item-sort-text? it)) - (lsp-completion--sort-completions it) - it) - (-map (lambda (item) - (lsp-put item - :_emacsStartPoint - (or (lsp-completion--guess-prefix item) - bounds-start))) - it)))) - (markers (list bounds-start (copy-marker (point) t))) - (prefix (buffer-substring-no-properties bounds-start (point))) - (lsp-completion--no-reordering (not lsp-completion-sort-initial-results))) - (lsp-completion--clear-cache same-session?) - (setf done? completed - lsp-completion--cache (list bounds-start - (cond - ((and done? (not (seq-empty-p items))) - (lsp-completion--to-internal items)) - ((not done?) :incomplete)) - :lsp-items nil - :markers markers - :prefix prefix) - result (lsp-completion--filter-candidates - (cond (done? - (cl-second lsp-completion--cache)) - (lsp-completion-filter-on-incomplete - (lsp-completion--to-internal items))) - :lsp-items items - :markers markers - :prefix prefix)))))) - (:interrupted lsp-completion--last-result) - (`,res (setq lsp-completion--last-result res)))))) - (list - bounds-start - (point) - (lambda (probe pred action) - (cond - ((eq action 'metadata) - '(metadata (category . lsp-capf) - (display-sort-function . identity) - (cycle-sort-function . identity))) - ((eq (car-safe action) 'boundaries) nil) - (t - (complete-with-action action (funcall candidates) probe pred)))) - :annotation-function #'lsp-completion--annotate - :company-kind #'lsp-completion--candidate-kind - :company-deprecated #'lsp-completion--candidate-deprecated - :company-require-match 'never - :company-prefix-length - (save-excursion - (let ( - ;; 2 is a heuristic number to make sure we look futher back than - ;; the bounds-start, which can be different from the actual start - ;; of the symbol - (bounds-left (max (line-beginning-position) (- bounds-start 2))) - triggered-by-char?) - (while (and (> (point) bounds-left) - (not (equal (char-after) ?\s)) - (not triggered-by-char?)) - (setq triggered-by-char? (lsp-completion--looking-back-trigger-characterp trigger-chars)) - (goto-char (1- (point)))) - (and triggered-by-char? t))) - :company-match #'lsp-completion--company-match - :company-doc-buffer (-compose #'lsp-doc-buffer - #'lsp-completion--get-documentation) - :exit-function - (-rpartial #'lsp-completion--exit-fn candidates))))) - -(defun lsp-completion--find-workspace (server-id) - (--first (eq (lsp--client-server-id (lsp--workspace-client it)) server-id) - (lsp-workspaces))) - -(defun lsp-completion--exit-fn (candidate _status &optional candidates) - "Exit function of `completion-at-point'. -CANDIDATE is the selected completion item. -Others: CANDIDATES" - (unwind-protect - (-let* ((candidate (if (plist-member (text-properties-at 0 candidate) - 'lsp-completion-item) - candidate - (cl-find candidate (funcall candidates) :test #'equal))) - ((&plist 'lsp-completion-item item - 'lsp-completion-start-point start-point - 'lsp-completion-markers markers - 'lsp-completion-resolved resolved - 'lsp-completion-prefix prefix) - (text-properties-at 0 candidate)) - ((&CompletionItem? :label :insert-text? :text-edit? :insert-text-format? - :additional-text-edits? :insert-text-mode? :command?) - ;; see #3498 typescript-language-server does not provide the - ;; proper insertText without resolving. - (if (and (lsp-completion--find-workspace 'ts-ls) - (not resolved)) - (lsp-completion--resolve item) - item))) - (cond - (text-edit? - (apply #'delete-region markers) - (insert prefix) - (pcase text-edit? - ((lsp-interface TextEdit) (lsp--apply-text-edit text-edit?)) - ((lsp-interface InsertReplaceEdit :insert :replace :new-text) - (lsp--apply-text-edit - (lsp-make-text-edit - :new-text new-text - :range (if (or (and current-prefix-arg (eq lsp-completion-default-behaviour :replace)) - (and (not current-prefix-arg) (eq lsp-completion-default-behaviour :insert))) - insert - replace)))))) - ((or (unless (lsp-falsy? insert-text?) insert-text?) label) - (apply #'delete-region markers) - (insert prefix) - (delete-region start-point (point)) - (insert (or (unless (lsp-falsy? insert-text?) insert-text?) label)))) - - (lsp--indent-lines start-point (point) insert-text-mode?) - (when (equal insert-text-format? lsp/insert-text-format-snippet) - (lsp--expand-snippet (buffer-substring start-point (point)) - start-point - (point))) - - (when lsp-completion-enable-additional-text-edit - (if (or (get-text-property 0 'lsp-completion-resolved candidate) - (not (seq-empty-p additional-text-edits?))) - (lsp--apply-text-edits additional-text-edits? 'completion) - (-let [(callback cleanup-fn) (lsp--create-apply-text-edits-handlers)] - (lsp-completion--resolve-async - item - (-compose callback #'lsp:completion-item-additional-text-edits?) - cleanup-fn)))) - - (if (or (get-text-property 0 'lsp-completion-resolved candidate) - command?) - (when command? (lsp--execute-command command?)) - (lsp-completion--resolve-async - item - (-lambda ((&CompletionItem? :command?)) - (when command? (lsp--execute-command command?))))) - - (when (and (or - (equal lsp-signature-auto-activate t) - (memq :after-completion lsp-signature-auto-activate) - (and (memq :on-trigger-char lsp-signature-auto-activate) - (-when-let ((&SignatureHelpOptions? :trigger-characters?) - (lsp--capability :signatureHelpProvider)) - (lsp-completion--looking-back-trigger-characterp - trigger-characters?)))) - (lsp-feature? "textDocument/signatureHelp")) - (lsp-signature-activate)) - - (setq-local lsp-inhibit-lsp-hooks nil)) - (lsp-completion--clear-cache))) - -(defun lsp-completion--regex-fuz (str) - "Build a regex sequence from STR. Insert .* between each char." - (apply #'concat - (cl-mapcar - #'concat - (cons "" (cdr (seq-map (lambda (c) (format "[^%c]*" c)) str))) - (seq-map (lambda (c) - (format "\\(%s\\)" (regexp-quote (char-to-string c)))) - str)))) - -(defun lsp-completion--fuz-score (query str) - "Calculate fuzzy score for STR with query QUERY. -The return is nil or in range of (0, inf)." - (-when-let* ((md (cddr (or (get-text-property 0 'match-data str) - (let ((re (lsp-completion--regex-fuz query))) - (when (string-match re str) - (match-data)))))) - (start (pop md)) - (len (length str)) - ;; To understand how this works, consider these bad ascii(tm) - ;; diagrams showing how the pattern "foo" flex-matches - ;; "fabrobazo", "fbarbazoo" and "barfoobaz": - - ;; f abr o baz o - ;; + --- + --- + - - ;; f barbaz oo - ;; + ------ ++ - - ;; bar foo baz - ;; --- +++ --- - - ;; "+" indicates parts where the pattern matched. A "hole" in - ;; the middle of the string is indicated by "-". Note that there - ;; are no "holes" near the edges of the string. The completion - ;; score is a number bound by ]0..1]: the higher the better and - ;; only a perfect match (pattern equals string) will have score - ;; 1. The formula takes the form of a quotient. For the - ;; numerator, we use the number of +, i.e. the length of the - ;; pattern. For the denominator, it first computes - ;; - ;; hole_i_contrib = 1 + (Li-1)^1.05 for first hole - ;; hole_i_contrib = 1 + (Li-1)^0.25 for hole i of length Li - ;; - ;; The final value for the denominator is then given by: - ;; - ;; (SUM_across_i(hole_i_contrib) + 1) - ;; - (score-numerator 0) - (score-denominator 0) - (last-b -1) - (q-ind 0) - (update-score - (lambda (a b) - "Update score variables given match range (A B)." - (setq score-numerator (+ score-numerator (- b a))) - (unless (= a len) - ;; case mismatch will be pushed to near next rank - (unless (equal (aref query q-ind) (aref str a)) - (cl-incf a 0.9)) - (setq score-denominator - (+ score-denominator - (if (= a last-b) 0 - (+ 1 (* (if (< 0 (- a last-b 1)) 1 -1) - (expt (abs (- a last-b 1)) - ;; Give a higher score for match near start - (if (eq last-b -1) 0.75 0.25)))))))) - (setq last-b b)))) - (while md - (funcall update-score start (cl-first md)) - ;; Due to the way completion regex is constructed, `(eq end (+ start 1))` - (cl-incf q-ind) - (pop md) - (setq start (pop md))) - (unless (zerop len) - (/ score-numerator (1+ score-denominator) 1.0)))) - -(defun lsp-completion--fix-resolve-data (item) - "Patch `CompletionItem' ITEM for rust-analyzer otherwise resolve will fail. -See #2675" - (let ((data (lsp:completion-item-data? item))) - (when (lsp-member? data :import_for_trait_assoc_item) - (unless (lsp-get data :import_for_trait_assoc_item) - (lsp-put data :import_for_trait_assoc_item :json-false))))) - -(defun lsp-completion--resolve (item) - "Resolve completion ITEM." - (cl-assert item nil "Completion item must not be nil") - (lsp-completion--fix-resolve-data item) - (or (ignore-errors - (when (lsp-feature? "completionItem/resolve") - (lsp-request "completionItem/resolve" - (lsp-delete (lsp-copy item) :_emacsStartPoint)))) - item)) - -(defun lsp-completion--resolve-async (item callback &optional cleanup-fn) - "Resolve completion ITEM asynchronously with CALLBACK. -The CLEANUP-FN will be called to cleanup." - (cl-assert item nil "Completion item must not be nil") - (lsp-completion--fix-resolve-data item) - (ignore-errors - (if (lsp-feature? "completionItem/resolve") - (lsp-request-async "completionItem/resolve" - (lsp-delete (lsp-copy item) :_emacsStartPoint) - (lambda (result) - (funcall callback result) - (when cleanup-fn (funcall cleanup-fn))) - :error-handler (lambda (err) - (when cleanup-fn (funcall cleanup-fn)) - (error (lsp:json-error-message err))) - :cancel-handler cleanup-fn - :mode 'alive) - (funcall callback item) - (when cleanup-fn (funcall cleanup-fn))))) - - -;;;###autoload -(defun lsp-completion--enable () - "Enable LSP completion support." - (when (and lsp-completion-enable - (lsp-feature? "textDocument/completion")) - (lsp-completion-mode 1))) - -(defun lsp-completion--disable () - "Disable LSP completion support." - (lsp-completion-mode -1)) - -(defun lsp-completion-passthrough-all-completions (_string table pred _point) - "Passthrough all completions from TABLE with PRED." - (defvar completion-lazy-hilit-fn) - (when (bound-and-true-p completion-lazy-hilit) - (setq completion-lazy-hilit-fn - (lambda (candidate) - (->> candidate - lsp-completion--company-match - (mapc (-lambda ((start . end)) - (put-text-property start end 'face 'completions-common-part candidate)))) - candidate))) - (all-completions "" table pred)) - -;;;###autoload -(define-minor-mode lsp-completion-mode - "Toggle LSP completion support." - :group 'lsp-completion - :global nil - :lighter "" - (let ((completion-started-fn (lambda (&rest _) - (setq-local lsp-inhibit-lsp-hooks t))) - (after-completion-fn (lambda (result) - (when (stringp result) - (lsp-completion--clear-cache)) - (setq-local lsp-inhibit-lsp-hooks nil)))) - (cond - (lsp-completion-mode - (make-local-variable 'completion-at-point-functions) - ;; Ensure that `lsp-completion-at-point' the first CAPF to be tried, - ;; unless user has put it elsewhere in the list by their own - (add-to-list 'completion-at-point-functions #'lsp-completion-at-point) - (make-local-variable 'completion-category-defaults) - (setf (alist-get 'lsp-capf completion-category-defaults) '((styles . (lsp-passthrough)))) - (make-local-variable 'completion-styles-alist) - (setf (alist-get 'lsp-passthrough completion-styles-alist) - '(completion-basic-try-completion - lsp-completion-passthrough-all-completions - "Passthrough completion.")) - - (cond - ((equal lsp-completion-provider :none)) - ((and (not (equal lsp-completion-provider :none)) - (fboundp 'company-mode)) - (setq-local company-abort-on-unique-match nil) - (company-mode 1) - (setq-local company-backends (cl-adjoin 'company-capf company-backends :test #'equal))) - (t - (lsp--warn "Unable to autoconfigure company-mode."))) - - (when (bound-and-true-p company-mode) - (add-hook 'company-completion-started-hook - completion-started-fn - nil - t) - (add-hook 'company-after-completion-hook - after-completion-fn - nil - t)) - (add-hook 'lsp-unconfigure-hook #'lsp-completion--disable nil t)) - (t - (remove-hook 'completion-at-point-functions #'lsp-completion-at-point t) - (setq-local completion-category-defaults - (cl-remove 'lsp-capf completion-category-defaults :key #'cl-first)) - (setq-local completion-styles-alist - (cl-remove 'lsp-passthrough completion-styles-alist :key #'cl-first)) - (remove-hook 'lsp-unconfigure-hook #'lsp-completion--disable t) - (when (featurep 'company) - (remove-hook 'company-completion-started-hook - completion-started-fn - t) - (remove-hook 'company-after-completion-hook - after-completion-fn - t)))))) - -;;;###autoload -(add-hook 'lsp-configure-hook (lambda () - (when (and lsp-auto-configure - lsp-completion-enable) - (lsp-completion--enable)))) - -(lsp-consistency-check lsp-completion) - -(provide 'lsp-completion) -;;; lsp-completion.el ends here diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-completion.elc b/emacs/elpa/lsp-mode-20241003.636/lsp-completion.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-mode-pkg.el b/emacs/elpa/lsp-mode-20241003.636/lsp-mode-pkg.el @@ -1,15 +0,0 @@ -;; -*- no-byte-compile: t; lexical-binding: nil -*- -(define-package "lsp-mode" "20241003.636" - "LSP mode." - '((emacs "27.1") - (dash "2.18.0") - (f "0.20.0") - (ht "2.3") - (spinner "1.7.3") - (markdown-mode "2.3") - (lv "0") - (eldoc "1.11")) - :url "https://github.com/emacs-lsp/lsp-mode" - :commit "52de586352de237951ee4cdd4a1351fa97e10c63" - :revdesc "52de586352de" - :keywords '("languages")) diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-mode.el b/emacs/elpa/lsp-mode-20241003.636/lsp-mode.el @@ -1,9917 +0,0 @@ -;;; lsp-mode.el --- LSP mode -*- lexical-binding: t; -*- - -;; Copyright (C) 2020-2024 emacs-lsp maintainers - -;; Author: Vibhav Pant, Fangrui Song, Ivan Yonchovski -;; Keywords: languages -;; Package-Requires: ((emacs "27.1") (dash "2.18.0") (f "0.20.0") (ht "2.3") (spinner "1.7.3") (markdown-mode "2.3") (lv "0") (eldoc "1.11")) -;; Package-Version: 20241003.636 -;; Package-Revision: 52de586352de - -;; URL: https://github.com/emacs-lsp/lsp-mode -;; This program is free software; you can redistribute it and/or modify -;; it under the terms of the GNU General Public License as published by -;; the Free Software Foundation, either version 3 of the License, or -;; (at your option) any later version. - -;; This program is distributed in the hope that it will be useful, -;; but WITHOUT ANY WARRANTY; without even the implied warranty of -;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -;; GNU General Public License for more details. - -;; You should have received a copy of the GNU General Public License -;; along with this program. If not, see <https://www.gnu.org/licenses/>. - -;;; Commentary: - -;; Emacs client/library for the Language Server Protocol - -;;; Code: - -(require 'cl-generic) -(require 'cl-lib) -(require 'compile) -(require 'dash) -(require 'epg) -(require 'ewoc) -(require 'f) -(require 'filenotify) -(require 'files) -(require 'ht) -(require 'imenu) -(require 'inline) -(require 'json) -(require 'lv) -(require 'markdown-mode) -(require 'network-stream) -(require 'pcase) -(require 'rx) -(require 's) -(require 'seq) -(require 'spinner) -(require 'subr-x) -(require 'tree-widget) -(require 'url-parse) -(require 'url-util) -(require 'widget) -(require 'xref) -(require 'minibuffer) -(require 'help-mode) -(require 'lsp-protocol) - -(defgroup lsp-mode nil - "Language Server Protocol client." - :group 'tools - :tag "Language Server (lsp-mode)") - -(declare-function evil-set-command-property "ext:evil-common") -(declare-function projectile-project-root "ext:projectile") -(declare-function yas-expand-snippet "ext:yasnippet") -(declare-function dap-mode "ext:dap-mode") -(declare-function dap-auto-configure-mode "ext:dap-mode") - -(defvar yas-inhibit-overlay-modification-protection) -(defvar yas-indent-line) -(defvar yas-wrap-around-region) -(defvar yas-also-auto-indent-first-line) -(defvar dap-auto-configure-mode) -(defvar dap-ui-menu-items) -(defvar company-minimum-prefix-length) - -(defconst lsp--message-type-face - `((1 . ,compilation-error-face) - (2 . ,compilation-warning-face) - (3 . ,compilation-message-face) - (4 . ,compilation-info-face))) - -(defconst lsp--errors - '((-32700 "Parse Error") - (-32600 "Invalid Request") - (-32601 "Method not Found") - (-32602 "Invalid Parameters") - (-32603 "Internal Error") - (-32099 "Server Start Error") - (-32000 "Server End Error") - (-32002 "Server Not Initialized") - (-32001 "Unknown Error Code") - (-32800 "Request Cancelled")) - "Alist of error codes to user friendly strings.") - -(defconst lsp--empty-ht (make-hash-table)) - -(eval-and-compile - (defun dash-expand:&lsp-wks (key source) - `(,(intern-soft (format "lsp--workspace-%s" (eval key))) ,source)) - - (defun dash-expand:&lsp-cln (key source) - `(,(intern-soft (format "lsp--client-%s" (eval key))) ,source))) - -(define-obsolete-variable-alias 'lsp-print-io 'lsp-log-io "lsp-mode 6.1") - -(defcustom lsp-log-io nil - "If non-nil, log all messages from the language server to a *lsp-log* buffer." - :group 'lsp-mode - :type 'boolean) - -(defcustom lsp-log-io-allowlist-methods '() - "The methods to filter before print to lsp-log-io." - :group 'lsp-mode - :type '(repeat string) - :package-version '(lsp-mode . "9.0.0")) - -(defcustom lsp-log-max message-log-max - "Maximum number of lines to keep in the log buffer. -If nil, disable message logging. If t, log messages but don’t truncate -the buffer when it becomes large." - :group 'lsp-mode - :type '(choice (const :tag "Disable" nil) - (integer :tag "lines") - (const :tag "Unlimited" t)) - :package-version '(lsp-mode . "6.1")) - -(defcustom lsp-io-messages-max t - "Maximum number of messages that can be locked in a `lsp-io' buffer." - :group 'lsp-mode - :type '(choice (const :tag "Unlimited" t) - (integer :tag "Messages")) - :package-version '(lsp-mode . "6.1")) - -(defcustom lsp-keep-workspace-alive t - "If non nil keep workspace alive when the last workspace buffer is closed." - :group 'lsp-mode - :type 'boolean) - -(defcustom lsp-enable-snippet t - "Enable/disable snippet completion support." - :group 'lsp-completion - :type 'boolean) - -(defcustom lsp-enable-folding t - "Enable/disable code folding support." - :group 'lsp-mode - :type 'boolean - :package-version '(lsp-mode . "6.1")) - -(define-obsolete-variable-alias 'lsp-enable-semantic-highlighting 'lsp-semantic-tokens-enable "lsp-mode 8.0.0") - -(defcustom lsp-semantic-tokens-enable nil - "Enable/disable support for semantic tokens. -As defined by the Language Server Protocol 3.16." - :group 'lsp-semantic-tokens - :type 'boolean) - -(defcustom lsp-folding-range-limit nil - "The maximum number of folding ranges to receive from the language server." - :group 'lsp-mode - :type '(choice (const :tag "No limit." nil) - (integer :tag "Number of lines.")) - :package-version '(lsp-mode . "6.1")) - -(defcustom lsp-folding-line-folding-only nil - "If non-nil, only fold complete lines." - :group 'lsp-mode - :type 'boolean - :package-version '(lsp-mode . "6.1")) - -(defcustom lsp-client-packages - '( ccls lsp-actionscript lsp-ada lsp-angular lsp-ansible lsp-asm lsp-astro - lsp-autotools lsp-awk lsp-bash lsp-beancount lsp-bufls lsp-clangd - lsp-clojure lsp-cmake lsp-cobol lsp-credo lsp-crystal lsp-csharp lsp-css - lsp-cucumber lsp-cypher lsp-d lsp-dart lsp-dhall lsp-docker lsp-dockerfile - lsp-earthly lsp-elixir lsp-elm lsp-emmet lsp-erlang lsp-eslint lsp-fortran lsp-futhark - lsp-fsharp lsp-gdscript lsp-gleam lsp-glsl lsp-go lsp-golangci-lint lsp-grammarly - lsp-graphql lsp-groovy lsp-hack lsp-haskell lsp-haxe lsp-idris lsp-java - lsp-javascript lsp-jq lsp-json lsp-kotlin lsp-latex lsp-lisp lsp-ltex - lsp-lua lsp-magik lsp-markdown lsp-marksman lsp-mdx lsp-meson lsp-metals lsp-mint - lsp-mojo lsp-move lsp-mssql lsp-nginx lsp-nim lsp-nix lsp-nushell lsp-ocaml - lsp-openscad lsp-pascal lsp-perl lsp-perlnavigator lsp-php lsp-pls - lsp-purescript lsp-pwsh lsp-pyls lsp-pylsp lsp-pyright lsp-python-ms - lsp-qml lsp-r lsp-racket lsp-remark lsp-rf lsp-roslyn lsp-rubocop lsp-ruby-lsp - lsp-ruby-syntax-tree lsp-ruff lsp-rust lsp-semgrep lsp-shader - lsp-solargraph lsp-solidity lsp-sonarlint lsp-sorbet lsp-sourcekit - lsp-sql lsp-sqls lsp-steep lsp-svelte lsp-tailwindcss lsp-terraform - lsp-tex lsp-tilt lsp-toml lsp-trunk lsp-ttcn3 lsp-typeprof lsp-v - lsp-vala lsp-verilog lsp-vetur lsp-vhdl lsp-vimscript lsp-volar lsp-wgsl - lsp-xml lsp-yaml lsp-yang lsp-zig) - "List of the clients to be automatically required." - :group 'lsp-mode - :type '(repeat symbol)) - -(defcustom lsp-progress-via-spinner t - "If non-nil, display LSP $/progress reports via a spinner in the modeline." - :group 'lsp-mode - :type 'boolean) - -(defcustom lsp-progress-spinner-type 'progress-bar - "Holds the type of spinner to be used in the mode-line. -Takes a value accepted by `spinner-start'." - :group 'lsp-mode - :type `(choice :tag "Choose a spinner by name" - ,@(mapcar (lambda (c) (list 'const (car c))) - spinner-types))) - -(defvar-local lsp-use-workspace-root-for-server-default-directory nil - "Use `lsp-workspace-root' for `default-directory' when starting LSP process.") - -(defvar-local lsp--cur-workspace nil) - -(defvar-local lsp--cur-version 0) -(defvar-local lsp--virtual-buffer-connections nil) -(defvar-local lsp--virtual-buffer nil) -(defvar lsp--virtual-buffer-mappings (ht)) - -(defvar lsp--uri-file-prefix (pcase system-type - (`windows-nt "file:///") - (_ "file://")) - "Prefix for a file-uri.") - -(defvar-local lsp-buffer-uri nil - "If set, return it instead of calculating it using `buffer-file-name'.") - -(define-error 'lsp-error "Unknown lsp-mode error") -(define-error 'lsp-empty-response-error - "Empty response from the language server" 'lsp-error) -(define-error 'lsp-timed-out-error - "Timed out while waiting for a response from the language server" 'lsp-error) -(define-error 'lsp-capability-not-supported - "Capability not supported by the language server" 'lsp-error) -(define-error 'lsp-file-scheme-not-supported - "Unsupported file scheme" 'lsp-error) -(define-error 'lsp-client-already-exists-error - "A client with this server-id already exists" 'lsp-error) -(define-error 'lsp-no-code-actions - "No code actions" 'lsp-error) - -(defcustom lsp-auto-guess-root nil - "Automatically guess the project root using projectile/project. -Do *not* use this setting unless you are familiar with `lsp-mode' -internals and you are sure that all of your projects are -following `projectile'/`project.el' conventions." - :group 'lsp-mode - :type 'boolean) - -(defcustom lsp-guess-root-without-session nil - "Ignore the session file when calculating the project root. -You almost always want to set lsp-auto-guess-root too. -Do *not* use this setting unless you are familiar with `lsp-mode' -internals and you are sure that all of your projects are -following `projectile'/`project.el' conventions." - :group 'lsp-mode - :type 'boolean) - -(defcustom lsp-restart 'interactive - "Defines how server-exited events must be handled." - :group 'lsp-mode - :type '(choice (const interactive) - (const auto-restart) - (const ignore))) - -(defcustom lsp-session-file (expand-file-name (locate-user-emacs-file ".lsp-session-v1")) - "File where session information is stored." - :group 'lsp-mode - :type 'file) - -(defcustom lsp-auto-configure t - "Auto configure `lsp-mode' main features. -When set to t `lsp-mode' will auto-configure completion, -code-actions, breadcrumb, `flycheck', `flymake', `imenu', symbol highlighting, -lenses, links, and so on. - -For finer granularity you may use `lsp-enable-*' properties." - :group 'lsp-mode - :type 'boolean - :package-version '(lsp-mode . "6.1")) - -(defcustom lsp-disabled-clients nil - "A list of disabled/blocklisted clients. -Each entry in the list can be either: -a symbol, the server-id for the LSP client, or -a cons pair (MAJOR-MODE . CLIENTS), where MAJOR-MODE is the major-mode, -and CLIENTS is either a client or a list of clients. - -This option can also be used as a file- or directory-local variable to -disable a language server for individual files or directories/projects -respectively." - :group 'lsp-mode - :type '(repeat (symbol)) - :safe 'listp - :package-version '(lsp-mode . "6.1")) - -(defvar lsp-clients (make-hash-table :test 'eql) - "Hash table server-id -> client. -It contains all of the clients that are currently registered.") - -(defvar lsp-enabled-clients nil - "List of clients allowed to be used for projects. -When nil, all registered clients are considered candidates.") - -(defvar lsp-last-id 0 - "Last request id.") - -(defcustom lsp-before-initialize-hook nil - "List of functions to be called before a Language Server has been initialized -for a new workspace." - :type 'hook - :group 'lsp-mode) - -(defcustom lsp-after-initialize-hook nil - "List of functions to be called after a Language Server has been initialized -for a new workspace." - :type 'hook - :group 'lsp-mode) - -(defcustom lsp-before-open-hook nil - "List of functions to be called before a new file with LSP support is opened." - :type 'hook - :group 'lsp-mode) - -(defcustom lsp-after-open-hook nil - "List of functions to be called after a new file with LSP support is opened." - :type 'hook - :group 'lsp-mode) - -(defcustom lsp-enable-file-watchers t - "If non-nil lsp-mode will watch the files in the workspace if -the server has requested that." - :type 'boolean - :group 'lsp-mode - :package-version '(lsp-mode . "6.1")) -;;;###autoload(put 'lsp-enable-file-watchers 'safe-local-variable #'booleanp) - -(define-obsolete-variable-alias 'lsp-file-watch-ignored 'lsp-file-watch-ignored-directories "8.0.0") - -(defcustom lsp-file-watch-ignored-directories - '(; SCM tools - "[/\\\\]\\.git\\'" - "[/\\\\]\\.github\\'" - "[/\\\\]\\.gitlab\\'" - "[/\\\\]\\.circleci\\'" - "[/\\\\]\\.hg\\'" - "[/\\\\]\\.bzr\\'" - "[/\\\\]_darcs\\'" - "[/\\\\]\\.svn\\'" - "[/\\\\]_FOSSIL_\\'" - ;; IDE or build tools - "[/\\\\]\\.idea\\'" - "[/\\\\]\\.ensime_cache\\'" - "[/\\\\]\\.eunit\\'" - "[/\\\\]node_modules" - "[/\\\\]\\.yarn\\'" - "[/\\\\]\\.fslckout\\'" - "[/\\\\]\\.tox\\'" - "[/\\\\]\\.nox\\'" - "[/\\\\]dist\\'" - "[/\\\\]dist-newstyle\\'" - "[/\\\\]\\.stack-work\\'" - "[/\\\\]\\.bloop\\'" - "[/\\\\]\\.metals\\'" - "[/\\\\]target\\'" - "[/\\\\]\\.ccls-cache\\'" - "[/\\\\]\\.vs\\'" - "[/\\\\]\\.vscode\\'" - "[/\\\\]\\.venv\\'" - "[/\\\\]\\.mypy_cache\\'" - "[/\\\\]\\.pytest_cache\\'" - ;; Swift Package Manager - "[/\\\\]\\.build\\'" - ;; Python - "[/\\\\]__pycache__\\'" - ;; Autotools output - "[/\\\\]\\.deps\\'" - "[/\\\\]build-aux\\'" - "[/\\\\]autom4te.cache\\'" - "[/\\\\]\\.reference\\'" - ;; Bazel - "[/\\\\]bazel-[^/\\\\]+\\'" - ;; CSharp - "[/\\\\]\\.cache[/\\\\]lsp-csharp\\'" - "[/\\\\]\\.meta\\'" - "[/\\\\]\\.nuget\\'" - ;; Unity - "[/\\\\]Library\\'" - ;; Clojure - "[/\\\\]\\.lsp\\'" - "[/\\\\]\\.clj-kondo\\'" - "[/\\\\]\\.shadow-cljs\\'" - "[/\\\\]\\.babel_cache\\'" - "[/\\\\]\\.cpcache\\'" - "[/\\\\]\\checkouts\\'" - ;; Gradle - "[/\\\\]\\.gradle\\'" - ;; Maven - "[/\\\\]\\.m2\\'" - ;; .Net Core build-output - "[/\\\\]bin/Debug\\'" - "[/\\\\]obj\\'" - ;; OCaml and Dune - "[/\\\\]_opam\\'" - "[/\\\\]_build\\'" - ;; Elixir - "[/\\\\]\\.elixir_ls\\'" - ;; Elixir Credo - "[/\\\\]\\.elixir-tools\\'" - ;; terraform and terragrunt - "[/\\\\]\\.terraform\\'" - "[/\\\\]\\.terragrunt-cache\\'" - ;; nix-direnv - "[/\\\\]\\result" - "[/\\\\]\\result-bin" - "[/\\\\]\\.direnv\\'") - "List of regexps matching directory paths which won't be monitored when -creating file watches. Customization of this variable is only honored at -the global level or at a root of an lsp workspace." - :group 'lsp-mode - :type '(repeat string) - :package-version '(lsp-mode . "8.0.0")) - -(define-obsolete-function-alias 'lsp-file-watch-ignored 'lsp-file-watch-ignored-directories "7.0.1") - -(defun lsp-file-watch-ignored-directories () - lsp-file-watch-ignored-directories) - -;; Allow lsp-file-watch-ignored-directories as a file or directory-local variable -;;;###autoload(put 'lsp-file-watch-ignored-directories 'safe-local-variable 'lsp--string-listp) - -(defcustom lsp-file-watch-ignored-files - '( - ;; Flycheck tempfiles - "[/\\\\]flycheck_[^/\\\\]+\\'" - ;; lockfiles - "[/\\\\]\\.#[^/\\\\]+\\'" - ;; backup files - "[/\\\\][^/\\\\]+~\\'" ) - "List of regexps matching files for which change events will -not be sent to the server. - -This setting has no impact on whether a file-watch is created for -a directory; it merely prevents notifications pertaining to -matched files from being sent to the server. To prevent a -file-watch from being created for a directory, customize -`lsp-file-watch-ignored-directories' - -Customization of this variable is only honored at the global -level or at a root of an lsp workspace." - :group 'lsp-mode - :type '(repeat string) - :package-version '(lsp-mode . "8.0.0")) - -;; Allow lsp-file-watch-ignored-files as a file or directory-local variable -;;;###autoload(put 'lsp-file-watch-ignored-files 'safe-local-variable 'lsp--string-listp) - -(defcustom lsp-after-uninitialized-functions nil - "List of functions to be called after a Language Server has been uninitialized." - :type 'hook - :group 'lsp-mode - :package-version '(lsp-mode . "6.3")) - -(defconst lsp--sync-full 1) -(defconst lsp--sync-incremental 2) - -(defcustom lsp-debounce-full-sync-notifications t - "If non-nil debounce full sync events. -This flag affects only servers which do not support incremental updates." - :type 'boolean - :group 'lsp-mode - :package-version '(lsp-mode . "6.1")) - -(defcustom lsp-debounce-full-sync-notifications-interval 1.0 - "Time to wait before sending full sync synchronization after buffer modification." - :type 'float - :group 'lsp-mode - :package-version '(lsp-mode . "6.1")) - -(defvar lsp--stderr-index 0) - -(defvar lsp--delayed-requests nil) -(defvar lsp--delay-timer nil) - -(defcustom lsp-document-sync-method nil - "How to sync the document with the language server." - :type '(choice (const :tag "Documents are synced by always sending the full content of the document." lsp--sync-full) - (const :tag "Documents are synced by always sending incremental changes to the document." lsp--sync-incremental) - (const :tag "Use the method recommended by the language server." nil)) - :group 'lsp-mode) - -(defcustom lsp-auto-execute-action t - "Auto-execute single action." - :type 'boolean - :group 'lsp-mode) - -(defcustom lsp-enable-links t - "If non-nil, all references to links in a file will be made clickable, if -supported by the language server." - :type 'boolean - :group 'lsp-mode - :package-version '(lsp-mode . "6.1")) - -(defcustom lsp-enable-imenu t - "If non-nil, automatically enable `imenu' integration when server provides -`textDocument/documentSymbol'." - :type 'boolean - :group 'lsp-mode - :package-version '(lsp-mode . "6.2")) - -(defcustom lsp-enable-dap-auto-configure t - "If non-nil, enable `dap-auto-configure-mode`." - :type 'boolean - :group 'lsp-mode - :package-version '(lsp-mode . "7.0")) - -(defcustom lsp-eldoc-enable-hover t - "If non-nil, `eldoc' will display hover info when it is present." - :type 'boolean - :group 'lsp-mode) - -(defcustom lsp-eldoc-render-all nil - "Display all of the info returned by document/onHover. -If this is set to nil, `eldoc' will show only the symbol information." - :type 'boolean - :group 'lsp-mode) - -(define-obsolete-variable-alias 'lsp-enable-completion-at-point - 'lsp-completion-enable "lsp-mode 7.0.1") - -(defcustom lsp-completion-enable t - "Enable `completion-at-point' integration." - :type 'boolean - :group 'lsp-completion) - -(defcustom lsp-enable-symbol-highlighting t - "Highlight references of the symbol at point." - :type 'boolean - :group 'lsp-mode) - -(defcustom lsp-enable-xref t - "Enable xref integration." - :type 'boolean - :group 'lsp-mode) - -(defcustom lsp-references-exclude-definition nil - "If non-nil, exclude declarations when finding references." - :type 'boolean - :group 'lsp-mode) - -(defcustom lsp-enable-indentation t - "Indent regions using the file formatting functionality provided by the -language server." - :type 'boolean - :group 'lsp-mode) - -(defcustom lsp-enable-on-type-formatting t - "Enable `textDocument/onTypeFormatting' integration." - :type 'boolean - :group 'lsp-mode) - -(defcustom lsp-enable-text-document-color t - "Enable `textDocument/documentColor' integration." - :type 'boolean - :group 'lsp-mode) - -(defcustom lsp-before-save-edits t - "If non-nil, `lsp-mode' will apply edits suggested by the language server -before saving a document." - :type 'boolean - :group 'lsp-mode) - -(defcustom lsp-after-apply-edits-hook nil - "Hooks to run when text edit is applied. -It contains the operation source." - :type 'hook - :group 'lsp-mode - :package-version '(lsp-mode . "8.0.0")) - -(defcustom lsp-apply-edits-after-file-operations t - "Whether to apply edits returned by server after file operations if any. -Applicable only if server supports workspace.fileOperations for operations: -`workspace/willRenameFiles', `workspace/willCreateFiles' and -`workspace/willDeleteFiles'." - :group 'lsp-mode - :type 'boolean) - -(defcustom lsp-modeline-code-actions-enable t - "Whether to show code actions on modeline." - :type 'boolean - :group 'lsp-modeline) - -(defcustom lsp-modeline-diagnostics-enable t - "Whether to show diagnostics on modeline." - :type 'boolean - :group 'lsp-modeline) - -(defcustom lsp-modeline-workspace-status-enable t - "Whether to show workspace status on modeline." - :type 'boolean - :group 'lsp-modeline - :package-version '(lsp-mode . "8.0.0")) - -(defcustom lsp-headerline-breadcrumb-enable t - "Whether to enable breadcrumb on headerline." - :type 'boolean - :group 'lsp-headerline) - -(defcustom lsp-configure-hook nil - "Hooks to run when `lsp-configure-buffer' is called." - :type 'hook - :group 'lsp-mode) - -(defcustom lsp-unconfigure-hook nil - "Hooks to run when `lsp-unconfig-buffer' is called." - :type 'hook - :group 'lsp-mode) - -(defcustom lsp-after-diagnostics-hook nil - "Hooks to run after diagnostics are received. -Note: it runs only if the receiving buffer is open. Use -`lsp-diagnostics-updated-hook'if you want to be notified when -diagnostics have changed." - :type 'hook - :group 'lsp-mode) - -(define-obsolete-variable-alias 'lsp-after-diagnostics-hook - 'lsp-diagnostics-updated-hook "lsp-mode 6.4") - -(defcustom lsp-diagnostics-updated-hook nil - "Hooks to run after diagnostics are received." - :type 'hook - :group 'lsp-mode) - -(define-obsolete-variable-alias 'lsp-workspace-folders-changed-hook - 'lsp-workspace-folders-changed-functions "lsp-mode 6.3") - -(defcustom lsp-workspace-folders-changed-functions nil - "Hooks to run after the folders has changed. -The hook will receive two parameters list of added and removed folders." - :type 'hook - :group 'lsp-mode) - -(define-obsolete-variable-alias 'lsp-eldoc-hook 'eldoc-documentation-functions "lsp-mode 9.0.0") - -(defcustom lsp-before-apply-edits-hook nil - "Hooks to run before applying edits." - :type 'hook - :group 'lsp-mode) - -(defgroup lsp-imenu nil - "LSP Imenu." - :group 'lsp-mode - :tag "LSP Imenu") - -(defcustom lsp-imenu-show-container-name t - "Display the symbol's container name in an imenu entry." - :type 'boolean - :group 'lsp-imenu) - -(defcustom lsp-imenu-container-name-separator "/" - "Separator string to use to separate the container name from the symbol while -displaying imenu entries." - :type 'string - :group 'lsp-imenu) - -(defcustom lsp-imenu-sort-methods '(kind name) - "How to sort the imenu items. - -The value is a list of `kind' `name' or `position'. Priorities -are determined by the index of the element." - :type '(repeat (choice (const name) - (const position) - (const kind))) - :group 'lsp-imenu) - -(defcustom lsp-imenu-index-symbol-kinds nil - "Which symbol kinds to show in imenu." - :type '(repeat (choice (const :tag "Miscellaneous" nil) - (const :tag "File" File) - (const :tag "Module" Module) - (const :tag "Namespace" Namespace) - (const :tag "Package" Package) - (const :tag "Class" Class) - (const :tag "Method" Method) - (const :tag "Property" Property) - (const :tag "Field" Field) - (const :tag "Constructor" Constructor) - (const :tag "Enum" Enum) - (const :tag "Interface" Interface) - (const :tag "Function" Function) - (const :tag "Variable" Variable) - (const :tag "Constant" Constant) - (const :tag "String" String) - (const :tag "Number" Number) - (const :tag "Boolean" Boolean) - (const :tag "Array" Array) - (const :tag "Object" Object) - (const :tag "Key" Key) - (const :tag "Null" Null) - (const :tag "Enum Member" EnumMember) - (const :tag "Struct" Struct) - (const :tag "Event" Event) - (const :tag "Operator" Operator) - (const :tag "Type Parameter" TypeParameter))) - :group 'lsp-imenu) - -;; vibhavp: Should we use a lower value (5)? -(defcustom lsp-response-timeout 10 - "Number of seconds to wait for a response from the language server before -timing out. Nil if no timeout." - :type '(choice - (number :tag "Seconds") - (const :tag "No timeout" nil)) - :group 'lsp-mode) - -(defcustom lsp-tcp-connection-timeout 2 - "The timeout for tcp connection in seconds." - :type 'number - :group 'lsp-mode - :package-version '(lsp-mode . "6.2")) - -(defconst lsp--imenu-compare-function-alist - (list (cons 'name #'lsp--imenu-compare-name) - (cons 'kind #'lsp--imenu-compare-kind) - (cons 'position #'lsp--imenu-compare-line-col)) - "An alist of (METHOD . FUNCTION). -METHOD is one of the symbols accepted by -`lsp-imenu-sort-methods'. - -FUNCTION takes two hash tables representing DocumentSymbol. It -returns a negative number, 0, or a positive number indicating -whether the first parameter is less than, equal to, or greater -than the second parameter.") - -(defcustom lsp-diagnostic-clean-after-change nil - "When non-nil, clean the diagnostics on change. - -Note that when that setting is nil, `lsp-mode' will show stale -diagnostics until server publishes the new set of diagnostics" - :type 'boolean - :group 'lsp-diagnostics - :package-version '(lsp-mode . "7.0.1")) - -(defcustom lsp-server-trace nil - "Request tracing on the server side. -The actual trace output at each level depends on the language server in use. -Changes take effect only when a new session is started." - :type '(choice (const :tag "Disabled" "off") - (const :tag "Messages only" "messages") - (const :tag "Verbose" "verbose") - (const :tag "Default (disabled)" nil)) - :group 'lsp-mode - :package-version '(lsp-mode . "6.1")) - -(defcustom lsp-auto-touch-files t - "If non-nil ensure the files exist before sending -`textDocument/didOpen' notification." - :type 'boolean - :group 'lsp-mode - :package-version '(lsp-mode . "9.0.0")) - -(defvar lsp-language-id-configuration - '(("\\(^CMakeLists\\.txt\\|\\.cmake\\)\\'" . "cmake") - ("\\(^Dockerfile\\(?:\\..*\\)?\\|\\.[Dd]ockerfile\\)\\'" . "dockerfile") - ("\\.astro$" . "astro") - ("\\.cs\\'" . "csharp") - ("\\.css$" . "css") - ("\\.cypher$" . "cypher") - ("Earthfile" . "earthfile") - ("\\.ebuild$" . "shellscript") - ("\\.go\\'" . "go") - ("\\.html$" . "html") - ("\\.hx$" . "haxe") - ("\\.hy$" . "hy") - ("\\.java\\'" . "java") - ("\\.jq$" . "jq") - ("\\.js$" . "javascript") - ("\\.json$" . "json") - ("\\.jsonc$" . "jsonc") - ("\\.jsonnet$" . "jsonnet") - ("\\.jsx$" . "javascriptreact") - ("\\.lua$" . "lua") - ("\\.mdx\\'" . "mdx") - ("\\.nu$" . "nushell") - ("\\.php$" . "php") - ("\\.ps[dm]?1\\'" . "powershell") - ("\\.rs\\'" . "rust") - ("\\.spec\\'" . "rpm-spec") - ("\\.sql$" . "sql") - ("\\.svelte$" . "svelte") - ("\\.toml\\'" . "toml") - ("\\.ts$" . "typescript") - ("\\.tsx$" . "typescriptreact") - ("\\.ttcn3$" . "ttcn3") - ("\\.vue$" . "vue") - ("\\.xml$" . "xml") - ("\\ya?ml$" . "yaml") - ("^PKGBUILD$" . "shellscript") - ("^go\\.mod\\'" . "go.mod") - ("^settings\\.json$" . "jsonc") - ("^yang\\.settings$" . "jsonc") - ("^meson\\(_options\\.txt\\|\\.\\(build\\|format\\)\\)\\'" . "meson") - (ada-mode . "ada") - (ada-ts-mode . "ada") - (gpr-mode . "gpr") - (gpr-ts-mode . "gpr") - (awk-mode . "awk") - (awk-ts-mode . "awk") - (nxml-mode . "xml") - (sql-mode . "sql") - (vimrc-mode . "vim") - (vimscript-ts-mode . "vim") - (sh-mode . "shellscript") - (bash-ts-mode . "shellscript") - (ebuild-mode . "shellscript") - (pkgbuild-mode . "shellscript") - (envrc-file-mode . "shellscript") - (scala-mode . "scala") - (scala-ts-mode . "scala") - (julia-mode . "julia") - (julia-ts-mode . "julia") - (clojure-mode . "clojure") - (clojurec-mode . "clojure") - (clojurescript-mode . "clojurescript") - (clojure-ts-mode . "clojure") - (clojure-ts-clojurec-mode . "clojure") - (clojure-ts-clojurescript-mode . "clojurescript") - (java-mode . "java") - (java-ts-mode . "java") - (jdee-mode . "java") - (groovy-mode . "groovy") - (python-mode . "python") - (python-ts-mode . "python") - (cython-mode . "python") - ("\\(\\.mojo\\|\\.🔥\\)\\'" . "mojo") - (lsp--render-markdown . "markdown") - (move-mode . "move") - (rust-mode . "rust") - (rust-ts-mode . "rust") - (rustic-mode . "rust") - (kotlin-mode . "kotlin") - (kotlin-ts-mode . "kotlin") - (css-mode . "css") - (css-ts-mode . "css") - (less-mode . "less") - (less-css-mode . "less") - (lua-mode . "lua") - (lua-ts-mode . "lua") - (sass-mode . "sass") - (ssass-mode . "sass") - (scss-mode . "scss") - (scad-mode . "openscad") - (xml-mode . "xml") - (c-mode . "c") - (c-ts-mode . "c") - (c++-mode . "cpp") - (c++-ts-mode . "cpp") - (cuda-mode . "cuda") - (objc-mode . "objective-c") - (html-mode . "html") - (html-ts-mode . "html") - (sgml-mode . "html") - (mhtml-mode . "html") - (mint-mode . "mint") - (go-dot-mod-mode . "go.mod") - (go-mod-ts-mode . "go.mod") - (go-mode . "go") - (go-ts-mode . "go") - (graphql-mode . "graphql") - (haskell-mode . "haskell") - (haskell-ts-mode . "haskell") - (hack-mode . "hack") - (php-mode . "php") - (php-ts-mode . "php") - (powershell-mode . "powershell") - (powershell-mode . "PowerShell") - (powershell-ts-mode . "powershell") - (json-mode . "json") - (json-ts-mode . "json") - (jsonc-mode . "jsonc") - (rjsx-mode . "javascript") - (js2-mode . "javascript") - (js-mode . "javascript") - (js-ts-mode . "javascript") - (typescript-mode . "typescript") - (typescript-ts-mode . "typescript") - (tsx-ts-mode . "typescriptreact") - (svelte-mode . "svelte") - (fsharp-mode . "fsharp") - (reason-mode . "reason") - (caml-mode . "ocaml") - (tuareg-mode . "ocaml") - (futhark-mode . "futhark") - (swift-mode . "swift") - (elixir-mode . "elixir") - (elixir-ts-mode . "elixir") - (heex-ts-mode . "elixir") - (conf-javaprop-mode . "spring-boot-properties") - (yaml-mode . "yaml") - (yaml-ts-mode . "yaml") - (ruby-mode . "ruby") - (enh-ruby-mode . "ruby") - (ruby-ts-mode . "ruby") - (feature-mode . "cucumber") - (fortran-mode . "fortran") - (f90-mode . "fortran") - (elm-mode . "elm") - (dart-mode . "dart") - (erlang-mode . "erlang") - (dockerfile-mode . "dockerfile") - (dockerfile-ts-mode . "dockerfile") - (csharp-mode . "csharp") - (csharp-tree-sitter-mode . "csharp") - (csharp-ts-mode . "csharp") - (plain-tex-mode . "plaintex") - (context-mode . "context") - (cypher-mode . "cypher") - (latex-mode . "latex") - (LaTeX-mode . "latex") - (v-mode . "v") - (vhdl-mode . "vhdl") - (vhdl-ts-mode . "vhdl") - (verilog-mode . "verilog") - (terraform-mode . "terraform") - (ess-julia-mode . "julia") - (ess-r-mode . "r") - (crystal-mode . "crystal") - (nim-mode . "nim") - (dhall-mode . "dhall") - (cmake-mode . "cmake") - (cmake-ts-mode . "cmake") - (purescript-mode . "purescript") - (gdscript-mode . "gdscript") - (gdscript-ts-mode . "gdscript") - (perl-mode . "perl") - (cperl-mode . "perl") - (robot-mode . "robot") - (racket-mode . "racket") - (nix-mode . "nix") - (nix-ts-mode . "nix") - (prolog-mode . "prolog") - (vala-mode . "vala") - (actionscript-mode . "actionscript") - (d-mode . "d") - (zig-mode . "zig") - (text-mode . "plaintext") - (markdown-mode . "markdown") - (gfm-mode . "markdown") - (beancount-mode . "beancount") - (conf-toml-mode . "toml") - (toml-ts-mode . "toml") - (org-mode . "org") - (org-journal-mode . "org") - (nginx-mode . "nginx") - (magik-mode . "magik") - (magik-ts-mode . "magik") - (idris-mode . "idris") - (idris2-mode . "idris2") - (gleam-mode . "gleam") - (gleam-ts-mode . "gleam") - (graphviz-dot-mode . "dot") - (tiltfile-mode . "tiltfile") - (solidity-mode . "solidity") - (bibtex-mode . "bibtex") - (rst-mode . "restructuredtext") - (glsl-mode . "glsl") - (shader-mode . "shaderlab") - (wgsl-mode . "wgsl") - (jq-mode . "jq") - (jq-ts-mode . "jq") - (protobuf-mode . "protobuf") - (nushell-mode . "nushell") - (nushell-ts-mode . "nushell") - (meson-mode . "meson") - (yang-mode . "yang")) - "Language id configuration.") - -(defvar lsp--last-active-workspaces nil - "Keep track of last active workspace. -We want to try the last workspace first when jumping into a library -directory") - -(defvar lsp-method-requirements - '(("textDocument/callHierarchy" :capability :callHierarchyProvider) - ("textDocument/codeAction" :capability :codeActionProvider) - ("codeAction/resolve" - :check-command (lambda (workspace) - (with-lsp-workspace workspace - (lsp:code-action-options-resolve-provider? - (lsp--capability-for-method "textDocument/codeAction"))))) - ("textDocument/codeLens" :capability :codeLensProvider) - ("textDocument/completion" :capability :completionProvider) - ("completionItem/resolve" - :check-command (lambda (wk) - (with-lsp-workspace wk - (lsp:completion-options-resolve-provider? - (lsp--capability-for-method "textDocument/completion"))))) - ("textDocument/declaration" :capability :declarationProvider) - ("textDocument/definition" :capability :definitionProvider) - ("textDocument/documentColor" :capability :colorProvider) - ("textDocument/documentLink" :capability :documentLinkProvider) - ("textDocument/inlayHint" :capability :inlayHintProvider) - ("textDocument/documentHighlight" :capability :documentHighlightProvider) - ("textDocument/documentSymbol" :capability :documentSymbolProvider) - ("textDocument/foldingRange" :capability :foldingRangeProvider) - ("textDocument/formatting" :capability :documentFormattingProvider) - ("textDocument/hover" :capability :hoverProvider) - ("textDocument/implementation" :capability :implementationProvider) - ("textDocument/linkedEditingRange" :capability :linkedEditingRangeProvider) - ("textDocument/onTypeFormatting" :capability :documentOnTypeFormattingProvider) - ("textDocument/prepareRename" - :check-command (lambda (workspace) - (with-lsp-workspace workspace - (lsp:rename-options-prepare-provider? - (lsp--capability-for-method "textDocument/rename"))))) - ("textDocument/rangeFormatting" :capability :documentRangeFormattingProvider) - ("textDocument/references" :capability :referencesProvider) - ("textDocument/rename" :capability :renameProvider) - ("textDocument/selectionRange" :capability :selectionRangeProvider) - ("textDocument/semanticTokens" :capability :semanticTokensProvider) - ("textDocument/semanticTokensFull" - :check-command (lambda (workspace) - (with-lsp-workspace workspace - (lsp-get (lsp--capability :semanticTokensProvider) :full)))) - ("textDocument/semanticTokensFull/Delta" - :check-command (lambda (workspace) - (with-lsp-workspace workspace - (let ((capFull (lsp-get (lsp--capability :semanticTokensProvider) :full))) - (and (not (booleanp capFull)) (lsp-get capFull :delta)))))) - ("textDocument/semanticTokensRangeProvider" - :check-command (lambda (workspace) - (with-lsp-workspace workspace - (lsp-get (lsp--capability :semanticTokensProvider) :range)))) - ("textDocument/signatureHelp" :capability :signatureHelpProvider) - ("textDocument/typeDefinition" :capability :typeDefinitionProvider) - ("textDocument/typeHierarchy" :capability :typeHierarchyProvider) - ("textDocument/diagnostic" :capability :diagnosticProvider) - ("workspace/executeCommand" :capability :executeCommandProvider) - ("workspace/symbol" :capability :workspaceSymbolProvider)) - - "Map methods to requirements. -It is used by request-sending functions to determine which server -must be used for handling a particular message.") - -(defconst lsp--file-change-type - `((created . 1) - (changed . 2) - (deleted . 3))) - -(defconst lsp--watch-kind - `((create . 1) - (change . 2) - (delete . 4))) - -(defvar lsp-window-body-width 40 - "Window body width when rendering doc.") - -(defface lsp-face-highlight-textual - '((t :inherit highlight)) - "Face used for textual occurrences of symbols." - :group 'lsp-mode) - -(defface lsp-face-highlight-read - '((t :inherit highlight :underline t)) - "Face used for highlighting symbols being read." - :group 'lsp-mode) - -(defface lsp-face-highlight-write - '((t :inherit highlight :weight bold)) - "Face used for highlighting symbols being written to." - :group 'lsp-mode) - -(define-obsolete-variable-alias 'lsp-lens-auto-enable - 'lsp-lens-enable "lsp-mode 7.0.1") - -(defcustom lsp-lens-enable t - "Auto enable lenses if server supports." - :group 'lsp-lens - :type 'boolean - :package-version '(lsp-mode . "6.3")) - -(defcustom lsp-symbol-highlighting-skip-current nil - "If non-nil skip current symbol when setting symbol highlights." - :group 'lsp-mode - :type 'boolean) - -(defcustom lsp-file-watch-threshold 1000 - "Show warning if the files to watch are more than. -Set to nil to disable the warning." - :type 'number - :group 'lsp-mode) -;;;###autoload(put 'lsp-file-watch-threshold 'safe-local-variable (lambda (i) (or (numberp i) (not i)))) - -(defvar lsp-custom-markup-modes - '((rust-mode "no_run" "rust,no_run" "rust,ignore" "rust,should_panic")) - "Mode to uses with markdown code blocks. -They are added to `markdown-code-lang-modes'") - -(defcustom lsp-signature-render-documentation t - "Display signature documentation in `eldoc'." - :type 'boolean - :group 'lsp-mode - :package-version '(lsp-mode . "6.2")) - -(defcustom lsp-signature-auto-activate '(:on-trigger-char :on-server-request) - "Auto activate signature conditions." - :type '(repeat (choice (const :tag "On trigger chars pressed." :on-trigger-char) - (const :tag "After selected completion." :after-completion) - (const :tag "When the server has sent show signature help." :on-server-request))) - :group 'lsp-mode - :package-version '(lsp-mode . "6.2")) - -(defcustom lsp-signature-doc-lines 20 - "If number, limit the number of lines to show in the docs." - :type 'number - :group 'lsp-mode - :package-version '(lsp-mode . "6.3")) - -(defcustom lsp-signature-function 'lsp-lv-message - "The function used for displaying signature info. -It will be called with one param - the signature info. When -called with nil the signature info must be cleared." - :type 'function - :group 'lsp-mode - :package-version '(lsp-mode . "6.3")) - -(defcustom lsp-keymap-prefix "s-l" - "LSP-mode keymap prefix." - :group 'lsp-mode - :type 'string - :package-version '(lsp-mode . "6.3")) - -(defvar-local lsp--buffer-workspaces () - "List of the buffer workspaces.") - -(defvar-local lsp--buffer-deferred nil - "Whether buffer was loaded via `lsp-deferred'.") - -(defvar lsp--session nil - "Contain the `lsp-session' for the current Emacs instance.") - -(defvar lsp--tcp-port 10000) - -(defvar lsp--client-packages-required nil - "If nil, `lsp-client-packages' are yet to be required.") - -(defvar lsp--tcp-server-port 0 - "The server socket which is opened when using `lsp-tcp-server' (a server -socket is opened in Emacs and the language server connects to it). The -default value of 0 ensures that a random high port is used. Set it to a positive -integer to use a specific port.") - -(defvar lsp--tcp-server-wait-seconds 10 - "Wait this amount of time for the client to connect to our server socket -when using `lsp-tcp-server'.") - -(defvar-local lsp--document-symbols nil - "The latest document symbols.") - -(defvar-local lsp--document-selection-range-cache nil - "The document selection cache.") - -(defvar-local lsp--document-symbols-request-async nil - "If non-nil, request document symbols asynchronously.") - -(defvar-local lsp--document-symbols-tick -1 - "The value of `buffer-chars-modified-tick' when document - symbols were last retrieved.") - -(defvar-local lsp--have-document-highlights nil - "Set to `t' on symbol highlighting, cleared on -`lsp--cleanup-highlights-if-needed'. Checking a separately -defined flag is substantially faster than unconditionally -calling `remove-overlays'.") - -;; Buffer local variable for storing number of lines. -(defvar lsp--log-lines) - -(defvar-local lsp--eldoc-saved-message nil) - -(defvar lsp--on-change-timer nil) -(defvar lsp--on-idle-timer nil) - -(defvar-local lsp--signature-last nil) -(defvar-local lsp--signature-last-index nil) -(defvar lsp--signature-last-buffer nil) - -(defvar-local lsp--virtual-buffer-point-max nil) - -(cl-defmethod lsp-execute-command (_server _command _arguments) - "Ask SERVER to execute COMMAND with ARGUMENTS.") - -(defun lsp-elt (sequence n) - "Return Nth element of SEQUENCE or nil if N is out of range." - (cond - ((listp sequence) (elt sequence n)) - ((arrayp sequence) - (and (> (length sequence) n) (aref sequence n))) - (t (and (> (length sequence) n) (elt sequence n))))) - -;; define seq-first and seq-rest for older emacs -(defun lsp-seq-first (sequence) - "Return the first element of SEQUENCE." - (lsp-elt sequence 0)) - -(defun lsp-seq-rest (sequence) - "Return a sequence of the elements of SEQUENCE except the first one." - (seq-drop sequence 1)) - -;;;###autoload -(defun lsp--string-listp (sequence) - "Return t if all elements of SEQUENCE are strings, else nil." - (not (seq-find (lambda (x) (not (stringp x))) sequence))) - -(defun lsp--string-vector-p (candidate) - "Returns true if CANDIDATE is a vector data structure and -every element of it is of type string, else nil." - (and - (vectorp candidate) - (seq-every-p #'stringp candidate))) - -(make-obsolete 'lsp--string-vector-p nil "lsp-mode 8.0.0") - -(defun lsp--editable-vector-match (widget value) - "Function for `lsp-editable-vector' :match." - ;; Value must be a list or a vector and all the members must match the type. - (and (or (listp value) (vectorp value)) - (length (cdr (lsp--editable-vector-match-inline widget value))))) - -(defun lsp--editable-vector-match-inline (widget value) - "Value for `lsp-editable-vector' :match-inline." - (let ((type (nth 0 (widget-get widget :args))) - (ok t) - found) - (while (and value ok) - (let ((answer (widget-match-inline type value))) - (if answer - (let ((head (if (vectorp answer) (aref answer 0) (car answer))) - (tail (if (vectorp answer) (seq-drop 1 answer) (cdr answer)))) - (setq found (append found head) - value tail)) - (setq ok nil)))) - (cons found value))) - -(defun lsp--editable-vector-value-to-external (_widget internal-value) - "Convert the internal list value to a vector." - (if (listp internal-value) - (apply 'vector internal-value) - internal-value)) - -(defun lsp--editable-vector-value-to-internal (_widget external-value) - "Convert the external vector value to a list." - (if (vectorp external-value) - (append external-value nil) - external-value)) - -(define-widget 'lsp--editable-vector 'editable-list - "A subclass of `editable-list' that accepts and returns a -vector instead of a list." - :value-to-external 'lsp--editable-vector-value-to-external - :value-to-internal 'lsp--editable-vector-value-to-internal - :match 'lsp--editable-vector-match - :match-inline 'lsp--editable-vector-match-inline) - -(define-widget 'lsp-repeatable-vector 'lsp--editable-vector - "A variable length homogeneous vector." - :tag "Repeat" - :format "%{%t%}:\n%v%i\n") - -(define-widget 'lsp-string-vector 'lazy - "A vector of zero or more elements, every element of which is a string. -Appropriate for any language-specific `defcustom' that needs to -serialize as a JSON array of strings. - -Deprecated. Use `lsp-repeatable-vector' instead. " - :offset 4 - :tag "Vector" - :type '(lsp-repeatable-vector string)) - -(make-obsolete 'lsp-string-vector nil "lsp-mode 8.0.0") - -(defvar lsp--show-message t - "If non-nil, show debug message from `lsp-mode'.") - -(defun lsp--message (format &rest args) - "Wrapper for `message' - -We `inhibit-message' the message when the cursor is in the -minibuffer and when emacs version is before emacs 27 due to the -fact that we often use `lsp--info', `lsp--warn' and `lsp--error' -in async context and the call to these function is removing the -minibuffer prompt. The issue with async messages is already fixed -in emacs 27. - -See #2049" - (when lsp--show-message - (let ((inhibit-message (or inhibit-message - (and (minibufferp) - (version< emacs-version "27.0"))))) - (apply #'message format args)))) - -(defun lsp--info (format &rest args) - "Display lsp info message with FORMAT with ARGS." - (lsp--message "%s :: %s" (propertize "LSP" 'face 'success) (apply #'format format args))) - -(defun lsp--warn (format &rest args) - "Display lsp warn message with FORMAT with ARGS." - (lsp--message "%s :: %s" (propertize "LSP" 'face 'warning) (apply #'format format args))) - -(defun lsp--error (format &rest args) - "Display lsp error message with FORMAT with ARGS." - (lsp--message "%s :: %s" (propertize "LSP" 'face 'error) (apply #'format format args))) - -(defun lsp-log (format &rest args) - "Log message to the ’*lsp-log*’ buffer. - -FORMAT and ARGS i the same as for `message'." - (when lsp-log-max - (let ((log-buffer (get-buffer "*lsp-log*")) - (inhibit-read-only t)) - (unless log-buffer - (setq log-buffer (get-buffer-create "*lsp-log*")) - (with-current-buffer log-buffer - (buffer-disable-undo) - (view-mode 1) - (set (make-local-variable 'lsp--log-lines) 0))) - (with-current-buffer log-buffer - (save-excursion - (let* ((message (apply 'format format args)) - ;; Count newlines in message. - (newlines (1+ (cl-loop with start = 0 - for count from 0 - while (string-match "\n" message start) - do (setq start (match-end 0)) - finally return count)))) - (goto-char (point-max)) - - ;; in case the buffer is not empty insert before last \n to preserve - ;; the point position(in case it is in the end) - (if (eq (point) (point-min)) - (progn - (insert "\n") - (backward-char)) - (backward-char) - (insert "\n")) - (insert message) - - (setq lsp--log-lines (+ lsp--log-lines newlines)) - - (when (and (integerp lsp-log-max) (> lsp--log-lines lsp-log-max)) - (let ((to-delete (- lsp--log-lines lsp-log-max))) - (goto-char (point-min)) - (forward-line to-delete) - (delete-region (point-min) (point)) - (setq lsp--log-lines lsp-log-max))))))))) - -(defalias 'lsp-message 'lsp-log) - -(defalias 'lsp-ht 'ht) - -(defalias 'lsp-file-local-name 'file-local-name) - -(defun lsp-f-canonical (file-name) - "Return the canonical FILE-NAME, without a trailing slash." - (directory-file-name (expand-file-name file-name))) - -(defalias 'lsp-canonical-file-name 'lsp-f-canonical) - -(defun lsp-f-same? (path-a path-b) - "Return t if PATH-A and PATH-B are references to the same file. -Symlinks are not followed." - (when (and (f-exists? path-a) - (f-exists? path-b)) - (equal - (lsp-f-canonical (directory-file-name (f-expand path-a))) - (lsp-f-canonical (directory-file-name (f-expand path-b)))))) - -(defun lsp-f-parent (path) - "Return the parent directory to PATH. -Symlinks are not followed." - (let ((parent (file-name-directory - (directory-file-name (f-expand path default-directory))))) - (unless (lsp-f-same? path parent) - (if (f-relative? path) - (f-relative parent) - (directory-file-name parent))))) - -(defun lsp-f-ancestor-of? (path-a path-b) - "Return t if PATH-A is an ancestor of PATH-B. -Symlinks are not followed." - (unless (lsp-f-same? path-a path-b) - (s-prefix? (concat (lsp-f-canonical path-a) (f-path-separator)) - (lsp-f-canonical path-b)))) - -(defun lsp--merge-results (results method) - "Merge RESULTS by filtering the empty hash-tables and merging -the lists according to METHOD." - (pcase (--map (if (vectorp it) - (append it nil) it) - (-filter #'identity results)) - (`() ()) - ;; only one result - simply return it - (`(,fst) fst) - ;; multiple results merge it based on strategy - (results - (pcase method - ("textDocument/hover" (pcase (seq-filter - (-compose #'not #'lsp-empty?) - results) - (`(,hover) hover) - (hovers (lsp-make-hover - :contents - (-mapcat - (-lambda ((&Hover :contents)) - (if (and (sequencep contents) - (not (stringp contents))) - (append contents ()) - (list contents))) - hovers))))) - ("textDocument/completion" - (lsp-make-completion-list - :is-incomplete (seq-some - #'lsp:completion-list-is-incomplete - results) - :items (cl-mapcan (lambda (it) (append (if (lsp-completion-list? it) - (lsp:completion-list-items it) - it) - nil)) - results))) - ("completionItem/resolve" - (let ((item (cl-first results))) - (when-let ((details (seq-filter #'identity - (seq-map #'lsp:completion-item-detail? results)))) - (lsp:set-completion-item-detail? - item - (string-join details " "))) - (when-let ((docs (seq-filter #'identity - (seq-map #'lsp:completion-item-documentation? results)))) - (lsp:set-completion-item-documentation? - item - (lsp-make-markup-content - :kind (or (seq-some (lambda (it) - (when (equal (lsp:markup-content-kind it) - lsp/markup-kind-markdown) - lsp/markup-kind-markdown)) - docs) - lsp/markup-kind-plain-text) - :value (string-join (seq-map (lambda (doc) - (or (lsp:markup-content-value doc) - (and (stringp doc) doc))) - docs) - "\n")))) - (when-let ((edits (seq-filter #'identity - (seq-map #'lsp:completion-item-additional-text-edits? results)))) - (lsp:set-completion-item-additional-text-edits? - item - (cl-mapcan (lambda (it) (if (seqp it) it (list it))) edits))) - item)) - (_ (cl-mapcan (lambda (it) (if (seqp it) it (list it))) results)))))) - -(defun lsp--spinner-start () - "Start spinner indication." - (condition-case _err (spinner-start (lsp-progress-spinner-type)) (error))) - -(defun lsp--propertize (str type) - "Propertize STR as per TYPE." - (propertize str 'face (alist-get type lsp--message-type-face))) - -(defun lsp-workspaces () - "Return the lsp workspaces associated with the current project." - (if lsp--cur-workspace (list lsp--cur-workspace) lsp--buffer-workspaces)) - -(defun lsp--completing-read (prompt collection transform-fn &optional predicate - require-match initial-input - hist def inherit-input-method) - "Wrap `completing-read' to provide transformation function and disable sort. - -TRANSFORM-FN will be used to transform each of the items before displaying. - -PROMPT COLLECTION PREDICATE REQUIRE-MATCH INITIAL-INPUT HIST DEF -INHERIT-INPUT-METHOD will be proxied to `completing-read' without changes." - (let* ((col (--map (cons (funcall transform-fn it) it) collection)) - (completion (completing-read prompt - (lambda (string pred action) - (if (eq action 'metadata) - `(metadata (display-sort-function . identity)) - (complete-with-action action col string pred))) - predicate require-match initial-input hist - def inherit-input-method))) - (cdr (assoc completion col)))) - -(defconst lsp--system-arch (lambda () - (setq lsp--system-arch - (pcase system-type - ('windows-nt - (pcase system-configuration - ((rx bol "x86_64-") 'x64) - (_ 'x86))) - ('darwin - (pcase system-configuration - ((rx "aarch64-") 'arm64) - (_ 'x64))) - ('gnu/linux - (pcase system-configuration - ((rx bol "aarch64-") 'arm64) - ((rx bol "x86_64") 'x64) - ((rx bol (| "i386" "i886")) 'x32))) - (_ - (pcase system-configuration - ((rx bol "x86_64") 'x64) - ((rx bol (| "i386" "i886")) 'x32)))))) - "Return the system architecture of `Emacs'. -Special values: - `x64' 64bit - `x32' 32bit - `arm64' ARM 64bit") - -(defmacro lsp-with-current-buffer (buffer-id &rest body) - (declare (indent 1) (debug t)) - `(if-let ((wcb (plist-get ,buffer-id :with-current-buffer))) - (with-lsp-workspaces (plist-get ,buffer-id :workspaces) - (funcall wcb (lambda () ,@body))) - (with-current-buffer ,buffer-id - ,@body))) - -(defvar lsp--throw-on-input nil - "Make `lsp-*-while-no-input' throws `input' on interrupted.") - -(defmacro lsp--catch (tag bodyform &rest handlers) - "Catch TAG thrown in BODYFORM. -The return value from TAG will be handled in HANDLERS by `pcase'." - (declare (debug (form form &rest (pcase-PAT body))) (indent 2)) - (let ((re-sym (make-symbol "re"))) - `(let ((,re-sym (catch ,tag ,bodyform))) - (pcase ,re-sym - ,@handlers)))) - -(defmacro lsp--while-no-input (&rest body) - "Wrap BODY in `while-no-input' and respecting `non-essential'. -If `lsp--throw-on-input' is set, will throw if input is pending, else -return value of `body' or nil if interrupted." - (declare (debug t) (indent 0)) - `(if non-essential - (let ((res (while-no-input ,@body))) - (cond - ((and lsp--throw-on-input (equal res t)) - (throw 'input :interrupted)) - ((booleanp res) nil) - (t res))) - ,@body)) - -;; A ‘lsp--client’ object describes the client-side behavior of a language -;; server. It is used to start individual server processes, each of which is -;; represented by a ‘lsp--workspace’ object. Client objects are normally -;; created using ‘lsp-define-stdio-client’ or ‘lsp-define-tcp-client’. Each -;; workspace refers to exactly one client, but there can be multiple workspaces -;; for a single client. -(cl-defstruct lsp--client - ;; ‘language-id’ is a function that receives a buffer as a single argument - ;; and should return the language identifier for that buffer. See - ;; https://microsoft.github.io/language-server-protocol/specification#textdocumentitem - ;; for a list of language identifiers. Also consult the documentation for - ;; the language server represented by this client to find out what language - ;; identifiers it supports or expects. - (language-id nil) - - ;; ‘add-on?’ when set to t the server will be started no matter whether there - ;; is another server handling the same mode. - (add-on? nil) - ;; ‘new-connection’ is a function that should start a language server process - ;; and return a cons (COMMAND-PROCESS . COMMUNICATION-PROCESS). - ;; COMMAND-PROCESS must be a process object representing the server process - ;; just started. COMMUNICATION-PROCESS must be a process (including pipe and - ;; network processes) that ‘lsp-mode’ uses to communicate with the language - ;; server using the language server protocol. COMMAND-PROCESS and - ;; COMMUNICATION-PROCESS may be the same process; in that case - ;; ‘new-connection’ may also return that process as a single - ;; object. ‘new-connection’ is called with two arguments, FILTER and - ;; SENTINEL. FILTER should be used as process filter for - ;; COMMUNICATION-PROCESS, and SENTINEL should be used as process sentinel for - ;; COMMAND-PROCESS. - (new-connection nil) - - ;; ‘ignore-regexps’ is a list of regexps. When a data packet from the - ;; language server matches any of these regexps, it will be ignored. This is - ;; intended for dealing with language servers that output non-protocol data. - (ignore-regexps nil) - - ;; ‘ignore-messages’ is a list of regexps. When a message from the language - ;; server matches any of these regexps, it will be ignored. This is useful - ;; for filtering out unwanted messages; such as servers that send nonstandard - ;; message types, or extraneous log messages. - (ignore-messages nil) - - ;; ‘notification-handlers’ is a hash table mapping notification method names - ;; (strings) to functions handling the respective notifications. Upon - ;; receiving a notification, ‘lsp-mode’ will call the associated handler - ;; function passing two arguments, the ‘lsp--workspace’ object and the - ;; deserialized notification parameters. - (notification-handlers (make-hash-table :test 'equal)) - - ;; ‘request-handlers’ is a hash table mapping request method names - ;; (strings) to functions handling the respective notifications. Upon - ;; receiving a request, ‘lsp-mode’ will call the associated handler function - ;; passing two arguments, the ‘lsp--workspace’ object and the deserialized - ;; request parameters. - (request-handlers (make-hash-table :test 'equal)) - - ;; ‘response-handlers’ is a hash table mapping integral JSON-RPC request - ;; identifiers for pending asynchronous requests to functions handling the - ;; respective responses. Upon receiving a response from the language server, - ;; ‘lsp-mode’ will call the associated response handler function with a - ;; single argument, the deserialized response parameters. - (response-handlers (make-hash-table :test 'eql)) - - ;; ‘prefix-function’ is called for getting the prefix for completion. - ;; The function takes no parameter and returns a cons (start . end) representing - ;; the start and end bounds of the prefix. If it's not set, the client uses a - ;; default prefix function." - (prefix-function nil) - - ;; Contains mapping of scheme to the function that is going to be used to load - ;; the file. - (uri-handlers (make-hash-table :test #'equal)) - - ;; ‘action-handlers’ is a hash table mapping action to a handler function. It - ;; can be used in `lsp-execute-code-action' to determine whether the action - ;; current client is interested in executing the action instead of sending it - ;; to the server. - (action-handlers (make-hash-table :test 'equal)) - - ;; `action-filter' can be set to a function that modifies any incoming - ;; `CodeAction' in place before it is executed. The return value is ignored. - ;; This can be used to patch up broken code action requests before they are - ;; sent back to the LSP server. See `lsp-fix-code-action-booleans' for an - ;; example of a function that can be useful here. - (action-filter nil) - - ;; major modes supported by the client. - major-modes - ;; Function that will be called to decide if this language client - ;; should manage a particular buffer. The function will be passed - ;; the file name and major mode to inform the decision. Setting - ;; `activation-fn' will override `major-modes', if - ;; present. - activation-fn - ;; Break the tie when major-mode is supported by multiple clients. - (priority 0) - ;; Unique identifier for representing the client object. - server-id - ;; defines whether the client supports multi root workspaces. - multi-root - ;; Initialization options or a function that returns initialization options. - initialization-options - ;; `semantic-tokens-faces-overrides’ is a plist that can be used to extend, or - ;; completely replace, the faces used for semantic highlighting on a - ;; client-by-client basis. - ;; - ;; It recognizes four members, all of which are optional: `:types’ and - ;; `:modifiers’, respectively, should be face definition lists akin to - ;; `:lsp-semantic-token-faces’. If specified, each of these face lists will be - ;; merged with the default face definition list. - ;; - ;; Alternatively, if the plist members `:discard-default-types’ or - ;; `:discard-default-modifiers' are non-nil, the default `:type' or `:modifiers' - ;; face definitions will be replaced entirely by their respective overrides. - ;; - ;; For example, setting `:semantic-tokens-faces-overrides' to - ;; `(:types (("macro" . font-lock-keyword-face)))' will remap "macro" tokens from - ;; their default face `lsp-face-semhl-macro' to `font-lock-keyword-face'. - ;; - ;; `(:types (("macro" . font-lock-keyword-face) ("not-quite-a-macro" . some-face)))' - ;; will also remap "macro", but on top of that associate the fictional token type - ;; "not-quite-a-macro" with the face named `some-face'. - ;; - ;; `(:types (("macro" . font-lock-keyword-face)) - ;; :modifiers (("declaration" . lsp-face-semhl-interface)) - ;; :discard-default-types t - ;; :discard-default-modifiers t)' - ;; will discard all default face definitions, hence leaving the client with - ;; only one token type "macro", mapped to `font-lock-keyword-face', and one - ;; modifier type "declaration", mapped to `lsp-face-semhl-interface'. - semantic-tokens-faces-overrides - ;; Provides support for registering LSP Server specific capabilities. - custom-capabilities - ;; Function which returns the folders that are considered to be not projects but library files. - ;; The function accepts one parameter currently active workspace. - ;; See: https://github.com/emacs-lsp/lsp-mode/issues/225. - library-folders-fn - ;; function which will be called when opening file in the workspace to perform - ;; client specific initialization. The function accepts one parameter - ;; currently active workspace. - before-file-open-fn - ;; Function which will be called right after a workspace has been initialized. - initialized-fn - ;; ‘remote?’ indicate whether the client can be used for LSP server over TRAMP. - (remote? nil) - - ;; ‘completion-in-comments?’ t if the client supports completion in comments. - (completion-in-comments? nil) - - ;; ‘path->uri-fn’ the function to use for path->uri conversion for the client. - (path->uri-fn nil) - - ;; ‘uri->path-fn’ the function to use for uri->path conversion for the client. - (uri->path-fn nil) - ;; Function that returns an environment structure that will be used - ;; to set some environment variables when starting the language - ;; server process. These environment variables enable some - ;; additional features in the language server. The environment - ;; structure is an alist of the form (KEY . VALUE), where KEY is a - ;; string (regularly in all caps), and VALUE may be a string, a - ;; boolean, or a sequence of strings. - environment-fn - - ;; ‘after-open-fn’ workspace after open specific hooks. - (after-open-fn nil) - - ;; ‘async-request-handlers’ is a hash table mapping request method names - ;; (strings) to functions handling the respective requests that may take - ;; time to finish. Upon receiving a request, ‘lsp-mode’ will call the - ;; associated handler function passing three arguments, the ‘lsp--workspace’ - ;; object, the deserialized request parameters and the callback which accept - ;; result as its parameter. - (async-request-handlers (make-hash-table :test 'equal)) - download-server-fn - download-in-progress? - buffers - synchronize-sections) - -(defun lsp-clients-executable-find (find-command &rest args) - "Finds an executable by invoking a search command. - -FIND-COMMAND is the executable finder that searches for the -actual language server executable. ARGS is a list of arguments to -give to FIND-COMMAND to find the language server. Returns the -output of FIND-COMMAND if it exits successfully, nil otherwise. - -Typical uses include finding an executable by invoking `find' in -a project, finding LLVM commands on macOS with `xcrun', or -looking up project-specific language servers for projects written -in the various dynamic languages, e.g. `nvm', `pyenv' and `rbenv' -etc." - (when-let* ((find-command-path (executable-find find-command)) - (executable-path - (with-temp-buffer - (when (zerop (apply 'call-process find-command-path nil t nil args)) - (buffer-substring-no-properties (point-min) (point-max)))))) - (string-trim executable-path))) - -(defvar lsp--already-widened nil) - -(defmacro lsp-save-restriction-and-excursion (&rest form) - (declare (indent 0) (debug t)) - `(if lsp--already-widened - (save-excursion ,@form) - (-let [lsp--already-widened t] - (save-restriction - (widen) - (save-excursion ,@form))))) - -;; from http://emacs.stackexchange.com/questions/8082/how-to-get-buffer-position-given-line-number-and-column-number -(defun lsp--line-character-to-point (line character) - "Return the point for character CHARACTER on line LINE." - (or (lsp-virtual-buffer-call :line/character->point line character) - (let ((inhibit-field-text-motion t)) - (lsp-save-restriction-and-excursion - (goto-char (point-min)) - (forward-line line) - ;; server may send character position beyond the current line and we - ;; should fallback to line end. - (-let [line-end (line-end-position)] - (if (> character (- line-end (point))) - line-end - (forward-char character) - (point))))))) - -(lsp-defun lsp--position-to-point ((&Position :line :character)) - "Convert `Position' object in PARAMS to a point." - (lsp--line-character-to-point line character)) - -(lsp-defun lsp--range-to-region ((&RangeToPoint :start :end)) - (cons start end)) - -(lsp-defun lsp--range-text ((&RangeToPoint :start :end)) - (buffer-substring start end)) - -(lsp-defun lsp--find-wrapping-range ((&SelectionRange :parent? :range (&RangeToPoint :start :end))) - (cond - ((and - (region-active-p) - (<= start (region-beginning) end) - (<= start (region-end) end) - (or (not (= start (region-beginning))) - (not (= end (region-end))))) - (cons start end)) - ((and (<= start (point) end) - (not (region-active-p))) - (cons start end)) - (parent? (lsp--find-wrapping-range parent?)))) - -(defun lsp--get-selection-range () - (or - (-when-let ((cache . cache-tick) lsp--document-selection-range-cache) - (when (= cache-tick (buffer-modified-tick)) cache)) - (let ((response (cl-first - (lsp-request - "textDocument/selectionRange" - (list :textDocument (lsp--text-document-identifier) - :positions (vector (lsp--cur-position))))))) - (setq lsp--document-selection-range-cache - (cons response (buffer-modified-tick))) - response))) - -(defun lsp-extend-selection () - "Extend selection." - (interactive) - (unless (lsp-feature? "textDocument/selectionRange") - (signal 'lsp-capability-not-supported (list "selectionRangeProvider"))) - (-when-let ((start . end) (lsp--find-wrapping-range (lsp--get-selection-range))) - (goto-char start) - (set-mark (point)) - (goto-char end) - (exchange-point-and-mark))) - -(defun lsp-warn (message &rest args) - "Display a warning message made from (`format-message' MESSAGE ARGS...). -This is equivalent to `display-warning', using `lsp-mode' as the type and -`:warning' as the level." - (display-warning 'lsp-mode (apply #'format-message message args))) - -(defun lsp--get-uri-handler (scheme) - "Get uri handler for SCHEME in the current workspace." - (--some (gethash scheme (lsp--client-uri-handlers (lsp--workspace-client it))) - (or (lsp-workspaces) (lsp--session-workspaces (lsp-session))))) - -(defun lsp--fix-path-casing (path) - "On windows, downcases path because the windows file system is -case-insensitive. - -On other systems, returns path without change." - (if (eq system-type 'windows-nt) (downcase path) path)) - -(defun lsp--uri-to-path (uri) - "Convert URI to a file path." - (if-let ((fn (->> (lsp-workspaces) - (-keep (-compose #'lsp--client-uri->path-fn #'lsp--workspace-client)) - (cl-first)))) - (funcall fn uri) - (lsp--uri-to-path-1 uri))) - -(defun lsp-remap-path-if-needed (file-name) - (-if-let ((virtual-buffer &as &plist :buffer) (gethash file-name lsp--virtual-buffer-mappings)) - (propertize (buffer-local-value 'buffer-file-name buffer) - 'lsp-virtual-buffer virtual-buffer) - file-name)) - -(defun lsp--uri-to-path-1 (uri) - "Convert URI to a file path." - (let* ((url (url-generic-parse-url (url-unhex-string uri))) - (type (url-type url)) - (target (url-target url)) - (file - (concat (decode-coding-string (url-filename url) - (or locale-coding-system 'utf-8)) - (when (and target - (not (s-match - (rx "#" (group (1+ num)) (or "," "#") - (group (1+ num)) - string-end) - uri))) - (concat "#" target)))) - (file-name (if (and type (not (string= type "file"))) - (if-let ((handler (lsp--get-uri-handler type))) - (funcall handler uri) - uri) - ;; `url-generic-parse-url' is buggy on windows: - ;; https://github.com/emacs-lsp/lsp-mode/pull/265 - (or (and (eq system-type 'windows-nt) - (eq (elt file 0) ?\/) - (substring file 1)) - file)))) - (->> file-name - (concat (-some #'lsp--workspace-host-root (lsp-workspaces))) - (lsp-remap-path-if-needed)))) - -(defun lsp--buffer-uri () - "Return URI of the current buffer." - (or lsp-buffer-uri - (plist-get lsp--virtual-buffer :buffer-uri) - (lsp--path-to-uri - (or (buffer-file-name) (buffer-file-name (buffer-base-buffer)))))) - -(defun lsp-register-client-capabilities (&rest _args) - "Implemented only to make `company-lsp' happy. -DELETE when `lsp-mode.el' is deleted.") - -(defconst lsp--url-path-allowed-chars - (url--allowed-chars (append '(?/) url-unreserved-chars)) - "`url-unreserved-chars' with additional delim ?/. -This set of allowed chars is enough for hexifying local file paths.") - -(defun lsp--path-to-uri-1 (path) - (concat lsp--uri-file-prefix - (--> path - (expand-file-name it) - (or (file-remote-p it 'localname t) it) - (url-hexify-string it lsp--url-path-allowed-chars)))) - -(defun lsp--path-to-uri (path) - "Convert PATH to a uri." - (if-let ((uri-fn (->> (lsp-workspaces) - (-keep (-compose #'lsp--client-path->uri-fn #'lsp--workspace-client)) - (cl-first)))) - (funcall uri-fn path) - (lsp--path-to-uri-1 path))) - -(defun lsp--string-match-any (regex-list str) - "Return the first regex, if any, within REGEX-LIST matching STR." - (--first (string-match it str) regex-list)) - -(cl-defstruct lsp-watch - (descriptors (make-hash-table :test 'equal)) - root-directory) - -(defun lsp--folder-watch-callback (event callback watch ignored-files ignored-directories) - (let ((file-name (cl-third event)) - (event-type (cl-second event))) - (cond - ((and (file-directory-p file-name) - (equal 'created event-type) - (not (lsp--string-match-any ignored-directories file-name))) - - (lsp-watch-root-folder (file-truename file-name) callback ignored-files ignored-directories watch) - - ;; process the files that are already present in - ;; the directory. - (->> (directory-files-recursively file-name ".*" t) - (seq-do (lambda (f) - (unless (file-directory-p f) - (funcall callback (list nil 'created f))))))) - ((and (memq event-type '(created deleted changed)) - (not (file-directory-p file-name)) - (not (lsp--string-match-any ignored-files file-name))) - (funcall callback event)) - ((and (memq event-type '(renamed)) - (not (file-directory-p file-name)) - (not (lsp--string-match-any ignored-files file-name))) - (funcall callback `(,(cl-first event) deleted ,(cl-third event))) - (funcall callback `(,(cl-first event) created ,(cl-fourth event))))))) - -(defun lsp--ask-about-watching-big-repo (number-of-directories dir) - "Ask the user if they want to watch NUMBER-OF-DIRECTORIES from a repository DIR. -This is useful when there is a lot of files in a repository, as -that may slow Emacs down. Returns t if the user wants to watch -the entire repository, nil otherwise." - (prog1 - (yes-or-no-p - (format - "Watching all the files in %s would require adding watches to %s directories, so watching the repo may slow Emacs down. -Do you want to watch all files in %s? " - dir - number-of-directories - dir)) - (lsp--info - (concat "You can configure this warning with the `lsp-enable-file-watchers' " - "and `lsp-file-watch-threshold' variables")))) - - -(defun lsp--path-is-watchable-directory (path dir ignored-directories) - "Figure out whether PATH (inside of DIR) is meant to have a file watcher set. -IGNORED-DIRECTORIES is a list of regexes to filter out directories we don't -want to watch." - (let - ((full-path (f-join dir path))) - (and (file-accessible-directory-p full-path) - (not (equal path ".")) - (not (equal path "..")) - (not (lsp--string-match-any ignored-directories full-path))))) - - -(defun lsp--all-watchable-directories (dir ignored-directories) - "Traverse DIR recursively returning a list of paths that should have watchers. -IGNORED-DIRECTORIES will be used for exclusions" - (let* ((dir (if (f-symlink? dir) - (file-truename dir) - dir))) - (apply #'nconc - ;; the directory itself is assumed to be part of the set - (list dir) - ;; collect all subdirectories that are watchable - (-map - (lambda (path) (lsp--all-watchable-directories (f-join dir path) ignored-directories)) - ;; but only look at subdirectories that are watchable - (-filter (lambda (path) (lsp--path-is-watchable-directory path dir ignored-directories)) - (directory-files dir)))))) - -(defun lsp-watch-root-folder (dir callback ignored-files ignored-directories &optional watch warn-big-repo?) - "Create recursive file notification watch in DIR. -CALLBACK will be called when there are changes in any of -the monitored files. WATCHES is a hash table directory->file -notification handle which contains all of the watch that -already have been created. Watches will not be created for -any directory that matches any regex in IGNORED-DIRECTORIES. -Watches will not be created for any file that matches any -regex in IGNORED-FILES." - (let* ((dir (if (f-symlink? dir) - (file-truename dir) - dir)) - (watch (or watch (make-lsp-watch :root-directory dir))) - (dirs-to-watch (lsp--all-watchable-directories dir ignored-directories))) - (lsp-log "Creating watchers for following %s folders:\n %s" - (length dirs-to-watch) - (s-join "\n " dirs-to-watch)) - (when (or - (not warn-big-repo?) - (not lsp-file-watch-threshold) - (let ((number-of-directories (length dirs-to-watch))) - (or - (< number-of-directories lsp-file-watch-threshold) - (condition-case nil - (lsp--ask-about-watching-big-repo number-of-directories dir) - (quit))))) - (dolist (current-dir dirs-to-watch) - (condition-case err - (progn - (puthash - current-dir - (file-notify-add-watch current-dir - '(change) - (lambda (event) - (lsp--folder-watch-callback event callback watch ignored-files ignored-directories))) - (lsp-watch-descriptors watch))) - (error (lsp-log "Failed to create a watch for %s: message" (error-message-string err))) - (file-missing (lsp-log "Failed to create a watch for %s: message" (error-message-string err)))))) - watch)) - -(defun lsp-kill-watch (watch) - "Delete WATCH." - (-> watch lsp-watch-descriptors hash-table-values (-each #'file-notify-rm-watch)) - (ht-clear! (lsp-watch-descriptors watch))) - -(defun lsp-json-bool (val) - "Convert VAL to JSON boolean." - (if val t :json-false)) - -(defmacro with-lsp-workspace (workspace &rest body) - "Helper macro for invoking BODY in WORKSPACE context." - (declare (debug (form body)) - (indent 1)) - `(let ((lsp--cur-workspace ,workspace)) ,@body)) - -(defmacro with-lsp-workspaces (workspaces &rest body) - "Helper macro for invoking BODY against multiple WORKSPACES." - (declare (debug (form body)) - (indent 1)) - `(let ((lsp--buffer-workspaces ,workspaces)) ,@body)) - - - -(defmacro lsp-consistency-check (package) - `(defconst ,(intern (concat (symbol-name package) - "-plist-value-when-compiled")) - (eval-when-compile lsp-use-plists))) - - -;; loading code-workspace files - -;;;###autoload -(defun lsp-load-vscode-workspace (file) - "Load vscode workspace from FILE" - (interactive "fSelect file to import: ") - (mapc #'lsp-workspace-folders-remove (lsp-session-folders (lsp-session))) - - (let ((dir (f-dirname file))) - (->> file - (json-read-file) - (alist-get 'folders) - (-map (-lambda ((&alist 'path)) - (lsp-workspace-folders-add (expand-file-name path dir))))))) - -;;;###autoload -(defun lsp-save-vscode-workspace (file) - "Save vscode workspace to FILE" - (interactive "FSelect file to save to: ") - - (let ((json-encoding-pretty-print t)) - (f-write-text (json-encode - `((folders . ,(->> (lsp-session) - (lsp-session-folders) - (--map `((path . ,it))))))) - 'utf-8 - file))) - - -(defmacro lsp-foreach-workspace (&rest body) - "Execute BODY for each of the current workspaces." - (declare (debug (form body))) - `(--map (with-lsp-workspace it ,@body) (lsp-workspaces))) - -(defmacro when-lsp-workspace (workspace &rest body) - "Helper macro for invoking BODY in WORKSPACE context if present." - (declare (debug (form body)) - (indent 1)) - `(when-let ((lsp--cur-workspace ,workspace)) ,@body)) - -(lsp-defun lsp--window-show-quick-pick (_workspace (&ShowQuickPickParams :place-holder :can-pick-many :items)) - (if-let* ((selectfunc (if can-pick-many #'completing-read-multiple #'completing-read)) - (itemLabels (seq-map (-lambda ((item &as &QuickPickItem :label)) (format "%s" label)) - items)) - (result (funcall-interactively - selectfunc - (format "%s%s " place-holder (if can-pick-many " (* for all)" "")) itemLabels)) - (choices (if (listp result) - (if (equal result '("*")) - itemLabels - result) - (list result)))) - (vconcat (seq-filter #'identity (seq-map (-lambda ((item &as &QuickPickItem :label :user-data)) - (if (member label choices) - (lsp-make-quick-pick-item :label label :picked t :user-data user-data) - nil)) - items))))) - -(lsp-defun lsp--window-show-input-box (_workspace (&ShowInputBoxParams :prompt :value?)) - (read-string (format "%s: " prompt) (or value? ""))) - -(lsp-defun lsp--window-show-message (_workspace (&ShowMessageRequestParams :message :type)) - "Send the server's messages to log. -PARAMS - the data sent from _WORKSPACE." - (funcall (cl-case type - (1 'lsp--error) - (2 'lsp--warn) - (t 'lsp--info)) - "%s" - message)) - -(lsp-defun lsp--window-log-message (workspace (&ShowMessageRequestParams :message :type)) - "Send the server's messages to log. -PARAMS - the data sent from WORKSPACE." - (ignore - (let ((client (lsp--workspace-client workspace))) - (when (or (not client) - (cl-notany (-rpartial #'string-match-p message) - (lsp--client-ignore-messages client))) - (lsp-log "%s" (lsp--propertize message type)))))) - -(lsp-defun lsp--window-log-message-request ((&ShowMessageRequestParams :message :type :actions?)) - "Display a message request to user sending the user selection back to server." - (let* ((message (lsp--propertize message type)) - (choices (seq-map #'lsp:message-action-item-title actions?))) - (if choices - (completing-read (concat message " ") (seq-into choices 'list) nil t) - (lsp-log message)))) - -(lsp-defun lsp--window-show-document ((&ShowDocumentParams :uri :selection?)) - "Show document URI in a buffer and go to SELECTION if any." - (let ((path (lsp--uri-to-path uri))) - (when (f-exists? path) - (with-current-buffer (find-file path) - (when selection? - (goto-char (lsp--position-to-point (lsp:range-start selection?)))) - t)))) - -(defcustom lsp-progress-prefix "⌛ " - "Progress prefix." - :group 'lsp-mode - :type 'string - :package-version '(lsp-mode . "8.0.0")) - -(defcustom lsp-progress-function #'lsp-on-progress-modeline - "Function for handling the progress notifications." - :group 'lsp-mode - :type '(choice - (const :tag "Use modeline" lsp-on-progress-modeline) - (const :tag "Legacy(uses either `progress-reporter' or `spinner' based on `lsp-progress-via-spinner')" - lsp-on-progress-legacy) - (const :tag "Ignore" ignore) - (function :tag "Other function")) - :package-version '(lsp-mode . "8.0.0")) - -(defcustom lsp-request-while-no-input-may-block nil - "Have `lsp-request-while-no-input` block unless `non-essential` is t." - :group 'lsp-mode - :type 'boolean) - -(defun lsp--progress-status () - "Returns the status of the progress for the current workspaces." - (-let ((progress-status - (s-join - "|" - (-keep - (lambda (workspace) - (let ((tokens (lsp--workspace-work-done-tokens workspace))) - (unless (ht-empty? tokens) - (mapconcat - (-lambda ((&WorkDoneProgressBegin :message? :title :percentage?)) - (concat (if percentage? - (if (numberp percentage?) - (format "%.0f%%%% " percentage?) - (format "%s%%%% " percentage?)) - "") - (or message? title))) - (ht-values tokens) - "|")))) - (lsp-workspaces))))) - (unless (s-blank? progress-status) - (concat lsp-progress-prefix progress-status " ")))) - -(lsp-defun lsp-on-progress-modeline (workspace (&ProgressParams :token :value - (value &as &WorkDoneProgress :kind))) - "PARAMS contains the progress data. -WORKSPACE is the workspace that contains the progress token." - (add-to-list 'global-mode-string '(t (:eval (lsp--progress-status)))) - (pcase kind - ("begin" (lsp-workspace-set-work-done-token token value workspace)) - ("report" (lsp-workspace-set-work-done-token token value workspace)) - ("end" (lsp-workspace-rem-work-done-token token workspace))) - (force-mode-line-update)) - -(lsp-defun lsp-on-progress-legacy (workspace (&ProgressParams :token :value - (value &as &WorkDoneProgress :kind))) - "PARAMS contains the progress data. -WORKSPACE is the workspace that contains the progress token." - (pcase kind - ("begin" - (-let* (((&WorkDoneProgressBegin :title :percentage?) value) - (reporter - (if lsp-progress-via-spinner - (let* ((spinner-strings (alist-get (lsp-progress-spinner-type) spinner-types)) - ;; Set message as a tooltip for the spinner strings - (propertized-strings - (seq-map (lambda (string) (propertize string 'help-echo title)) - spinner-strings)) - (spinner-type (vconcat propertized-strings))) - ;; The progress relates to the server as a whole, - ;; display it on all buffers. - (mapcar (lambda (buffer) - (lsp-with-current-buffer buffer - (spinner-start spinner-type)) - buffer) - (lsp--workspace-buffers workspace))) - (if percentage? - (make-progress-reporter title 0 100 percentage?) - ;; No percentage, just progress - (make-progress-reporter title nil nil))))) - (lsp-workspace-set-work-done-token token reporter workspace))) - ("report" - (when-let ((reporter (lsp-workspace-get-work-done-token token workspace))) - (unless lsp-progress-via-spinner - (progress-reporter-update reporter (lsp:work-done-progress-report-percentage? value))))) - - ("end" - (when-let ((reporter (lsp-workspace-get-work-done-token token workspace))) - (if lsp-progress-via-spinner - (mapc (lambda (buffer) - (when (lsp-buffer-live-p buffer) - (lsp-with-current-buffer buffer - (spinner-stop)))) - reporter) - (progress-reporter-done reporter)) - (lsp-workspace-rem-work-done-token token workspace))))) - - -;; diagnostics - -(defvar lsp-diagnostic-filter nil - "A a function which will be called with - `&PublishDiagnosticsParams' and `workspace' which can be used - to filter out the diagnostics. The function should return - `&PublishDiagnosticsParams'. - -Common usecase are: -1. Filter the diagnostics for a particular language server. -2. Filter out the diagnostics under specific level.") - -(defvar lsp-diagnostic-stats (ht)) - -(defun lsp-diagnostics (&optional current-workspace?) - "Return the diagnostics from all workspaces." - (or (pcase (if current-workspace? - (lsp-workspaces) - (lsp--session-workspaces (lsp-session))) - (`() ()) - (`(,workspace) (lsp--workspace-diagnostics workspace)) - (`,workspaces (let ((result (make-hash-table :test 'equal))) - (mapc (lambda (workspace) - (->> workspace - (lsp--workspace-diagnostics) - (maphash (lambda (file-name diagnostics) - (puthash file-name - (append (gethash file-name result) diagnostics) - result))))) - workspaces) - result))) - (ht))) - -(defun lsp-diagnostics-stats-for (path) - "Get diagnostics statistics for PATH. -The result format is vector [_ errors warnings infos hints] or nil." - (gethash (lsp--fix-path-casing path) lsp-diagnostic-stats)) - -(defun lsp-diagnostics--request-pull-diagnostics (workspace) - "Request new diagnostics for the current file within WORKSPACE. -This is only executed if the server supports pull diagnostics." - (when (lsp-feature? "textDocument/diagnostic") - (let ((path (lsp--fix-path-casing (buffer-file-name)))) - (lsp-request-async "textDocument/diagnostic" - (list :textDocument (lsp--text-document-identifier)) - (-lambda ((&DocumentDiagnosticReport :kind :items?)) - (lsp-diagnostics--apply-pull-diagnostics workspace path kind items?)) - :mode 'tick)))) - -(defun lsp-diagnostics--update-path (path new-stats) - (let ((new-stats (copy-sequence new-stats)) - (path (lsp--fix-path-casing (directory-file-name path)))) - (if-let ((old-data (gethash path lsp-diagnostic-stats))) - (dotimes (idx 5) - (cl-callf + (aref old-data idx) - (aref new-stats idx))) - (puthash path new-stats lsp-diagnostic-stats)))) - -(defun lsp-diagnostics--convert-and-update-path-stats (workspace path diagnostics) - (let ((path (lsp--fix-path-casing path)) - (new-stats (make-vector 5 0))) - (mapc (-lambda ((&Diagnostic :severity?)) - (cl-incf (aref new-stats (or severity? 1)))) - diagnostics) - (when-let ((old-diags (gethash path (lsp--workspace-diagnostics workspace)))) - (mapc (-lambda ((&Diagnostic :severity?)) - (cl-decf (aref new-stats (or severity? 1)))) - old-diags)) - (lsp-diagnostics--update-path path new-stats) - (while (not (string= path (setf path (file-name-directory - (directory-file-name path))))) - (lsp-diagnostics--update-path path new-stats)))) - -(lsp-defun lsp--on-diagnostics-update-stats (workspace - (&PublishDiagnosticsParams :uri :diagnostics)) - (lsp-diagnostics--convert-and-update-path-stats workspace (lsp--uri-to-path uri) diagnostics)) - -(defun lsp-diagnostics--apply-pull-diagnostics (workspace path kind diagnostics?) - "Update WORKSPACE diagnostics at PATH with DIAGNOSTICS?. -Depends on KIND being a \\='full\\=' update." - (cond - ((equal kind "full") - ;; TODO support `lsp-diagnostic-filter' - ;; (the params types differ from the published diagnostics response) - (lsp-diagnostics--convert-and-update-path-stats workspace path diagnostics?) - (-let* ((lsp--virtual-buffer-mappings (ht)) - (workspace-diagnostics (lsp--workspace-diagnostics workspace))) - (if (seq-empty-p diagnostics?) - (remhash path workspace-diagnostics) - (puthash path (append diagnostics? nil) workspace-diagnostics)) - (run-hooks 'lsp-diagnostics-updated-hook))) - ((equal kind "unchanged") t) - (t (lsp--error "Unknown pull diagnostic result kind '%s'" kind)))) - -(defun lsp--on-diagnostics (workspace params) - "Callback for textDocument/publishDiagnostics. -interface PublishDiagnosticsParams { - uri: string; - diagnostics: Diagnostic[]; -} -PARAMS contains the diagnostics data. -WORKSPACE is the workspace that contains the diagnostics." - (when lsp-diagnostic-filter - (setf params (funcall lsp-diagnostic-filter params workspace))) - - (lsp--on-diagnostics-update-stats workspace params) - - (-let* (((&PublishDiagnosticsParams :uri :diagnostics) params) - (lsp--virtual-buffer-mappings (ht)) - (file (lsp--fix-path-casing (lsp--uri-to-path uri))) - (workspace-diagnostics (lsp--workspace-diagnostics workspace))) - - (if (seq-empty-p diagnostics) - (remhash file workspace-diagnostics) - (puthash file (append diagnostics nil) workspace-diagnostics)) - - (run-hooks 'lsp-diagnostics-updated-hook))) - -(defun lsp-diagnostics--workspace-cleanup (workspace) - (->> workspace - (lsp--workspace-diagnostics) - (maphash (lambda (key _) - (lsp--on-diagnostics-update-stats - workspace - (lsp-make-publish-diagnostics-params - :uri (lsp--path-to-uri key) - :diagnostics []))))) - (clrhash (lsp--workspace-diagnostics workspace))) - - - -;; textDocument/foldingRange support - -(cl-defstruct lsp--folding-range beg end kind children) - -(defvar-local lsp--cached-folding-ranges nil) -(defvar-local lsp--cached-nested-folding-ranges nil) - -(defun lsp--folding-range-width (range) - (- (lsp--folding-range-end range) - (lsp--folding-range-beg range))) - -(defun lsp--get-folding-ranges () - "Get the folding ranges for the current buffer." - (unless (eq (buffer-chars-modified-tick) (car lsp--cached-folding-ranges)) - (let* ((ranges (lsp-request "textDocument/foldingRange" - `(:textDocument ,(lsp--text-document-identifier)))) - (sorted-line-col-pairs (->> ranges - (cl-mapcan (-lambda ((&FoldingRange :start-line - :start-character? - :end-line - :end-character?)) - (list (cons start-line start-character?) - (cons end-line end-character?)))) - (-sort #'lsp--line-col-comparator))) - (line-col-to-point-map (lsp--convert-line-col-to-points-batch - sorted-line-col-pairs))) - (setq lsp--cached-folding-ranges - (cons (buffer-chars-modified-tick) - (--> ranges - (seq-map (-lambda ((range &as - &FoldingRange :start-line - :start-character? - :end-line - :end-character? - :kind?)) - (make-lsp--folding-range - :beg (ht-get line-col-to-point-map - (cons start-line start-character?)) - :end (ht-get line-col-to-point-map - (cons end-line end-character?)) - :kind kind?)) - it) - (seq-filter (lambda (folding-range) - (< (lsp--folding-range-beg folding-range) - (lsp--folding-range-end folding-range))) - it) - (seq-into it 'list) - (delete-dups it)))))) - (cdr lsp--cached-folding-ranges)) - -(defun lsp--get-nested-folding-ranges () - "Get a list of nested folding ranges for the current buffer." - (-let [(tick . _) lsp--cached-folding-ranges] - (if (and (eq tick (buffer-chars-modified-tick)) - lsp--cached-nested-folding-ranges) - lsp--cached-nested-folding-ranges - (setq lsp--cached-nested-folding-ranges - (lsp--folding-range-build-trees (lsp--get-folding-ranges)))))) - -(defun lsp--folding-range-build-trees (ranges) - (setq ranges (seq-sort #'lsp--range-before-p ranges)) - (let* ((dummy-node (make-lsp--folding-range - :beg most-negative-fixnum - :end most-positive-fixnum)) - (stack (list dummy-node))) - (dolist (range ranges) - (while (not (lsp--range-inside-p range (car stack))) - (pop stack)) - (push range (lsp--folding-range-children (car stack))) - (push range stack)) - (lsp--folding-range-children dummy-node))) - -(defun lsp--range-inside-p (r1 r2) - "Return non-nil if folding range R1 lies inside R2" - (and (>= (lsp--folding-range-beg r1) (lsp--folding-range-beg r2)) - (<= (lsp--folding-range-end r1) (lsp--folding-range-end r2)))) - -(defun lsp--range-before-p (r1 r2) - "Return non-nil if folding range R1 ends before R2" - ;; Ensure r1 comes before r2 - (or (< (lsp--folding-range-beg r1) - (lsp--folding-range-beg r2)) - ;; If beg(r1) == beg(r2) make sure r2 ends first - (and (= (lsp--folding-range-beg r1) - (lsp--folding-range-beg r2)) - (< (lsp--folding-range-end r2) - (lsp--folding-range-end r1))))) - -(defun lsp--point-inside-range-p (point range) - "Return non-nil if POINT lies inside folding range RANGE." - (and (>= point (lsp--folding-range-beg range)) - (<= point (lsp--folding-range-end range)))) - -(cl-defun lsp--get-current-innermost-folding-range (&optional (point (point))) - "Return the innermost folding range POINT lies in." - (seq-reduce (lambda (innermost-range curr-range) - (if (and (lsp--point-inside-range-p point curr-range) - (or (null innermost-range) - (lsp--range-inside-p curr-range innermost-range))) - curr-range - innermost-range)) - (lsp--get-folding-ranges) - nil)) - -(cl-defun lsp--get-current-outermost-folding-range (&optional (point (point))) - "Return the outermost folding range POINT lies in." - (cdr (seq-reduce (-lambda ((best-pair &as outermost-width . _) curr-range) - (let ((curr-width (lsp--folding-range-width curr-range))) - (if (and (lsp--point-inside-range-p point curr-range) - (or (null best-pair) - (> curr-width outermost-width))) - (cons curr-width curr-range) - best-pair))) - (lsp--get-folding-ranges) - nil))) - -(defun lsp--folding-range-at-point-bounds () - (when (and lsp-enable-folding - (lsp-feature? "textDocument/foldingRange")) - (if-let ((range (lsp--get-current-innermost-folding-range))) - (cons (lsp--folding-range-beg range) - (lsp--folding-range-end range))))) -(put 'lsp--folding-range 'bounds-of-thing-at-point - #'lsp--folding-range-at-point-bounds) - -(defun lsp--get-nearest-folding-range (&optional backward) - (let ((point (point)) - (found nil)) - (while (not - (or found - (if backward - (<= point (point-min)) - (>= point (point-max))))) - (if backward (cl-decf point) (cl-incf point)) - (setq found (lsp--get-current-innermost-folding-range point))) - found)) - -(defun lsp--folding-range-at-point-forward-op (n) - (when (and lsp-enable-folding - (not (zerop n)) - (lsp-feature? "textDocument/foldingRange")) - (cl-block break - (dotimes (_ (abs n)) - (if-let ((range (lsp--get-nearest-folding-range (< n 0)))) - (goto-char (if (< n 0) - (lsp--folding-range-beg range) - (lsp--folding-range-end range))) - (cl-return-from break)))))) -(put 'lsp--folding-range 'forward-op - #'lsp--folding-range-at-point-forward-op) - -(defun lsp--folding-range-at-point-beginning-op () - (goto-char (car (lsp--folding-range-at-point-bounds)))) -(put 'lsp--folding-range 'beginning-op - #'lsp--folding-range-at-point-beginning-op) - -(defun lsp--folding-range-at-point-end-op () - (goto-char (cdr (lsp--folding-range-at-point-bounds)))) -(put 'lsp--folding-range 'end-op - #'lsp--folding-range-at-point-end-op) - -(defun lsp--range-at-point-bounds () - (or (lsp--folding-range-at-point-bounds) - (when-let ((range (and - (lsp-feature? "textDocument/hover") - (->> (lsp--text-document-position-params) - (lsp-request "textDocument/hover") - (lsp:hover-range?))))) - (lsp--range-to-region range)))) - -;; A more general purpose "thing", useful for applications like focus.el -(put 'lsp--range 'bounds-of-thing-at-point - #'lsp--range-at-point-bounds) - -(defun lsp--log-io-p (method) - "Return non nil if should log for METHOD." - (and lsp-log-io - (or (not lsp-log-io-allowlist-methods) - (member method lsp-log-io-allowlist-methods)))) - - -;; toggles - -(defun lsp-toggle-trace-io () - "Toggle client-server protocol logging." - (interactive) - (setq lsp-log-io (not lsp-log-io)) - (lsp--info "Server logging %s." (if lsp-log-io "enabled" "disabled"))) - -(defun lsp-toggle-signature-auto-activate () - "Toggle signature auto activate." - (interactive) - (setq lsp-signature-auto-activate - (unless lsp-signature-auto-activate '(:on-trigger-char))) - (lsp--info "Signature autoactivate %s." (if lsp-signature-auto-activate "enabled" "disabled")) - (lsp--update-signature-help-hook)) - -(defun lsp-toggle-on-type-formatting () - "Toggle on type formatting." - (interactive) - (setq lsp-enable-on-type-formatting (not lsp-enable-on-type-formatting)) - (lsp--info "On type formatting is %s." (if lsp-enable-on-type-formatting "enabled" "disabled")) - (lsp--update-on-type-formatting-hook)) - -(defun lsp-toggle-symbol-highlight () - "Toggle symbol highlighting." - (interactive) - (setq lsp-enable-symbol-highlighting (not lsp-enable-symbol-highlighting)) - - (cond - ((and lsp-enable-symbol-highlighting - (lsp-feature? "textDocument/documentHighlight")) - (add-hook 'lsp-on-idle-hook #'lsp--document-highlight nil t) - (lsp--info "Symbol highlighting enabled in current buffer.")) - ((not lsp-enable-symbol-highlighting) - (remove-hook 'lsp-on-idle-hook #'lsp--document-highlight t) - (lsp--remove-overlays 'lsp-highlight) - (lsp--info "Symbol highlighting disabled in current buffer.")))) - - -;; keybindings -(defvar lsp--binding-descriptions nil - "List of key binding/short description pair.") - -(defmacro lsp-define-conditional-key (keymap key def desc cond &rest bindings) - "In KEYMAP, define key sequence KEY as DEF conditionally. -This is like `define-key', except the definition disappears -whenever COND evaluates to nil. -DESC is the short-description for the binding. -BINDINGS is a list of (key def desc cond)." - (declare (indent defun) - (debug (form form form form form &rest sexp))) - (->> (cl-list* key def desc cond bindings) - (-partition 4) - (-mapcat (-lambda ((key def desc cond)) - `((define-key ,keymap ,key - '(menu-item - ,(format "maybe-%s" def) - ,def - :filter - (lambda (item) - (when (with-current-buffer (or (when (buffer-live-p lsp--describe-buffer) - lsp--describe-buffer) - (current-buffer)) - ,cond) - item)))) - (when (stringp ,key) - (setq lsp--binding-descriptions - (append lsp--binding-descriptions '(,key ,desc))))))) - macroexp-progn)) - -(defvar lsp--describe-buffer nil) - -(defun lsp-describe-buffer-bindings-advice (fn buffer &optional prefix menus) - (let ((lsp--describe-buffer buffer)) - (funcall fn buffer prefix menus))) - -(advice-add 'describe-buffer-bindings - :around - #'lsp-describe-buffer-bindings-advice) - -(defun lsp--prepend-prefix (mappings) - (->> mappings - (-partition 2) - (-mapcat (-lambda ((key description)) - (list (concat lsp-keymap-prefix " " key) - description))))) - -(defvar lsp-command-map - (-doto (make-sparse-keymap) - (lsp-define-conditional-key - ;; workspaces - "wD" lsp-disconnect "disconnect" (lsp-workspaces) - "wd" lsp-describe-session "describe session" t - "wq" lsp-workspace-shutdown "shutdown server" (lsp-workspaces) - "wr" lsp-workspace-restart "restart server" (lsp-workspaces) - "ws" lsp "start server" t - - ;; formatting - "==" lsp-format-buffer "format buffer" (or (lsp-feature? "textDocument/rangeFormatting") - (lsp-feature? "textDocument/formatting")) - "=r" lsp-format-region "format region" (lsp-feature? "textDocument/rangeFormatting") - - ;; folders - "Fa" lsp-workspace-folders-add "add folder" t - "Fb" lsp-workspace-blocklist-remove "un-blocklist folder" t - "Fr" lsp-workspace-folders-remove "remove folder" t - - ;; toggles - "TD" lsp-modeline-diagnostics-mode "toggle modeline diagnostics" (lsp-feature? - "textDocument/publishDiagnostics") - "TL" lsp-toggle-trace-io "toggle log io" t - "TS" lsp-ui-sideline-mode "toggle sideline" (featurep 'lsp-ui-sideline) - "TT" lsp-treemacs-sync-mode "toggle treemacs integration" (featurep 'lsp-treemacs) - "Ta" lsp-modeline-code-actions-mode "toggle modeline code actions" (lsp-feature? - "textDocument/codeAction") - "Tb" lsp-headerline-breadcrumb-mode "toggle breadcrumb" (lsp-feature? - "textDocument/documentSymbol") - "Td" lsp-ui-doc-mode "toggle documentation popup" (featurep 'lsp-ui-doc) - "Tf" lsp-toggle-on-type-formatting "toggle on type formatting" (lsp-feature? - "textDocument/onTypeFormatting") - "Th" lsp-toggle-symbol-highlight "toggle highlighting" (lsp-feature? "textDocument/documentHighlight") - "Tl" lsp-lens-mode "toggle lenses" (lsp-feature? "textDocument/codeLens") - "Ts" lsp-toggle-signature-auto-activate "toggle signature" (lsp-feature? "textDocument/signatureHelp") - - ;; goto - "ga" xref-find-apropos "find symbol in workspace" (lsp-feature? "workspace/symbol") - "gd" lsp-find-declaration "find declarations" (lsp-feature? "textDocument/declaration") - "ge" lsp-treemacs-errors-list "show errors" (fboundp 'lsp-treemacs-errors-list) - "gg" lsp-find-definition "find definitions" (lsp-feature? "textDocument/definition") - "gh" lsp-treemacs-call-hierarchy "call hierarchy" (and (lsp-feature? "callHierarchy/incomingCalls") - (fboundp 'lsp-treemacs-call-hierarchy)) - "gi" lsp-find-implementation "find implementations" (lsp-feature? "textDocument/implementation") - "gr" lsp-find-references "find references" (lsp-feature? "textDocument/references") - "gt" lsp-find-type-definition "find type definition" (lsp-feature? "textDocument/typeDefinition") - - ;; help - "hg" lsp-ui-doc-glance "glance symbol" (and (featurep 'lsp-ui-doc) - (lsp-feature? "textDocument/hover")) - "hh" lsp-describe-thing-at-point "describe symbol at point" (lsp-feature? "textDocument/hover") - "hs" lsp-signature-activate "signature help" (lsp-feature? "textDocument/signatureHelp") - - ;; refactoring - "ro" lsp-organize-imports "organize imports" (lsp-feature? "textDocument/codeAction") - "rr" lsp-rename "rename" (lsp-feature? "textDocument/rename") - - ;; actions - "aa" lsp-execute-code-action "code actions" (lsp-feature? "textDocument/codeAction") - "ah" lsp-document-highlight "highlight symbol" (lsp-feature? "textDocument/documentHighlight") - "al" lsp-avy-lens "lens" (and (bound-and-true-p lsp-lens-mode) (featurep 'avy)) - - ;; peeks - "Gg" lsp-ui-peek-find-definitions "peek definitions" (and (lsp-feature? "textDocument/definition") - (fboundp 'lsp-ui-peek-find-definitions)) - "Gi" lsp-ui-peek-find-implementation "peek implementations" (and - (fboundp 'lsp-ui-peek-find-implementation) - (lsp-feature? "textDocument/implementation")) - "Gr" lsp-ui-peek-find-references "peek references" (and (fboundp 'lsp-ui-peek-find-references) - (lsp-feature? "textDocument/references")) - "Gs" lsp-ui-peek-find-workspace-symbol "peek workspace symbol" (and (fboundp - 'lsp-ui-peek-find-workspace-symbol) - (lsp-feature? "workspace/symbol"))))) - - -;; which-key integration - -(declare-function which-key-add-major-mode-key-based-replacements "ext:which-key") -(declare-function which-key-add-key-based-replacements "ext:which-key") - -(defun lsp-enable-which-key-integration (&optional all-modes) - "Adds descriptions for `lsp-mode-map' to `which-key-mode' for the current -active `major-mode', or for all major modes when ALL-MODES is t." - (cl-flet ((which-key-fn (if all-modes - 'which-key-add-key-based-replacements - (apply-partially 'which-key-add-major-mode-key-based-replacements major-mode)))) - (apply - #'which-key-fn - (lsp--prepend-prefix - (cl-list* - "" "lsp" - "w" "workspaces" - "F" "folders" - "=" "formatting" - "T" "toggle" - "g" "goto" - "h" "help" - "r" "refactor" - "a" "code actions" - "G" "peek" - lsp--binding-descriptions))))) - - -;; Globbing syntax - -;; We port VSCode's glob-to-regexp code -;; (https://github.com/Microsoft/vscode/blob/466da1c9013c624140f6d1473b23a870abc82d44/src/vs/base/common/glob.ts) -;; since the LSP globbing syntax seems to be the same as that of -;; VSCode. - -(defconst lsp-globstar "**" - "Globstar pattern.") - -(defconst lsp-glob-split ?/ - "The character by which we split path components in a glob -pattern.") - -(defconst lsp-path-regexp "[/\\\\]" - "Forward or backslash to be used as a path separator in -computed regexps.") - -(defconst lsp-non-path-regexp "[^/\\\\]" - "A regexp matching anything other than a slash.") - -(defconst lsp-globstar-regexp - (format "\\(?:%s\\|%s+%s\\|%s%s+\\)*?" - lsp-path-regexp - lsp-non-path-regexp lsp-path-regexp - lsp-path-regexp lsp-non-path-regexp) - "Globstar in regexp form.") - -(defun lsp-split-glob-pattern (pattern split-char) - "Split PATTERN at SPLIT-CHAR while respecting braces and brackets." - (when pattern - (let ((segments nil) - (in-braces nil) - (in-brackets nil) - (current-segment "")) - (dolist (char (string-to-list pattern)) - (cl-block 'exit-point - (if (eq char split-char) - (when (and (null in-braces) - (null in-brackets)) - (push current-segment segments) - (setq current-segment "") - (cl-return-from 'exit-point)) - (pcase char - (?{ - (setq in-braces t)) - (?} - (setq in-braces nil)) - (?\[ - (setq in-brackets t)) - (?\] - (setq in-brackets nil)))) - (setq current-segment (concat current-segment - (char-to-string char))))) - (unless (string-empty-p current-segment) - (push current-segment segments)) - (nreverse segments)))) - -(defun lsp--glob-to-regexp (pattern) - "Helper function to convert a PATTERN from LSP's glob syntax to -an Elisp regexp." - (if (string-empty-p pattern) - "" - (let ((current-regexp "") - (glob-segments (lsp-split-glob-pattern pattern lsp-glob-split))) - (if (-all? (lambda (segment) (eq segment lsp-globstar)) - glob-segments) - ".*" - (let ((prev-segment-was-globstar nil)) - (seq-do-indexed - (lambda (segment index) - (if (string-equal segment lsp-globstar) - (unless prev-segment-was-globstar - (setq current-regexp (concat current-regexp - lsp-globstar-regexp)) - (setq prev-segment-was-globstar t)) - (let ((in-braces nil) - (brace-val "") - (in-brackets nil) - (bracket-val "")) - (dolist (char (string-to-list segment)) - (cond - ((and (not (char-equal char ?\})) - in-braces) - (setq brace-val (concat brace-val - (char-to-string char)))) - ((and in-brackets - (or (not (char-equal char ?\])) - (string-empty-p bracket-val))) - (let ((curr (cond - ((char-equal char ?-) - "-") - ;; NOTE: ?\^ and ?^ are different characters - ((and (memq char '(?^ ?!)) - (string-empty-p bracket-val)) - "^") - ((char-equal char lsp-glob-split) - "") - (t - (regexp-quote (char-to-string char)))))) - (setq bracket-val (concat bracket-val curr)))) - (t - (cl-case char - (?{ - (setq in-braces t)) - (?\[ - (setq in-brackets t)) - (?} - (let* ((choices (lsp-split-glob-pattern brace-val ?\,)) - (brace-regexp (concat "\\(?:" - (mapconcat #'lsp--glob-to-regexp choices "\\|") - "\\)"))) - (setq current-regexp (concat current-regexp - brace-regexp)) - (setq in-braces nil) - (setq brace-val ""))) - (?\] - (setq current-regexp - (concat current-regexp - "[" bracket-val "]")) - (setq in-brackets nil) - (setq bracket-val "")) - (?? - (setq current-regexp - (concat current-regexp - lsp-non-path-regexp))) - (?* - (setq current-regexp - (concat current-regexp - lsp-non-path-regexp "*?"))) - (t - (setq current-regexp - (concat current-regexp - (regexp-quote (char-to-string char))))))))) - (when (and (< index (1- (length glob-segments))) - (or (not (string-equal (nth (1+ index) glob-segments) - lsp-globstar)) - (< (+ index 2) - (length glob-segments)))) - (setq current-regexp - (concat current-regexp - lsp-path-regexp))) - (setq prev-segment-was-globstar nil)))) - glob-segments) - current-regexp))))) - -;; See https://github.com/emacs-lsp/lsp-mode/issues/2365 -(defun lsp-glob-unbrace-at-top-level (glob-pattern) - "If GLOB-PATTERN does not start with a brace, return a singleton list -containing GLOB-PATTERN. - -If GLOB-PATTERN does start with a brace, return a list of the -comma-separated globs within the top-level braces." - (if (not (string-prefix-p "{" glob-pattern)) - (list glob-pattern) - (lsp-split-glob-pattern (substring glob-pattern 1 -1) ?\,))) - -(defun lsp-glob-convert-to-wrapped-regexp (glob-pattern) - "Convert GLOB-PATTERN to a regexp wrapped with the beginning- -and end-of-string meta-characters." - (concat "\\`" (lsp--glob-to-regexp (string-trim glob-pattern)) "\\'")) - -(defun lsp-glob-to-regexps (glob-pattern) - "Convert a GLOB-PATTERN to a list of Elisp regexps." - (when-let* - ((glob-pattern (cond ((hash-table-p glob-pattern) - (ht-get glob-pattern "pattern")) - ((stringp glob-pattern) glob-pattern) - (t (error "Unknown glob-pattern type: %s" glob-pattern)))) - (trimmed-pattern (string-trim glob-pattern)) - (top-level-unbraced-patterns (lsp-glob-unbrace-at-top-level trimmed-pattern))) - (seq-map #'lsp-glob-convert-to-wrapped-regexp - top-level-unbraced-patterns))) - - - -(defvar lsp-mode-menu) - -(defun lsp-mouse-click (event) - (interactive "e") - (let* ((ec (event-start event)) - (choice (x-popup-menu event lsp-mode-menu)) - (action (lookup-key lsp-mode-menu (apply 'vector choice)))) - - (select-window (posn-window ec)) - - (unless (and (region-active-p) (eq action 'lsp-execute-code-action)) - (goto-char (posn-point ec))) - (run-with-idle-timer - 0.001 nil - (lambda () - (cl-labels ((check (value) (not (null value)))) - (when choice - (call-interactively action))))))) - -(defvar lsp-mode-map - (let ((map (make-sparse-keymap))) - (define-key map (kbd "C-<down-mouse-1>") #'lsp-find-definition-mouse) - (define-key map (kbd "C-<mouse-1>") #'ignore) - (define-key map (kbd "<mouse-3>") #'lsp-mouse-click) - (define-key map (kbd "C-S-SPC") #'lsp-signature-activate) - (when lsp-keymap-prefix - (define-key map (kbd lsp-keymap-prefix) lsp-command-map)) - map) - "Keymap for `lsp-mode'.") - -(define-minor-mode lsp-mode "Mode for LSP interaction." - :keymap lsp-mode-map - :lighter - (" LSP[" - (lsp--buffer-workspaces - (:eval (mapconcat #'lsp--workspace-print lsp--buffer-workspaces "][")) - (:propertize "Disconnected" face warning)) - "]") - :group 'lsp-mode - (when (and lsp-mode (not lsp--buffer-workspaces) (not lsp--buffer-deferred)) - ;; fire up `lsp' when someone calls `lsp-mode' instead of `lsp' - (lsp))) - -(defvar lsp-mode-menu - (easy-menu-create-menu - nil - `(["Go to definition" lsp-find-definition - :active (lsp-feature? "textDocument/definition")] - ["Find references" lsp-find-references - :active (lsp-feature? "textDocument/references")] - ["Find implementations" lsp-find-implementation - :active (lsp-feature? "textDocument/implementation")] - ["Find declarations" lsp-find-declaration - :active (lsp-feature? "textDocument/declaration")] - ["Go to type declaration" lsp-find-type-definition - :active (lsp-feature? "textDocument/typeDefinition")] - "--" - ["Describe" lsp-describe-thing-at-point] - ["Code action" lsp-execute-code-action] - ["Format" lsp-format-buffer] - ["Highlight references" lsp-document-highlight] - ["Type Hierarchy" lsp-java-type-hierarchy - :visible (lsp-can-execute-command? "java.navigate.resolveTypeHierarchy")] - ["Type Hierarchy" lsp-treemacs-type-hierarchy - :visible (and (not (lsp-can-execute-command? "java.navigate.resolveTypeHierarchy")) - (functionp 'lsp-treemacs-type-hierarchy) - (lsp-feature? "textDocument/typeHierarchy"))] - ["Call Hierarchy" lsp-treemacs-call-hierarchy - :visible (and (functionp 'lsp-treemacs-call-hierarchy) - (lsp-feature? "textDocument/callHierarchy"))] - ["Rename" lsp-rename - :active (lsp-feature? "textDocument/rename")] - "--" - ("Session" - ["View logs" lsp-workspace-show-log] - ["Describe" lsp-describe-session] - ["Shutdown" lsp-shutdown-workspace] - ["Restart" lsp-restart-workspace]) - ("Workspace Folders" - ["Add" lsp-workspace-folders-add] - ["Remove" lsp-workspace-folders-remove] - ["Open" lsp-workspace-folders-open]) - ("Toggle features" - ["Lenses" lsp-lens-mode] - ["Headerline breadcrumb" lsp-headerline-breadcrumb-mode] - ["Modeline code actions" lsp-modeline-code-actions-mode] - ["Modeline diagnostics" lsp-modeline-diagnostics-mode]) - "---" - ("Debug" - :active (bound-and-true-p dap-ui-mode) - :filter ,(lambda (_) - (and (boundp 'dap-ui-menu-items) - (nthcdr 3 dap-ui-menu-items)))))) - "Menu for lsp-mode.") - -(defalias 'make-lsp-client 'make-lsp--client) - -(cl-defstruct lsp--registered-capability - (id "") - (method " ") - (options nil)) - -;; A ‘lsp--workspace’ object represents exactly one language server process. -(cl-defstruct lsp--workspace - ;; the `ewoc' object for displaying I/O to and from the server - (ewoc nil) - - ;; ‘server-capabilities’ is a hash table of the language server capabilities. - ;; It is the hash table representation of a LSP ServerCapabilities structure; - ;; cf. https://microsoft.github.io/language-server-protocol/specification#initialize. - (server-capabilities nil) - - ;; ‘registered-server-capabilities’ is a list of hash tables that represent - ;; dynamically-registered Registration objects. See - ;; https://microsoft.github.io/language-server-protocol/specification#client_registerCapability. - (registered-server-capabilities nil) - - ;; ‘root’ is a directory name or a directory file name for the workspace - ;; root. ‘lsp-mode’ passes this directory to the ‘initialize’ method of the - ;; language server; see - ;; https://microsoft.github.io/language-server-protocol/specification#initialize. - (root nil) - - ;; ‘client’ is the ‘lsp--client’ object associated with this workspace. - (client nil) - - ;; ‘host-root’ contains the host root info as derived from `file-remote-p'. It - ;; used to derive the file path in `lsp--uri-to-path' when using tramp - ;; connection. - (host-root nil) - - ;; ‘proc’ is a process object; it may represent a regular process, a pipe, or - ;; a network connection. ‘lsp-mode’ communicates with ‘proc’ using the - ;; language server protocol. ‘proc’ corresponds to the COMMUNICATION-PROCESS - ;; element of the return value of the client’s ‘get-root’ field, which see. - (proc nil) - - ;; ‘proc’ is a process object; it must represent a regular process, not a - ;; pipe or network process. It represents the actual server process that - ;; corresponds to this workspace. ‘cmd-proc’ corresponds to the - ;; COMMAND-PROCESS element of the return value of the client’s ‘get-root’ - ;; field, which see. - (cmd-proc nil) - - ;; ‘buffers’ is a list of buffers associated with this workspace. - (buffers nil) - - ;; if semantic tokens is enabled, `semantic-tokens-faces' contains - ;; one face (or nil) for each token type supported by the language server. - (semantic-tokens-faces nil) - - ;; If semantic highlighting is enabled, `semantic-tokens-modifier-faces' - ;; contains one face (or nil) for each modifier type supported by the language - ;; server - (semantic-tokens-modifier-faces nil) - - ;; Extra client capabilities provided by third-party packages using - ;; `lsp-register-client-capabilities'. It's value is an alist of (PACKAGE-NAME - ;; . CAPS), where PACKAGE-NAME is a symbol of the third-party package name, - ;; and CAPS is either a plist of the client capabilities, or a function that - ;; takes no argument and returns a plist of the client capabilities or nil. - (extra-client-capabilities nil) - - ;; Workspace status - (status nil) - - ;; ‘metadata’ is a generic storage for workspace specific data. It is - ;; accessed via `lsp-workspace-set-metadata' and `lsp-workspace-set-metadata' - (metadata (make-hash-table :test 'equal)) - - ;; contains all the file notification watches that have been created for the - ;; current workspace in format filePath->file notification handle. - (watches (make-hash-table :test 'equal)) - - ;; list of workspace folders - (workspace-folders nil) - - ;; ‘last-id’ the last request id for the current workspace. - (last-id 0) - - ;; ‘status-string’ allows extensions to specify custom status string based on - ;; the Language Server specific messages. - (status-string nil) - - ;; ‘shutdown-action’ flag used to mark that workspace should not be restarted (e.g. it - ;; was stopped). - shutdown-action - - ;; ‘diagnostics’ a hashmap with workspace diagnostics. - (diagnostics (make-hash-table :test 'equal)) - - ;; contains all the workDone progress tokens that have been created - ;; for the current workspace. - (work-done-tokens (make-hash-table :test 'equal))) - - -(cl-defstruct lsp-session - ;; contains the folders that are part of the current session - folders - ;; contains the folders that must not be imported in the current workspace. - folders-blocklist - ;; contains the list of folders that must be imported in a project in case of - ;; multi root LSP server. - (server-id->folders (make-hash-table :test 'equal)) - ;; folder to list of the servers that are associated with the folder. - (folder->servers (make-hash-table :test 'equal)) - ;; ‘metadata’ is a generic storage for workspace specific data. It is - ;; accessed via `lsp-workspace-set-metadata' and `lsp-workspace-set-metadata' - (metadata (make-hash-table :test 'equal))) - -(defun lsp-workspace-status (status-string &optional workspace) - "Set current workspace status to STATUS-STRING. -If WORKSPACE is not specified defaults to lsp--cur-workspace." - (let ((status-string (when status-string (replace-regexp-in-string "%" "%%" status-string)))) - (setf (lsp--workspace-status-string (or workspace lsp--cur-workspace)) status-string))) - -(defun lsp-session-set-metadata (key value &optional _workspace) - "Associate KEY with VALUE in the WORKSPACE metadata. -If WORKSPACE is not provided current workspace will be used." - (puthash key value (lsp-session-metadata (lsp-session)))) - -(defalias 'lsp-workspace-set-metadata 'lsp-session-set-metadata) - -(defun lsp-session-get-metadata (key &optional _workspace) - "Lookup KEY in WORKSPACE metadata. -If WORKSPACE is not provided current workspace will be used." - (gethash key (lsp-session-metadata (lsp-session)))) - -(defalias 'lsp-workspace-get-metadata 'lsp-session-get-metadata) - -(defun lsp-workspace-set-work-done-token (token value workspace) - "Associate TOKEN with VALUE in the WORKSPACE work-done-tokens." - (puthash token value (lsp--workspace-work-done-tokens workspace))) - -(defun lsp-workspace-get-work-done-token (token workspace) - "Lookup TOKEN in the WORKSPACE work-done-tokens." - (gethash token (lsp--workspace-work-done-tokens workspace))) - -(defun lsp-workspace-rem-work-done-token (token workspace) - "Remove TOKEN from the WORKSPACE work-done-tokens." - (remhash token (lsp--workspace-work-done-tokens workspace))) - - -(defun lsp--make-notification (method &optional params) - "Create notification body for method METHOD and parameters PARAMS." - (list :jsonrpc "2.0" :method method :params params)) - -(defalias 'lsp--make-request 'lsp--make-notification) -(defalias 'lsp-make-request 'lsp--make-notification) - -(defun lsp--make-response (id result) - "Create response for REQUEST with RESULT." - `(:jsonrpc "2.0" :id ,id :result ,result)) - -(defun lsp-make-notification (method &optional params) - "Create notification body for method METHOD and parameters PARAMS." - (lsp--make-notification method params)) - -(defmacro lsp--json-serialize (params) - (if (progn - (require 'json) - (fboundp 'json-serialize)) - `(json-serialize ,params - :null-object nil - :false-object :json-false) - `(let ((json-false :json-false)) - (json-encode ,params)))) - -(defun lsp--make-message (params) - "Create a LSP message from PARAMS, after encoding it to a JSON string." - (let ((body (lsp--json-serialize params))) - (concat "Content-Length: " - (number-to-string (1+ (string-bytes body))) - "\r\n\r\n" - body - "\n"))) - -(cl-defstruct lsp--log-entry timestamp process-time type method id body) - -(defun lsp--make-log-entry (method id body type &optional process-time) - "Create an outgoing log object from BODY with method METHOD and id ID. -If ID is non-nil, then the body is assumed to be a notification. -TYPE can either be `incoming' or `outgoing'" - (cl-assert (memq type '(incoming-req outgoing-req incoming-notif - outgoing-notif incoming-resp - outgoing-resp))) - (make-lsp--log-entry - :timestamp (format-time-string "%I:%M:%S %p") - :process-time process-time - :method method - :id id - :type type - :body body)) - -(defun lsp--log-font-lock-json (body) - "Font lock JSON BODY." - (with-temp-buffer - (insert body) - ;; We set the temp buffer file-name extension to .json and call `set-auto-mode' - ;; so the users configured json mode is used which could be - ;; `json-mode', `json-ts-mode', `jsonian-mode', etc. - (let ((buffer-file-name "lsp-log.json")) - (delay-mode-hooks - (set-auto-mode) - (if (fboundp 'font-lock-ensure) - (font-lock-ensure) - (with-no-warnings - (font-lock-fontify-buffer))))) - (buffer-string))) - -(defun lsp--log-entry-pp (entry) - (cl-assert (lsp--log-entry-p entry)) - (pcase-let (((cl-struct lsp--log-entry timestamp method id type process-time - body) - entry) - (json-false :json-false) - (json-encoding-pretty-print t) - (str nil)) - (setq str - (concat (format "[Trace - %s] " timestamp) - (pcase type - ('incoming-req (format "Received request '%s - (%s)." method id)) - ('outgoing-req (format "Sending request '%s - (%s)'." method id)) - - ('incoming-notif (format "Received notification '%s'." method)) - ('outgoing-notif (format "Sending notification '%s'." method)) - - ('incoming-resp (format "Received response '%s - (%s)' in %dms." - method id process-time)) - ('outgoing-resp - (format - "Sending response '%s - (%s)'. Processing request took %dms" - method id process-time))) - "\n" - (if (memq type '(incoming-resp ougoing-resp)) - "Result: " - "Params: ") - (lsp--log-font-lock-json (json-encode body)) - "\n\n\n")) - (setq str (propertize str 'mouse-face 'highlight 'read-only t)) - (insert str))) - -(defvar-local lsp--log-io-ewoc nil) - -(defun lsp--get-create-io-ewoc (workspace) - (if (and (lsp--workspace-ewoc workspace) - (buffer-live-p (ewoc-buffer (lsp--workspace-ewoc workspace)))) - (lsp--workspace-ewoc workspace) - (with-current-buffer (lsp--get-log-buffer-create workspace) - (unless (eq 'lsp-log-io-mode major-mode) (lsp-log-io-mode)) - (setq-local window-point-insertion-type t) - (setq lsp--log-io-ewoc (ewoc-create #'lsp--log-entry-pp nil nil t)) - (setf (lsp--workspace-ewoc workspace) lsp--log-io-ewoc)) - (lsp--workspace-ewoc workspace))) - -(defun lsp--ewoc-count (ewoc) - (let* ((count 0) - (count-fn (lambda (_) (setq count (1+ count))))) - (ewoc-map count-fn ewoc) - count)) - -(defun lsp--log-entry-new (entry workspace) - (let* ((ewoc (lsp--get-create-io-ewoc workspace)) - (count (and (not (eq lsp-io-messages-max t)) (lsp--ewoc-count ewoc))) - (node (if (or (eq lsp-io-messages-max t) - (>= lsp-io-messages-max count)) - nil - (ewoc-nth ewoc (1- lsp-io-messages-max)))) - (prev nil) - (inhibit-read-only t)) - (while node - (setq prev (ewoc-prev ewoc node)) - (ewoc-delete ewoc node) - (setq node prev)) - (ewoc-enter-last ewoc entry))) - -(defun lsp--send-notification (body) - "Send BODY as a notification to the language server." - (lsp-foreach-workspace - (when (lsp--log-io-p (plist-get body :method)) - (lsp--log-entry-new (lsp--make-log-entry - (plist-get body :method) - nil (plist-get body :params) 'outgoing-notif) - lsp--cur-workspace)) - (lsp--send-no-wait body - (lsp--workspace-proc lsp--cur-workspace)))) - -(defalias 'lsp-send-notification 'lsp--send-notification) - -(defun lsp-notify (method params) - "Send notification METHOD with PARAMS." - (lsp--send-notification (lsp--make-notification method params))) - -(defun lsp--cur-workspace-check () - "Check whether buffer lsp workspace(s) are set." - (cl-assert (lsp-workspaces) nil - "No language server(s) is associated with this buffer.")) - -(defun lsp--send-request (body &optional no-wait no-merge) - "Send BODY as a request to the language server, get the response. -If NO-WAIT is non-nil, don't synchronously wait for a response. -If NO-MERGE is non-nil, don't merge the results but return an -alist mapping workspace->result." - (lsp-request (plist-get body :method) - (plist-get body :params) - :no-wait no-wait - :no-merge no-merge)) - -(defalias 'lsp-send-request 'lsp--send-request - "Send BODY as a request to the language server and return the response -synchronously. -\n(fn BODY)") - -(cl-defun lsp-request (method params &key no-wait no-merge) - "Send request METHOD with PARAMS. -If NO-MERGE is non-nil, don't merge the results but return alist -workspace->result. -If NO-WAIT is non-nil send the request as notification." - (if no-wait - (lsp-notify method params) - (let* ((send-time (float-time)) - ;; max time by which we must get a response - (expected-time - (and - lsp-response-timeout - (+ send-time lsp-response-timeout))) - resp-result resp-error done?) - (unwind-protect - (progn - (lsp-request-async method params - (lambda (res) (setf resp-result (or res :finished)) (throw 'lsp-done '_)) - :error-handler (lambda (err) (setf resp-error err) (throw 'lsp-done '_)) - :no-merge no-merge - :mode 'detached - :cancel-token :sync-request) - (while (not (or resp-error resp-result)) - (if (functionp 'json-rpc-connection) - (catch 'lsp-done (sit-for 0.01)) - (catch 'lsp-done - (accept-process-output - nil - (if expected-time (- expected-time send-time) 1)))) - (setq send-time (float-time)) - (when (and expected-time (< expected-time send-time)) - (error "Timeout while waiting for response. Method: %s" method))) - (setq done? t) - (cond - ((eq resp-result :finished) nil) - (resp-result resp-result) - ((lsp-json-error? resp-error) (error (lsp:json-error-message resp-error))) - ((lsp-json-error? (cl-first resp-error)) - (error (lsp:json-error-message (cl-first resp-error)))))) - (unless done? - (lsp-cancel-request-by-token :sync-request)))))) - -(cl-defun lsp-request-while-no-input (method params) - "Send request METHOD with PARAMS and waits until there is no input. -Return same value as `lsp--while-no-input' and respecting `non-essential'." - (if (or non-essential (not lsp-request-while-no-input-may-block)) - (let* ((send-time (float-time)) - ;; max time by which we must get a response - (expected-time - (and - lsp-response-timeout - (+ send-time lsp-response-timeout))) - resp-result resp-error done?) - (unwind-protect - (progn - (lsp-request-async method params - (lambda (res) (setf resp-result (or res :finished)) (throw 'lsp-done '_)) - :error-handler (lambda (err) (setf resp-error err) (throw 'lsp-done '_)) - :mode 'detached - :cancel-token :sync-request) - (while (not (or resp-error resp-result (input-pending-p))) - (catch 'lsp-done - (sit-for - (if expected-time (- expected-time send-time) 1))) - (setq send-time (float-time)) - (when (and expected-time (< expected-time send-time)) - (error "Timeout while waiting for response. Method: %s" method))) - (setq done? (or resp-error resp-result)) - (cond - ((eq resp-result :finished) nil) - (resp-result resp-result) - ((lsp-json-error? resp-error) (error (lsp:json-error-message resp-error))) - ((lsp-json-error? (cl-first resp-error)) - (error (lsp:json-error-message (cl-first resp-error)))))) - (unless done? - (lsp-cancel-request-by-token :sync-request)) - (when (and (input-pending-p) lsp--throw-on-input) - (throw 'input :interrupted)))) - (lsp-request method params))) - -(defvar lsp--cancelable-requests (ht)) - -(cl-defun lsp-request-async (method params callback - &key mode error-handler cancel-handler no-merge cancel-token) - "Send METHOD with PARAMS as a request to the language server. -Call CALLBACK with the response received from the server -asynchronously. -MODE determines when the callback will be called depending on the -condition of the original buffer. It could be: -- `detached' which means that the callback will be executed no -matter what has happened to the buffer. -- `alive' - the callback will be executed only if the buffer from -which the call was executed is still alive. -- `current' the callback will be executed only if the original buffer -is still selected. -- `tick' - the callback will be executed only if the buffer was not modified. -- `unchanged' - the callback will be executed only if the buffer hasn't -changed and if the buffer is not modified. - -ERROR-HANDLER will be called in case the request has failed. -CANCEL-HANDLER will be called in case the request is being canceled. -If NO-MERGE is non-nil, don't merge the results but return alist -workspace->result. -CANCEL-TOKEN is the token that can be used to cancel request." - (lsp--send-request-async `(:jsonrpc "2.0" :method ,method :params ,params) - callback mode error-handler cancel-handler no-merge cancel-token)) - -(defun lsp--create-request-cancel (id workspaces hook buf method cancel-callback) - (lambda (&rest _) - (unless (and (equal 'post-command-hook hook) - (equal (current-buffer) buf)) - (lsp--request-cleanup-hooks id) - (with-lsp-workspaces workspaces - (lsp--cancel-request id) - (when cancel-callback (funcall cancel-callback))) - (lsp-log "Cancelling %s(%s) in hook %s" method id hook)))) - -(defun lsp--create-async-callback - (callback method no-merge workspaces) - "Create async handler expecting COUNT results, merge them and call CALLBACK. -MODE determines when the callback will be called depending on the -condition of the original buffer. METHOD is the invoked method. -If NO-MERGE is non-nil, don't merge the results but return alist -workspace->result. ID is the request id." - (let (results errors) - (lambda (result) - (push (cons lsp--cur-workspace result) - (if (eq result :error) errors results)) - (when (and (not (eq (length errors) (length workspaces))) - (eq (+ (length errors) (length results)) (length workspaces))) - (funcall callback - (if no-merge - results - (lsp--merge-results (-map #'cl-rest results) method))))))) - -(defcustom lsp-default-create-error-handler-fn nil - "Default error handler customization. -Handler should give METHOD as argument and return function of one argument -ERROR." - :type 'function - :group 'lsp-mode - :package-version '(lsp-mode . "9.0.0")) - -(defun lsp--create-default-error-handler (method) - "Default error handler. -METHOD is the executed method." - (if lsp-default-create-error-handler-fn - (funcall lsp-default-create-error-handler-fn method) - (lambda (error) - (lsp--warn "%s" (or (lsp--error-string error) - (format "%s Request has failed" method)))))) - -(defvar lsp--request-cleanup-hooks (ht)) - -(defun lsp--request-cleanup-hooks (request-id) - (when-let ((cleanup-function (gethash request-id lsp--request-cleanup-hooks))) - (funcall cleanup-function) - (remhash request-id lsp--request-cleanup-hooks))) - -(defun lsp-cancel-request-by-token (cancel-token) - "Cancel request using CANCEL-TOKEN." - (-when-let ((request-id . workspaces) (gethash cancel-token lsp--cancelable-requests)) - (with-lsp-workspaces workspaces - (lsp--cancel-request request-id)) - (remhash cancel-token lsp--cancelable-requests) - (lsp--request-cleanup-hooks request-id))) - -(defun lsp--send-request-async (body callback - &optional mode error-callback cancel-callback - no-merge cancel-token) - "Send BODY as a request to the language server. -Call CALLBACK with the response received from the server -asynchronously. -MODE determines when the callback will be called depending on the -condition of the original buffer. It could be: -- `detached' which means that the callback will be executed no -matter what has happened to the buffer. -- `alive' - the callback will be executed only if the buffer from -which the call was executed is still alive. -- `current' the callback will be executed only if the original buffer -is still selected. -- `tick' - the callback will be executed only if the buffer was not modified. -- `unchanged' - the callback will be executed only if the buffer hasn't -changed and if the buffer is not modified. - -ERROR-CALLBACK will be called in case the request has failed. -CANCEL-CALLBACK will be called in case the request is being canceled. -If NO-MERGE is non-nil, don't merge the results but return alist -workspace->result. -CANCEL-TOKEN is the token that can be used to cancel request." - (when cancel-token - (lsp-cancel-request-by-token cancel-token)) - - (if-let ((target-workspaces (lsp--find-workspaces-for body))) - (let* ((start-time (current-time)) - (method (plist-get body :method)) - (id (cl-incf lsp-last-id)) - (buf (current-buffer)) - (cancel-callback (when cancel-callback - (pcase mode - ((or 'alive 'tick 'unchanged) - (lambda () - (with-current-buffer buf - (funcall cancel-callback)))) - (_ cancel-callback)))) - ;; calculate what are the (hook . local) pairs which will cancel - ;; the request - (hooks (pcase mode - ('alive '((kill-buffer-hook . t))) - ('tick '((kill-buffer-hook . t) (after-change-functions . t))) - ('unchanged '((after-change-functions . t) (post-command-hook . nil))) - ('current '((post-command-hook . nil))))) - ;; note: lambdas in emacs can be compared but we should make sure - ;; that all of the captured arguments are the same - in our case - ;; `lsp--create-request-cancel' will return the same lambda when - ;; called with the same params. - (cleanup-hooks - (lambda () (mapc - (-lambda ((hook . local)) - (if local - (when (buffer-live-p buf) - (with-current-buffer buf - (remove-hook hook - (lsp--create-request-cancel - id target-workspaces hook buf method cancel-callback) - t))) - (remove-hook hook (lsp--create-request-cancel - id target-workspaces hook buf method cancel-callback)))) - hooks) - (remhash cancel-token lsp--cancelable-requests))) - (callback (pcase mode - ((or 'alive 'tick 'unchanged) (lambda (&rest args) - (with-current-buffer buf - (apply callback args)))) - (_ callback))) - (callback (lsp--create-async-callback callback - method - no-merge - target-workspaces)) - (callback (lambda (result) - (lsp--request-cleanup-hooks id) - (funcall callback result))) - (error-callback (lsp--create-async-callback - (or error-callback - (lsp--create-default-error-handler method)) - method - nil - target-workspaces)) - (error-callback (lambda (error) - (funcall callback :error) - (lsp--request-cleanup-hooks id) - (funcall error-callback error))) - (body (plist-put body :id id))) - - ;; cancel request in any of the hooks - (mapc (-lambda ((hook . local)) - (add-hook hook - (lsp--create-request-cancel - id target-workspaces hook buf method cancel-callback) - nil local)) - hooks) - (puthash id cleanup-hooks lsp--request-cleanup-hooks) - - (setq lsp--last-active-workspaces target-workspaces) - - (when cancel-token - (puthash cancel-token (cons id target-workspaces) lsp--cancelable-requests)) - - (seq-doseq (workspace target-workspaces) - (when (lsp--log-io-p method) - (lsp--log-entry-new (lsp--make-log-entry method id - (plist-get body :params) - 'outgoing-req) - workspace)) - (puthash id - (list callback error-callback method start-time (current-time)) - (-> workspace - (lsp--workspace-client) - (lsp--client-response-handlers))) - (lsp--send-no-wait body (lsp--workspace-proc workspace))) - body) - (error "The connected server(s) does not support method %s. -To find out what capabilities support your server use `M-x lsp-describe-session' -and expand the capabilities section" - (plist-get body :method)))) - -;; deprecated, use lsp-request-async. -(defalias 'lsp-send-request-async 'lsp--send-request-async) -(make-obsolete 'lsp-send-request-async 'lsp-request-async "lsp-mode 7.0.1") - -;; Clean up the entire state of lsp mode when Emacs is killed, to get rid of any -;; pending language servers. -(add-hook 'kill-emacs-hook #'lsp--global-teardown) - -(defun lsp--global-teardown () - "Unload working workspaces." - (lsp-foreach-workspace (lsp--shutdown-workspace))) - -(defun lsp--shutdown-workspace (&optional restart) - "Shut down the language server process for ‘lsp--cur-workspace’." - (with-demoted-errors "LSP error: %S" - (let ((lsp-response-timeout 0.5)) - (condition-case err - (lsp-request "shutdown" nil) - (error (lsp--error "%s" err)))) - (lsp-notify "exit" nil)) - (setf (lsp--workspace-shutdown-action lsp--cur-workspace) (or (and restart 'restart) 'shutdown)) - (lsp--uninitialize-workspace)) - -(defcustom lsp-inlay-hint-enable nil - "If non-nil it will enable inlay hints." - :type 'boolean - :group 'lsp-mode - :package-version '(lsp-mode . "9.0.0")) - -(defun lsp--uninitialize-workspace () - "Cleanup buffer state. -When a workspace is shut down, by request or from just -disappearing, unset all the variables related to it." - (-let [(&lsp-wks 'cmd-proc 'buffers) lsp--cur-workspace] - (lsp-process-kill cmd-proc) - (mapc (lambda (buf) - (when (lsp-buffer-live-p buf) - (lsp-with-current-buffer buf - (lsp-managed-mode -1)))) - buffers) - (lsp-diagnostics--workspace-cleanup lsp--cur-workspace))) - -(defun lsp--client-capabilities (&optional custom-capabilities) - "Return the client capabilities appending CUSTOM-CAPABILITIES." - (append - `((general . ((positionEncodings . ["utf-32", "utf-16"]))) - (workspace . ((workspaceEdit . ((documentChanges . t) - (resourceOperations . ["create" "rename" "delete"]))) - (applyEdit . t) - (symbol . ((symbolKind . ((valueSet . ,(apply 'vector (number-sequence 1 26))))))) - (executeCommand . ((dynamicRegistration . :json-false))) - ,@(when lsp-enable-file-watchers '((didChangeWatchedFiles . ((dynamicRegistration . t))))) - (workspaceFolders . t) - (configuration . t) - ,@(when lsp-semantic-tokens-enable - `((semanticTokens . ((refreshSupport . ,(or (and (boundp 'lsp-semantic-tokens-honor-refresh-requests) - lsp-semantic-tokens-honor-refresh-requests) - :json-false)))))) - ,@(when lsp-lens-enable '((codeLens . ((refreshSupport . t))))) - ,@(when lsp-inlay-hint-enable '((inlayHint . ((refreshSupport . :json-false))))) - (fileOperations . ((didCreate . :json-false) - (willCreate . :json-false) - (didRename . t) - (willRename . t) - (didDelete . :json-false) - (willDelete . :json-false))))) - (textDocument . ((declaration . ((dynamicRegistration . t) - (linkSupport . t))) - (definition . ((dynamicRegistration . t) - (linkSupport . t))) - (references . ((dynamicRegistration . t))) - (implementation . ((dynamicRegistration . t) - (linkSupport . t))) - (typeDefinition . ((dynamicRegistration . t) - (linkSupport . t))) - (synchronization . ((willSave . t) (didSave . t) (willSaveWaitUntil . t))) - (documentSymbol . ((symbolKind . ((valueSet . ,(apply 'vector (number-sequence 1 26))))) - (hierarchicalDocumentSymbolSupport . t))) - (formatting . ((dynamicRegistration . t))) - (rangeFormatting . ((dynamicRegistration . t))) - (onTypeFormatting . ((dynamicRegistration . t))) - ,@(when (and lsp-semantic-tokens-enable - (functionp 'lsp--semantic-tokens-capabilities)) - (lsp--semantic-tokens-capabilities)) - (rename . ((dynamicRegistration . t) (prepareSupport . t))) - (codeAction . ((dynamicRegistration . t) - (isPreferredSupport . t) - (codeActionLiteralSupport . ((codeActionKind . ((valueSet . ["" - "quickfix" - "refactor" - "refactor.extract" - "refactor.inline" - "refactor.rewrite" - "source" - "source.organizeImports"]))))) - (resolveSupport . ((properties . ["edit" "command"]))) - (dataSupport . t))) - (completion . ((completionItem . ((snippetSupport . ,(cond - ((and lsp-enable-snippet (not (fboundp 'yas-minor-mode))) - (lsp--warn (concat - "Yasnippet is not installed, but `lsp-enable-snippet' is set to `t'. " - "You must either install yasnippet, or disable snippet support.")) - :json-false) - (lsp-enable-snippet t) - (t :json-false))) - (documentationFormat . ["markdown" "plaintext"]) - ;; Remove this after jdtls support resolveSupport - (resolveAdditionalTextEditsSupport . t) - (insertReplaceSupport . t) - (deprecatedSupport . t) - (resolveSupport - . ((properties . ["documentation" - "detail" - "additionalTextEdits" - "command"]))) - (insertTextModeSupport . ((valueSet . [1 2]))))) - (contextSupport . t) - (dynamicRegistration . t))) - (signatureHelp . ((signatureInformation . ((parameterInformation . ((labelOffsetSupport . t))))) - (dynamicRegistration . t))) - (documentLink . ((dynamicRegistration . t) - (tooltipSupport . t))) - (hover . ((contentFormat . ["markdown" "plaintext"]) - (dynamicRegistration . t))) - ,@(when lsp-enable-folding - `((foldingRange . ((dynamicRegistration . t) - ,@(when lsp-folding-range-limit - `((rangeLimit . ,lsp-folding-range-limit))) - ,@(when lsp-folding-line-folding-only - `((lineFoldingOnly . t))))))) - (selectionRange . ((dynamicRegistration . t))) - (callHierarchy . ((dynamicRegistration . :json-false))) - (typeHierarchy . ((dynamicRegistration . t))) - (publishDiagnostics . ((relatedInformation . t) - (tagSupport . ((valueSet . [1 2]))) - (versionSupport . t))) - (diagnostic . ((dynamicRegistration . :json-false) - (relatedDocumentSupport . :json-false))) - (linkedEditingRange . ((dynamicRegistration . t))))) - (window . ((workDoneProgress . t) - (showDocument . ((support . t)))))) - custom-capabilities)) - -(defun lsp-find-roots-for-workspace (workspace session) - "Get all roots for the WORKSPACE." - (-filter #'identity (ht-map (lambda (folder workspaces) - (when (-contains? workspaces workspace) - folder)) - (lsp-session-folder->servers session)))) - -(defun lsp-session-watches (&optional session) - "Get watches created for SESSION." - (or (gethash "__watches" (lsp-session-metadata (or session (lsp-session)))) - (-let [res (make-hash-table :test 'equal)] - (puthash "__watches" res (lsp-session-metadata (or session (lsp-session)))) - res))) - -(defun lsp--file-process-event (session root-folder event) - "Process file event." - (let* ((changed-file (cl-third event)) - (rel-changed-file (f-relative changed-file root-folder)) - (event-numeric-kind (alist-get (cl-second event) lsp--file-change-type)) - (bit-position (1- event-numeric-kind)) - (watch-bit (ash 1 bit-position))) - (->> - session - lsp-session-folder->servers - (gethash root-folder) - (seq-do (lambda (workspace) - (when (->> - workspace - lsp--workspace-registered-server-capabilities - (-any? - (lambda (capability) - (and - (equal (lsp--registered-capability-method capability) - "workspace/didChangeWatchedFiles") - (->> - capability - lsp--registered-capability-options - (lsp:did-change-watched-files-registration-options-watchers) - (seq-find - (-lambda ((fs-watcher &as &FileSystemWatcher :glob-pattern :kind? :_cachedRegexp cached-regexp)) - (when (or (null kind?) - (> (logand kind? watch-bit) 0)) - (-let [regexes (or cached-regexp - (let ((regexp (lsp-glob-to-regexps glob-pattern))) - (lsp-put fs-watcher :_cachedRegexp regexp) - regexp))] - (-any? (lambda (re) - (or (string-match re changed-file) - (string-match re rel-changed-file))) - regexes)))))))))) - (with-lsp-workspace workspace - (lsp-notify - "workspace/didChangeWatchedFiles" - `((changes . [((type . ,event-numeric-kind) - (uri . ,(lsp--path-to-uri changed-file)))])))))))))) - -(lsp-defun lsp--server-register-capability ((&Registration :method :id :register-options?)) - "Register capability REG." - (when (and lsp-enable-file-watchers - (equal method "workspace/didChangeWatchedFiles")) - (-let* ((created-watches (lsp-session-watches (lsp-session))) - (root-folders (cl-set-difference - (lsp-find-roots-for-workspace lsp--cur-workspace (lsp-session)) - (ht-keys created-watches)))) - ;; create watch for each root folder without such - (dolist (folder root-folders) - (let* ((watch (make-lsp-watch :root-directory folder)) - (ignored-things (lsp--get-ignored-regexes-for-workspace-root folder)) - (ignored-files-regex-list (car ignored-things)) - (ignored-directories-regex-list (cadr ignored-things))) - (puthash folder watch created-watches) - (lsp-watch-root-folder (file-truename folder) - (-partial #'lsp--file-process-event (lsp-session) folder) - ignored-files-regex-list - ignored-directories-regex-list - watch - t))))) - - (push - (make-lsp--registered-capability :id id :method method :options register-options?) - (lsp--workspace-registered-server-capabilities lsp--cur-workspace))) - -(defmacro lsp--with-workspace-temp-buffer (workspace-root &rest body) - "With a temp-buffer under `WORKSPACE-ROOT' and evaluate `BODY', useful to -access dir-local variables." - (declare (indent 1) (debug t)) - `(with-temp-buffer - ;; Set the buffer's name to something under the root so that we can hack the local variables - ;; This file doesn't need to exist and will not be created due to this. - (setq-local buffer-file-name (expand-file-name "lsp-mode-temp" (expand-file-name ,workspace-root))) - (hack-local-variables) - (prog1 ,@body - (setq-local buffer-file-name nil)))) - -(defun lsp--get-ignored-regexes-for-workspace-root (workspace-root) - "Return a list of the form -(lsp-file-watch-ignored-files lsp-file-watch-ignored-directories) for the given -WORKSPACE-ROOT." - ;; The intent of this function is to provide per-root workspace-level customization of the - ;; lsp-file-watch-ignored-directories and lsp-file-watch-ignored-files variables. - (lsp--with-workspace-temp-buffer workspace-root - (list lsp-file-watch-ignored-files (lsp-file-watch-ignored-directories)))) - - -(defun lsp--cleanup-hanging-watches () - "Cleanup watches in case there are no more workspaces that are interested -in that particular folder." - (let* ((session (lsp-session)) - (watches (lsp-session-watches session))) - (dolist (watched-folder (ht-keys watches)) - (when (-none? (lambda (workspace) - (with-lsp-workspace workspace - (lsp--registered-capability "workspace/didChangeWatchedFiles"))) - (gethash watched-folder (lsp-session-folder->servers (lsp-session)))) - (lsp-log "Cleaning up watches for folder %s. There is no workspace watching this folder..." watched-folder) - (lsp-kill-watch (gethash watched-folder watches)) - (remhash watched-folder watches))))) - -(lsp-defun lsp--server-unregister-capability ((&Unregistration :id :method)) - "Unregister capability UNREG." - (setf (lsp--workspace-registered-server-capabilities lsp--cur-workspace) - (seq-remove (lambda (e) (equal (lsp--registered-capability-id e) id)) - (lsp--workspace-registered-server-capabilities lsp--cur-workspace))) - (when (equal method "workspace/didChangeWatchedFiles") - (lsp--cleanup-hanging-watches))) - -(defun lsp--server-capabilities () - "Return the capabilities of the language server associated with the buffer." - (->> (lsp-workspaces) - (-keep #'lsp--workspace-server-capabilities) - (apply #'lsp-merge))) - -(defun lsp--send-open-close-p () - "Return whether open and close notifications should be sent to the server." - (let ((sync (lsp:server-capabilities-text-document-sync? (lsp--server-capabilities)))) - (or (memq sync '(1 2)) - (lsp:text-document-sync-options-open-close? sync)))) - -(defun lsp--send-will-save-p () - "Return whether willSave notifications should be sent to the server." - (-> (lsp--server-capabilities) - (lsp:server-capabilities-text-document-sync?) - (lsp:text-document-sync-options-will-save?))) - -(defun lsp--send-will-save-wait-until-p () - "Return whether willSaveWaitUntil notifications should be sent to the server." - (-> (lsp--server-capabilities) - (lsp:server-capabilities-text-document-sync?) - (lsp:text-document-sync-options-will-save-wait-until?))) - -(defun lsp--send-did-save-p () - "Return whether didSave notifications should be sent to the server." - (let ((sync (lsp:server-capabilities-text-document-sync? (lsp--server-capabilities)))) - (or (memq sync '(1 2)) - (lsp:text-document-sync-options-save? sync)))) - -(defun lsp--save-include-text-p () - "Return whether save notifications should include the text document's contents." - (->> (lsp--server-capabilities) - (lsp:server-capabilities-text-document-sync?) - (lsp:text-document-sync-options-save?) - (lsp:text-document-save-registration-options-include-text?))) - -(defun lsp--send-will-rename-files-p (path) - "Return whether willRenameFiles request should be sent to the server. -If any filters, checks if it applies for PATH." - (let* ((will-rename (-> (lsp--server-capabilities) - (lsp:server-capabilities-workspace?) - (lsp:workspace-server-capabilities-file-operations?) - (lsp:workspace-file-operations-will-rename?))) - (filters (seq-into (lsp:file-operation-registration-options-filters will-rename) 'list))) - (and will-rename - (or (seq-empty-p filters) - (-any? (-lambda ((&FileOperationFilter :scheme? :pattern (&FileOperationPattern :glob))) - (-let [regexes (lsp-glob-to-regexps glob)] - (and (or (not scheme?) - (string-prefix-p scheme? (lsp--path-to-uri path))) - (-any? (lambda (re) - (string-match re path)) - regexes)))) - filters))))) - -(defun lsp--send-did-rename-files-p () - "Return whether didRenameFiles notification should be sent to the server." - (-> (lsp--server-capabilities) - (lsp:server-capabilities-workspace?) - (lsp:workspace-server-capabilities-file-operations?) - (lsp:workspace-file-operations-did-rename?))) - -(declare-function project-roots "ext:project" (project) t) -(declare-function project-root "ext:project" (project) t) - -(defun lsp--suggest-project-root () - "Get project root." - (or - (when (fboundp 'projectile-project-root) - (condition-case nil - (projectile-project-root) - (error nil))) - (when (fboundp 'project-current) - (when-let ((project (project-current))) - (if (fboundp 'project-root) - (project-root project) - (car (with-no-warnings - (project-roots project)))))) - default-directory)) - -(defun lsp--read-from-file (file) - "Read FILE content." - (when (file-exists-p file) - (cl-first (read-from-string (f-read-text file 'utf-8))))) - -(defun lsp--persist (file-name to-persist) - "Persist TO-PERSIST in FILE-NAME. - -This function creates the parent directories if they don't exist -yet." - (let ((print-length nil) - (print-level nil)) - ;; Create all parent directories: - (make-directory (f-parent file-name) t) - (f-write-text (prin1-to-string to-persist) 'utf-8 file-name))) - -(defun lsp-workspace-folders-add (project-root) - "Add PROJECT-ROOT to the list of workspace folders." - (interactive - (list (read-directory-name "Select folder to add: " - (or (lsp--suggest-project-root) default-directory) nil t))) - (cl-pushnew (lsp-f-canonical project-root) - (lsp-session-folders (lsp-session)) :test 'equal) - (lsp--persist-session (lsp-session)) - - (run-hook-with-args 'lsp-workspace-folders-changed-functions (list project-root) nil)) - -(defun lsp-workspace-folders-remove (project-root) - "Remove PROJECT-ROOT from the list of workspace folders." - (interactive (list (completing-read "Select folder to remove: " - (lsp-session-folders (lsp-session)) - nil t nil nil - (lsp-find-session-folder (lsp-session) default-directory)))) - - (setq project-root (lsp-f-canonical project-root)) - - ;; send remove folder to each multiroot workspace associated with the folder - (dolist (wks (->> (lsp-session) - (lsp-session-folder->servers) - (gethash project-root) - (--filter (lsp--client-multi-root (lsp--workspace-client it))))) - (with-lsp-workspace wks - (lsp-notify "workspace/didChangeWorkspaceFolders" - (lsp-make-did-change-workspace-folders-params - :event (lsp-make-workspace-folders-change-event - :removed (vector (lsp-make-workspace-folder - :uri (lsp--path-to-uri project-root) - :name (f-filename project-root))) - :added []))))) - - ;; turn off servers in the removed directory - (let* ((session (lsp-session)) - (folder->servers (lsp-session-folder->servers session)) - (server-id->folders (lsp-session-server-id->folders session)) - (workspaces (gethash project-root folder->servers))) - - (remhash project-root folder->servers) - - ;; turn off the servers without root folders - (dolist (workspace workspaces) - (when (--none? (-contains? it workspace) (ht-values folder->servers)) - (lsp--info "Shutdown %s since folder %s is removed..." - (lsp--workspace-print workspace) project-root) - (with-lsp-workspace workspace (lsp--shutdown-workspace)))) - - (setf (lsp-session-folders session) - (-remove-item project-root (lsp-session-folders session))) - - (ht-aeach (puthash key - (-remove-item project-root value) - server-id->folders) - server-id->folders) - (lsp--persist-session (lsp-session))) - - (run-hook-with-args 'lsp-workspace-folders-changed-functions nil (list project-root))) - -(defun lsp-workspace-blocklist-remove (project-root) - "Remove PROJECT-ROOT from the workspace blocklist." - (interactive (list (completing-read "Select folder to remove:" - (lsp-session-folders-blocklist (lsp-session)) - nil t))) - (setf (lsp-session-folders-blocklist (lsp-session)) - (delete project-root - (lsp-session-folders-blocklist (lsp-session)))) - (lsp--persist-session (lsp-session))) - -(define-obsolete-function-alias 'lsp-workspace-folders-switch - 'lsp-workspace-folders-open "lsp-mode 6.1") - -(defun lsp-workspace-folders-open (project-root) - "Open the directory located at PROJECT-ROOT" - (interactive (list (completing-read "Open folder: " - (lsp-session-folders (lsp-session)) - nil t))) - (find-file project-root)) - -(defun lsp--maybe-enable-signature-help (trigger-characters) - (let ((ch last-command-event)) - (when (cl-find ch trigger-characters :key #'string-to-char) - (lsp-signature-activate)))) - -(defun lsp--on-type-formatting-handler-create () - (when-let ((provider (lsp--capability-for-method "textDocument/onTypeFormatting" ))) - (-let [(&DocumentOnTypeFormattingOptions :more-trigger-character? - :first-trigger-character) provider] - (lambda () - (lsp--on-type-formatting first-trigger-character - more-trigger-character?))))) - -(defun lsp--update-on-type-formatting-hook (&optional cleanup?) - (let ((on-type-formatting-handler (lsp--on-type-formatting-handler-create))) - (cond - ((and lsp-enable-on-type-formatting on-type-formatting-handler (not cleanup?)) - (add-hook 'post-self-insert-hook on-type-formatting-handler nil t)) - ((or cleanup? - (not lsp-enable-on-type-formatting)) - (remove-hook 'post-self-insert-hook on-type-formatting-handler t))))) - -(defun lsp--signature-help-handler-create () - (-when-let ((&SignatureHelpOptions? :trigger-characters?) - (lsp--capability-for-method "textDocument/signatureHelp")) - (lambda () - (lsp--maybe-enable-signature-help trigger-characters?)))) - -(defun lsp--update-signature-help-hook (&optional cleanup?) - (let ((signature-help-handler (lsp--signature-help-handler-create))) - (cond - ((and (or (equal lsp-signature-auto-activate t) - (memq :on-trigger-char lsp-signature-auto-activate)) - signature-help-handler - (not cleanup?)) - (add-hook 'post-self-insert-hook signature-help-handler nil t)) - - ((or cleanup? - (not (or (equal lsp-signature-auto-activate t) - (memq :on-trigger-char lsp-signature-auto-activate)))) - (remove-hook 'post-self-insert-hook signature-help-handler t))))) - -(defun lsp--after-set-visited-file-name () - (lsp-disconnect) - (lsp)) - -;; TODO remove those eldoc workarounds when dropping support for Emacs 27 -;; https://github.com/emacs-lsp/lsp-mode/issues/3295#issuecomment-1308994099 -(defvar eldoc-documentation-default) ; CI -(when (< emacs-major-version 28) - (unless (boundp 'eldoc-documentation-functions) - (load "eldoc" nil 'nomessage)) - (when (memq (default-value 'eldoc-documentation-function) '(nil ignore)) - ;; actually `eldoc-documentation-strategy', but CI was failing - (setq-default eldoc-documentation-function 'eldoc-documentation-default))) - -(define-minor-mode lsp-managed-mode - "Mode for source buffers managed by lsp-mode." - :lighter nil - (cond - (lsp-managed-mode - (when (lsp-feature? "textDocument/hover") - (add-hook 'eldoc-documentation-functions #'lsp-eldoc-function nil t) - (eldoc-mode 1)) - - (add-hook 'after-change-functions #'lsp-on-change nil t) - (add-hook 'after-revert-hook #'lsp-on-revert nil t) - (add-hook 'after-save-hook #'lsp-on-save nil t) - (add-hook 'auto-save-hook #'lsp--on-auto-save nil t) - (add-hook 'before-change-functions #'lsp-before-change nil t) - (add-hook 'before-save-hook #'lsp--before-save nil t) - (add-hook 'kill-buffer-hook #'lsp--text-document-did-close nil t) - (add-hook 'post-command-hook #'lsp--post-command nil t) - - (lsp--update-on-type-formatting-hook) - (lsp--update-signature-help-hook) - - (when lsp-enable-xref - (add-hook 'xref-backend-functions #'lsp--xref-backend nil t)) - - (lsp-configure-buffer) - - ;; make sure we turn off lsp-mode in case major mode changes, because major - ;; mode change will wipe the buffer locals. - (add-hook 'change-major-mode-hook #'lsp-disconnect nil t) - (add-hook 'after-set-visited-file-name-hook #'lsp--after-set-visited-file-name nil t) - - (let ((buffer (lsp-current-buffer))) - (run-with-idle-timer - 0.0 nil - (lambda () - (when (lsp-buffer-live-p buffer) - (lsp-with-current-buffer buffer - (lsp--on-change-debounce buffer) - (lsp--on-idle buffer))))))) - (t - (lsp-unconfig-buffer) - - (remove-hook 'eldoc-documentation-functions #'lsp-eldoc-function t) - (remove-hook 'post-command-hook #'lsp--post-command t) - (remove-hook 'after-change-functions #'lsp-on-change t) - (remove-hook 'after-revert-hook #'lsp-on-revert t) - (remove-hook 'after-save-hook #'lsp-on-save t) - (remove-hook 'auto-save-hook #'lsp--on-auto-save t) - (remove-hook 'before-change-functions #'lsp-before-change t) - (remove-hook 'before-save-hook #'lsp--before-save t) - (remove-hook 'kill-buffer-hook #'lsp--text-document-did-close t) - - (lsp--update-on-type-formatting-hook :cleanup) - (lsp--update-signature-help-hook :cleanup) - - (when lsp--on-idle-timer - (cancel-timer lsp--on-idle-timer) - (setq lsp--on-idle-timer nil)) - - (remove-hook 'lsp-on-idle-hook #'lsp--document-links t) - (remove-hook 'lsp-on-idle-hook #'lsp--document-highlight t) - - (lsp--remove-overlays 'lsp-highlight) - (lsp--remove-overlays 'lsp-links) - - (remove-hook 'xref-backend-functions #'lsp--xref-backend t) - (remove-hook 'change-major-mode-hook #'lsp-disconnect t) - (remove-hook 'after-set-visited-file-name-hook #'lsp--after-set-visited-file-name t) - (setq-local lsp-buffer-uri nil)))) - -(defun lsp-configure-buffer () - "Configure LSP features for current buffer." - ;; make sure the core is running in the context of all available workspaces - ;; to avoid misconfiguration in case we are running in `with-lsp-workspace' context - (let ((lsp--buffer-workspaces (cond - (lsp--buffer-workspaces) - (lsp--cur-workspace (list lsp--cur-workspace)))) - lsp--cur-workspace) - (when lsp-auto-configure - (lsp--auto-configure) - - (when (and lsp-enable-text-document-color - (lsp-feature? "textDocument/documentColor")) - (add-hook 'lsp-on-change-hook #'lsp--document-color nil t)) - - (when (and lsp-enable-imenu - (lsp-feature? "textDocument/documentSymbol")) - (lsp-enable-imenu)) - - (when (and lsp-enable-indentation - (lsp-feature? "textDocument/rangeFormatting")) - (add-function :override (local 'indent-region-function) #'lsp-format-region)) - - (when (and lsp-enable-symbol-highlighting - (lsp-feature? "textDocument/documentHighlight")) - (add-hook 'lsp-on-idle-hook #'lsp--document-highlight nil t)) - - (when (and lsp-enable-links - (lsp-feature? "textDocument/documentLink")) - (add-hook 'lsp-on-idle-hook #'lsp--document-links nil t)) - - (when (and lsp-inlay-hint-enable - (lsp-feature? "textDocument/inlayHint")) - (lsp-inlay-hints-mode)) - - (when (and lsp-enable-dap-auto-configure - (functionp 'dap-mode)) - (dap-auto-configure-mode 1))) - (run-hooks 'lsp-configure-hook))) - -(defun lsp-unconfig-buffer () - "Unconfigure LSP features for buffer." - (lsp--remove-overlays 'lsp-color) - - (when (advice-function-member-p 'lsp--imenu-create-index imenu-create-index-function) - (remove-function (local 'imenu-create-index-function) #'lsp--imenu-create-index) - (setq-local imenu-menubar-modified-tick 0) - (setq-local imenu--index-alist nil) - (imenu--cleanup)) - - (remove-function (local 'indent-region-function) #'lsp-format-region) - - (remove-hook 'lsp-on-change-hook #'lsp--document-color t) - (remove-hook 'lsp-on-idle-hook #'lsp--document-highlight t) - (remove-hook 'lsp-on-idle-hook #'lsp--document-links t) - - (when (and lsp-enable-dap-auto-configure - (functionp 'dap-mode)) - (dap-auto-configure-mode -1)) - - (run-hooks 'lsp-unconfigure-hook)) - -(defun lsp--buffer-content () - (lsp-save-restriction-and-excursion - (or (lsp-virtual-buffer-call :buffer-string) - (buffer-substring-no-properties (point-min) - (point-max))))) - -(defun lsp--text-document-did-open () - "`document/didOpen' event." - (run-hooks 'lsp-before-open-hook) - (when (and lsp-auto-touch-files - (not (f-exists? (lsp--uri-to-path (lsp--buffer-uri))))) - (lsp--info "Saving file '%s' because it is not present on the disk." (lsp--buffer-uri)) - (save-buffer)) - - (setq lsp--cur-version (or lsp--cur-version 0)) - (cl-pushnew (lsp-current-buffer) (lsp--workspace-buffers lsp--cur-workspace)) - (lsp-notify - "textDocument/didOpen" - (list :textDocument - (list :uri (lsp--buffer-uri) - :languageId (lsp-buffer-language) - :version lsp--cur-version - :text (lsp--buffer-content)))) - - (lsp-managed-mode 1) - - (lsp-diagnostics--request-pull-diagnostics lsp--cur-workspace) - - (run-hooks 'lsp-after-open-hook) - (when-let ((client (-some-> lsp--cur-workspace (lsp--workspace-client)))) - (-some-> (lsp--client-after-open-fn client) - (funcall)) - (-some-> (format "lsp-%s-after-open-hook" (lsp--client-server-id client)) - (intern-soft) - (run-hooks)))) - -(defun lsp--text-document-identifier () - "Make TextDocumentIdentifier." - (list :uri (lsp--buffer-uri))) - -(defun lsp--versioned-text-document-identifier () - "Make VersionedTextDocumentIdentifier." - (plist-put (lsp--text-document-identifier) :version lsp--cur-version)) - -(defun lsp--cur-line (&optional point) - (1- (line-number-at-pos point))) - -(defun lsp--cur-position () - "Make a Position object for the current point." - (or (lsp-virtual-buffer-call :cur-position) - (lsp-save-restriction-and-excursion - (list :line (lsp--cur-line) - :character (- (point) (line-beginning-position)))))) - -(defun lsp--point-to-position (point) - "Convert POINT to Position." - (lsp-save-restriction-and-excursion - (goto-char point) - (lsp--cur-position))) - -(defun lsp--range (start end) - "Make Range body from START and END." - ;; make sure start and end are Position objects - (list :start start :end end)) - -(defun lsp--region-to-range (start end) - "Make Range object for the current region." - (lsp--range (lsp--point-to-position start) - (lsp--point-to-position end))) - -(defun lsp--region-or-line () - "The active region or the current line." - (if (use-region-p) - (lsp--region-to-range (region-beginning) (region-end)) - (lsp--region-to-range (line-beginning-position) (line-end-position)))) - -(defun lsp--check-document-changes-version (document-changes) - "Verify that DOCUMENT-CHANGES have the proper version." - (unless (seq-every-p - (-lambda ((&TextDocumentEdit :text-document)) - (or - (not text-document) - (let* ((filename (-> text-document - lsp:versioned-text-document-identifier-uri - lsp--uri-to-path)) - (version (lsp:versioned-text-document-identifier-version? text-document))) - (with-current-buffer (find-file-noselect filename) - (or (null version) (zerop version) (= -1 version) - (equal version lsp--cur-version)))))) - document-changes) - (error "Document changes cannot be applied due to different document version"))) - -(defun lsp--apply-workspace-edit (workspace-edit &optional operation) - "Apply the WorkspaceEdit object WORKSPACE-EDIT. -OPERATION is symbol representing the source of this text edit." - (-let (((&WorkspaceEdit :document-changes? :changes?) workspace-edit)) - (if-let ((document-changes (seq-reverse document-changes?))) - (progn - (lsp--check-document-changes-version document-changes) - (->> document-changes - (seq-filter (-lambda ((&CreateFile :kind)) (equal kind "create"))) - (seq-do (lambda (change) (lsp--apply-text-document-edit change operation)))) - (->> document-changes - (seq-filter (-lambda ((&CreateFile :kind)) - (and (or (not kind) (equal kind "edit")) - (not (equal kind "create"))))) - (seq-do (lambda (change) (lsp--apply-text-document-edit change operation)))) - (->> document-changes - (seq-filter (-lambda ((&CreateFile :kind)) - (and (not (or (not kind) (equal kind "edit"))) - (not (equal kind "create"))))) - (seq-do (lambda (change) (lsp--apply-text-document-edit change operation))))) - (lsp-map - (lambda (uri text-edits) - (with-current-buffer (-> uri lsp--uri-to-path find-file-noselect) - (lsp--apply-text-edits text-edits operation))) - changes?)))) - -(defmacro lsp-with-filename (file &rest body) - "Execute BODY with FILE as a context. -Need to handle the case when FILE indicates virtual buffer." - (declare (indent 1) (debug t)) - `(if-let ((lsp--virtual-buffer (get-text-property 0 'lsp-virtual-buffer ,file))) - (lsp-with-current-buffer lsp--virtual-buffer - ,@body) - ,@body)) - -(defun lsp--apply-text-document-edit (edit &optional operation) - "Apply the TextDocumentEdit object EDIT. -OPERATION is symbol representing the source of this text edit. -If the file is not being visited by any buffer, it is opened with -`find-file-noselect'. -Because lsp-mode does not store previous document versions, the edit is only -applied if the version of the textDocument matches the version of the -corresponding file. - -interface TextDocumentEdit { - textDocument: VersionedTextDocumentIdentifier; - edits: TextEdit[]; -}" - (pcase (lsp:edit-kind edit) - ("create" (-let* (((&CreateFile :uri :options?) edit) - (file-name (lsp--uri-to-path uri))) - (mkdir (f-dirname file-name) t) - (f-touch file-name) - (when (lsp:create-file-options-overwrite? options?) - (f-write-text "" nil file-name)) - (find-file-noselect file-name))) - ("delete" (-let (((&DeleteFile :uri :options? (&DeleteFileOptions? :recursive?)) edit)) - (f-delete (lsp--uri-to-path uri) recursive?))) - ("rename" (-let* (((&RenameFile :old-uri :new-uri :options? (&RenameFileOptions? :overwrite?)) edit) - (old-file-name (lsp--uri-to-path old-uri)) - (new-file-name (lsp--uri-to-path new-uri)) - (buf (find-buffer-visiting old-file-name))) - (when buf - (lsp-with-current-buffer buf - (save-buffer) - (lsp--text-document-did-close))) - (mkdir (f-dirname new-file-name) t) - (rename-file old-file-name new-file-name overwrite?) - (when buf - (lsp-with-current-buffer buf - (set-buffer-modified-p nil) - (setq lsp-buffer-uri nil) - (set-visited-file-name new-file-name) - (lsp))))) - (_ (let ((file-name (->> edit - (lsp:text-document-edit-text-document) - (lsp:versioned-text-document-identifier-uri) - (lsp--uri-to-path)))) - (lsp-with-current-buffer (find-buffer-visiting file-name) - (lsp-with-filename file-name - (lsp--apply-text-edits (lsp:text-document-edit-edits edit) operation))))))) - -(lsp-defun lsp--position-compare ((&Position :line left-line - :character left-character) - (&Position :line right-line - :character right-character)) - "Return t if position LEFT is greater than RIGHT." - (if (= left-line right-line) - (> left-character right-character) - (> left-line right-line))) - -(lsp-defun lsp-point-in-range? (position (&Range :start :end)) - "Returns if POINT is in RANGE." - (not (or (lsp--position-compare start position) - (lsp--position-compare position end)))) - -(lsp-defun lsp--position-equal ((&Position :line left-line - :character left-character) - (&Position :line right-line - :character right-character)) - "Return whether LEFT and RIGHT positions are equal." - (and (= left-line right-line) - (= left-character right-character))) - -(lsp-defun lsp--text-edit-sort-predicate ((&TextEdit :range (&Range :start left-start :end left-end)) - (&TextEdit :range (&Range :start right-start :end right-end))) - (if (lsp--position-equal left-start right-start) - (lsp--position-compare left-end right-end) - (lsp--position-compare left-start right-start))) - -(lsp-defun lsp--apply-text-edit ((edit &as &TextEdit :range (&RangeToPoint :start :end) :new-text)) - "Apply the edits described in the TextEdit object in TEXT-EDIT." - (setq new-text (s-replace "\r" "" (or new-text ""))) - (lsp:set-text-edit-new-text edit new-text) - (goto-char start) - (delete-region start end) - (insert new-text)) - -;; WORKAROUND: typescript-language might send -1 when applying code actions. -;; see https://github.com/emacs-lsp/lsp-mode/issues/1582 -(lsp-defun lsp--fix-point ((point &as &Position :character :line)) - (-doto point - (lsp:set-position-line (max 0 line)) - (lsp:set-position-character (max 0 character)))) - -(lsp-defun lsp--apply-text-edit-replace-buffer-contents ((edit &as - &TextEdit - :range (&Range :start :end) - :new-text)) - "Apply the edits described in the TextEdit object in TEXT-EDIT. -The method uses `replace-buffer-contents'." - (setq new-text (s-replace "\r" "" (or new-text ""))) - (lsp:set-text-edit-new-text edit new-text) - (-let* ((source (current-buffer)) - ((beg . end) (lsp--range-to-region (lsp-make-range :start (lsp--fix-point start) - :end (lsp--fix-point end))))) - (with-temp-buffer - (insert new-text) - (let ((temp (current-buffer))) - (with-current-buffer source - (save-excursion - (save-restriction - (narrow-to-region beg end) - - ;; On emacs versions < 26.2, - ;; `replace-buffer-contents' is buggy - it calls - ;; change functions with invalid arguments - so we - ;; manually call the change functions here. - ;; - ;; See emacs bugs #32237, #32278: - ;; https://debbugs.gnu.org/cgi/bugreport.cgi?bug=32237 - ;; https://debbugs.gnu.org/cgi/bugreport.cgi?bug=32278 - (let ((inhibit-modification-hooks t) - (length (- end beg))) - (run-hook-with-args 'before-change-functions - beg end) - (replace-buffer-contents temp) - (run-hook-with-args 'after-change-functions - beg (+ beg (length new-text)) - length))))))))) - -(defun lsp--to-yasnippet-snippet (snippet) - "Convert LSP SNIPPET to yasnippet snippet." - ;; LSP snippet doesn't escape "{" and "`", but yasnippet requires escaping it. - (replace-regexp-in-string (rx (or bos (not (any "$" "\\"))) (group (or "{" "`"))) - (rx "\\" (backref 1)) - snippet - nil nil 1)) - -(defvar-local lsp-enable-relative-indentation nil - "Enable relative indentation when insert texts, snippets ... -from language server.") - -(defun lsp--expand-snippet (snippet &optional start end expand-env) - "Wrapper of `yas-expand-snippet' with all of it arguments. -The snippet will be convert to LSP style and indent according to -LSP server result." - (require 'yasnippet nil t) - (let* ((inhibit-field-text-motion t) - (yas-wrap-around-region nil) - (yas-indent-line 'none) - (yas-also-auto-indent-first-line nil)) - (yas-expand-snippet - (lsp--to-yasnippet-snippet snippet) - start end expand-env))) - -(defun lsp--indent-lines (start end &optional insert-text-mode?) - "Indent from START to END based on INSERT-TEXT-MODE? value. -- When INSERT-TEXT-MODE? is provided - - if it's `lsp/insert-text-mode-as-it', do no editor indentation. - - if it's `lsp/insert-text-mode-adjust-indentation', adjust leading - whitespaces to match the line where text is inserted. -- When it's not provided, using `indent-line-function' for each line." - (save-excursion - (goto-char end) - (let* ((end-line (line-number-at-pos)) - (offset (save-excursion - (goto-char start) - (current-indentation))) - (indent-line-function - (cond ((equal insert-text-mode? lsp/insert-text-mode-as-it) - #'ignore) - ((or (equal insert-text-mode? lsp/insert-text-mode-adjust-indentation) - lsp-enable-relative-indentation - ;; Indenting snippets is extremely slow in `org-mode' buffers - ;; since it has to calculate indentation based on SRC block - ;; position. Thus we use relative indentation as default. - (derived-mode-p 'org-mode)) - (lambda () (save-excursion - (beginning-of-line) - (indent-to-column offset)))) - (t indent-line-function)))) - (goto-char start) - (forward-line) - (while (and (not (eobp)) - (<= (line-number-at-pos) end-line)) - (funcall indent-line-function) - (forward-line))))) - -(defun lsp--apply-text-edits (edits &optional operation) - "Apply the EDITS described in the TextEdit[] object. -OPERATION is symbol representing the source of this text edit." - (unless (seq-empty-p edits) - (atomic-change-group - (run-hooks 'lsp-before-apply-edits-hook) - (let* ((change-group (prepare-change-group)) - (howmany (length edits)) - (message (format "Applying %s edits to `%s' ..." howmany (current-buffer))) - (_ (lsp--info message)) - (reporter (make-progress-reporter message 0 howmany)) - (done 0) - (apply-edit (if (not lsp--virtual-buffer) - #'lsp--apply-text-edit-replace-buffer-contents - #'lsp--apply-text-edit))) - (unwind-protect - (->> edits - ;; We sort text edits so as to apply edits that modify latter - ;; parts of the document first. Furthermore, because the LSP - ;; spec dictates that: "If multiple inserts have the same - ;; position, the order in the array defines which edit to - ;; apply first." We reverse the initial list and sort stably - ;; to make sure the order among edits with the same position - ;; is preserved. - (nreverse) - (seq-sort #'lsp--text-edit-sort-predicate) - (mapc (lambda (edit) - (progress-reporter-update reporter (cl-incf done)) - (funcall apply-edit edit) - (when (lsp:snippet-text-edit-insert-text-format? edit) - (-when-let ((&SnippetTextEdit :range (&RangeToPoint :start) - :insert-text-format? :new-text) edit) - (when (eq insert-text-format? lsp/insert-text-format-snippet) - ;; No `save-excursion' needed since expand snippet will change point anyway - (goto-char (+ start (length new-text))) - (lsp--indent-lines start (point)) - (lsp--expand-snippet new-text start (point))))) - (run-hook-with-args 'lsp-after-apply-edits-hook operation)))) - (undo-amalgamate-change-group change-group) - (progress-reporter-done reporter)))))) - -(defun lsp--create-apply-text-edits-handlers () - "Create (handler cleanup-fn) for applying text edits in async request. -Only works when mode is `tick or `alive." - (let* (first-edited - (func (lambda (start &rest _) - (setq first-edited (if first-edited - (min start first-edited) - start))))) - (add-hook 'before-change-functions func nil t) - (list - (lambda (edits) - (if (and first-edited - (seq-find (-lambda ((&TextEdit :range (&RangeToPoint :end))) - ;; Text edit region is overlapped - (> end first-edited)) - edits)) - (lsp--warn "TextEdits will not be applied since document has been modified before of them.") - (lsp--apply-text-edits edits 'completion-cleanup))) - (lambda () - (remove-hook 'before-change-functions func t))))) - -(defun lsp--capability (cap &optional capabilities) - "Get the value of capability CAP. If CAPABILITIES is non-nil, use them instead." - (when (stringp cap) - (setq cap (intern (concat ":" cap)))) - - (lsp-get (or capabilities - (lsp--server-capabilities)) - cap)) - -(defun lsp--registered-capability (method) - "Check whether there is workspace providing METHOD." - (->> (lsp-workspaces) - (--keep (seq-find (lambda (reg) - (equal (lsp--registered-capability-method reg) method)) - (lsp--workspace-registered-server-capabilities it))) - cl-first)) - -(defun lsp--capability-for-method (method) - "Get the value of capability for METHOD." - (-let* ((reqs (cdr (assoc method lsp-method-requirements))) - ((&plist :capability) reqs)) - (or (and capability (lsp--capability capability)) - (-some-> (lsp--registered-capability method) - (lsp--registered-capability-options))))) - -(defvar-local lsp--before-change-vals nil - "Store the positions from the `lsp-before-change' function call, for -validation and use in the `lsp-on-change' function.") - -(defun lsp--text-document-content-change-event (start end length) - "Make a TextDocumentContentChangeEvent body for START to END, of length LENGTH." - ;; So (47 54 0) means add 7 chars starting at pos 47 - ;; must become - ;; {"range":{"start":{"line":5,"character":6} - ;; ,"end" :{"line":5,"character":6}} - ;; ,"rangeLength":0 - ;; ,"text":"\nbb = 5"} - ;; - ;; And (47 47 7) means delete 7 chars starting at pos 47 - ;; must become - ;; {"range":{"start":{"line":6,"character":0} - ;; ,"end" :{"line":7,"character":0}} - ;; ,"rangeLength":7 - ;; ,"text":""} - ;; - ;; (208 221 3) means delete 3 chars starting at pos 208, and replace them with - ;; 13 chars. So it must become - ;; {"range":{"start":{"line":5,"character":8} - ;; ,"end" :{"line":5,"character":11}} - ;; ,"rangeLength":3 - ;; ,"text":"new-chars-xxx"} - ;; - - ;; Adding text: - ;; lsp-before-change:(start,end)=(33,33) - ;; lsp-on-change:(start,end,length)=(33,34,0) - ;; - ;; Changing text: - ;; lsp-before-change:(start,end)=(208,211) - ;; lsp-on-change:(start,end,length)=(208,221,3) - ;; - ;; Deleting text: - ;; lsp-before-change:(start,end)=(19,27) - ;; lsp-on-change:(start,end,length)=(19,19,8) - (if (zerop length) - ;; Adding something only, work from start only - `( :range ,(lsp--range - (lsp--point-to-position start) - (lsp--point-to-position start)) - :rangeLength 0 - :text ,(buffer-substring-no-properties start end)) - - (if (eq start end) - ;; Deleting something only - (if (lsp--bracketed-change-p start length) - ;; The before-change value is bracketed, use it - `( :range ,(lsp--range - (lsp--point-to-position start) - (plist-get lsp--before-change-vals :end-pos)) - :rangeLength ,length - :text "") - ;; If the change is not bracketed, send a full change event instead. - (lsp--full-change-event)) - - ;; Deleting some things, adding others - (if (lsp--bracketed-change-p start length) - ;; The before-change value is valid, use it - `( :range ,(lsp--range - (lsp--point-to-position start) - (plist-get lsp--before-change-vals :end-pos)) - :rangeLength ,length - :text ,(buffer-substring-no-properties start end)) - (lsp--full-change-event))))) - -(defun lsp--bracketed-change-p (start length) - "If the before and after positions are the same, and the length -is the size of the start range, we are probably good." - (-let [(&plist :end before-end :start before-start) lsp--before-change-vals] - (and (eq start before-start) - (eq length (- before-end before-start))))) - -(defun lsp--full-change-event () - `(:text ,(lsp--buffer-content))) - -(defun lsp-before-change (start end) - "Executed before a file is changed. -Added to `before-change-functions'." - ;; Note: - ;; - ;; This variable holds a list of functions to call when Emacs is about to - ;; modify a buffer. Each function gets two arguments, the beginning and end of - ;; the region that is about to change, represented as integers. The buffer - ;; that is about to change is always the current buffer when the function is - ;; called. - ;; - ;; WARNING: - ;; - ;; Do not expect the before-change hooks and the after-change hooks be called - ;; in balanced pairs around each buffer change. Also don't expect the - ;; before-change hooks to be called for every chunk of text Emacs is about to - ;; delete. These hooks are provided on the assumption that Lisp programs will - ;; use either before- or the after-change hooks, but not both, and the - ;; boundaries of the region where the changes happen might include more than - ;; just the actual changed text, or even lump together several changes done - ;; piecemeal. - (save-match-data - (lsp-save-restriction-and-excursion - (setq lsp--before-change-vals - (list :start start - :end end - :end-pos (lsp--point-to-position end)))))) - -(defun lsp--flush-delayed-changes () - (let ((inhibit-quit t)) - (when lsp--delay-timer - (cancel-timer lsp--delay-timer)) - (mapc (-lambda ((workspace buffer document change)) - (with-current-buffer buffer - (with-lsp-workspace workspace - (lsp-notify "textDocument/didChange" - (list :textDocument document - :contentChanges (vector change)))))) - (prog1 (nreverse lsp--delayed-requests) - (setq lsp--delayed-requests nil))))) - -(defun lsp--workspace-sync-method (workspace) - (let ((sync (-> workspace - (lsp--workspace-server-capabilities) - (lsp:server-capabilities-text-document-sync?)))) - (if (lsp-text-document-sync-options? sync) - (lsp:text-document-sync-options-change? sync) - sync))) - -(defun lsp-on-change (start end length &optional content-change-event-fn) - "Executed when a file is changed. -Added to `after-change-functions'." - ;; Note: - ;; - ;; Each function receives three arguments: the beginning and end of the region - ;; just changed, and the length of the text that existed before the change. - ;; All three arguments are integers. The buffer that has been changed is - ;; always the current buffer when the function is called. - ;; - ;; The length of the old text is the difference between the buffer positions - ;; before and after that text as it was before the change. As for the - ;; changed text, its length is simply the difference between the first two - ;; arguments. - ;; - ;; So (47 54 0) means add 7 chars starting at pos 47 - ;; So (47 47 7) means delete 7 chars starting at pos 47 - (save-match-data - (let ((inhibit-quit t) - ;; make sure that `lsp-on-change' is called in multi-workspace context - ;; see #2901 - lsp--cur-workspace) - ;; A (revert-buffer) call with the 'preserve-modes parameter (eg, as done - ;; by auto-revert-mode) will cause this handler to get called with a nil - ;; buffer-file-name. We need the buffer-file-name to send notifications; - ;; so we skip handling revert-buffer-caused changes and instead handle - ;; reverts separately in lsp-on-revert - (when (not revert-buffer-in-progress-p) - (cl-incf lsp--cur-version) - (mapc - (lambda (workspace) - (pcase (or lsp-document-sync-method - (lsp--workspace-sync-method workspace)) - (1 - (if lsp-debounce-full-sync-notifications - (setq lsp--delayed-requests - (->> lsp--delayed-requests - (-remove (-lambda ((_ buffer)) - (equal (current-buffer) buffer))) - (cons (list workspace - (current-buffer) - (lsp--versioned-text-document-identifier) - (lsp--full-change-event))))) - (with-lsp-workspace workspace - (lsp-notify "textDocument/didChange" - (list :contentChanges (vector (lsp--full-change-event)) - :textDocument (lsp--versioned-text-document-identifier))) - (lsp-diagnostics--request-pull-diagnostics workspace)))) - (2 - (with-lsp-workspace workspace - (lsp-notify - "textDocument/didChange" - (list :textDocument (lsp--versioned-text-document-identifier) - :contentChanges (vector - (if content-change-event-fn - (funcall content-change-event-fn start end length) - (lsp--text-document-content-change-event - start end length))))) - (lsp-diagnostics--request-pull-diagnostics workspace))))) - (lsp-workspaces)) - (when lsp--delay-timer (cancel-timer lsp--delay-timer)) - (setq lsp--delay-timer (run-with-idle-timer - lsp-debounce-full-sync-notifications-interval - nil - #'lsp--flush-delayed-changes)) - ;; force cleanup overlays after each change - (lsp--remove-overlays 'lsp-highlight) - (lsp--after-change (current-buffer)))))) - - - -;; facilities for on change hooks. We do not want to make lsp calls on each -;; change event so we add debounce to avoid flooding the server with events. -;; Additionally, we want to have a mechanism for stopping the server calls in -;; particular cases like, e. g. when performing completion. - -(defvar lsp-inhibit-lsp-hooks nil - "Flag to control.") - -(defcustom lsp-on-change-hook nil - "Hooks to run when buffer has changed." - :type 'hook - :group 'lsp-mode) - -(defcustom lsp-idle-delay 0.500 - "Debounce interval for `after-change-functions'." - :type 'number - :group 'lsp-mode) - -(defcustom lsp-on-idle-hook nil - "Hooks to run after `lsp-idle-delay'." - :type 'hook - :group 'lsp-mode) - -(defun lsp--idle-reschedule (buffer) - (when lsp--on-idle-timer - (cancel-timer lsp--on-idle-timer)) - - (setq lsp--on-idle-timer (run-with-idle-timer - lsp-idle-delay - nil - #'lsp--on-idle - buffer))) - -(defun lsp--post-command () - (lsp--cleanup-highlights-if-needed) - (lsp--idle-reschedule (current-buffer))) - -(defun lsp--on-idle (buffer) - "Start post command loop." - (when (and (buffer-live-p buffer) - (equal buffer (current-buffer)) - (not lsp-inhibit-lsp-hooks) - lsp-managed-mode) - (run-hooks 'lsp-on-idle-hook))) - -(defun lsp--on-change-debounce (buffer) - (when (and (buffer-live-p buffer) - (equal buffer (current-buffer)) - (not lsp-inhibit-lsp-hooks) - lsp-managed-mode) - (run-hooks 'lsp-on-change-hook))) - -(defun lsp--after-change (buffer) - "Called after most textDocument/didChange events." - (setq lsp--signature-last-index nil - lsp--signature-last nil) - - ;; cleanup diagnostics - (when lsp-diagnostic-clean-after-change - (dolist (workspace (lsp-workspaces)) - (-let [diagnostics (lsp--workspace-diagnostics workspace)] - (remhash (lsp--fix-path-casing (buffer-file-name)) diagnostics)))) - - (when (fboundp 'lsp--semantic-tokens-refresh-if-enabled) - (lsp--semantic-tokens-refresh-if-enabled buffer)) - (when lsp--on-change-timer - (cancel-timer lsp--on-change-timer)) - (setq lsp--on-change-timer (run-with-idle-timer - lsp-idle-delay - nil - #'lsp--on-change-debounce - buffer)) - (lsp--idle-reschedule buffer)) - - -(defcustom lsp-trim-trailing-whitespace t - "Trim trailing whitespace on a line." - :group 'lsp-mode - :type 'boolean) - -(defcustom lsp-insert-final-newline t - "Insert a newline character at the end of the file if one does not exist." - :group 'lsp-mode - :type 'boolean) - -(defcustom lsp-trim-final-newlines t - "Trim all newlines after the final newline at the end of the file." - :group 'lsp-mode - :type 'boolean) - - -(defun lsp--on-type-formatting (first-trigger-characters more-trigger-characters) - "Self insert handling. -Applies on type formatting." - (let ((ch last-command-event)) - (when (or (eq (string-to-char first-trigger-characters) ch) - (cl-find ch more-trigger-characters :key #'string-to-char)) - (lsp-request-async "textDocument/onTypeFormatting" - (lsp-make-document-on-type-formatting-params - :text-document (lsp--text-document-identifier) - :options (lsp-make-formatting-options - :tab-size (symbol-value (lsp--get-indent-width major-mode)) - :insert-spaces (lsp-json-bool (not indent-tabs-mode)) - :trim-trailing-whitespace? (lsp-json-bool lsp-trim-trailing-whitespace) - :insert-final-newline? (lsp-json-bool lsp-insert-final-newline) - :trim-final-newlines? (lsp-json-bool lsp-trim-final-newlines)) - :ch (char-to-string ch) - :position (lsp--cur-position)) - (lambda (data) (lsp--apply-text-edits data 'format)) - :mode 'tick)))) - - -;; links -(defun lsp--document-links () - (when (lsp-feature? "textDocument/documentLink") - (lsp-request-async - "textDocument/documentLink" - `(:textDocument ,(lsp--text-document-identifier)) - (lambda (links) - (lsp--remove-overlays 'lsp-link) - (seq-do - (-lambda ((link &as &DocumentLink :range (&Range :start :end))) - (-doto (make-button (lsp--position-to-point start) - (lsp--position-to-point end) - 'action (lsp--document-link-keymap link) - 'keymap (let ((map (make-sparse-keymap))) - (define-key map [M-return] 'push-button) - (define-key map [mouse-2] 'push-button) - map) - 'help-echo "mouse-2, M-RET: Visit this link") - (overlay-put 'lsp-link t))) - links)) - :mode 'unchanged))) - -(defun lsp--document-link-handle-target (url) - (let* ((parsed-url (url-generic-parse-url (url-unhex-string url))) - (type (url-type parsed-url))) - (pcase type - ("file" - (xref-push-marker-stack) - (find-file (lsp--uri-to-path url)) - (-when-let ((_ line column) (s-match (rx "#" (group (1+ num)) (or "," "#") (group (1+ num))) url)) - (goto-char (lsp--position-to-point - (lsp-make-position :character (1- (string-to-number column)) - :line (1- (string-to-number line))))))) - ((or "http" "https") (browse-url url)) - (type (if-let ((handler (lsp--get-uri-handler type))) - (funcall handler url) - (signal 'lsp-file-scheme-not-supported (list url))))))) - -(lsp-defun lsp--document-link-keymap ((link &as &DocumentLink :target?)) - (if target? - (lambda (_) - (interactive) - (lsp--document-link-handle-target target?)) - (lambda (_) - (interactive) - (when (lsp:document-link-registration-options-resolve-provider? - (lsp--capability-for-method "textDocument/documentLink")) - (lsp-request-async - "documentLink/resolve" - link - (-lambda ((&DocumentLink :target?)) - (lsp--document-link-handle-target target?))))))) - - - -(defcustom lsp-warn-no-matched-clients t - "Whether to show messages when there are no supported clients." - :group 'lsp-mode - :type 'boolean) - -(defun lsp-buffer-language--configured-id () - "Return nil when not registered." - (->> lsp-language-id-configuration - (-first - (-lambda ((mode-or-pattern . language)) - (cond - ((and (stringp mode-or-pattern) - (s-matches? mode-or-pattern (buffer-file-name))) - language) - ((eq mode-or-pattern major-mode) language)))) - cl-rest)) - -(defvar-local lsp--buffer-language nil - "Locally cached returned value of `lsp-buffer-language'.") - -(defun lsp-buffer-language () - "Get language corresponding current buffer." - (or lsp--buffer-language - (let* ((configured-language (lsp-buffer-language--configured-id))) - (setq lsp--buffer-language - (or configured-language - ;; ensure non-nil - (string-remove-suffix "-mode" (symbol-name major-mode)))) - (when (and lsp-warn-no-matched-clients - (null configured-language)) - (lsp-warn "Unable to calculate the languageId for buffer `%s'. \ -Take a look at `lsp-language-id-configuration'. The `major-mode' is %s" - (buffer-name) - major-mode)) - lsp--buffer-language))) - -(defun lsp-activate-on (&rest languages) - "Returns language activation function. -The function will return t when the `lsp-buffer-language' returns -one of the LANGUAGES." - (lambda (_file-name _mode) - (-contains? languages (lsp-buffer-language)))) - -(defun lsp-workspace-root (&optional path) - "Find the workspace root for the current file or PATH." - (-when-let* ((file-name (or path (buffer-file-name))) - (file-name (lsp-f-canonical file-name))) - (->> (lsp-session) - (lsp-session-folders) - (--filter (and (lsp--files-same-host it file-name) - (or (lsp-f-ancestor-of? it file-name) - (equal it file-name)))) - (--max-by (> (length it) (length other)))))) - -(defun lsp-on-revert () - "Executed when a file is reverted. -Added to `after-revert-hook'." - (let ((n (buffer-size)) - (revert-buffer-in-progress-p nil)) - (lsp-on-change 0 n n))) - -(defun lsp--text-document-did-close (&optional keep-workspace-alive) - "Executed when the file is closed, added to `kill-buffer-hook'. - -If KEEP-WORKSPACE-ALIVE is non-nil, do not shutdown the workspace -if it's closing the last buffer in the workspace." - (lsp-foreach-workspace - (cl-callf2 delq (lsp-current-buffer) (lsp--workspace-buffers lsp--cur-workspace)) - (with-demoted-errors "Error sending didClose notification in ‘lsp--text-document-did-close’: %S" - (lsp-notify "textDocument/didClose" - `(:textDocument ,(lsp--text-document-identifier)))) - (when (and (not lsp-keep-workspace-alive) - (not keep-workspace-alive) - (not (lsp--workspace-buffers lsp--cur-workspace))) - (lsp--shutdown-workspace)))) - -(defun lsp--will-save-text-document-params (reason) - (list :textDocument (lsp--text-document-identifier) - :reason reason)) - -(defun lsp--before-save () - "Before save handler." - (with-demoted-errors "Error in ‘lsp--before-save’: %S" - (let ((params (lsp--will-save-text-document-params 1))) - (when (lsp--send-will-save-p) - (lsp-notify "textDocument/willSave" params)) - (when (and (lsp--send-will-save-wait-until-p) lsp-before-save-edits) - (let ((lsp-response-timeout 0.1)) - (condition-case nil - (lsp--apply-text-edits - (lsp-request "textDocument/willSaveWaitUntil" - params) - 'before-save) - (error))))))) - -(defun lsp--on-auto-save () - "Handler for auto-save." - (when (lsp--send-will-save-p) - (with-demoted-errors "Error in ‘lsp--on-auto-save’: %S" - (lsp-notify "textDocument/willSave" (lsp--will-save-text-document-params 2))))) - -(defun lsp--text-document-did-save () - "Executed when the file is closed, added to `after-save-hook''." - (when (lsp--send-did-save-p) - (with-demoted-errors "Error on ‘lsp--text-document-did-save: %S’" - (lsp-notify "textDocument/didSave" - `( :textDocument ,(lsp--versioned-text-document-identifier) - ,@(when (lsp--save-include-text-p) - (list :text (lsp--buffer-content)))))))) - -(defun lsp--text-document-position-params (&optional identifier position) - "Make TextDocumentPositionParams for the current point in the current document. -If IDENTIFIER and POSITION are non-nil, they will be used as the document -identifier and the position respectively." - (list :textDocument (or identifier (lsp--text-document-identifier)) - :position (or position (lsp--cur-position)))) - -(defun lsp--get-buffer-diagnostics () - "Return buffer diagnostics." - (gethash (or - (plist-get lsp--virtual-buffer :buffer-file-name) - (lsp--fix-path-casing (buffer-file-name))) - (lsp-diagnostics t))) - -(defun lsp-cur-line-diagnostics () - "Return any diagnostics that apply to the current line." - (-let [(&plist :start (&plist :line start) :end (&plist :line end)) (lsp--region-or-line)] - (cl-coerce (-filter - (-lambda ((&Diagnostic :range (&Range :start (&Position :line)))) - (and (>= line start) (<= line end))) - (lsp--get-buffer-diagnostics)) - 'vector))) - -(lsp-defun lsp-range-overlapping?((left &as &Range :start left-start :end left-end) - (right &as &Range :start right-start :end right-end)) - (or (lsp-point-in-range? right-start left) - (lsp-point-in-range? right-end left) - (lsp-point-in-range? left-start right) - (lsp-point-in-range? left-end right))) - -(defun lsp-make-position-1 (position) - (lsp-make-position :line (plist-get position :line) - :character (plist-get position :character))) - -(defun lsp-cur-possition-diagnostics () - "Return any diagnostics that apply to the current line." - (-let* ((start (if (use-region-p) (region-beginning) (point))) - (end (if (use-region-p) (region-end) (point))) - (current-range (lsp-make-range :start (lsp-make-position-1 (lsp-point-to-position start)) - :end (lsp-make-position-1 (lsp-point-to-position end))))) - (->> (lsp--get-buffer-diagnostics) - (-filter - (-lambda ((&Diagnostic :range)) - (lsp-range-overlapping? range current-range))) - (apply 'vector)))) - -(defalias 'lsp--cur-line-diagnotics 'lsp-cur-line-diagnostics) - -(defun lsp--extract-line-from-buffer (pos) - "Return the line pointed to by POS (a Position object) in the current buffer." - (let* ((point (lsp--position-to-point pos)) - (inhibit-field-text-motion t)) - (save-excursion - (goto-char point) - (buffer-substring (line-beginning-position) (line-end-position))))) - -(lsp-defun lsp--xref-make-item (filename (&Range :start (start &as &Position :character start-char :line start-line) - :end (end &as &Position :character end-char))) - "Return a xref-item from a RANGE in FILENAME." - (let* ((line (lsp--extract-line-from-buffer start)) - (len (length line))) - (add-face-text-property (max (min start-char len) 0) - (max (min end-char len) 0) - 'xref-match t line) - ;; LINE is nil when FILENAME is not being current visited by any buffer. - (xref-make-match (or line filename) - (xref-make-file-location - filename - (lsp-translate-line (1+ start-line)) - (lsp-translate-column start-char)) - (- end-char start-char)))) - -(defun lsp--location-uri (loc) - (if (lsp-location? loc) - (lsp:location-uri loc) - (lsp:location-link-target-uri loc))) - -(lsp-defun lsp-goto-location ((loc &as &Location :uri :range (&Range :start))) - "Go to location." - (let ((path (lsp--uri-to-path uri))) - (if (f-exists? path) - (with-current-buffer (find-file path) - (goto-char (lsp--position-to-point start))) - (error "There is no file %s" path)))) - -(defun lsp--location-range (loc) - (if (lsp-location? loc) - (lsp:location-range loc) - (lsp:location-link-target-selection-range loc))) - -(defun lsp--locations-to-xref-items (locations) - "Return a list of `xref-item' given LOCATIONS, which can be of -type Location, LocationLink, Location[] or LocationLink[]." - (setq locations - (pcase locations - ((seq (or (lsp-interface Location) - (lsp-interface LocationLink))) - (append locations nil)) - ((or (lsp-interface Location) - (lsp-interface LocationLink)) - (list locations)))) - - (cl-labels ((get-xrefs-in-file - (file-locs) - (-let [(filename . matches) file-locs] - (condition-case err - (let ((visiting (find-buffer-visiting filename)) - (fn (lambda (loc) - (lsp-with-filename filename - (lsp--xref-make-item filename - (lsp--location-range loc)))))) - (if visiting - (with-current-buffer visiting - (seq-map fn matches)) - (when (file-readable-p filename) - (with-temp-buffer - (insert-file-contents-literally filename) - (seq-map fn matches))))) - (error (lsp-warn "Failed to process xref entry for filename '%s': %s" - filename (error-message-string err))) - (file-error (lsp-warn "Failed to process xref entry, file-error, '%s': %s" - filename (error-message-string err))))))) - - (->> locations - (seq-sort #'lsp--location-before-p) - (seq-group-by (-compose #'lsp--uri-to-path #'lsp--location-uri)) - (seq-map #'get-xrefs-in-file) - (apply #'nconc)))) - -(defun lsp--location-before-p (left right) - "Sort first by file, then by line, then by column." - (let ((left-uri (lsp--location-uri left)) - (right-uri (lsp--location-uri right))) - (if (not (string= left-uri right-uri)) - (string< left-uri right-uri) - (-let (((&Range :start left-start) (lsp--location-range left)) - ((&Range :start right-start) (lsp--location-range right))) - (lsp--position-compare right-start left-start))))) - -(defun lsp--make-reference-params (&optional td-position exclude-declaration) - "Make a ReferenceParam object. -If TD-POSITION is non-nil, use it as TextDocumentPositionParams object instead. -If EXCLUDE-DECLARATION is non-nil, request the server to include declarations." - (let ((json-false :json-false)) - (plist-put (or td-position (lsp--text-document-position-params)) - :context `(:includeDeclaration ,(lsp-json-bool (not exclude-declaration)))))) - -(defun lsp--cancel-request (id) - "Cancel request with ID in all workspaces." - (lsp-foreach-workspace - (->> lsp--cur-workspace lsp--workspace-client lsp--client-response-handlers (remhash id)) - (lsp-notify "$/cancelRequest" `(:id ,id)))) - -(defvar-local lsp--hover-saved-bounds nil) - -(defun lsp-eldoc-function (cb &rest _ignored) - "`lsp-mode' eldoc function to display hover info (based on `textDocument/hover')." - (if (and lsp--hover-saved-bounds - (lsp--point-in-bounds-p lsp--hover-saved-bounds)) - lsp--eldoc-saved-message - (setq lsp--hover-saved-bounds nil - lsp--eldoc-saved-message nil) - (if (looking-at-p "[[:space:]\n]") - (setq lsp--eldoc-saved-message nil) ; And returns nil. - (when (and lsp-eldoc-enable-hover (lsp-feature? "textDocument/hover")) - (lsp-request-async - "textDocument/hover" - (lsp--text-document-position-params) - (-lambda ((hover &as &Hover? :range? :contents)) - (setq lsp--hover-saved-bounds (when range? - (lsp--range-to-region range?))) - (funcall cb (setq lsp--eldoc-saved-message - (when contents - (lsp--render-on-hover-content - contents - lsp-eldoc-render-all))))) - :error-handler #'ignore - :mode 'tick - :cancel-token :eldoc-hover))))) - -(defun lsp--point-on-highlight? () - (-some? (lambda (overlay) - (overlay-get overlay 'lsp-highlight)) - (overlays-at (point)))) - -(defun lsp--cleanup-highlights-if-needed () - (when (and lsp-enable-symbol-highlighting - lsp--have-document-highlights - (not (lsp--point-on-highlight?))) - (lsp--remove-overlays 'lsp-highlight) - (setq lsp--have-document-highlights nil) - (lsp-cancel-request-by-token :highlights))) - -(defvar-local lsp--symbol-bounds-of-last-highlight-invocation nil - "The bounds of the symbol from which `lsp--document-highlight' - most recently requested highlights.") - -(defun lsp--document-highlight () - (when (lsp-feature? "textDocument/documentHighlight") - (let ((curr-sym-bounds (bounds-of-thing-at-point 'symbol))) - (unless (or (looking-at-p "[[:space:]\n]") - (not lsp-enable-symbol-highlighting) - (and lsp--have-document-highlights - curr-sym-bounds - (equal curr-sym-bounds - lsp--symbol-bounds-of-last-highlight-invocation))) - (setq lsp--symbol-bounds-of-last-highlight-invocation - curr-sym-bounds) - (lsp-request-async "textDocument/documentHighlight" - (lsp--text-document-position-params) - #'lsp--document-highlight-callback - :mode 'tick - :cancel-token :highlights))))) - -(defun lsp--help-open-link (&rest _) - "Open markdown link at point via mouse or keyboard." - (interactive "P") - (let ((buffer-list-update-hook nil)) - (-let [(buffer point) (if-let* ((valid (and (listp last-input-event) - (eq (car last-input-event) 'mouse-2))) - (event (cadr last-input-event)) - (win (posn-window event)) - (buffer (window-buffer win))) - `(,buffer ,(posn-point event)) - `(,(current-buffer) ,(point)))] - (with-current-buffer buffer - (when-let* ((face (get-text-property point 'face)) - (url (or (and (eq face 'markdown-link-face) - (get-text-property point 'help-echo)) - (and (memq face '(markdown-url-face markdown-plain-url-face)) - (nth 3 (markdown-link-at-pos point)))))) - (lsp--document-link-handle-target url)))))) - -(defvar lsp-help-mode-map - (-doto (make-sparse-keymap) - (define-key [remap markdown-follow-link-at-point] #'lsp--help-open-link)) - "Keymap for `lsp-help-mode'.") - -(define-derived-mode lsp-help-mode help-mode "LspHelp" - "Major mode for displaying lsp help.") - -(defun lsp-describe-thing-at-point () - "Display the type signature and documentation of the thing at point." - (interactive) - (let ((contents (-some->> (lsp--text-document-position-params) - (lsp--make-request "textDocument/hover") - (lsp--send-request) - (lsp:hover-contents)))) - (if (and contents (not (equal contents ""))) - (let ((lsp-help-buf-name "*lsp-help*")) - (with-current-buffer (get-buffer-create lsp-help-buf-name) - (delay-mode-hooks - (lsp-help-mode) - (with-help-window lsp-help-buf-name - (insert (string-trim-right (lsp--render-on-hover-content contents t))))) - (run-mode-hooks))) - (lsp--info "No content at point.")))) - -(defun lsp--point-in-bounds-p (bounds) - "Return whether the current point is within BOUNDS." - (and (<= (car bounds) (point)) (< (point) (cdr bounds)))) - -(defun lsp-get-renderer (language) - "Get renderer for LANGUAGE." - (lambda (str) - (lsp--render-string str language))) - -(defun lsp--setup-markdown (mode) - "Setup the ‘markdown-mode’ in the frame. -MODE is the mode used in the parent frame." - (make-local-variable 'markdown-code-lang-modes) - (dolist (mark (alist-get mode lsp-custom-markup-modes)) - (add-to-list 'markdown-code-lang-modes (cons mark mode))) - (setq-local markdown-fontify-code-blocks-natively t) - (setq-local markdown-fontify-code-block-default-mode mode) - (setq-local markdown-hide-markup t) - - ;; Render some common HTML entities. - ;; This should really happen in markdown-mode instead, - ;; but it doesn't, so we do it here for now. - (setq prettify-symbols-alist - (cl-loop for i from 0 to 255 - collect (cons (format "&#x%02X;" i) i))) - (push '("<" . ?<) prettify-symbols-alist) - (push '(">" . ?>) prettify-symbols-alist) - (push '("&" . ?&) prettify-symbols-alist) - (push '(" " . ? ) prettify-symbols-alist) - (setq prettify-symbols-compose-predicate - (lambda (_start _end _match) t)) - (prettify-symbols-mode 1)) - -(defvar lsp-help-link-keymap - (let ((map (make-sparse-keymap))) - (define-key map [mouse-2] #'lsp--help-open-link) - (define-key map "\r" #'lsp--help-open-link) - map) - "Keymap active on links in *lsp-help* mode.") - -(defun lsp--fix-markdown-links () - (let ((inhibit-read-only t) - (inhibit-modification-hooks t) - (prop)) - (save-restriction - (goto-char (point-min)) - (while (setq prop (markdown-find-next-prop 'face)) - (let ((end (or (next-single-property-change (car prop) 'face) - (point-max)))) - (when (memq (get-text-property (car prop) 'face) - '(markdown-link-face - markdown-url-face - markdown-plain-url-face)) - (add-text-properties (car prop) end - (list 'button t - 'category 'lsp-help-link - 'follow-link t - 'keymap lsp-help-link-keymap))) - (goto-char end)))))) - -(defun lsp--buffer-string-visible () - "Return visible buffer string. -Stolen from `org-copy-visible'." - (let ((temp (generate-new-buffer " *temp*")) - (beg (point-min)) - (end (point-max))) - (while (/= beg end) - (when (get-char-property beg 'invisible) - (setq beg (next-single-char-property-change beg 'invisible nil end))) - (let* ((next (next-single-char-property-change beg 'invisible nil end)) - (substring (buffer-substring beg next))) - (with-current-buffer temp (insert substring)) - ;; (setq result (concat result substring)) - (setq beg next))) - (setq deactivate-mark t) - (prog1 (with-current-buffer temp - (s-chop-suffix "\n" (buffer-string))) - (kill-buffer temp)))) - -(defvar lsp-buffer-major-mode nil - "Holds the major mode when fontification function is running. -See #2588") - -(defvar view-inhibit-help-message) - -(defun lsp--render-markdown () - "Render markdown." - - (let ((markdown-enable-math nil)) - (goto-char (point-min)) - (while (re-search-forward - (rx (and "\\" (group (or "\\" "`" "*" "_" ":" "/" - "{" "}" "[" "]" "(" ")" - "#" "+" "-" "." "!" "|")))) - nil t) - (replace-match (rx (backref 1)))) - - ;; markdown-mode v2.3 does not yet provide gfm-view-mode - (if (fboundp 'gfm-view-mode) - (let ((view-inhibit-help-message t)) - (gfm-view-mode)) - (gfm-mode)) - - (lsp--setup-markdown lsp-buffer-major-mode))) - -(defvar lsp--display-inline-image-alist - '((lsp--render-markdown - (:regexp - "!\\[.*?\\](data:image/[a-zA-Z]+;base64,\\([A-Za-z0-9+/\n]+?=*?\\)\\(|[^)]+\\)?)" - :sexp - (create-image - (base64-decode-string - (buffer-substring-no-properties (match-beginning 1) (match-end 1))) - nil t)))) - "Replaced string regexp and function returning image. -Each element should have the form (MODE . (PROPERTY-LIST...)). -MODE (car) is function which is defined in `lsp-language-id-configuration'. -Cdr should be list of PROPERTY-LIST. - -Each PROPERTY-LIST should have properties: -:regexp Regexp which determines what string is relpaced to image. - You should also get information of image, by parenthesis constructs. - By default, all matched string is replaced to image, but you can - change index of replaced string by keyword :replaced-index. - -:sexp Return image when evaluated. You can use information of regexp - by using (match-beggining N), (match-end N) or (match-substring N). - -In addition, each can have property: -:replaced-index Determine index which is used to replace regexp to image. - The value means first argument of `match-beginning' and - `match-end'. If omitted, interpreted as index 0.") - -(defcustom lsp-display-inline-image t - "Showing inline image or not." - :group 'lsp-mode - :type 'boolean) - -(defcustom lsp-enable-suggest-server-download t - "When non-nil enable server downloading suggestions." - :group 'lsp-mode - :type 'boolean - :package-version '(lsp-mode . "9.0.0")) - -(defcustom lsp-auto-register-remote-clients t - "When non-nil register remote when registering the local one." - :group 'lsp-mode - :type 'boolean - :package-version '(lsp-mode . "9.0.0")) - -(defun lsp--display-inline-image (mode) - "Add image property if available." - (let ((plist-list (cdr (assq mode lsp--display-inline-image-alist)))) - (when (and (display-images-p) lsp-display-inline-image) - (cl-loop - for plist in plist-list - with regexp with replaced-index - do - (setq regexp (plist-get plist :regexp)) - (setq replaced-index (or (plist-get plist :replaced-index) 0)) - - (font-lock-remove-keywords nil (list regexp replaced-index)) - (let ((inhibit-read-only t)) - (save-excursion - (goto-char (point-min)) - (while (re-search-forward regexp nil t) - (set-text-properties - (match-beginning replaced-index) (match-end replaced-index) - nil) - (add-text-properties - (match-beginning replaced-index) (match-end replaced-index) - `(display ,(eval (plist-get plist :sexp))))))))))) - -(defun lsp--fontlock-with-mode (str mode) - "Fontlock STR with MODE." - (let ((lsp-buffer-major-mode major-mode)) - (with-temp-buffer - (with-demoted-errors "Error during doc rendering: %s" - (insert str) - (delay-mode-hooks (funcall mode)) - (cl-flet ((window-body-width () lsp-window-body-width)) - ;; This can go wrong in some cases, and the fontification would - ;; not work as expected. - ;; - ;; See #2984 - (ignore-errors (font-lock-ensure)) - (lsp--display-inline-image mode) - (when (eq mode 'lsp--render-markdown) - (lsp--fix-markdown-links)))) - (lsp--buffer-string-visible)))) - -(defun lsp--render-string (str language) - "Render STR using `major-mode' corresponding to LANGUAGE. -When language is nil render as markup if `markdown-mode' is loaded." - (setq str (s-replace "\r" "" (or str ""))) - (if-let* ((modes (-keep (-lambda ((mode . lang)) - (when (and (equal lang language) (functionp mode)) - mode)) - lsp-language-id-configuration)) - (mode (car (or (member major-mode modes) modes)))) - (lsp--fontlock-with-mode str mode) - str)) - -(defun lsp--render-element (content) - "Render CONTENT element." - (let ((inhibit-message t)) - (or - (pcase content - ((lsp-interface MarkedString :value :language) - (lsp--render-string value language)) - ((lsp-interface MarkupContent :value :kind) - (lsp--render-string value kind)) - ;; plain string - ((pred stringp) (lsp--render-string content "markdown")) - ((pred null) "") - (_ (error "Failed to handle %s" content))) - ""))) - -(defun lsp--create-unique-string-fn () - (let (elements) - (lambda (element) - (let ((count (cl-count element elements :test #'string=))) - (prog1 (if (zerop count) - element - (format "%s (%s)" element count)) - (push element elements)))))) - -(defun lsp--select-action (actions) - "Select an action to execute from ACTIONS." - (cond - ((seq-empty-p actions) (signal 'lsp-no-code-actions nil)) - ((and (eq (seq-length actions) 1) lsp-auto-execute-action) - (lsp-seq-first actions)) - (t (let ((completion-ignore-case t)) - (lsp--completing-read "Select code action: " - (seq-into actions 'list) - (-compose (lsp--create-unique-string-fn) - #'lsp:code-action-title) - nil t))))) - -(defun lsp--workspace-server-id (workspace) - "Return the server ID of WORKSPACE." - (-> workspace lsp--workspace-client lsp--client-server-id)) - -(defun lsp--handle-rendered-for-echo-area (contents) - "Return a single line from RENDERED, appropriate for display in the echo area." - (pcase (lsp-workspaces) - (`(,workspace) - (lsp-clients-extract-signature-on-hover contents (lsp--workspace-server-id workspace))) - ;; For projects with multiple active workspaces we also default to - ;; render the first line. - (_ (lsp-clients-extract-signature-on-hover contents nil)))) - -(cl-defmethod lsp-clients-extract-signature-on-hover (contents _server-id) - "Extract a representative line from CONTENTS, to show in the echo area." - (car (s-lines (s-trim (lsp--render-element contents))))) - -(defun lsp--render-on-hover-content (contents render-all) - "Render the content received from `document/onHover' request. -CONTENTS - MarkedString | MarkedString[] | MarkupContent -RENDER-ALL - nil if only the signature should be rendered." - (cond - ((lsp-markup-content? contents) - ;; MarkupContent. - ;; It tends to be long and is not suitable to display fully in the echo area. - ;; Just display the first line which is typically the signature. - (if render-all - (lsp--render-element contents) - (lsp--handle-rendered-for-echo-area contents))) - ((and (stringp contents) (not (string-match-p "\n" contents))) - ;; If the contents is a single string containing a single line, - ;; render it always. - (lsp--render-element contents)) - (t - ;; MarkedString -> MarkedString[] - (when (or (lsp-marked-string? contents) (stringp contents)) - (setq contents (list contents))) - ;; Consider the signature consisting of the elements who have a renderable - ;; "language" property. When render-all is nil, ignore other elements. - (string-join - (seq-map - #'lsp--render-element - (if render-all - contents - ;; Only render contents that have an available renderer. - (seq-take - (seq-filter - (-andfn #'lsp-marked-string? - (-compose #'lsp-get-renderer #'lsp:marked-string-language)) - contents) - 1))) - (if (bound-and-true-p page-break-lines-mode) - "\n\n" - "\n"))))) - - - -(defvar lsp-signature-mode-map - (-doto (make-sparse-keymap) - (define-key (kbd "M-n") #'lsp-signature-next) - (define-key (kbd "M-p") #'lsp-signature-previous) - (define-key (kbd "M-a") #'lsp-signature-toggle-full-docs) - (define-key (kbd "C-c C-k") #'lsp-signature-stop) - (define-key (kbd "C-g") #'lsp-signature-stop)) - "Keymap for `lsp-signature-mode'.") - -(define-minor-mode lsp-signature-mode - "Mode used to show signature popup." - :keymap lsp-signature-mode-map - :lighter "" - :group 'lsp-mode) - -(defun lsp-signature-stop () - "Stop showing current signature help." - (interactive) - (lsp-cancel-request-by-token :signature) - (remove-hook 'post-command-hook #'lsp-signature) - (funcall lsp-signature-function nil) - (lsp-signature-mode -1)) - -(declare-function page-break-lines--update-display-tables "ext:page-break-lines") - -(defun lsp--setup-page-break-mode-if-present () - "Enable `page-break-lines-mode' in current buffer." - (when (fboundp 'page-break-lines-mode) - (page-break-lines-mode) - ;; force page-break-lines-mode to update the display tables. - (page-break-lines--update-display-tables))) - -(defun lsp-lv-message (message) - (add-hook 'lv-window-hook #'lsp--setup-page-break-mode-if-present) - (if message - (progn - (setq lsp--signature-last-buffer (current-buffer)) - (let ((lv-force-update t)) - (lv-message "%s" message))) - (lv-delete-window) - (remove-hook 'lv-window-hook #'lsp--setup-page-break-mode-if-present))) - -(declare-function posframe-show "ext:posframe") -(declare-function posframe-hide "ext:posframe") -(declare-function posframe-poshandler-point-bottom-left-corner-upward "ext:posframe") - -(defface lsp-signature-posframe - '((t :inherit tooltip)) - "Background and foreground for `lsp-signature-posframe'." - :group 'lsp-mode) - -(defvar lsp-signature-posframe-params - (list :poshandler #'posframe-poshandler-point-bottom-left-corner-upward - :height 10 - :width 60 - :border-width 1 - :min-width 60) - "Params for signature and `posframe-show'.") - -(defun lsp-signature-posframe (str) - "Use posframe to show the STR signatureHelp string." - (if str - (apply #'posframe-show - (with-current-buffer (get-buffer-create " *lsp-signature*") - (erase-buffer) - (insert str) - (visual-line-mode 1) - (lsp--setup-page-break-mode-if-present) - (current-buffer)) - (append - lsp-signature-posframe-params - (list :position (point) - :background-color (face-attribute 'lsp-signature-posframe :background nil t) - :foreground-color (face-attribute 'lsp-signature-posframe :foreground nil t) - :border-color (face-attribute 'font-lock-comment-face :foreground nil t)))) - (posframe-hide " *lsp-signature*"))) - -(defun lsp--handle-signature-update (signature) - (let ((message - (if (lsp-signature-help? signature) - (lsp--signature->message signature) - (mapconcat #'lsp--signature->message signature "\n")))) - (if (s-present? message) - (funcall lsp-signature-function message) - (lsp-signature-stop)))) - -(defun lsp-signature-activate () - "Activate signature help. -It will show up only if current point has signature help." - (interactive) - (setq lsp--signature-last nil - lsp--signature-last-index nil - lsp--signature-last-buffer (current-buffer)) - (add-hook 'post-command-hook #'lsp-signature) - (lsp-signature-mode t)) - -(defcustom lsp-signature-cycle t - "Whether `lsp-signature-next' and prev should cycle." - :type 'boolean - :group 'lsp-mode) - -(defun lsp-signature-next () - "Show next signature." - (interactive) - (let ((nsigs (length (lsp:signature-help-signatures lsp--signature-last)))) - (when (and lsp--signature-last-index - lsp--signature-last - (or lsp-signature-cycle (< (1+ lsp--signature-last-index) nsigs))) - (setq lsp--signature-last-index (% (1+ lsp--signature-last-index) nsigs)) - (funcall lsp-signature-function (lsp--signature->message lsp--signature-last))))) - -(defun lsp-signature-previous () - "Next signature." - (interactive) - (when (and lsp--signature-last-index - lsp--signature-last - (or lsp-signature-cycle (not (zerop lsp--signature-last-index)))) - (setq lsp--signature-last-index (1- (if (zerop lsp--signature-last-index) - (length (lsp:signature-help-signatures lsp--signature-last)) - lsp--signature-last-index))) - (funcall lsp-signature-function (lsp--signature->message lsp--signature-last)))) - -(defun lsp-signature-toggle-full-docs () - "Toggle full/partial signature documentation." - (interactive) - (let ((all? (not (numberp lsp-signature-doc-lines)))) - (setq lsp-signature-doc-lines (if all? - (or (car-safe lsp-signature-doc-lines) - 20) - (list lsp-signature-doc-lines)))) - (lsp-signature-activate)) - -(defun lsp--signature->message (signature-help) - "Generate eldoc message from SIGNATURE-HELP response." - (setq lsp--signature-last signature-help) - - (when (and signature-help (not (seq-empty-p (lsp:signature-help-signatures signature-help)))) - (-let* (((&SignatureHelp :active-signature? - :active-parameter? - :signatures) signature-help) - (active-signature? (or lsp--signature-last-index active-signature? 0)) - (_ (setq lsp--signature-last-index active-signature?)) - ((signature &as &SignatureInformation? :label :parameters?) (seq-elt signatures active-signature?)) - (prefix (if (= (length signatures) 1) - "" - (concat (propertize (format " %s/%s" - (1+ active-signature?) - (length signatures)) - 'face 'success) - " "))) - (method-docs (when - (and lsp-signature-render-documentation - (or (not (numberp lsp-signature-doc-lines)) (< 0 lsp-signature-doc-lines))) - (let ((docs (lsp--render-element - (lsp:parameter-information-documentation? signature)))) - (when (s-present? docs) - (concat - "\n" - (if (fboundp 'page-break-lines-mode) - "\n" - "") - (if (and (numberp lsp-signature-doc-lines) - (> (length (s-lines docs)) lsp-signature-doc-lines)) - (concat (s-join "\n" (-take lsp-signature-doc-lines (s-lines docs))) - (propertize "\nTruncated..." 'face 'highlight)) - docs))))))) - (when (and active-parameter? (not (seq-empty-p parameters?))) - (-when-let* ((param (when (and (< -1 active-parameter? (length parameters?))) - (seq-elt parameters? active-parameter?))) - (selected-param-label (let ((label (lsp:parameter-information-label param))) - (if (stringp label) label (append label nil)))) - (start (if (stringp selected-param-label) - (s-index-of selected-param-label label) - (cl-first selected-param-label))) - (end (if (stringp selected-param-label) - (+ start (length selected-param-label)) - (cl-second selected-param-label)))) - (add-face-text-property start end 'eldoc-highlight-function-argument nil label))) - (concat prefix label method-docs)))) - -(defun lsp-signature () - "Display signature info (based on `textDocument/signatureHelp')" - (if (and lsp--signature-last-buffer - (not (equal (current-buffer) lsp--signature-last-buffer))) - (lsp-signature-stop) - (lsp-request-async "textDocument/signatureHelp" - (lsp--text-document-position-params) - #'lsp--handle-signature-update - :cancel-token :signature))) - - -(defcustom lsp-overlay-document-color-char "■" - "Display the char represent the document color in overlay" - :type 'string - :group 'lsp-mode) - -;; color presentation -(defun lsp--color-create-interactive-command (color range) - (lambda () - (interactive) - (-let [(&ColorPresentation? :text-edit? - :additional-text-edits?) - (lsp--completing-read - "Select color presentation: " - (lsp-request - "textDocument/colorPresentation" - `( :textDocument ,(lsp--text-document-identifier) - :color ,color - :range ,range)) - #'lsp:color-presentation-label - nil - t)] - (when text-edit? - (lsp--apply-text-edit text-edit?)) - (when additional-text-edits? - (lsp--apply-text-edits additional-text-edits? 'color-presentation))))) - -(defun lsp--number->color (number) - (let ((result (format "%x" - (round (* (or number 0) 255.0))))) - (if (= 1 (length result)) - (concat "0" result) - result))) - -(defun lsp--document-color () - "Document color handler." - (when (lsp-feature? "textDocument/documentColor") - (lsp-request-async - "textDocument/documentColor" - `(:textDocument ,(lsp--text-document-identifier)) - (lambda (result) - (lsp--remove-overlays 'lsp-color) - (seq-do - (-lambda ((&ColorInformation :color (color &as &Color :red :green :blue) - :range)) - (-let* (((beg . end) (lsp--range-to-region range)) - (overlay (make-overlay beg end)) - (command (lsp--color-create-interactive-command color range))) - (overlay-put overlay 'lsp-color t) - (overlay-put overlay 'evaporate t) - (overlay-put overlay - 'before-string - (propertize - lsp-overlay-document-color-char - 'face `((:foreground ,(format - "#%s%s%s" - (lsp--number->color red) - (lsp--number->color green) - (lsp--number->color blue)))) - 'action command - 'mouse-face 'lsp-lens-mouse-face - 'local-map (-doto (make-sparse-keymap) - (define-key [mouse-1] command)))))) - result)) - :mode 'unchanged - :cancel-token :document-color-token))) - - - -(defun lsp--action-trigger-parameter-hints (_command) - "Handler for editor.action.triggerParameterHints." - (when (member :on-server-request lsp-signature-auto-activate) - (lsp-signature-activate))) - -(defun lsp--action-trigger-suggest (_command) - "Handler for editor.action.triggerSuggest." - (cond - ((and (bound-and-true-p company-mode) - (fboundp 'company-auto-begin) - (fboundp 'company-post-command)) - (run-at-time 0 nil - (lambda () - (let ((this-command 'company-idle-begin) - (company-minimum-prefix-length 0)) - (company-auto-begin) - (company-post-command))))) - (t - (completion-at-point)))) - -(defconst lsp--default-action-handlers - (ht ("editor.action.triggerParameterHints" #'lsp--action-trigger-parameter-hints) - ("editor.action.triggerSuggest" #'lsp--action-trigger-suggest)) - "Default action handlers.") - -(defun lsp--find-action-handler (command) - "Find action handler for particular COMMAND." - (or - (--some (-some->> it - (lsp--workspace-client) - (lsp--client-action-handlers) - (gethash command)) - (lsp-workspaces)) - (gethash command lsp--default-action-handlers))) - -(defun lsp--text-document-code-action-params (&optional kind) - "Code action params." - (list :textDocument (lsp--text-document-identifier) - :range (if (use-region-p) - (lsp--region-to-range (region-beginning) (region-end)) - (lsp--region-to-range (point) (point))) - :context `( :diagnostics ,(lsp-cur-possition-diagnostics) - ,@(when kind (list :only (vector kind)))))) - -(defun lsp-code-actions-at-point (&optional kind) - "Retrieve the code actions for the active region or the current line. -It will filter by KIND if non nil." - (lsp-request "textDocument/codeAction" (lsp--text-document-code-action-params kind))) - -(defun lsp-execute-code-action-by-kind (command-kind) - "Execute code action by COMMAND-KIND." - (if-let ((action (->> (lsp-get-or-calculate-code-actions command-kind) - (-filter (-lambda ((&CodeAction :kind?)) - (and kind? (s-prefix? command-kind kind?)))) - lsp--select-action))) - (lsp-execute-code-action action) - (signal 'lsp-no-code-actions '(command-kind)))) - -(defalias 'lsp-get-or-calculate-code-actions 'lsp-code-actions-at-point) - -(lsp-defun lsp--execute-command ((action &as &Command :command :arguments?)) - "Parse and execute a code ACTION represented as a Command LSP type." - (let ((server-id (->> (lsp-workspaces) - (cl-first) - (or lsp--cur-workspace) - (lsp--workspace-client) - (lsp--client-server-id)))) - (condition-case nil - (with-no-warnings - (lsp-execute-command server-id (intern command) arguments?)) - (cl-no-applicable-method - (if-let ((action-handler (lsp--find-action-handler command))) - (funcall action-handler action) - (lsp-send-execute-command command arguments?)))))) - -(lsp-defun lsp-execute-code-action ((action &as &CodeAction :command? :edit?)) - "Execute code action ACTION. For example, when text under the -caret has a suggestion to apply a fix from an lsp-server, calling -this function will do so. -If ACTION is not set it will be selected from `lsp-code-actions-at-point'. -Request codeAction/resolve for more info if server supports." - (interactive (list (lsp--select-action (lsp-code-actions-at-point)))) - (if (and (lsp-feature? "codeAction/resolve") - (not command?) - (not edit?)) - (lsp--execute-code-action (lsp-request "codeAction/resolve" action)) - (lsp--execute-code-action action))) - -(lsp-defun lsp--execute-code-action ((action &as &CodeAction :command? :edit?)) - "Execute code action ACTION." - (when edit? - (lsp--apply-workspace-edit edit? 'code-action)) - - (cond - ((stringp command?) (lsp--execute-command action)) - ((lsp-command? command?) (progn - (when-let ((action-filter (->> (lsp-workspaces) - (cl-first) - (or lsp--cur-workspace) - (lsp--workspace-client) - (lsp--client-action-filter)))) - (funcall action-filter command?)) - (lsp--execute-command command?))))) - -(lsp-defun lsp-fix-code-action-booleans ((&Command :arguments?) boolean-action-arguments) - "Patch incorrect boolean argument values in the provided `CodeAction' command -in place, based on the BOOLEAN-ACTION-ARGUMENTS list. The values -in this list can be either symbols or lists of symbols that -represent paths to boolean arguments in code actions: - -> (lsp-fix-code-action-booleans command `(:foo :bar (:some :nested :boolean))) - -When there are available code actions, the server sends -`lsp-mode' a list of possible command names and arguments as -JSON. `lsp-mode' parses all boolean false values as `nil'. As a -result code action arguments containing falsy values don't -roundtrip correctly because `lsp-mode' will end up sending null -values back to the client. This list makes it possible to -selectively transform `nil' values back into `:json-false'." - (seq-doseq (path boolean-action-arguments) - (seq-doseq (args arguments?) - (lsp--fix-nested-boolean args (if (listp path) path (list path)))))) - -(defun lsp--fix-nested-boolean (structure path) - "Traverse STRUCTURE using the paths from the PATH list, changing the value to -`:json-false' if it was `nil'. PATH should be a list containing -one or more symbols, and STRUCTURE should be compatible with -`lsp-member?', `lsp-get', and `lsp-put'." - (let ((key (car path)) - (rest (cdr path))) - (if (null rest) - ;; `lsp-put' returns `nil' both when the key doesn't exist and when the - ;; value is `nil', so we need to explicitly check its presence here - (when (and (lsp-member? structure key) (not (lsp-get structure key))) - (lsp-put structure key :json-false)) - ;; If `key' does not exist, then we'll silently ignore it - (when-let ((child (lsp-get structure key))) - (lsp--fix-nested-boolean child rest))))) - -(defvar lsp--formatting-indent-alist - ;; Taken from `dtrt-indent-mode' - '( - (ada-mode . ada-indent) ; Ada - (ada-ts-mode . ada-ts-mode-indent-offset) - (c++-mode . c-basic-offset) ; C++ - (c++-ts-mode . c-ts-mode-indent-offset) - (c-mode . c-basic-offset) ; C - (c-ts-mode . c-ts-mode-indent-offset) - (cperl-mode . cperl-indent-level) ; Perl - (crystal-mode . crystal-indent-level) ; Crystal (Ruby) - (csharp-mode . c-basic-offset) ; C# - (csharp-tree-sitter-mode . csharp-tree-sitter-indent-offset) ; C# - (csharp-ts-mode . csharp-ts-mode-indent-offset) ; C# (tree-sitter, Emacs29) - (css-mode . css-indent-offset) ; CSS - (d-mode . c-basic-offset) ; D - (enh-ruby-mode . enh-ruby-indent-level) ; Ruby - (erlang-mode . erlang-indent-level) ; Erlang - (ess-mode . ess-indent-offset) ; ESS (R) - (go-ts-mode . go-ts-mode-indent-offset) - (gpr-mode . gpr-indent-offset) ; GNAT Project - (gpr-ts-mode . gpr-ts-mode-indent-offset) - (hack-mode . hack-indent-offset) ; Hack - (java-mode . c-basic-offset) ; Java - (java-ts-mode . java-ts-mode-indent-offset) - (jde-mode . c-basic-offset) ; Java (JDE) - (js-mode . js-indent-level) ; JavaScript - (js-ts-mode . js-indent-level) - (js2-mode . js2-basic-offset) ; JavaScript-IDE - (js3-mode . js3-indent-level) ; JavaScript-IDE - (json-mode . js-indent-level) ; JSON - (json-ts-mode . json-ts-mode-indent-offset) - (lua-mode . lua-indent-level) ; Lua - (lua-ts-mode . lua-ts-indent-offset) - (nxml-mode . nxml-child-indent) ; XML - (objc-mode . c-basic-offset) ; Objective C - (pascal-mode . pascal-indent-level) ; Pascal - (perl-mode . perl-indent-level) ; Perl - (php-mode . c-basic-offset) ; PHP - (php-ts-mode . php-ts-mode-indent-offset) ; PHP - (powershell-mode . powershell-indent) ; PowerShell - (powershell-ts-mode . powershell-ts-mode-indent-offset) ; PowerShell - (raku-mode . raku-indent-offset) ; Perl6/Raku - (ruby-mode . ruby-indent-level) ; Ruby - (rust-mode . rust-indent-offset) ; Rust - (rust-ts-mode . rust-ts-mode-indent-offset) - (rustic-mode . rustic-indent-offset) ; Rust - (scala-mode . scala-indent:step) ; Scala - (sgml-mode . sgml-basic-offset) ; SGML - (sh-mode . sh-basic-offset) ; Shell Script - (toml-ts-mode . toml-ts-mode-indent-offset) - (typescript-mode . typescript-indent-level) ; Typescript - (typescript-ts-mode . typescript-ts-mode-indent-offset) ; Typescript (tree-sitter, Emacs29) - (yaml-mode . yaml-indent-offset) ; YAML - (yang-mode . c-basic-offset) ; YANG (yang-mode) - - (default . standard-indent)) ; default fallback - "A mapping from `major-mode' to its indent variable.") - -(defun lsp--get-indent-width (mode) - "Get indentation offset for MODE." - (or (alist-get mode lsp--formatting-indent-alist) - (lsp--get-indent-width (or (get mode 'derived-mode-parent) 'default)))) - -(defun lsp--make-document-formatting-params () - "Create document formatting params." - (lsp-make-document-formatting-params - :text-document (lsp--text-document-identifier) - :options (lsp-make-formatting-options - :tab-size (symbol-value (lsp--get-indent-width major-mode)) - :insert-spaces (lsp-json-bool (not indent-tabs-mode)) - :trim-trailing-whitespace? (lsp-json-bool lsp-trim-trailing-whitespace) - :insert-final-newline? (lsp-json-bool lsp-insert-final-newline) - :trim-final-newlines? (lsp-json-bool lsp-trim-final-newlines)))) - -(defun lsp-format-buffer () - "Ask the server to format this document." - (interactive "*") - (cond ((lsp-feature? "textDocument/formatting") - (let ((edits (lsp-request "textDocument/formatting" - (lsp--make-document-formatting-params)))) - (if (seq-empty-p edits) - (lsp--info "No formatting changes provided") - (lsp--apply-text-edits edits 'format)))) - ((lsp-feature? "textDocument/rangeFormatting") - (save-restriction - (widen) - (lsp-format-region (point-min) (point-max)))) - (t (signal 'lsp-capability-not-supported (list "documentFormattingProvider"))))) - -(defun lsp-format-region (s e) - "Ask the server to format the region, or if none is selected, the current line." - (interactive "r") - (let ((edits (lsp-request - "textDocument/rangeFormatting" - (lsp--make-document-range-formatting-params s e)))) - (if (seq-empty-p edits) - (lsp--info "No formatting changes provided") - (lsp--apply-text-edits edits 'format)))) - -(defmacro lsp-make-interactive-code-action (func-name code-action-kind) - "Define an interactive function FUNC-NAME that attempts to -execute a CODE-ACTION-KIND action." - `(defun ,(intern (concat "lsp-" (symbol-name func-name))) () - ,(format "Perform the %s code action, if available." code-action-kind) - (interactive) - ;; Even when `lsp-auto-execute-action' is nil, it still makes sense to - ;; auto-execute here: the user has specified exactly what they want. - (let ((lsp-auto-execute-action t)) - (condition-case nil - (lsp-execute-code-action-by-kind ,code-action-kind) - (lsp-no-code-actions - (when (called-interactively-p 'any) - (lsp--info ,(format "%s action not available" code-action-kind)))))))) - -(lsp-make-interactive-code-action organize-imports "source.organizeImports") - -(defun lsp--make-document-range-formatting-params (start end) - "Make DocumentRangeFormattingParams for selected region." - (lsp:set-document-range-formatting-params-range (lsp--make-document-formatting-params) - (lsp--region-to-range start end))) - -(defconst lsp--highlight-kind-face - '((1 . lsp-face-highlight-textual) - (2 . lsp-face-highlight-read) - (3 . lsp-face-highlight-write))) - -(defun lsp--remove-overlays (name) - (save-restriction - (widen) - (remove-overlays (point-min) (point-max) name t))) - -(defun lsp-document-highlight () - "Highlight all relevant references to the symbol under point." - (interactive) - (lsp--remove-overlays 'lsp-highlight) ;; clear any previous highlights - (setq lsp--have-document-highlights nil - lsp--symbol-bounds-of-last-highlight-invocation nil) - (let ((lsp-enable-symbol-highlighting t)) - (lsp--document-highlight))) - -(defun lsp--document-highlight-callback (highlights) - "Create a callback to process the reply of a -`textDocument/documentHighlight' message for the buffer BUF. -A reference is highlighted only if it is visible in a window." - (lsp--remove-overlays 'lsp-highlight) - - (let* ((wins-visible-pos (-map (lambda (win) - (cons (1- (line-number-at-pos (window-start win) t)) - (1+ (line-number-at-pos (window-end win) t)))) - (get-buffer-window-list nil nil 'visible)))) - (setq lsp--have-document-highlights t) - (-map - (-lambda ((&DocumentHighlight :range (&Range :start (start &as &Position :line start-line) - :end (end &as &Position :line end-line)) - :kind?)) - (-map - (-lambda ((start-window . end-window)) - ;; Make the overlay only if the reference is visible - (when (and (> (1+ start-line) start-window) - (< (1+ end-line) end-window)) - (let ((start-point (lsp--position-to-point start)) - (end-point (lsp--position-to-point end))) - (when (not (and lsp-symbol-highlighting-skip-current - (<= start-point (point) end-point))) - (-doto (make-overlay start-point end-point) - (overlay-put 'face (cdr (assq (or kind? 1) lsp--highlight-kind-face))) - (overlay-put 'lsp-highlight t)))))) - wins-visible-pos)) - highlights))) - -(defcustom lsp-symbol-kinds - '((1 . "File") - (2 . "Module") - (3 . "Namespace") - (4 . "Package") - (5 . "Class") - (6 . "Method") - (7 . "Property") - (8 . "Field") - (9 . "Constructor") - (10 . "Enum") - (11 . "Interface") - (12 . "Function") - (13 . "Variable") - (14 . "Constant") - (15 . "String") - (16 . "Number") - (17 . "Boolean") - (18 . "Array") - (19 . "Object") - (20 . "Key") - (21 . "Null") - (22 . "Enum Member") - (23 . "Struct") - (24 . "Event") - (25 . "Operator") - (26 . "Type Parameter")) - "Alist mapping SymbolKinds to human-readable strings. -Various Symbol objects in the LSP protocol have an integral type, -specifying what they are. This alist maps such type integrals to -readable representations of them. See -`https://microsoft.github.io/language-server-protocol/specifications/specification-current/', -namespace SymbolKind." - :group 'lsp-mode - :type '(alist :key-type integer :value-type string)) -(defalias 'lsp--symbol-kind 'lsp-symbol-kinds) - -(lsp-defun lsp--symbol-information-to-xref - ((&SymbolInformation :kind :name - :location (&Location :uri :range (&Range :start - (&Position :line :character))))) - "Return a `xref-item' from SYMBOL information." - (xref-make (format "[%s] %s" (alist-get kind lsp-symbol-kinds) name) - (xref-make-file-location (lsp--uri-to-path uri) - line - character))) - -(defun lsp--get-document-symbols () - "Get document symbols. - -If the buffer has not been modified since symbols were last -retrieved, simply return the latest result. - -Else, if the request was initiated by Imenu updating its menu-bar -entry, perform it asynchronously; i.e., give Imenu the latest -result and then force a refresh when a new one is available. - -Else (e.g., due to interactive use of `imenu' or `xref'), -perform the request synchronously." - (if (= (buffer-chars-modified-tick) lsp--document-symbols-tick) - lsp--document-symbols - (let ((method "textDocument/documentSymbol") - (params `(:textDocument ,(lsp--text-document-identifier))) - (tick (buffer-chars-modified-tick))) - (if (not lsp--document-symbols-request-async) - (prog1 - (setq lsp--document-symbols (lsp-request method params)) - (setq lsp--document-symbols-tick tick)) - (lsp-request-async method params - (lambda (document-symbols) - (setq lsp--document-symbols document-symbols - lsp--document-symbols-tick tick) - (lsp--imenu-refresh)) - :mode 'alive - :cancel-token :document-symbols) - lsp--document-symbols)))) - -(advice-add 'imenu-update-menubar :around - (lambda (oldfun &rest r) - (let ((lsp--document-symbols-request-async t)) - (apply oldfun r)))) - -(defun lsp--document-symbols->document-symbols-hierarchy (document-symbols current-position) - "Convert DOCUMENT-SYMBOLS to symbols hierarchy on CURRENT-POSITION." - (-let (((symbol &as &DocumentSymbol? :children?) - (seq-find (-lambda ((&DocumentSymbol :range)) - (lsp-point-in-range? current-position range)) - document-symbols))) - (if children? - (cons symbol (lsp--document-symbols->document-symbols-hierarchy children? current-position)) - (when symbol - (list symbol))))) - -(lsp-defun lsp--symbol-information->document-symbol ((&SymbolInformation :name :kind :location :container-name? :deprecated?)) - "Convert a SymbolInformation to a DocumentInformation" - (lsp-make-document-symbol :name name - :kind kind - :range (lsp:location-range location) - :children? nil - :deprecated? deprecated? - :selection-range (lsp:location-range location) - :detail? container-name?)) - -(defun lsp--symbols-informations->document-symbols-hierarchy (symbols-informations current-position) - "Convert SYMBOLS-INFORMATIONS to symbols hierarchy on CURRENT-POSITION." - (--> symbols-informations - (-keep (-lambda ((symbol &as &SymbolInformation :location (&Location :range))) - (when (lsp-point-in-range? current-position range) - (lsp--symbol-information->document-symbol symbol))) - it) - (sort it (-lambda ((&DocumentSymbol :range (&Range :start a-start-position :end a-end-position)) - (&DocumentSymbol :range (&Range :start b-start-position :end b-end-position))) - (and (lsp--position-compare b-start-position a-start-position) - (lsp--position-compare a-end-position b-end-position)))))) - -(defun lsp--symbols->document-symbols-hierarchy (symbols) - "Convert SYMBOLS to symbols-hierarchy." - (when-let ((first-symbol (lsp-seq-first symbols))) - (let ((cur-position (lsp-make-position :line (plist-get (lsp--cur-position) :line) - :character (plist-get (lsp--cur-position) :character)))) - (if (lsp-symbol-information? first-symbol) - (lsp--symbols-informations->document-symbols-hierarchy symbols cur-position) - (lsp--document-symbols->document-symbols-hierarchy symbols cur-position))))) - -(defun lsp--xref-backend () 'xref-lsp) - -(cl-defmethod xref-backend-identifier-at-point ((_backend (eql xref-lsp))) - (propertize (or (thing-at-point 'symbol) "") - 'identifier-at-point t)) - -(defun lsp--xref-elements-index (symbols path) - (-mapcat - (-lambda (sym) - (pcase-exhaustive sym - ((lsp-interface DocumentSymbol :name :children? :selection-range (lsp-interface Range :start)) - (cons (cons (concat path name) - (lsp--position-to-point start)) - (lsp--xref-elements-index children? (concat path name " / ")))) - ((lsp-interface SymbolInformation :name :location (lsp-interface Location :range (lsp-interface Range :start))) - (list (cons (concat path name) - (lsp--position-to-point start)))))) - symbols)) - -(defvar-local lsp--symbols-cache nil) - -(cl-defmethod xref-backend-identifier-completion-table ((_backend (eql xref-lsp))) - (if (lsp--find-workspaces-for "textDocument/documentSymbol") - (progn - (setq lsp--symbols-cache (lsp--xref-elements-index - (lsp--get-document-symbols) nil)) - lsp--symbols-cache) - (list (propertize (or (thing-at-point 'symbol) "") - 'identifier-at-point t)))) - -(cl-defmethod xref-backend-definitions ((_backend (eql xref-lsp)) identifier) - (save-excursion - (unless (get-text-property 0 'identifier-at-point identifier) - (goto-char (cl-rest (or (assoc identifier lsp--symbols-cache) - (user-error "Unable to find symbol %s in current document" identifier))))) - (lsp--locations-to-xref-items (lsp-request "textDocument/definition" - (lsp--text-document-position-params))))) - -(cl-defmethod xref-backend-references ((_backend (eql xref-lsp)) identifier) - (save-excursion - (unless (get-text-property 0 'identifier-at-point identifier) - (goto-char (cl-rest (or (assoc identifier lsp--symbols-cache) - (user-error "Unable to find symbol %s" identifier))))) - (lsp--locations-to-xref-items (lsp-request "textDocument/references" - (lsp--make-reference-params nil lsp-references-exclude-definition))))) - -(cl-defmethod xref-backend-apropos ((_backend (eql xref-lsp)) pattern) - (seq-map #'lsp--symbol-information-to-xref - (lsp-request "workspace/symbol" `(:query ,pattern)))) - -(defcustom lsp-rename-use-prepare t - "Whether `lsp-rename' should do a prepareRename first. -For some language servers, textDocument/prepareRename might be -too slow, in which case this variable may be set to nil. -`lsp-rename' will then use `thing-at-point' `symbol' to determine -the symbol to rename at point." - :group 'lsp-mode - :type 'boolean) - -(defun lsp--get-symbol-to-rename () - "Get a symbol to rename and placeholder at point. -Returns a cons ((START . END) . PLACEHOLDER?), and nil if -renaming is generally supported but cannot be done at point. -START and END are the bounds of the identifiers being renamed, -while PLACEHOLDER?, is either nil or a string suggested by the -language server as the initial input of a new-name prompt." - (unless (lsp-feature? "textDocument/rename") - (error "The connected server(s) doesn't support renaming")) - (if (and lsp-rename-use-prepare (lsp-feature? "textDocument/prepareRename")) - (when-let ((response - (lsp-request "textDocument/prepareRename" - (lsp--text-document-position-params)))) - (let* ((bounds (lsp--range-to-region - (if (lsp-range? response) - response - (lsp:prepare-rename-result-range response)))) - (placeholder - (and (not (lsp-range? response)) - (lsp:prepare-rename-result-placeholder response)))) - (cons bounds placeholder))) - (when-let ((bounds (bounds-of-thing-at-point 'symbol))) - (cons bounds nil)))) - -(defface lsp-face-rename '((t :underline t)) - "Face used to highlight the identifier being renamed. -Renaming can be done using `lsp-rename'." - :group 'lsp-mode) - -(defface lsp-rename-placeholder-face '((t :inherit font-lock-variable-name-face)) - "Face used to display the rename placeholder in. -When calling `lsp-rename' interactively, this will be the face of -the new name." - :group 'lsp-mode) - -(defvar lsp-rename-history '() - "History for `lsp--read-rename'.") - -(defun lsp--read-rename (at-point) - "Read a new name for a `lsp-rename' at `point' from the user. -AT-POINT shall be a structure as returned by -`lsp--get-symbol-to-rename'. - -Returns a string, which should be the new name for the identifier -at point. If renaming cannot be done at point (as determined from -AT-POINT), throw a `user-error'. - -This function is for use in `lsp-rename' only, and shall not be -relied upon." - (unless at-point - (user-error "`lsp-rename' is invalid here")) - (-let* ((((start . end) . placeholder?) at-point) - ;; Do the `buffer-substring' first to not include `lsp-face-rename' - (rename-me (buffer-substring start end)) - (placeholder (or placeholder? rename-me)) - (placeholder (propertize placeholder 'face 'lsp-rename-placeholder-face)) - - overlay) - ;; We need unwind protect, as the user might cancel here, causing the - ;; overlay to linger. - (unwind-protect - (progn - (setq overlay (make-overlay start end)) - (overlay-put overlay 'face 'lsp-face-rename) - - (read-string (format "Rename %s to: " rename-me) placeholder - 'lsp-rename-history)) - (and overlay (delete-overlay overlay))))) - -(defun lsp-rename (newname) - "Rename the symbol (and all references to it) under point to NEWNAME." - (interactive (list (lsp--read-rename (lsp--get-symbol-to-rename)))) - (when-let ((edits (lsp-request "textDocument/rename" - `( :textDocument ,(lsp--text-document-identifier) - :position ,(lsp--cur-position) - :newName ,newname)))) - (lsp--apply-workspace-edit edits 'rename))) - -(defun lsp--on-rename-file (old-func old-name new-name &optional ok-if-already-exists?) - "Advice around function `rename-file'. -Applies OLD-FUNC with OLD-NAME, NEW-NAME and OK-IF-ALREADY-EXISTS?. - -This advice sends workspace/willRenameFiles before renaming file -to check if server wants to apply any workspaceEdits after renamed." - (if (and lsp-apply-edits-after-file-operations - (lsp--send-will-rename-files-p old-name)) - (let ((params (lsp-make-rename-files-params - :files (vector (lsp-make-file-rename - :oldUri (lsp--path-to-uri old-name) - :newUri (lsp--path-to-uri new-name)))))) - (when-let ((edits (lsp-request "workspace/willRenameFiles" params))) - (lsp--apply-workspace-edit edits 'rename-file) - (funcall old-func old-name new-name ok-if-already-exists?) - (when (lsp--send-did-rename-files-p) - (lsp-notify "workspace/didRenameFiles" params)))) - (funcall old-func old-name new-name ok-if-already-exists?))) - -(advice-add 'rename-file :around #'lsp--on-rename-file) - -(defcustom lsp-xref-force-references nil - "If non-nil threat everything as references(e. g. jump if only one item.)" - :group 'lsp-mode - :type 'boolean) - -(defun lsp-show-xrefs (xrefs display-action references?) - (unless (region-active-p) (push-mark nil t)) - (if (boundp 'xref-show-definitions-function) - (with-no-warnings - (xref-push-marker-stack) - (funcall (if (and references? (not lsp-xref-force-references)) - xref-show-xrefs-function - xref-show-definitions-function) - (-const xrefs) - `((window . ,(selected-window)) - (display-action . ,display-action) - ,(if (and references? (not lsp-xref-force-references)) - `(auto-jump . ,xref-auto-jump-to-first-xref) - `(auto-jump . ,xref-auto-jump-to-first-definition))))) - (xref--show-xrefs xrefs display-action))) - -(cl-defmethod seq-empty-p ((ht hash-table)) - "Function `seq-empty-p' for hash-table." - (hash-table-empty-p ht)) - -(cl-defun lsp-find-locations (method &optional extra &key display-action references?) - "Send request named METHOD and get cross references of the symbol under point. -EXTRA is a plist of extra parameters. -REFERENCES? t when METHOD returns references." - (let ((loc (lsp-request method - (append (lsp--text-document-position-params) extra)))) - (if (seq-empty-p loc) - (lsp--error "Not found for: %s" (or (thing-at-point 'symbol t) "")) - (lsp-show-xrefs (lsp--locations-to-xref-items loc) display-action references?)))) - -(cl-defun lsp-find-declaration (&key display-action) - "Find declarations of the symbol under point." - (interactive) - (lsp-find-locations "textDocument/declaration" nil :display-action display-action)) - -(cl-defun lsp-find-definition (&key display-action) - "Find definitions of the symbol under point." - (interactive) - (lsp-find-locations "textDocument/definition" nil :display-action display-action)) - -(defun lsp-find-definition-mouse (click) - "Click to start `lsp-find-definition' at clicked point." - (interactive "e") - (let* ((ec (event-start click)) - (p1 (posn-point ec)) - (w1 (posn-window ec))) - (select-window w1) - (goto-char p1) - (lsp-find-definition))) - -(cl-defun lsp-find-implementation (&key display-action) - "Find implementations of the symbol under point." - (interactive) - (lsp-find-locations "textDocument/implementation" - nil - :display-action display-action - :references? t)) - -(cl-defun lsp-find-references (&optional exclude-declaration &key display-action) - "Find references of the symbol under point." - (interactive "P") - (lsp-find-locations "textDocument/references" - (list :context `(:includeDeclaration ,(lsp-json-bool (not (or exclude-declaration lsp-references-exclude-definition))))) - :display-action display-action - :references? t)) - -(cl-defun lsp-find-type-definition (&key display-action) - "Find type definitions of the symbol under point." - (interactive) - (lsp-find-locations "textDocument/typeDefinition" nil :display-action display-action)) - -(defalias 'lsp-find-custom #'lsp-find-locations) -(defalias 'lsp-goto-implementation #'lsp-find-implementation) -(defalias 'lsp-goto-type-definition #'lsp-find-type-definition) - -(with-eval-after-load 'evil - (evil-set-command-property 'lsp-find-definition :jump t) - (evil-set-command-property 'lsp-find-implementation :jump t) - (evil-set-command-property 'lsp-find-references :jump t) - (evil-set-command-property 'lsp-find-type-definition :jump t)) - -(defun lsp--workspace-method-supported? (check-command method capability workspace) - (with-lsp-workspace workspace - (if check-command - (funcall check-command workspace) - (or - (when capability (lsp--capability capability)) - (lsp--registered-capability method) - (and (not capability) (not check-command)))))) - -(defun lsp-disable-method-for-server (method server-id) - "Disable METHOD for SERVER-ID." - (cl-callf - (lambda (reqs) - (-let (((&plist :check-command :capability) reqs)) - (list :check-command - (lambda (workspace) - (unless (-> workspace - lsp--workspace-client - lsp--client-server-id - (eq server-id)) - (lsp--workspace-method-supported? check-command - method - capability - workspace)))))) - (alist-get method lsp-method-requirements nil nil 'string=))) - -(defun lsp--find-workspaces-for (msg-or-method) - "Find all workspaces in the current project that can handle MSG." - (let ((method (if (stringp msg-or-method) - msg-or-method - (plist-get msg-or-method :method)))) - (-if-let (reqs (cdr (assoc method lsp-method-requirements))) - (-let (((&plist :capability :check-command) reqs)) - (-filter - (-partial #'lsp--workspace-method-supported? - check-command method capability) - (lsp-workspaces))) - (lsp-workspaces)))) - -(defun lsp-can-execute-command? (command-name) - "Returns non-nil if current language server(s) can execute COMMAND-NAME. -The command is executed via `workspace/executeCommand'" - (cl-position - command-name - (lsp:execute-command-options-commands - (lsp:server-capabilities-execute-command-provider? - (lsp--server-capabilities))) - :test #'equal)) - -(defalias 'lsp-feature? 'lsp--find-workspaces-for) - -(cl-defmethod lsp-execute-command (_server _command _arguments) - "Dispatch COMMAND execution." - (signal 'cl-no-applicable-method nil)) - -(defun lsp-workspace-command-execute (command &optional args) - "Execute workspace COMMAND with ARGS." - (condition-case-unless-debug err - (let ((params (if args - (list :command command :arguments args) - (list :command command)))) - (lsp-request "workspace/executeCommand" params)) - (error - (error "`workspace/executeCommand' with `%s' failed.\n\n%S" - command err)))) - -(defun lsp-send-execute-command (command &optional args) - "Create and send a `workspace/executeCommand' message having command COMMAND -and optional ARGS." - (lsp-workspace-command-execute command args)) - -(defalias 'lsp-point-to-position #'lsp--point-to-position) -(defalias 'lsp-text-document-identifier #'lsp--text-document-identifier) -(defalias 'lsp--send-execute-command #'lsp-send-execute-command) -(defalias 'lsp-on-open #'lsp--text-document-did-open) -(defalias 'lsp-on-save #'lsp--text-document-did-save) - -(defun lsp--set-configuration (settings) - "Set the SETTINGS for the lsp server." - (lsp-notify "workspace/didChangeConfiguration" `(:settings ,settings))) - -(defun lsp-current-buffer () - (or lsp--virtual-buffer - (current-buffer))) - -(defun lsp-buffer-live-p (buffer-id) - (if-let ((buffer-live (plist-get buffer-id :buffer-live?))) - (funcall buffer-live buffer-id) - (buffer-live-p buffer-id))) - -(defun lsp--on-set-visited-file-name (old-func &rest args) - "Advice around function `set-visited-file-name'. - -This advice sends textDocument/didClose for the old file and -textDocument/didOpen for the new file." - (when lsp--cur-workspace - (lsp--text-document-did-close t)) - (prog1 (apply old-func args) - (when lsp--cur-workspace - (lsp--text-document-did-open)))) - -(advice-add 'set-visited-file-name :around #'lsp--on-set-visited-file-name) - -(defcustom lsp-flush-delayed-changes-before-next-message t - "If non-nil send the document changes update before sending other messages. - -If nil, and `lsp-debounce-full-sync-notifications' is non-nil, - change notifications will be throttled by - `lsp-debounce-full-sync-notifications-interval' regardless of - other messages." - :group 'lsp-mode - :type 'boolean) - -(defvar lsp--not-flushing-delayed-changes t) - -(defun lsp--send-no-wait (message proc) - "Send MESSAGE to PROC without waiting for further output." - - (when (and lsp--not-flushing-delayed-changes - lsp-flush-delayed-changes-before-next-message) - (let ((lsp--not-flushing-delayed-changes nil)) - (lsp--flush-delayed-changes))) - (lsp-process-send proc message)) - -(define-error 'lsp-parse-error - "Error parsing message from language server" 'lsp-error) -(define-error 'lsp-unknown-message-type - "Unknown message type" '(lsp-error lsp-parse-error)) -(define-error 'lsp-unknown-json-rpc-version - "Unknown JSON-RPC protocol version" '(lsp-error lsp-parse-error)) -(define-error 'lsp-no-content-length - "Content-Length header missing in message" '(lsp-error lsp-parse-error)) -(define-error 'lsp-invalid-header-name - "Invalid header name" '(lsp-error lsp-parse-error)) - -;; id method -;; x x request -;; x . response -;; . x notification -(defun lsp--get-message-type (json-data) - "Get the message type from JSON-DATA." - (if (lsp:json-message-id? json-data) - (if (lsp:json-message-error? json-data) - 'response-error - (if (lsp:json-message-method? json-data) - 'request - 'response)) - 'notification)) - -(defconst lsp--default-notification-handlers - (ht ("window/showMessage" #'lsp--window-show-message) - ("window/logMessage" #'lsp--window-log-message) - ("window/showInputBox" #'lsp--window-show-input-box) - ("window/showQuickPick" #'lsp--window-show-quick-pick) - ("textDocument/publishDiagnostics" #'lsp--on-diagnostics) - ("textDocument/diagnosticsEnd" #'ignore) - ("textDocument/diagnosticsBegin" #'ignore) - ("telemetry/event" #'ignore) - ("$/progress" (lambda (workspace params) - (funcall lsp-progress-function workspace params))))) - -(lsp-defun lsp--on-notification (workspace (&JSONNotification :params :method)) - "Call the appropriate handler for NOTIFICATION." - (-let ((client (lsp--workspace-client workspace))) - (when (lsp--log-io-p method) - (lsp--log-entry-new (lsp--make-log-entry method nil params 'incoming-notif) - lsp--cur-workspace)) - (if-let ((handler (or (gethash method (lsp--client-notification-handlers client)) - (gethash method lsp--default-notification-handlers)))) - (funcall handler workspace params) - (when (and method (not (string-prefix-p "$" method))) - (lsp-warn "Unknown notification: %s" method))))) - -(lsp-defun lsp--build-workspace-configuration-response ((&ConfigurationParams :items)) - "Get section configuration. -PARAMS are the `workspace/configuration' request params" - (->> items - (-map (-lambda ((&ConfigurationItem :section?)) - (-let* ((path-parts (split-string section? "\\.")) - (path-without-last (s-join "." (-slice path-parts 0 -1))) - (path-parts-len (length path-parts))) - (cond - ((<= path-parts-len 1) - (ht-get (lsp-configuration-section section?) - (car-safe path-parts) - (ht-create))) - ((> path-parts-len 1) - (when-let ((section (lsp-configuration-section path-without-last)) - (keys path-parts)) - (while (and keys section) - (setf section (ht-get section (pop keys)))) - section)))))) - (apply #'vector))) - -(defun lsp--ms-since (timestamp) - "Integer number of milliseconds since TIMESTAMP. Fractions discarded." - (floor (* 1000 (float-time (time-since timestamp))))) - -(defun lsp--send-request-response (workspace recv-time request response) - "Send the RESPONSE for REQUEST in WORKSPACE and log if needed." - (-let* (((&JSONResponse :params :method :id) request) - (process (lsp--workspace-proc workspace)) - (response (lsp--make-response id response)) - (req-entry (and lsp-log-io - (lsp--make-log-entry method id params 'incoming-req))) - (resp-entry (and lsp-log-io - (lsp--make-log-entry method id response 'outgoing-resp - (lsp--ms-since recv-time))))) - ;; Send response to the server. - (when (lsp--log-io-p method) - (lsp--log-entry-new req-entry workspace) - (lsp--log-entry-new resp-entry workspace)) - (lsp--send-no-wait response process))) - -(lsp-defun lsp--on-request (workspace (request &as &JSONRequest :params :method)) - "Call the appropriate handler for REQUEST, and send the return value to the -server. WORKSPACE is the active workspace." - (-let* ((recv-time (current-time)) - (client (lsp--workspace-client workspace)) - (buffers (lsp--workspace-buffers workspace)) - handler - (response (cond - ((setq handler (gethash method (lsp--client-request-handlers client) nil)) - (funcall handler workspace params)) - ((setq handler (gethash method (lsp--client-async-request-handlers client) nil)) - (funcall handler workspace params - (-partial #'lsp--send-request-response - workspace recv-time request)) - 'delay-response) - ((equal method "client/registerCapability") - (mapc #'lsp--server-register-capability - (lsp:registration-params-registrations params)) - (mapc (lambda (buf) - (when (lsp-buffer-live-p buf) - (lsp-with-current-buffer buf - (lsp-unconfig-buffer) - (lsp-configure-buffer)))) - buffers) - nil) - ((equal method "window/showMessageRequest") - (let ((choice (lsp--window-log-message-request params))) - `(:title ,choice))) - ((equal method "window/showDocument") - (let ((success? (lsp--window-show-document params))) - (lsp-make-show-document-result :success (or success? - :json-false)))) - ((equal method "client/unregisterCapability") - (mapc #'lsp--server-unregister-capability - (lsp:unregistration-params-unregisterations params)) - (mapc (lambda (buf) - (when (lsp-buffer-live-p buf) - (lsp-with-current-buffer buf - (lsp-unconfig-buffer) - (lsp-configure-buffer)))) - buffers) - nil) - ((equal method "workspace/applyEdit") - (list :applied (condition-case err - (prog1 t - (lsp--apply-workspace-edit (lsp:apply-workspace-edit-params-edit params) 'server-requested)) - (error - (lsp--error "Failed to apply edits with message %s" - (error-message-string err)) - :json-false)))) - ((equal method "workspace/configuration") - (with-lsp-workspace workspace - (if-let ((buf (car buffers))) - (lsp-with-current-buffer buf - (lsp--build-workspace-configuration-response params)) - (lsp--with-workspace-temp-buffer (lsp--workspace-root workspace) - (lsp--build-workspace-configuration-response params))))) - ((equal method "workspace/workspaceFolders") - (let ((folders (or (-> workspace - (lsp--workspace-client) - (lsp--client-server-id) - (gethash (lsp-session-server-id->folders (lsp-session)))) - (lsp-session-folders (lsp-session))))) - (->> folders - (-distinct) - (-map (lambda (folder) - (list :uri (lsp--path-to-uri folder)))) - (apply #'vector)))) - ((equal method "window/workDoneProgress/create") - nil ;; no specific reply, no processing required - ) - ((equal method "workspace/semanticTokens/refresh") - (when (and lsp-semantic-tokens-enable - (fboundp 'lsp--semantic-tokens-on-refresh)) - (lsp--semantic-tokens-on-refresh workspace)) - nil) - ((equal method "workspace/codeLens/refresh") - (when (and lsp-lens-enable - (fboundp 'lsp--lens-on-refresh)) - (lsp--lens-on-refresh workspace)) - nil) - (t (lsp-warn "Unknown request method: %s" method) nil)))) - ;; Send response to the server. - (unless (eq response 'delay-response) - (lsp--send-request-response workspace recv-time request response)))) - -(lsp-defun lsp--error-string ((&JSONError :message :code)) - "Format ERR as a user friendly string." - (format "Error from the Language Server: %s (%s)" - message - (or (car (alist-get code lsp--errors)) "Unknown error"))) - -(defun lsp--get-body-length (headers) - (let ((content-length (cdr (assoc "Content-Length" headers)))) - (if content-length - (string-to-number content-length) - - ;; This usually means either the server or our parser is - ;; screwed up with a previous Content-Length - (error "No Content-Length header")))) - -(defun lsp--parse-header (s) - "Parse string S as a LSP (KEY . VAL) header." - (let ((pos (string-match "\:" s)) - key val) - (unless pos - (signal 'lsp-invalid-header-name (list s))) - (setq key (substring s 0 pos) - val (s-trim-left (substring s (+ 1 pos)))) - (when (equal key "Content-Length") - (cl-assert (cl-loop for c across val - when (or (> c ?9) (< c ?0)) return nil - finally return t) - nil (format "Invalid Content-Length value: %s" val))) - (cons key val))) - -(defmacro lsp--read-json (str) - "Read json string STR." - (if (progn - (require 'json) - (fboundp 'json-parse-string)) - `(json-parse-string ,str - :object-type (if lsp-use-plists - 'plist - 'hash-table) - :null-object nil - :false-object nil) - `(let ((json-array-type 'vector) - (json-object-type (if lsp-use-plists - 'plist - 'hash-table)) - (json-false nil)) - (json-read-from-string ,str)))) - -(defmacro lsp-json-read-buffer () - "Read json from the current buffer." - (if (progn - (require 'json) - (fboundp 'json-parse-buffer)) - `(json-parse-buffer :object-type (if lsp-use-plists - 'plist - 'hash-table) - :null-object nil - :false-object nil) - `(let ((json-array-type 'vector) - (json-object-type (if lsp-use-plists - 'plist - 'hash-table)) - (json-false nil)) - (json-read)))) - -(defun lsp--read-json-file (file-path) - "Read json file." - (-> file-path - (f-read-text) - (lsp--read-json))) - -(defun lsp--parser-on-message (json-data workspace) - "Called when the parser P read a complete MSG from the server." - (with-demoted-errors "Error processing message %S." - (with-lsp-workspace workspace - (let* ((client (lsp--workspace-client workspace)) - (id (--when-let (lsp:json-response-id json-data) - (if (stringp it) (string-to-number it) it))) - (data (lsp:json-response-result json-data))) - (pcase (lsp--get-message-type json-data) - ('response - (cl-assert id) - (-let [(callback _ method _ before-send) (gethash id (lsp--client-response-handlers client))] - (when (lsp--log-io-p method) - (lsp--log-entry-new - (lsp--make-log-entry method id data 'incoming-resp - (lsp--ms-since before-send)) - workspace)) - (when callback - (remhash id (lsp--client-response-handlers client)) - (funcall callback (lsp:json-response-result json-data))))) - ('response-error - (cl-assert id) - (-let [(_ callback method _ before-send) (gethash id (lsp--client-response-handlers client))] - (when (lsp--log-io-p method) - (lsp--log-entry-new - (lsp--make-log-entry method id (lsp:json-response-error-error json-data) - 'incoming-resp (lsp--ms-since before-send)) - workspace)) - (when callback - (remhash id (lsp--client-response-handlers client)) - (funcall callback (lsp:json-response-error-error json-data))))) - ('notification - (lsp--on-notification workspace json-data)) - ('request (lsp--on-request workspace json-data))))))) - -(defun lsp--create-filter-function (workspace) - "Make filter for the workspace." - (let ((body-received 0) - leftovers body-length body chunk) - (lambda (_proc input) - (setf chunk (if (s-blank? leftovers) - input - (concat leftovers input))) - - (let (messages) - (while (not (s-blank? chunk)) - (if (not body-length) - ;; Read headers - (if-let ((body-sep-pos (string-match-p "\r\n\r\n" chunk))) - ;; We've got all the headers, handle them all at once: - (setf body-length (lsp--get-body-length - (mapcar #'lsp--parse-header - (split-string - (substring-no-properties chunk - (or (string-match-p "Content-Length" chunk) - (error "Unable to find Content-Length header.")) - body-sep-pos) - "\r\n"))) - body-received 0 - leftovers nil - chunk (substring-no-properties chunk (+ body-sep-pos 4))) - - ;; Haven't found the end of the headers yet. Save everything - ;; for when the next chunk arrives and await further input. - (setf leftovers chunk - chunk nil)) - (let* ((chunk-length (string-bytes chunk)) - (left-to-receive (- body-length body-received)) - (this-body (if (< left-to-receive chunk-length) - (prog1 (substring-no-properties chunk 0 left-to-receive) - (setf chunk (substring-no-properties chunk left-to-receive))) - (prog1 chunk - (setf chunk nil)))) - (body-bytes (string-bytes this-body))) - (push this-body body) - (setf body-received (+ body-received body-bytes)) - (when (>= chunk-length left-to-receive) - (condition-case err - (with-temp-buffer - (apply #'insert - (nreverse - (prog1 body - (setf leftovers nil - body-length nil - body-received nil - body nil)))) - (decode-coding-region (point-min) - (point-max) - 'utf-8) - (goto-char (point-min)) - (push (lsp-json-read-buffer) messages)) - - (error - (lsp-warn "Failed to parse the following chunk:\n'''\n%s\n'''\nwith message %s" - (concat leftovers input) - err))))))) - (mapc (lambda (msg) - (lsp--parser-on-message msg workspace)) - (nreverse messages)))))) - -(defvar-local lsp--line-col-to-point-hash-table nil - "Hash table with keys (line . col) and values that are either point positions -or markers.") - -(defcustom lsp-imenu-detailed-outline t - "Whether `lsp-imenu' should include signatures. -This will be ignored if the server doesn't provide the necessary -information, for example if it doesn't support DocumentSymbols." - :group 'lsp-imenu - :type 'boolean) - -(defcustom lsp-imenu-hide-parent-details t - "Whether `lsp-imenu' should hide signatures of parent nodes." - :group 'lsp-imenu - :type 'boolean) - -(defface lsp-details-face '((t :height 0.8 :inherit shadow)) - "Used to display additional information throughout `lsp'. -Things like line numbers, signatures, ... are considered -additional information. Often, additional faces are defined that -inherit from this face by default, like `lsp-signature-face', and -they may be customized for finer control." - :group 'lsp-mode) - -(defface lsp-signature-face '((t :inherit lsp-details-face)) - "Used to display signatures in `imenu', ...." - :group 'lsp-mode) - -(lsp-defun lsp-render-symbol ((&DocumentSymbol :name :detail? :deprecated?) - show-detail?) - "Render INPUT0, an `&DocumentSymbol', to a string. -If SHOW-DETAIL? is set, make use of its `:detail?' field (often -the signature)." - (let ((detail (and show-detail? (s-present? detail?) - (propertize (concat " " (s-trim-left detail?)) - 'face 'lsp-signature-face))) - (name (if deprecated? - (propertize name 'face 'lsp-face-semhl-deprecated) name))) - (concat name detail))) - -(lsp-defun lsp-render-symbol-information ((&SymbolInformation :name :deprecated? :container-name?) - separator) - "Render a piece of SymbolInformation. -Handle :deprecated?. If SEPARATOR is non-nil, the -symbol's (optional) parent, SEPARATOR and the symbol itself are -concatenated." - (when (and separator container-name? (not (string-empty-p container-name?))) - (setq name (concat name separator container-name?))) - (if deprecated? (propertize name 'face 'lsp-face-semhl-deprecated) name)) - -(defun lsp--symbol-to-imenu-elem (sym) - "Convert SYM to imenu element. - -SYM is a SymbolInformation message. - -Return a cons cell (full-name . start-point)." - (let ((start-point (ht-get lsp--line-col-to-point-hash-table - (lsp--get-line-and-col sym)))) - (cons (lsp-render-symbol-information - sym (and lsp-imenu-show-container-name - lsp-imenu-container-name-separator)) - start-point))) - -(lsp-defun lsp--symbol-to-hierarchical-imenu-elem ((sym &as &DocumentSymbol :children?)) - "Convert SYM to hierarchical imenu elements. - -SYM is a DocumentSymbol message. - -Return cons cell (\"symbol-name (symbol-kind)\" . start-point) if -SYM doesn't have any children. Otherwise return a cons cell with -an alist - - (\"symbol-name\" . ((\"(symbol-kind)\" . start-point) - cons-cells-from-children))" - (let ((filtered-children (lsp--imenu-filter-symbols children?)) - (signature (lsp-render-symbol sym lsp-imenu-detailed-outline))) - (if (seq-empty-p filtered-children) - (cons signature - (ht-get lsp--line-col-to-point-hash-table - (lsp--get-line-and-col sym))) - (cons signature - (lsp--imenu-create-hierarchical-index filtered-children))))) - -(lsp-defun lsp--symbol-ignore ((&SymbolInformation :kind)) - "Determine if SYM is for the current document and is to be shown." - ;; It's a SymbolInformation or DocumentSymbol, which is always in the - ;; current buffer file. - (and lsp-imenu-index-symbol-kinds - (numberp kind) - (let ((clamped-kind (if (< 0 kind (length lsp/symbol-kind-lookup)) - kind - 0))) - (not (memql (aref lsp/symbol-kind-lookup clamped-kind) - lsp-imenu-index-symbol-kinds))))) - -(lsp-defun lsp--get-symbol-type ((&SymbolInformation :kind)) - "The string name of the kind of SYM." - (alist-get kind lsp-symbol-kinds "Other")) - -(defun lsp--get-line-and-col (sym) - "Obtain the line and column corresponding to SYM." - (-let* ((location (lsp:symbol-information-location sym)) - (name-range (or (and location (lsp:location-range location)) - (lsp:document-symbol-selection-range sym))) - ((&Range :start (&Position :line :character)) name-range)) - (cons line character))) - -(defun lsp--collect-lines-and-cols (symbols) - "Return a sorted list ((line . col) ...) of the locations of SYMBOLS." - (let ((stack (mapcar 'identity symbols)) - line-col-list) - (while stack - (let ((sym (pop stack))) - (push (lsp--get-line-and-col sym) line-col-list) - (unless (seq-empty-p (lsp:document-symbol-children? sym)) - (setf stack (nconc (lsp--imenu-filter-symbols (lsp:document-symbol-children? sym)) stack))))) - (-sort #'lsp--line-col-comparator line-col-list))) - -(defun lsp--convert-line-col-to-points-batch (line-col-list) - "Convert a sorted list of positions from line-column -representation to point representation." - (let ((line-col-to-point-map (ht-create)) - (inhibit-field-text-motion t) - (curr-line 0)) - (lsp-save-restriction-and-excursion - (goto-char (point-min)) - (cl-loop for (line . col) in line-col-list do - (forward-line (- line curr-line)) - (setq curr-line line) - (let ((line-end (line-end-position))) - (if (or (not col) (> col (- line-end (point)))) - (goto-char line-end) - (forward-char col))) - (ht-set! line-col-to-point-map (cons line col) (if imenu-use-markers - (point-marker) - (point))))) - line-col-to-point-map)) - -(cl-defun lsp--line-col-comparator ((l1 . c1) (l2 . c2)) - (or (< l1 l2) - (and (= l1 l2) - (cond ((and c1 c2) - (< c1 c2)) - (c1 t))))) - -(defun lsp-imenu-create-uncategorized-index (symbols) - "Create imenu index from document SYMBOLS. -This function, unlike `lsp-imenu-create-categorized-index', does -not categorize by type, but instead returns an `imenu' index -corresponding to the symbol hierarchy returned by the server -directly." - (let* ((lsp--line-col-to-point-hash-table (-> symbols - lsp--collect-lines-and-cols - lsp--convert-line-col-to-points-batch))) - (if (lsp--imenu-hierarchical-p symbols) - (lsp--imenu-create-hierarchical-index symbols) - (lsp--imenu-create-non-hierarchical-index symbols)))) - -(defcustom lsp-imenu-symbol-kinds - '((1 . "Files") - (2 . "Modules") - (3 . "Namespaces") - (4 . "Packages") - (5 . "Classes") - (6 . "Methods") - (7 . "Properties") - (8 . "Fields") - (9 . "Constructors") - (10 . "Enums") - (11 . "Interfaces") - (12 . "Functions") - (13 . "Variables") - (14 . "Constants") - (15 . "Strings") - (16 . "Numbers") - (17 . "Booleans") - (18 . "Arrays") - (19 . "Objects") - (20 . "Keys") - (21 . "Nulls") - (22 . "Enum Members") - (23 . "Structs") - (24 . "Events") - (25 . "Operators") - (26 . "Type Parameters")) - "`lsp-symbol-kinds', but only used by `imenu'. -A new variable is needed, as it is `imenu' convention to use -pluralized categories, which `lsp-symbol-kinds' doesn't. If the -non-pluralized names are preferred, this can be set to -`lsp-symbol-kinds'." - :type '(alist :key-type integer :value-type string)) - -(defun lsp--imenu-kind->name (kind) - (alist-get kind lsp-imenu-symbol-kinds "?")) - -(defun lsp-imenu-create-top-level-categorized-index (symbols) - "Create an `imenu' index categorizing SYMBOLS by type. -Only root symbols are categorized. - -See `lsp-symbol-kinds' to customize the category naming. SYMBOLS -shall be a list of DocumentSymbols or SymbolInformation." - (mapcan - (-lambda ((type . symbols)) - (let ((cat (lsp--imenu-kind->name type)) - (symbols (lsp-imenu-create-uncategorized-index symbols))) - ;; If there is no :kind (this is being defensive), or we couldn't look it - ;; up, just display the symbols inline, without categories. - (if cat (list (cons cat symbols)) symbols))) - (sort (seq-group-by #'lsp:document-symbol-kind symbols) - (-lambda ((kinda) (kindb)) (< kinda kindb))))) - -(lsp-defun lsp--symbol->imenu ((sym &as &DocumentSymbol :selection-range (&RangeToPoint :start))) - "Convert an `&DocumentSymbol' to an `imenu' entry." - (cons (lsp-render-symbol sym lsp-imenu-detailed-outline) start)) - -(defun lsp--imenu-create-categorized-index-1 (symbols) - "Returns an `imenu' index from SYMBOLS categorized by type. -The result looks like this: ((\"Variables\" . (...)))." - (->> - symbols - (mapcan - (-lambda ((sym &as &DocumentSymbol :kind :children?)) - (if (seq-empty-p children?) - (list (list kind (lsp--symbol->imenu sym))) - (let ((parent (lsp-render-symbol sym (and lsp-imenu-detailed-outline - (not lsp-imenu-hide-parent-details))))) - (cons - (list kind (lsp--symbol->imenu sym)) - (mapcar (-lambda ((type . imenu-items)) - (list type (cons parent (mapcan #'cdr imenu-items)))) - (-group-by #'car (lsp--imenu-create-categorized-index-1 children?)))))))) - (-group-by #'car) - (mapcar - (-lambda ((kind . syms)) - (cons kind (mapcan #'cdr syms)))))) - -(defun lsp--imenu-create-categorized-index (symbols) - (let ((syms (lsp--imenu-create-categorized-index-1 symbols))) - (dolist (sym syms) - (setcar sym (lsp--imenu-kind->name (car sym)))) - syms)) - -(lsp-defun lsp--symbol-information->imenu ((sym &as &SymbolInformation :location (&Location :range (&RangeToPoint :start)))) - (cons (lsp-render-symbol-information sym nil) start)) - -(defun lsp--imenu-create-categorized-index-flat (symbols) - "Create a kind-categorized index for SymbolInformation." - (mapcar (-lambda ((kind . syms)) - (cons (lsp--imenu-kind->name kind) - (mapcan (-lambda ((parent . children)) - (let ((children (mapcar #'lsp--symbol-information->imenu children))) - (if parent (list (cons parent children)) children))) - (-group-by #'lsp:symbol-information-container-name? syms)))) - (seq-group-by #'lsp:symbol-information-kind symbols))) - -(defun lsp-imenu-create-categorized-index (symbols) - (if (lsp--imenu-hierarchical-p symbols) - (lsp--imenu-create-categorized-index symbols) - (lsp--imenu-create-categorized-index-flat symbols))) - -(defcustom lsp-imenu-index-function #'lsp-imenu-create-uncategorized-index - "Function that should create an `imenu' index. -It will be called with a list of SymbolInformation or -DocumentSymbols, whose first level is already filtered. It shall -then return an appropriate `imenu' index (see -`imenu-create-index-function'). - -Note that this interface is not stable, and subject to change any -time." - :group 'lsp-imenu - :type '(radio - (const :tag "Categorize by type" - lsp-imenu-create-categorized-index) - (const :tag "Categorize root symbols by type" - lsp-imenu-create-top-level-categorized-index) - (const :tag "Uncategorized, inline entries" - lsp-imenu-create-uncategorized-index) - (function :tag "Custom function"))) - -(defun lsp--imenu-create-index () - "Create an `imenu' index based on the language server. -Respects `lsp-imenu-index-function'." - (let ((symbols (lsp--imenu-filter-symbols (lsp--get-document-symbols)))) - (funcall lsp-imenu-index-function symbols))) - -(defun lsp--imenu-filter-symbols (symbols) - "Filter out unsupported symbols from SYMBOLS." - (seq-remove #'lsp--symbol-ignore symbols)) - -(defun lsp--imenu-hierarchical-p (symbols) - "Determine whether any element in SYMBOLS has children." - (seq-some #'lsp-document-symbol? symbols)) - -(defun lsp--imenu-create-non-hierarchical-index (symbols) - "Create imenu index for non-hierarchical SYMBOLS. - -SYMBOLS are a list of DocumentSymbol messages. - -Return a nested alist keyed by symbol names. e.g. - - ((\"SomeClass\" (\"(Class)\" . 10) - (\"someField (Field)\" . 20) - (\"someFunction (Function)\" . 25) - (\"SomeSubClass\" (\"(Class)\" . 30) - (\"someSubField (Field)\" . 35)) - (\"someFunction (Function)\" . 40))" - (seq-map (lambda (nested-alist) - (cons (car nested-alist) - (seq-map #'lsp--symbol-to-imenu-elem (cdr nested-alist)))) - (seq-group-by #'lsp--get-symbol-type symbols))) - -(defun lsp--imenu-create-hierarchical-index (symbols) - "Create imenu index for hierarchical SYMBOLS. - -SYMBOLS are a list of DocumentSymbol messages. - -Return a nested alist keyed by symbol names. e.g. - - ((\"SomeClass\" (\"(Class)\" . 10) - (\"someField (Field)\" . 20) - (\"someFunction (Function)\" . 25) - (\"SomeSubClass\" (\"(Class)\" . 30) - (\"someSubField (Field)\" . 35)) - (\"someFunction (Function)\" . 40))" - (seq-map #'lsp--symbol-to-hierarchical-imenu-elem - (seq-sort #'lsp--imenu-symbol-lessp symbols))) - -(defun lsp--imenu-symbol-lessp (sym1 sym2) - (let* ((compare-results (mapcar (lambda (method) - (funcall (alist-get method lsp--imenu-compare-function-alist) - sym1 sym2)) - lsp-imenu-sort-methods)) - (result (seq-find (lambda (result) - (not (= result 0))) - compare-results - 0))) - (and (numberp result) (< result 0)))) - -(lsp-defun lsp--imenu-compare-kind ((&SymbolInformation :kind left) - (&SymbolInformation :kind right)) - "Compare SYM1 and SYM2 by kind." - (- left right)) - -(defun lsp--imenu-compare-line-col (sym1 sym2) - (if (lsp--line-col-comparator - (lsp--get-line-and-col sym1) - (lsp--get-line-and-col sym2)) - -1 - 1)) - -(lsp-defun lsp--imenu-compare-name ((&SymbolInformation :name name1) - (&SymbolInformation :name name2)) - "Compare SYM1 and SYM2 by name." - (let ((result (compare-strings name1 0 (length name1) name2 0 (length name2)))) - (if (numberp result) result 0))) - -(defun lsp--imenu-refresh () - "Force Imenu to refresh itself." - (imenu--menubar-select imenu--rescan-item)) - -(defun lsp-enable-imenu () - "Use lsp-imenu for the current buffer." - (imenu--cleanup) - (add-function :override (local 'imenu-create-index-function) #'lsp--imenu-create-index) - (setq-local imenu-menubar-modified-tick -1) - (setq-local imenu--index-alist nil) - (when menu-bar-mode - (lsp--imenu-refresh))) - -(defun lsp-resolve-final-command (command &optional test?) - "Resolve final function COMMAND." - (let* ((command (lsp-resolve-value command)) - (command (cl-etypecase command - (list - (cl-assert (seq-every-p (apply-partially #'stringp) command) nil - "Invalid command list") - command) - (string (list command))))) - (if (and (file-remote-p default-directory) (not test?)) - (list shell-file-name "-c" - (string-join (cons "stty raw > /dev/null;" - (mapcar #'shell-quote-argument command)) - " ")) - command))) - -(defun lsp-server-present? (final-command) - "Check whether FINAL-COMMAND is present." - (let ((binary-found? (executable-find (cl-first final-command) t))) - (if binary-found? - (lsp-log "Command \"%s\" is present on the path." (s-join " " final-command)) - (lsp-log "Command \"%s\" is not present on the path." (s-join " " final-command))) - binary-found?)) - -(defun lsp--value-to-string (value) - "Convert VALUE to a string that can be set as value in an environment -variable." - (cond - ((stringp value) value) - ((booleanp value) (if value - "1" - "0")) - ((and (sequencep value) - (seq-every-p #'stringp value)) (string-join value ":")) - (t (user-error "Only strings, booleans, and sequences of strings are supported as environment variables")))) - -(defun lsp--compute-process-environment (environment-fn) - "Append a list of KEY=VALUE from the alist ENVIRONMENT to `process-environment'. -Ignore non-boolean keys whose value is nil." - (let ((environment (if environment-fn - (funcall environment-fn) - nil))) - (-flatten (cons (cl-loop for (key . value) in environment - if (or (eval value) - (eq (get value 'custom-type) 'boolean)) - collect (concat key "=" (lsp--value-to-string - (eval value)))) - process-environment)))) - -(defun lsp--default-directory-for-connection (&optional path) - "Return path to be used for the working directory of a LSP process. - -If `lsp-use-workspace-root-for-server-default-directory' is -non-nil, uses `lsp-workspace-root' to find the directory -corresponding to PATH, else returns `default-directory'." - (if lsp-use-workspace-root-for-server-default-directory - (lsp-workspace-root path) - default-directory)) - -(defun lsp--fix-remote-cmd (program) - "Helper for `lsp-stdio-connection'. -Originally coppied from eglot." - - (if (file-remote-p default-directory) - (list shell-file-name "-c" - (string-join (cons "stty raw > /dev/null;" - (mapcar #'shell-quote-argument program)) - " ")) - program)) - -(defvar tramp-use-ssh-controlmaster-options) -(defvar tramp-ssh-controlmaster-options) - -(defun lsp-stdio-connection (command &optional test-command) - "Returns a connection property list using COMMAND. -COMMAND can be: A string, denoting the command to launch the -language server. A list of strings, denoting an executable with -its command line arguments. A function, that either returns a -string or a list of strings. In all cases, the launched language -server should send and receive messages on standard I/O. -TEST-COMMAND is a function with no arguments which returns -whether the command is present or not. When not specified -`lsp-mode' will check whether the first element of the list -returned by COMMAND is available via `executable-find'" - (cl-check-type command (or string - function - (and list - (satisfies (lambda (l) - (seq-every-p (lambda (el) - (stringp el)) - l)))))) - (list :connect (lambda (filter sentinel name environment-fn workspace) - (if (and (functionp 'json-rpc-connection) - (not (file-remote-p default-directory))) - (lsp-json-rpc-connection workspace (lsp-resolve-final-command command)) - (let ((final-command (lsp-resolve-final-command command)) - (process-name (generate-new-buffer-name name)) - (process-environment - (lsp--compute-process-environment environment-fn))) - (let* ((stderr-buf (get-buffer-create (format "*%s::stderr*" process-name))) - (default-directory (lsp--default-directory-for-connection)) - (tramp-use-ssh-controlmaster-options 'suppress) - (tramp-ssh-controlmaster-options "-o ControlMaster=no -o ControlPath=none") - (proc (make-process - :name process-name - :connection-type 'pipe - :buffer (format "*%s*" process-name) - :coding 'no-conversion - :command final-command - :filter filter - :sentinel sentinel - :stderr stderr-buf - :noquery t - :file-handler t))) - (set-process-query-on-exit-flag proc nil) - (set-process-query-on-exit-flag (get-buffer-process stderr-buf) nil) - (with-current-buffer (get-buffer stderr-buf) - ;; Make the *NAME::stderr* buffer buffer-read-only, q to bury, etc. - (special-mode)) - (cons proc proc))))) - :test? (or - test-command - (lambda () - (lsp-server-present? (lsp-resolve-final-command command t)))))) - -(defun lsp--open-network-stream (host port name) - "Open network stream to HOST:PORT. - NAME will be passed to `open-network-stream'. - RETRY-COUNT is the number of the retries. - SLEEP-INTERVAL is the sleep interval between each retry." - (let* ((retries 0) - (sleep-interval 0.01) - (number-of-retries (/ lsp-tcp-connection-timeout sleep-interval)) - connection) - (while (and (not connection) (< retries number-of-retries)) - (condition-case err - (setq connection (open-network-stream name nil host port - :type 'plain - :coding 'no-conversion)) - (file-error - (let ((inhibit-message t)) - (lsp--warn "Failed to connect to %s:%s with error message %s" - host - port - (error-message-string err)) - (sleep-for sleep-interval) - (cl-incf retries))))) - (or connection (error "Port %s was never taken. Consider increasing `lsp-tcp-connection-timeout'." port)))) - -(defun lsp--port-available (host port) - "Return non-nil if HOST and PORT are available." - (condition-case _err - (delete-process (open-network-stream "*connection-test*" nil host port :type 'plain)) - (file-error t))) - -(defun lsp--find-available-port (host starting-port) - "Find available port on HOST starting from STARTING-PORT." - (let ((port starting-port)) - (while (not (lsp--port-available host port)) - (cl-incf port)) - port)) - -(defun lsp-tcp-connection (command-fn) - "Returns a connection property list similar to `lsp-stdio-connection'. -COMMAND-FN can only be a function that takes a single argument, a -port number. It should return a command for launches a language server -process listening for TCP connections on the provided port." - (cl-check-type command-fn function) - (list - :connect (lambda (filter sentinel name environment-fn _workspace) - (let* ((host "localhost") - (port (lsp--find-available-port host (cl-incf lsp--tcp-port))) - (command (funcall command-fn port)) - (final-command (if (consp command) command (list command))) - (_ (unless (lsp-server-present? final-command) - (user-error (format "Couldn't find executable %s" (cl-first final-command))))) - (process-environment - (lsp--compute-process-environment environment-fn)) - (proc (make-process :name name :connection-type 'pipe :coding 'no-conversion - :command final-command :sentinel sentinel :stderr (format "*%s::stderr*" name) :noquery t)) - (tcp-proc (lsp--open-network-stream host port (concat name "::tcp")))) - - ;; TODO: Same :noquery issue (see above) - (set-process-query-on-exit-flag proc nil) - (set-process-query-on-exit-flag tcp-proc nil) - (set-process-filter tcp-proc filter) - (cons tcp-proc proc))) - :test? (lambda () (lsp-server-present? (funcall command-fn 0))))) - -(defalias 'lsp-tcp-server 'lsp-tcp-server-command) - -(defun lsp-tcp-server-command (command-fn) - "Create tcp server connection. -In this mode Emacs is TCP server and the language server connects -to it. COMMAND is function with one parameter(the port) and it -should return the command to start the LS server." - (cl-check-type command-fn function) - (list - :connect (lambda (filter sentinel name environment-fn _workspace) - (let* (tcp-client-connection - (tcp-server (make-network-process :name (format "*tcp-server-%s*" name) - :buffer (format "*tcp-server-%s*" name) - :family 'ipv4 - :service lsp--tcp-server-port - :sentinel (lambda (proc _string) - (lsp-log "Language server %s is connected." name) - (setf tcp-client-connection proc)) - :server 't)) - (port (process-contact tcp-server :service)) - (final-command (funcall command-fn port)) - (process-environment - (lsp--compute-process-environment environment-fn)) - (cmd-proc (make-process :name name - :connection-type 'pipe - :coding 'no-conversion - :command final-command - :stderr (format "*tcp-server-%s*::stderr" name) - :noquery t))) - (let ((retries 0)) - ;; wait for the client to connect (we sit-for 500 ms, so have to double lsp--tcp-server-wait-seconds) - (while (and (not tcp-client-connection) (< retries (* 2 lsp--tcp-server-wait-seconds))) - (lsp--info "Waiting for connection for %s, retries: %s" name retries) - (sit-for 0.500) - (cl-incf retries))) - - (unless tcp-client-connection - (condition-case nil (delete-process tcp-server) (error)) - (condition-case nil (delete-process cmd-proc) (error)) - (error "Failed to create connection to %s on port %s" name port)) - (lsp--info "Successfully connected to %s" name) - - (set-process-query-on-exit-flag cmd-proc nil) - (set-process-query-on-exit-flag tcp-client-connection nil) - (set-process-query-on-exit-flag tcp-server nil) - - (set-process-filter tcp-client-connection filter) - (set-process-sentinel tcp-client-connection sentinel) - (cons tcp-client-connection cmd-proc))) - :test? (lambda () (lsp-server-present? (funcall command-fn 0))))) - -(defalias 'lsp-tramp-connection 'lsp-stdio-connection) - -(defun lsp--auto-configure () - "Autoconfigure `company', `flycheck', `lsp-ui', etc if they are installed." - (when (functionp 'lsp-ui-mode) - (lsp-ui-mode)) - - (if lsp-headerline-breadcrumb-enable - (add-hook 'lsp-configure-hook 'lsp-headerline-breadcrumb-mode) - (remove-hook 'lsp-configure-hook 'lsp-headerline-breadcrumb-mode)) - (if lsp-modeline-code-actions-enable - (add-hook 'lsp-configure-hook 'lsp-modeline-code-actions-mode) - (remove-hook 'lsp-configure-hook 'lsp-modeline-code-actions-mode)) - (if lsp-modeline-diagnostics-enable - (add-hook 'lsp-configure-hook 'lsp-modeline-diagnostics-mode) - (remove-hook 'lsp-configure-hook 'lsp-modeline-diagnostics-mode)) - (if lsp-modeline-workspace-status-enable - (add-hook 'lsp-configure-hook 'lsp-modeline-workspace-status-mode) - (remove-hook 'lsp-configure-hook 'lsp-modeline-workspace-status-mode)) - (if lsp-lens-enable - (add-hook 'lsp-configure-hook 'lsp-lens--enable) - (remove-hook 'lsp-configure-hook 'lsp-lens--enable)) - (if lsp-semantic-tokens-enable - (add-hook 'lsp-configure-hook 'lsp-semantic-tokens--enable) - (remove-hook 'lsp-configure-hook 'lsp-semantic-tokens--enable)) - - ;; yas-snippet config - (setq-local yas-inhibit-overlay-modification-protection t)) - -(defun lsp--restart-if-needed (workspace) - "Handler restart for WORKSPACE." - (when (or (eq lsp-restart 'auto-restart) - (eq (lsp--workspace-shutdown-action workspace) 'restart) - (and (eq lsp-restart 'interactive) - (let ((query (format - "Server %s exited (check corresponding stderr buffer for details). Do you want to restart it?" - (lsp--workspace-print workspace)))) - (y-or-n-p query)))) - (--each (lsp--workspace-buffers workspace) - (when (lsp-buffer-live-p it) - (lsp-with-current-buffer it - (if lsp--buffer-deferred - (lsp-deferred) - (lsp--info "Restarting LSP in buffer %s" (buffer-name)) - (lsp))))))) - -(defun lsp--update-key (table key fn) - "Apply FN on value corresponding to KEY in TABLE." - (let ((existing-value (gethash key table))) - (if-let ((new-value (funcall fn existing-value))) - (puthash key new-value table) - (remhash key table)))) - -(defun lsp--process-sentinel (workspace process exit-str) - "Create the sentinel for WORKSPACE." - (unless (process-live-p process) - (lsp--handle-process-exit workspace exit-str))) - -(defun lsp--handle-process-exit (workspace exit-str) - (let* ((folder->workspaces (lsp-session-folder->servers (lsp-session))) - (proc (lsp--workspace-proc workspace))) - (lsp--warn "%s has exited (%s)" - (lsp-process-name proc) - (string-trim-right (or exit-str ""))) - (with-lsp-workspace workspace - ;; Clean workspace related data in each of the buffers - ;; in the workspace. - (--each (lsp--workspace-buffers workspace) - (when (lsp-buffer-live-p it) - (lsp-with-current-buffer it - (setq lsp--buffer-workspaces (delete workspace lsp--buffer-workspaces)) - (lsp--uninitialize-workspace) - (lsp--spinner-stop) - (lsp--remove-overlays 'lsp-highlight)))) - - ;; Cleanup session from references to the closed workspace. - (--each (hash-table-keys folder->workspaces) - (lsp--update-key folder->workspaces it (apply-partially 'delete workspace))) - - (lsp-process-cleanup proc)) - - (run-hook-with-args 'lsp-after-uninitialized-functions workspace) - - (if (eq (lsp--workspace-shutdown-action workspace) 'shutdown) - (lsp--info "Workspace %s shutdown." (lsp--workspace-print workspace)) - (lsp--restart-if-needed workspace)) - (lsp--cleanup-hanging-watches))) - -(defun lsp-workspace-folders (workspace) - "Return all folders associated with WORKSPACE." - (let (result) - (->> (lsp-session) - (lsp-session-folder->servers) - (maphash (lambda (folder workspaces) - (when (-contains? workspaces workspace) - (push folder result))))) - result)) - -(defun lsp--start-workspace (session client-template root &optional initialization-options) - "Create new workspace for CLIENT-TEMPLATE with project root ROOT. -INITIALIZATION-OPTIONS are passed to initialize function. -SESSION is the active session." - (lsp--spinner-start) - (-let* ((default-directory root) - (client (copy-lsp--client client-template)) - (workspace (make-lsp--workspace - :root root - :client client - :status 'starting - :buffers (list (lsp-current-buffer)) - :host-root (file-remote-p root))) - ((&lsp-cln 'server-id 'environment-fn 'new-connection 'custom-capabilities - 'multi-root 'initialized-fn) client) - ((proc . cmd-proc) (funcall - (or (plist-get new-connection :connect) - (user-error "Client %s is configured incorrectly" client)) - (lsp--create-filter-function workspace) - (apply-partially #'lsp--process-sentinel workspace) - (format "%s" server-id) - environment-fn - workspace)) - (workspace-folders (gethash server-id (lsp-session-server-id->folders session)))) - (setf (lsp--workspace-proc workspace) proc - (lsp--workspace-cmd-proc workspace) cmd-proc) - - ;; update (lsp-session-folder->servers) depending on whether we are starting - ;; multi/single folder workspace - (mapc (lambda (project-root) - (->> session - (lsp-session-folder->servers) - (gethash project-root) - (cl-pushnew workspace))) - (or workspace-folders (list root))) - - (with-lsp-workspace workspace - (run-hooks 'lsp-before-initialize-hook) - (lsp-request-async - "initialize" - (append - (list :processId (unless (file-remote-p (buffer-file-name)) - (emacs-pid)) - :rootPath (lsp-file-local-name (expand-file-name root)) - :clientInfo (list :name "emacs" - :version (emacs-version)) - :rootUri (lsp--path-to-uri root) - :capabilities (lsp--client-capabilities custom-capabilities) - :initializationOptions initialization-options - :workDoneToken "1") - (when lsp-server-trace - (list :trace lsp-server-trace)) - (when multi-root - (->> workspace-folders - (-distinct) - (-map (lambda (folder) - (list :uri (lsp--path-to-uri folder) - :name (f-filename folder)))) - (apply 'vector) - (list :workspaceFolders)))) - (-lambda ((&InitializeResult :capabilities)) - ;; we know that Rust Analyzer will send {} which will be parsed as null - ;; when using plists - (when (equal 'rust-analyzer server-id) - (-> capabilities - (lsp:server-capabilities-text-document-sync?) - (lsp:set-text-document-sync-options-save? t))) - - (setf (lsp--workspace-server-capabilities workspace) capabilities - (lsp--workspace-status workspace) 'initialized) - - (with-lsp-workspace workspace - (lsp-notify "initialized" lsp--empty-ht)) - - (when initialized-fn (funcall initialized-fn workspace)) - - (cl-callf2 -filter #'lsp-buffer-live-p (lsp--workspace-buffers workspace)) - (->> workspace - (lsp--workspace-buffers) - (mapc (lambda (buffer) - (lsp-with-current-buffer buffer - (lsp--open-in-workspace workspace))))) - - (with-lsp-workspace workspace - (run-hooks 'lsp-after-initialize-hook)) - (lsp--info "%s initialized successfully in folders: %s" - (lsp--workspace-print workspace) - (lsp-workspace-folders workspace))) - :mode 'detached)) - workspace)) - -(defun lsp--load-default-session () - "Load default session." - (setq lsp--session (or (condition-case err - (lsp--read-from-file lsp-session-file) - (error (lsp--error "Failed to parse the session %s, starting with clean one." - (error-message-string err)) - nil)) - (make-lsp-session)))) - -(defun lsp-session () - "Get the session associated with the current buffer." - (or lsp--session (setq lsp--session (lsp--load-default-session)))) - -(defun lsp--client-disabled-p (buffer-major-mode client) - (seq-some - (lambda (entry) - (pcase entry - ((pred symbolp) (eq entry client)) - (`(,mode . ,client-or-list) - (and (eq mode buffer-major-mode) - (if (listp client-or-list) - (memq client client-or-list) - (eq client client-or-list)))))) - lsp-disabled-clients)) - - -;; download server - -(defcustom lsp-server-install-dir (expand-file-name - (locate-user-emacs-file (f-join ".cache" "lsp"))) - "Directory in which the servers will be installed." - :risky t - :type 'directory - :package-version '(lsp-mode . "6.3") - :group 'lsp-mode) - -(defcustom lsp-verify-signature t - "Whether to check GPG signatures of downloaded files." - :type 'boolean - :package-version '(lsp-mode . "8.0.0") - :group 'lsp-mode) - -(defvar lsp--dependencies (ht)) - -(defun lsp-dependency (name &rest definitions) - "Used to specify a language server DEPENDENCY, the server -executable or other required file path. Typically, the -DEPENDENCY is found by locating it on the system path using -`executable-find'. - -You can explicitly call lsp-dependency in your environment to -specify the absolute path to the DEPENDENCY. For example, the -typescript-language-server requires both the server and the -typescript compiler. If you have installed them in a team shared -read-only location, you can instruct lsp-mode to use them via - - (eval-after-load `lsp-mode - `(progn - (require lsp-javascript) - (lsp-dependency typescript-language-server (:system ,tls-exe)) - (lsp-dependency typescript (:system ,ts-js)))) - -where tls-exe is the absolute path to the typescript-language-server -executable and ts-js is the absolute path to the typescript compiler -JavaScript file, tsserver.js (the *.js is required for Windows)." - (ht-set lsp--dependencies name definitions)) - -(defun lsp--server-binary-present? (client) - (unless (equal (lsp--client-server-id client) 'lsp-pwsh) - (condition-case () - (-some-> client lsp--client-new-connection (plist-get :test?) funcall) - (error nil) - (args-out-of-range nil)))) - -(define-minor-mode lsp-installation-buffer-mode - "Mode used in *lsp-installation* buffers. -It can be used to set-up keybindings, etc. Disabling this mode -detaches the installation buffer from commands like -`lsp-select-installation-buffer'." - :init-value nil - :lighter nil) - -(defface lsp-installation-finished-buffer-face '((t :foreground "orange")) - "Face used for finished installation buffers. -Used in `lsp-select-installation-buffer'." - :group 'lsp-mode) - -(defface lsp-installation-buffer-face '((t :foreground "green")) - "Face used for installation buffers still in progress. -Used in `lsp-select-installation-buffer'." - :group 'lsp-mode) - -(defun lsp--installation-buffer? (buf) - "Check whether BUF is an `lsp-async-start-process' buffer." - (buffer-local-value 'lsp-installation-buffer-mode buf)) - -(defun lsp-select-installation-buffer (&optional show-finished) - "Interactively choose an installation buffer. -If SHOW-FINISHED is set, leftover (finished) installation buffers -are still shown." - (interactive "P") - (let ((bufs (--filter (and (lsp--installation-buffer? it) - (or show-finished (get-buffer-process it))) - (buffer-list)))) - (pcase bufs - (`nil (user-error "No installation buffers")) - (`(,buf) (pop-to-buffer buf)) - (bufs (pop-to-buffer (completing-read "Select installation buffer: " - (--map (propertize (buffer-name it) 'face - (if (get-buffer-process it) - 'lsp-installation-buffer-face - 'lsp-installation-finished-buffer-face)) - bufs))))))) - -(defun lsp-cleanup-installation-buffers () - "Delete finished *lsp-installation* buffers." - (interactive) - (dolist (buf (buffer-list)) - (when (and (lsp--installation-buffer? buf) (not (get-buffer-process buf))) - (kill-buffer buf)))) - -(defun lsp--download-status () - (-some--> #'lsp--client-download-in-progress? - (lsp--filter-clients it) - (-map (-compose #'symbol-name #'lsp--client-server-id) it) - (format "%s" it) - (propertize it 'face 'success) - (format " Installing following servers: %s" it) - (propertize it - 'local-map (make-mode-line-mouse-map - 'mouse-1 #'lsp-select-installation-buffer) - 'mouse-face 'highlight))) - -(defun lsp--install-server-internal (client &optional update?) - (unless (lsp--client-download-server-fn client) - (user-error "There is no automatic installation for `%s', you have to install it manually following lsp-mode's documentation." - (lsp--client-server-id client))) - - (setf (lsp--client-download-in-progress? client) t) - (add-to-list 'global-mode-string '(t (:eval (lsp--download-status)))) - (cl-flet ((done - (success? &optional error-message) - ;; run with idle timer to make sure the lsp command is executed in - ;; the main thread, see #2739. - (run-with-timer - 0.0 - nil - (lambda () - (-let [(&lsp-cln 'server-id 'buffers) client] - (setf (lsp--client-download-in-progress? client) nil - (lsp--client-buffers client) nil) - (if success? - (lsp--info "Server %s downloaded, auto-starting in %s buffers." server-id - (length buffers)) - (lsp--error "Server %s install process failed with the following error message: %s. -Check `*lsp-install*' and `*lsp-log*' buffer." - server-id - error-message)) - (seq-do - (lambda (buffer) - (when (lsp-buffer-live-p buffer) - (lsp-with-current-buffer buffer - (cl-callf2 -remove-item '(t (:eval (lsp--download-status))) - global-mode-string) - (when success? (lsp))))) - buffers) - (unless (lsp--filter-clients #'lsp--client-download-in-progress?) - (cl-callf2 -remove-item '(t (:eval (lsp--download-status))) - global-mode-string))))))) - (lsp--info "Download %s started." (lsp--client-server-id client)) - (condition-case err - (funcall - (lsp--client-download-server-fn client) - client - (lambda () (done t)) - (lambda (msg) (done nil msg)) - update?) - (error - (done nil (error-message-string err)))))) - -(defun lsp--require-packages () - "Load `lsp-client-packages' if needed." - (when (and lsp-auto-configure (not lsp--client-packages-required)) - (seq-do (lambda (package) - ;; loading client is slow and `lsp' can be called repeatedly - (unless (featurep package) - (require package nil t))) - lsp-client-packages) - (setq lsp--client-packages-required t))) - -;;;###autoload -(defun lsp-install-server (update? &optional server-id) - "Interactively install or re-install server. -When prefix UPDATE? is t force installation even if the server is present." - (interactive "P") - (lsp--require-packages) - (let* ((chosen-client (or (gethash server-id lsp-clients) - (lsp--completing-read - "Select server to install/re-install: " - (or (->> lsp-clients - (ht-values) - (-filter (-andfn - (-not #'lsp--client-download-in-progress?) - #'lsp--client-download-server-fn))) - (user-error "There are no servers with automatic installation")) - (lambda (client) - (let ((server-name (-> client lsp--client-server-id symbol-name))) - (if (lsp--server-binary-present? client) - (concat server-name " (Already installed)") - server-name))) - nil - t))) - (update? (or update? - (and (not (lsp--client-download-in-progress? chosen-client)) - (lsp--server-binary-present? chosen-client))))) - (lsp--install-server-internal chosen-client update?))) - -;;;###autoload -(defun lsp-uninstall-server (dir) - "Delete a LSP server from `lsp-server-install-dir'." - (interactive - (list (read-directory-name "Uninstall LSP server: " (f-slash lsp-server-install-dir)))) - (unless (file-directory-p dir) - (user-error "Couldn't find %s directory" dir)) - (delete-directory dir 'recursive) - (message "Server `%s' uninstalled." (file-name-nondirectory (directory-file-name dir)))) - -;;;###autoload -(defun lsp-uninstall-servers () - "Uninstall all installed servers." - (interactive) - (let* ((dir lsp-server-install-dir) - (servers (ignore-errors - (directory-files dir t - directory-files-no-dot-files-regexp)))) - (if (or (not (file-directory-p dir)) (zerop (length servers))) - (user-error "No servers to uninstall") - (when (yes-or-no-p - (format "Servers to uninstall: %d (%s), proceed? " - (length servers) - (mapconcat (lambda (server) - (file-name-nondirectory (directory-file-name server))) - servers " "))) - (mapc #'lsp-uninstall-server servers) - (message "All servers uninstalled"))))) - -;;;###autoload -(defun lsp-update-server (&optional server-id) - "Interactively update (reinstall) a server." - (interactive) - (lsp--require-packages) - (let ((chosen-client (or (gethash server-id lsp-clients) - (lsp--completing-read - "Select server to update (if not on the list, probably you need to `lsp-install-server`): " - (or (->> lsp-clients - (ht-values) - (-filter (-andfn - (-not #'lsp--client-download-in-progress?) - #'lsp--client-download-server-fn - #'lsp--server-binary-present?))) - (user-error "There are no servers to update")) - (lambda (client) - (-> client lsp--client-server-id symbol-name)) - nil - t)))) - (lsp--install-server-internal chosen-client t))) - -;;;###autoload -(defun lsp-update-servers () - "Update (reinstall) all installed servers." - (interactive) - (lsp--require-packages) - (mapc (lambda (client) (lsp--install-server-internal client t)) - (-filter (-andfn - (-not #'lsp--client-download-in-progress?) - #'lsp--client-download-server-fn - #'lsp--server-binary-present?) (hash-table-values lsp-clients)))) - -;;;###autoload -(defun lsp-ensure-server (server-id) - "Ensure server SERVER-ID" - (lsp--require-packages) - (if-let ((client (gethash server-id lsp-clients))) - (unless (lsp--server-binary-present? client) - (lsp--info "Server `%s' is not preset, installing..." server-id) - (lsp-install-server nil server-id)) - (warn "Unable to find server registration with id %s" server-id))) - -(defun lsp-async-start-process (callback error-callback &rest command) - "Start async process COMMAND with CALLBACK and ERROR-CALLBACK." - (let ((name (cl-first command))) - (with-current-buffer (compilation-start (mapconcat #'shell-quote-argument (-filter (lambda (cmd) - (not (null cmd))) - command) - " ") t - (lambda (&rest _) - (generate-new-buffer-name (format "*lsp-install: %s*" name)))) - (lsp-installation-buffer-mode +1) - (view-mode +1) - (add-hook - 'compilation-finish-functions - (lambda (_buf status) - (if (string= "finished\n" status) - (condition-case err - (funcall callback) - (error - (funcall error-callback (error-message-string err)))) - (funcall error-callback (s-trim-right status)))) - nil t)))) - -(defun lsp-resolve-value (value) - "Resolve VALUE's value. -If it is function - call it. -If it is a variable - return it's value -Otherwise returns value itself." - (cond - ((functionp value) (funcall value)) - ((and (symbolp value) (boundp value)) (symbol-value value)) - (value))) - -(defvar lsp-deps-providers - (list :npm (list :path #'lsp--npm-dependency-path - :install #'lsp--npm-dependency-install) - :cargo (list :path #'lsp--cargo-dependency-path - :install #'lsp--cargo-dependency-install) - :system (list :path #'lsp--system-path) - :download (list :path #'lsp-download-path - :install #'lsp-download-install))) - -(defun lsp--system-path (path) - "If PATH is absolute and exists return it as is. Otherwise, -return the absolute path to the executable defined by PATH or -nil." - ;; For node.js 'sub-packages' PATH may point to a *.js file. Consider the - ;; typescript-language-server. When lsp invokes the server, lsp needs to - ;; supply the path to the typescript compiler, tsserver.js, as an argument. To - ;; make code platform independent, one must pass the absolute path to the - ;; tsserver.js file (Windows requires a *.js file - see help on the JavaScript - ;; child process spawn command that is invoked by the - ;; typescript-language-server). This is why we check for existence and not - ;; that the path is executable. - (let ((path (lsp-resolve-value path))) - (cond - ((and (f-absolute? path) - (f-exists? path)) - path) - ((executable-find path t) path)))) - -(defun lsp-package-path (dependency) - "Path to the DEPENDENCY each of the registered providers." - (let (path) - (-first (-lambda ((provider . rest)) - (setq path (-some-> lsp-deps-providers - (plist-get provider) - (plist-get :path) - (apply rest)))) - (gethash dependency lsp--dependencies)) - path)) - -(defun lsp-package-ensure (dependency callback error-callback) - "Asynchronously ensure a package." - (or (-first (-lambda ((provider . rest)) - (-some-> lsp-deps-providers - (plist-get provider) - (plist-get :install) - (apply (cl-list* callback error-callback rest)))) - (gethash dependency lsp--dependencies)) - (funcall error-callback (format "Unable to find a way to install %s" dependency)))) - - -;; npm handling - -;; https://docs.npmjs.com/files/folders#executables -(cl-defun lsp--npm-dependency-path (&key package path &allow-other-keys) - "Return npm dependency PATH for PACKAGE." - (let ((path (executable-find - (f-join lsp-server-install-dir "npm" package - (cond ((eq system-type 'windows-nt) "") - (t "bin")) - path) - t))) - (unless (and path (f-exists? path)) - (error "The package %s is not installed. Unable to find %s" package path)) - path)) - -(cl-defun lsp--npm-dependency-install (callback error-callback &key package &allow-other-keys) - (if-let ((npm-binary (executable-find "npm"))) - (progn - ;; Explicitly `make-directory' to work around NPM bug in - ;; versions 7.0.0 through 7.4.1. See - ;; https://github.com/emacs-lsp/lsp-mode/issues/2364 for - ;; discussion. - (make-directory (f-join lsp-server-install-dir "npm" package "lib") 'parents) - (lsp-async-start-process (lambda () - (if (string-empty-p - (string-trim (shell-command-to-string - (mapconcat #'shell-quote-argument `(,npm-binary "view" ,package "peerDependencies") " ")))) - (funcall callback) - (let ((default-directory (f-dirname (car (last (directory-files-recursively (f-join lsp-server-install-dir "npm" package) "package.json"))))) - (process-environment (append '("npm_config_yes=true") process-environment))) ;; Disable prompting for older versions of npx - (when (f-dir-p default-directory) - (lsp-async-start-process callback - error-callback - (executable-find "npx") - "npm-install-peers"))))) - error-callback - npm-binary - "-g" - "--prefix" - (f-join lsp-server-install-dir "npm" package) - "install" - package)) - (lsp-log "Unable to install %s via `npm' because it is not present" package) - nil)) - - -;; Cargo dependency handling -(cl-defun lsp--cargo-dependency-path (&key package path &allow-other-keys) - (let ((path (executable-find - (f-join lsp-server-install-dir - "cargo" - package - "bin" - path) - t))) - (unless (and path (f-exists? path)) - (error "The package %s is not installed. Unable to find %s" package path)) - path)) - -(cl-defun lsp--cargo-dependency-install (callback error-callback &key package git &allow-other-keys) - (if-let ((cargo-binary (executable-find "cargo"))) - (lsp-async-start-process - callback - error-callback - cargo-binary - "install" - package - (when git - "--git") - git - "--root" - (f-join lsp-server-install-dir "cargo" package)) - (lsp-log "Unable to install %s via `cargo' because it is not present" package) - nil)) - - - -;; Download URL handling -(cl-defun lsp-download-install (callback error-callback &key url asc-url pgp-key store-path decompress &allow-other-keys) - (let* ((url (lsp-resolve-value url)) - (store-path (lsp-resolve-value store-path)) - ;; (decompress (lsp-resolve-value decompress)) - (download-path - (pcase decompress - (:gzip (concat store-path ".gz")) - (:zip (concat store-path ".zip")) - (:targz (concat store-path ".tar.gz")) - (`nil store-path) - (_ (error ":decompress must be `:gzip', `:zip', `:targz' or `nil'"))))) - (make-thread - (lambda () - (condition-case err - (progn - (when (f-exists? download-path) - (f-delete download-path)) - (when (f-exists? store-path) - (f-delete store-path)) - (lsp--info "Starting to download %s to %s..." url download-path) - (mkdir (f-parent download-path) t) - (url-copy-file url download-path) - (lsp--info "Finished downloading %s..." download-path) - (when (and lsp-verify-signature asc-url pgp-key) - (if (executable-find epg-gpg-program) - (let ((asc-download-path (concat download-path ".asc")) - (context (epg-make-context)) - (fingerprint) - (signature)) - (when (f-exists? asc-download-path) - (f-delete asc-download-path)) - (lsp--info "Starting to download %s to %s..." asc-url asc-download-path) - (url-copy-file asc-url asc-download-path) - (lsp--info "Finished downloading %s..." asc-download-path) - (epg-import-keys-from-string context pgp-key) - (setq fingerprint (epg-import-status-fingerprint - (car - (epg-import-result-imports - (epg-context-result-for context 'import))))) - (lsp--info "Verifying signature %s..." asc-download-path) - (epg-verify-file context asc-download-path download-path) - (setq signature (car (epg-context-result-for context 'verify))) - (unless (and - (eq (epg-signature-status signature) 'good) - (equal (epg-signature-fingerprint signature) fingerprint)) - (error "Failed to verify GPG signature: %s" (epg-signature-to-string signature)))) - (lsp--warn "GPG is not installed, skipping the signature check."))) - (when decompress - (lsp--info "Decompressing %s..." download-path) - (pcase decompress - (:gzip - (lsp-gunzip download-path)) - (:zip (lsp-unzip download-path (f-parent store-path))) - (:targz (lsp-tar-gz-decompress download-path (f-parent store-path)))) - (lsp--info "Decompressed %s..." store-path)) - (funcall callback)) - (error (funcall error-callback err))))))) - -(cl-defun lsp-download-path (&key store-path binary-path set-executable? &allow-other-keys) - "Download URL and store it into STORE-PATH. - -SET-EXECUTABLE? when non-nil change the executable flags of -STORE-PATH to make it executable. BINARY-PATH can be specified -when the binary to start does not match the name of the -archive (e.g. when the archive has multiple files)" - (let ((store-path (or (lsp-resolve-value binary-path) - (lsp-resolve-value store-path)))) - (cond - ((executable-find store-path) store-path) - ((and set-executable? (f-exists? store-path)) - (set-file-modes store-path #o0700) - store-path) - ((f-exists? store-path) store-path)))) - -(defun lsp--find-latest-gh-release-url (url regex) - "Fetch the latest version in the releases given by URL by using REGEX." - (let ((url-request-method "GET")) - (with-current-buffer (url-retrieve-synchronously url) - (goto-char (point-min)) - (re-search-forward "\n\n" nil 'noerror) - (delete-region (point-min) (point)) - (let* ((json-result (lsp-json-read-buffer))) - (message "Latest version found: %s" (lsp-get json-result :tag_name)) - (--> json-result - (lsp-get it :assets) - (seq-find (lambda (entry) (string-match-p regex (lsp-get entry :name))) it) - (lsp-get it :browser_download_url)))))) - -;; unzip - -(defconst lsp-ext-pwsh-script "powershell -noprofile -noninteractive \ --nologo -ex bypass -command Expand-Archive -path '%s' -dest '%s'" - "Powershell script to unzip file.") - -(defconst lsp-ext-unzip-script "bash -c 'mkdir -p %2$s && unzip -qq -o %1$s -d %2$s'" - "Unzip script to unzip file.") - -(defcustom lsp-unzip-script (lambda () - (cond ((and (eq system-type 'windows-nt) - (executable-find "powershell")) - lsp-ext-pwsh-script) - ((executable-find "unzip") lsp-ext-unzip-script) - ((executable-find "powershell") lsp-ext-pwsh-script) - (t nil))) - "The script to unzip." - :group 'lsp-mode - :type 'string - :package-version '(lsp-mode . "8.0.0")) - -(defun lsp-unzip (zip-file dest) - "Unzip ZIP-FILE to DEST." - (unless lsp-unzip-script - (error "Unable to find `unzip' or `powershell' on the path, please customize `lsp-unzip-script'")) - (shell-command (format (lsp-resolve-value lsp-unzip-script) zip-file dest))) - -;; gunzip - -(defconst lsp-ext-gunzip-script "gzip -d %1$s" - "Script to decompress a gzippped file with gzip.") - -(defcustom lsp-gunzip-script (lambda () - (cond ((executable-find "gzip") lsp-ext-gunzip-script) - (t nil))) - "The script to decompress a gzipped file. -Should be a format string with one argument for the file to be decompressed -in place." - :group 'lsp-mode - :type 'string - :package-version '(lsp-mode . "8.0.0")) - -(defun lsp-gunzip (gz-file) - "Decompress GZ-FILE in place." - (unless lsp-gunzip-script - (error "Unable to find `gzip' on the path, please either customize `lsp-gunzip-script' or manually decompress %s" gz-file)) - (shell-command (format (lsp-resolve-value lsp-gunzip-script) gz-file))) - -;; tar.gz decompression - -(defconst lsp-ext-tar-script "bash -c 'mkdir -p %2$s; tar xf %1$s --directory=%2$s'" - "Script to decompress a .tar.gz file.") - -(defcustom lsp-tar-script (lambda () - (cond ((executable-find "tar") lsp-ext-tar-script) - (t nil))) - "The script to decompress a .tar.gz file. -Should be a format string with one argument for the file to be decompressed -in place." - :group 'lsp-mode - :type 'string) - -(defun lsp-tar-gz-decompress (targz-file dest) - "Decompress TARGZ-FILE in DEST." - (unless lsp-tar-script - (error "Unable to find `tar' on the path, please either customize `lsp-tar-script' or manually decompress %s" targz-file)) - (shell-command (format (lsp-resolve-value lsp-tar-script) targz-file dest))) - - -;; VSCode marketplace - -(defcustom lsp-vscode-ext-url - "https://marketplace.visualstudio.com/_apis/public/gallery/publishers/%s/vsextensions/%s/%s/vspackage%s" - "Vscode extension template url." - :group 'lsp-mode - :type 'string - :package-version '(lsp-mode . "8.0.0")) - -(defun lsp-vscode-extension-url (publisher name version &optional targetPlatform) - "Return the URL to vscode extension. -PUBLISHER is the extension publisher. -NAME is the name of the extension. -VERSION is the version of the extension. -TARGETPLATFORM is the targetPlatform of the extension." - (format lsp-vscode-ext-url publisher name version (or targetPlatform ""))) - - - -;; Queueing prompts - -(defvar lsp--question-queue nil - "List of questions yet to be asked by `lsp-ask-question'.") - -(defun lsp-ask-question (question options callback) - "Prompt the user to answer the QUESTION with one of the OPTIONS from the -minibuffer. Once the user selects an option, the CALLBACK function will be -called, passing the selected option to it. - -If the user is currently being shown a question, the question will be stored in -`lsp--question-queue', and will be asked once the user has answered the current -question." - (add-to-list 'lsp--question-queue `(("question" . ,question) - ("options" . ,options) - ("callback" . ,callback)) t) - (when (eq (length lsp--question-queue) 1) - (lsp--process-question-queue))) - -(defun lsp--process-question-queue () - "Take the first question from `lsp--question-queue', process it, then process -the next question until the queue is empty." - (-let* (((&alist "question" "options" "callback") (car lsp--question-queue)) - (answer (completing-read question options nil t))) - (pop lsp--question-queue) - (funcall callback answer) - (when lsp--question-queue - (lsp--process-question-queue)))) - -(defun lsp--supports-buffer? (client) - (and - ;; both file and client remote or both local - (eq (---truthy? (file-remote-p (buffer-file-name))) - (---truthy? (lsp--client-remote? client))) - - ;; activation function or major-mode match. - (if-let ((activation-fn (lsp--client-activation-fn client))) - (funcall activation-fn (buffer-file-name) major-mode) - (-contains? (lsp--client-major-modes client) major-mode)) - - ;; check whether it is enabled if `lsp-enabled-clients' is not null - (or (null lsp-enabled-clients) - (or (member (lsp--client-server-id client) lsp-enabled-clients) - (ignore (lsp--info "Client %s is not in lsp-enabled-clients" - (lsp--client-server-id client))))) - - ;; check whether it is not disabled. - (not (lsp--client-disabled-p major-mode (lsp--client-server-id client))))) - -(defun lsp--filter-clients (pred) - (->> lsp-clients hash-table-values (-filter pred))) - -(defun lsp--find-clients () - "Find clients which can handle current buffer." - (-when-let (matching-clients (lsp--filter-clients (-andfn #'lsp--supports-buffer? - #'lsp--server-binary-present?))) - (lsp-log "Found the following clients for %s: %s" - (buffer-file-name) - (s-join ", " - (-map (lambda (client) - (format "(server-id %s, priority %s)" - (lsp--client-server-id client) - (lsp--client-priority client))) - matching-clients))) - (-let* (((add-on-clients main-clients) (-separate #'lsp--client-add-on? matching-clients)) - (selected-clients (if-let ((main-client (and main-clients - (--max-by (> (lsp--client-priority it) - (lsp--client-priority other)) - main-clients)))) - (cons main-client add-on-clients) - add-on-clients))) - (lsp-log "The following clients were selected based on priority: %s" - (s-join ", " - (-map (lambda (client) - (format "(server-id %s, priority %s)" - (lsp--client-server-id client) - (lsp--client-priority client))) - selected-clients))) - selected-clients))) - -(defun lsp-workspace-remove-all-folders() - "Delete all lsp tracked folders." - (interactive) - (--each (lsp-session-folders (lsp-session)) - (lsp-workspace-folders-remove it))) - -(defun lsp-register-client (client) - "Registers LSP client CLIENT." - (let ((client-id (lsp--client-server-id client))) - (puthash client-id client lsp-clients) - (setplist (intern (format "lsp-%s-after-open-hook" client-id)) - `( standard-value (nil) custom-type hook - custom-package-version (lsp-mode . "7.0.1") - variable-documentation ,(format "Hooks to run after `%s' server is run." client-id) - custom-requests nil))) - (when (and lsp-auto-register-remote-clients - (not (lsp--client-remote? client))) - (let ((remote-client (copy-lsp--client client))) - (setf (lsp--client-remote? remote-client) t - (lsp--client-server-id remote-client) (intern - (format "%s-tramp" - (lsp--client-server-id client))) - ;; disable automatic download - (lsp--client-download-server-fn remote-client) nil) - (lsp-register-client remote-client)))) - -(defun lsp--create-initialization-options (_session client) - "Create initialization-options from SESSION and CLIENT. -Add workspace folders depending on server being multiroot and -session workspace folder configuration for the server." - (let* ((initialization-options-or-fn (lsp--client-initialization-options client))) - (if (functionp initialization-options-or-fn) - (funcall initialization-options-or-fn) - initialization-options-or-fn))) - -(defvar lsp-client-settings (make-hash-table :test 'equal) - "For internal use, any external users please use - `lsp-register-custom-settings' function instead") - -(defun lsp-register-custom-settings (props) - "Register PROPS. -PROPS is list of triple (path value boolean?) where PATH is the path to the -property; VALUE can be a literal value, symbol to be evaluated, or either a -function or lambda function to be called without arguments; BOOLEAN? is an -optional flag that should be non-nil for boolean settings, when it is nil the -property will be ignored if the VALUE is nil. - -Example: `(lsp-register-custom-settings `((\"foo.bar.buzz.enabled\" t t)))' -\(note the double parentheses)" - (mapc - (-lambda ((path . rest)) - (puthash path rest lsp-client-settings)) - props)) - -(defun lsp-region-text (region) - "Get the text for REGION in current buffer." - (-let (((start . end) (lsp--range-to-region region))) - (buffer-substring-no-properties start end))) - -(defun lsp-ht-set (tbl paths value) - "Set nested hash table value. -TBL - a hash table, PATHS is the path to the nested VALUE." - (pcase paths - (`(,path) (ht-set! tbl path value)) - (`(,path . ,rst) (let ((nested-tbl (or (gethash path tbl) - (let ((temp-tbl (ht))) - (ht-set! tbl path temp-tbl) - temp-tbl)))) - (lsp-ht-set nested-tbl rst value))))) - -;; sections - -(defalias 'defcustom-lsp 'lsp-defcustom) - -(defmacro lsp-defcustom (symbol standard doc &rest args) - "Defines `lsp-mode' server property." - (declare (doc-string 3) (debug (name body)) - (indent defun)) - (let ((path (plist-get args :lsp-path)) - (setter (intern (concat (symbol-name symbol) "--set")))) - (cl-remf args :lsp-path) - `(progn - (lsp-register-custom-settings - (quote ((,path ,symbol ,(equal ''boolean (plist-get args :type)))))) - - (defcustom ,symbol ,standard ,doc ,@args) - - ;; Use a variable watcher instead of registering a `defcustom' - ;; setter since `hack-local-variables' is not aware of custom - ;; setters and won't invoke them. - - (defun ,setter (sym val op _where) - (when (eq op 'set) - (lsp--set-custom-property sym val ,path))) - - (add-variable-watcher ',symbol #',setter)))) - -(defun lsp--set-custom-property (sym val path) - (set sym val) - (let ((section (cl-first (s-split "\\." path)))) - (mapc (lambda (workspace) - (when (-contains? (lsp--client-synchronize-sections (lsp--workspace-client workspace)) - section) - (with-lsp-workspace workspace - (lsp--set-configuration (lsp-configuration-section section))))) - (lsp--session-workspaces (lsp-session))))) - -(defun lsp-configuration-section (section) - "Get settings for SECTION." - (let ((ret (ht-create))) - (maphash (-lambda (path (variable boolean?)) - (when (s-matches? (concat (regexp-quote section) "\\..*") path) - (let* ((symbol-value (-> variable - lsp-resolve-value - lsp-resolve-value)) - (value (if (and boolean? (not symbol-value)) - :json-false - symbol-value))) - (when (or boolean? value) - (lsp-ht-set ret (s-split "\\." path) value))))) - lsp-client-settings) - ret)) - - -(defun lsp--start-connection (session client project-root) - "Initiates connection created from CLIENT for PROJECT-ROOT. -SESSION is the active session." - (when (lsp--client-multi-root client) - (cl-pushnew project-root (gethash (lsp--client-server-id client) - (lsp-session-server-id->folders session)))) - (run-hook-with-args 'lsp-workspace-folders-changed-functions (list project-root) nil) - - (unwind-protect - (lsp--start-workspace session client project-root (lsp--create-initialization-options session client)) - (lsp--spinner-stop))) - -;; lsp-log-io-mode - -(defvar lsp-log-io-mode-map - (let ((map (make-sparse-keymap))) - (define-key map (kbd "M-n") #'lsp-log-io-next) - (define-key map (kbd "M-p") #'lsp-log-io-prev) - (define-key map (kbd "k") #'lsp--erase-log-buffer) - (define-key map (kbd "K") #'lsp--erase-session-log-buffers) - map) - "Keymap for lsp log buffer mode.") - -(define-derived-mode lsp-log-io-mode special-mode "LspLogIo" - "Special mode for viewing IO logs.") - -(defun lsp-workspace-show-log (workspace) - "Display the log buffer of WORKSPACE." - (interactive - (list (if lsp-log-io - (if (eq (length (lsp-workspaces)) 1) - (cl-first (lsp-workspaces)) - (lsp--completing-read "Workspace: " (lsp-workspaces) - #'lsp--workspace-print nil t)) - (user-error "IO logging is disabled")))) - (pop-to-buffer (lsp--get-log-buffer-create workspace))) - -(defalias 'lsp-switch-to-io-log-buffer 'lsp-workspace-show-log) - -(defun lsp--get-log-buffer-create (workspace) - "Return the lsp log buffer of WORKSPACE, creating a new one if needed." - (let* ((server-id (-> workspace lsp--workspace-client lsp--client-server-id symbol-name)) - (pid (-> workspace lsp--workspace-cmd-proc lsp-process-id))) - (get-buffer-create (format "*lsp-log: %s:%s*" server-id pid)))) - -(defun lsp--erase-log-buffer (&optional all) - "Delete contents of current lsp log buffer. -When ALL is t, erase all log buffers of the running session." - (interactive) - (let* ((workspaces (lsp--session-workspaces (lsp-session))) - (current-log-buffer (current-buffer))) - (dolist (w workspaces) - (let ((b (lsp--get-log-buffer-create w))) - (when (or all (eq b current-log-buffer)) - (with-current-buffer b - (let ((inhibit-read-only t)) - (erase-buffer)))))))) - -(defun lsp--erase-session-log-buffers () - "Erase log buffers of the running session." - (interactive) - (lsp--erase-log-buffer t)) - -(defun lsp-log-io-next (arg) - "Move to next log entry." - (interactive "P") - (ewoc-goto-next lsp--log-io-ewoc (or arg 1))) - -(defun lsp-log-io-prev (arg) - "Move to previous log entry." - (interactive "P") - (ewoc-goto-prev lsp--log-io-ewoc (or arg 1))) - - - -(cl-defmethod lsp-process-id ((process process)) - (process-id process)) - -(cl-defmethod lsp-process-name ((process process)) (process-name process)) - -(cl-defmethod lsp-process-status ((process process)) (process-status process)) - -(cl-defmethod lsp-process-kill ((process process)) - (when (process-live-p process) - (kill-process process))) - -(cl-defmethod lsp-process-send ((process process) message) - (condition-case err - (process-send-string process (lsp--make-message message)) - (error (lsp--error "Sending to process failed with the following error: %s" - (error-message-string err))))) - -(cl-defmethod lsp-process-cleanup (process) - ;; Kill standard error buffer only if the process exited normally. - ;; Leave it intact otherwise for debugging purposes. - (let ((buffer (-> process process-name get-buffer))) - (when (and (eq (process-status process) 'exit) - (zerop (process-exit-status process)) - (buffer-live-p buffer)) - (kill-buffer buffer)))) - - -;; native JSONRPC - -(declare-function json-rpc "ext:json") -(declare-function json-rpc-connection "ext:json") -(declare-function json-rpc-send "ext:json") -(declare-function json-rpc-shutdown "ext:json") -(declare-function json-rpc-stderr "ext:json") -(declare-function json-rpc-pid "ext:json") - -(defvar lsp-json-rpc-thread nil) -(defvar lsp-json-rpc-queue nil) -(defvar lsp-json-rpc-done nil) -(defvar lsp-json-rpc-mutex (make-mutex)) -(defvar lsp-json-rpc-condition (make-condition-variable lsp-json-rpc-mutex)) - -(defun lsp-json-rpc-process-queue () - (while (not lsp-json-rpc-done) - (while lsp-json-rpc-queue - (-let (((proc . message) (pop lsp-json-rpc-queue))) - (json-rpc-send - proc message - :null-object nil - :false-object :json-false))) - (with-mutex lsp-json-rpc-mutex - (condition-wait lsp-json-rpc-condition)))) - -(cl-defmethod lsp-process-id (process) (json-rpc-pid process)) - -(cl-defmethod lsp-process-name (_process) "TBD") - -(cl-defmethod lsp-process-kill (process) (json-rpc-shutdown process)) - -(cl-defmethod lsp-process-send (proc message) - (unless lsp-json-rpc-thread - (with-current-buffer (get-buffer-create " *json-rpc*") - (setq lsp-json-rpc-thread (make-thread #'lsp-json-rpc-process-queue "*json-rpc-queue*")))) - - (with-mutex lsp-json-rpc-mutex - (setq lsp-json-rpc-queue (append lsp-json-rpc-queue - (list (cons proc message)))) - (condition-notify lsp-json-rpc-condition))) - -(cl-defmethod lsp-process-cleanup (_proc)) - -(defun lsp-json-rpc-connection (workspace command) - (let ((con (apply #'json-rpc-connection command)) - (object-type (if lsp-use-plists 'plist 'hash-table))) - (with-current-buffer (get-buffer-create " *json-rpc*") - (make-thread - (lambda () - (json-rpc - con - (lambda (result err done) - (run-with-timer - 0.0 - nil - (lambda () - (cond - (result (lsp--parser-on-message result workspace)) - (err (warn "Json parsing failed with the following error: %s" err)) - (done (lsp--handle-process-exit workspace "")))))) - :object-type object-type - :null-object nil - :false-object nil)) - "*json-rpc-connection*")) - (cons con con))) - -(defun lsp-json-rpc-stderr () - (interactive) - (--when-let (pcase (lsp-workspaces) - (`nil (user-error "There are no active servers in the current buffer")) - (`(,workspace) workspace) - (workspaces (lsp--completing-read "Select server: " - workspaces - 'lsp--workspace-print nil t))) - (let ((content (json-rpc-stderr (lsp--workspace-cmd-proc it))) - (buffer (format "*stderr-%s*" (lsp--workspace-print it)) )) - (with-current-buffer (get-buffer-create buffer) - (with-help-window buffer - (insert content)))))) - - -(defun lsp--workspace-print (workspace) - "Visual representation WORKSPACE." - (let* ((proc (lsp--workspace-cmd-proc workspace)) - (status (lsp--workspace-status workspace)) - (server-id (-> workspace lsp--workspace-client lsp--client-server-id symbol-name)) - (pid (lsp-process-id proc))) - - (if (eq 'initialized status) - (format "%s:%s" server-id pid) - (format "%s:%s/%s" server-id pid status)))) - -(defun lsp--map-tree-widget (m) - "Build `tree-widget' from a hash-table or plist M." - (when (lsp-structure-p m) - (let (nodes) - (lsp-map (lambda (k v) - (push `(tree-widget - :tag ,(if (lsp-structure-p v) - (format "%s:" k) - (format "%s: %s" k - (propertize (format "%s" v) - 'face - 'font-lock-string-face))) - :open t - ,@(lsp--map-tree-widget v)) - nodes)) - m) - nodes))) - -(defun lsp-buffer-name (buffer-id) - (if-let ((buffer-name (plist-get buffer-id :buffer-name))) - (funcall buffer-name buffer-id) - (buffer-name buffer-id))) - -(defun lsp--render-workspace (workspace) - "Tree node representation of WORKSPACE." - `(tree-widget :tag ,(lsp--workspace-print workspace) - :open t - (tree-widget :tag ,(propertize "Buffers" 'face 'font-lock-function-name-face) - :open t - ,@(->> workspace - (lsp--workspace-buffers) - (--map `(tree-widget - :tag ,(when (lsp-buffer-live-p it) - (let ((buffer-name (lsp-buffer-name it))) - (if (lsp-with-current-buffer it buffer-read-only) - (propertize buffer-name 'face 'font-lock-constant-face) - buffer-name))))))) - (tree-widget :tag ,(propertize "Capabilities" 'face 'font-lock-function-name-face) - ,@(-> workspace lsp--workspace-server-capabilities lsp--map-tree-widget)))) - -(define-derived-mode lsp-browser-mode special-mode "LspBrowser" - "Define mode for displaying lsp sessions." - (setq-local display-buffer-base-action '(nil . ((inhibit-same-window . t))))) - -(defun lsp-describe-session () - "Describes current `lsp-session'." - (interactive) - (let ((session (lsp-session)) - (buf (get-buffer-create "*lsp session*")) - (root (lsp-workspace-root))) - (with-current-buffer buf - (lsp-browser-mode) - (let ((inhibit-read-only t)) - (erase-buffer) - (--each (lsp-session-folders session) - (widget-create - `(tree-widget - :tag ,(propertize it 'face 'font-lock-keyword-face) - :open t - ,@(->> session - (lsp-session-folder->servers) - (gethash it) - (-map 'lsp--render-workspace))))))) - (pop-to-buffer buf) - (goto-char (point-min)) - (cl-loop for tag = (widget-get (widget-get (widget-at) :node) :tag) - until (or (and root (string= tag root)) (eobp)) - do (goto-char (next-overlay-change (point)))))) - -(defun lsp--session-workspaces (session) - "Get all workspaces that are part of the SESSION." - (-> session lsp-session-folder->servers hash-table-values -flatten -uniq)) - -(defun lsp--find-multiroot-workspace (session client project-root) - "Look for a multiroot connection in SESSION created from CLIENT for -PROJECT-ROOT and BUFFER-MAJOR-MODE." - (when (lsp--client-multi-root client) - (-when-let (multi-root-workspace (->> session - (lsp--session-workspaces) - (--first (eq (-> it lsp--workspace-client lsp--client-server-id) - (lsp--client-server-id client))))) - (with-lsp-workspace multi-root-workspace - (lsp-notify "workspace/didChangeWorkspaceFolders" - (lsp-make-did-change-workspace-folders-params - :event (lsp-make-workspace-folders-change-event - :added (vector (lsp-make-workspace-folder - :uri (lsp--path-to-uri project-root) - :name (f-filename project-root))) - :removed [])))) - - (->> session (lsp-session-folder->servers) (gethash project-root) (cl-pushnew multi-root-workspace)) - (->> session (lsp-session-server-id->folders) (gethash (lsp--client-server-id client)) (cl-pushnew project-root)) - - (lsp--persist-session session) - - (lsp--info "Opened folder %s in workspace %s" project-root (lsp--workspace-print multi-root-workspace)) - (lsp--open-in-workspace multi-root-workspace) - - multi-root-workspace))) - -(defun lsp--ensure-lsp-servers (session clients project-root ignore-multi-folder) - "Ensure that SESSION contain server CLIENTS created for PROJECT-ROOT. -IGNORE-MULTI-FOLDER to ignore multi folder server." - (-map (lambda (client) - (or - (lsp--find-workspace session client project-root) - (unless ignore-multi-folder - (lsp--find-multiroot-workspace session client project-root)) - (lsp--start-connection session client project-root))) - clients)) - -(defun lsp--spinner-stop () - "Stop the spinner in case all of the workspaces are started." - (when (--all? (eq (lsp--workspace-status it) 'initialized) - lsp--buffer-workspaces) - (spinner-stop))) - -(defun lsp--open-in-workspace (workspace) - "Open in existing WORKSPACE." - (if (eq 'initialized (lsp--workspace-status workspace)) - ;; when workspace is initialized just call document did open. - (progn - (with-lsp-workspace workspace - (when-let ((before-document-open-fn (-> workspace - lsp--workspace-client - lsp--client-before-file-open-fn))) - (funcall before-document-open-fn workspace)) - (lsp--text-document-did-open)) - (lsp--spinner-stop)) - ;; when it is not initialized - (lsp--spinner-start) - (cl-pushnew (lsp-current-buffer) (lsp--workspace-buffers workspace)))) - -(defun lsp--find-workspace (session client project-root) - "Find server connection created with CLIENT in SESSION for PROJECT-ROOT." - (when-let ((workspace (->> session - (lsp-session-folder->servers) - (gethash project-root) - (--first (eql (-> it lsp--workspace-client lsp--client-server-id) - (lsp--client-server-id client)))))) - (lsp--open-in-workspace workspace) - workspace)) - -(defun lsp--read-char (prompt &optional options) - "Wrapper for `read-char-from-minibuffer' if Emacs +27. -Fallback to `read-key' otherwise. -PROMPT is the message and OPTIONS the available options." - (if (fboundp 'read-char-from-minibuffer) - (read-char-from-minibuffer prompt options) - (read-key prompt))) - -(defun lsp--find-root-interactively (session) - "Find project interactively. -Returns nil if the project should not be added to the current SESSION." - (condition-case nil - (let* ((project-root-suggestion (or (lsp--suggest-project-root) default-directory)) - (action (lsp--read-char - (format - "%s is not part of any project. - -%s ==> Import project root %s -%s ==> Import project by selecting root directory interactively -%s ==> Import project at current directory %s -%s ==> Do not ask again for the current project by adding %s to lsp-session-folders-blocklist -%s ==> Do not ask again for the current project by selecting ignore path interactively -%s ==> Do nothing: ask again when opening other files from the current project - -Select action: " - (propertize (buffer-name) 'face 'bold) - (propertize "i" 'face 'success) - (propertize project-root-suggestion 'face 'bold) - (propertize "I" 'face 'success) - (propertize "." 'face 'success) - (propertize default-directory 'face 'bold) - (propertize "d" 'face 'warning) - (propertize project-root-suggestion 'face 'bold) - (propertize "D" 'face 'warning) - (propertize "n" 'face 'warning)) - '(?i ?\r ?I ?. ?d ?D ?n)))) - (cl-case action - (?i project-root-suggestion) - (?\r project-root-suggestion) - (?I (read-directory-name "Select workspace folder to add: " - (or project-root-suggestion default-directory) - nil - t)) - (?. default-directory) - (?d (push project-root-suggestion (lsp-session-folders-blocklist session)) - (lsp--persist-session session) - nil) - (?D (push (read-directory-name "Select folder to blocklist: " - (or project-root-suggestion default-directory) - nil - t) - (lsp-session-folders-blocklist session)) - (lsp--persist-session session) - nil) - (t nil))) - (quit))) - -(declare-function tramp-file-name-host "ext:tramp" (file) t) -(declare-function tramp-dissect-file-name "ext:tramp" (file &optional nodefault)) - -(defun lsp--files-same-host (f1 f2) - "Predicate on whether or not two files are on the same host." - (or (not (or (file-remote-p f1) (file-remote-p f2))) - (and (file-remote-p f1) - (file-remote-p f2) - (progn (require 'tramp) - (equal (tramp-file-name-host (tramp-dissect-file-name f1)) - (tramp-file-name-host (tramp-dissect-file-name f2))))))) - -(defun lsp-find-session-folder (session file-name) - "Look in the current SESSION for folder containing FILE-NAME." - (let ((file-name-canonical (lsp-f-canonical file-name))) - (->> session - (lsp-session-folders) - (--filter (and (lsp--files-same-host it file-name-canonical) - (or (lsp-f-same? it file-name-canonical) - (and (f-dir? it) - (lsp-f-ancestor-of? it file-name-canonical))))) - (--max-by (> (length it) - (length other)))))) - -(defun lsp-find-workspace (server-id &optional file-name) - "Find workspace for SERVER-ID for FILE-NAME." - (-when-let* ((session (lsp-session)) - (folder->servers (lsp-session-folder->servers session)) - (workspaces (if file-name - (gethash (lsp-find-session-folder session file-name) folder->servers) - (lsp--session-workspaces session)))) - - (--first (eq (lsp--client-server-id (lsp--workspace-client it)) server-id) workspaces))) - -(defun lsp--calculate-root (session file-name) - "Calculate project root for FILE-NAME in SESSION." - (and - (->> session - (lsp-session-folders-blocklist) - (--first (and (lsp--files-same-host it file-name) - (lsp-f-ancestor-of? it file-name) - (prog1 t - (lsp--info "File %s is in blocklisted directory %s" file-name it)))) - not) - (or - (when lsp-auto-guess-root - (lsp--suggest-project-root)) - (unless lsp-guess-root-without-session - (lsp-find-session-folder session file-name)) - (unless lsp-auto-guess-root - (when-let ((root-folder (lsp--find-root-interactively session))) - (if (or (not (f-equal? root-folder (expand-file-name "~/"))) - (yes-or-no-p - (concat - (propertize "[WARNING] " 'face 'warning) - "You are trying to import your home folder as project root. This may cause performance issue because some language servers (python, lua, etc) will try to scan all files under project root. To avoid that you may: - -1. Use `I' option from the interactive project import to select subfolder(e. g. `~/foo/bar' instead of `~/'). -2. If your file is under `~/' then create a subfolder and move that file in this folder. - -Type `No' to go back to project selection. -Type `Yes' to confirm `HOME' as project root. -Type `C-g' to cancel project import process and stop `lsp'"))) - root-folder - (lsp--calculate-root session file-name))))))) - -(defun lsp--try-open-in-library-workspace () - "Try opening current file as library file in any of the active workspace. -The library folders are defined by each client for each of the active workspace." - (when-let ((workspace (->> (lsp-session) - (lsp--session-workspaces) - ;; Sort the last active workspaces first as they are more likely to be - ;; the correct ones, especially when jumping to a definition. - (-sort (lambda (a _b) - (-contains? lsp--last-active-workspaces a))) - (--first - (and (-> it lsp--workspace-client lsp--supports-buffer?) - (when-let ((library-folders-fn - (-> it lsp--workspace-client lsp--client-library-folders-fn))) - (-first (lambda (library-folder) - (lsp-f-ancestor-of? library-folder (buffer-file-name))) - (funcall library-folders-fn it)))))))) - (lsp--open-in-workspace workspace) - (view-mode t) - (lsp--info "Opening read-only library file %s." (buffer-file-name)) - (list workspace))) - -(defun lsp--persist-session (session) - "Persist SESSION to `lsp-session-file'." - (lsp--persist lsp-session-file (make-lsp-session - :folders (lsp-session-folders session) - :folders-blocklist (lsp-session-folders-blocklist session) - :server-id->folders (lsp-session-server-id->folders session)))) - -(defun lsp--try-project-root-workspaces (ask-for-client ignore-multi-folder) - "Try create opening file as a project file. -When IGNORE-MULTI-FOLDER is t the lsp mode will start new -language server even if there is language server which can handle -current language. When IGNORE-MULTI-FOLDER is nil current file -will be opened in multi folder language server if there is -such." - (-let ((session (lsp-session))) - (-if-let (clients (if ask-for-client - (list (lsp--completing-read "Select server to start: " - (ht-values lsp-clients) - (-compose 'symbol-name 'lsp--client-server-id) nil t)) - (lsp--find-clients))) - (-if-let (project-root (-some-> session - (lsp--calculate-root (buffer-file-name)) - (lsp-f-canonical))) - (progn - ;; update project roots if needed and persist the lsp session - (unless (-contains? (lsp-session-folders session) project-root) - (cl-pushnew project-root (lsp-session-folders session)) - (lsp--persist-session session)) - (lsp--ensure-lsp-servers session clients project-root ignore-multi-folder)) - (lsp--warn "%s not in project or it is blocklisted." (buffer-name)) - nil) - (lsp--warn "No LSP server for %s(check *lsp-log*)." major-mode) - nil))) - -(defun lsp-shutdown-workspace () - "Shutdown language server." - (interactive) - (--when-let (pcase (lsp-workspaces) - (`nil (user-error "There are no active servers in the current buffer")) - (`(,workspace) (when (y-or-n-p (format "Are you sure you want to stop the server %s?" - (lsp--workspace-print workspace))) - workspace)) - (workspaces (lsp--completing-read "Select server: " - workspaces - 'lsp--workspace-print nil t))) - (lsp-workspace-shutdown it))) - -(make-obsolete 'lsp-shutdown-workspace 'lsp-workspace-shutdown "lsp-mode 6.1") - -(defcustom lsp-auto-select-workspace t - "Shutdown or restart a single workspace. -If set and the current buffer has only a single workspace -associated with it, `lsp-shutdown-workspace' and -`lsp-restart-workspace' will act on it without asking." - :type 'boolean - :group 'lsp-mode) - -(defun lsp--read-workspace () - "Ask the user to select a workspace. -Errors if there are none." - (pcase (lsp-workspaces) - (`nil (error "No workspaces associated with the current buffer")) - ((and `(,workspace) (guard lsp-auto-select-workspace)) workspace) - (workspaces (lsp--completing-read "Select workspace: " workspaces - #'lsp--workspace-print nil t)))) - -(defun lsp-workspace-shutdown (workspace) - "Shut the workspace WORKSPACE and the language server associated with it" - (interactive (list (lsp--read-workspace))) - (lsp--warn "Stopping %s" (lsp--workspace-print workspace)) - (with-lsp-workspace workspace (lsp--shutdown-workspace))) - -(defun lsp-disconnect () - "Disconnect the buffer from the language server." - (interactive) - (lsp--text-document-did-close t) - (lsp-managed-mode -1) - (lsp-mode -1) - (setq lsp--buffer-workspaces nil) - (lsp--info "Disconnected")) - -(defun lsp-restart-workspace () - (interactive) - (--when-let (pcase (lsp-workspaces) - (`nil (user-error "There are no active servers in the current buffer")) - (`(,workspace) workspace) - (workspaces (lsp--completing-read "Select server: " - workspaces - 'lsp--workspace-print nil t))) - (lsp-workspace-restart it))) - -(make-obsolete 'lsp-restart-workspace 'lsp-workspace-restart "lsp-mode 6.1") - -(defun lsp-workspace-restart (workspace) - "Restart the workspace WORKSPACE and the language server associated with it" - (interactive (list (lsp--read-workspace))) - (lsp--warn "Restarting %s" (lsp--workspace-print workspace)) - (with-lsp-workspace workspace (lsp--shutdown-workspace t))) - -;;;###autoload -(defun lsp (&optional arg) - "Entry point for the server startup. -When ARG is t the lsp mode will start new language server even if -there is language server which can handle current language. When -ARG is nil current file will be opened in multi folder language -server if there is such. When `lsp' is called with prefix -argument ask the user to select which language server to start." - (interactive "P") - - (lsp--require-packages) - - (when (buffer-file-name) - (let (clients - (matching-clients (lsp--filter-clients - (-andfn #'lsp--supports-buffer? - #'lsp--server-binary-present?)))) - (cond - (matching-clients - (when (setq lsp--buffer-workspaces - (or (and - ;; Don't open as library file if file is part of a project. - (not (lsp-find-session-folder (lsp-session) (buffer-file-name))) - (lsp--try-open-in-library-workspace)) - (lsp--try-project-root-workspaces (equal arg '(4)) - (and arg (not (equal arg 1)))))) - (lsp-mode 1) - (when lsp-auto-configure (lsp--auto-configure)) - (setq lsp-buffer-uri (lsp--buffer-uri)) - (lsp--info "Connected to %s." - (apply 'concat (--map (format "[%s %s]" - (lsp--workspace-print it) - (lsp--workspace-root it)) - lsp--buffer-workspaces))))) - ;; look for servers which are currently being downloaded. - ((setq clients (lsp--filter-clients (-andfn #'lsp--supports-buffer? - #'lsp--client-download-in-progress?))) - (lsp--info "There are language server(%s) installation in progress. -The server(s) will be started in the buffer when it has finished." - (-map #'lsp--client-server-id clients)) - (seq-do (lambda (client) - (cl-pushnew (current-buffer) (lsp--client-buffers client))) - clients)) - ;; look for servers to install - ((setq clients (lsp--filter-clients - (-andfn #'lsp--supports-buffer? - (-const lsp-enable-suggest-server-download) - #'lsp--client-download-server-fn - (-not #'lsp--client-download-in-progress?)))) - (let ((client (lsp--completing-read - (concat "Unable to find installed server supporting this file. " - "The following servers could be installed automatically: ") - clients - (-compose #'symbol-name #'lsp--client-server-id) - nil - t))) - (cl-pushnew (current-buffer) (lsp--client-buffers client)) - (lsp--install-server-internal client))) - ;; ignore other warnings - ((not lsp-warn-no-matched-clients) - nil) - ;; automatic installation disabled - ((setq clients (unless matching-clients - (lsp--filter-clients (-andfn #'lsp--supports-buffer? - #'lsp--client-download-server-fn - (-not (-const lsp-enable-suggest-server-download)) - (-not #'lsp--server-binary-present?))))) - (lsp--warn "The following servers support current file but automatic download is disabled: %s -\(If you have already installed the server check *lsp-log*)." - (mapconcat (lambda (client) - (symbol-name (lsp--client-server-id client))) - clients - " "))) - ;; no clients present - ((setq clients (unless matching-clients - (lsp--filter-clients (-andfn #'lsp--supports-buffer? - (-not #'lsp--server-binary-present?))))) - (lsp--warn "The following servers support current file but do not have automatic installation: %s -You may find the installation instructions at https://emacs-lsp.github.io/lsp-mode/page/languages. -\(If you have already installed the server check *lsp-log*)." - (mapconcat (lambda (client) - (symbol-name (lsp--client-server-id client))) - clients - " "))) - ;; no matches - ((-> #'lsp--supports-buffer? lsp--filter-clients not) - (lsp--error "There are no language servers supporting current mode `%s' registered with `lsp-mode'. -This issue might be caused by: -1. The language you are trying to use does not have built-in support in `lsp-mode'. You must install the required support manually. Examples of this are `lsp-java' or `lsp-metals'. -2. The language server that you expect to run is not configured to run for major mode `%s'. You may check that by checking the `:major-modes' that are passed to `lsp-register-client'. -3. `lsp-mode' doesn't have any integration for the language behind `%s'. Refer to https://emacs-lsp.github.io/lsp-mode/page/languages and https://langserver.org/ . -4. You are over `tramp'. In this case follow https://emacs-lsp.github.io/lsp-mode/page/remote/. -5. You have disabled the `lsp-mode' clients for that file. (Check `lsp-enabled-clients' and `lsp-disabled-clients'). -You can customize `lsp-warn-no-matched-clients' to disable this message." - major-mode major-mode major-mode)))))) - -(defun lsp--buffer-visible-p () - "Return non nil if current buffer is visible." - (or (buffer-modified-p) (get-buffer-window nil t))) - -(defun lsp--init-if-visible () - "Run `lsp' for the current buffer if the buffer is visible. -Returns non nil if `lsp' was run for the buffer." - (when (lsp--buffer-visible-p) - (remove-hook 'window-configuration-change-hook #'lsp--init-if-visible t) - (lsp) - t)) - -;;;###autoload -(defun lsp-deferred () - "Entry point that defers server startup until buffer is visible. -`lsp-deferred' will wait until the buffer is visible before invoking `lsp'. -This avoids overloading the server with many files when starting Emacs." - ;; Workspace may not be initialized yet. Use a buffer local variable to - ;; remember that we deferred loading of this buffer. - (setq lsp--buffer-deferred t) - (let ((buffer (current-buffer))) - ;; Avoid false positives as desktop-mode restores buffers by deferring - ;; visibility check until the stack clears. - (run-with-idle-timer 0 nil (lambda () - (when (buffer-live-p buffer) - (with-current-buffer buffer - (unless (lsp--init-if-visible) - (add-hook 'window-configuration-change-hook #'lsp--init-if-visible nil t)))))))) - - - -(defvar lsp-file-truename-cache (ht)) - -(defmacro lsp-with-cached-filetrue-name (&rest body) - "Executes BODY caching the `file-truename' calls." - `(let ((old-fn (symbol-function 'file-truename))) - (unwind-protect - (progn - (fset 'file-truename - (lambda (file-name &optional counter prev-dirs) - (or (gethash file-name lsp-file-truename-cache) - (puthash file-name (apply old-fn (list file-name counter prev-dirs)) - lsp-file-truename-cache)))) - ,@body) - (fset 'file-truename old-fn)))) - - -(defun lsp-virtual-buffer-call (key &rest args) - (when lsp--virtual-buffer - (when-let ((fn (plist-get lsp--virtual-buffer key))) - (apply fn args)))) - -(defun lsp-translate-column (column) - "Translate COLUMN taking into account virtual buffers." - (or (lsp-virtual-buffer-call :real->virtual-char column) - column)) - -(defun lsp-translate-line (line) - "Translate LINE taking into account virtual buffers." - (or (lsp-virtual-buffer-call :real->virtual-line line) - line)) - - -;; lsp internal validation. - -(defmacro lsp--doctor (&rest checks) - `(-let [buf (current-buffer)] - (with-current-buffer (get-buffer-create "*lsp-performance*") - (with-help-window (current-buffer) - ,@(-map (-lambda ((msg form)) - `(insert (format "%s: %s\n" ,msg - (let ((res (with-current-buffer buf - ,form))) - (cond - ((eq res :optional) (propertize "OPTIONAL" 'face 'warning)) - (res (propertize "OK" 'face 'success)) - (t (propertize "ERROR" 'face 'error))))))) - (-partition 2 checks)))))) - -(define-obsolete-function-alias 'lsp-diagnose - 'lsp-doctor "lsp-mode 8.0.0") - -(defun lsp-doctor () - "Validate performance settings." - (interactive) - (lsp--doctor - "Checking for Native JSON support" (functionp 'json-serialize) - "Check emacs supports `read-process-output-max'" (boundp 'read-process-output-max) - "Check `read-process-output-max' default has been changed from 4k" - (and (boundp 'read-process-output-max) - (> read-process-output-max 4096)) - "Byte compiled against Native JSON (recompile lsp-mode if failing when Native JSON available)" - (condition-case _err - (progn (lsp--make-message (list "a" "b")) - nil) - (error t)) - "`gc-cons-threshold' increased?" (> gc-cons-threshold 800000) - "Using `plist' for deserialized objects? (refer to https://emacs-lsp.github.io/lsp-mode/page/performance/#use-plists-for-deserialization)" (or lsp-use-plists :optional) - "Using emacs 28+ with native compilation?" - (or (and (fboundp 'native-comp-available-p) - (native-comp-available-p)) - :optional))) - -(declare-function package-version-join "ext:package") -(declare-function package-desc-version "ext:package") -(declare-function package--alist "ext:package") - -(defun lsp-version () - "Return string describing current version of `lsp-mode'." - (interactive) - (unless (featurep 'package) - (require 'package)) - (let ((ver (format "lsp-mode %s, Emacs %s, %s" - (package-version-join - (package-desc-version - (car (alist-get 'lsp-mode (package--alist))))) - emacs-version - system-type))) - (if (called-interactively-p 'interactive) - (lsp--info "%s" ver) - ver))) - - - -;; org-mode/virtual-buffer - -(declare-function org-babel-get-src-block-info "ext:ob-core") -(declare-function org-do-remove-indentation "ext:org-macs") -(declare-function org-src-get-lang-mode "ext:org-src") -(declare-function org-element-context "ext:org-element") - -(defun lsp--virtual-buffer-update-position () - (-if-let (virtual-buffer (-first (-lambda ((&plist :in-range)) - (funcall in-range)) - lsp--virtual-buffer-connections)) - (unless (equal virtual-buffer lsp--virtual-buffer) - (lsp-org)) - (when lsp-managed-mode - (lsp-managed-mode -1) - (lsp-mode -1) - (setq lsp--buffer-workspaces nil) - (setq lsp--virtual-buffer nil) - (setq lsp-buffer-uri nil) - - ;; force refresh of diagnostics - (run-hooks 'lsp-after-diagnostics-hook)))) - -(defun lsp-virtual-buffer-on-change (start end length) - "Adjust on change event to be executed against the proper language server." - (let ((max-point (max end - (or (plist-get lsp--before-change-vals :end) 0) - (+ start length)))) - (when-let ((virtual-buffer (-first (lambda (vb) - (let ((lsp--virtual-buffer vb)) - (and (lsp-virtual-buffer-call :in-range start) - (lsp-virtual-buffer-call :in-range max-point)))) - lsp--virtual-buffer-connections))) - (lsp-with-current-buffer virtual-buffer - (lsp-on-change start end length - (lambda (&rest _) - (list :range (lsp--range (list :character 0 :line 0) - lsp--virtual-buffer-point-max) - :text (lsp--buffer-content)))))))) - -(defun lsp-virtual-buffer-before-change (start _end) - (when-let ((virtual-buffer (-first (lambda (vb) - (lsp-with-current-buffer vb - (lsp-virtual-buffer-call :in-range start))) - lsp--virtual-buffer-connections))) - (lsp-with-current-buffer virtual-buffer - (setq lsp--virtual-buffer-point-max - (lsp--point-to-position (lsp-virtual-buffer-call :last-point)))))) - -(defun lsp-patch-on-change-event () - (remove-hook 'after-change-functions #'lsp-on-change t) - (add-hook 'after-change-functions #'lsp-virtual-buffer-on-change nil t) - (add-hook 'before-change-functions #'lsp-virtual-buffer-before-change nil t)) - -(defun lsp-kill-virtual-buffers () - (mapc #'lsp-virtual-buffer-disconnect lsp--virtual-buffer-connections)) - -(defun lsp--move-point-in-indentation (point indentation) - (save-excursion - (goto-char point) - (if (<= point (+ (line-beginning-position) indentation)) - (line-beginning-position) - point))) - -(declare-function flycheck-checker-supports-major-mode-p "ext:flycheck") -(declare-function flycheck-add-mode "ext:flycheck") -(declare-function lsp-diagnostics-lsp-checker-if-needed "lsp-diagnostics") - -(defalias 'lsp-client-download-server-fn 'lsp--client-download-server-fn) - -(defun lsp-flycheck-add-mode (mode) - "Register flycheck support for MODE." - (lsp-diagnostics-lsp-checker-if-needed) - (unless (flycheck-checker-supports-major-mode-p 'lsp mode) - (flycheck-add-mode 'lsp mode))) - -(defun lsp-progress-spinner-type () - "Retrieve the spinner type value, if value is not a symbol of `spinner-types -defaults to `progress-bar." - (or (car (assoc lsp-progress-spinner-type spinner-types)) 'progress-bar)) - -(defun lsp-org () - (interactive) - (-if-let ((virtual-buffer &as &plist :workspaces) (-first (-lambda ((&plist :in-range)) - (funcall in-range)) - lsp--virtual-buffer-connections)) - (unless (equal lsp--virtual-buffer virtual-buffer) - (setq lsp--buffer-workspaces workspaces) - (setq lsp--virtual-buffer virtual-buffer) - (setq lsp-buffer-uri nil) - (lsp-mode 1) - (lsp-managed-mode 1) - (lsp-patch-on-change-event)) - - (save-excursion - (-let* (virtual-buffer - (wcb (lambda (f) - (with-current-buffer (plist-get virtual-buffer :buffer) - (-let* (((&plist :major-mode :buffer-file-name - :goto-buffer :workspaces) virtual-buffer) - (lsp--virtual-buffer virtual-buffer) - (lsp--buffer-workspaces workspaces)) - (save-excursion - (funcall goto-buffer) - (funcall f)))))) - ((&plist :begin :end :post-blank :language) (cl-second (org-element-context))) - ((&alist :tangle file-name) (cl-third (org-babel-get-src-block-info 'light))) - - (file-name (if file-name - (f-expand file-name) - (user-error "You should specify file name in the src block header."))) - (begin-marker (progn - (goto-char begin) - (forward-line) - (set-marker (make-marker) (point)))) - (end-marker (progn - (goto-char end) - (forward-line (1- (- post-blank))) - (set-marker (make-marker) (1+ (point))))) - (buf (current-buffer)) - (src-block (buffer-substring-no-properties begin-marker - (1- end-marker))) - (indentation (with-temp-buffer - (insert src-block) - - (goto-char (point-min)) - (let ((indentation (current-indentation))) - (plist-put lsp--virtual-buffer :indentation indentation) - (org-do-remove-indentation) - (goto-char (point-min)) - (- indentation (current-indentation)))))) - (add-hook 'post-command-hook #'lsp--virtual-buffer-update-position nil t) - - (when (fboundp 'flycheck-add-mode) - (lsp-flycheck-add-mode 'org-mode)) - - (setq lsp--virtual-buffer - (list - :in-range (lambda (&optional point) - (<= begin-marker (or point (point)) (1- end-marker))) - :goto-buffer (lambda () (goto-char begin-marker)) - :buffer-string - (lambda () - (let ((src-block (buffer-substring-no-properties - begin-marker - (1- end-marker)))) - (with-temp-buffer - (insert src-block) - - (goto-char (point-min)) - (while (not (eobp)) - (delete-region (point) (if (> (+ (point) indentation) (line-end-position)) - (line-end-position) - (+ (point) indentation))) - (forward-line)) - (buffer-substring-no-properties (point-min) - (point-max))))) - :buffer buf - :begin begin-marker - :end end-marker - :indentation indentation - :last-point (lambda () (1- end-marker)) - :cur-position (lambda () - (lsp-save-restriction-and-excursion - (list :line (- (lsp--cur-line) - (lsp--cur-line begin-marker)) - :character (let ((character (- (point) - (line-beginning-position) - indentation))) - (if (< character 0) - 0 - character))))) - :line/character->point (-lambda (line character) - (-let [inhibit-field-text-motion t] - (+ indentation - (lsp-save-restriction-and-excursion - (goto-char begin-marker) - (forward-line line) - (-let [line-end (line-end-position)] - (if (> character (- line-end (point))) - line-end - (forward-char character) - (point))))))) - :major-mode (org-src-get-lang-mode language) - :buffer-file-name file-name - :buffer-uri (lsp--path-to-uri file-name) - :with-current-buffer wcb - :buffer-live? (lambda (_) (buffer-live-p buf)) - :buffer-name (lambda (_) - (propertize (format "%s(%s:%s)%s" - (buffer-name buf) - begin-marker - end-marker - language) - 'face 'italic)) - :real->virtual-line (lambda (line) - (+ line (line-number-at-pos begin-marker) -1)) - :real->virtual-char (lambda (char) (+ char indentation)) - :cleanup (lambda () - (set-marker begin-marker nil) - (set-marker end-marker nil)))) - (setf virtual-buffer lsp--virtual-buffer) - (puthash file-name virtual-buffer lsp--virtual-buffer-mappings) - (push virtual-buffer lsp--virtual-buffer-connections) - - ;; TODO: tangle only connected sections - (add-hook 'after-save-hook 'org-babel-tangle nil t) - (add-hook 'lsp-after-open-hook #'lsp-patch-on-change-event nil t) - (add-hook 'kill-buffer-hook #'lsp-kill-virtual-buffers nil t) - - (setq lsp--buffer-workspaces - (lsp-with-current-buffer virtual-buffer - (lsp) - (plist-put virtual-buffer :workspaces (lsp-workspaces)) - (lsp-workspaces))))))) - -(defun lsp-virtual-buffer-disconnect (virtual-buffer) - (interactive (list (or - lsp--virtual-buffer - (when lsp--virtual-buffer-connections - (lsp--completing-read "Select virtual buffer to disconnect: " - lsp--virtual-buffer-connections - (-lambda ((&plist :buffer-file-name)) - buffer-file-name)))))) - (-if-let ((&plist :buffer-file-name file-name :cleanup) virtual-buffer) - (progn - (lsp-with-current-buffer virtual-buffer - (lsp--text-document-did-close)) - (setq lsp--virtual-buffer-connections (-remove-item virtual-buffer lsp--virtual-buffer-connections)) - (when (eq virtual-buffer lsp--virtual-buffer) - (setf lsp--virtual-buffer nil)) - (when cleanup (funcall cleanup)) - (remhash file-name lsp--virtual-buffer-mappings) - - (lsp--virtual-buffer-update-position) - (lsp--info "Disconnected from buffer %s" file-name)) - (lsp--error "Nothing to disconnect from?"))) - - -;; inlay hints - -(defface lsp-inlay-hint-face - '((t :inherit font-lock-comment-face)) - "The face to use for the JavaScript inlays." - :group 'lsp-mode - :package-version '(lsp-mode . "9.0.0")) - -(defface lsp-inlay-hint-type-face - '((t :inherit lsp-inlay-hint-face)) - "Face for inlay type hints (e.g. inferred variable types)." - :group 'lsp-mode - :package-version '(lsp-mode . "9.0.0")) - -(defcustom lsp-inlay-hint-type-format "%s" - "Format string for variable inlays (part of the inlay face)." - :type '(string :tag "String") - :group 'lsp-mode - :package-version '(lsp-mode . "9.0.0")) - -(defface lsp-inlay-hint-parameter-face - '((t :inherit lsp-inlay-hint-face)) - "Face for inlay parameter hints (e.g. function parameter names at -call-site)." - :group 'lsp-mode - :package-version '(lsp-mode . "9.0.0")) - -(defcustom lsp-inlay-hint-param-format "%s" - "Format string for parameter inlays (part of the inlay face)." - :type '(string :tag "String") - :group 'lsp-mode - :package-version '(lsp-mode . "9.0.0")) - -(defcustom lsp-update-inlay-hints-on-scroll t - "If non-nil update inlay hints immediately when scrolling or -modifying window sizes." - :type 'boolean - :package-version '(lsp-mode . "9.0.0")) - -(defun lsp--format-inlay (text kind) - (cond - ((eql kind lsp/inlay-hint-kind-type-hint) (format lsp-inlay-hint-type-format text)) - ((eql kind lsp/inlay-hint-kind-parameter-hint) (format lsp-inlay-hint-param-format text)) - (t text))) - -(defun lsp--face-for-inlay (kind) - (cond - ((eql kind lsp/inlay-hint-kind-type-hint) 'lsp-inlay-hint-type-face) - ((eql kind lsp/inlay-hint-kind-parameter-hint) 'lsp-inlay-hint-parameter-face) - (t 'lsp-inlay-hint-face))) - -(defun lsp--update-inlay-hints-scroll-function (window start) - (lsp-update-inlay-hints start (window-end window t))) - -(defun lsp--update-inlay-hints () - (lsp-update-inlay-hints (window-start) (window-end nil t))) - -(defun lsp--label-from-inlay-hints-response (label) - "Returns a string label built from an array of -InlayHintLabelParts or the argument itself if it's already a -string." - (cl-typecase label - (string label) - (vector - (string-join (mapcar (lambda (part) - (-let (((&InlayHintLabelPart :value) part)) - value)) - label))))) - -(defun lsp-update-inlay-hints (start end) - (lsp-request-async - "textDocument/inlayHint" - (lsp-make-inlay-hints-params - :text-document (lsp--text-document-identifier) - :range (lsp-make-range :start - (lsp-point-to-position start) - :end - (lsp-point-to-position end))) - (lambda (res) - (lsp--remove-overlays 'lsp-inlay-hint) - (dolist (hint res) - (-let* (((&InlayHint :label :position :kind? :padding-left? :padding-right?) hint) - (kind (or kind? lsp/inlay-hint-kind-type-hint)) - (label (lsp--label-from-inlay-hints-response label)) - (pos (lsp--position-to-point position)) - (overlay (make-overlay pos pos nil 'front-advance 'end-advance))) - (when (stringp label) - (overlay-put overlay 'lsp-inlay-hint t) - (overlay-put overlay 'before-string - (format "%s%s%s" - (if padding-left? " " "") - (propertize (lsp--format-inlay label kind) - 'font-lock-face (lsp--face-for-inlay kind)) - (if padding-right? " " ""))))))) - :mode 'tick)) - -(define-minor-mode lsp-inlay-hints-mode - "Mode for displaying inlay hints." - :lighter nil - (cond - ((and lsp-inlay-hints-mode lsp--buffer-workspaces) - (add-hook 'lsp-on-idle-hook #'lsp--update-inlay-hints nil t) - (when lsp-update-inlay-hints-on-scroll - (add-to-list (make-local-variable 'window-scroll-functions) - #'lsp--update-inlay-hints-scroll-function))) - (t - (lsp--remove-overlays 'lsp-inlay-hint) - (remove-hook 'lsp-on-idle-hook #'lsp--update-inlay-hints t) - (setf window-scroll-functions - (delete #'lsp--update-inlay-hints-scroll-function window-scroll-functions))))) - - - -;;;###autoload -(defun lsp-start-plain () - "Start `lsp-mode' using minimal configuration using the latest `melpa' version -of the packages. - -In case the major-mode that you are using for " - (interactive) - (let ((start-plain (make-temp-file "plain" nil ".el"))) - (url-copy-file "https://raw.githubusercontent.com/emacs-lsp/lsp-mode/master/scripts/lsp-start-plain.el" - start-plain t) - (async-shell-command - (format "%s -q -l %s %s" - (expand-file-name invocation-name invocation-directory) - start-plain - (or (buffer-file-name) "")) - (generate-new-buffer " *lsp-start-plain*")))) - - - -(provide 'lsp-mode) -;;; lsp-mode.el ends here diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-mode.elc b/emacs/elpa/lsp-mode-20241003.636/lsp-mode.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-terraform.elc b/emacs/elpa/lsp-mode-20241003.636/lsp-terraform.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-zig.el b/emacs/elpa/lsp-mode-20241003.636/lsp-zig.el @@ -1,301 +0,0 @@ -;;; lsp-zig.el --- lsp-mode Zig integration -*- lexical-binding: t; -*- - -;; Copyright (C) 2021 Riccardo Binetti - -;; Author: Riccardo Binetti <rbino@gmx.com> -;; Keywords: languages,tools - -;; This program is free software; you can redistribute it and/or modify -;; it under the terms of the GNU General Public License as published by -;; the Free Software Foundation, either version 3 of the License, or -;; (at your option) any later version. - -;; This program is distributed in the hope that it will be useful, -;; but WITHOUT ANY WARRANTY; without even the implied warranty of -;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -;; GNU General Public License for more details. - -;; You should have received a copy of the GNU General Public License -;; along with this program. If not, see <https://www.gnu.org/licenses/>. - -;;; Commentary: - -;; client for zls, the Zig language server - -;;; Code: - -(require 'lsp-mode) - -(defgroup lsp-zig nil - "LSP support for Zig via zls." - :group 'lsp-mode - :link '(url-link "https://github.com/zigtools/zls")) - -(defcustom lsp-zig-zls-executable "zls" - "The zls executable to use. - -Leave as just the executable name to use the default behavior of finding the -executable with variable `exec-path'." - :group 'lsp-zig - :type 'string) - -(defcustom lsp-zig-trace-server "off" - "Traces the communication between Emacs and the language server." - :group 'lsp-zig - :type '(choice (const "off") - (const "messages") - (const "verbose"))) - -(defcustom lsp-zls-enable-snippets t - "Enables snippet completions when the client also supports them." - :group 'lsp-zig - :type 'boolean) - -(defcustom lsp-zig-enable-argument-placeholders t - "Whether to enable function argument placeholder completions." - :group 'lsp-zig - :type 'boolean) - -(defcustom lsp-zig-enable-build-on-save nil - "Whether to enable build-on-save diagnostics." - :group 'lsp-zig - :type 'boolean) - -(defcustom lsp-zig-build-on-save-step "install" - "Select which step should be executed on build-on-save." - :group 'lsp-zig - :type 'string) - -(defcustom lsp-zig-enable-autofix nil - "Whether to automatically fix errors on save. -Currently supports adding and removing discards." - :group 'lsp-zig - :type 'boolean) - -(defcustom lsp-zig-semantic-tokens "partial" - "Traces the communication between Emacs and the language server." - :group 'lsp-zig - :type '(choice (const "off") - (const "messages") - (const "verbose"))) - -(defcustom lsp-zig-enable-inlay-hints t - "Enables inlay hint support when the client also supports it." - :group 'lsp-zig - :type 'boolean) - -(defcustom lsp-zig-inlay-hints-show-variable-type-hints t - "Enable inlay hints for variable type." - :group 'lsp-zig - :type 'boolean) - -(defcustom lsp-zig-inlay-hints-show-parameter-name t - "Enable inlay hints for parameter names." - :group 'lsp-zig - :type 'boolean) - -(defcustom lsp-zig-inlay-hints-exclude-single-argument t - "Don't show inlay hints for single argument calls." - :group 'lsp-zig - :type 'boolean) - -(defcustom lsp-zig-inlay-hints-show-builtin t - "Don't show inlay hints for single argument calls." - :group 'lsp-zig - :type 'boolean) - -(defcustom lsp-zig-inlay-hints-hide-redundant-param-names nil - "Hides inlay hints when parameter name matches the identifier (e.g. foo: foo)." - :group 'lsp-zig - :type 'boolean) - -(defcustom lsp-zig-inlay-hints-hide-redundant-param-names-last-token nil - "Hides inlay hints when parameter name matches the last token of a parameter -node (e.g. foo: bar.foo, foo: &foo)." - :group 'lsp-zig - :type 'boolean) - -(defcustom lsp-zig-warn-style nil - "Enables warnings for style guideline mismatches." - :group 'lsp-zig - :type 'boolean) - -(defcustom lsp-zig-highlight-global-var-declarations nil - "Whether to highlight global var declarations." - :group 'lsp-zig - :type 'boolean) - -(defcustom lsp-zig-dangerous-comptime-experiments-do-not-enable nil - "When true, skips searching for references in std. -Improves lookup speed for functions in user's code. Renaming and -go-to-definition will continue to work as is." - :group 'lsp-zig - :type 'boolean) - -(defcustom lsp-zig-skip-std-references nil - "hen true, skips searching for references in std. -Improves lookup speed for functions in user's code. Renaming and - go-to-definition will continue to work as is." - :group 'lsp-zig - :type 'boolean) - -(defcustom lsp-zig-prefer-ast-check-as-child-process t - "Favor using `zig ast-check` instead of ZLS's fork." - :group 'lsp-zig - :type 'boolean) - -(defcustom lsp-zig-record-session nil - "When true, zls will record all request is receives and write in into -`record_session_path`, so that they can replayed with `zls replay`." - :group 'lsp-zig - :type 'boolean) - -(defcustom lsp-zig-record-session-path "" - "Output file path when `record_session` is set. -The recommended file extension *.zlsreplay." - :group 'lsp-zig - :type 'string) - -(defcustom lsp-zig-replay-session-path "" - "Used when calling `zls replay` for specifying the replay file. -If no extra argument is given `record_session_path` is used as the default path." - :group 'lsp-zig - :type 'string) - -(defcustom lsp-zig-builtin-path "" - "Path to `builtin'; useful for debugging, automatically set if let null." - :group 'lsp-zig - :type 'string) - -(defcustom lsp-zig-zig-lib-path "" - "Zig library path. -e.g. `/path/to/zig/lib/zig`, used to analyze std library imports." - :group 'lsp-zig - :type 'string) - -(defcustom lsp-zig-zig-exe-path "" - " Zig executable path. -e.g. /path/to/zig/zig, used to run the custom build runner. If null, zig is -looked up in PATH. Will be used to infer the zig standard library path if none -is provided." - :group 'lsp-zig - :type 'string) - -(defcustom lsp-zig-build-runner-path "" - "Path to the `build_runner.zig` file provided by zls. -null is equivalent to `${executable_directory}/build_runner.zig`." - :group 'lsp-zig - :type 'string) - -(defcustom lsp-zig-global-cache-path "" - "Path to a directory that will be used as zig's cache. -null is equivalent to `${KnownFolders.Cache}/zls`." - :group 'lsp-zig - :type 'string) - -(defcustom lsp-zig-build-runner-global-cache-path "" - "Path to a directory that will be used as the global cache path when executing -a projects build.zig. null is equivalent to the path shown by `zig env`." - :group 'lsp-zig - :type 'string) - -(defcustom lsp-zig-completions-with-replace nil - "Completions confirm behavior. -If `true', replace the text after the cursor." - :group 'lsp-zig - :type 'boolean) - -;; -;;; Installation - -(defcustom lsp-zig-server-store-path - (expand-file-name "zig/" lsp-server-install-dir) - "The path to the file in which zls will be stored." - :type 'file - :group 'lsp-zig) - -(defconst lsp-zig-download-url-format - "https://github.com/zigtools/zls/releases/latest/download/zls-%s-%s.%s" - "Format to the download url link.") - -(defun lsp-zig--zls-url () - "Return Url points to the zls' zip/tar file." - (let* ((x86 (string-prefix-p "x86_64" system-configuration)) - (arch (if x86 "x86_64" "aarch64"))) - (cl-case system-type - ((cygwin windows-nt ms-dos) - (format lsp-zig-download-url-format arch "windows" "zip")) - (darwin - (format lsp-zig-download-url-format arch "macos" "tar.gz")) - (gnu/linux - (format lsp-zig-download-url-format arch "linux" "tar.gz"))))) - -(defun lsp-zig--stored-zls-executable () - "Return the stored zls executable. - -This is differ from the variable `lsp-zig-zls-executable'; this is local storage -and not the global storage." - (f-join lsp-zig-server-store-path - (pcase system-type ('windows-nt "bin/zls.exe") (_ "bin/zls")))) - -(lsp-dependency - 'zls - '(:system "zls") - `(:download :url ,(lsp-zig--zls-url) - :decompress ,(pcase system-type ('windows-nt :zip) (_ :targz)) - :store-path ,(f-join lsp-zig-server-store-path "temp") - :set-executable? t) - `(:system ,(lsp-zig--stored-zls-executable))) - -;; -;;; Core - -(lsp-register-custom-settings - '(("zls.enable_snippets" lsp-zls-enable-snippets t) - ("zls.enable_argument_placeholders" lsp-zig-enable-argument-placeholders t) - ("zls.enable_build_on_save" lsp-zig-enable-build-on-save t) - ("zls.build_on_save_step" lsp-zig-build-on-save-step) - ("zls.enable_autofix" lsp-zig-enable-autofix t) - ("zls.semantic_tokens" lsp-zig-semantic-tokens) - ("zls.enable_inlay_hints" lsp-zig-enable-inlay-hints t) - ("zls.inlay_hints_show_variable_type_hints" lsp-zig-inlay-hints-show-variable-type-hints t) - ("zls.inlay_hints_show_parameter_name" lsp-zig-inlay-hints-show-parameter-name t) - ("zls.inlay_hints_show_builtin" lsp-zig-inlay-hints-show-builtin t) - ("zls.inlay_hints_exclude_single_argument" lsp-zig-inlay-hints-exclude-single-argument t) - ("zls.inlay_hints_hide_redundant_param_names" lsp-zig-inlay-hints-hide-redundant-param-names t) - ("zls.inlay_hints_hide_redundant_param_names_last_token" lsp-zig-inlay-hints-hide-redundant-param-names-last-token t) - ("zls.warn_style" lsp-zig-warn-style t) - ("zls.highlight_global_var_declarations" lsp-zig-highlight-global-var-declarations t) - ("zls.dangerous_comptime_experiments_do_not_enable" lsp-zig-dangerous-comptime-experiments-do-not-enable t) - ("zls.skip_std_references" lsp-zig-skip-std-references t) - ("zls.prefer_ast_check_as_child_process" lsp-zig-prefer-ast-check-as-child-process t) - ("zls.record_session" lsp-zig-record-session t) - ("zls.record_session_path" lsp-zig-record-session-path) - ("zls.replay_session_path" lsp-zig-replay-session-path) - ("zls.builtin_path" lsp-zig-builtin-path) - ("zls.zig_lib_path" lsp-zig-zig-lib-path) - ("zls.zig_exe_path" lsp-zig-zig-exe-path) - ("zls.build_runner_path" lsp-zig-build-runner-path) - ("zls.global_cache_path" lsp-zig-global-cache-path) - ("zls.build_runner_global_cache_path" lsp-zig-build-runner-global-cache-path) - ("zls.completion_label_details" lsp-zig-completions-with-replace t))) - -(lsp-register-client - (make-lsp-client - :new-connection (lsp-stdio-connection - (lambda () (or (executable-find lsp-zig-zls-executable) - (lsp-zig--stored-zls-executable))) - (lambda () - (or (executable-find lsp-zig-zls-executable) - (file-executable-p (lsp-zig--stored-zls-executable))))) - :activation-fn (lsp-activate-on "zig") - :priority -1 - :server-id 'zls - :download-server-fn - (lambda (_client callback error-callback _update?) - (lsp-package-ensure 'zls callback error-callback)))) - -(lsp-consistency-check lsp-zig) - -(provide 'lsp-zig) -;;; lsp-zig.el ends here diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-zig.elc b/emacs/elpa/lsp-mode-20241003.636/lsp-zig.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-actionscript.el b/emacs/elpa/lsp-mode-20241004.151/lsp-actionscript.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-actionscript.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-actionscript.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-ada.el b/emacs/elpa/lsp-mode-20241004.151/lsp-ada.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-ada.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-ada.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-angular.el b/emacs/elpa/lsp-mode-20241004.151/lsp-angular.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-angular.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-angular.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-ansible.el b/emacs/elpa/lsp-mode-20241004.151/lsp-ansible.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-ansible.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-ansible.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-asm.el b/emacs/elpa/lsp-mode-20241004.151/lsp-asm.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-asm.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-asm.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-astro.el b/emacs/elpa/lsp-mode-20241004.151/lsp-astro.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-astro.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-astro.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-autotools.el b/emacs/elpa/lsp-mode-20241004.151/lsp-autotools.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-autotools.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-autotools.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-awk.el b/emacs/elpa/lsp-mode-20241004.151/lsp-awk.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-awk.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-awk.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-bash.el b/emacs/elpa/lsp-mode-20241004.151/lsp-bash.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-bash.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-bash.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-beancount.el b/emacs/elpa/lsp-mode-20241004.151/lsp-beancount.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-beancount.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-beancount.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-bufls.el b/emacs/elpa/lsp-mode-20241004.151/lsp-bufls.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-bufls.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-bufls.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-camel.el b/emacs/elpa/lsp-mode-20241004.151/lsp-camel.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-camel.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-camel.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-clangd.el b/emacs/elpa/lsp-mode-20241004.151/lsp-clangd.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-clangd.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-clangd.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-clojure.el b/emacs/elpa/lsp-mode-20241004.151/lsp-clojure.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-clojure.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-clojure.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-cmake.el b/emacs/elpa/lsp-mode-20241004.151/lsp-cmake.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-cmake.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-cmake.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-cobol.el b/emacs/elpa/lsp-mode-20241004.151/lsp-cobol.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-cobol.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-cobol.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241004.151/lsp-completion.el b/emacs/elpa/lsp-mode-20241004.151/lsp-completion.el @@ -0,0 +1,841 @@ +;;; lsp-completion.el --- LSP completion -*- lexical-binding: t; -*- +;; +;; Copyright (C) 2020 emacs-lsp maintainers +;; +;; This program is free software; you can redistribute it and/or modify +;; it under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. + +;; This program is distributed in the hope that it will be useful, +;; but WITHOUT ANY WARRANTY; without even the implied warranty of +;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +;; GNU General Public License for more details. + +;; You should have received a copy of the GNU General Public License +;; along with this program. If not, see <https://www.gnu.org/licenses/>. +;; +;;; Commentary: +;; +;; LSP completion +;; +;;; Code: + +(require 'lsp-mode) + +(defgroup lsp-completion nil + "LSP support for completion." + :prefix "lsp-completion-" + :group 'lsp-mode + :tag "LSP Completion") + +;;;###autoload +(define-obsolete-variable-alias 'lsp-prefer-capf + 'lsp-completion-provider "lsp-mode 7.0.1") + +(defcustom lsp-completion-provider :capf + "The completion backend provider." + :type '(choice + (const :tag "Use company-capf" :capf) + (const :tag "None" :none)) + :group 'lsp-completion + :package-version '(lsp-mode . "7.0.1")) + +;;;###autoload +(define-obsolete-variable-alias 'lsp-enable-completion-at-point + 'lsp-completion-enable "lsp-mode 7.0.1") + +(defcustom lsp-completion-enable t + "Enable `completion-at-point' integration." + :type 'boolean + :group 'lsp-completion) + +(defcustom lsp-completion-enable-additional-text-edit t + "Whether or not to apply additional text edit when performing completion. + +If set to non-nil, `lsp-mode' will apply additional text edits +from the server. Otherwise, the additional text edits are +ignored." + :type 'boolean + :group 'lsp-completion + :package-version '(lsp-mode . "6.3.2")) + +(defcustom lsp-completion-show-kind t + "Whether or not to show kind of completion candidates." + :type 'boolean + :group 'lsp-completion + :package-version '(lsp-mode . "7.0.1")) + +(defcustom lsp-completion-show-detail t + "Whether or not to show detail of completion candidates." + :type 'boolean + :group 'lsp-completion) + +(defcustom lsp-completion-show-label-description t + "Whether or not to show description of completion candidates." + :type 'boolean + :group 'lsp-completion + :package-version '(lsp-mode . "9.0.0")) + +(defcustom lsp-completion-no-cache nil + "Whether or not caching the returned completions from server." + :type 'boolean + :group 'lsp-completion + :package-version '(lsp-mode . "7.0.1")) + +(defcustom lsp-completion-filter-on-incomplete t + "Whether or not filter incomplete results." + :type 'boolean + :group 'lsp-completion + :package-version '(lsp-mode . "7.0.1")) + +(defcustom lsp-completion-sort-initial-results t + "Whether or not filter initial results from server." + :type 'boolean + :group 'lsp-completion + :package-version '(lsp-mode . "8.0.0")) + +(defcustom lsp-completion-use-last-result t + "Temporarily use last server result when interrupted by keyboard. +This will help minimize popup flickering issue in `company-mode'." + :type 'boolean + :group 'lsp-completion + :package-version '(lsp-mode . "8.0.0")) + +(defconst lsp-completion--item-kind + [nil + "Text" + "Method" + "Function" + "Constructor" + "Field" + "Variable" + "Class" + "Interface" + "Module" + "Property" + "Unit" + "Value" + "Enum" + "Keyword" + "Snippet" + "Color" + "File" + "Reference" + "Folder" + "EnumMember" + "Constant" + "Struct" + "Event" + "Operator" + "TypeParameter"]) + +(defvar yas-indent-line) +(defvar company-backends) +(defvar company-abort-on-unique-match) + +(defvar lsp-completion--no-reordering nil + "Dont do client-side reordering completion items when set.") + +(declare-function company-mode "ext:company") +(declare-function yas-expand-snippet "ext:yasnippet") + +(defun lsp-doc-buffer (&optional string) + "Return doc for STRING." + (with-current-buffer (get-buffer-create "*lsp-documentation*") + (erase-buffer) + (fundamental-mode) + (when string + (save-excursion + (insert string) + (visual-line-mode))) + (current-buffer))) + +(defun lsp-falsy? (val) + "Non-nil if VAL is falsy." + ;; https://developer.mozilla.org/en-US/docs/Glossary/Falsy + (or (not val) (equal val "") (equal val 0))) + +(cl-defun lsp-completion--make-item (item &key markers prefix) + "Make completion item from lsp ITEM and with MARKERS and PREFIX." + (-let (((&CompletionItem :label + :sort-text? + :_emacsStartPoint start-point) + item)) + (propertize label + 'lsp-completion-item item + 'lsp-sort-text sort-text? + 'lsp-completion-start-point start-point + 'lsp-completion-markers markers + 'lsp-completion-prefix prefix))) + +(defun lsp-completion--annotate (item) + "Annotate ITEM detail." + (-let (((&CompletionItem :detail? :kind? :label-details?) (plist-get (text-properties-at 0 item) + 'lsp-completion-item))) + (concat (when (and lsp-completion-show-detail detail?) + (concat " " (s-replace "\r" "" detail?))) + (when (and lsp-completion-show-label-description label-details?) + (when-let ((description (and label-details? (lsp:label-details-description label-details?)))) + (format " %s" description))) + (when lsp-completion-show-kind + (when-let ((kind-name (and kind? (aref lsp-completion--item-kind kind?)))) + (format " (%s)" kind-name)))))) + +(defun lsp-completion--looking-back-trigger-characterp (trigger-characters) + "Return character if text before point match any of the TRIGGER-CHARACTERS." + (unless (= (point) (line-beginning-position)) + (seq-some + (lambda (trigger-char) + (and (equal (buffer-substring-no-properties (- (point) (length trigger-char)) (point)) + trigger-char) + trigger-char)) + trigger-characters))) + +(defvar lsp-completion--cache nil + "Cached candidates for completion at point function. +In the form of plist (prefix-pos items :lsp-items :prefix ...). +When the completion is incomplete, `items' contains value of :incomplete.") + +(defvar lsp-completion--last-result nil + "Last completion result.") + +(defun lsp-completion--clear-cache (&optional keep-last-result) + "Clear completion caches. +KEEP-LAST-RESULT if specified." + (-some-> lsp-completion--cache + (cddr) + (plist-get :markers) + (cl-second) + (set-marker nil)) + (setq lsp-completion--cache nil) + (unless keep-last-result (setq lsp-completion--last-result nil))) + +(defcustom lsp-completion-default-behaviour :replace + "Default behaviour of `InsertReplaceEdit'." + :type '(choice + (const :tag "Default completion inserts" :insert) + (const :tag "Default completion replaces" :replace)) + :group 'lsp-mode + :package-version '(lsp-mode . "8.0.0")) + +(lsp-defun lsp-completion--guess-prefix ((item &as &CompletionItem :text-edit?)) + "Guess ITEM's prefix start point according to following heuristics: +- If `textEdit' exists, use insertion range start as prefix start point. +- Else, find the point before current point is longest prefix match of +`insertText' or `label'. And: + - The character before prefix is not word constitute +Return `nil' when fails to guess prefix." + (cond + ((lsp-insert-replace-edit? text-edit?) + (lsp--position-to-point (lsp:range-start (lsp:insert-replace-edit-insert text-edit?)))) + (text-edit? + (lsp--position-to-point (lsp:range-start (lsp:text-edit-range text-edit?)))) + (t + (-let* (((&CompletionItem :label :insert-text?) item) + (text (or (unless (lsp-falsy? insert-text?) insert-text?) label)) + (point (point)) + (start (max 1 (- point (length text)))) + (char-before (char-before start)) + start-point) + (while (and (< start point) (not start-point)) + (unless (or (and char-before (equal (char-syntax char-before) ?w)) + (not (string-prefix-p (buffer-substring-no-properties start point) + text))) + (setq start-point start)) + (cl-incf start) + (setq char-before (char-before start))) + start-point)))) + +(defun lsp-completion--to-internal (items) + "Convert ITEMS into internal form." + (--> items + (-map (-lambda ((item &as &CompletionItem + :label + :filter-text? + :_emacsStartPoint start-point + :score?)) + `( :label ,(or (unless (lsp-falsy? filter-text?) filter-text?) label) + :item ,item + :start-point ,start-point + :score ,score?)) + it))) + +(cl-defun lsp-completion--filter-candidates (items &key + lsp-items + markers + prefix + &allow-other-keys) + "List all possible completions in cached ITEMS with their prefixes. +We can pass LSP-ITEMS, which will be used when there's no cache. +The MARKERS and PREFIX value will be attached to each candidate." + (lsp--while-no-input + (->> + (if items + (--> (let (queries fuz-queries) + (-keep (-lambda ((cand &as &plist :label :start-point :score)) + (let* ((query (or (plist-get queries start-point) + (let ((s (buffer-substring-no-properties + start-point (point)))) + (setq queries (plist-put queries start-point s)) + s))) + (fuz-query (or (plist-get fuz-queries start-point) + (let ((s (lsp-completion--regex-fuz query))) + (setq fuz-queries + (plist-put fuz-queries start-point s)) + s))) + (label-len (length label))) + (when (string-match fuz-query label) + (put-text-property 0 label-len 'match-data (match-data) label) + (plist-put cand + :sort-score + (* (or (lsp-completion--fuz-score query label) 1e-05) + (or score 0.001))) + cand))) + items)) + (if lsp-completion--no-reordering + it + (sort it (lambda (o1 o2) + (> (plist-get o1 :sort-score) + (plist-get o2 :sort-score))))) + ;; TODO: pass additional function to sort the candidates + (-map (-rpartial #'plist-get :item) it)) + lsp-items) + (-map (lambda (item) (lsp-completion--make-item item + :markers markers + :prefix prefix)))))) + +(defconst lsp-completion--kind->symbol + '((1 . text) + (2 . method) + (3 . function) + (4 . constructor) + (5 . field) + (6 . variable) + (7 . class) + (8 . interface) + (9 . module) + (10 . property) + (11 . unit) + (12 . value) + (13 . enum) + (14 . keyword) + (15 . snippet) + (16 . color) + (17 . file) + (18 . reference) + (19 . folder) + (20 . enum-member) + (21 . constant) + (22 . struct) + (23 . event) + (24 . operator) + (25 . type-parameter))) + +(defun lsp-completion--candidate-kind (item) + "Return ITEM's kind." + (alist-get (lsp:completion-item-kind? (get-text-property 0 'lsp-completion-item item)) + lsp-completion--kind->symbol)) + +(defun lsp-completion--candidate-deprecated (item) + "Return if ITEM is deprecated." + (let ((completion-item (get-text-property 0 'lsp-completion-item item))) + (or (lsp:completion-item-deprecated? completion-item) + (seq-position (lsp:completion-item-tags? completion-item) + lsp/completion-item-tag-deprecated)))) + +(defun lsp-completion--company-match (candidate) + "Return highlight of typed prefix inside CANDIDATE." + (if-let ((md (cddr (plist-get (text-properties-at 0 candidate) 'match-data)))) + (let (matches start end) + (while (progn (setq start (pop md) end (pop md)) + (and start end)) + (setq matches (nconc matches `((,start . ,end))))) + matches) + (let* ((prefix (downcase + (buffer-substring-no-properties + ;; Put a safe guard to prevent staled cache from setting a wrong start point #4192 + (max (line-beginning-position) + (plist-get (text-properties-at 0 candidate) 'lsp-completion-start-point)) + (point)))) + (prefix-len (length prefix)) + (prefix-pos 0) + (label (downcase candidate)) + (label-len (length label)) + (label-pos 0) + matches start) + (while (and (not matches) + (< prefix-pos prefix-len)) + (while (and (< prefix-pos prefix-len) + (< label-pos label-len)) + (if (equal (aref prefix prefix-pos) (aref label label-pos)) + (progn + (unless start (setq start label-pos)) + (cl-incf prefix-pos)) + (when start + (setq matches (nconc matches `((,start . ,label-pos)))) + (setq start nil))) + (cl-incf label-pos)) + (when start (setq matches (nconc matches `((,start . ,label-pos))))) + ;; Search again when the whole prefix is not matched + (when (< prefix-pos prefix-len) + (setq matches nil)) + ;; Start search from next offset of prefix to find a match with label + (unless matches + (cl-incf prefix-pos) + (setq label-pos 0))) + matches))) + +(defun lsp-completion--get-documentation (item) + "Get doc comment for completion ITEM." + (unless (get-text-property 0 'lsp-completion-resolved item) + (let ((resolved-item + (-some->> item + (get-text-property 0 'lsp-completion-item) + (lsp-completion--resolve))) + (len (length item))) + (put-text-property 0 len 'lsp-completion-item resolved-item item) + (put-text-property 0 len 'lsp-completion-resolved t item))) + (-some->> item + (get-text-property 0 'lsp-completion-item) + (lsp:completion-item-documentation?) + (lsp--render-element))) + +(defun lsp-completion--get-context (trigger-characters same-session?) + "Get completion context with provided TRIGGER-CHARACTERS and SAME-SESSION?." + (let* ((triggered-by-char non-essential) + (trigger-char (when triggered-by-char + (lsp-completion--looking-back-trigger-characterp + trigger-characters))) + (trigger-kind (cond + (trigger-char + lsp/completion-trigger-kind-trigger-character) + ((and same-session? + (equal (cl-second lsp-completion--cache) :incomplete)) + lsp/completion-trigger-kind-trigger-for-incomplete-completions) + (t lsp/completion-trigger-kind-invoked)))) + (apply #'lsp-make-completion-context + (nconc + `(:trigger-kind ,trigger-kind) + (when trigger-char + `(:trigger-character? ,trigger-char)))))) + +(defun lsp-completion--sort-completions (completions) + "Sort COMPLETIONS." + (sort + completions + (-lambda ((&CompletionItem :sort-text? sort-text-left :label label-left) + (&CompletionItem :sort-text? sort-text-right :label label-right)) + (if (equal sort-text-left sort-text-right) + (string-lessp label-left label-right) + (string-lessp sort-text-left sort-text-right))))) + +;;;###autoload +(defun lsp-completion-at-point () + "Get lsp completions." + (when (or (--some (lsp--client-completion-in-comments? (lsp--workspace-client it)) + (lsp-workspaces)) + (not (nth 4 (syntax-ppss)))) + (let* ((trigger-chars (-> (lsp--capability-for-method "textDocument/completion") + (lsp:completion-options-trigger-characters?))) + (bounds-start (or (cl-first (bounds-of-thing-at-point 'symbol)) + (point))) + result done? + (candidates + (lambda () + (lsp--catch 'input + (let ((lsp--throw-on-input lsp-completion-use-last-result) + (same-session? (and lsp-completion--cache + ;; Special case for empty prefix and empty result + (or (cl-second lsp-completion--cache) + (not (string-empty-p + (plist-get (cddr lsp-completion--cache) :prefix)))) + (equal (cl-first lsp-completion--cache) bounds-start) + (s-prefix? + (plist-get (cddr lsp-completion--cache) :prefix) + (buffer-substring-no-properties bounds-start (point)))))) + (cond + ((or done? result) result) + ((and (not lsp-completion-no-cache) + same-session? + (listp (cl-second lsp-completion--cache))) + (setf result (apply #'lsp-completion--filter-candidates + (cdr lsp-completion--cache)))) + (t + (-let* ((resp (lsp-request-while-no-input + "textDocument/completion" + (plist-put (lsp--text-document-position-params) + :context (lsp-completion--get-context trigger-chars same-session?)))) + (completed (and resp + (not (and (lsp-completion-list? resp) + (lsp:completion-list-is-incomplete resp))))) + (items (lsp--while-no-input + (--> (cond + ((lsp-completion-list? resp) + (lsp:completion-list-items resp)) + (t resp)) + (if (or completed + (seq-some #'lsp:completion-item-sort-text? it)) + (lsp-completion--sort-completions it) + it) + (-map (lambda (item) + (lsp-put item + :_emacsStartPoint + (or (lsp-completion--guess-prefix item) + bounds-start))) + it)))) + (markers (list bounds-start (copy-marker (point) t))) + (prefix (buffer-substring-no-properties bounds-start (point))) + (lsp-completion--no-reordering (not lsp-completion-sort-initial-results))) + (lsp-completion--clear-cache same-session?) + (setf done? completed + lsp-completion--cache (list bounds-start + (cond + ((and done? (not (seq-empty-p items))) + (lsp-completion--to-internal items)) + ((not done?) :incomplete)) + :lsp-items nil + :markers markers + :prefix prefix) + result (lsp-completion--filter-candidates + (cond (done? + (cl-second lsp-completion--cache)) + (lsp-completion-filter-on-incomplete + (lsp-completion--to-internal items))) + :lsp-items items + :markers markers + :prefix prefix)))))) + (:interrupted lsp-completion--last-result) + (`,res (setq lsp-completion--last-result res)))))) + (list + bounds-start + (point) + (lambda (probe pred action) + (cond + ((eq action 'metadata) + '(metadata (category . lsp-capf) + (display-sort-function . identity) + (cycle-sort-function . identity))) + ((eq (car-safe action) 'boundaries) nil) + (t + (complete-with-action action (funcall candidates) probe pred)))) + :annotation-function #'lsp-completion--annotate + :company-kind #'lsp-completion--candidate-kind + :company-deprecated #'lsp-completion--candidate-deprecated + :company-require-match 'never + :company-prefix-length + (save-excursion + (let ( + ;; 2 is a heuristic number to make sure we look futher back than + ;; the bounds-start, which can be different from the actual start + ;; of the symbol + (bounds-left (max (line-beginning-position) (- bounds-start 2))) + triggered-by-char?) + (while (and (> (point) bounds-left) + (not (equal (char-after) ?\s)) + (not triggered-by-char?)) + (setq triggered-by-char? (lsp-completion--looking-back-trigger-characterp trigger-chars)) + (goto-char (1- (point)))) + (and triggered-by-char? t))) + :company-match #'lsp-completion--company-match + :company-doc-buffer (-compose #'lsp-doc-buffer + #'lsp-completion--get-documentation) + :exit-function + (-rpartial #'lsp-completion--exit-fn candidates))))) + +(defun lsp-completion--find-workspace (server-id) + (--first (eq (lsp--client-server-id (lsp--workspace-client it)) server-id) + (lsp-workspaces))) + +(defun lsp-completion--exit-fn (candidate _status &optional candidates) + "Exit function of `completion-at-point'. +CANDIDATE is the selected completion item. +Others: CANDIDATES" + (unwind-protect + (-let* ((candidate (if (plist-member (text-properties-at 0 candidate) + 'lsp-completion-item) + candidate + (cl-find candidate (funcall candidates) :test #'equal))) + ((&plist 'lsp-completion-item item + 'lsp-completion-start-point start-point + 'lsp-completion-markers markers + 'lsp-completion-resolved resolved + 'lsp-completion-prefix prefix) + (text-properties-at 0 candidate)) + ((&CompletionItem? :label :insert-text? :text-edit? :insert-text-format? + :additional-text-edits? :insert-text-mode? :command?) + ;; see #3498 typescript-language-server does not provide the + ;; proper insertText without resolving. + (if (and (lsp-completion--find-workspace 'ts-ls) + (not resolved)) + (lsp-completion--resolve item) + item))) + (cond + (text-edit? + (apply #'delete-region markers) + (insert prefix) + (pcase text-edit? + ((lsp-interface TextEdit) (lsp--apply-text-edit text-edit?)) + ((lsp-interface InsertReplaceEdit :insert :replace :new-text) + (lsp--apply-text-edit + (lsp-make-text-edit + :new-text new-text + :range (if (or (and current-prefix-arg (eq lsp-completion-default-behaviour :replace)) + (and (not current-prefix-arg) (eq lsp-completion-default-behaviour :insert))) + insert + replace)))))) + ((or (unless (lsp-falsy? insert-text?) insert-text?) label) + (apply #'delete-region markers) + (insert prefix) + (delete-region start-point (point)) + (insert (or (unless (lsp-falsy? insert-text?) insert-text?) label)))) + + (lsp--indent-lines start-point (point) insert-text-mode?) + (when (equal insert-text-format? lsp/insert-text-format-snippet) + (lsp--expand-snippet (buffer-substring start-point (point)) + start-point + (point))) + + (when lsp-completion-enable-additional-text-edit + (if (or (get-text-property 0 'lsp-completion-resolved candidate) + (not (seq-empty-p additional-text-edits?))) + (lsp--apply-text-edits additional-text-edits? 'completion) + (-let [(callback cleanup-fn) (lsp--create-apply-text-edits-handlers)] + (lsp-completion--resolve-async + item + (-compose callback #'lsp:completion-item-additional-text-edits?) + cleanup-fn)))) + + (if (or (get-text-property 0 'lsp-completion-resolved candidate) + command?) + (when command? (lsp--execute-command command?)) + (lsp-completion--resolve-async + item + (-lambda ((&CompletionItem? :command?)) + (when command? (lsp--execute-command command?))))) + + (when (and (or + (equal lsp-signature-auto-activate t) + (memq :after-completion lsp-signature-auto-activate) + (and (memq :on-trigger-char lsp-signature-auto-activate) + (-when-let ((&SignatureHelpOptions? :trigger-characters?) + (lsp--capability :signatureHelpProvider)) + (lsp-completion--looking-back-trigger-characterp + trigger-characters?)))) + (lsp-feature? "textDocument/signatureHelp")) + (lsp-signature-activate)) + + (setq-local lsp-inhibit-lsp-hooks nil)) + (lsp-completion--clear-cache))) + +(defun lsp-completion--regex-fuz (str) + "Build a regex sequence from STR. Insert .* between each char." + (apply #'concat + (cl-mapcar + #'concat + (cons "" (cdr (seq-map (lambda (c) (format "[^%c]*" c)) str))) + (seq-map (lambda (c) + (format "\\(%s\\)" (regexp-quote (char-to-string c)))) + str)))) + +(defun lsp-completion--fuz-score (query str) + "Calculate fuzzy score for STR with query QUERY. +The return is nil or in range of (0, inf)." + (-when-let* ((md (cddr (or (get-text-property 0 'match-data str) + (let ((re (lsp-completion--regex-fuz query))) + (when (string-match re str) + (match-data)))))) + (start (pop md)) + (len (length str)) + ;; To understand how this works, consider these bad ascii(tm) + ;; diagrams showing how the pattern "foo" flex-matches + ;; "fabrobazo", "fbarbazoo" and "barfoobaz": + + ;; f abr o baz o + ;; + --- + --- + + + ;; f barbaz oo + ;; + ------ ++ + + ;; bar foo baz + ;; --- +++ --- + + ;; "+" indicates parts where the pattern matched. A "hole" in + ;; the middle of the string is indicated by "-". Note that there + ;; are no "holes" near the edges of the string. The completion + ;; score is a number bound by ]0..1]: the higher the better and + ;; only a perfect match (pattern equals string) will have score + ;; 1. The formula takes the form of a quotient. For the + ;; numerator, we use the number of +, i.e. the length of the + ;; pattern. For the denominator, it first computes + ;; + ;; hole_i_contrib = 1 + (Li-1)^1.05 for first hole + ;; hole_i_contrib = 1 + (Li-1)^0.25 for hole i of length Li + ;; + ;; The final value for the denominator is then given by: + ;; + ;; (SUM_across_i(hole_i_contrib) + 1) + ;; + (score-numerator 0) + (score-denominator 0) + (last-b -1) + (q-ind 0) + (update-score + (lambda (a b) + "Update score variables given match range (A B)." + (setq score-numerator (+ score-numerator (- b a))) + (unless (= a len) + ;; case mismatch will be pushed to near next rank + (unless (equal (aref query q-ind) (aref str a)) + (cl-incf a 0.9)) + (setq score-denominator + (+ score-denominator + (if (= a last-b) 0 + (+ 1 (* (if (< 0 (- a last-b 1)) 1 -1) + (expt (abs (- a last-b 1)) + ;; Give a higher score for match near start + (if (eq last-b -1) 0.75 0.25)))))))) + (setq last-b b)))) + (while md + (funcall update-score start (cl-first md)) + ;; Due to the way completion regex is constructed, `(eq end (+ start 1))` + (cl-incf q-ind) + (pop md) + (setq start (pop md))) + (unless (zerop len) + (/ score-numerator (1+ score-denominator) 1.0)))) + +(defun lsp-completion--fix-resolve-data (item) + "Patch `CompletionItem' ITEM for rust-analyzer otherwise resolve will fail. +See #2675" + (let ((data (lsp:completion-item-data? item))) + (when (lsp-member? data :import_for_trait_assoc_item) + (unless (lsp-get data :import_for_trait_assoc_item) + (lsp-put data :import_for_trait_assoc_item :json-false))))) + +(defun lsp-completion--resolve (item) + "Resolve completion ITEM." + (cl-assert item nil "Completion item must not be nil") + (lsp-completion--fix-resolve-data item) + (or (ignore-errors + (when (lsp-feature? "completionItem/resolve") + (lsp-request "completionItem/resolve" + (lsp-delete (lsp-copy item) :_emacsStartPoint)))) + item)) + +(defun lsp-completion--resolve-async (item callback &optional cleanup-fn) + "Resolve completion ITEM asynchronously with CALLBACK. +The CLEANUP-FN will be called to cleanup." + (cl-assert item nil "Completion item must not be nil") + (lsp-completion--fix-resolve-data item) + (ignore-errors + (if (lsp-feature? "completionItem/resolve") + (lsp-request-async "completionItem/resolve" + (lsp-delete (lsp-copy item) :_emacsStartPoint) + (lambda (result) + (funcall callback result) + (when cleanup-fn (funcall cleanup-fn))) + :error-handler (lambda (err) + (when cleanup-fn (funcall cleanup-fn)) + (error (lsp:json-error-message err))) + :cancel-handler cleanup-fn + :mode 'alive) + (funcall callback item) + (when cleanup-fn (funcall cleanup-fn))))) + + +;;;###autoload +(defun lsp-completion--enable () + "Enable LSP completion support." + (when (and lsp-completion-enable + (lsp-feature? "textDocument/completion")) + (lsp-completion-mode 1))) + +(defun lsp-completion--disable () + "Disable LSP completion support." + (lsp-completion-mode -1)) + +(defun lsp-completion-passthrough-all-completions (_string table pred _point) + "Passthrough all completions from TABLE with PRED." + (defvar completion-lazy-hilit-fn) + (when (bound-and-true-p completion-lazy-hilit) + (setq completion-lazy-hilit-fn + (lambda (candidate) + (->> candidate + lsp-completion--company-match + (mapc (-lambda ((start . end)) + (put-text-property start end 'face 'completions-common-part candidate)))) + candidate))) + (all-completions "" table pred)) + +;;;###autoload +(define-minor-mode lsp-completion-mode + "Toggle LSP completion support." + :group 'lsp-completion + :global nil + :lighter "" + (let ((completion-started-fn (lambda (&rest _) + (setq-local lsp-inhibit-lsp-hooks t))) + (after-completion-fn (lambda (result) + (when (stringp result) + (lsp-completion--clear-cache)) + (setq-local lsp-inhibit-lsp-hooks nil)))) + (cond + (lsp-completion-mode + (make-local-variable 'completion-at-point-functions) + ;; Ensure that `lsp-completion-at-point' the first CAPF to be tried, + ;; unless user has put it elsewhere in the list by their own + (add-to-list 'completion-at-point-functions #'lsp-completion-at-point) + (make-local-variable 'completion-category-defaults) + (setf (alist-get 'lsp-capf completion-category-defaults) '((styles . (lsp-passthrough)))) + (make-local-variable 'completion-styles-alist) + (setf (alist-get 'lsp-passthrough completion-styles-alist) + '(completion-basic-try-completion + lsp-completion-passthrough-all-completions + "Passthrough completion.")) + + (cond + ((equal lsp-completion-provider :none)) + ((and (not (equal lsp-completion-provider :none)) + (fboundp 'company-mode)) + (setq-local company-abort-on-unique-match nil) + (company-mode 1) + (setq-local company-backends (cl-adjoin 'company-capf company-backends :test #'equal))) + (t + (lsp--warn "Unable to autoconfigure company-mode."))) + + (when (bound-and-true-p company-mode) + (add-hook 'company-completion-started-hook + completion-started-fn + nil + t) + (add-hook 'company-after-completion-hook + after-completion-fn + nil + t)) + (add-hook 'lsp-unconfigure-hook #'lsp-completion--disable nil t)) + (t + (remove-hook 'completion-at-point-functions #'lsp-completion-at-point t) + (setq-local completion-category-defaults + (cl-remove 'lsp-capf completion-category-defaults :key #'cl-first)) + (setq-local completion-styles-alist + (cl-remove 'lsp-passthrough completion-styles-alist :key #'cl-first)) + (remove-hook 'lsp-unconfigure-hook #'lsp-completion--disable t) + (when (featurep 'company) + (remove-hook 'company-completion-started-hook + completion-started-fn + t) + (remove-hook 'company-after-completion-hook + after-completion-fn + t)))))) + +;;;###autoload +(add-hook 'lsp-configure-hook (lambda () + (when (and lsp-auto-configure + lsp-completion-enable) + (lsp-completion--enable)))) + +(lsp-consistency-check lsp-completion) + +(provide 'lsp-completion) +;;; lsp-completion.el ends here diff --git a/emacs/elpa/lsp-mode-20241004.151/lsp-completion.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-completion.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-credo.el b/emacs/elpa/lsp-mode-20241004.151/lsp-credo.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-credo.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-credo.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-crystal.el b/emacs/elpa/lsp-mode-20241004.151/lsp-crystal.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-crystal.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-crystal.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-csharp.el b/emacs/elpa/lsp-mode-20241004.151/lsp-csharp.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-csharp.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-csharp.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-css.el b/emacs/elpa/lsp-mode-20241004.151/lsp-css.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-css.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-css.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-cucumber.el b/emacs/elpa/lsp-mode-20241004.151/lsp-cucumber.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-cucumber.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-cucumber.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-cypher.el b/emacs/elpa/lsp-mode-20241004.151/lsp-cypher.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-cypher.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-cypher.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-d.el b/emacs/elpa/lsp-mode-20241004.151/lsp-d.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-d.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-d.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-dhall.el b/emacs/elpa/lsp-mode-20241004.151/lsp-dhall.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-dhall.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-dhall.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-diagnostics.el b/emacs/elpa/lsp-mode-20241004.151/lsp-diagnostics.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-diagnostics.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-diagnostics.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-dired.el b/emacs/elpa/lsp-mode-20241004.151/lsp-dired.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-dired.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-dired.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-dockerfile.el b/emacs/elpa/lsp-mode-20241004.151/lsp-dockerfile.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-dockerfile.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-dockerfile.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-dot.el b/emacs/elpa/lsp-mode-20241004.151/lsp-dot.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-dot.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-dot.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-earthly.el b/emacs/elpa/lsp-mode-20241004.151/lsp-earthly.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-earthly.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-earthly.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-elixir.el b/emacs/elpa/lsp-mode-20241004.151/lsp-elixir.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-elixir.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-elixir.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-elm.el b/emacs/elpa/lsp-mode-20241004.151/lsp-elm.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-elm.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-elm.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-emmet.el b/emacs/elpa/lsp-mode-20241004.151/lsp-emmet.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-emmet.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-emmet.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-erlang.el b/emacs/elpa/lsp-mode-20241004.151/lsp-erlang.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-erlang.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-erlang.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-eslint.el b/emacs/elpa/lsp-mode-20241004.151/lsp-eslint.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-eslint.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-eslint.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-fortran.el b/emacs/elpa/lsp-mode-20241004.151/lsp-fortran.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-fortran.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-fortran.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-fsharp.el b/emacs/elpa/lsp-mode-20241004.151/lsp-fsharp.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-fsharp.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-fsharp.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-futhark.el b/emacs/elpa/lsp-mode-20241004.151/lsp-futhark.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-futhark.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-futhark.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-gdscript.el b/emacs/elpa/lsp-mode-20241004.151/lsp-gdscript.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-gdscript.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-gdscript.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-gleam.el b/emacs/elpa/lsp-mode-20241004.151/lsp-gleam.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-gleam.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-gleam.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-glsl.el b/emacs/elpa/lsp-mode-20241004.151/lsp-glsl.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-glsl.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-glsl.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-go.el b/emacs/elpa/lsp-mode-20241004.151/lsp-go.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-go.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-go.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-golangci-lint.el b/emacs/elpa/lsp-mode-20241004.151/lsp-golangci-lint.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-golangci-lint.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-golangci-lint.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-graphql.el b/emacs/elpa/lsp-mode-20241004.151/lsp-graphql.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-graphql.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-graphql.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-groovy.el b/emacs/elpa/lsp-mode-20241004.151/lsp-groovy.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-groovy.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-groovy.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-hack.el b/emacs/elpa/lsp-mode-20241004.151/lsp-hack.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-hack.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-hack.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-haxe.el b/emacs/elpa/lsp-mode-20241004.151/lsp-haxe.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-haxe.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-haxe.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-headerline.el b/emacs/elpa/lsp-mode-20241004.151/lsp-headerline.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-headerline.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-headerline.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-html.el b/emacs/elpa/lsp-mode-20241004.151/lsp-html.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-html.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-html.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-hy.el b/emacs/elpa/lsp-mode-20241004.151/lsp-hy.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-hy.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-hy.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-icons.el b/emacs/elpa/lsp-mode-20241004.151/lsp-icons.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-icons.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-icons.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-ido.el b/emacs/elpa/lsp-mode-20241004.151/lsp-ido.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-ido.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-ido.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-idris.el b/emacs/elpa/lsp-mode-20241004.151/lsp-idris.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-idris.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-idris.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-iedit.el b/emacs/elpa/lsp-mode-20241004.151/lsp-iedit.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-iedit.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-iedit.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-javascript.el b/emacs/elpa/lsp-mode-20241004.151/lsp-javascript.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-javascript.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-javascript.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-jq.el b/emacs/elpa/lsp-mode-20241004.151/lsp-jq.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-jq.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-jq.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-json.el b/emacs/elpa/lsp-mode-20241004.151/lsp-json.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-json.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-json.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-jsonnet.el b/emacs/elpa/lsp-mode-20241004.151/lsp-jsonnet.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-jsonnet.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-jsonnet.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-kotlin.el b/emacs/elpa/lsp-mode-20241004.151/lsp-kotlin.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-kotlin.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-kotlin.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-lens.el b/emacs/elpa/lsp-mode-20241004.151/lsp-lens.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-lens.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-lens.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-lisp.el b/emacs/elpa/lsp-mode-20241004.151/lsp-lisp.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-lisp.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-lisp.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-lua.el b/emacs/elpa/lsp-mode-20241004.151/lsp-lua.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-lua.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-lua.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-magik.el b/emacs/elpa/lsp-mode-20241004.151/lsp-magik.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-magik.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-magik.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-markdown.el b/emacs/elpa/lsp-mode-20241004.151/lsp-markdown.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-markdown.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-markdown.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-marksman.el b/emacs/elpa/lsp-mode-20241004.151/lsp-marksman.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-marksman.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-marksman.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-mdx.el b/emacs/elpa/lsp-mode-20241004.151/lsp-mdx.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-mdx.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-mdx.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-meson.el b/emacs/elpa/lsp-mode-20241004.151/lsp-meson.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-meson.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-meson.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-mint.el b/emacs/elpa/lsp-mode-20241004.151/lsp-mint.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-mint.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-mint.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-mode-autoloads.el b/emacs/elpa/lsp-mode-20241004.151/lsp-mode-autoloads.el diff --git a/emacs/elpa/lsp-mode-20241004.151/lsp-mode-pkg.el b/emacs/elpa/lsp-mode-20241004.151/lsp-mode-pkg.el @@ -0,0 +1,15 @@ +;; -*- no-byte-compile: t; lexical-binding: nil -*- +(define-package "lsp-mode" "20241004.151" + "LSP mode." + '((emacs "27.1") + (dash "2.18.0") + (f "0.20.0") + (ht "2.3") + (spinner "1.7.3") + (markdown-mode "2.3") + (lv "0") + (eldoc "1.11")) + :url "https://github.com/emacs-lsp/lsp-mode" + :commit "3a952ca135bd508e7dee4650a195b7ec5886a0ea" + :revdesc "3a952ca135bd" + :keywords '("languages")) diff --git a/emacs/elpa/lsp-mode-20241004.151/lsp-mode.el b/emacs/elpa/lsp-mode-20241004.151/lsp-mode.el @@ -0,0 +1,9924 @@ +;;; lsp-mode.el --- LSP mode -*- lexical-binding: t; -*- + +;; Copyright (C) 2020-2024 emacs-lsp maintainers + +;; Author: Vibhav Pant, Fangrui Song, Ivan Yonchovski +;; Keywords: languages +;; Package-Requires: ((emacs "27.1") (dash "2.18.0") (f "0.20.0") (ht "2.3") (spinner "1.7.3") (markdown-mode "2.3") (lv "0") (eldoc "1.11")) +;; Package-Version: 20241004.151 +;; Package-Revision: 3a952ca135bd + +;; URL: https://github.com/emacs-lsp/lsp-mode +;; This program is free software; you can redistribute it and/or modify +;; it under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. + +;; This program is distributed in the hope that it will be useful, +;; but WITHOUT ANY WARRANTY; without even the implied warranty of +;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +;; GNU General Public License for more details. + +;; You should have received a copy of the GNU General Public License +;; along with this program. If not, see <https://www.gnu.org/licenses/>. + +;;; Commentary: + +;; Emacs client/library for the Language Server Protocol + +;;; Code: + +(require 'cl-generic) +(require 'cl-lib) +(require 'compile) +(require 'dash) +(require 'epg) +(require 'ewoc) +(require 'f) +(require 'filenotify) +(require 'files) +(require 'ht) +(require 'imenu) +(require 'inline) +(require 'json) +(require 'lv) +(require 'markdown-mode) +(require 'network-stream) +(require 'pcase) +(require 'rx) +(require 's) +(require 'seq) +(require 'spinner) +(require 'subr-x) +(require 'tree-widget) +(require 'url-parse) +(require 'url-util) +(require 'widget) +(require 'xref) +(require 'minibuffer) +(require 'help-mode) +(require 'lsp-protocol) + +(defgroup lsp-mode nil + "Language Server Protocol client." + :group 'tools + :tag "Language Server (lsp-mode)") + +(declare-function evil-set-command-property "ext:evil-common") +(declare-function projectile-project-root "ext:projectile") +(declare-function yas-expand-snippet "ext:yasnippet") +(declare-function dap-mode "ext:dap-mode") +(declare-function dap-auto-configure-mode "ext:dap-mode") + +(defvar yas-inhibit-overlay-modification-protection) +(defvar yas-indent-line) +(defvar yas-wrap-around-region) +(defvar yas-also-auto-indent-first-line) +(defvar dap-auto-configure-mode) +(defvar dap-ui-menu-items) +(defvar company-minimum-prefix-length) + +(defconst lsp--message-type-face + `((1 . ,compilation-error-face) + (2 . ,compilation-warning-face) + (3 . ,compilation-message-face) + (4 . ,compilation-info-face))) + +(defconst lsp--errors + '((-32700 "Parse Error") + (-32600 "Invalid Request") + (-32601 "Method not Found") + (-32602 "Invalid Parameters") + (-32603 "Internal Error") + (-32099 "Server Start Error") + (-32000 "Server End Error") + (-32002 "Server Not Initialized") + (-32001 "Unknown Error Code") + (-32800 "Request Cancelled")) + "Alist of error codes to user friendly strings.") + +(defconst lsp--empty-ht (make-hash-table)) + +(eval-and-compile + (defun dash-expand:&lsp-wks (key source) + `(,(intern-soft (format "lsp--workspace-%s" (eval key))) ,source)) + + (defun dash-expand:&lsp-cln (key source) + `(,(intern-soft (format "lsp--client-%s" (eval key))) ,source))) + +(define-obsolete-variable-alias 'lsp-print-io 'lsp-log-io "lsp-mode 6.1") + +(defcustom lsp-log-io nil + "If non-nil, log all messages from the language server to a *lsp-log* buffer." + :group 'lsp-mode + :type 'boolean) + +(defcustom lsp-log-io-allowlist-methods '() + "The methods to filter before print to lsp-log-io." + :group 'lsp-mode + :type '(repeat string) + :package-version '(lsp-mode . "9.0.0")) + +(defcustom lsp-log-max message-log-max + "Maximum number of lines to keep in the log buffer. +If nil, disable message logging. If t, log messages but don’t truncate +the buffer when it becomes large." + :group 'lsp-mode + :type '(choice (const :tag "Disable" nil) + (integer :tag "lines") + (const :tag "Unlimited" t)) + :package-version '(lsp-mode . "6.1")) + +(defcustom lsp-io-messages-max t + "Maximum number of messages that can be locked in a `lsp-io' buffer." + :group 'lsp-mode + :type '(choice (const :tag "Unlimited" t) + (integer :tag "Messages")) + :package-version '(lsp-mode . "6.1")) + +(defcustom lsp-keep-workspace-alive t + "If non nil keep workspace alive when the last workspace buffer is closed." + :group 'lsp-mode + :type 'boolean) + +(defcustom lsp-enable-snippet t + "Enable/disable snippet completion support." + :group 'lsp-completion + :type 'boolean) + +(defcustom lsp-enable-folding t + "Enable/disable code folding support." + :group 'lsp-mode + :type 'boolean + :package-version '(lsp-mode . "6.1")) + +(define-obsolete-variable-alias 'lsp-enable-semantic-highlighting 'lsp-semantic-tokens-enable "lsp-mode 8.0.0") + +(defcustom lsp-semantic-tokens-enable nil + "Enable/disable support for semantic tokens. +As defined by the Language Server Protocol 3.16." + :group 'lsp-semantic-tokens + :type 'boolean) + +(defcustom lsp-folding-range-limit nil + "The maximum number of folding ranges to receive from the language server." + :group 'lsp-mode + :type '(choice (const :tag "No limit." nil) + (integer :tag "Number of lines.")) + :package-version '(lsp-mode . "6.1")) + +(defcustom lsp-folding-line-folding-only nil + "If non-nil, only fold complete lines." + :group 'lsp-mode + :type 'boolean + :package-version '(lsp-mode . "6.1")) + +(defcustom lsp-client-packages + '( ccls lsp-actionscript lsp-ada lsp-angular lsp-ansible lsp-asm lsp-astro + lsp-autotools lsp-awk lsp-bash lsp-beancount lsp-bufls lsp-clangd + lsp-clojure lsp-cmake lsp-cobol lsp-credo lsp-crystal lsp-csharp lsp-css + lsp-cucumber lsp-cypher lsp-d lsp-dart lsp-dhall lsp-docker lsp-dockerfile + lsp-earthly lsp-elixir lsp-elm lsp-emmet lsp-erlang lsp-eslint lsp-fortran lsp-futhark + lsp-fsharp lsp-gdscript lsp-gleam lsp-glsl lsp-go lsp-golangci-lint lsp-grammarly + lsp-graphql lsp-groovy lsp-hack lsp-haskell lsp-haxe lsp-idris lsp-java + lsp-javascript lsp-jq lsp-json lsp-kotlin lsp-latex lsp-lisp lsp-ltex + lsp-lua lsp-magik lsp-markdown lsp-marksman lsp-mdx lsp-meson lsp-metals lsp-mint + lsp-mojo lsp-move lsp-mssql lsp-nginx lsp-nim lsp-nix lsp-nushell lsp-ocaml + lsp-openscad lsp-pascal lsp-perl lsp-perlnavigator lsp-php lsp-pls + lsp-purescript lsp-pwsh lsp-pyls lsp-pylsp lsp-pyright lsp-python-ms + lsp-qml lsp-r lsp-racket lsp-remark lsp-rf lsp-roslyn lsp-rubocop lsp-ruby-lsp + lsp-ruby-syntax-tree lsp-ruff lsp-rust lsp-semgrep lsp-shader + lsp-solargraph lsp-solidity lsp-sonarlint lsp-sorbet lsp-sourcekit + lsp-sql lsp-sqls lsp-steep lsp-svelte lsp-tailwindcss lsp-terraform + lsp-tex lsp-tilt lsp-toml lsp-trunk lsp-ttcn3 lsp-typeprof lsp-v + lsp-vala lsp-verilog lsp-vetur lsp-vhdl lsp-vimscript lsp-volar lsp-wgsl + lsp-xml lsp-yaml lsp-yang lsp-zig) + "List of the clients to be automatically required." + :group 'lsp-mode + :type '(repeat symbol)) + +(defcustom lsp-progress-via-spinner t + "If non-nil, display LSP $/progress reports via a spinner in the modeline." + :group 'lsp-mode + :type 'boolean) + +(defcustom lsp-progress-spinner-type 'progress-bar + "Holds the type of spinner to be used in the mode-line. +Takes a value accepted by `spinner-start'." + :group 'lsp-mode + :type `(choice :tag "Choose a spinner by name" + ,@(mapcar (lambda (c) (list 'const (car c))) + spinner-types))) + +(defvar-local lsp-use-workspace-root-for-server-default-directory nil + "Use `lsp-workspace-root' for `default-directory' when starting LSP process.") + +(defvar-local lsp--cur-workspace nil) + +(defvar-local lsp--cur-version 0) +(defvar-local lsp--virtual-buffer-connections nil) +(defvar-local lsp--virtual-buffer nil) +(defvar lsp--virtual-buffer-mappings (ht)) + +(defvar lsp--uri-file-prefix (pcase system-type + (`windows-nt "file:///") + (_ "file://")) + "Prefix for a file-uri.") + +(defvar-local lsp-buffer-uri nil + "If set, return it instead of calculating it using `buffer-file-name'.") + +(define-error 'lsp-error "Unknown lsp-mode error") +(define-error 'lsp-empty-response-error + "Empty response from the language server" 'lsp-error) +(define-error 'lsp-timed-out-error + "Timed out while waiting for a response from the language server" 'lsp-error) +(define-error 'lsp-capability-not-supported + "Capability not supported by the language server" 'lsp-error) +(define-error 'lsp-file-scheme-not-supported + "Unsupported file scheme" 'lsp-error) +(define-error 'lsp-client-already-exists-error + "A client with this server-id already exists" 'lsp-error) +(define-error 'lsp-no-code-actions + "No code actions" 'lsp-error) + +(defcustom lsp-auto-guess-root nil + "Automatically guess the project root using projectile/project. +Do *not* use this setting unless you are familiar with `lsp-mode' +internals and you are sure that all of your projects are +following `projectile'/`project.el' conventions." + :group 'lsp-mode + :type 'boolean) + +(defcustom lsp-guess-root-without-session nil + "Ignore the session file when calculating the project root. +You almost always want to set lsp-auto-guess-root too. +Do *not* use this setting unless you are familiar with `lsp-mode' +internals and you are sure that all of your projects are +following `projectile'/`project.el' conventions." + :group 'lsp-mode + :type 'boolean) + +(defcustom lsp-restart 'interactive + "Defines how server-exited events must be handled." + :group 'lsp-mode + :type '(choice (const interactive) + (const auto-restart) + (const ignore))) + +(defcustom lsp-session-file (expand-file-name (locate-user-emacs-file ".lsp-session-v1")) + "File where session information is stored." + :group 'lsp-mode + :type 'file) + +(defcustom lsp-auto-configure t + "Auto configure `lsp-mode' main features. +When set to t `lsp-mode' will auto-configure completion, +code-actions, breadcrumb, `flycheck', `flymake', `imenu', symbol highlighting, +lenses, links, and so on. + +For finer granularity you may use `lsp-enable-*' properties." + :group 'lsp-mode + :type 'boolean + :package-version '(lsp-mode . "6.1")) + +(defcustom lsp-disabled-clients nil + "A list of disabled/blocklisted clients. +Each entry in the list can be either: +a symbol, the server-id for the LSP client, or +a cons pair (MAJOR-MODE . CLIENTS), where MAJOR-MODE is the major-mode, +and CLIENTS is either a client or a list of clients. + +This option can also be used as a file- or directory-local variable to +disable a language server for individual files or directories/projects +respectively." + :group 'lsp-mode + :type '(repeat (symbol)) + :safe 'listp + :package-version '(lsp-mode . "6.1")) + +(defvar lsp-clients (make-hash-table :test 'eql) + "Hash table server-id -> client. +It contains all of the clients that are currently registered.") + +(defvar lsp-enabled-clients nil + "List of clients allowed to be used for projects. +When nil, all registered clients are considered candidates.") + +(defvar lsp-last-id 0 + "Last request id.") + +(defcustom lsp-before-initialize-hook nil + "List of functions to be called before a Language Server has been initialized +for a new workspace." + :type 'hook + :group 'lsp-mode) + +(defcustom lsp-after-initialize-hook nil + "List of functions to be called after a Language Server has been initialized +for a new workspace." + :type 'hook + :group 'lsp-mode) + +(defcustom lsp-before-open-hook nil + "List of functions to be called before a new file with LSP support is opened." + :type 'hook + :group 'lsp-mode) + +(defcustom lsp-after-open-hook nil + "List of functions to be called after a new file with LSP support is opened." + :type 'hook + :group 'lsp-mode) + +(defcustom lsp-enable-file-watchers t + "If non-nil lsp-mode will watch the files in the workspace if +the server has requested that." + :type 'boolean + :group 'lsp-mode + :package-version '(lsp-mode . "6.1")) +;;;###autoload(put 'lsp-enable-file-watchers 'safe-local-variable #'booleanp) + +(define-obsolete-variable-alias 'lsp-file-watch-ignored 'lsp-file-watch-ignored-directories "8.0.0") + +(defcustom lsp-file-watch-ignored-directories + '(; SCM tools + "[/\\\\]\\.git\\'" + "[/\\\\]\\.github\\'" + "[/\\\\]\\.gitlab\\'" + "[/\\\\]\\.circleci\\'" + "[/\\\\]\\.hg\\'" + "[/\\\\]\\.bzr\\'" + "[/\\\\]_darcs\\'" + "[/\\\\]\\.svn\\'" + "[/\\\\]_FOSSIL_\\'" + ;; IDE or build tools + "[/\\\\]\\.idea\\'" + "[/\\\\]\\.ensime_cache\\'" + "[/\\\\]\\.eunit\\'" + "[/\\\\]node_modules" + "[/\\\\]\\.yarn\\'" + "[/\\\\]\\.fslckout\\'" + "[/\\\\]\\.tox\\'" + "[/\\\\]\\.nox\\'" + "[/\\\\]dist\\'" + "[/\\\\]dist-newstyle\\'" + "[/\\\\]\\.stack-work\\'" + "[/\\\\]\\.bloop\\'" + "[/\\\\]\\.metals\\'" + "[/\\\\]target\\'" + "[/\\\\]\\.ccls-cache\\'" + "[/\\\\]\\.vs\\'" + "[/\\\\]\\.vscode\\'" + "[/\\\\]\\.venv\\'" + "[/\\\\]\\.mypy_cache\\'" + "[/\\\\]\\.pytest_cache\\'" + ;; Swift Package Manager + "[/\\\\]\\.build\\'" + ;; Python + "[/\\\\]__pycache__\\'" + ;; Autotools output + "[/\\\\]\\.deps\\'" + "[/\\\\]build-aux\\'" + "[/\\\\]autom4te.cache\\'" + "[/\\\\]\\.reference\\'" + ;; Bazel + "[/\\\\]bazel-[^/\\\\]+\\'" + ;; CSharp + "[/\\\\]\\.cache[/\\\\]lsp-csharp\\'" + "[/\\\\]\\.meta\\'" + "[/\\\\]\\.nuget\\'" + ;; Unity + "[/\\\\]Library\\'" + ;; Clojure + "[/\\\\]\\.lsp\\'" + "[/\\\\]\\.clj-kondo\\'" + "[/\\\\]\\.shadow-cljs\\'" + "[/\\\\]\\.babel_cache\\'" + "[/\\\\]\\.cpcache\\'" + "[/\\\\]\\checkouts\\'" + ;; Gradle + "[/\\\\]\\.gradle\\'" + ;; Maven + "[/\\\\]\\.m2\\'" + ;; .Net Core build-output + "[/\\\\]bin/Debug\\'" + "[/\\\\]obj\\'" + ;; OCaml and Dune + "[/\\\\]_opam\\'" + "[/\\\\]_build\\'" + ;; Elixir + "[/\\\\]\\.elixir_ls\\'" + ;; Elixir Credo + "[/\\\\]\\.elixir-tools\\'" + ;; terraform and terragrunt + "[/\\\\]\\.terraform\\'" + "[/\\\\]\\.terragrunt-cache\\'" + ;; nix-direnv + "[/\\\\]\\result" + "[/\\\\]\\result-bin" + "[/\\\\]\\.direnv\\'") + "List of regexps matching directory paths which won't be monitored when +creating file watches. Customization of this variable is only honored at +the global level or at a root of an lsp workspace." + :group 'lsp-mode + :type '(repeat string) + :package-version '(lsp-mode . "8.0.0")) + +(define-obsolete-function-alias 'lsp-file-watch-ignored 'lsp-file-watch-ignored-directories "7.0.1") + +(defun lsp-file-watch-ignored-directories () + lsp-file-watch-ignored-directories) + +;; Allow lsp-file-watch-ignored-directories as a file or directory-local variable +;;;###autoload(put 'lsp-file-watch-ignored-directories 'safe-local-variable 'lsp--string-listp) + +(defcustom lsp-file-watch-ignored-files + '( + ;; Flycheck tempfiles + "[/\\\\]flycheck_[^/\\\\]+\\'" + ;; lockfiles + "[/\\\\]\\.#[^/\\\\]+\\'" + ;; backup files + "[/\\\\][^/\\\\]+~\\'" ) + "List of regexps matching files for which change events will +not be sent to the server. + +This setting has no impact on whether a file-watch is created for +a directory; it merely prevents notifications pertaining to +matched files from being sent to the server. To prevent a +file-watch from being created for a directory, customize +`lsp-file-watch-ignored-directories' + +Customization of this variable is only honored at the global +level or at a root of an lsp workspace." + :group 'lsp-mode + :type '(repeat string) + :package-version '(lsp-mode . "8.0.0")) + +;; Allow lsp-file-watch-ignored-files as a file or directory-local variable +;;;###autoload(put 'lsp-file-watch-ignored-files 'safe-local-variable 'lsp--string-listp) + +(defcustom lsp-after-uninitialized-functions nil + "List of functions to be called after a Language Server has been uninitialized." + :type 'hook + :group 'lsp-mode + :package-version '(lsp-mode . "6.3")) + +(defconst lsp--sync-full 1) +(defconst lsp--sync-incremental 2) + +(defcustom lsp-debounce-full-sync-notifications t + "If non-nil debounce full sync events. +This flag affects only servers which do not support incremental updates." + :type 'boolean + :group 'lsp-mode + :package-version '(lsp-mode . "6.1")) + +(defcustom lsp-debounce-full-sync-notifications-interval 1.0 + "Time to wait before sending full sync synchronization after buffer modification." + :type 'float + :group 'lsp-mode + :package-version '(lsp-mode . "6.1")) + +(defvar lsp--stderr-index 0) + +(defvar lsp--delayed-requests nil) +(defvar lsp--delay-timer nil) + +(defcustom lsp-document-sync-method nil + "How to sync the document with the language server." + :type '(choice (const :tag "Documents are synced by always sending the full content of the document." lsp--sync-full) + (const :tag "Documents are synced by always sending incremental changes to the document." lsp--sync-incremental) + (const :tag "Use the method recommended by the language server." nil)) + :group 'lsp-mode) + +(defcustom lsp-auto-execute-action t + "Auto-execute single action." + :type 'boolean + :group 'lsp-mode) + +(defcustom lsp-enable-links t + "If non-nil, all references to links in a file will be made clickable, if +supported by the language server." + :type 'boolean + :group 'lsp-mode + :package-version '(lsp-mode . "6.1")) + +(defcustom lsp-enable-imenu t + "If non-nil, automatically enable `imenu' integration when server provides +`textDocument/documentSymbol'." + :type 'boolean + :group 'lsp-mode + :package-version '(lsp-mode . "6.2")) + +(defcustom lsp-enable-dap-auto-configure t + "If non-nil, enable `dap-auto-configure-mode`." + :type 'boolean + :group 'lsp-mode + :package-version '(lsp-mode . "7.0")) + +(defcustom lsp-eldoc-enable-hover t + "If non-nil, `eldoc' will display hover info when it is present." + :type 'boolean + :group 'lsp-mode) + +(defcustom lsp-eldoc-render-all nil + "Display all of the info returned by document/onHover. +If this is set to nil, `eldoc' will show only the symbol information." + :type 'boolean + :group 'lsp-mode) + +(define-obsolete-variable-alias 'lsp-enable-completion-at-point + 'lsp-completion-enable "lsp-mode 7.0.1") + +(defcustom lsp-completion-enable t + "Enable `completion-at-point' integration." + :type 'boolean + :group 'lsp-completion) + +(defcustom lsp-enable-symbol-highlighting t + "Highlight references of the symbol at point." + :type 'boolean + :group 'lsp-mode) + +(defcustom lsp-enable-xref t + "Enable xref integration." + :type 'boolean + :group 'lsp-mode) + +(defcustom lsp-references-exclude-definition nil + "If non-nil, exclude declarations when finding references." + :type 'boolean + :group 'lsp-mode) + +(defcustom lsp-enable-indentation t + "Indent regions using the file formatting functionality provided by the +language server." + :type 'boolean + :group 'lsp-mode) + +(defcustom lsp-enable-on-type-formatting t + "Enable `textDocument/onTypeFormatting' integration." + :type 'boolean + :group 'lsp-mode) + +(defcustom lsp-enable-text-document-color t + "Enable `textDocument/documentColor' integration." + :type 'boolean + :group 'lsp-mode) + +(defcustom lsp-before-save-edits t + "If non-nil, `lsp-mode' will apply edits suggested by the language server +before saving a document." + :type 'boolean + :group 'lsp-mode) + +(defcustom lsp-after-apply-edits-hook nil + "Hooks to run when text edit is applied. +It contains the operation source." + :type 'hook + :group 'lsp-mode + :package-version '(lsp-mode . "8.0.0")) + +(defcustom lsp-apply-edits-after-file-operations t + "Whether to apply edits returned by server after file operations if any. +Applicable only if server supports workspace.fileOperations for operations: +`workspace/willRenameFiles', `workspace/willCreateFiles' and +`workspace/willDeleteFiles'." + :group 'lsp-mode + :type 'boolean) + +(defcustom lsp-modeline-code-actions-enable t + "Whether to show code actions on modeline." + :type 'boolean + :group 'lsp-modeline) + +(defcustom lsp-modeline-diagnostics-enable t + "Whether to show diagnostics on modeline." + :type 'boolean + :group 'lsp-modeline) + +(defcustom lsp-modeline-workspace-status-enable t + "Whether to show workspace status on modeline." + :type 'boolean + :group 'lsp-modeline + :package-version '(lsp-mode . "8.0.0")) + +(defcustom lsp-headerline-breadcrumb-enable t + "Whether to enable breadcrumb on headerline." + :type 'boolean + :group 'lsp-headerline) + +(defcustom lsp-configure-hook nil + "Hooks to run when `lsp-configure-buffer' is called." + :type 'hook + :group 'lsp-mode) + +(defcustom lsp-unconfigure-hook nil + "Hooks to run when `lsp-unconfig-buffer' is called." + :type 'hook + :group 'lsp-mode) + +(defcustom lsp-after-diagnostics-hook nil + "Hooks to run after diagnostics are received. +Note: it runs only if the receiving buffer is open. Use +`lsp-diagnostics-updated-hook'if you want to be notified when +diagnostics have changed." + :type 'hook + :group 'lsp-mode) + +(define-obsolete-variable-alias 'lsp-after-diagnostics-hook + 'lsp-diagnostics-updated-hook "lsp-mode 6.4") + +(defcustom lsp-diagnostics-updated-hook nil + "Hooks to run after diagnostics are received." + :type 'hook + :group 'lsp-mode) + +(define-obsolete-variable-alias 'lsp-workspace-folders-changed-hook + 'lsp-workspace-folders-changed-functions "lsp-mode 6.3") + +(defcustom lsp-workspace-folders-changed-functions nil + "Hooks to run after the folders has changed. +The hook will receive two parameters list of added and removed folders." + :type 'hook + :group 'lsp-mode) + +(define-obsolete-variable-alias 'lsp-eldoc-hook 'eldoc-documentation-functions "lsp-mode 9.0.0") + +(defcustom lsp-before-apply-edits-hook nil + "Hooks to run before applying edits." + :type 'hook + :group 'lsp-mode) + +(defgroup lsp-imenu nil + "LSP Imenu." + :group 'lsp-mode + :tag "LSP Imenu") + +(defcustom lsp-imenu-show-container-name t + "Display the symbol's container name in an imenu entry." + :type 'boolean + :group 'lsp-imenu) + +(defcustom lsp-imenu-container-name-separator "/" + "Separator string to use to separate the container name from the symbol while +displaying imenu entries." + :type 'string + :group 'lsp-imenu) + +(defcustom lsp-imenu-sort-methods '(kind name) + "How to sort the imenu items. + +The value is a list of `kind' `name' or `position'. Priorities +are determined by the index of the element." + :type '(repeat (choice (const name) + (const position) + (const kind))) + :group 'lsp-imenu) + +(defcustom lsp-imenu-index-symbol-kinds nil + "Which symbol kinds to show in imenu." + :type '(repeat (choice (const :tag "Miscellaneous" nil) + (const :tag "File" File) + (const :tag "Module" Module) + (const :tag "Namespace" Namespace) + (const :tag "Package" Package) + (const :tag "Class" Class) + (const :tag "Method" Method) + (const :tag "Property" Property) + (const :tag "Field" Field) + (const :tag "Constructor" Constructor) + (const :tag "Enum" Enum) + (const :tag "Interface" Interface) + (const :tag "Function" Function) + (const :tag "Variable" Variable) + (const :tag "Constant" Constant) + (const :tag "String" String) + (const :tag "Number" Number) + (const :tag "Boolean" Boolean) + (const :tag "Array" Array) + (const :tag "Object" Object) + (const :tag "Key" Key) + (const :tag "Null" Null) + (const :tag "Enum Member" EnumMember) + (const :tag "Struct" Struct) + (const :tag "Event" Event) + (const :tag "Operator" Operator) + (const :tag "Type Parameter" TypeParameter))) + :group 'lsp-imenu) + +;; vibhavp: Should we use a lower value (5)? +(defcustom lsp-response-timeout 10 + "Number of seconds to wait for a response from the language server before +timing out. Nil if no timeout." + :type '(choice + (number :tag "Seconds") + (const :tag "No timeout" nil)) + :group 'lsp-mode) + +(defcustom lsp-tcp-connection-timeout 2 + "The timeout for tcp connection in seconds." + :type 'number + :group 'lsp-mode + :package-version '(lsp-mode . "6.2")) + +(defconst lsp--imenu-compare-function-alist + (list (cons 'name #'lsp--imenu-compare-name) + (cons 'kind #'lsp--imenu-compare-kind) + (cons 'position #'lsp--imenu-compare-line-col)) + "An alist of (METHOD . FUNCTION). +METHOD is one of the symbols accepted by +`lsp-imenu-sort-methods'. + +FUNCTION takes two hash tables representing DocumentSymbol. It +returns a negative number, 0, or a positive number indicating +whether the first parameter is less than, equal to, or greater +than the second parameter.") + +(defcustom lsp-diagnostic-clean-after-change nil + "When non-nil, clean the diagnostics on change. + +Note that when that setting is nil, `lsp-mode' will show stale +diagnostics until server publishes the new set of diagnostics" + :type 'boolean + :group 'lsp-diagnostics + :package-version '(lsp-mode . "7.0.1")) + +(defcustom lsp-server-trace nil + "Request tracing on the server side. +The actual trace output at each level depends on the language server in use. +Changes take effect only when a new session is started." + :type '(choice (const :tag "Disabled" "off") + (const :tag "Messages only" "messages") + (const :tag "Verbose" "verbose") + (const :tag "Default (disabled)" nil)) + :group 'lsp-mode + :package-version '(lsp-mode . "6.1")) + +(defcustom lsp-auto-touch-files t + "If non-nil ensure the files exist before sending +`textDocument/didOpen' notification." + :type 'boolean + :group 'lsp-mode + :package-version '(lsp-mode . "9.0.0")) + +(defvar lsp-language-id-configuration + '(("\\(^CMakeLists\\.txt\\|\\.cmake\\)\\'" . "cmake") + ("\\(^Dockerfile\\(?:\\..*\\)?\\|\\.[Dd]ockerfile\\)\\'" . "dockerfile") + ("\\.astro$" . "astro") + ("\\.cs\\'" . "csharp") + ("\\.css$" . "css") + ("\\.cypher$" . "cypher") + ("Earthfile" . "earthfile") + ("\\.ebuild$" . "shellscript") + ("\\.go\\'" . "go") + ("\\.html$" . "html") + ("\\.hx$" . "haxe") + ("\\.hy$" . "hy") + ("\\.java\\'" . "java") + ("\\.jq$" . "jq") + ("\\.js$" . "javascript") + ("\\.json$" . "json") + ("\\.jsonc$" . "jsonc") + ("\\.jsonnet$" . "jsonnet") + ("\\.jsx$" . "javascriptreact") + ("\\.lua$" . "lua") + ("\\.mdx\\'" . "mdx") + ("\\.nu$" . "nushell") + ("\\.php$" . "php") + ("\\.ps[dm]?1\\'" . "powershell") + ("\\.rs\\'" . "rust") + ("\\.spec\\'" . "rpm-spec") + ("\\.sql$" . "sql") + ("\\.svelte$" . "svelte") + ("\\.toml\\'" . "toml") + ("\\.ts$" . "typescript") + ("\\.tsx$" . "typescriptreact") + ("\\.ttcn3$" . "ttcn3") + ("\\.vue$" . "vue") + ("\\.xml$" . "xml") + ("\\ya?ml$" . "yaml") + ("^PKGBUILD$" . "shellscript") + ("^go\\.mod\\'" . "go.mod") + ("^settings\\.json$" . "jsonc") + ("^yang\\.settings$" . "jsonc") + ("^meson\\(_options\\.txt\\|\\.\\(build\\|format\\)\\)\\'" . "meson") + (ada-mode . "ada") + (ada-ts-mode . "ada") + (gpr-mode . "gpr") + (gpr-ts-mode . "gpr") + (awk-mode . "awk") + (awk-ts-mode . "awk") + (nxml-mode . "xml") + (sql-mode . "sql") + (vimrc-mode . "vim") + (vimscript-ts-mode . "vim") + (sh-mode . "shellscript") + (bash-ts-mode . "shellscript") + (ebuild-mode . "shellscript") + (pkgbuild-mode . "shellscript") + (envrc-file-mode . "shellscript") + (scala-mode . "scala") + (scala-ts-mode . "scala") + (julia-mode . "julia") + (julia-ts-mode . "julia") + (clojure-mode . "clojure") + (clojurec-mode . "clojure") + (clojurescript-mode . "clojurescript") + (clojure-ts-mode . "clojure") + (clojure-ts-clojurec-mode . "clojure") + (clojure-ts-clojurescript-mode . "clojurescript") + (java-mode . "java") + (java-ts-mode . "java") + (jdee-mode . "java") + (groovy-mode . "groovy") + (python-mode . "python") + (python-ts-mode . "python") + (cython-mode . "python") + ("\\(\\.mojo\\|\\.🔥\\)\\'" . "mojo") + (lsp--render-markdown . "markdown") + (move-mode . "move") + (rust-mode . "rust") + (rust-ts-mode . "rust") + (rustic-mode . "rust") + (kotlin-mode . "kotlin") + (kotlin-ts-mode . "kotlin") + (css-mode . "css") + (css-ts-mode . "css") + (less-mode . "less") + (less-css-mode . "less") + (lua-mode . "lua") + (lua-ts-mode . "lua") + (sass-mode . "sass") + (ssass-mode . "sass") + (scss-mode . "scss") + (scad-mode . "openscad") + (xml-mode . "xml") + (c-mode . "c") + (c-ts-mode . "c") + (c++-mode . "cpp") + (c++-ts-mode . "cpp") + (cuda-mode . "cuda") + (objc-mode . "objective-c") + (html-mode . "html") + (html-ts-mode . "html") + (sgml-mode . "html") + (mhtml-mode . "html") + (mint-mode . "mint") + (go-dot-mod-mode . "go.mod") + (go-mod-ts-mode . "go.mod") + (go-mode . "go") + (go-ts-mode . "go") + (graphql-mode . "graphql") + (haskell-mode . "haskell") + (haskell-ts-mode . "haskell") + (hack-mode . "hack") + (php-mode . "php") + (php-ts-mode . "php") + (powershell-mode . "powershell") + (powershell-mode . "PowerShell") + (powershell-ts-mode . "powershell") + (json-mode . "json") + (json-ts-mode . "json") + (jsonc-mode . "jsonc") + (rjsx-mode . "javascript") + (js2-mode . "javascript") + (js-mode . "javascript") + (js-ts-mode . "javascript") + (typescript-mode . "typescript") + (typescript-ts-mode . "typescript") + (tsx-ts-mode . "typescriptreact") + (svelte-mode . "svelte") + (fsharp-mode . "fsharp") + (reason-mode . "reason") + (caml-mode . "ocaml") + (tuareg-mode . "ocaml") + (futhark-mode . "futhark") + (swift-mode . "swift") + (elixir-mode . "elixir") + (elixir-ts-mode . "elixir") + (heex-ts-mode . "elixir") + (conf-javaprop-mode . "spring-boot-properties") + (yaml-mode . "yaml") + (yaml-ts-mode . "yaml") + (ruby-mode . "ruby") + (enh-ruby-mode . "ruby") + (ruby-ts-mode . "ruby") + (feature-mode . "cucumber") + (fortran-mode . "fortran") + (f90-mode . "fortran") + (elm-mode . "elm") + (dart-mode . "dart") + (erlang-mode . "erlang") + (dockerfile-mode . "dockerfile") + (dockerfile-ts-mode . "dockerfile") + (csharp-mode . "csharp") + (csharp-tree-sitter-mode . "csharp") + (csharp-ts-mode . "csharp") + (plain-tex-mode . "plaintex") + (context-mode . "context") + (cypher-mode . "cypher") + (latex-mode . "latex") + (LaTeX-mode . "latex") + (v-mode . "v") + (vhdl-mode . "vhdl") + (vhdl-ts-mode . "vhdl") + (verilog-mode . "verilog") + (terraform-mode . "terraform") + (ess-julia-mode . "julia") + (ess-r-mode . "r") + (crystal-mode . "crystal") + (nim-mode . "nim") + (dhall-mode . "dhall") + (cmake-mode . "cmake") + (cmake-ts-mode . "cmake") + (purescript-mode . "purescript") + (gdscript-mode . "gdscript") + (gdscript-ts-mode . "gdscript") + (perl-mode . "perl") + (cperl-mode . "perl") + (robot-mode . "robot") + (racket-mode . "racket") + (nix-mode . "nix") + (nix-ts-mode . "nix") + (prolog-mode . "prolog") + (vala-mode . "vala") + (actionscript-mode . "actionscript") + (d-mode . "d") + (zig-mode . "zig") + (text-mode . "plaintext") + (markdown-mode . "markdown") + (gfm-mode . "markdown") + (beancount-mode . "beancount") + (conf-toml-mode . "toml") + (toml-ts-mode . "toml") + (org-mode . "org") + (org-journal-mode . "org") + (nginx-mode . "nginx") + (magik-mode . "magik") + (magik-ts-mode . "magik") + (idris-mode . "idris") + (idris2-mode . "idris2") + (gleam-mode . "gleam") + (gleam-ts-mode . "gleam") + (graphviz-dot-mode . "dot") + (tiltfile-mode . "tiltfile") + (solidity-mode . "solidity") + (bibtex-mode . "bibtex") + (rst-mode . "restructuredtext") + (glsl-mode . "glsl") + (shader-mode . "shaderlab") + (wgsl-mode . "wgsl") + (jq-mode . "jq") + (jq-ts-mode . "jq") + (protobuf-mode . "protobuf") + (nushell-mode . "nushell") + (nushell-ts-mode . "nushell") + (meson-mode . "meson") + (yang-mode . "yang")) + "Language id configuration.") + +(defvar lsp--last-active-workspaces nil + "Keep track of last active workspace. +We want to try the last workspace first when jumping into a library +directory") + +(defvar lsp-method-requirements + '(("textDocument/callHierarchy" :capability :callHierarchyProvider) + ("textDocument/codeAction" :capability :codeActionProvider) + ("codeAction/resolve" + :check-command (lambda (workspace) + (with-lsp-workspace workspace + (lsp:code-action-options-resolve-provider? + (lsp--capability-for-method "textDocument/codeAction"))))) + ("textDocument/codeLens" :capability :codeLensProvider) + ("textDocument/completion" :capability :completionProvider) + ("completionItem/resolve" + :check-command (lambda (wk) + (with-lsp-workspace wk + (lsp:completion-options-resolve-provider? + (lsp--capability-for-method "textDocument/completion"))))) + ("textDocument/declaration" :capability :declarationProvider) + ("textDocument/definition" :capability :definitionProvider) + ("textDocument/documentColor" :capability :colorProvider) + ("textDocument/documentLink" :capability :documentLinkProvider) + ("textDocument/inlayHint" :capability :inlayHintProvider) + ("textDocument/documentHighlight" :capability :documentHighlightProvider) + ("textDocument/documentSymbol" :capability :documentSymbolProvider) + ("textDocument/foldingRange" :capability :foldingRangeProvider) + ("textDocument/formatting" :capability :documentFormattingProvider) + ("textDocument/hover" :capability :hoverProvider) + ("textDocument/implementation" :capability :implementationProvider) + ("textDocument/linkedEditingRange" :capability :linkedEditingRangeProvider) + ("textDocument/onTypeFormatting" :capability :documentOnTypeFormattingProvider) + ("textDocument/prepareRename" + :check-command (lambda (workspace) + (with-lsp-workspace workspace + (lsp:rename-options-prepare-provider? + (lsp--capability-for-method "textDocument/rename"))))) + ("textDocument/rangeFormatting" :capability :documentRangeFormattingProvider) + ("textDocument/references" :capability :referencesProvider) + ("textDocument/rename" :capability :renameProvider) + ("textDocument/selectionRange" :capability :selectionRangeProvider) + ("textDocument/semanticTokens" :capability :semanticTokensProvider) + ("textDocument/semanticTokensFull" + :check-command (lambda (workspace) + (with-lsp-workspace workspace + (lsp-get (lsp--capability :semanticTokensProvider) :full)))) + ("textDocument/semanticTokensFull/Delta" + :check-command (lambda (workspace) + (with-lsp-workspace workspace + (let ((capFull (lsp-get (lsp--capability :semanticTokensProvider) :full))) + (and (not (booleanp capFull)) (lsp-get capFull :delta)))))) + ("textDocument/semanticTokensRangeProvider" + :check-command (lambda (workspace) + (with-lsp-workspace workspace + (lsp-get (lsp--capability :semanticTokensProvider) :range)))) + ("textDocument/signatureHelp" :capability :signatureHelpProvider) + ("textDocument/typeDefinition" :capability :typeDefinitionProvider) + ("textDocument/typeHierarchy" :capability :typeHierarchyProvider) + ("textDocument/diagnostic" :capability :diagnosticProvider) + ("workspace/executeCommand" :capability :executeCommandProvider) + ("workspace/symbol" :capability :workspaceSymbolProvider)) + + "Map methods to requirements. +It is used by request-sending functions to determine which server +must be used for handling a particular message.") + +(defconst lsp--file-change-type + `((created . 1) + (changed . 2) + (deleted . 3))) + +(defconst lsp--watch-kind + `((create . 1) + (change . 2) + (delete . 4))) + +(defvar lsp-window-body-width 40 + "Window body width when rendering doc.") + +(defface lsp-face-highlight-textual + '((t :inherit highlight)) + "Face used for textual occurrences of symbols." + :group 'lsp-mode) + +(defface lsp-face-highlight-read + '((t :inherit highlight :underline t)) + "Face used for highlighting symbols being read." + :group 'lsp-mode) + +(defface lsp-face-highlight-write + '((t :inherit highlight :weight bold)) + "Face used for highlighting symbols being written to." + :group 'lsp-mode) + +(define-obsolete-variable-alias 'lsp-lens-auto-enable + 'lsp-lens-enable "lsp-mode 7.0.1") + +(defcustom lsp-lens-enable t + "Auto enable lenses if server supports." + :group 'lsp-lens + :type 'boolean + :package-version '(lsp-mode . "6.3")) + +(defcustom lsp-symbol-highlighting-skip-current nil + "If non-nil skip current symbol when setting symbol highlights." + :group 'lsp-mode + :type 'boolean) + +(defcustom lsp-file-watch-threshold 1000 + "Show warning if the files to watch are more than. +Set to nil to disable the warning." + :type 'number + :group 'lsp-mode) +;;;###autoload(put 'lsp-file-watch-threshold 'safe-local-variable (lambda (i) (or (numberp i) (not i)))) + +(defvar lsp-custom-markup-modes + '((rust-mode "no_run" "rust,no_run" "rust,ignore" "rust,should_panic")) + "Mode to uses with markdown code blocks. +They are added to `markdown-code-lang-modes'") + +(defcustom lsp-signature-render-documentation t + "Display signature documentation in `eldoc'." + :type 'boolean + :group 'lsp-mode + :package-version '(lsp-mode . "6.2")) + +(defcustom lsp-signature-auto-activate '(:on-trigger-char :on-server-request) + "Auto activate signature conditions." + :type '(repeat (choice (const :tag "On trigger chars pressed." :on-trigger-char) + (const :tag "After selected completion." :after-completion) + (const :tag "When the server has sent show signature help." :on-server-request))) + :group 'lsp-mode + :package-version '(lsp-mode . "6.2")) + +(defcustom lsp-signature-doc-lines 20 + "If number, limit the number of lines to show in the docs." + :type 'number + :group 'lsp-mode + :package-version '(lsp-mode . "6.3")) + +(defcustom lsp-signature-function 'lsp-lv-message + "The function used for displaying signature info. +It will be called with one param - the signature info. When +called with nil the signature info must be cleared." + :type 'function + :group 'lsp-mode + :package-version '(lsp-mode . "6.3")) + +(defcustom lsp-keymap-prefix "s-l" + "LSP-mode keymap prefix." + :group 'lsp-mode + :type 'string + :package-version '(lsp-mode . "6.3")) + +(defvar-local lsp--buffer-workspaces () + "List of the buffer workspaces.") + +(defvar-local lsp--buffer-deferred nil + "Whether buffer was loaded via `lsp-deferred'.") + +(defvar lsp--session nil + "Contain the `lsp-session' for the current Emacs instance.") + +(defvar lsp--tcp-port 10000) + +(defvar lsp--client-packages-required nil + "If nil, `lsp-client-packages' are yet to be required.") + +(defvar lsp--tcp-server-port 0 + "The server socket which is opened when using `lsp-tcp-server' (a server +socket is opened in Emacs and the language server connects to it). The +default value of 0 ensures that a random high port is used. Set it to a positive +integer to use a specific port.") + +(defvar lsp--tcp-server-wait-seconds 10 + "Wait this amount of time for the client to connect to our server socket +when using `lsp-tcp-server'.") + +(defvar-local lsp--document-symbols nil + "The latest document symbols.") + +(defvar-local lsp--document-selection-range-cache nil + "The document selection cache.") + +(defvar-local lsp--document-symbols-request-async nil + "If non-nil, request document symbols asynchronously.") + +(defvar-local lsp--document-symbols-tick -1 + "The value of `buffer-chars-modified-tick' when document + symbols were last retrieved.") + +(defvar-local lsp--have-document-highlights nil + "Set to `t' on symbol highlighting, cleared on +`lsp--cleanup-highlights-if-needed'. Checking a separately +defined flag is substantially faster than unconditionally +calling `remove-overlays'.") + +;; Buffer local variable for storing number of lines. +(defvar lsp--log-lines) + +(defvar-local lsp--eldoc-saved-message nil) + +(defvar lsp--on-change-timer nil) +(defvar lsp--on-idle-timer nil) + +(defvar-local lsp--signature-last nil) +(defvar-local lsp--signature-last-index nil) +(defvar lsp--signature-last-buffer nil) + +(defvar-local lsp--virtual-buffer-point-max nil) + +(cl-defmethod lsp-execute-command (_server _command _arguments) + "Ask SERVER to execute COMMAND with ARGUMENTS.") + +(defun lsp-elt (sequence n) + "Return Nth element of SEQUENCE or nil if N is out of range." + (cond + ((listp sequence) (elt sequence n)) + ((arrayp sequence) + (and (> (length sequence) n) (aref sequence n))) + (t (and (> (length sequence) n) (elt sequence n))))) + +;; define seq-first and seq-rest for older emacs +(defun lsp-seq-first (sequence) + "Return the first element of SEQUENCE." + (lsp-elt sequence 0)) + +(defun lsp-seq-rest (sequence) + "Return a sequence of the elements of SEQUENCE except the first one." + (seq-drop sequence 1)) + +;;;###autoload +(defun lsp--string-listp (sequence) + "Return t if all elements of SEQUENCE are strings, else nil." + (not (seq-find (lambda (x) (not (stringp x))) sequence))) + +(defun lsp--string-vector-p (candidate) + "Returns true if CANDIDATE is a vector data structure and +every element of it is of type string, else nil." + (and + (vectorp candidate) + (seq-every-p #'stringp candidate))) + +(make-obsolete 'lsp--string-vector-p nil "lsp-mode 8.0.0") + +(defun lsp--editable-vector-match (widget value) + "Function for `lsp-editable-vector' :match." + ;; Value must be a list or a vector and all the members must match the type. + (and (or (listp value) (vectorp value)) + (length (cdr (lsp--editable-vector-match-inline widget value))))) + +(defun lsp--editable-vector-match-inline (widget value) + "Value for `lsp-editable-vector' :match-inline." + (let ((type (nth 0 (widget-get widget :args))) + (ok t) + found) + (while (and value ok) + (let ((answer (widget-match-inline type value))) + (if answer + (let ((head (if (vectorp answer) (aref answer 0) (car answer))) + (tail (if (vectorp answer) (seq-drop 1 answer) (cdr answer)))) + (setq found (append found head) + value tail)) + (setq ok nil)))) + (cons found value))) + +(defun lsp--editable-vector-value-to-external (_widget internal-value) + "Convert the internal list value to a vector." + (if (listp internal-value) + (apply 'vector internal-value) + internal-value)) + +(defun lsp--editable-vector-value-to-internal (_widget external-value) + "Convert the external vector value to a list." + (if (vectorp external-value) + (append external-value nil) + external-value)) + +(define-widget 'lsp--editable-vector 'editable-list + "A subclass of `editable-list' that accepts and returns a +vector instead of a list." + :value-to-external 'lsp--editable-vector-value-to-external + :value-to-internal 'lsp--editable-vector-value-to-internal + :match 'lsp--editable-vector-match + :match-inline 'lsp--editable-vector-match-inline) + +(define-widget 'lsp-repeatable-vector 'lsp--editable-vector + "A variable length homogeneous vector." + :tag "Repeat" + :format "%{%t%}:\n%v%i\n") + +(define-widget 'lsp-string-vector 'lazy + "A vector of zero or more elements, every element of which is a string. +Appropriate for any language-specific `defcustom' that needs to +serialize as a JSON array of strings. + +Deprecated. Use `lsp-repeatable-vector' instead. " + :offset 4 + :tag "Vector" + :type '(lsp-repeatable-vector string)) + +(make-obsolete 'lsp-string-vector nil "lsp-mode 8.0.0") + +(defvar lsp--show-message t + "If non-nil, show debug message from `lsp-mode'.") + +(defun lsp--message (format &rest args) + "Wrapper for `message' + +We `inhibit-message' the message when the cursor is in the +minibuffer and when emacs version is before emacs 27 due to the +fact that we often use `lsp--info', `lsp--warn' and `lsp--error' +in async context and the call to these function is removing the +minibuffer prompt. The issue with async messages is already fixed +in emacs 27. + +See #2049" + (when lsp--show-message + (let ((inhibit-message (or inhibit-message + (and (minibufferp) + (version< emacs-version "27.0"))))) + (apply #'message format args)))) + +(defun lsp--info (format &rest args) + "Display lsp info message with FORMAT with ARGS." + (lsp--message "%s :: %s" (propertize "LSP" 'face 'success) (apply #'format format args))) + +(defun lsp--warn (format &rest args) + "Display lsp warn message with FORMAT with ARGS." + (lsp--message "%s :: %s" (propertize "LSP" 'face 'warning) (apply #'format format args))) + +(defun lsp--error (format &rest args) + "Display lsp error message with FORMAT with ARGS." + (lsp--message "%s :: %s" (propertize "LSP" 'face 'error) (apply #'format format args))) + +(defun lsp-log (format &rest args) + "Log message to the ’*lsp-log*’ buffer. + +FORMAT and ARGS i the same as for `message'." + (when lsp-log-max + (let ((log-buffer (get-buffer "*lsp-log*")) + (inhibit-read-only t)) + (unless log-buffer + (setq log-buffer (get-buffer-create "*lsp-log*")) + (with-current-buffer log-buffer + (buffer-disable-undo) + (view-mode 1) + (set (make-local-variable 'lsp--log-lines) 0))) + (with-current-buffer log-buffer + (save-excursion + (let* ((message (apply 'format format args)) + ;; Count newlines in message. + (newlines (1+ (cl-loop with start = 0 + for count from 0 + while (string-match "\n" message start) + do (setq start (match-end 0)) + finally return count)))) + (goto-char (point-max)) + + ;; in case the buffer is not empty insert before last \n to preserve + ;; the point position(in case it is in the end) + (if (eq (point) (point-min)) + (progn + (insert "\n") + (backward-char)) + (backward-char) + (insert "\n")) + (insert message) + + (setq lsp--log-lines (+ lsp--log-lines newlines)) + + (when (and (integerp lsp-log-max) (> lsp--log-lines lsp-log-max)) + (let ((to-delete (- lsp--log-lines lsp-log-max))) + (goto-char (point-min)) + (forward-line to-delete) + (delete-region (point-min) (point)) + (setq lsp--log-lines lsp-log-max))))))))) + +(defalias 'lsp-message 'lsp-log) + +(defalias 'lsp-ht 'ht) + +(defalias 'lsp-file-local-name 'file-local-name) + +(defun lsp-f-canonical (file-name) + "Return the canonical FILE-NAME, without a trailing slash." + (directory-file-name (expand-file-name file-name))) + +(defalias 'lsp-canonical-file-name 'lsp-f-canonical) + +(defun lsp-f-same? (path-a path-b) + "Return t if PATH-A and PATH-B are references to the same file. +Symlinks are not followed." + (when (and (f-exists? path-a) + (f-exists? path-b)) + (equal + (lsp-f-canonical (directory-file-name (f-expand path-a))) + (lsp-f-canonical (directory-file-name (f-expand path-b)))))) + +(defun lsp-f-parent (path) + "Return the parent directory to PATH. +Symlinks are not followed." + (let ((parent (file-name-directory + (directory-file-name (f-expand path default-directory))))) + (unless (lsp-f-same? path parent) + (if (f-relative? path) + (f-relative parent) + (directory-file-name parent))))) + +(defun lsp-f-ancestor-of? (path-a path-b) + "Return t if PATH-A is an ancestor of PATH-B. +Symlinks are not followed." + (unless (lsp-f-same? path-a path-b) + (s-prefix? (concat (lsp-f-canonical path-a) (f-path-separator)) + (lsp-f-canonical path-b)))) + +(defun lsp--merge-results (results method) + "Merge RESULTS by filtering the empty hash-tables and merging +the lists according to METHOD." + (pcase (--map (if (vectorp it) + (append it nil) it) + (-filter #'identity results)) + (`() ()) + ;; only one result - simply return it + (`(,fst) fst) + ;; multiple results merge it based on strategy + (results + (pcase method + ("textDocument/hover" (pcase (seq-filter + (-compose #'not #'lsp-empty?) + results) + (`(,hover) hover) + (hovers (lsp-make-hover + :contents + (-mapcat + (-lambda ((&Hover :contents)) + (if (and (sequencep contents) + (not (stringp contents))) + (append contents ()) + (list contents))) + hovers))))) + ("textDocument/completion" + (lsp-make-completion-list + :is-incomplete (seq-some + #'lsp:completion-list-is-incomplete + results) + :items (cl-mapcan (lambda (it) (append (if (lsp-completion-list? it) + (lsp:completion-list-items it) + it) + nil)) + results))) + ("completionItem/resolve" + (let ((item (cl-first results))) + (when-let ((details (seq-filter #'identity + (seq-map #'lsp:completion-item-detail? results)))) + (lsp:set-completion-item-detail? + item + (string-join details " "))) + (when-let ((docs (seq-filter #'identity + (seq-map #'lsp:completion-item-documentation? results)))) + (lsp:set-completion-item-documentation? + item + (lsp-make-markup-content + :kind (or (seq-some (lambda (it) + (when (equal (lsp:markup-content-kind it) + lsp/markup-kind-markdown) + lsp/markup-kind-markdown)) + docs) + lsp/markup-kind-plain-text) + :value (string-join (seq-map (lambda (doc) + (or (lsp:markup-content-value doc) + (and (stringp doc) doc))) + docs) + "\n")))) + (when-let ((edits (seq-filter #'identity + (seq-map #'lsp:completion-item-additional-text-edits? results)))) + (lsp:set-completion-item-additional-text-edits? + item + (cl-mapcan (lambda (it) (if (seqp it) it (list it))) edits))) + item)) + (_ (cl-mapcan (lambda (it) (if (seqp it) it (list it))) results)))))) + +(defun lsp--spinner-start () + "Start spinner indication." + (condition-case _err (spinner-start (lsp-progress-spinner-type)) (error))) + +(defun lsp--propertize (str type) + "Propertize STR as per TYPE." + (propertize str 'face (alist-get type lsp--message-type-face))) + +(defun lsp-workspaces () + "Return the lsp workspaces associated with the current project." + (if lsp--cur-workspace (list lsp--cur-workspace) lsp--buffer-workspaces)) + +(defun lsp--completing-read (prompt collection transform-fn &optional predicate + require-match initial-input + hist def inherit-input-method) + "Wrap `completing-read' to provide transformation function and disable sort. + +TRANSFORM-FN will be used to transform each of the items before displaying. + +PROMPT COLLECTION PREDICATE REQUIRE-MATCH INITIAL-INPUT HIST DEF +INHERIT-INPUT-METHOD will be proxied to `completing-read' without changes." + (let* ((col (--map (cons (funcall transform-fn it) it) collection)) + (completion (completing-read prompt + (lambda (string pred action) + (if (eq action 'metadata) + `(metadata (display-sort-function . identity)) + (complete-with-action action col string pred))) + predicate require-match initial-input hist + def inherit-input-method))) + (cdr (assoc completion col)))) + +(defconst lsp--system-arch (lambda () + (setq lsp--system-arch + (pcase system-type + ('windows-nt + (pcase system-configuration + ((rx bol "x86_64-") 'x64) + (_ 'x86))) + ('darwin + (pcase system-configuration + ((rx "aarch64-") 'arm64) + (_ 'x64))) + ('gnu/linux + (pcase system-configuration + ((rx bol "aarch64-") 'arm64) + ((rx bol "x86_64") 'x64) + ((rx bol (| "i386" "i886")) 'x32))) + (_ + (pcase system-configuration + ((rx bol "x86_64") 'x64) + ((rx bol (| "i386" "i886")) 'x32)))))) + "Return the system architecture of `Emacs'. +Special values: + `x64' 64bit + `x32' 32bit + `arm64' ARM 64bit") + +(defmacro lsp-with-current-buffer (buffer-id &rest body) + (declare (indent 1) (debug t)) + `(if-let ((wcb (plist-get ,buffer-id :with-current-buffer))) + (with-lsp-workspaces (plist-get ,buffer-id :workspaces) + (funcall wcb (lambda () ,@body))) + (with-current-buffer ,buffer-id + ,@body))) + +(defvar lsp--throw-on-input nil + "Make `lsp-*-while-no-input' throws `input' on interrupted.") + +(defmacro lsp--catch (tag bodyform &rest handlers) + "Catch TAG thrown in BODYFORM. +The return value from TAG will be handled in HANDLERS by `pcase'." + (declare (debug (form form &rest (pcase-PAT body))) (indent 2)) + (let ((re-sym (make-symbol "re"))) + `(let ((,re-sym (catch ,tag ,bodyform))) + (pcase ,re-sym + ,@handlers)))) + +(defmacro lsp--while-no-input (&rest body) + "Wrap BODY in `while-no-input' and respecting `non-essential'. +If `lsp--throw-on-input' is set, will throw if input is pending, else +return value of `body' or nil if interrupted." + (declare (debug t) (indent 0)) + `(if non-essential + (let ((res (while-no-input ,@body))) + (cond + ((and lsp--throw-on-input (equal res t)) + (throw 'input :interrupted)) + ((booleanp res) nil) + (t res))) + ,@body)) + +;; A ‘lsp--client’ object describes the client-side behavior of a language +;; server. It is used to start individual server processes, each of which is +;; represented by a ‘lsp--workspace’ object. Client objects are normally +;; created using ‘lsp-define-stdio-client’ or ‘lsp-define-tcp-client’. Each +;; workspace refers to exactly one client, but there can be multiple workspaces +;; for a single client. +(cl-defstruct lsp--client + ;; ‘language-id’ is a function that receives a buffer as a single argument + ;; and should return the language identifier for that buffer. See + ;; https://microsoft.github.io/language-server-protocol/specification#textdocumentitem + ;; for a list of language identifiers. Also consult the documentation for + ;; the language server represented by this client to find out what language + ;; identifiers it supports or expects. + (language-id nil) + + ;; ‘add-on?’ when set to t the server will be started no matter whether there + ;; is another server handling the same mode. + (add-on? nil) + ;; ‘new-connection’ is a function that should start a language server process + ;; and return a cons (COMMAND-PROCESS . COMMUNICATION-PROCESS). + ;; COMMAND-PROCESS must be a process object representing the server process + ;; just started. COMMUNICATION-PROCESS must be a process (including pipe and + ;; network processes) that ‘lsp-mode’ uses to communicate with the language + ;; server using the language server protocol. COMMAND-PROCESS and + ;; COMMUNICATION-PROCESS may be the same process; in that case + ;; ‘new-connection’ may also return that process as a single + ;; object. ‘new-connection’ is called with two arguments, FILTER and + ;; SENTINEL. FILTER should be used as process filter for + ;; COMMUNICATION-PROCESS, and SENTINEL should be used as process sentinel for + ;; COMMAND-PROCESS. + (new-connection nil) + + ;; ‘ignore-regexps’ is a list of regexps. When a data packet from the + ;; language server matches any of these regexps, it will be ignored. This is + ;; intended for dealing with language servers that output non-protocol data. + (ignore-regexps nil) + + ;; ‘ignore-messages’ is a list of regexps. When a message from the language + ;; server matches any of these regexps, it will be ignored. This is useful + ;; for filtering out unwanted messages; such as servers that send nonstandard + ;; message types, or extraneous log messages. + (ignore-messages nil) + + ;; ‘notification-handlers’ is a hash table mapping notification method names + ;; (strings) to functions handling the respective notifications. Upon + ;; receiving a notification, ‘lsp-mode’ will call the associated handler + ;; function passing two arguments, the ‘lsp--workspace’ object and the + ;; deserialized notification parameters. + (notification-handlers (make-hash-table :test 'equal)) + + ;; ‘request-handlers’ is a hash table mapping request method names + ;; (strings) to functions handling the respective notifications. Upon + ;; receiving a request, ‘lsp-mode’ will call the associated handler function + ;; passing two arguments, the ‘lsp--workspace’ object and the deserialized + ;; request parameters. + (request-handlers (make-hash-table :test 'equal)) + + ;; ‘response-handlers’ is a hash table mapping integral JSON-RPC request + ;; identifiers for pending asynchronous requests to functions handling the + ;; respective responses. Upon receiving a response from the language server, + ;; ‘lsp-mode’ will call the associated response handler function with a + ;; single argument, the deserialized response parameters. + (response-handlers (make-hash-table :test 'eql)) + + ;; ‘prefix-function’ is called for getting the prefix for completion. + ;; The function takes no parameter and returns a cons (start . end) representing + ;; the start and end bounds of the prefix. If it's not set, the client uses a + ;; default prefix function." + (prefix-function nil) + + ;; Contains mapping of scheme to the function that is going to be used to load + ;; the file. + (uri-handlers (make-hash-table :test #'equal)) + + ;; ‘action-handlers’ is a hash table mapping action to a handler function. It + ;; can be used in `lsp-execute-code-action' to determine whether the action + ;; current client is interested in executing the action instead of sending it + ;; to the server. + (action-handlers (make-hash-table :test 'equal)) + + ;; `action-filter' can be set to a function that modifies any incoming + ;; `CodeAction' in place before it is executed. The return value is ignored. + ;; This can be used to patch up broken code action requests before they are + ;; sent back to the LSP server. See `lsp-fix-code-action-booleans' for an + ;; example of a function that can be useful here. + (action-filter nil) + + ;; major modes supported by the client. + major-modes + ;; Function that will be called to decide if this language client + ;; should manage a particular buffer. The function will be passed + ;; the file name and major mode to inform the decision. Setting + ;; `activation-fn' will override `major-modes', if + ;; present. + activation-fn + ;; Break the tie when major-mode is supported by multiple clients. + (priority 0) + ;; Unique identifier for representing the client object. + server-id + ;; defines whether the client supports multi root workspaces. + multi-root + ;; Initialization options or a function that returns initialization options. + initialization-options + ;; `semantic-tokens-faces-overrides’ is a plist that can be used to extend, or + ;; completely replace, the faces used for semantic highlighting on a + ;; client-by-client basis. + ;; + ;; It recognizes four members, all of which are optional: `:types’ and + ;; `:modifiers’, respectively, should be face definition lists akin to + ;; `:lsp-semantic-token-faces’. If specified, each of these face lists will be + ;; merged with the default face definition list. + ;; + ;; Alternatively, if the plist members `:discard-default-types’ or + ;; `:discard-default-modifiers' are non-nil, the default `:type' or `:modifiers' + ;; face definitions will be replaced entirely by their respective overrides. + ;; + ;; For example, setting `:semantic-tokens-faces-overrides' to + ;; `(:types (("macro" . font-lock-keyword-face)))' will remap "macro" tokens from + ;; their default face `lsp-face-semhl-macro' to `font-lock-keyword-face'. + ;; + ;; `(:types (("macro" . font-lock-keyword-face) ("not-quite-a-macro" . some-face)))' + ;; will also remap "macro", but on top of that associate the fictional token type + ;; "not-quite-a-macro" with the face named `some-face'. + ;; + ;; `(:types (("macro" . font-lock-keyword-face)) + ;; :modifiers (("declaration" . lsp-face-semhl-interface)) + ;; :discard-default-types t + ;; :discard-default-modifiers t)' + ;; will discard all default face definitions, hence leaving the client with + ;; only one token type "macro", mapped to `font-lock-keyword-face', and one + ;; modifier type "declaration", mapped to `lsp-face-semhl-interface'. + semantic-tokens-faces-overrides + ;; Provides support for registering LSP Server specific capabilities. + custom-capabilities + ;; Function which returns the folders that are considered to be not projects but library files. + ;; The function accepts one parameter currently active workspace. + ;; See: https://github.com/emacs-lsp/lsp-mode/issues/225. + library-folders-fn + ;; function which will be called when opening file in the workspace to perform + ;; client specific initialization. The function accepts one parameter + ;; currently active workspace. + before-file-open-fn + ;; Function which will be called right after a workspace has been initialized. + initialized-fn + ;; ‘remote?’ indicate whether the client can be used for LSP server over TRAMP. + (remote? nil) + + ;; ‘completion-in-comments?’ t if the client supports completion in comments. + (completion-in-comments? nil) + + ;; ‘path->uri-fn’ the function to use for path->uri conversion for the client. + (path->uri-fn nil) + + ;; ‘uri->path-fn’ the function to use for uri->path conversion for the client. + (uri->path-fn nil) + ;; Function that returns an environment structure that will be used + ;; to set some environment variables when starting the language + ;; server process. These environment variables enable some + ;; additional features in the language server. The environment + ;; structure is an alist of the form (KEY . VALUE), where KEY is a + ;; string (regularly in all caps), and VALUE may be a string, a + ;; boolean, or a sequence of strings. + environment-fn + + ;; ‘after-open-fn’ workspace after open specific hooks. + (after-open-fn nil) + + ;; ‘async-request-handlers’ is a hash table mapping request method names + ;; (strings) to functions handling the respective requests that may take + ;; time to finish. Upon receiving a request, ‘lsp-mode’ will call the + ;; associated handler function passing three arguments, the ‘lsp--workspace’ + ;; object, the deserialized request parameters and the callback which accept + ;; result as its parameter. + (async-request-handlers (make-hash-table :test 'equal)) + download-server-fn + download-in-progress? + buffers + synchronize-sections) + +(defun lsp-clients-executable-find (find-command &rest args) + "Finds an executable by invoking a search command. + +FIND-COMMAND is the executable finder that searches for the +actual language server executable. ARGS is a list of arguments to +give to FIND-COMMAND to find the language server. Returns the +output of FIND-COMMAND if it exits successfully, nil otherwise. + +Typical uses include finding an executable by invoking `find' in +a project, finding LLVM commands on macOS with `xcrun', or +looking up project-specific language servers for projects written +in the various dynamic languages, e.g. `nvm', `pyenv' and `rbenv' +etc." + (when-let* ((find-command-path (executable-find find-command)) + (executable-path + (with-temp-buffer + (when (zerop (apply 'call-process find-command-path nil t nil args)) + (buffer-substring-no-properties (point-min) (point-max)))))) + (string-trim executable-path))) + +(defvar lsp--already-widened nil) + +(defmacro lsp-save-restriction-and-excursion (&rest form) + (declare (indent 0) (debug t)) + `(if lsp--already-widened + (save-excursion ,@form) + (-let [lsp--already-widened t] + (save-restriction + (widen) + (save-excursion ,@form))))) + +;; from http://emacs.stackexchange.com/questions/8082/how-to-get-buffer-position-given-line-number-and-column-number +(defun lsp--line-character-to-point (line character) + "Return the point for character CHARACTER on line LINE." + (or (lsp-virtual-buffer-call :line/character->point line character) + (let ((inhibit-field-text-motion t)) + (lsp-save-restriction-and-excursion + (goto-char (point-min)) + (forward-line line) + ;; server may send character position beyond the current line and we + ;; should fallback to line end. + (-let [line-end (line-end-position)] + (if (> character (- line-end (point))) + line-end + (forward-char character) + (point))))))) + +(lsp-defun lsp--position-to-point ((&Position :line :character)) + "Convert `Position' object in PARAMS to a point." + (lsp--line-character-to-point line character)) + +(lsp-defun lsp--range-to-region ((&RangeToPoint :start :end)) + (cons start end)) + +(lsp-defun lsp--range-text ((&RangeToPoint :start :end)) + (buffer-substring start end)) + +(lsp-defun lsp--find-wrapping-range ((&SelectionRange :parent? :range (&RangeToPoint :start :end))) + (cond + ((and + (region-active-p) + (<= start (region-beginning) end) + (<= start (region-end) end) + (or (not (= start (region-beginning))) + (not (= end (region-end))))) + (cons start end)) + ((and (<= start (point) end) + (not (region-active-p))) + (cons start end)) + (parent? (lsp--find-wrapping-range parent?)))) + +(defun lsp--get-selection-range () + (or + (-when-let ((cache . cache-tick) lsp--document-selection-range-cache) + (when (= cache-tick (buffer-modified-tick)) cache)) + (let ((response (cl-first + (lsp-request + "textDocument/selectionRange" + (list :textDocument (lsp--text-document-identifier) + :positions (vector (lsp--cur-position))))))) + (setq lsp--document-selection-range-cache + (cons response (buffer-modified-tick))) + response))) + +(defun lsp-extend-selection () + "Extend selection." + (interactive) + (unless (lsp-feature? "textDocument/selectionRange") + (signal 'lsp-capability-not-supported (list "selectionRangeProvider"))) + (-when-let ((start . end) (lsp--find-wrapping-range (lsp--get-selection-range))) + (goto-char start) + (set-mark (point)) + (goto-char end) + (exchange-point-and-mark))) + +(defun lsp-warn (message &rest args) + "Display a warning message made from (`format-message' MESSAGE ARGS...). +This is equivalent to `display-warning', using `lsp-mode' as the type and +`:warning' as the level." + (display-warning 'lsp-mode (apply #'format-message message args))) + +(defun lsp--get-uri-handler (scheme) + "Get uri handler for SCHEME in the current workspace." + (--some (gethash scheme (lsp--client-uri-handlers (lsp--workspace-client it))) + (or (lsp-workspaces) (lsp--session-workspaces (lsp-session))))) + +(defun lsp--fix-path-casing (path) + "On windows, downcases path because the windows file system is +case-insensitive. + +On other systems, returns path without change." + (if (eq system-type 'windows-nt) (downcase path) path)) + +(defun lsp--uri-to-path (uri) + "Convert URI to a file path." + (if-let ((fn (->> (lsp-workspaces) + (-keep (-compose #'lsp--client-uri->path-fn #'lsp--workspace-client)) + (cl-first)))) + (funcall fn uri) + (lsp--uri-to-path-1 uri))) + +(defun lsp-remap-path-if-needed (file-name) + (-if-let ((virtual-buffer &as &plist :buffer) (gethash file-name lsp--virtual-buffer-mappings)) + (propertize (buffer-local-value 'buffer-file-name buffer) + 'lsp-virtual-buffer virtual-buffer) + file-name)) + +(defun lsp--uri-to-path-1 (uri) + "Convert URI to a file path." + (let* ((url (url-generic-parse-url (url-unhex-string uri))) + (type (url-type url)) + (target (url-target url)) + (file + (concat (decode-coding-string (url-filename url) + (or locale-coding-system 'utf-8)) + (when (and target + (not (s-match + (rx "#" (group (1+ num)) (or "," "#") + (group (1+ num)) + string-end) + uri))) + (concat "#" target)))) + (file-name (if (and type (not (string= type "file"))) + (if-let ((handler (lsp--get-uri-handler type))) + (funcall handler uri) + uri) + ;; `url-generic-parse-url' is buggy on windows: + ;; https://github.com/emacs-lsp/lsp-mode/pull/265 + (or (and (eq system-type 'windows-nt) + (eq (elt file 0) ?\/) + (substring file 1)) + file)))) + (->> file-name + (concat (-some #'lsp--workspace-host-root (lsp-workspaces))) + (lsp-remap-path-if-needed)))) + +(defun lsp--buffer-uri () + "Return URI of the current buffer." + (or lsp-buffer-uri + (plist-get lsp--virtual-buffer :buffer-uri) + (lsp--path-to-uri + (or (buffer-file-name) (buffer-file-name (buffer-base-buffer)))))) + +(defun lsp-register-client-capabilities (&rest _args) + "Implemented only to make `company-lsp' happy. +DELETE when `lsp-mode.el' is deleted.") + +(defconst lsp--url-path-allowed-chars + (url--allowed-chars (append '(?/) url-unreserved-chars)) + "`url-unreserved-chars' with additional delim ?/. +This set of allowed chars is enough for hexifying local file paths.") + +(defun lsp--path-to-uri-1 (path) + (concat lsp--uri-file-prefix + (--> path + (expand-file-name it) + (or (file-remote-p it 'localname t) it) + (url-hexify-string it lsp--url-path-allowed-chars)))) + +(defun lsp--path-to-uri (path) + "Convert PATH to a uri." + (if-let ((uri-fn (->> (lsp-workspaces) + (-keep (-compose #'lsp--client-path->uri-fn #'lsp--workspace-client)) + (cl-first)))) + (funcall uri-fn path) + (lsp--path-to-uri-1 path))) + +(defun lsp--string-match-any (regex-list str) + "Return the first regex, if any, within REGEX-LIST matching STR." + (--first (string-match it str) regex-list)) + +(cl-defstruct lsp-watch + (descriptors (make-hash-table :test 'equal)) + root-directory) + +(defun lsp--folder-watch-callback (event callback watch ignored-files ignored-directories) + (let ((file-name (cl-third event)) + (event-type (cl-second event))) + (cond + ((and (file-directory-p file-name) + (equal 'created event-type) + (not (lsp--string-match-any ignored-directories file-name))) + + (lsp-watch-root-folder (file-truename file-name) callback ignored-files ignored-directories watch) + + ;; process the files that are already present in + ;; the directory. + (->> (directory-files-recursively file-name ".*" t) + (seq-do (lambda (f) + (unless (file-directory-p f) + (funcall callback (list nil 'created f))))))) + ((and (memq event-type '(created deleted changed)) + (not (file-directory-p file-name)) + (not (lsp--string-match-any ignored-files file-name))) + (funcall callback event)) + ((and (memq event-type '(renamed)) + (not (file-directory-p file-name)) + (not (lsp--string-match-any ignored-files file-name))) + (funcall callback `(,(cl-first event) deleted ,(cl-third event))) + (funcall callback `(,(cl-first event) created ,(cl-fourth event))))))) + +(defun lsp--ask-about-watching-big-repo (number-of-directories dir) + "Ask the user if they want to watch NUMBER-OF-DIRECTORIES from a repository DIR. +This is useful when there is a lot of files in a repository, as +that may slow Emacs down. Returns t if the user wants to watch +the entire repository, nil otherwise." + (prog1 + (yes-or-no-p + (format + "Watching all the files in %s would require adding watches to %s directories, so watching the repo may slow Emacs down. +Do you want to watch all files in %s? " + dir + number-of-directories + dir)) + (lsp--info + (concat "You can configure this warning with the `lsp-enable-file-watchers' " + "and `lsp-file-watch-threshold' variables")))) + + +(defun lsp--path-is-watchable-directory (path dir ignored-directories) + "Figure out whether PATH (inside of DIR) is meant to have a file watcher set. +IGNORED-DIRECTORIES is a list of regexes to filter out directories we don't +want to watch." + (let + ((full-path (f-join dir path))) + (and (file-accessible-directory-p full-path) + (not (equal path ".")) + (not (equal path "..")) + (not (lsp--string-match-any ignored-directories full-path))))) + + +(defun lsp--all-watchable-directories (dir ignored-directories) + "Traverse DIR recursively returning a list of paths that should have watchers. +IGNORED-DIRECTORIES will be used for exclusions" + (let* ((dir (if (f-symlink? dir) + (file-truename dir) + dir))) + (apply #'nconc + ;; the directory itself is assumed to be part of the set + (list dir) + ;; collect all subdirectories that are watchable + (-map + (lambda (path) (lsp--all-watchable-directories (f-join dir path) ignored-directories)) + ;; but only look at subdirectories that are watchable + (-filter (lambda (path) (lsp--path-is-watchable-directory path dir ignored-directories)) + (directory-files dir)))))) + +(defun lsp-watch-root-folder (dir callback ignored-files ignored-directories &optional watch warn-big-repo?) + "Create recursive file notification watch in DIR. +CALLBACK will be called when there are changes in any of +the monitored files. WATCHES is a hash table directory->file +notification handle which contains all of the watch that +already have been created. Watches will not be created for +any directory that matches any regex in IGNORED-DIRECTORIES. +Watches will not be created for any file that matches any +regex in IGNORED-FILES." + (let* ((dir (if (f-symlink? dir) + (file-truename dir) + dir)) + (watch (or watch (make-lsp-watch :root-directory dir))) + (dirs-to-watch (lsp--all-watchable-directories dir ignored-directories))) + (lsp-log "Creating watchers for following %s folders:\n %s" + (length dirs-to-watch) + (s-join "\n " dirs-to-watch)) + (when (or + (not warn-big-repo?) + (not lsp-file-watch-threshold) + (let ((number-of-directories (length dirs-to-watch))) + (or + (< number-of-directories lsp-file-watch-threshold) + (condition-case nil + (lsp--ask-about-watching-big-repo number-of-directories dir) + (quit))))) + (dolist (current-dir dirs-to-watch) + (condition-case err + (progn + (puthash + current-dir + (file-notify-add-watch current-dir + '(change) + (lambda (event) + (lsp--folder-watch-callback event callback watch ignored-files ignored-directories))) + (lsp-watch-descriptors watch))) + (error (lsp-log "Failed to create a watch for %s: message" (error-message-string err))) + (file-missing (lsp-log "Failed to create a watch for %s: message" (error-message-string err)))))) + watch)) + +(defun lsp-kill-watch (watch) + "Delete WATCH." + (-> watch lsp-watch-descriptors hash-table-values (-each #'file-notify-rm-watch)) + (ht-clear! (lsp-watch-descriptors watch))) + +(defun lsp-json-bool (val) + "Convert VAL to JSON boolean." + (if val t :json-false)) + +(defmacro with-lsp-workspace (workspace &rest body) + "Helper macro for invoking BODY in WORKSPACE context." + (declare (debug (form body)) + (indent 1)) + `(let ((lsp--cur-workspace ,workspace)) ,@body)) + +(defmacro with-lsp-workspaces (workspaces &rest body) + "Helper macro for invoking BODY against multiple WORKSPACES." + (declare (debug (form body)) + (indent 1)) + `(let ((lsp--buffer-workspaces ,workspaces)) ,@body)) + + + +(defmacro lsp-consistency-check (package) + `(defconst ,(intern (concat (symbol-name package) + "-plist-value-when-compiled")) + (eval-when-compile lsp-use-plists))) + + +;; loading code-workspace files + +;;;###autoload +(defun lsp-load-vscode-workspace (file) + "Load vscode workspace from FILE" + (interactive "fSelect file to import: ") + (mapc #'lsp-workspace-folders-remove (lsp-session-folders (lsp-session))) + + (let ((dir (f-dirname file))) + (->> file + (json-read-file) + (alist-get 'folders) + (-map (-lambda ((&alist 'path)) + (lsp-workspace-folders-add (expand-file-name path dir))))))) + +;;;###autoload +(defun lsp-save-vscode-workspace (file) + "Save vscode workspace to FILE" + (interactive "FSelect file to save to: ") + + (let ((json-encoding-pretty-print t)) + (f-write-text (json-encode + `((folders . ,(->> (lsp-session) + (lsp-session-folders) + (--map `((path . ,it))))))) + 'utf-8 + file))) + + +(defmacro lsp-foreach-workspace (&rest body) + "Execute BODY for each of the current workspaces." + (declare (debug (form body))) + `(--map (with-lsp-workspace it ,@body) (lsp-workspaces))) + +(defmacro when-lsp-workspace (workspace &rest body) + "Helper macro for invoking BODY in WORKSPACE context if present." + (declare (debug (form body)) + (indent 1)) + `(when-let ((lsp--cur-workspace ,workspace)) ,@body)) + +(lsp-defun lsp--window-show-quick-pick (_workspace (&ShowQuickPickParams :place-holder :can-pick-many :items)) + (if-let* ((selectfunc (if can-pick-many #'completing-read-multiple #'completing-read)) + (itemLabels (seq-map (-lambda ((item &as &QuickPickItem :label)) (format "%s" label)) + items)) + (result (funcall-interactively + selectfunc + (format "%s%s " place-holder (if can-pick-many " (* for all)" "")) itemLabels)) + (choices (if (listp result) + (if (equal result '("*")) + itemLabels + result) + (list result)))) + (vconcat (seq-filter #'identity (seq-map (-lambda ((item &as &QuickPickItem :label :user-data)) + (if (member label choices) + (lsp-make-quick-pick-item :label label :picked t :user-data user-data) + nil)) + items))))) + +(lsp-defun lsp--window-show-input-box (_workspace (&ShowInputBoxParams :prompt :value?)) + (read-string (format "%s: " prompt) (or value? ""))) + +(lsp-defun lsp--window-show-message (_workspace (&ShowMessageRequestParams :message :type)) + "Send the server's messages to log. +PARAMS - the data sent from _WORKSPACE." + (funcall (cl-case type + (1 'lsp--error) + (2 'lsp--warn) + (t 'lsp--info)) + "%s" + message)) + +(lsp-defun lsp--window-log-message (workspace (&ShowMessageRequestParams :message :type)) + "Send the server's messages to log. +PARAMS - the data sent from WORKSPACE." + (ignore + (let ((client (lsp--workspace-client workspace))) + (when (or (not client) + (cl-notany (-rpartial #'string-match-p message) + (lsp--client-ignore-messages client))) + (lsp-log "%s" (lsp--propertize message type)))))) + +(lsp-defun lsp--window-log-message-request ((&ShowMessageRequestParams :message :type :actions?)) + "Display a message request to user sending the user selection back to server." + (let* ((message (lsp--propertize message type)) + (choices (seq-map #'lsp:message-action-item-title actions?))) + (if choices + (completing-read (concat message " ") (seq-into choices 'list) nil t) + (lsp-log message)))) + +(lsp-defun lsp--window-show-document ((&ShowDocumentParams :uri :selection?)) + "Show document URI in a buffer and go to SELECTION if any." + (let ((path (lsp--uri-to-path uri))) + (when (f-exists? path) + (with-current-buffer (find-file path) + (when selection? + (goto-char (lsp--position-to-point (lsp:range-start selection?)))) + t)))) + +(defcustom lsp-progress-prefix "⌛ " + "Progress prefix." + :group 'lsp-mode + :type 'string + :package-version '(lsp-mode . "8.0.0")) + +(defcustom lsp-progress-function #'lsp-on-progress-modeline + "Function for handling the progress notifications." + :group 'lsp-mode + :type '(choice + (const :tag "Use modeline" lsp-on-progress-modeline) + (const :tag "Legacy(uses either `progress-reporter' or `spinner' based on `lsp-progress-via-spinner')" + lsp-on-progress-legacy) + (const :tag "Ignore" ignore) + (function :tag "Other function")) + :package-version '(lsp-mode . "8.0.0")) + +(defcustom lsp-request-while-no-input-may-block nil + "Have `lsp-request-while-no-input` block unless `non-essential` is t." + :group 'lsp-mode + :type 'boolean) + +(defun lsp--progress-status () + "Returns the status of the progress for the current workspaces." + (-let ((progress-status + (s-join + "|" + (-keep + (lambda (workspace) + (let ((tokens (lsp--workspace-work-done-tokens workspace))) + (unless (ht-empty? tokens) + (mapconcat + (-lambda ((&WorkDoneProgressBegin :message? :title :percentage?)) + (concat (if percentage? + (if (numberp percentage?) + (format "%.0f%%%% " percentage?) + (format "%s%%%% " percentage?)) + "") + (or message? title))) + (ht-values tokens) + "|")))) + (lsp-workspaces))))) + (unless (s-blank? progress-status) + (concat lsp-progress-prefix progress-status " ")))) + +(lsp-defun lsp-on-progress-modeline (workspace (&ProgressParams :token :value + (value &as &WorkDoneProgress :kind))) + "PARAMS contains the progress data. +WORKSPACE is the workspace that contains the progress token." + (add-to-list 'global-mode-string '(t (:eval (lsp--progress-status)))) + (pcase kind + ("begin" (lsp-workspace-set-work-done-token token value workspace)) + ("report" (lsp-workspace-set-work-done-token token value workspace)) + ("end" (lsp-workspace-rem-work-done-token token workspace))) + (force-mode-line-update)) + +(lsp-defun lsp-on-progress-legacy (workspace (&ProgressParams :token :value + (value &as &WorkDoneProgress :kind))) + "PARAMS contains the progress data. +WORKSPACE is the workspace that contains the progress token." + (pcase kind + ("begin" + (-let* (((&WorkDoneProgressBegin :title :percentage?) value) + (reporter + (if lsp-progress-via-spinner + (let* ((spinner-strings (alist-get (lsp-progress-spinner-type) spinner-types)) + ;; Set message as a tooltip for the spinner strings + (propertized-strings + (seq-map (lambda (string) (propertize string 'help-echo title)) + spinner-strings)) + (spinner-type (vconcat propertized-strings))) + ;; The progress relates to the server as a whole, + ;; display it on all buffers. + (mapcar (lambda (buffer) + (lsp-with-current-buffer buffer + (spinner-start spinner-type)) + buffer) + (lsp--workspace-buffers workspace))) + (if percentage? + (make-progress-reporter title 0 100 percentage?) + ;; No percentage, just progress + (make-progress-reporter title nil nil))))) + (lsp-workspace-set-work-done-token token reporter workspace))) + ("report" + (when-let ((reporter (lsp-workspace-get-work-done-token token workspace))) + (unless lsp-progress-via-spinner + (progress-reporter-update reporter (lsp:work-done-progress-report-percentage? value))))) + + ("end" + (when-let ((reporter (lsp-workspace-get-work-done-token token workspace))) + (if lsp-progress-via-spinner + (mapc (lambda (buffer) + (when (lsp-buffer-live-p buffer) + (lsp-with-current-buffer buffer + (spinner-stop)))) + reporter) + (progress-reporter-done reporter)) + (lsp-workspace-rem-work-done-token token workspace))))) + + +;; diagnostics + +(defvar lsp-diagnostic-filter nil + "A a function which will be called with + `&PublishDiagnosticsParams' and `workspace' which can be used + to filter out the diagnostics. The function should return + `&PublishDiagnosticsParams'. + +Common usecase are: +1. Filter the diagnostics for a particular language server. +2. Filter out the diagnostics under specific level.") + +(defvar lsp-diagnostic-stats (ht)) + +(defun lsp-diagnostics (&optional current-workspace?) + "Return the diagnostics from all workspaces." + (or (pcase (if current-workspace? + (lsp-workspaces) + (lsp--session-workspaces (lsp-session))) + (`() ()) + (`(,workspace) (lsp--workspace-diagnostics workspace)) + (`,workspaces (let ((result (make-hash-table :test 'equal))) + (mapc (lambda (workspace) + (->> workspace + (lsp--workspace-diagnostics) + (maphash (lambda (file-name diagnostics) + (puthash file-name + (append (gethash file-name result) diagnostics) + result))))) + workspaces) + result))) + (ht))) + +(defun lsp-diagnostics-stats-for (path) + "Get diagnostics statistics for PATH. +The result format is vector [_ errors warnings infos hints] or nil." + (gethash (lsp--fix-path-casing path) lsp-diagnostic-stats)) + +(defun lsp-diagnostics--request-pull-diagnostics (workspace) + "Request new diagnostics for the current file within WORKSPACE. +This is only executed if the server supports pull diagnostics." + (when (lsp-feature? "textDocument/diagnostic") + (let ((path (lsp--fix-path-casing (buffer-file-name)))) + (lsp-request-async "textDocument/diagnostic" + (list :textDocument (lsp--text-document-identifier)) + (-lambda ((&DocumentDiagnosticReport :kind :items?)) + (lsp-diagnostics--apply-pull-diagnostics workspace path kind items?)) + :mode 'tick)))) + +(defun lsp-diagnostics--update-path (path new-stats) + (let ((new-stats (copy-sequence new-stats)) + (path (lsp--fix-path-casing (directory-file-name path)))) + (if-let ((old-data (gethash path lsp-diagnostic-stats))) + (dotimes (idx 5) + (cl-callf + (aref old-data idx) + (aref new-stats idx))) + (puthash path new-stats lsp-diagnostic-stats)))) + +(defun lsp-diagnostics--convert-and-update-path-stats (workspace path diagnostics) + (let ((path (lsp--fix-path-casing path)) + (new-stats (make-vector 5 0))) + (mapc (-lambda ((&Diagnostic :severity?)) + (cl-incf (aref new-stats (or severity? 1)))) + diagnostics) + (when-let ((old-diags (gethash path (lsp--workspace-diagnostics workspace)))) + (mapc (-lambda ((&Diagnostic :severity?)) + (cl-decf (aref new-stats (or severity? 1)))) + old-diags)) + (lsp-diagnostics--update-path path new-stats) + (while (not (string= path (setf path (file-name-directory + (directory-file-name path))))) + (lsp-diagnostics--update-path path new-stats)))) + +(lsp-defun lsp--on-diagnostics-update-stats (workspace + (&PublishDiagnosticsParams :uri :diagnostics)) + (lsp-diagnostics--convert-and-update-path-stats workspace (lsp--uri-to-path uri) diagnostics)) + +(defun lsp-diagnostics--apply-pull-diagnostics (workspace path kind diagnostics?) + "Update WORKSPACE diagnostics at PATH with DIAGNOSTICS?. +Depends on KIND being a \\='full\\=' update." + (cond + ((equal kind "full") + ;; TODO support `lsp-diagnostic-filter' + ;; (the params types differ from the published diagnostics response) + (lsp-diagnostics--convert-and-update-path-stats workspace path diagnostics?) + (-let* ((lsp--virtual-buffer-mappings (ht)) + (workspace-diagnostics (lsp--workspace-diagnostics workspace))) + (if (seq-empty-p diagnostics?) + (remhash path workspace-diagnostics) + (puthash path (append diagnostics? nil) workspace-diagnostics)) + (run-hooks 'lsp-diagnostics-updated-hook))) + ((equal kind "unchanged") t) + (t (lsp--error "Unknown pull diagnostic result kind '%s'" kind)))) + +(defun lsp--on-diagnostics (workspace params) + "Callback for textDocument/publishDiagnostics. +interface PublishDiagnosticsParams { + uri: string; + diagnostics: Diagnostic[]; +} +PARAMS contains the diagnostics data. +WORKSPACE is the workspace that contains the diagnostics." + (when lsp-diagnostic-filter + (setf params (funcall lsp-diagnostic-filter params workspace))) + + (lsp--on-diagnostics-update-stats workspace params) + + (-let* (((&PublishDiagnosticsParams :uri :diagnostics) params) + (lsp--virtual-buffer-mappings (ht)) + (file (lsp--fix-path-casing (lsp--uri-to-path uri))) + (workspace-diagnostics (lsp--workspace-diagnostics workspace))) + + (if (seq-empty-p diagnostics) + (remhash file workspace-diagnostics) + (puthash file (append diagnostics nil) workspace-diagnostics)) + + (run-hooks 'lsp-diagnostics-updated-hook))) + +(defun lsp-diagnostics--workspace-cleanup (workspace) + (->> workspace + (lsp--workspace-diagnostics) + (maphash (lambda (key _) + (lsp--on-diagnostics-update-stats + workspace + (lsp-make-publish-diagnostics-params + :uri (lsp--path-to-uri key) + :diagnostics []))))) + (clrhash (lsp--workspace-diagnostics workspace))) + + + +;; textDocument/foldingRange support + +(cl-defstruct lsp--folding-range beg end kind children) + +(defvar-local lsp--cached-folding-ranges nil) +(defvar-local lsp--cached-nested-folding-ranges nil) + +(defun lsp--folding-range-width (range) + (- (lsp--folding-range-end range) + (lsp--folding-range-beg range))) + +(defun lsp--get-folding-ranges () + "Get the folding ranges for the current buffer." + (unless (eq (buffer-chars-modified-tick) (car lsp--cached-folding-ranges)) + (let* ((ranges (lsp-request "textDocument/foldingRange" + `(:textDocument ,(lsp--text-document-identifier)))) + (sorted-line-col-pairs (->> ranges + (cl-mapcan (-lambda ((&FoldingRange :start-line + :start-character? + :end-line + :end-character?)) + (list (cons start-line start-character?) + (cons end-line end-character?)))) + (-sort #'lsp--line-col-comparator))) + (line-col-to-point-map (lsp--convert-line-col-to-points-batch + sorted-line-col-pairs))) + (setq lsp--cached-folding-ranges + (cons (buffer-chars-modified-tick) + (--> ranges + (seq-map (-lambda ((range &as + &FoldingRange :start-line + :start-character? + :end-line + :end-character? + :kind?)) + (make-lsp--folding-range + :beg (ht-get line-col-to-point-map + (cons start-line start-character?)) + :end (ht-get line-col-to-point-map + (cons end-line end-character?)) + :kind kind?)) + it) + (seq-filter (lambda (folding-range) + (< (lsp--folding-range-beg folding-range) + (lsp--folding-range-end folding-range))) + it) + (seq-into it 'list) + (delete-dups it)))))) + (cdr lsp--cached-folding-ranges)) + +(defun lsp--get-nested-folding-ranges () + "Get a list of nested folding ranges for the current buffer." + (-let [(tick . _) lsp--cached-folding-ranges] + (if (and (eq tick (buffer-chars-modified-tick)) + lsp--cached-nested-folding-ranges) + lsp--cached-nested-folding-ranges + (setq lsp--cached-nested-folding-ranges + (lsp--folding-range-build-trees (lsp--get-folding-ranges)))))) + +(defun lsp--folding-range-build-trees (ranges) + (setq ranges (seq-sort #'lsp--range-before-p ranges)) + (let* ((dummy-node (make-lsp--folding-range + :beg most-negative-fixnum + :end most-positive-fixnum)) + (stack (list dummy-node))) + (dolist (range ranges) + (while (not (lsp--range-inside-p range (car stack))) + (pop stack)) + (push range (lsp--folding-range-children (car stack))) + (push range stack)) + (lsp--folding-range-children dummy-node))) + +(defun lsp--range-inside-p (r1 r2) + "Return non-nil if folding range R1 lies inside R2" + (and (>= (lsp--folding-range-beg r1) (lsp--folding-range-beg r2)) + (<= (lsp--folding-range-end r1) (lsp--folding-range-end r2)))) + +(defun lsp--range-before-p (r1 r2) + "Return non-nil if folding range R1 ends before R2" + ;; Ensure r1 comes before r2 + (or (< (lsp--folding-range-beg r1) + (lsp--folding-range-beg r2)) + ;; If beg(r1) == beg(r2) make sure r2 ends first + (and (= (lsp--folding-range-beg r1) + (lsp--folding-range-beg r2)) + (< (lsp--folding-range-end r2) + (lsp--folding-range-end r1))))) + +(defun lsp--point-inside-range-p (point range) + "Return non-nil if POINT lies inside folding range RANGE." + (and (>= point (lsp--folding-range-beg range)) + (<= point (lsp--folding-range-end range)))) + +(cl-defun lsp--get-current-innermost-folding-range (&optional (point (point))) + "Return the innermost folding range POINT lies in." + (seq-reduce (lambda (innermost-range curr-range) + (if (and (lsp--point-inside-range-p point curr-range) + (or (null innermost-range) + (lsp--range-inside-p curr-range innermost-range))) + curr-range + innermost-range)) + (lsp--get-folding-ranges) + nil)) + +(cl-defun lsp--get-current-outermost-folding-range (&optional (point (point))) + "Return the outermost folding range POINT lies in." + (cdr (seq-reduce (-lambda ((best-pair &as outermost-width . _) curr-range) + (let ((curr-width (lsp--folding-range-width curr-range))) + (if (and (lsp--point-inside-range-p point curr-range) + (or (null best-pair) + (> curr-width outermost-width))) + (cons curr-width curr-range) + best-pair))) + (lsp--get-folding-ranges) + nil))) + +(defun lsp--folding-range-at-point-bounds () + (when (and lsp-enable-folding + (lsp-feature? "textDocument/foldingRange")) + (if-let ((range (lsp--get-current-innermost-folding-range))) + (cons (lsp--folding-range-beg range) + (lsp--folding-range-end range))))) +(put 'lsp--folding-range 'bounds-of-thing-at-point + #'lsp--folding-range-at-point-bounds) + +(defun lsp--get-nearest-folding-range (&optional backward) + (let ((point (point)) + (found nil)) + (while (not + (or found + (if backward + (<= point (point-min)) + (>= point (point-max))))) + (if backward (cl-decf point) (cl-incf point)) + (setq found (lsp--get-current-innermost-folding-range point))) + found)) + +(defun lsp--folding-range-at-point-forward-op (n) + (when (and lsp-enable-folding + (not (zerop n)) + (lsp-feature? "textDocument/foldingRange")) + (cl-block break + (dotimes (_ (abs n)) + (if-let ((range (lsp--get-nearest-folding-range (< n 0)))) + (goto-char (if (< n 0) + (lsp--folding-range-beg range) + (lsp--folding-range-end range))) + (cl-return-from break)))))) +(put 'lsp--folding-range 'forward-op + #'lsp--folding-range-at-point-forward-op) + +(defun lsp--folding-range-at-point-beginning-op () + (goto-char (car (lsp--folding-range-at-point-bounds)))) +(put 'lsp--folding-range 'beginning-op + #'lsp--folding-range-at-point-beginning-op) + +(defun lsp--folding-range-at-point-end-op () + (goto-char (cdr (lsp--folding-range-at-point-bounds)))) +(put 'lsp--folding-range 'end-op + #'lsp--folding-range-at-point-end-op) + +(defun lsp--range-at-point-bounds () + (or (lsp--folding-range-at-point-bounds) + (when-let ((range (and + (lsp-feature? "textDocument/hover") + (->> (lsp--text-document-position-params) + (lsp-request "textDocument/hover") + (lsp:hover-range?))))) + (lsp--range-to-region range)))) + +;; A more general purpose "thing", useful for applications like focus.el +(put 'lsp--range 'bounds-of-thing-at-point + #'lsp--range-at-point-bounds) + +(defun lsp--log-io-p (method) + "Return non nil if should log for METHOD." + (and lsp-log-io + (or (not lsp-log-io-allowlist-methods) + (member method lsp-log-io-allowlist-methods)))) + + +;; toggles + +(defun lsp-toggle-trace-io () + "Toggle client-server protocol logging." + (interactive) + (setq lsp-log-io (not lsp-log-io)) + (lsp--info "Server logging %s." (if lsp-log-io "enabled" "disabled"))) + +(defun lsp-toggle-signature-auto-activate () + "Toggle signature auto activate." + (interactive) + (setq lsp-signature-auto-activate + (unless lsp-signature-auto-activate '(:on-trigger-char))) + (lsp--info "Signature autoactivate %s." (if lsp-signature-auto-activate "enabled" "disabled")) + (lsp--update-signature-help-hook)) + +(defun lsp-toggle-on-type-formatting () + "Toggle on type formatting." + (interactive) + (setq lsp-enable-on-type-formatting (not lsp-enable-on-type-formatting)) + (lsp--info "On type formatting is %s." (if lsp-enable-on-type-formatting "enabled" "disabled")) + (lsp--update-on-type-formatting-hook)) + +(defun lsp-toggle-symbol-highlight () + "Toggle symbol highlighting." + (interactive) + (setq lsp-enable-symbol-highlighting (not lsp-enable-symbol-highlighting)) + + (cond + ((and lsp-enable-symbol-highlighting + (lsp-feature? "textDocument/documentHighlight")) + (add-hook 'lsp-on-idle-hook #'lsp--document-highlight nil t) + (lsp--info "Symbol highlighting enabled in current buffer.")) + ((not lsp-enable-symbol-highlighting) + (remove-hook 'lsp-on-idle-hook #'lsp--document-highlight t) + (lsp--remove-overlays 'lsp-highlight) + (lsp--info "Symbol highlighting disabled in current buffer.")))) + + +;; keybindings +(defvar lsp--binding-descriptions nil + "List of key binding/short description pair.") + +(defmacro lsp-define-conditional-key (keymap key def desc cond &rest bindings) + "In KEYMAP, define key sequence KEY as DEF conditionally. +This is like `define-key', except the definition disappears +whenever COND evaluates to nil. +DESC is the short-description for the binding. +BINDINGS is a list of (key def desc cond)." + (declare (indent defun) + (debug (form form form form form &rest sexp))) + (->> (cl-list* key def desc cond bindings) + (-partition 4) + (-mapcat (-lambda ((key def desc cond)) + `((define-key ,keymap ,key + '(menu-item + ,(format "maybe-%s" def) + ,def + :filter + (lambda (item) + (when (with-current-buffer (or (when (buffer-live-p lsp--describe-buffer) + lsp--describe-buffer) + (current-buffer)) + ,cond) + item)))) + (when (stringp ,key) + (setq lsp--binding-descriptions + (append lsp--binding-descriptions '(,key ,desc))))))) + macroexp-progn)) + +(defvar lsp--describe-buffer nil) + +(defun lsp-describe-buffer-bindings-advice (fn buffer &optional prefix menus) + (let ((lsp--describe-buffer buffer)) + (funcall fn buffer prefix menus))) + +(advice-add 'describe-buffer-bindings + :around + #'lsp-describe-buffer-bindings-advice) + +(defun lsp--prepend-prefix (mappings) + (->> mappings + (-partition 2) + (-mapcat (-lambda ((key description)) + (list (concat lsp-keymap-prefix " " key) + description))))) + +(defvar lsp-command-map + (-doto (make-sparse-keymap) + (lsp-define-conditional-key + ;; workspaces + "wD" lsp-disconnect "disconnect" (lsp-workspaces) + "wd" lsp-describe-session "describe session" t + "wq" lsp-workspace-shutdown "shutdown server" (lsp-workspaces) + "wr" lsp-workspace-restart "restart server" (lsp-workspaces) + "ws" lsp "start server" t + + ;; formatting + "==" lsp-format-buffer "format buffer" (or (lsp-feature? "textDocument/rangeFormatting") + (lsp-feature? "textDocument/formatting")) + "=r" lsp-format-region "format region" (lsp-feature? "textDocument/rangeFormatting") + + ;; folders + "Fa" lsp-workspace-folders-add "add folder" t + "Fb" lsp-workspace-blocklist-remove "un-blocklist folder" t + "Fr" lsp-workspace-folders-remove "remove folder" t + + ;; toggles + "TD" lsp-modeline-diagnostics-mode "toggle modeline diagnostics" (lsp-feature? + "textDocument/publishDiagnostics") + "TL" lsp-toggle-trace-io "toggle log io" t + "TS" lsp-ui-sideline-mode "toggle sideline" (featurep 'lsp-ui-sideline) + "TT" lsp-treemacs-sync-mode "toggle treemacs integration" (featurep 'lsp-treemacs) + "Ta" lsp-modeline-code-actions-mode "toggle modeline code actions" (lsp-feature? + "textDocument/codeAction") + "Tb" lsp-headerline-breadcrumb-mode "toggle breadcrumb" (lsp-feature? + "textDocument/documentSymbol") + "Td" lsp-ui-doc-mode "toggle documentation popup" (featurep 'lsp-ui-doc) + "Tf" lsp-toggle-on-type-formatting "toggle on type formatting" (lsp-feature? + "textDocument/onTypeFormatting") + "Th" lsp-toggle-symbol-highlight "toggle highlighting" (lsp-feature? "textDocument/documentHighlight") + "Tl" lsp-lens-mode "toggle lenses" (lsp-feature? "textDocument/codeLens") + "Ts" lsp-toggle-signature-auto-activate "toggle signature" (lsp-feature? "textDocument/signatureHelp") + + ;; goto + "ga" xref-find-apropos "find symbol in workspace" (lsp-feature? "workspace/symbol") + "gd" lsp-find-declaration "find declarations" (lsp-feature? "textDocument/declaration") + "ge" lsp-treemacs-errors-list "show errors" (fboundp 'lsp-treemacs-errors-list) + "gg" lsp-find-definition "find definitions" (lsp-feature? "textDocument/definition") + "gh" lsp-treemacs-call-hierarchy "call hierarchy" (and (lsp-feature? "callHierarchy/incomingCalls") + (fboundp 'lsp-treemacs-call-hierarchy)) + "gi" lsp-find-implementation "find implementations" (lsp-feature? "textDocument/implementation") + "gr" lsp-find-references "find references" (lsp-feature? "textDocument/references") + "gt" lsp-find-type-definition "find type definition" (lsp-feature? "textDocument/typeDefinition") + + ;; help + "hg" lsp-ui-doc-glance "glance symbol" (and (featurep 'lsp-ui-doc) + (lsp-feature? "textDocument/hover")) + "hh" lsp-describe-thing-at-point "describe symbol at point" (lsp-feature? "textDocument/hover") + "hs" lsp-signature-activate "signature help" (lsp-feature? "textDocument/signatureHelp") + + ;; refactoring + "ro" lsp-organize-imports "organize imports" (lsp-feature? "textDocument/codeAction") + "rr" lsp-rename "rename" (lsp-feature? "textDocument/rename") + + ;; actions + "aa" lsp-execute-code-action "code actions" (lsp-feature? "textDocument/codeAction") + "ah" lsp-document-highlight "highlight symbol" (lsp-feature? "textDocument/documentHighlight") + "al" lsp-avy-lens "lens" (and (bound-and-true-p lsp-lens-mode) (featurep 'avy)) + + ;; peeks + "Gg" lsp-ui-peek-find-definitions "peek definitions" (and (lsp-feature? "textDocument/definition") + (fboundp 'lsp-ui-peek-find-definitions)) + "Gi" lsp-ui-peek-find-implementation "peek implementations" (and + (fboundp 'lsp-ui-peek-find-implementation) + (lsp-feature? "textDocument/implementation")) + "Gr" lsp-ui-peek-find-references "peek references" (and (fboundp 'lsp-ui-peek-find-references) + (lsp-feature? "textDocument/references")) + "Gs" lsp-ui-peek-find-workspace-symbol "peek workspace symbol" (and (fboundp + 'lsp-ui-peek-find-workspace-symbol) + (lsp-feature? "workspace/symbol"))))) + + +;; which-key integration + +(declare-function which-key-add-major-mode-key-based-replacements "ext:which-key") +(declare-function which-key-add-key-based-replacements "ext:which-key") + +(defun lsp-enable-which-key-integration (&optional all-modes) + "Adds descriptions for `lsp-mode-map' to `which-key-mode' for the current +active `major-mode', or for all major modes when ALL-MODES is t." + (cl-flet ((which-key-fn (if all-modes + 'which-key-add-key-based-replacements + (apply-partially 'which-key-add-major-mode-key-based-replacements major-mode)))) + (apply + #'which-key-fn + (lsp--prepend-prefix + (cl-list* + "" "lsp" + "w" "workspaces" + "F" "folders" + "=" "formatting" + "T" "toggle" + "g" "goto" + "h" "help" + "r" "refactor" + "a" "code actions" + "G" "peek" + lsp--binding-descriptions))))) + + +;; Globbing syntax + +;; We port VSCode's glob-to-regexp code +;; (https://github.com/Microsoft/vscode/blob/466da1c9013c624140f6d1473b23a870abc82d44/src/vs/base/common/glob.ts) +;; since the LSP globbing syntax seems to be the same as that of +;; VSCode. + +(defconst lsp-globstar "**" + "Globstar pattern.") + +(defconst lsp-glob-split ?/ + "The character by which we split path components in a glob +pattern.") + +(defconst lsp-path-regexp "[/\\\\]" + "Forward or backslash to be used as a path separator in +computed regexps.") + +(defconst lsp-non-path-regexp "[^/\\\\]" + "A regexp matching anything other than a slash.") + +(defconst lsp-globstar-regexp + (format "\\(?:%s\\|%s+%s\\|%s%s+\\)*?" + lsp-path-regexp + lsp-non-path-regexp lsp-path-regexp + lsp-path-regexp lsp-non-path-regexp) + "Globstar in regexp form.") + +(defun lsp-split-glob-pattern (pattern split-char) + "Split PATTERN at SPLIT-CHAR while respecting braces and brackets." + (when pattern + (let ((segments nil) + (in-braces nil) + (in-brackets nil) + (current-segment "")) + (dolist (char (string-to-list pattern)) + (cl-block 'exit-point + (if (eq char split-char) + (when (and (null in-braces) + (null in-brackets)) + (push current-segment segments) + (setq current-segment "") + (cl-return-from 'exit-point)) + (pcase char + (?{ + (setq in-braces t)) + (?} + (setq in-braces nil)) + (?\[ + (setq in-brackets t)) + (?\] + (setq in-brackets nil)))) + (setq current-segment (concat current-segment + (char-to-string char))))) + (unless (string-empty-p current-segment) + (push current-segment segments)) + (nreverse segments)))) + +(defun lsp--glob-to-regexp (pattern) + "Helper function to convert a PATTERN from LSP's glob syntax to +an Elisp regexp." + (if (string-empty-p pattern) + "" + (let ((current-regexp "") + (glob-segments (lsp-split-glob-pattern pattern lsp-glob-split))) + (if (-all? (lambda (segment) (eq segment lsp-globstar)) + glob-segments) + ".*" + (let ((prev-segment-was-globstar nil)) + (seq-do-indexed + (lambda (segment index) + (if (string-equal segment lsp-globstar) + (unless prev-segment-was-globstar + (setq current-regexp (concat current-regexp + lsp-globstar-regexp)) + (setq prev-segment-was-globstar t)) + (let ((in-braces nil) + (brace-val "") + (in-brackets nil) + (bracket-val "")) + (dolist (char (string-to-list segment)) + (cond + ((and (not (char-equal char ?\})) + in-braces) + (setq brace-val (concat brace-val + (char-to-string char)))) + ((and in-brackets + (or (not (char-equal char ?\])) + (string-empty-p bracket-val))) + (let ((curr (cond + ((char-equal char ?-) + "-") + ;; NOTE: ?\^ and ?^ are different characters + ((and (memq char '(?^ ?!)) + (string-empty-p bracket-val)) + "^") + ((char-equal char lsp-glob-split) + "") + (t + (regexp-quote (char-to-string char)))))) + (setq bracket-val (concat bracket-val curr)))) + (t + (cl-case char + (?{ + (setq in-braces t)) + (?\[ + (setq in-brackets t)) + (?} + (let* ((choices (lsp-split-glob-pattern brace-val ?\,)) + (brace-regexp (concat "\\(?:" + (mapconcat #'lsp--glob-to-regexp choices "\\|") + "\\)"))) + (setq current-regexp (concat current-regexp + brace-regexp)) + (setq in-braces nil) + (setq brace-val ""))) + (?\] + (setq current-regexp + (concat current-regexp + "[" bracket-val "]")) + (setq in-brackets nil) + (setq bracket-val "")) + (?? + (setq current-regexp + (concat current-regexp + lsp-non-path-regexp))) + (?* + (setq current-regexp + (concat current-regexp + lsp-non-path-regexp "*?"))) + (t + (setq current-regexp + (concat current-regexp + (regexp-quote (char-to-string char))))))))) + (when (and (< index (1- (length glob-segments))) + (or (not (string-equal (nth (1+ index) glob-segments) + lsp-globstar)) + (< (+ index 2) + (length glob-segments)))) + (setq current-regexp + (concat current-regexp + lsp-path-regexp))) + (setq prev-segment-was-globstar nil)))) + glob-segments) + current-regexp))))) + +;; See https://github.com/emacs-lsp/lsp-mode/issues/2365 +(defun lsp-glob-unbrace-at-top-level (glob-pattern) + "If GLOB-PATTERN does not start with a brace, return a singleton list +containing GLOB-PATTERN. + +If GLOB-PATTERN does start with a brace, return a list of the +comma-separated globs within the top-level braces." + (if (not (string-prefix-p "{" glob-pattern)) + (list glob-pattern) + (lsp-split-glob-pattern (substring glob-pattern 1 -1) ?\,))) + +(defun lsp-glob-convert-to-wrapped-regexp (glob-pattern) + "Convert GLOB-PATTERN to a regexp wrapped with the beginning- +and end-of-string meta-characters." + (concat "\\`" (lsp--glob-to-regexp (string-trim glob-pattern)) "\\'")) + +(defun lsp-glob-to-regexps (glob-pattern) + "Convert a GLOB-PATTERN to a list of Elisp regexps." + (when-let* + ((glob-pattern (cond ((hash-table-p glob-pattern) + (ht-get glob-pattern "pattern")) + ((stringp glob-pattern) glob-pattern) + (t (error "Unknown glob-pattern type: %s" glob-pattern)))) + (trimmed-pattern (string-trim glob-pattern)) + (top-level-unbraced-patterns (lsp-glob-unbrace-at-top-level trimmed-pattern))) + (seq-map #'lsp-glob-convert-to-wrapped-regexp + top-level-unbraced-patterns))) + + + +(defvar lsp-mode-menu) + +(defun lsp-mouse-click (event) + (interactive "e") + (let* ((ec (event-start event)) + (choice (x-popup-menu event lsp-mode-menu)) + (action (lookup-key lsp-mode-menu (apply 'vector choice)))) + + (select-window (posn-window ec)) + + (unless (and (region-active-p) (eq action 'lsp-execute-code-action)) + (goto-char (posn-point ec))) + (run-with-idle-timer + 0.001 nil + (lambda () + (cl-labels ((check (value) (not (null value)))) + (when choice + (call-interactively action))))))) + +(defvar lsp-mode-map + (let ((map (make-sparse-keymap))) + (define-key map (kbd "C-<down-mouse-1>") #'lsp-find-definition-mouse) + (define-key map (kbd "C-<mouse-1>") #'ignore) + (define-key map (kbd "<mouse-3>") #'lsp-mouse-click) + (define-key map (kbd "C-S-SPC") #'lsp-signature-activate) + (when lsp-keymap-prefix + (define-key map (kbd lsp-keymap-prefix) lsp-command-map)) + map) + "Keymap for `lsp-mode'.") + +(define-minor-mode lsp-mode "Mode for LSP interaction." + :keymap lsp-mode-map + :lighter + (" LSP[" + (lsp--buffer-workspaces + (:eval (mapconcat #'lsp--workspace-print lsp--buffer-workspaces "][")) + (:propertize "Disconnected" face warning)) + "]") + :group 'lsp-mode + (when (and lsp-mode (not lsp--buffer-workspaces) (not lsp--buffer-deferred)) + ;; fire up `lsp' when someone calls `lsp-mode' instead of `lsp' + (lsp))) + +(defvar lsp-mode-menu + (easy-menu-create-menu + nil + `(["Go to definition" lsp-find-definition + :active (lsp-feature? "textDocument/definition")] + ["Find references" lsp-find-references + :active (lsp-feature? "textDocument/references")] + ["Find implementations" lsp-find-implementation + :active (lsp-feature? "textDocument/implementation")] + ["Find declarations" lsp-find-declaration + :active (lsp-feature? "textDocument/declaration")] + ["Go to type declaration" lsp-find-type-definition + :active (lsp-feature? "textDocument/typeDefinition")] + "--" + ["Describe" lsp-describe-thing-at-point] + ["Code action" lsp-execute-code-action] + ["Format" lsp-format-buffer] + ["Highlight references" lsp-document-highlight] + ["Type Hierarchy" lsp-java-type-hierarchy + :visible (lsp-can-execute-command? "java.navigate.resolveTypeHierarchy")] + ["Type Hierarchy" lsp-treemacs-type-hierarchy + :visible (and (not (lsp-can-execute-command? "java.navigate.resolveTypeHierarchy")) + (functionp 'lsp-treemacs-type-hierarchy) + (lsp-feature? "textDocument/typeHierarchy"))] + ["Call Hierarchy" lsp-treemacs-call-hierarchy + :visible (and (functionp 'lsp-treemacs-call-hierarchy) + (lsp-feature? "textDocument/callHierarchy"))] + ["Rename" lsp-rename + :active (lsp-feature? "textDocument/rename")] + "--" + ("Session" + ["View logs" lsp-workspace-show-log] + ["Describe" lsp-describe-session] + ["Shutdown" lsp-shutdown-workspace] + ["Restart" lsp-restart-workspace]) + ("Workspace Folders" + ["Add" lsp-workspace-folders-add] + ["Remove" lsp-workspace-folders-remove] + ["Open" lsp-workspace-folders-open]) + ("Toggle features" + ["Lenses" lsp-lens-mode] + ["Headerline breadcrumb" lsp-headerline-breadcrumb-mode] + ["Modeline code actions" lsp-modeline-code-actions-mode] + ["Modeline diagnostics" lsp-modeline-diagnostics-mode]) + "---" + ("Debug" + :active (bound-and-true-p dap-ui-mode) + :filter ,(lambda (_) + (and (boundp 'dap-ui-menu-items) + (nthcdr 3 dap-ui-menu-items)))))) + "Menu for lsp-mode.") + +(defalias 'make-lsp-client 'make-lsp--client) + +(cl-defstruct lsp--registered-capability + (id "") + (method " ") + (options nil)) + +;; A ‘lsp--workspace’ object represents exactly one language server process. +(cl-defstruct lsp--workspace + ;; the `ewoc' object for displaying I/O to and from the server + (ewoc nil) + + ;; ‘server-capabilities’ is a hash table of the language server capabilities. + ;; It is the hash table representation of a LSP ServerCapabilities structure; + ;; cf. https://microsoft.github.io/language-server-protocol/specification#initialize. + (server-capabilities nil) + + ;; ‘registered-server-capabilities’ is a list of hash tables that represent + ;; dynamically-registered Registration objects. See + ;; https://microsoft.github.io/language-server-protocol/specification#client_registerCapability. + (registered-server-capabilities nil) + + ;; ‘root’ is a directory name or a directory file name for the workspace + ;; root. ‘lsp-mode’ passes this directory to the ‘initialize’ method of the + ;; language server; see + ;; https://microsoft.github.io/language-server-protocol/specification#initialize. + (root nil) + + ;; ‘client’ is the ‘lsp--client’ object associated with this workspace. + (client nil) + + ;; ‘host-root’ contains the host root info as derived from `file-remote-p'. It + ;; used to derive the file path in `lsp--uri-to-path' when using tramp + ;; connection. + (host-root nil) + + ;; ‘proc’ is a process object; it may represent a regular process, a pipe, or + ;; a network connection. ‘lsp-mode’ communicates with ‘proc’ using the + ;; language server protocol. ‘proc’ corresponds to the COMMUNICATION-PROCESS + ;; element of the return value of the client’s ‘get-root’ field, which see. + (proc nil) + + ;; ‘proc’ is a process object; it must represent a regular process, not a + ;; pipe or network process. It represents the actual server process that + ;; corresponds to this workspace. ‘cmd-proc’ corresponds to the + ;; COMMAND-PROCESS element of the return value of the client’s ‘get-root’ + ;; field, which see. + (cmd-proc nil) + + ;; ‘buffers’ is a list of buffers associated with this workspace. + (buffers nil) + + ;; if semantic tokens is enabled, `semantic-tokens-faces' contains + ;; one face (or nil) for each token type supported by the language server. + (semantic-tokens-faces nil) + + ;; If semantic highlighting is enabled, `semantic-tokens-modifier-faces' + ;; contains one face (or nil) for each modifier type supported by the language + ;; server + (semantic-tokens-modifier-faces nil) + + ;; Extra client capabilities provided by third-party packages using + ;; `lsp-register-client-capabilities'. It's value is an alist of (PACKAGE-NAME + ;; . CAPS), where PACKAGE-NAME is a symbol of the third-party package name, + ;; and CAPS is either a plist of the client capabilities, or a function that + ;; takes no argument and returns a plist of the client capabilities or nil. + (extra-client-capabilities nil) + + ;; Workspace status + (status nil) + + ;; ‘metadata’ is a generic storage for workspace specific data. It is + ;; accessed via `lsp-workspace-set-metadata' and `lsp-workspace-set-metadata' + (metadata (make-hash-table :test 'equal)) + + ;; contains all the file notification watches that have been created for the + ;; current workspace in format filePath->file notification handle. + (watches (make-hash-table :test 'equal)) + + ;; list of workspace folders + (workspace-folders nil) + + ;; ‘last-id’ the last request id for the current workspace. + (last-id 0) + + ;; ‘status-string’ allows extensions to specify custom status string based on + ;; the Language Server specific messages. + (status-string nil) + + ;; ‘shutdown-action’ flag used to mark that workspace should not be restarted (e.g. it + ;; was stopped). + shutdown-action + + ;; ‘diagnostics’ a hashmap with workspace diagnostics. + (diagnostics (make-hash-table :test 'equal)) + + ;; contains all the workDone progress tokens that have been created + ;; for the current workspace. + (work-done-tokens (make-hash-table :test 'equal))) + + +(cl-defstruct lsp-session + ;; contains the folders that are part of the current session + folders + ;; contains the folders that must not be imported in the current workspace. + folders-blocklist + ;; contains the list of folders that must be imported in a project in case of + ;; multi root LSP server. + (server-id->folders (make-hash-table :test 'equal)) + ;; folder to list of the servers that are associated with the folder. + (folder->servers (make-hash-table :test 'equal)) + ;; ‘metadata’ is a generic storage for workspace specific data. It is + ;; accessed via `lsp-workspace-set-metadata' and `lsp-workspace-set-metadata' + (metadata (make-hash-table :test 'equal))) + +(defun lsp-workspace-status (status-string &optional workspace) + "Set current workspace status to STATUS-STRING. +If WORKSPACE is not specified defaults to lsp--cur-workspace." + (let ((status-string (when status-string (replace-regexp-in-string "%" "%%" status-string)))) + (setf (lsp--workspace-status-string (or workspace lsp--cur-workspace)) status-string))) + +(defun lsp-session-set-metadata (key value &optional _workspace) + "Associate KEY with VALUE in the WORKSPACE metadata. +If WORKSPACE is not provided current workspace will be used." + (puthash key value (lsp-session-metadata (lsp-session)))) + +(defalias 'lsp-workspace-set-metadata 'lsp-session-set-metadata) + +(defun lsp-session-get-metadata (key &optional _workspace) + "Lookup KEY in WORKSPACE metadata. +If WORKSPACE is not provided current workspace will be used." + (gethash key (lsp-session-metadata (lsp-session)))) + +(defalias 'lsp-workspace-get-metadata 'lsp-session-get-metadata) + +(defun lsp-workspace-set-work-done-token (token value workspace) + "Associate TOKEN with VALUE in the WORKSPACE work-done-tokens." + (puthash token value (lsp--workspace-work-done-tokens workspace))) + +(defun lsp-workspace-get-work-done-token (token workspace) + "Lookup TOKEN in the WORKSPACE work-done-tokens." + (gethash token (lsp--workspace-work-done-tokens workspace))) + +(defun lsp-workspace-rem-work-done-token (token workspace) + "Remove TOKEN from the WORKSPACE work-done-tokens." + (remhash token (lsp--workspace-work-done-tokens workspace))) + + +(defun lsp--make-notification (method &optional params) + "Create notification body for method METHOD and parameters PARAMS." + (list :jsonrpc "2.0" :method method :params params)) + +(defalias 'lsp--make-request 'lsp--make-notification) +(defalias 'lsp-make-request 'lsp--make-notification) + +(defun lsp--make-response (id result) + "Create response for REQUEST with RESULT." + `(:jsonrpc "2.0" :id ,id :result ,result)) + +(defun lsp-make-notification (method &optional params) + "Create notification body for method METHOD and parameters PARAMS." + (lsp--make-notification method params)) + +(defmacro lsp--json-serialize (params) + (if (progn + (require 'json) + (fboundp 'json-serialize)) + `(json-serialize ,params + :null-object nil + :false-object :json-false) + `(let ((json-false :json-false)) + (json-encode ,params)))) + +(defun lsp--make-message (params) + "Create a LSP message from PARAMS, after encoding it to a JSON string." + (let ((body (lsp--json-serialize params))) + (concat "Content-Length: " + (number-to-string (1+ (string-bytes body))) + "\r\n\r\n" + body + "\n"))) + +(cl-defstruct lsp--log-entry timestamp process-time type method id body) + +(defun lsp--make-log-entry (method id body type &optional process-time) + "Create an outgoing log object from BODY with method METHOD and id ID. +If ID is non-nil, then the body is assumed to be a notification. +TYPE can either be `incoming' or `outgoing'" + (cl-assert (memq type '(incoming-req outgoing-req incoming-notif + outgoing-notif incoming-resp + outgoing-resp))) + (make-lsp--log-entry + :timestamp (format-time-string "%I:%M:%S %p") + :process-time process-time + :method method + :id id + :type type + :body body)) + +(defun lsp--log-font-lock-json (body) + "Font lock JSON BODY." + (with-temp-buffer + (insert body) + ;; We set the temp buffer file-name extension to .json and call `set-auto-mode' + ;; so the users configured json mode is used which could be + ;; `json-mode', `json-ts-mode', `jsonian-mode', etc. + (let ((buffer-file-name "lsp-log.json")) + (delay-mode-hooks + (set-auto-mode) + (if (fboundp 'font-lock-ensure) + (font-lock-ensure) + (with-no-warnings + (font-lock-fontify-buffer))))) + (buffer-string))) + +(defun lsp--log-entry-pp (entry) + (cl-assert (lsp--log-entry-p entry)) + (pcase-let (((cl-struct lsp--log-entry timestamp method id type process-time + body) + entry) + (json-false :json-false) + (json-encoding-pretty-print t) + (str nil)) + (setq str + (concat (format "[Trace - %s] " timestamp) + (pcase type + ('incoming-req (format "Received request '%s - (%s)." method id)) + ('outgoing-req (format "Sending request '%s - (%s)'." method id)) + + ('incoming-notif (format "Received notification '%s'." method)) + ('outgoing-notif (format "Sending notification '%s'." method)) + + ('incoming-resp (format "Received response '%s - (%s)' in %dms." + method id process-time)) + ('outgoing-resp + (format + "Sending response '%s - (%s)'. Processing request took %dms" + method id process-time))) + "\n" + (if (memq type '(incoming-resp ougoing-resp)) + "Result: " + "Params: ") + (lsp--log-font-lock-json (json-encode body)) + "\n\n\n")) + (setq str (propertize str 'mouse-face 'highlight 'read-only t)) + (insert str))) + +(defvar-local lsp--log-io-ewoc nil) + +(defun lsp--get-create-io-ewoc (workspace) + (if (and (lsp--workspace-ewoc workspace) + (buffer-live-p (ewoc-buffer (lsp--workspace-ewoc workspace)))) + (lsp--workspace-ewoc workspace) + (with-current-buffer (lsp--get-log-buffer-create workspace) + (unless (eq 'lsp-log-io-mode major-mode) (lsp-log-io-mode)) + (setq-local window-point-insertion-type t) + (setq lsp--log-io-ewoc (ewoc-create #'lsp--log-entry-pp nil nil t)) + (setf (lsp--workspace-ewoc workspace) lsp--log-io-ewoc)) + (lsp--workspace-ewoc workspace))) + +(defun lsp--ewoc-count (ewoc) + (let* ((count 0) + (count-fn (lambda (_) (setq count (1+ count))))) + (ewoc-map count-fn ewoc) + count)) + +(defun lsp--log-entry-new (entry workspace) + (let* ((ewoc (lsp--get-create-io-ewoc workspace)) + (count (and (not (eq lsp-io-messages-max t)) (lsp--ewoc-count ewoc))) + (node (if (or (eq lsp-io-messages-max t) + (>= lsp-io-messages-max count)) + nil + (ewoc-nth ewoc (1- lsp-io-messages-max)))) + (prev nil) + (inhibit-read-only t)) + (while node + (setq prev (ewoc-prev ewoc node)) + (ewoc-delete ewoc node) + (setq node prev)) + (ewoc-enter-last ewoc entry))) + +(defun lsp--send-notification (body) + "Send BODY as a notification to the language server." + (lsp-foreach-workspace + (when (lsp--log-io-p (plist-get body :method)) + (lsp--log-entry-new (lsp--make-log-entry + (plist-get body :method) + nil (plist-get body :params) 'outgoing-notif) + lsp--cur-workspace)) + (lsp--send-no-wait body + (lsp--workspace-proc lsp--cur-workspace)))) + +(defalias 'lsp-send-notification 'lsp--send-notification) + +(defun lsp-notify (method params) + "Send notification METHOD with PARAMS." + (lsp--send-notification (lsp--make-notification method params))) + +(defun lsp--cur-workspace-check () + "Check whether buffer lsp workspace(s) are set." + (cl-assert (lsp-workspaces) nil + "No language server(s) is associated with this buffer.")) + +(defun lsp--send-request (body &optional no-wait no-merge) + "Send BODY as a request to the language server, get the response. +If NO-WAIT is non-nil, don't synchronously wait for a response. +If NO-MERGE is non-nil, don't merge the results but return an +alist mapping workspace->result." + (lsp-request (plist-get body :method) + (plist-get body :params) + :no-wait no-wait + :no-merge no-merge)) + +(defalias 'lsp-send-request 'lsp--send-request + "Send BODY as a request to the language server and return the response +synchronously. +\n(fn BODY)") + +(cl-defun lsp-request (method params &key no-wait no-merge) + "Send request METHOD with PARAMS. +If NO-MERGE is non-nil, don't merge the results but return alist +workspace->result. +If NO-WAIT is non-nil send the request as notification." + (if no-wait + (lsp-notify method params) + (let* ((send-time (float-time)) + ;; max time by which we must get a response + (expected-time + (and + lsp-response-timeout + (+ send-time lsp-response-timeout))) + resp-result resp-error done?) + (unwind-protect + (progn + (lsp-request-async method params + (lambda (res) (setf resp-result (or res :finished)) (throw 'lsp-done '_)) + :error-handler (lambda (err) (setf resp-error err) (throw 'lsp-done '_)) + :no-merge no-merge + :mode 'detached + :cancel-token :sync-request) + (while (not (or resp-error resp-result)) + (if (functionp 'json-rpc-connection) + (catch 'lsp-done (sit-for 0.01)) + (catch 'lsp-done + (accept-process-output + nil + (if expected-time (- expected-time send-time) 1)))) + (setq send-time (float-time)) + (when (and expected-time (< expected-time send-time)) + (error "Timeout while waiting for response. Method: %s" method))) + (setq done? t) + (cond + ((eq resp-result :finished) nil) + (resp-result resp-result) + ((lsp-json-error? resp-error) (error (lsp:json-error-message resp-error))) + ((lsp-json-error? (cl-first resp-error)) + (error (lsp:json-error-message (cl-first resp-error)))))) + (unless done? + (lsp-cancel-request-by-token :sync-request)))))) + +(cl-defun lsp-request-while-no-input (method params) + "Send request METHOD with PARAMS and waits until there is no input. +Return same value as `lsp--while-no-input' and respecting `non-essential'." + (if (or non-essential (not lsp-request-while-no-input-may-block)) + (let* ((send-time (float-time)) + ;; max time by which we must get a response + (expected-time + (and + lsp-response-timeout + (+ send-time lsp-response-timeout))) + resp-result resp-error done?) + (unwind-protect + (progn + (lsp-request-async method params + (lambda (res) (setf resp-result (or res :finished)) (throw 'lsp-done '_)) + :error-handler (lambda (err) (setf resp-error err) (throw 'lsp-done '_)) + :mode 'detached + :cancel-token :sync-request) + (while (not (or resp-error resp-result (input-pending-p))) + (catch 'lsp-done + (sit-for + (if expected-time (- expected-time send-time) 1))) + (setq send-time (float-time)) + (when (and expected-time (< expected-time send-time)) + (error "Timeout while waiting for response. Method: %s" method))) + (setq done? (or resp-error resp-result)) + (cond + ((eq resp-result :finished) nil) + (resp-result resp-result) + ((lsp-json-error? resp-error) (error (lsp:json-error-message resp-error))) + ((lsp-json-error? (cl-first resp-error)) + (error (lsp:json-error-message (cl-first resp-error)))))) + (unless done? + (lsp-cancel-request-by-token :sync-request)) + (when (and (input-pending-p) lsp--throw-on-input) + (throw 'input :interrupted)))) + (lsp-request method params))) + +(defvar lsp--cancelable-requests (ht)) + +(cl-defun lsp-request-async (method params callback + &key mode error-handler cancel-handler no-merge cancel-token) + "Send METHOD with PARAMS as a request to the language server. +Call CALLBACK with the response received from the server +asynchronously. +MODE determines when the callback will be called depending on the +condition of the original buffer. It could be: +- `detached' which means that the callback will be executed no +matter what has happened to the buffer. +- `alive' - the callback will be executed only if the buffer from +which the call was executed is still alive. +- `current' the callback will be executed only if the original buffer +is still selected. +- `tick' - the callback will be executed only if the buffer was not modified. +- `unchanged' - the callback will be executed only if the buffer hasn't +changed and if the buffer is not modified. + +ERROR-HANDLER will be called in case the request has failed. +CANCEL-HANDLER will be called in case the request is being canceled. +If NO-MERGE is non-nil, don't merge the results but return alist +workspace->result. +CANCEL-TOKEN is the token that can be used to cancel request." + (lsp--send-request-async `(:jsonrpc "2.0" :method ,method :params ,params) + callback mode error-handler cancel-handler no-merge cancel-token)) + +(defun lsp--create-request-cancel (id workspaces hook buf method cancel-callback) + (lambda (&rest _) + (unless (and (equal 'post-command-hook hook) + (equal (current-buffer) buf)) + (lsp--request-cleanup-hooks id) + (with-lsp-workspaces workspaces + (lsp--cancel-request id) + (when cancel-callback (funcall cancel-callback))) + (lsp-log "Cancelling %s(%s) in hook %s" method id hook)))) + +(defun lsp--create-async-callback + (callback method no-merge workspaces) + "Create async handler expecting COUNT results, merge them and call CALLBACK. +MODE determines when the callback will be called depending on the +condition of the original buffer. METHOD is the invoked method. +If NO-MERGE is non-nil, don't merge the results but return alist +workspace->result. ID is the request id." + (let (results errors) + (lambda (result) + (push (cons lsp--cur-workspace result) + (if (eq result :error) errors results)) + (when (and (not (eq (length errors) (length workspaces))) + (eq (+ (length errors) (length results)) (length workspaces))) + (funcall callback + (if no-merge + results + (lsp--merge-results (-map #'cl-rest results) method))))))) + +(defcustom lsp-default-create-error-handler-fn nil + "Default error handler customization. +Handler should give METHOD as argument and return function of one argument +ERROR." + :type 'function + :group 'lsp-mode + :package-version '(lsp-mode . "9.0.0")) + +(defun lsp--create-default-error-handler (method) + "Default error handler. +METHOD is the executed method." + (if lsp-default-create-error-handler-fn + (funcall lsp-default-create-error-handler-fn method) + (lambda (error) + (lsp--warn "%s" (or (lsp--error-string error) + (format "%s Request has failed" method)))))) + +(defvar lsp--request-cleanup-hooks (ht)) + +(defun lsp--request-cleanup-hooks (request-id) + (when-let ((cleanup-function (gethash request-id lsp--request-cleanup-hooks))) + (funcall cleanup-function) + (remhash request-id lsp--request-cleanup-hooks))) + +(defun lsp-cancel-request-by-token (cancel-token) + "Cancel request using CANCEL-TOKEN." + (-when-let ((request-id . workspaces) (gethash cancel-token lsp--cancelable-requests)) + (with-lsp-workspaces workspaces + (lsp--cancel-request request-id)) + (remhash cancel-token lsp--cancelable-requests) + (lsp--request-cleanup-hooks request-id))) + +(defun lsp--send-request-async (body callback + &optional mode error-callback cancel-callback + no-merge cancel-token) + "Send BODY as a request to the language server. +Call CALLBACK with the response received from the server +asynchronously. +MODE determines when the callback will be called depending on the +condition of the original buffer. It could be: +- `detached' which means that the callback will be executed no +matter what has happened to the buffer. +- `alive' - the callback will be executed only if the buffer from +which the call was executed is still alive. +- `current' the callback will be executed only if the original buffer +is still selected. +- `tick' - the callback will be executed only if the buffer was not modified. +- `unchanged' - the callback will be executed only if the buffer hasn't +changed and if the buffer is not modified. + +ERROR-CALLBACK will be called in case the request has failed. +CANCEL-CALLBACK will be called in case the request is being canceled. +If NO-MERGE is non-nil, don't merge the results but return alist +workspace->result. +CANCEL-TOKEN is the token that can be used to cancel request." + (when cancel-token + (lsp-cancel-request-by-token cancel-token)) + + (if-let ((target-workspaces (lsp--find-workspaces-for body))) + (let* ((start-time (current-time)) + (method (plist-get body :method)) + (id (cl-incf lsp-last-id)) + (buf (current-buffer)) + (cancel-callback (when cancel-callback + (pcase mode + ((or 'alive 'tick 'unchanged) + (lambda () + (with-current-buffer buf + (funcall cancel-callback)))) + (_ cancel-callback)))) + ;; calculate what are the (hook . local) pairs which will cancel + ;; the request + (hooks (pcase mode + ('alive '((kill-buffer-hook . t))) + ('tick '((kill-buffer-hook . t) (after-change-functions . t))) + ('unchanged '((after-change-functions . t) (post-command-hook . nil))) + ('current '((post-command-hook . nil))))) + ;; note: lambdas in emacs can be compared but we should make sure + ;; that all of the captured arguments are the same - in our case + ;; `lsp--create-request-cancel' will return the same lambda when + ;; called with the same params. + (cleanup-hooks + (lambda () (mapc + (-lambda ((hook . local)) + (if local + (when (buffer-live-p buf) + (with-current-buffer buf + (remove-hook hook + (lsp--create-request-cancel + id target-workspaces hook buf method cancel-callback) + t))) + (remove-hook hook (lsp--create-request-cancel + id target-workspaces hook buf method cancel-callback)))) + hooks) + (remhash cancel-token lsp--cancelable-requests))) + (callback (pcase mode + ((or 'alive 'tick 'unchanged) (lambda (&rest args) + (with-current-buffer buf + (apply callback args)))) + (_ callback))) + (callback (lsp--create-async-callback callback + method + no-merge + target-workspaces)) + (callback (lambda (result) + (lsp--request-cleanup-hooks id) + (funcall callback result))) + (error-callback (lsp--create-async-callback + (or error-callback + (lsp--create-default-error-handler method)) + method + nil + target-workspaces)) + (error-callback (lambda (error) + (funcall callback :error) + (lsp--request-cleanup-hooks id) + (funcall error-callback error))) + (body (plist-put body :id id))) + + ;; cancel request in any of the hooks + (mapc (-lambda ((hook . local)) + (add-hook hook + (lsp--create-request-cancel + id target-workspaces hook buf method cancel-callback) + nil local)) + hooks) + (puthash id cleanup-hooks lsp--request-cleanup-hooks) + + (setq lsp--last-active-workspaces target-workspaces) + + (when cancel-token + (puthash cancel-token (cons id target-workspaces) lsp--cancelable-requests)) + + (seq-doseq (workspace target-workspaces) + (when (lsp--log-io-p method) + (lsp--log-entry-new (lsp--make-log-entry method id + (plist-get body :params) + 'outgoing-req) + workspace)) + (puthash id + (list callback error-callback method start-time (current-time)) + (-> workspace + (lsp--workspace-client) + (lsp--client-response-handlers))) + (lsp--send-no-wait body (lsp--workspace-proc workspace))) + body) + (error "The connected server(s) does not support method %s. +To find out what capabilities support your server use `M-x lsp-describe-session' +and expand the capabilities section" + (plist-get body :method)))) + +;; deprecated, use lsp-request-async. +(defalias 'lsp-send-request-async 'lsp--send-request-async) +(make-obsolete 'lsp-send-request-async 'lsp-request-async "lsp-mode 7.0.1") + +;; Clean up the entire state of lsp mode when Emacs is killed, to get rid of any +;; pending language servers. +(add-hook 'kill-emacs-hook #'lsp--global-teardown) + +(defun lsp--global-teardown () + "Unload working workspaces." + (lsp-foreach-workspace (lsp--shutdown-workspace))) + +(defun lsp--shutdown-workspace (&optional restart) + "Shut down the language server process for ‘lsp--cur-workspace’." + (with-demoted-errors "LSP error: %S" + (let ((lsp-response-timeout 0.5)) + (condition-case err + (lsp-request "shutdown" nil) + (error (lsp--error "%s" err)))) + (lsp-notify "exit" nil)) + (setf (lsp--workspace-shutdown-action lsp--cur-workspace) (or (and restart 'restart) 'shutdown)) + (lsp--uninitialize-workspace)) + +(defcustom lsp-inlay-hint-enable nil + "If non-nil it will enable inlay hints." + :type 'boolean + :group 'lsp-mode + :package-version '(lsp-mode . "9.0.0")) + +(defun lsp--uninitialize-workspace () + "Cleanup buffer state. +When a workspace is shut down, by request or from just +disappearing, unset all the variables related to it." + (-let [(&lsp-wks 'cmd-proc 'buffers) lsp--cur-workspace] + (lsp-process-kill cmd-proc) + (mapc (lambda (buf) + (when (lsp-buffer-live-p buf) + (lsp-with-current-buffer buf + (lsp-managed-mode -1)))) + buffers) + (lsp-diagnostics--workspace-cleanup lsp--cur-workspace))) + +(defun lsp--client-capabilities (&optional custom-capabilities) + "Return the client capabilities appending CUSTOM-CAPABILITIES." + (append + `((general . ((positionEncodings . ["utf-32", "utf-16"]))) + (workspace . ((workspaceEdit . ((documentChanges . t) + (resourceOperations . ["create" "rename" "delete"]))) + (applyEdit . t) + (symbol . ((symbolKind . ((valueSet . ,(apply 'vector (number-sequence 1 26))))))) + (executeCommand . ((dynamicRegistration . :json-false))) + ,@(when lsp-enable-file-watchers '((didChangeWatchedFiles . ((dynamicRegistration . t))))) + (workspaceFolders . t) + (configuration . t) + ,@(when lsp-semantic-tokens-enable + `((semanticTokens . ((refreshSupport . ,(or (and (boundp 'lsp-semantic-tokens-honor-refresh-requests) + lsp-semantic-tokens-honor-refresh-requests) + :json-false)))))) + ,@(when lsp-lens-enable '((codeLens . ((refreshSupport . t))))) + ,@(when lsp-inlay-hint-enable '((inlayHint . ((refreshSupport . :json-false))))) + (fileOperations . ((didCreate . :json-false) + (willCreate . :json-false) + (didRename . t) + (willRename . t) + (didDelete . :json-false) + (willDelete . :json-false))))) + (textDocument . ((declaration . ((dynamicRegistration . t) + (linkSupport . t))) + (definition . ((dynamicRegistration . t) + (linkSupport . t))) + (references . ((dynamicRegistration . t))) + (implementation . ((dynamicRegistration . t) + (linkSupport . t))) + (typeDefinition . ((dynamicRegistration . t) + (linkSupport . t))) + (synchronization . ((willSave . t) (didSave . t) (willSaveWaitUntil . t))) + (documentSymbol . ((symbolKind . ((valueSet . ,(apply 'vector (number-sequence 1 26))))) + (hierarchicalDocumentSymbolSupport . t))) + (formatting . ((dynamicRegistration . t))) + (rangeFormatting . ((dynamicRegistration . t))) + (onTypeFormatting . ((dynamicRegistration . t))) + ,@(when (and lsp-semantic-tokens-enable + (functionp 'lsp--semantic-tokens-capabilities)) + (lsp--semantic-tokens-capabilities)) + (rename . ((dynamicRegistration . t) (prepareSupport . t))) + (codeAction . ((dynamicRegistration . t) + (isPreferredSupport . t) + (codeActionLiteralSupport . ((codeActionKind . ((valueSet . ["" + "quickfix" + "refactor" + "refactor.extract" + "refactor.inline" + "refactor.rewrite" + "source" + "source.organizeImports"]))))) + (resolveSupport . ((properties . ["edit" "command"]))) + (dataSupport . t))) + (completion . ((completionItem . ((snippetSupport . ,(cond + ((and lsp-enable-snippet (not (fboundp 'yas-minor-mode))) + (lsp--warn (concat + "Yasnippet is not installed, but `lsp-enable-snippet' is set to `t'. " + "You must either install yasnippet, or disable snippet support.")) + :json-false) + (lsp-enable-snippet t) + (t :json-false))) + (documentationFormat . ["markdown" "plaintext"]) + ;; Remove this after jdtls support resolveSupport + (resolveAdditionalTextEditsSupport . t) + (insertReplaceSupport . t) + (deprecatedSupport . t) + (resolveSupport + . ((properties . ["documentation" + "detail" + "additionalTextEdits" + "command"]))) + (insertTextModeSupport . ((valueSet . [1 2]))))) + (contextSupport . t) + (dynamicRegistration . t))) + (signatureHelp . ((signatureInformation . ((parameterInformation . ((labelOffsetSupport . t))))) + (dynamicRegistration . t))) + (documentLink . ((dynamicRegistration . t) + (tooltipSupport . t))) + (hover . ((contentFormat . ["markdown" "plaintext"]) + (dynamicRegistration . t))) + ,@(when lsp-enable-folding + `((foldingRange . ((dynamicRegistration . t) + ,@(when lsp-folding-range-limit + `((rangeLimit . ,lsp-folding-range-limit))) + ,@(when lsp-folding-line-folding-only + `((lineFoldingOnly . t))))))) + (selectionRange . ((dynamicRegistration . t))) + (callHierarchy . ((dynamicRegistration . :json-false))) + (typeHierarchy . ((dynamicRegistration . t))) + (publishDiagnostics . ((relatedInformation . t) + (tagSupport . ((valueSet . [1 2]))) + (versionSupport . t))) + (diagnostic . ((dynamicRegistration . :json-false) + (relatedDocumentSupport . :json-false))) + (linkedEditingRange . ((dynamicRegistration . t))))) + (window . ((workDoneProgress . t) + (showDocument . ((support . t)))))) + custom-capabilities)) + +(defun lsp-find-roots-for-workspace (workspace session) + "Get all roots for the WORKSPACE." + (-filter #'identity (ht-map (lambda (folder workspaces) + (when (-contains? workspaces workspace) + folder)) + (lsp-session-folder->servers session)))) + +(defun lsp-session-watches (&optional session) + "Get watches created for SESSION." + (or (gethash "__watches" (lsp-session-metadata (or session (lsp-session)))) + (-let [res (make-hash-table :test 'equal)] + (puthash "__watches" res (lsp-session-metadata (or session (lsp-session)))) + res))) + +(defun lsp--file-process-event (session root-folder event) + "Process file event." + (let* ((changed-file (cl-third event)) + (rel-changed-file (f-relative changed-file root-folder)) + (event-numeric-kind (alist-get (cl-second event) lsp--file-change-type)) + (bit-position (1- event-numeric-kind)) + (watch-bit (ash 1 bit-position))) + (->> + session + lsp-session-folder->servers + (gethash root-folder) + (seq-do (lambda (workspace) + (when (->> + workspace + lsp--workspace-registered-server-capabilities + (-any? + (lambda (capability) + (and + (equal (lsp--registered-capability-method capability) + "workspace/didChangeWatchedFiles") + (->> + capability + lsp--registered-capability-options + (lsp:did-change-watched-files-registration-options-watchers) + (seq-find + (-lambda ((fs-watcher &as &FileSystemWatcher :glob-pattern :kind? :_cachedRegexp cached-regexp)) + (when (or (null kind?) + (> (logand kind? watch-bit) 0)) + (-let [regexes (or cached-regexp + (let ((regexp (lsp-glob-to-regexps glob-pattern))) + (lsp-put fs-watcher :_cachedRegexp regexp) + regexp))] + (-any? (lambda (re) + (or (string-match re changed-file) + (string-match re rel-changed-file))) + regexes)))))))))) + (with-lsp-workspace workspace + (lsp-notify + "workspace/didChangeWatchedFiles" + `((changes . [((type . ,event-numeric-kind) + (uri . ,(lsp--path-to-uri changed-file)))])))))))))) + +(lsp-defun lsp--server-register-capability ((&Registration :method :id :register-options?)) + "Register capability REG." + (when (and lsp-enable-file-watchers + (equal method "workspace/didChangeWatchedFiles")) + (-let* ((created-watches (lsp-session-watches (lsp-session))) + (root-folders (cl-set-difference + (lsp-find-roots-for-workspace lsp--cur-workspace (lsp-session)) + (ht-keys created-watches)))) + ;; create watch for each root folder without such + (dolist (folder root-folders) + (let* ((watch (make-lsp-watch :root-directory folder)) + (ignored-things (lsp--get-ignored-regexes-for-workspace-root folder)) + (ignored-files-regex-list (car ignored-things)) + (ignored-directories-regex-list (cadr ignored-things))) + (puthash folder watch created-watches) + (lsp-watch-root-folder (file-truename folder) + (-partial #'lsp--file-process-event (lsp-session) folder) + ignored-files-regex-list + ignored-directories-regex-list + watch + t))))) + + (push + (make-lsp--registered-capability :id id :method method :options register-options?) + (lsp--workspace-registered-server-capabilities lsp--cur-workspace))) + +(defmacro lsp--with-workspace-temp-buffer (workspace-root &rest body) + "With a temp-buffer under `WORKSPACE-ROOT' and evaluate `BODY', useful to +access dir-local variables." + (declare (indent 1) (debug t)) + `(with-temp-buffer + ;; Set the buffer's name to something under the root so that we can hack the local variables + ;; This file doesn't need to exist and will not be created due to this. + (setq-local buffer-file-name (expand-file-name "lsp-mode-temp" (expand-file-name ,workspace-root))) + (hack-local-variables) + (prog1 ,@body + (setq-local buffer-file-name nil)))) + +(defun lsp--get-ignored-regexes-for-workspace-root (workspace-root) + "Return a list of the form +(lsp-file-watch-ignored-files lsp-file-watch-ignored-directories) for the given +WORKSPACE-ROOT." + ;; The intent of this function is to provide per-root workspace-level customization of the + ;; lsp-file-watch-ignored-directories and lsp-file-watch-ignored-files variables. + (lsp--with-workspace-temp-buffer workspace-root + (list lsp-file-watch-ignored-files (lsp-file-watch-ignored-directories)))) + + +(defun lsp--cleanup-hanging-watches () + "Cleanup watches in case there are no more workspaces that are interested +in that particular folder." + (let* ((session (lsp-session)) + (watches (lsp-session-watches session))) + (dolist (watched-folder (ht-keys watches)) + (when (-none? (lambda (workspace) + (with-lsp-workspace workspace + (lsp--registered-capability "workspace/didChangeWatchedFiles"))) + (gethash watched-folder (lsp-session-folder->servers (lsp-session)))) + (lsp-log "Cleaning up watches for folder %s. There is no workspace watching this folder..." watched-folder) + (lsp-kill-watch (gethash watched-folder watches)) + (remhash watched-folder watches))))) + +(lsp-defun lsp--server-unregister-capability ((&Unregistration :id :method)) + "Unregister capability UNREG." + (setf (lsp--workspace-registered-server-capabilities lsp--cur-workspace) + (seq-remove (lambda (e) (equal (lsp--registered-capability-id e) id)) + (lsp--workspace-registered-server-capabilities lsp--cur-workspace))) + (when (equal method "workspace/didChangeWatchedFiles") + (lsp--cleanup-hanging-watches))) + +(defun lsp--server-capabilities () + "Return the capabilities of the language server associated with the buffer." + (->> (lsp-workspaces) + (-keep #'lsp--workspace-server-capabilities) + (apply #'lsp-merge))) + +(defun lsp--send-open-close-p () + "Return whether open and close notifications should be sent to the server." + (let ((sync (lsp:server-capabilities-text-document-sync? (lsp--server-capabilities)))) + (or (memq sync '(1 2)) + (lsp:text-document-sync-options-open-close? sync)))) + +(defun lsp--send-will-save-p () + "Return whether willSave notifications should be sent to the server." + (-> (lsp--server-capabilities) + (lsp:server-capabilities-text-document-sync?) + (lsp:text-document-sync-options-will-save?))) + +(defun lsp--send-will-save-wait-until-p () + "Return whether willSaveWaitUntil notifications should be sent to the server." + (-> (lsp--server-capabilities) + (lsp:server-capabilities-text-document-sync?) + (lsp:text-document-sync-options-will-save-wait-until?))) + +(defun lsp--send-did-save-p () + "Return whether didSave notifications should be sent to the server." + (let ((sync (lsp:server-capabilities-text-document-sync? (lsp--server-capabilities)))) + (or (memq sync '(1 2)) + (lsp:text-document-sync-options-save? sync)))) + +(defun lsp--save-include-text-p () + "Return whether save notifications should include the text document's contents." + (->> (lsp--server-capabilities) + (lsp:server-capabilities-text-document-sync?) + (lsp:text-document-sync-options-save?) + (lsp:text-document-save-registration-options-include-text?))) + +(defun lsp--send-will-rename-files-p (path) + "Return whether willRenameFiles request should be sent to the server. +If any filters, checks if it applies for PATH." + (let* ((will-rename (-> (lsp--server-capabilities) + (lsp:server-capabilities-workspace?) + (lsp:workspace-server-capabilities-file-operations?) + (lsp:workspace-file-operations-will-rename?))) + (filters (seq-into (lsp:file-operation-registration-options-filters will-rename) 'list))) + (and will-rename + (or (seq-empty-p filters) + (-any? (-lambda ((&FileOperationFilter :scheme? :pattern (&FileOperationPattern :glob))) + (-let [regexes (lsp-glob-to-regexps glob)] + (and (or (not scheme?) + (string-prefix-p scheme? (lsp--path-to-uri path))) + (-any? (lambda (re) + (string-match re path)) + regexes)))) + filters))))) + +(defun lsp--send-did-rename-files-p () + "Return whether didRenameFiles notification should be sent to the server." + (-> (lsp--server-capabilities) + (lsp:server-capabilities-workspace?) + (lsp:workspace-server-capabilities-file-operations?) + (lsp:workspace-file-operations-did-rename?))) + +(declare-function project-roots "ext:project" (project) t) +(declare-function project-root "ext:project" (project) t) + +(defun lsp--suggest-project-root () + "Get project root." + (or + (when (fboundp 'projectile-project-root) + (condition-case nil + (projectile-project-root) + (error nil))) + (when (fboundp 'project-current) + (when-let ((project (project-current))) + (if (fboundp 'project-root) + (project-root project) + (car (with-no-warnings + (project-roots project)))))) + default-directory)) + +(defun lsp--read-from-file (file) + "Read FILE content." + (when (file-exists-p file) + (cl-first (read-from-string (f-read-text file 'utf-8))))) + +(defun lsp--persist (file-name to-persist) + "Persist TO-PERSIST in FILE-NAME. + +This function creates the parent directories if they don't exist +yet." + (let ((print-length nil) + (print-level nil)) + ;; Create all parent directories: + (make-directory (f-parent file-name) t) + (f-write-text (prin1-to-string to-persist) 'utf-8 file-name))) + +(defun lsp-workspace-folders-add (project-root) + "Add PROJECT-ROOT to the list of workspace folders." + (interactive + (list (read-directory-name "Select folder to add: " + (or (lsp--suggest-project-root) default-directory) nil t))) + (cl-pushnew (lsp-f-canonical project-root) + (lsp-session-folders (lsp-session)) :test 'equal) + (lsp--persist-session (lsp-session)) + + (run-hook-with-args 'lsp-workspace-folders-changed-functions (list project-root) nil)) + +(defun lsp-workspace-folders-remove (project-root) + "Remove PROJECT-ROOT from the list of workspace folders." + (interactive (list (completing-read "Select folder to remove: " + (lsp-session-folders (lsp-session)) + nil t nil nil + (lsp-find-session-folder (lsp-session) default-directory)))) + + (setq project-root (lsp-f-canonical project-root)) + + ;; send remove folder to each multiroot workspace associated with the folder + (dolist (wks (->> (lsp-session) + (lsp-session-folder->servers) + (gethash project-root) + (--filter (lsp--client-multi-root (lsp--workspace-client it))))) + (with-lsp-workspace wks + (lsp-notify "workspace/didChangeWorkspaceFolders" + (lsp-make-did-change-workspace-folders-params + :event (lsp-make-workspace-folders-change-event + :removed (vector (lsp-make-workspace-folder + :uri (lsp--path-to-uri project-root) + :name (f-filename project-root))) + :added []))))) + + ;; turn off servers in the removed directory + (let* ((session (lsp-session)) + (folder->servers (lsp-session-folder->servers session)) + (server-id->folders (lsp-session-server-id->folders session)) + (workspaces (gethash project-root folder->servers))) + + (remhash project-root folder->servers) + + ;; turn off the servers without root folders + (dolist (workspace workspaces) + (when (--none? (-contains? it workspace) (ht-values folder->servers)) + (lsp--info "Shutdown %s since folder %s is removed..." + (lsp--workspace-print workspace) project-root) + (with-lsp-workspace workspace (lsp--shutdown-workspace)))) + + (setf (lsp-session-folders session) + (-remove-item project-root (lsp-session-folders session))) + + (ht-aeach (puthash key + (-remove-item project-root value) + server-id->folders) + server-id->folders) + (lsp--persist-session (lsp-session))) + + (run-hook-with-args 'lsp-workspace-folders-changed-functions nil (list project-root))) + +(defun lsp-workspace-blocklist-remove (project-root) + "Remove PROJECT-ROOT from the workspace blocklist." + (interactive (list (completing-read "Select folder to remove:" + (lsp-session-folders-blocklist (lsp-session)) + nil t))) + (setf (lsp-session-folders-blocklist (lsp-session)) + (delete project-root + (lsp-session-folders-blocklist (lsp-session)))) + (lsp--persist-session (lsp-session))) + +(define-obsolete-function-alias 'lsp-workspace-folders-switch + 'lsp-workspace-folders-open "lsp-mode 6.1") + +(defun lsp-workspace-folders-open (project-root) + "Open the directory located at PROJECT-ROOT" + (interactive (list (completing-read "Open folder: " + (lsp-session-folders (lsp-session)) + nil t))) + (find-file project-root)) + +(defun lsp--maybe-enable-signature-help (trigger-characters) + (let ((ch last-command-event)) + (when (cl-find ch trigger-characters :key #'string-to-char) + (lsp-signature-activate)))) + +(defun lsp--on-type-formatting-handler-create () + (when-let ((provider (lsp--capability-for-method "textDocument/onTypeFormatting" ))) + (-let [(&DocumentOnTypeFormattingOptions :more-trigger-character? + :first-trigger-character) provider] + (lambda () + (lsp--on-type-formatting first-trigger-character + more-trigger-character?))))) + +(defun lsp--update-on-type-formatting-hook (&optional cleanup?) + (let ((on-type-formatting-handler (lsp--on-type-formatting-handler-create))) + (cond + ((and lsp-enable-on-type-formatting on-type-formatting-handler (not cleanup?)) + (add-hook 'post-self-insert-hook on-type-formatting-handler nil t)) + ((or cleanup? + (not lsp-enable-on-type-formatting)) + (remove-hook 'post-self-insert-hook on-type-formatting-handler t))))) + +(defun lsp--signature-help-handler-create () + (-when-let ((&SignatureHelpOptions? :trigger-characters?) + (lsp--capability-for-method "textDocument/signatureHelp")) + (lambda () + (lsp--maybe-enable-signature-help trigger-characters?)))) + +(defun lsp--update-signature-help-hook (&optional cleanup?) + (let ((signature-help-handler (lsp--signature-help-handler-create))) + (cond + ((and (or (equal lsp-signature-auto-activate t) + (memq :on-trigger-char lsp-signature-auto-activate)) + signature-help-handler + (not cleanup?)) + (add-hook 'post-self-insert-hook signature-help-handler nil t)) + + ((or cleanup? + (not (or (equal lsp-signature-auto-activate t) + (memq :on-trigger-char lsp-signature-auto-activate)))) + (remove-hook 'post-self-insert-hook signature-help-handler t))))) + +(defun lsp--after-set-visited-file-name () + (lsp-disconnect) + (lsp)) + +;; TODO remove those eldoc workarounds when dropping support for Emacs 27 +;; https://github.com/emacs-lsp/lsp-mode/issues/3295#issuecomment-1308994099 +(defvar eldoc-documentation-default) ; CI +(when (< emacs-major-version 28) + (unless (boundp 'eldoc-documentation-functions) + (load "eldoc" nil 'nomessage)) + (when (memq (default-value 'eldoc-documentation-function) '(nil ignore)) + ;; actually `eldoc-documentation-strategy', but CI was failing + (setq-default eldoc-documentation-function 'eldoc-documentation-default))) + +(define-minor-mode lsp-managed-mode + "Mode for source buffers managed by lsp-mode." + :lighter nil + (cond + (lsp-managed-mode + (when (lsp-feature? "textDocument/hover") + (add-hook 'eldoc-documentation-functions #'lsp-eldoc-function nil t) + (eldoc-mode 1)) + + (add-hook 'after-change-functions #'lsp-on-change nil t) + (add-hook 'after-revert-hook #'lsp-on-revert nil t) + (add-hook 'after-save-hook #'lsp-on-save nil t) + (add-hook 'auto-save-hook #'lsp--on-auto-save nil t) + (add-hook 'before-change-functions #'lsp-before-change nil t) + (add-hook 'before-save-hook #'lsp--before-save nil t) + (add-hook 'kill-buffer-hook #'lsp--text-document-did-close nil t) + (add-hook 'post-command-hook #'lsp--post-command nil t) + + (lsp--update-on-type-formatting-hook) + (lsp--update-signature-help-hook) + + (when lsp-enable-xref + (add-hook 'xref-backend-functions #'lsp--xref-backend nil t)) + + (lsp-configure-buffer) + + ;; make sure we turn off lsp-mode in case major mode changes, because major + ;; mode change will wipe the buffer locals. + (add-hook 'change-major-mode-hook #'lsp-disconnect nil t) + (add-hook 'after-set-visited-file-name-hook #'lsp--after-set-visited-file-name nil t) + + (let ((buffer (lsp-current-buffer))) + (run-with-idle-timer + 0.0 nil + (lambda () + (when (lsp-buffer-live-p buffer) + (lsp-with-current-buffer buffer + (lsp--on-change-debounce buffer) + (lsp--on-idle buffer))))))) + (t + (lsp-unconfig-buffer) + + (remove-hook 'eldoc-documentation-functions #'lsp-eldoc-function t) + (remove-hook 'post-command-hook #'lsp--post-command t) + (remove-hook 'after-change-functions #'lsp-on-change t) + (remove-hook 'after-revert-hook #'lsp-on-revert t) + (remove-hook 'after-save-hook #'lsp-on-save t) + (remove-hook 'auto-save-hook #'lsp--on-auto-save t) + (remove-hook 'before-change-functions #'lsp-before-change t) + (remove-hook 'before-save-hook #'lsp--before-save t) + (remove-hook 'kill-buffer-hook #'lsp--text-document-did-close t) + + (lsp--update-on-type-formatting-hook :cleanup) + (lsp--update-signature-help-hook :cleanup) + + (when lsp--on-idle-timer + (cancel-timer lsp--on-idle-timer) + (setq lsp--on-idle-timer nil)) + + (remove-hook 'lsp-on-idle-hook #'lsp--document-links t) + (remove-hook 'lsp-on-idle-hook #'lsp--document-highlight t) + + (lsp--remove-overlays 'lsp-highlight) + (lsp--remove-overlays 'lsp-links) + + (remove-hook 'xref-backend-functions #'lsp--xref-backend t) + (remove-hook 'change-major-mode-hook #'lsp-disconnect t) + (remove-hook 'after-set-visited-file-name-hook #'lsp--after-set-visited-file-name t) + (setq-local lsp-buffer-uri nil)))) + +(defun lsp-configure-buffer () + "Configure LSP features for current buffer." + ;; make sure the core is running in the context of all available workspaces + ;; to avoid misconfiguration in case we are running in `with-lsp-workspace' context + (let ((lsp--buffer-workspaces (cond + (lsp--buffer-workspaces) + (lsp--cur-workspace (list lsp--cur-workspace)))) + lsp--cur-workspace) + (when lsp-auto-configure + (lsp--auto-configure) + + (when (and lsp-enable-text-document-color + (lsp-feature? "textDocument/documentColor")) + (add-hook 'lsp-on-change-hook #'lsp--document-color nil t)) + + (when (and lsp-enable-imenu + (lsp-feature? "textDocument/documentSymbol")) + (lsp-enable-imenu)) + + (when (and lsp-enable-indentation + (lsp-feature? "textDocument/rangeFormatting")) + (add-function :override (local 'indent-region-function) #'lsp-format-region)) + + (when (and lsp-enable-symbol-highlighting + (lsp-feature? "textDocument/documentHighlight")) + (add-hook 'lsp-on-idle-hook #'lsp--document-highlight nil t)) + + (when (and lsp-enable-links + (lsp-feature? "textDocument/documentLink")) + (add-hook 'lsp-on-idle-hook #'lsp--document-links nil t)) + + (when (and lsp-inlay-hint-enable + (lsp-feature? "textDocument/inlayHint")) + (lsp-inlay-hints-mode)) + + (when (and lsp-enable-dap-auto-configure + (functionp 'dap-mode)) + (dap-auto-configure-mode 1))) + (run-hooks 'lsp-configure-hook))) + +(defun lsp-unconfig-buffer () + "Unconfigure LSP features for buffer." + (lsp--remove-overlays 'lsp-color) + + (when (advice-function-member-p 'lsp--imenu-create-index imenu-create-index-function) + (remove-function (local 'imenu-create-index-function) #'lsp--imenu-create-index) + (setq-local imenu-menubar-modified-tick 0) + (setq-local imenu--index-alist nil) + (imenu--cleanup)) + + (remove-function (local 'indent-region-function) #'lsp-format-region) + + (remove-hook 'lsp-on-change-hook #'lsp--document-color t) + (remove-hook 'lsp-on-idle-hook #'lsp--document-highlight t) + (remove-hook 'lsp-on-idle-hook #'lsp--document-links t) + + (when (and lsp-enable-dap-auto-configure + (functionp 'dap-mode)) + (dap-auto-configure-mode -1)) + + (run-hooks 'lsp-unconfigure-hook)) + +(defun lsp--buffer-content () + (lsp-save-restriction-and-excursion + (or (lsp-virtual-buffer-call :buffer-string) + (buffer-substring-no-properties (point-min) + (point-max))))) + +(defun lsp--text-document-did-open () + "`document/didOpen' event." + (run-hooks 'lsp-before-open-hook) + (when (and lsp-auto-touch-files + (not (f-exists? (lsp--uri-to-path (lsp--buffer-uri))))) + (lsp--info "Saving file '%s' because it is not present on the disk." (lsp--buffer-uri)) + (save-buffer)) + + (setq lsp--cur-version (or lsp--cur-version 0)) + (cl-pushnew (lsp-current-buffer) (lsp--workspace-buffers lsp--cur-workspace)) + (lsp-notify + "textDocument/didOpen" + (list :textDocument + (list :uri (lsp--buffer-uri) + :languageId (lsp-buffer-language) + :version lsp--cur-version + :text (lsp--buffer-content)))) + + (lsp-managed-mode 1) + + (lsp-diagnostics--request-pull-diagnostics lsp--cur-workspace) + + (run-hooks 'lsp-after-open-hook) + (when-let ((client (-some-> lsp--cur-workspace (lsp--workspace-client)))) + (-some-> (lsp--client-after-open-fn client) + (funcall)) + (-some-> (format "lsp-%s-after-open-hook" (lsp--client-server-id client)) + (intern-soft) + (run-hooks)))) + +(defun lsp--text-document-identifier () + "Make TextDocumentIdentifier." + (list :uri (lsp--buffer-uri))) + +(defun lsp--versioned-text-document-identifier () + "Make VersionedTextDocumentIdentifier." + (plist-put (lsp--text-document-identifier) :version lsp--cur-version)) + +(defun lsp--cur-line (&optional point) + (1- (line-number-at-pos point))) + +(defun lsp--cur-position () + "Make a Position object for the current point." + (or (lsp-virtual-buffer-call :cur-position) + (lsp-save-restriction-and-excursion + (list :line (lsp--cur-line) + :character (- (point) (line-beginning-position)))))) + +(defun lsp--point-to-position (point) + "Convert POINT to Position." + (lsp-save-restriction-and-excursion + (goto-char point) + (lsp--cur-position))) + +(defun lsp--range (start end) + "Make Range body from START and END." + ;; make sure start and end are Position objects + (list :start start :end end)) + +(defun lsp--region-to-range (start end) + "Make Range object for the current region." + (lsp--range (lsp--point-to-position start) + (lsp--point-to-position end))) + +(defun lsp--region-or-line () + "The active region or the current line." + (if (use-region-p) + (lsp--region-to-range (region-beginning) (region-end)) + (lsp--region-to-range (line-beginning-position) (line-end-position)))) + +(defun lsp--check-document-changes-version (document-changes) + "Verify that DOCUMENT-CHANGES have the proper version." + (unless (seq-every-p + (-lambda ((&TextDocumentEdit :text-document)) + (or + (not text-document) + (let* ((filename (-> text-document + lsp:versioned-text-document-identifier-uri + lsp--uri-to-path)) + (version (lsp:versioned-text-document-identifier-version? text-document))) + (with-current-buffer (find-file-noselect filename) + (or (null version) (zerop version) (= -1 version) + (equal version lsp--cur-version)))))) + document-changes) + (error "Document changes cannot be applied due to different document version"))) + +(defun lsp--apply-workspace-edit (workspace-edit &optional operation) + "Apply the WorkspaceEdit object WORKSPACE-EDIT. +OPERATION is symbol representing the source of this text edit." + (-let (((&WorkspaceEdit :document-changes? :changes?) workspace-edit)) + (if-let ((document-changes (seq-reverse document-changes?))) + (progn + (lsp--check-document-changes-version document-changes) + (->> document-changes + (seq-filter (-lambda ((&CreateFile :kind)) (equal kind "create"))) + (seq-do (lambda (change) (lsp--apply-text-document-edit change operation)))) + (->> document-changes + (seq-filter (-lambda ((&CreateFile :kind)) + (and (or (not kind) (equal kind "edit")) + (not (equal kind "create"))))) + (seq-do (lambda (change) (lsp--apply-text-document-edit change operation)))) + (->> document-changes + (seq-filter (-lambda ((&CreateFile :kind)) + (and (not (or (not kind) (equal kind "edit"))) + (not (equal kind "create"))))) + (seq-do (lambda (change) (lsp--apply-text-document-edit change operation))))) + (lsp-map + (lambda (uri text-edits) + (with-current-buffer (-> uri lsp--uri-to-path find-file-noselect) + (lsp--apply-text-edits text-edits operation))) + changes?)))) + +(defmacro lsp-with-filename (file &rest body) + "Execute BODY with FILE as a context. +Need to handle the case when FILE indicates virtual buffer." + (declare (indent 1) (debug t)) + `(if-let ((lsp--virtual-buffer (get-text-property 0 'lsp-virtual-buffer ,file))) + (lsp-with-current-buffer lsp--virtual-buffer + ,@body) + ,@body)) + +(defun lsp--apply-text-document-edit (edit &optional operation) + "Apply the TextDocumentEdit object EDIT. +OPERATION is symbol representing the source of this text edit. +If the file is not being visited by any buffer, it is opened with +`find-file-noselect'. +Because lsp-mode does not store previous document versions, the edit is only +applied if the version of the textDocument matches the version of the +corresponding file. + +interface TextDocumentEdit { + textDocument: VersionedTextDocumentIdentifier; + edits: TextEdit[]; +}" + (pcase (lsp:edit-kind edit) + ("create" (-let* (((&CreateFile :uri :options?) edit) + (file-name (lsp--uri-to-path uri))) + (mkdir (f-dirname file-name) t) + (f-touch file-name) + (when (lsp:create-file-options-overwrite? options?) + (f-write-text "" nil file-name)) + (find-file-noselect file-name))) + ("delete" (-let (((&DeleteFile :uri :options? (&DeleteFileOptions? :recursive?)) edit)) + (f-delete (lsp--uri-to-path uri) recursive?))) + ("rename" (-let* (((&RenameFile :old-uri :new-uri :options? (&RenameFileOptions? :overwrite?)) edit) + (old-file-name (lsp--uri-to-path old-uri)) + (new-file-name (lsp--uri-to-path new-uri)) + (buf (find-buffer-visiting old-file-name))) + (when buf + (lsp-with-current-buffer buf + (save-buffer) + (lsp--text-document-did-close))) + (mkdir (f-dirname new-file-name) t) + (rename-file old-file-name new-file-name overwrite?) + (when buf + (lsp-with-current-buffer buf + (set-buffer-modified-p nil) + (setq lsp-buffer-uri nil) + (set-visited-file-name new-file-name) + (lsp))))) + (_ (let ((file-name (->> edit + (lsp:text-document-edit-text-document) + (lsp:versioned-text-document-identifier-uri) + (lsp--uri-to-path)))) + (lsp-with-current-buffer (find-buffer-visiting file-name) + (lsp-with-filename file-name + (lsp--apply-text-edits (lsp:text-document-edit-edits edit) operation))))))) + +(lsp-defun lsp--position-compare ((&Position :line left-line + :character left-character) + (&Position :line right-line + :character right-character)) + "Return t if position LEFT is greater than RIGHT." + (if (= left-line right-line) + (> left-character right-character) + (> left-line right-line))) + +(lsp-defun lsp-point-in-range? (position (&Range :start :end)) + "Returns if POINT is in RANGE." + (not (or (lsp--position-compare start position) + (lsp--position-compare position end)))) + +(lsp-defun lsp--position-equal ((&Position :line left-line + :character left-character) + (&Position :line right-line + :character right-character)) + "Return whether LEFT and RIGHT positions are equal." + (and (= left-line right-line) + (= left-character right-character))) + +(lsp-defun lsp--text-edit-sort-predicate ((&TextEdit :range (&Range :start left-start :end left-end)) + (&TextEdit :range (&Range :start right-start :end right-end))) + (if (lsp--position-equal left-start right-start) + (lsp--position-compare left-end right-end) + (lsp--position-compare left-start right-start))) + +(lsp-defun lsp--apply-text-edit ((edit &as &TextEdit :range (&RangeToPoint :start :end) :new-text)) + "Apply the edits described in the TextEdit object in TEXT-EDIT." + (setq new-text (s-replace "\r" "" (or new-text ""))) + (lsp:set-text-edit-new-text edit new-text) + (goto-char start) + (delete-region start end) + (insert new-text)) + +;; WORKAROUND: typescript-language might send -1 when applying code actions. +;; see https://github.com/emacs-lsp/lsp-mode/issues/1582 +(lsp-defun lsp--fix-point ((point &as &Position :character :line)) + (-doto point + (lsp:set-position-line (max 0 line)) + (lsp:set-position-character (max 0 character)))) + +(lsp-defun lsp--apply-text-edit-replace-buffer-contents ((edit &as + &TextEdit + :range (&Range :start :end) + :new-text)) + "Apply the edits described in the TextEdit object in TEXT-EDIT. +The method uses `replace-buffer-contents'." + (setq new-text (s-replace "\r" "" (or new-text ""))) + (lsp:set-text-edit-new-text edit new-text) + (-let* ((source (current-buffer)) + ((beg . end) (lsp--range-to-region (lsp-make-range :start (lsp--fix-point start) + :end (lsp--fix-point end))))) + (with-temp-buffer + (insert new-text) + (let ((temp (current-buffer))) + (with-current-buffer source + (save-excursion + (save-restriction + (narrow-to-region beg end) + + ;; On emacs versions < 26.2, + ;; `replace-buffer-contents' is buggy - it calls + ;; change functions with invalid arguments - so we + ;; manually call the change functions here. + ;; + ;; See emacs bugs #32237, #32278: + ;; https://debbugs.gnu.org/cgi/bugreport.cgi?bug=32237 + ;; https://debbugs.gnu.org/cgi/bugreport.cgi?bug=32278 + (let ((inhibit-modification-hooks t) + (length (- end beg))) + (run-hook-with-args 'before-change-functions + beg end) + (replace-buffer-contents temp) + (run-hook-with-args 'after-change-functions + beg (+ beg (length new-text)) + length))))))))) + +(defun lsp--to-yasnippet-snippet (snippet) + "Convert LSP SNIPPET to yasnippet snippet." + ;; LSP snippet doesn't escape "{" and "`", but yasnippet requires escaping it. + (replace-regexp-in-string (rx (or bos (not (any "$" "\\"))) (group (or "{" "`"))) + (rx "\\" (backref 1)) + snippet + nil nil 1)) + +(defvar-local lsp-enable-relative-indentation nil + "Enable relative indentation when insert texts, snippets ... +from language server.") + +(defun lsp--expand-snippet (snippet &optional start end expand-env) + "Wrapper of `yas-expand-snippet' with all of it arguments. +The snippet will be convert to LSP style and indent according to +LSP server result." + (require 'yasnippet nil t) + (let* ((inhibit-field-text-motion t) + (yas-wrap-around-region nil) + (yas-indent-line 'none) + (yas-also-auto-indent-first-line nil)) + (yas-expand-snippet + (lsp--to-yasnippet-snippet snippet) + start end expand-env))) + +(defun lsp--indent-lines (start end &optional insert-text-mode?) + "Indent from START to END based on INSERT-TEXT-MODE? value. +- When INSERT-TEXT-MODE? is provided + - if it's `lsp/insert-text-mode-as-it', do no editor indentation. + - if it's `lsp/insert-text-mode-adjust-indentation', adjust leading + whitespaces to match the line where text is inserted. +- When it's not provided, using `indent-line-function' for each line." + (save-excursion + (goto-char end) + (let* ((end-line (line-number-at-pos)) + (offset (save-excursion + (goto-char start) + (current-indentation))) + (indent-line-function + (cond ((equal insert-text-mode? lsp/insert-text-mode-as-it) + #'ignore) + ((or (equal insert-text-mode? lsp/insert-text-mode-adjust-indentation) + lsp-enable-relative-indentation + ;; Indenting snippets is extremely slow in `org-mode' buffers + ;; since it has to calculate indentation based on SRC block + ;; position. Thus we use relative indentation as default. + (derived-mode-p 'org-mode)) + (lambda () (save-excursion + (beginning-of-line) + (indent-to-column offset)))) + (t indent-line-function)))) + (goto-char start) + (forward-line) + (while (and (not (eobp)) + (<= (line-number-at-pos) end-line)) + (funcall indent-line-function) + (forward-line))))) + +(defun lsp--apply-text-edits (edits &optional operation) + "Apply the EDITS described in the TextEdit[] object. +OPERATION is symbol representing the source of this text edit." + (unless (seq-empty-p edits) + (atomic-change-group + (run-hooks 'lsp-before-apply-edits-hook) + (let* ((change-group (prepare-change-group)) + (howmany (length edits)) + (message (format "Applying %s edits to `%s' ..." howmany (current-buffer))) + (_ (lsp--info message)) + (reporter (make-progress-reporter message 0 howmany)) + (done 0) + (apply-edit (if (not lsp--virtual-buffer) + #'lsp--apply-text-edit-replace-buffer-contents + #'lsp--apply-text-edit))) + (unwind-protect + (->> edits + ;; We sort text edits so as to apply edits that modify latter + ;; parts of the document first. Furthermore, because the LSP + ;; spec dictates that: "If multiple inserts have the same + ;; position, the order in the array defines which edit to + ;; apply first." We reverse the initial list and sort stably + ;; to make sure the order among edits with the same position + ;; is preserved. + (nreverse) + (seq-sort #'lsp--text-edit-sort-predicate) + (mapc (lambda (edit) + (progress-reporter-update reporter (cl-incf done)) + (funcall apply-edit edit) + (when (lsp:snippet-text-edit-insert-text-format? edit) + (-when-let ((&SnippetTextEdit :range (&RangeToPoint :start) + :insert-text-format? :new-text) edit) + (when (eq insert-text-format? lsp/insert-text-format-snippet) + ;; No `save-excursion' needed since expand snippet will change point anyway + (goto-char (+ start (length new-text))) + (lsp--indent-lines start (point)) + (lsp--expand-snippet new-text start (point))))) + (run-hook-with-args 'lsp-after-apply-edits-hook operation)))) + (undo-amalgamate-change-group change-group) + (progress-reporter-done reporter)))))) + +(defun lsp--create-apply-text-edits-handlers () + "Create (handler cleanup-fn) for applying text edits in async request. +Only works when mode is `tick or `alive." + (let* (first-edited + (func (lambda (start &rest _) + (setq first-edited (if first-edited + (min start first-edited) + start))))) + (add-hook 'before-change-functions func nil t) + (list + (lambda (edits) + (if (and first-edited + (seq-find (-lambda ((&TextEdit :range (&RangeToPoint :end))) + ;; Text edit region is overlapped + (> end first-edited)) + edits)) + (lsp--warn "TextEdits will not be applied since document has been modified before of them.") + (lsp--apply-text-edits edits 'completion-cleanup))) + (lambda () + (remove-hook 'before-change-functions func t))))) + +(defun lsp--capability (cap &optional capabilities) + "Get the value of capability CAP. If CAPABILITIES is non-nil, use them instead." + (when (stringp cap) + (setq cap (intern (concat ":" cap)))) + + (lsp-get (or capabilities + (lsp--server-capabilities)) + cap)) + +(defun lsp--registered-capability (method) + "Check whether there is workspace providing METHOD." + (->> (lsp-workspaces) + (--keep (seq-find (lambda (reg) + (equal (lsp--registered-capability-method reg) method)) + (lsp--workspace-registered-server-capabilities it))) + cl-first)) + +(defun lsp--capability-for-method (method) + "Get the value of capability for METHOD." + (-let* ((reqs (cdr (assoc method lsp-method-requirements))) + ((&plist :capability) reqs)) + (or (and capability (lsp--capability capability)) + (-some-> (lsp--registered-capability method) + (lsp--registered-capability-options))))) + +(defvar-local lsp--before-change-vals nil + "Store the positions from the `lsp-before-change' function call, for +validation and use in the `lsp-on-change' function.") + +(defun lsp--text-document-content-change-event (start end length) + "Make a TextDocumentContentChangeEvent body for START to END, of length LENGTH." + ;; So (47 54 0) means add 7 chars starting at pos 47 + ;; must become + ;; {"range":{"start":{"line":5,"character":6} + ;; ,"end" :{"line":5,"character":6}} + ;; ,"rangeLength":0 + ;; ,"text":"\nbb = 5"} + ;; + ;; And (47 47 7) means delete 7 chars starting at pos 47 + ;; must become + ;; {"range":{"start":{"line":6,"character":0} + ;; ,"end" :{"line":7,"character":0}} + ;; ,"rangeLength":7 + ;; ,"text":""} + ;; + ;; (208 221 3) means delete 3 chars starting at pos 208, and replace them with + ;; 13 chars. So it must become + ;; {"range":{"start":{"line":5,"character":8} + ;; ,"end" :{"line":5,"character":11}} + ;; ,"rangeLength":3 + ;; ,"text":"new-chars-xxx"} + ;; + + ;; Adding text: + ;; lsp-before-change:(start,end)=(33,33) + ;; lsp-on-change:(start,end,length)=(33,34,0) + ;; + ;; Changing text: + ;; lsp-before-change:(start,end)=(208,211) + ;; lsp-on-change:(start,end,length)=(208,221,3) + ;; + ;; Deleting text: + ;; lsp-before-change:(start,end)=(19,27) + ;; lsp-on-change:(start,end,length)=(19,19,8) + (if (zerop length) + ;; Adding something only, work from start only + `( :range ,(lsp--range + (lsp--point-to-position start) + (lsp--point-to-position start)) + :rangeLength 0 + :text ,(buffer-substring-no-properties start end)) + + (if (eq start end) + ;; Deleting something only + (if (lsp--bracketed-change-p start length) + ;; The before-change value is bracketed, use it + `( :range ,(lsp--range + (lsp--point-to-position start) + (plist-get lsp--before-change-vals :end-pos)) + :rangeLength ,length + :text "") + ;; If the change is not bracketed, send a full change event instead. + (lsp--full-change-event)) + + ;; Deleting some things, adding others + (if (lsp--bracketed-change-p start length) + ;; The before-change value is valid, use it + `( :range ,(lsp--range + (lsp--point-to-position start) + (plist-get lsp--before-change-vals :end-pos)) + :rangeLength ,length + :text ,(buffer-substring-no-properties start end)) + (lsp--full-change-event))))) + +(defun lsp--bracketed-change-p (start length) + "If the before and after positions are the same, and the length +is the size of the start range, we are probably good." + (-let [(&plist :end before-end :start before-start) lsp--before-change-vals] + (and (eq start before-start) + (eq length (- before-end before-start))))) + +(defun lsp--full-change-event () + `(:text ,(lsp--buffer-content))) + +(defun lsp-before-change (start end) + "Executed before a file is changed. +Added to `before-change-functions'." + ;; Note: + ;; + ;; This variable holds a list of functions to call when Emacs is about to + ;; modify a buffer. Each function gets two arguments, the beginning and end of + ;; the region that is about to change, represented as integers. The buffer + ;; that is about to change is always the current buffer when the function is + ;; called. + ;; + ;; WARNING: + ;; + ;; Do not expect the before-change hooks and the after-change hooks be called + ;; in balanced pairs around each buffer change. Also don't expect the + ;; before-change hooks to be called for every chunk of text Emacs is about to + ;; delete. These hooks are provided on the assumption that Lisp programs will + ;; use either before- or the after-change hooks, but not both, and the + ;; boundaries of the region where the changes happen might include more than + ;; just the actual changed text, or even lump together several changes done + ;; piecemeal. + (save-match-data + (lsp-save-restriction-and-excursion + (setq lsp--before-change-vals + (list :start start + :end end + :end-pos (lsp--point-to-position end)))))) + +(defun lsp--flush-delayed-changes () + (let ((inhibit-quit t)) + (when lsp--delay-timer + (cancel-timer lsp--delay-timer)) + (mapc (-lambda ((workspace buffer document change)) + (with-current-buffer buffer + (with-lsp-workspace workspace + (lsp-notify "textDocument/didChange" + (list :textDocument document + :contentChanges (vector change)))))) + (prog1 (nreverse lsp--delayed-requests) + (setq lsp--delayed-requests nil))))) + +(defun lsp--workspace-sync-method (workspace) + (let ((sync (-> workspace + (lsp--workspace-server-capabilities) + (lsp:server-capabilities-text-document-sync?)))) + (if (lsp-text-document-sync-options? sync) + (lsp:text-document-sync-options-change? sync) + sync))) + +(defun lsp-on-change (start end length &optional content-change-event-fn) + "Executed when a file is changed. +Added to `after-change-functions'." + ;; Note: + ;; + ;; Each function receives three arguments: the beginning and end of the region + ;; just changed, and the length of the text that existed before the change. + ;; All three arguments are integers. The buffer that has been changed is + ;; always the current buffer when the function is called. + ;; + ;; The length of the old text is the difference between the buffer positions + ;; before and after that text as it was before the change. As for the + ;; changed text, its length is simply the difference between the first two + ;; arguments. + ;; + ;; So (47 54 0) means add 7 chars starting at pos 47 + ;; So (47 47 7) means delete 7 chars starting at pos 47 + (save-match-data + (let ((inhibit-quit t) + ;; make sure that `lsp-on-change' is called in multi-workspace context + ;; see #2901 + lsp--cur-workspace) + ;; A (revert-buffer) call with the 'preserve-modes parameter (eg, as done + ;; by auto-revert-mode) will cause this handler to get called with a nil + ;; buffer-file-name. We need the buffer-file-name to send notifications; + ;; so we skip handling revert-buffer-caused changes and instead handle + ;; reverts separately in lsp-on-revert + (when (not revert-buffer-in-progress-p) + (cl-incf lsp--cur-version) + (mapc + (lambda (workspace) + (pcase (or lsp-document-sync-method + (lsp--workspace-sync-method workspace)) + (1 + (if lsp-debounce-full-sync-notifications + (setq lsp--delayed-requests + (->> lsp--delayed-requests + (-remove (-lambda ((_ buffer)) + (equal (current-buffer) buffer))) + (cons (list workspace + (current-buffer) + (lsp--versioned-text-document-identifier) + (lsp--full-change-event))))) + (with-lsp-workspace workspace + (lsp-notify "textDocument/didChange" + (list :contentChanges (vector (lsp--full-change-event)) + :textDocument (lsp--versioned-text-document-identifier))) + (lsp-diagnostics--request-pull-diagnostics workspace)))) + (2 + (with-lsp-workspace workspace + (lsp-notify + "textDocument/didChange" + (list :textDocument (lsp--versioned-text-document-identifier) + :contentChanges (vector + (if content-change-event-fn + (funcall content-change-event-fn start end length) + (lsp--text-document-content-change-event + start end length))))) + (lsp-diagnostics--request-pull-diagnostics workspace))))) + (lsp-workspaces)) + (when lsp--delay-timer (cancel-timer lsp--delay-timer)) + (setq lsp--delay-timer (run-with-idle-timer + lsp-debounce-full-sync-notifications-interval + nil + #'lsp--flush-delayed-changes)) + ;; force cleanup overlays after each change + (lsp--remove-overlays 'lsp-highlight) + (lsp--after-change (current-buffer)))))) + + + +;; facilities for on change hooks. We do not want to make lsp calls on each +;; change event so we add debounce to avoid flooding the server with events. +;; Additionally, we want to have a mechanism for stopping the server calls in +;; particular cases like, e. g. when performing completion. + +(defvar lsp-inhibit-lsp-hooks nil + "Flag to control.") + +(defcustom lsp-on-change-hook nil + "Hooks to run when buffer has changed." + :type 'hook + :group 'lsp-mode) + +(defcustom lsp-idle-delay 0.500 + "Debounce interval for `after-change-functions'." + :type 'number + :group 'lsp-mode) + +(defcustom lsp-on-idle-hook nil + "Hooks to run after `lsp-idle-delay'." + :type 'hook + :group 'lsp-mode) + +(defun lsp--idle-reschedule (buffer) + (when lsp--on-idle-timer + (cancel-timer lsp--on-idle-timer)) + + (setq lsp--on-idle-timer (run-with-idle-timer + lsp-idle-delay + nil + #'lsp--on-idle + buffer))) + +(defun lsp--post-command () + (lsp--cleanup-highlights-if-needed) + (lsp--idle-reschedule (current-buffer))) + +(defun lsp--on-idle (buffer) + "Start post command loop." + (when (and (buffer-live-p buffer) + (equal buffer (current-buffer)) + (not lsp-inhibit-lsp-hooks) + lsp-managed-mode) + (run-hooks 'lsp-on-idle-hook))) + +(defun lsp--on-change-debounce (buffer) + (when (and (buffer-live-p buffer) + (equal buffer (current-buffer)) + (not lsp-inhibit-lsp-hooks) + lsp-managed-mode) + (run-hooks 'lsp-on-change-hook))) + +(defun lsp--after-change (buffer) + "Called after most textDocument/didChange events." + (setq lsp--signature-last-index nil + lsp--signature-last nil) + + ;; cleanup diagnostics + (when lsp-diagnostic-clean-after-change + (dolist (workspace (lsp-workspaces)) + (-let [diagnostics (lsp--workspace-diagnostics workspace)] + (remhash (lsp--fix-path-casing (buffer-file-name)) diagnostics)))) + + (when (fboundp 'lsp--semantic-tokens-refresh-if-enabled) + (lsp--semantic-tokens-refresh-if-enabled buffer)) + (when lsp--on-change-timer + (cancel-timer lsp--on-change-timer)) + (setq lsp--on-change-timer (run-with-idle-timer + lsp-idle-delay + nil + #'lsp--on-change-debounce + buffer)) + (lsp--idle-reschedule buffer)) + + +(defcustom lsp-trim-trailing-whitespace t + "Trim trailing whitespace on a line." + :group 'lsp-mode + :type 'boolean) + +(defcustom lsp-insert-final-newline t + "Insert a newline character at the end of the file if one does not exist." + :group 'lsp-mode + :type 'boolean) + +(defcustom lsp-trim-final-newlines t + "Trim all newlines after the final newline at the end of the file." + :group 'lsp-mode + :type 'boolean) + + +(defun lsp--on-type-formatting (first-trigger-characters more-trigger-characters) + "Self insert handling. +Applies on type formatting." + (let ((ch last-command-event)) + (when (or (eq (string-to-char first-trigger-characters) ch) + (cl-find ch more-trigger-characters :key #'string-to-char)) + (lsp-request-async "textDocument/onTypeFormatting" + (lsp-make-document-on-type-formatting-params + :text-document (lsp--text-document-identifier) + :options (lsp-make-formatting-options + :tab-size (symbol-value (lsp--get-indent-width major-mode)) + :insert-spaces (lsp-json-bool (not indent-tabs-mode)) + :trim-trailing-whitespace? (lsp-json-bool lsp-trim-trailing-whitespace) + :insert-final-newline? (lsp-json-bool lsp-insert-final-newline) + :trim-final-newlines? (lsp-json-bool lsp-trim-final-newlines)) + :ch (char-to-string ch) + :position (lsp--cur-position)) + (lambda (data) (lsp--apply-text-edits data 'format)) + :mode 'tick)))) + + +;; links +(defun lsp--document-links () + (when (lsp-feature? "textDocument/documentLink") + (lsp-request-async + "textDocument/documentLink" + `(:textDocument ,(lsp--text-document-identifier)) + (lambda (links) + (lsp--remove-overlays 'lsp-link) + (seq-do + (-lambda ((link &as &DocumentLink :range (&Range :start :end))) + (-doto (make-button (lsp--position-to-point start) + (lsp--position-to-point end) + 'action (lsp--document-link-keymap link) + 'keymap (let ((map (make-sparse-keymap))) + (define-key map [M-return] 'push-button) + (define-key map [mouse-2] 'push-button) + map) + 'help-echo "mouse-2, M-RET: Visit this link") + (overlay-put 'lsp-link t))) + links)) + :mode 'unchanged))) + +(defun lsp--document-link-handle-target (url) + (let* ((parsed-url (url-generic-parse-url (url-unhex-string url))) + (type (url-type parsed-url))) + (pcase type + ("file" + (xref-push-marker-stack) + (find-file (lsp--uri-to-path url)) + (-when-let ((_ line column) (s-match (rx "#" (group (1+ num)) (or "," "#") (group (1+ num))) url)) + (goto-char (lsp--position-to-point + (lsp-make-position :character (1- (string-to-number column)) + :line (1- (string-to-number line))))))) + ((or "http" "https") (browse-url url)) + (type (if-let ((handler (lsp--get-uri-handler type))) + (funcall handler url) + (signal 'lsp-file-scheme-not-supported (list url))))))) + +(lsp-defun lsp--document-link-keymap ((link &as &DocumentLink :target?)) + (if target? + (lambda (_) + (interactive) + (lsp--document-link-handle-target target?)) + (lambda (_) + (interactive) + (when (lsp:document-link-registration-options-resolve-provider? + (lsp--capability-for-method "textDocument/documentLink")) + (lsp-request-async + "documentLink/resolve" + link + (-lambda ((&DocumentLink :target?)) + (lsp--document-link-handle-target target?))))))) + + + +(defcustom lsp-warn-no-matched-clients t + "Whether to show messages when there are no supported clients." + :group 'lsp-mode + :type 'boolean) + +(defun lsp-buffer-language--configured-id () + "Return nil when not registered." + (->> lsp-language-id-configuration + (-first + (-lambda ((mode-or-pattern . language)) + (cond + ((and (stringp mode-or-pattern) + (s-matches? mode-or-pattern (buffer-file-name))) + language) + ((eq mode-or-pattern major-mode) language)))) + cl-rest)) + +(defvar-local lsp--buffer-language nil + "Locally cached returned value of `lsp-buffer-language'.") + +(defun lsp-buffer-language () + "Get language corresponding current buffer." + (or lsp--buffer-language + (let* ((configured-language (lsp-buffer-language--configured-id))) + (setq lsp--buffer-language + (or configured-language + ;; ensure non-nil + (string-remove-suffix "-mode" (symbol-name major-mode)))) + (when (and lsp-warn-no-matched-clients + (null configured-language)) + (lsp-warn "Unable to calculate the languageId for buffer `%s'. \ +Take a look at `lsp-language-id-configuration'. The `major-mode' is %s" + (buffer-name) + major-mode)) + lsp--buffer-language))) + +(defun lsp-activate-on (&rest languages) + "Returns language activation function. +The function will return t when the `lsp-buffer-language' returns +one of the LANGUAGES." + (lambda (_file-name _mode) + (-contains? languages (lsp-buffer-language)))) + +(defun lsp-workspace-root (&optional path) + "Find the workspace root for the current file or PATH." + (-when-let* ((file-name (or path (buffer-file-name))) + (file-name (lsp-f-canonical file-name))) + (->> (lsp-session) + (lsp-session-folders) + (--filter (and (lsp--files-same-host it file-name) + (or (lsp-f-ancestor-of? it file-name) + (equal it file-name)))) + (--max-by (> (length it) (length other)))))) + +(defun lsp-on-revert () + "Executed when a file is reverted. +Added to `after-revert-hook'." + (let ((n (buffer-size)) + (revert-buffer-in-progress-p nil)) + (lsp-on-change 0 n n))) + +(defun lsp--text-document-did-close (&optional keep-workspace-alive) + "Executed when the file is closed, added to `kill-buffer-hook'. + +If KEEP-WORKSPACE-ALIVE is non-nil, do not shutdown the workspace +if it's closing the last buffer in the workspace." + (lsp-foreach-workspace + (cl-callf2 delq (lsp-current-buffer) (lsp--workspace-buffers lsp--cur-workspace)) + (with-demoted-errors "Error sending didClose notification in ‘lsp--text-document-did-close’: %S" + (lsp-notify "textDocument/didClose" + `(:textDocument ,(lsp--text-document-identifier)))) + (when (and (not lsp-keep-workspace-alive) + (not keep-workspace-alive) + (not (lsp--workspace-buffers lsp--cur-workspace))) + (lsp--shutdown-workspace)))) + +(defun lsp--will-save-text-document-params (reason) + (list :textDocument (lsp--text-document-identifier) + :reason reason)) + +(defun lsp--before-save () + "Before save handler." + (with-demoted-errors "Error in ‘lsp--before-save’: %S" + (let ((params (lsp--will-save-text-document-params 1))) + (when (lsp--send-will-save-p) + (lsp-notify "textDocument/willSave" params)) + (when (and (lsp--send-will-save-wait-until-p) lsp-before-save-edits) + (let ((lsp-response-timeout 0.1)) + (condition-case nil + (lsp--apply-text-edits + (lsp-request "textDocument/willSaveWaitUntil" + params) + 'before-save) + (error))))))) + +(defun lsp--on-auto-save () + "Handler for auto-save." + (when (lsp--send-will-save-p) + (with-demoted-errors "Error in ‘lsp--on-auto-save’: %S" + (lsp-notify "textDocument/willSave" (lsp--will-save-text-document-params 2))))) + +(defun lsp--text-document-did-save () + "Executed when the file is closed, added to `after-save-hook''." + (when (lsp--send-did-save-p) + (with-demoted-errors "Error on ‘lsp--text-document-did-save: %S’" + (lsp-notify "textDocument/didSave" + `( :textDocument ,(lsp--versioned-text-document-identifier) + ,@(when (lsp--save-include-text-p) + (list :text (lsp--buffer-content)))))))) + +(defun lsp--text-document-position-params (&optional identifier position) + "Make TextDocumentPositionParams for the current point in the current document. +If IDENTIFIER and POSITION are non-nil, they will be used as the document +identifier and the position respectively." + (list :textDocument (or identifier (lsp--text-document-identifier)) + :position (or position (lsp--cur-position)))) + +(defun lsp--get-buffer-diagnostics () + "Return buffer diagnostics." + (gethash (or + (plist-get lsp--virtual-buffer :buffer-file-name) + (lsp--fix-path-casing (buffer-file-name))) + (lsp-diagnostics t))) + +(defun lsp-cur-line-diagnostics () + "Return any diagnostics that apply to the current line." + (-let [(&plist :start (&plist :line start) :end (&plist :line end)) (lsp--region-or-line)] + (cl-coerce (-filter + (-lambda ((&Diagnostic :range (&Range :start (&Position :line)))) + (and (>= line start) (<= line end))) + (lsp--get-buffer-diagnostics)) + 'vector))) + +(lsp-defun lsp-range-overlapping?((left &as &Range :start left-start :end left-end) + (right &as &Range :start right-start :end right-end)) + (or (lsp-point-in-range? right-start left) + (lsp-point-in-range? right-end left) + (lsp-point-in-range? left-start right) + (lsp-point-in-range? left-end right))) + +(defun lsp-make-position-1 (position) + (lsp-make-position :line (plist-get position :line) + :character (plist-get position :character))) + +(defun lsp-cur-possition-diagnostics () + "Return any diagnostics that apply to the current line." + (-let* ((start (if (use-region-p) (region-beginning) (point))) + (end (if (use-region-p) (region-end) (point))) + (current-range (lsp-make-range :start (lsp-make-position-1 (lsp-point-to-position start)) + :end (lsp-make-position-1 (lsp-point-to-position end))))) + (->> (lsp--get-buffer-diagnostics) + (-filter + (-lambda ((&Diagnostic :range)) + (lsp-range-overlapping? range current-range))) + (apply 'vector)))) + +(defalias 'lsp--cur-line-diagnotics 'lsp-cur-line-diagnostics) + +(defun lsp--extract-line-from-buffer (pos) + "Return the line pointed to by POS (a Position object) in the current buffer." + (let* ((point (lsp--position-to-point pos)) + (inhibit-field-text-motion t)) + (save-excursion + (goto-char point) + (buffer-substring (line-beginning-position) (line-end-position))))) + +(lsp-defun lsp--xref-make-item (filename (&Range :start (start &as &Position :character start-char :line start-line) + :end (end &as &Position :character end-char))) + "Return a xref-item from a RANGE in FILENAME." + (let* ((line (lsp--extract-line-from-buffer start)) + (len (length line))) + (add-face-text-property (max (min start-char len) 0) + (max (min end-char len) 0) + 'xref-match t line) + ;; LINE is nil when FILENAME is not being current visited by any buffer. + (xref-make-match (or line filename) + (xref-make-file-location + filename + (lsp-translate-line (1+ start-line)) + (lsp-translate-column start-char)) + (- end-char start-char)))) + +(defun lsp--location-uri (loc) + (if (lsp-location? loc) + (lsp:location-uri loc) + (lsp:location-link-target-uri loc))) + +(lsp-defun lsp-goto-location ((loc &as &Location :uri :range (&Range :start))) + "Go to location." + (let ((path (lsp--uri-to-path uri))) + (if (f-exists? path) + (with-current-buffer (find-file path) + (goto-char (lsp--position-to-point start))) + (error "There is no file %s" path)))) + +(defun lsp--location-range (loc) + (if (lsp-location? loc) + (lsp:location-range loc) + (lsp:location-link-target-selection-range loc))) + +(defun lsp--locations-to-xref-items (locations) + "Return a list of `xref-item' given LOCATIONS, which can be of +type Location, LocationLink, Location[] or LocationLink[]." + (setq locations + (pcase locations + ((seq (or (lsp-interface Location) + (lsp-interface LocationLink))) + (append locations nil)) + ((or (lsp-interface Location) + (lsp-interface LocationLink)) + (list locations)))) + + (cl-labels ((get-xrefs-in-file + (file-locs) + (-let [(filename . matches) file-locs] + (condition-case err + (let ((visiting (find-buffer-visiting filename)) + (fn (lambda (loc) + (lsp-with-filename filename + (lsp--xref-make-item filename + (lsp--location-range loc)))))) + (if visiting + (with-current-buffer visiting + (seq-map fn matches)) + (when (file-readable-p filename) + (with-temp-buffer + (insert-file-contents-literally filename) + (seq-map fn matches))))) + (error (lsp-warn "Failed to process xref entry for filename '%s': %s" + filename (error-message-string err))) + (file-error (lsp-warn "Failed to process xref entry, file-error, '%s': %s" + filename (error-message-string err))))))) + + (->> locations + (seq-sort #'lsp--location-before-p) + (seq-group-by (-compose #'lsp--uri-to-path #'lsp--location-uri)) + (seq-map #'get-xrefs-in-file) + (apply #'nconc)))) + +(defun lsp--location-before-p (left right) + "Sort first by file, then by line, then by column." + (let ((left-uri (lsp--location-uri left)) + (right-uri (lsp--location-uri right))) + (if (not (string= left-uri right-uri)) + (string< left-uri right-uri) + (-let (((&Range :start left-start) (lsp--location-range left)) + ((&Range :start right-start) (lsp--location-range right))) + (lsp--position-compare right-start left-start))))) + +(defun lsp--make-reference-params (&optional td-position exclude-declaration) + "Make a ReferenceParam object. +If TD-POSITION is non-nil, use it as TextDocumentPositionParams object instead. +If EXCLUDE-DECLARATION is non-nil, request the server to include declarations." + (let ((json-false :json-false)) + (plist-put (or td-position (lsp--text-document-position-params)) + :context `(:includeDeclaration ,(lsp-json-bool (not exclude-declaration)))))) + +(defun lsp--cancel-request (id) + "Cancel request with ID in all workspaces." + (lsp-foreach-workspace + (->> lsp--cur-workspace lsp--workspace-client lsp--client-response-handlers (remhash id)) + (lsp-notify "$/cancelRequest" `(:id ,id)))) + +(defvar-local lsp--hover-saved-bounds nil) + +(defun lsp-eldoc-function (cb &rest _ignored) + "`lsp-mode' eldoc function to display hover info (based on `textDocument/hover')." + (if (and lsp--hover-saved-bounds + (lsp--point-in-bounds-p lsp--hover-saved-bounds)) + lsp--eldoc-saved-message + (setq lsp--hover-saved-bounds nil + lsp--eldoc-saved-message nil) + (if (looking-at-p "[[:space:]\n]") + (setq lsp--eldoc-saved-message nil) ; And returns nil. + (when (and lsp-eldoc-enable-hover (lsp-feature? "textDocument/hover")) + (lsp-request-async + "textDocument/hover" + (lsp--text-document-position-params) + (-lambda ((hover &as &Hover? :range? :contents)) + (setq lsp--hover-saved-bounds (when range? + (lsp--range-to-region range?))) + (funcall cb (setq lsp--eldoc-saved-message + (when contents + (lsp--render-on-hover-content + contents + lsp-eldoc-render-all))))) + :error-handler #'ignore + :mode 'tick + :cancel-token :eldoc-hover))))) + +(defun lsp--point-on-highlight? () + (-some? (lambda (overlay) + (overlay-get overlay 'lsp-highlight)) + (overlays-at (point)))) + +(defun lsp--cleanup-highlights-if-needed () + (when (and lsp-enable-symbol-highlighting + lsp--have-document-highlights + (not (lsp--point-on-highlight?))) + (lsp--remove-overlays 'lsp-highlight) + (setq lsp--have-document-highlights nil) + (lsp-cancel-request-by-token :highlights))) + +(defvar-local lsp--symbol-bounds-of-last-highlight-invocation nil + "The bounds of the symbol from which `lsp--document-highlight' + most recently requested highlights.") + +(defun lsp--document-highlight () + (when (lsp-feature? "textDocument/documentHighlight") + (let ((curr-sym-bounds (bounds-of-thing-at-point 'symbol))) + (unless (or (looking-at-p "[[:space:]\n]") + (not lsp-enable-symbol-highlighting) + (and lsp--have-document-highlights + curr-sym-bounds + (equal curr-sym-bounds + lsp--symbol-bounds-of-last-highlight-invocation))) + (setq lsp--symbol-bounds-of-last-highlight-invocation + curr-sym-bounds) + (lsp-request-async "textDocument/documentHighlight" + (lsp--text-document-position-params) + #'lsp--document-highlight-callback + :mode 'tick + :cancel-token :highlights))))) + +(defun lsp--help-open-link (&rest _) + "Open markdown link at point via mouse or keyboard." + (interactive "P") + (let ((buffer-list-update-hook nil)) + (-let [(buffer point) (if-let* ((valid (and (listp last-input-event) + (eq (car last-input-event) 'mouse-2))) + (event (cadr last-input-event)) + (win (posn-window event)) + (buffer (window-buffer win))) + `(,buffer ,(posn-point event)) + `(,(current-buffer) ,(point)))] + (with-current-buffer buffer + (when-let* ((face (get-text-property point 'face)) + (url (or (and (eq face 'markdown-link-face) + (get-text-property point 'help-echo)) + (and (memq face '(markdown-url-face markdown-plain-url-face)) + (nth 3 (markdown-link-at-pos point)))))) + (lsp--document-link-handle-target url)))))) + +(defvar lsp-help-mode-map + (-doto (make-sparse-keymap) + (define-key [remap markdown-follow-link-at-point] #'lsp--help-open-link)) + "Keymap for `lsp-help-mode'.") + +(define-derived-mode lsp-help-mode help-mode "LspHelp" + "Major mode for displaying lsp help.") + +(defun lsp-describe-thing-at-point () + "Display the type signature and documentation of the thing at point." + (interactive) + (let ((contents (-some->> (lsp--text-document-position-params) + (lsp--make-request "textDocument/hover") + (lsp--send-request) + (lsp:hover-contents)))) + (if (and contents (not (equal contents ""))) + (let ((lsp-help-buf-name "*lsp-help*")) + (with-current-buffer (get-buffer-create lsp-help-buf-name) + (delay-mode-hooks + (lsp-help-mode) + (with-help-window lsp-help-buf-name + (insert (string-trim-right (lsp--render-on-hover-content contents t))))) + (run-mode-hooks))) + (lsp--info "No content at point.")))) + +(defun lsp--point-in-bounds-p (bounds) + "Return whether the current point is within BOUNDS." + (and (<= (car bounds) (point)) (< (point) (cdr bounds)))) + +(defun lsp-get-renderer (language) + "Get renderer for LANGUAGE." + (lambda (str) + (lsp--render-string str language))) + +(defun lsp--setup-markdown (mode) + "Setup the ‘markdown-mode’ in the frame. +MODE is the mode used in the parent frame." + (make-local-variable 'markdown-code-lang-modes) + (dolist (mark (alist-get mode lsp-custom-markup-modes)) + (add-to-list 'markdown-code-lang-modes (cons mark mode))) + (setq-local markdown-fontify-code-blocks-natively t) + (setq-local markdown-fontify-code-block-default-mode mode) + (setq-local markdown-hide-markup t) + + ;; Render some common HTML entities. + ;; This should really happen in markdown-mode instead, + ;; but it doesn't, so we do it here for now. + (setq prettify-symbols-alist + (cl-loop for i from 0 to 255 + collect (cons (format "&#x%02X;" i) i))) + (push '("<" . ?<) prettify-symbols-alist) + (push '(">" . ?>) prettify-symbols-alist) + (push '("&" . ?&) prettify-symbols-alist) + (push '(" " . ? ) prettify-symbols-alist) + (setq prettify-symbols-compose-predicate + (lambda (_start _end _match) t)) + (prettify-symbols-mode 1)) + +(defvar lsp-help-link-keymap + (let ((map (make-sparse-keymap))) + (define-key map [mouse-2] #'lsp--help-open-link) + (define-key map "\r" #'lsp--help-open-link) + map) + "Keymap active on links in *lsp-help* mode.") + +(defun lsp--fix-markdown-links () + (let ((inhibit-read-only t) + (inhibit-modification-hooks t) + (prop)) + (save-restriction + (goto-char (point-min)) + (while (setq prop (markdown-find-next-prop 'face)) + (let ((end (or (next-single-property-change (car prop) 'face) + (point-max)))) + (when (memq (get-text-property (car prop) 'face) + '(markdown-link-face + markdown-url-face + markdown-plain-url-face)) + (add-text-properties (car prop) end + (list 'button t + 'category 'lsp-help-link + 'follow-link t + 'keymap lsp-help-link-keymap))) + (goto-char end)))))) + +(defun lsp--buffer-string-visible () + "Return visible buffer string. +Stolen from `org-copy-visible'." + (let ((temp (generate-new-buffer " *temp*")) + (beg (point-min)) + (end (point-max))) + (while (/= beg end) + (when (get-char-property beg 'invisible) + (setq beg (next-single-char-property-change beg 'invisible nil end))) + (let* ((next (next-single-char-property-change beg 'invisible nil end)) + (substring (buffer-substring beg next))) + (with-current-buffer temp (insert substring)) + ;; (setq result (concat result substring)) + (setq beg next))) + (setq deactivate-mark t) + (prog1 (with-current-buffer temp + (s-chop-suffix "\n" (buffer-string))) + (kill-buffer temp)))) + +(defvar lsp-buffer-major-mode nil + "Holds the major mode when fontification function is running. +See #2588") + +(defvar view-inhibit-help-message) + +(defun lsp--render-markdown () + "Render markdown." + + (let ((markdown-enable-math nil)) + (goto-char (point-min)) + (while (re-search-forward + (rx (and "\\" (group (or "\\" "`" "*" "_" ":" "/" + "{" "}" "[" "]" "(" ")" + "#" "+" "-" "." "!" "|")))) + nil t) + (replace-match (rx (backref 1)))) + + ;; markdown-mode v2.3 does not yet provide gfm-view-mode + (if (fboundp 'gfm-view-mode) + (let ((view-inhibit-help-message t)) + (gfm-view-mode)) + (gfm-mode)) + + (lsp--setup-markdown lsp-buffer-major-mode))) + +(defvar lsp--display-inline-image-alist + '((lsp--render-markdown + (:regexp + "!\\[.*?\\](data:image/[a-zA-Z]+;base64,\\([A-Za-z0-9+/\n]+?=*?\\)\\(|[^)]+\\)?)" + :sexp + (create-image + (base64-decode-string + (buffer-substring-no-properties (match-beginning 1) (match-end 1))) + nil t)))) + "Replaced string regexp and function returning image. +Each element should have the form (MODE . (PROPERTY-LIST...)). +MODE (car) is function which is defined in `lsp-language-id-configuration'. +Cdr should be list of PROPERTY-LIST. + +Each PROPERTY-LIST should have properties: +:regexp Regexp which determines what string is relpaced to image. + You should also get information of image, by parenthesis constructs. + By default, all matched string is replaced to image, but you can + change index of replaced string by keyword :replaced-index. + +:sexp Return image when evaluated. You can use information of regexp + by using (match-beggining N), (match-end N) or (match-substring N). + +In addition, each can have property: +:replaced-index Determine index which is used to replace regexp to image. + The value means first argument of `match-beginning' and + `match-end'. If omitted, interpreted as index 0.") + +(defcustom lsp-display-inline-image t + "Showing inline image or not." + :group 'lsp-mode + :type 'boolean) + +(defcustom lsp-enable-suggest-server-download t + "When non-nil enable server downloading suggestions." + :group 'lsp-mode + :type 'boolean + :package-version '(lsp-mode . "9.0.0")) + +(defcustom lsp-auto-register-remote-clients t + "When non-nil register remote when registering the local one." + :group 'lsp-mode + :type 'boolean + :package-version '(lsp-mode . "9.0.0")) + +(defun lsp--display-inline-image (mode) + "Add image property if available." + (let ((plist-list (cdr (assq mode lsp--display-inline-image-alist)))) + (when (and (display-images-p) lsp-display-inline-image) + (cl-loop + for plist in plist-list + with regexp with replaced-index + do + (setq regexp (plist-get plist :regexp)) + (setq replaced-index (or (plist-get plist :replaced-index) 0)) + + (font-lock-remove-keywords nil (list regexp replaced-index)) + (let ((inhibit-read-only t)) + (save-excursion + (goto-char (point-min)) + (while (re-search-forward regexp nil t) + (set-text-properties + (match-beginning replaced-index) (match-end replaced-index) + nil) + (add-text-properties + (match-beginning replaced-index) (match-end replaced-index) + `(display ,(eval (plist-get plist :sexp))))))))))) + +(defun lsp--fontlock-with-mode (str mode) + "Fontlock STR with MODE." + (let ((lsp-buffer-major-mode major-mode)) + (with-temp-buffer + (with-demoted-errors "Error during doc rendering: %s" + (insert str) + (delay-mode-hooks (funcall mode)) + (cl-flet ((window-body-width () lsp-window-body-width)) + ;; This can go wrong in some cases, and the fontification would + ;; not work as expected. + ;; + ;; See #2984 + (ignore-errors (font-lock-ensure)) + (lsp--display-inline-image mode) + (when (eq mode 'lsp--render-markdown) + (lsp--fix-markdown-links)))) + (lsp--buffer-string-visible)))) + +(defun lsp--render-string (str language) + "Render STR using `major-mode' corresponding to LANGUAGE. +When language is nil render as markup if `markdown-mode' is loaded." + (setq str (s-replace "\r" "" (or str ""))) + (if-let* ((modes (-keep (-lambda ((mode . lang)) + (when (and (equal lang language) (functionp mode)) + mode)) + lsp-language-id-configuration)) + (mode (car (or (member major-mode modes) modes)))) + (lsp--fontlock-with-mode str mode) + str)) + +(defun lsp--render-element (content) + "Render CONTENT element." + (let ((inhibit-message t)) + (or + (pcase content + ((lsp-interface MarkedString :value :language) + (lsp--render-string value language)) + ((lsp-interface MarkupContent :value :kind) + (lsp--render-string value kind)) + ;; plain string + ((pred stringp) (lsp--render-string content "markdown")) + ((pred null) "") + (_ (error "Failed to handle %s" content))) + ""))) + +(defun lsp--create-unique-string-fn () + (let (elements) + (lambda (element) + (let ((count (cl-count element elements :test #'string=))) + (prog1 (if (zerop count) + element + (format "%s (%s)" element count)) + (push element elements)))))) + +(defun lsp--select-action (actions) + "Select an action to execute from ACTIONS." + (cond + ((seq-empty-p actions) (signal 'lsp-no-code-actions nil)) + ((and (eq (seq-length actions) 1) lsp-auto-execute-action) + (lsp-seq-first actions)) + (t (let ((completion-ignore-case t)) + (lsp--completing-read "Select code action: " + (seq-into actions 'list) + (-compose (lsp--create-unique-string-fn) + #'lsp:code-action-title) + nil t))))) + +(defun lsp--workspace-server-id (workspace) + "Return the server ID of WORKSPACE." + (-> workspace lsp--workspace-client lsp--client-server-id)) + +(defun lsp--handle-rendered-for-echo-area (contents) + "Return a single line from RENDERED, appropriate for display in the echo area." + (pcase (lsp-workspaces) + (`(,workspace) + (lsp-clients-extract-signature-on-hover contents (lsp--workspace-server-id workspace))) + ;; For projects with multiple active workspaces we also default to + ;; render the first line. + (_ (lsp-clients-extract-signature-on-hover contents nil)))) + +(cl-defmethod lsp-clients-extract-signature-on-hover (contents _server-id) + "Extract a representative line from CONTENTS, to show in the echo area." + (car (s-lines (s-trim (lsp--render-element contents))))) + +(defun lsp--render-on-hover-content (contents render-all) + "Render the content received from `document/onHover' request. +CONTENTS - MarkedString | MarkedString[] | MarkupContent +RENDER-ALL - nil if only the signature should be rendered." + (cond + ((lsp-markup-content? contents) + ;; MarkupContent. + ;; It tends to be long and is not suitable to display fully in the echo area. + ;; Just display the first line which is typically the signature. + (if render-all + (lsp--render-element contents) + (lsp--handle-rendered-for-echo-area contents))) + ((and (stringp contents) (not (string-match-p "\n" contents))) + ;; If the contents is a single string containing a single line, + ;; render it always. + (lsp--render-element contents)) + (t + ;; MarkedString -> MarkedString[] + (when (or (lsp-marked-string? contents) (stringp contents)) + (setq contents (list contents))) + ;; Consider the signature consisting of the elements who have a renderable + ;; "language" property. When render-all is nil, ignore other elements. + (string-join + (seq-map + #'lsp--render-element + (if render-all + contents + ;; Only render contents that have an available renderer. + (seq-take + (seq-filter + (-andfn #'lsp-marked-string? + (-compose #'lsp-get-renderer #'lsp:marked-string-language)) + contents) + 1))) + (if (bound-and-true-p page-break-lines-mode) + "\n\n" + "\n"))))) + + + +(defvar lsp-signature-mode-map + (-doto (make-sparse-keymap) + (define-key (kbd "M-n") #'lsp-signature-next) + (define-key (kbd "M-p") #'lsp-signature-previous) + (define-key (kbd "M-a") #'lsp-signature-toggle-full-docs) + (define-key (kbd "C-c C-k") #'lsp-signature-stop) + (define-key (kbd "C-g") #'lsp-signature-stop)) + "Keymap for `lsp-signature-mode'.") + +(define-minor-mode lsp-signature-mode + "Mode used to show signature popup." + :keymap lsp-signature-mode-map + :lighter "" + :group 'lsp-mode) + +(defun lsp-signature-stop () + "Stop showing current signature help." + (interactive) + (lsp-cancel-request-by-token :signature) + (remove-hook 'post-command-hook #'lsp-signature) + (funcall lsp-signature-function nil) + (lsp-signature-mode -1)) + +(declare-function page-break-lines--update-display-tables "ext:page-break-lines") + +(defun lsp--setup-page-break-mode-if-present () + "Enable `page-break-lines-mode' in current buffer." + (when (fboundp 'page-break-lines-mode) + (page-break-lines-mode) + ;; force page-break-lines-mode to update the display tables. + (page-break-lines--update-display-tables))) + +(defun lsp-lv-message (message) + (add-hook 'lv-window-hook #'lsp--setup-page-break-mode-if-present) + (if message + (progn + (setq lsp--signature-last-buffer (current-buffer)) + (let ((lv-force-update t)) + (lv-message "%s" message))) + (lv-delete-window) + (remove-hook 'lv-window-hook #'lsp--setup-page-break-mode-if-present))) + +(declare-function posframe-show "ext:posframe") +(declare-function posframe-hide "ext:posframe") +(declare-function posframe-poshandler-point-bottom-left-corner-upward "ext:posframe") + +(defface lsp-signature-posframe + '((t :inherit tooltip)) + "Background and foreground for `lsp-signature-posframe'." + :group 'lsp-mode) + +(defvar lsp-signature-posframe-params + (list :poshandler #'posframe-poshandler-point-bottom-left-corner-upward + :height 10 + :width 60 + :border-width 1 + :min-width 60) + "Params for signature and `posframe-show'.") + +(defun lsp-signature-posframe (str) + "Use posframe to show the STR signatureHelp string." + (if str + (apply #'posframe-show + (with-current-buffer (get-buffer-create " *lsp-signature*") + (erase-buffer) + (insert str) + (visual-line-mode 1) + (lsp--setup-page-break-mode-if-present) + (current-buffer)) + (append + lsp-signature-posframe-params + (list :position (point) + :background-color (face-attribute 'lsp-signature-posframe :background nil t) + :foreground-color (face-attribute 'lsp-signature-posframe :foreground nil t) + :border-color (face-attribute 'font-lock-comment-face :foreground nil t)))) + (posframe-hide " *lsp-signature*"))) + +(defun lsp--handle-signature-update (signature) + (let ((message + (if (lsp-signature-help? signature) + (lsp--signature->message signature) + (mapconcat #'lsp--signature->message signature "\n")))) + (if (s-present? message) + (funcall lsp-signature-function message) + (lsp-signature-stop)))) + +(defun lsp-signature-activate () + "Activate signature help. +It will show up only if current point has signature help." + (interactive) + (setq lsp--signature-last nil + lsp--signature-last-index nil + lsp--signature-last-buffer (current-buffer)) + (add-hook 'post-command-hook #'lsp-signature) + (lsp-signature-mode t)) + +(defcustom lsp-signature-cycle t + "Whether `lsp-signature-next' and prev should cycle." + :type 'boolean + :group 'lsp-mode) + +(defun lsp-signature-next () + "Show next signature." + (interactive) + (let ((nsigs (length (lsp:signature-help-signatures lsp--signature-last)))) + (when (and lsp--signature-last-index + lsp--signature-last + (or lsp-signature-cycle (< (1+ lsp--signature-last-index) nsigs))) + (setq lsp--signature-last-index (% (1+ lsp--signature-last-index) nsigs)) + (funcall lsp-signature-function (lsp--signature->message lsp--signature-last))))) + +(defun lsp-signature-previous () + "Next signature." + (interactive) + (when (and lsp--signature-last-index + lsp--signature-last + (or lsp-signature-cycle (not (zerop lsp--signature-last-index)))) + (setq lsp--signature-last-index (1- (if (zerop lsp--signature-last-index) + (length (lsp:signature-help-signatures lsp--signature-last)) + lsp--signature-last-index))) + (funcall lsp-signature-function (lsp--signature->message lsp--signature-last)))) + +(defun lsp-signature-toggle-full-docs () + "Toggle full/partial signature documentation." + (interactive) + (let ((all? (not (numberp lsp-signature-doc-lines)))) + (setq lsp-signature-doc-lines (if all? + (or (car-safe lsp-signature-doc-lines) + 20) + (list lsp-signature-doc-lines)))) + (lsp-signature-activate)) + +(defun lsp--signature->message (signature-help) + "Generate eldoc message from SIGNATURE-HELP response." + (setq lsp--signature-last signature-help) + + (when (and signature-help (not (seq-empty-p (lsp:signature-help-signatures signature-help)))) + (-let* (((&SignatureHelp :active-signature? + :active-parameter? + :signatures) signature-help) + (active-signature? (or lsp--signature-last-index active-signature? 0)) + (_ (setq lsp--signature-last-index active-signature?)) + ((signature &as &SignatureInformation? :label :parameters?) (seq-elt signatures active-signature?)) + (prefix (if (= (length signatures) 1) + "" + (concat (propertize (format " %s/%s" + (1+ active-signature?) + (length signatures)) + 'face 'success) + " "))) + (method-docs (when + (and lsp-signature-render-documentation + (or (not (numberp lsp-signature-doc-lines)) (< 0 lsp-signature-doc-lines))) + (let ((docs (lsp--render-element + (lsp:parameter-information-documentation? signature)))) + (when (s-present? docs) + (concat + "\n" + (if (fboundp 'page-break-lines-mode) + "\n" + "") + (if (and (numberp lsp-signature-doc-lines) + (> (length (s-lines docs)) lsp-signature-doc-lines)) + (concat (s-join "\n" (-take lsp-signature-doc-lines (s-lines docs))) + (propertize "\nTruncated..." 'face 'highlight)) + docs))))))) + (when (and active-parameter? (not (seq-empty-p parameters?))) + (-when-let* ((param (when (and (< -1 active-parameter? (length parameters?))) + (seq-elt parameters? active-parameter?))) + (selected-param-label (let ((label (lsp:parameter-information-label param))) + (if (stringp label) label (append label nil)))) + (start (if (stringp selected-param-label) + (s-index-of selected-param-label label) + (cl-first selected-param-label))) + (end (if (stringp selected-param-label) + (+ start (length selected-param-label)) + (cl-second selected-param-label)))) + (add-face-text-property start end 'eldoc-highlight-function-argument nil label))) + (concat prefix label method-docs)))) + +(defun lsp-signature () + "Display signature info (based on `textDocument/signatureHelp')" + (if (and lsp--signature-last-buffer + (not (equal (current-buffer) lsp--signature-last-buffer))) + (lsp-signature-stop) + (lsp-request-async "textDocument/signatureHelp" + (lsp--text-document-position-params) + #'lsp--handle-signature-update + :cancel-token :signature))) + + +(defcustom lsp-overlay-document-color-char "■" + "Display the char represent the document color in overlay" + :type 'string + :group 'lsp-mode) + +;; color presentation +(defun lsp--color-create-interactive-command (color range) + (lambda () + (interactive) + (-let [(&ColorPresentation? :text-edit? + :additional-text-edits?) + (lsp--completing-read + "Select color presentation: " + (lsp-request + "textDocument/colorPresentation" + `( :textDocument ,(lsp--text-document-identifier) + :color ,color + :range ,range)) + #'lsp:color-presentation-label + nil + t)] + (when text-edit? + (lsp--apply-text-edit text-edit?)) + (when additional-text-edits? + (lsp--apply-text-edits additional-text-edits? 'color-presentation))))) + +(defun lsp--number->color (number) + (let ((result (format "%x" + (round (* (or number 0) 255.0))))) + (if (= 1 (length result)) + (concat "0" result) + result))) + +(defun lsp--document-color () + "Document color handler." + (when (lsp-feature? "textDocument/documentColor") + (lsp-request-async + "textDocument/documentColor" + `(:textDocument ,(lsp--text-document-identifier)) + (lambda (result) + (lsp--remove-overlays 'lsp-color) + (seq-do + (-lambda ((&ColorInformation :color (color &as &Color :red :green :blue) + :range)) + (-let* (((beg . end) (lsp--range-to-region range)) + (overlay (make-overlay beg end)) + (command (lsp--color-create-interactive-command color range))) + (overlay-put overlay 'lsp-color t) + (overlay-put overlay 'evaporate t) + (overlay-put overlay + 'before-string + (propertize + lsp-overlay-document-color-char + 'face `((:foreground ,(format + "#%s%s%s" + (lsp--number->color red) + (lsp--number->color green) + (lsp--number->color blue)))) + 'action command + 'mouse-face 'lsp-lens-mouse-face + 'local-map (-doto (make-sparse-keymap) + (define-key [mouse-1] command)))))) + result)) + :mode 'unchanged + :cancel-token :document-color-token))) + + + +(defun lsp--action-trigger-parameter-hints (_command) + "Handler for editor.action.triggerParameterHints." + (when (member :on-server-request lsp-signature-auto-activate) + (lsp-signature-activate))) + +(defun lsp--action-trigger-suggest (_command) + "Handler for editor.action.triggerSuggest." + (cond + ((and (bound-and-true-p company-mode) + (fboundp 'company-auto-begin) + (fboundp 'company-post-command)) + (run-at-time 0 nil + (lambda () + (let ((this-command 'company-idle-begin) + (company-minimum-prefix-length 0)) + (company-auto-begin) + (company-post-command))))) + (t + (completion-at-point)))) + +(defconst lsp--default-action-handlers + (ht ("editor.action.triggerParameterHints" #'lsp--action-trigger-parameter-hints) + ("editor.action.triggerSuggest" #'lsp--action-trigger-suggest)) + "Default action handlers.") + +(defun lsp--find-action-handler (command) + "Find action handler for particular COMMAND." + (or + (--some (-some->> it + (lsp--workspace-client) + (lsp--client-action-handlers) + (gethash command)) + (lsp-workspaces)) + (gethash command lsp--default-action-handlers))) + +(defun lsp--text-document-code-action-params (&optional kind) + "Code action params." + (list :textDocument (lsp--text-document-identifier) + :range (if (use-region-p) + (lsp--region-to-range (region-beginning) (region-end)) + (lsp--region-to-range (point) (point))) + :context `( :diagnostics ,(lsp-cur-possition-diagnostics) + ,@(when kind (list :only (vector kind)))))) + +(defun lsp-code-actions-at-point (&optional kind) + "Retrieve the code actions for the active region or the current line. +It will filter by KIND if non nil." + (lsp-request "textDocument/codeAction" (lsp--text-document-code-action-params kind))) + +(defun lsp-execute-code-action-by-kind (command-kind) + "Execute code action by COMMAND-KIND." + (if-let ((action (->> (lsp-get-or-calculate-code-actions command-kind) + (-filter (-lambda ((&CodeAction :kind?)) + (and kind? (s-prefix? command-kind kind?)))) + lsp--select-action))) + (lsp-execute-code-action action) + (signal 'lsp-no-code-actions '(command-kind)))) + +(defalias 'lsp-get-or-calculate-code-actions 'lsp-code-actions-at-point) + +(lsp-defun lsp--execute-command ((action &as &Command :command :arguments?)) + "Parse and execute a code ACTION represented as a Command LSP type." + (let ((server-id (->> (lsp-workspaces) + (cl-first) + (or lsp--cur-workspace) + (lsp--workspace-client) + (lsp--client-server-id)))) + (condition-case nil + (with-no-warnings + (lsp-execute-command server-id (intern command) arguments?)) + (cl-no-applicable-method + (if-let ((action-handler (lsp--find-action-handler command))) + (funcall action-handler action) + (lsp-send-execute-command command arguments?)))))) + +(lsp-defun lsp-execute-code-action ((action &as &CodeAction :command? :edit?)) + "Execute code action ACTION. For example, when text under the +caret has a suggestion to apply a fix from an lsp-server, calling +this function will do so. +If ACTION is not set it will be selected from `lsp-code-actions-at-point'. +Request codeAction/resolve for more info if server supports." + (interactive (list (lsp--select-action (lsp-code-actions-at-point)))) + (if (and (lsp-feature? "codeAction/resolve") + (not command?) + (not edit?)) + (lsp--execute-code-action (lsp-request "codeAction/resolve" action)) + (lsp--execute-code-action action))) + +(lsp-defun lsp--execute-code-action ((action &as &CodeAction :command? :edit?)) + "Execute code action ACTION." + (when edit? + (lsp--apply-workspace-edit edit? 'code-action)) + + (cond + ((stringp command?) (lsp--execute-command action)) + ((lsp-command? command?) (progn + (when-let ((action-filter (->> (lsp-workspaces) + (cl-first) + (or lsp--cur-workspace) + (lsp--workspace-client) + (lsp--client-action-filter)))) + (funcall action-filter command?)) + (lsp--execute-command command?))))) + +(lsp-defun lsp-fix-code-action-booleans ((&Command :arguments?) boolean-action-arguments) + "Patch incorrect boolean argument values in the provided `CodeAction' command +in place, based on the BOOLEAN-ACTION-ARGUMENTS list. The values +in this list can be either symbols or lists of symbols that +represent paths to boolean arguments in code actions: + +> (lsp-fix-code-action-booleans command `(:foo :bar (:some :nested :boolean))) + +When there are available code actions, the server sends +`lsp-mode' a list of possible command names and arguments as +JSON. `lsp-mode' parses all boolean false values as `nil'. As a +result code action arguments containing falsy values don't +roundtrip correctly because `lsp-mode' will end up sending null +values back to the client. This list makes it possible to +selectively transform `nil' values back into `:json-false'." + (seq-doseq (path boolean-action-arguments) + (seq-doseq (args arguments?) + (lsp--fix-nested-boolean args (if (listp path) path (list path)))))) + +(defun lsp--fix-nested-boolean (structure path) + "Traverse STRUCTURE using the paths from the PATH list, changing the value to +`:json-false' if it was `nil'. PATH should be a list containing +one or more symbols, and STRUCTURE should be compatible with +`lsp-member?', `lsp-get', and `lsp-put'." + (let ((key (car path)) + (rest (cdr path))) + (if (null rest) + ;; `lsp-put' returns `nil' both when the key doesn't exist and when the + ;; value is `nil', so we need to explicitly check its presence here + (when (and (lsp-member? structure key) (not (lsp-get structure key))) + (lsp-put structure key :json-false)) + ;; If `key' does not exist, then we'll silently ignore it + (when-let ((child (lsp-get structure key))) + (lsp--fix-nested-boolean child rest))))) + +(defvar lsp--formatting-indent-alist + ;; Taken from `dtrt-indent-mode' + '( + (ada-mode . ada-indent) ; Ada + (ada-ts-mode . ada-ts-mode-indent-offset) + (c++-mode . c-basic-offset) ; C++ + (c++-ts-mode . c-ts-mode-indent-offset) + (c-mode . c-basic-offset) ; C + (c-ts-mode . c-ts-mode-indent-offset) + (cperl-mode . cperl-indent-level) ; Perl + (crystal-mode . crystal-indent-level) ; Crystal (Ruby) + (csharp-mode . c-basic-offset) ; C# + (csharp-tree-sitter-mode . csharp-tree-sitter-indent-offset) ; C# + (csharp-ts-mode . csharp-ts-mode-indent-offset) ; C# (tree-sitter, Emacs29) + (css-mode . css-indent-offset) ; CSS + (d-mode . c-basic-offset) ; D + (enh-ruby-mode . enh-ruby-indent-level) ; Ruby + (erlang-mode . erlang-indent-level) ; Erlang + (ess-mode . ess-indent-offset) ; ESS (R) + (go-ts-mode . go-ts-mode-indent-offset) + (gpr-mode . gpr-indent-offset) ; GNAT Project + (gpr-ts-mode . gpr-ts-mode-indent-offset) + (hack-mode . hack-indent-offset) ; Hack + (java-mode . c-basic-offset) ; Java + (java-ts-mode . java-ts-mode-indent-offset) + (jde-mode . c-basic-offset) ; Java (JDE) + (js-mode . js-indent-level) ; JavaScript + (js-ts-mode . js-indent-level) + (js2-mode . js2-basic-offset) ; JavaScript-IDE + (js3-mode . js3-indent-level) ; JavaScript-IDE + (json-mode . js-indent-level) ; JSON + (json-ts-mode . json-ts-mode-indent-offset) + (lua-mode . lua-indent-level) ; Lua + (lua-ts-mode . lua-ts-indent-offset) + (nxml-mode . nxml-child-indent) ; XML + (objc-mode . c-basic-offset) ; Objective C + (pascal-mode . pascal-indent-level) ; Pascal + (perl-mode . perl-indent-level) ; Perl + (php-mode . c-basic-offset) ; PHP + (php-ts-mode . php-ts-mode-indent-offset) ; PHP + (powershell-mode . powershell-indent) ; PowerShell + (powershell-ts-mode . powershell-ts-mode-indent-offset) ; PowerShell + (raku-mode . raku-indent-offset) ; Perl6/Raku + (ruby-mode . ruby-indent-level) ; Ruby + (rust-mode . rust-indent-offset) ; Rust + (rust-ts-mode . rust-ts-mode-indent-offset) + (rustic-mode . rustic-indent-offset) ; Rust + (scala-mode . scala-indent:step) ; Scala + (sgml-mode . sgml-basic-offset) ; SGML + (sh-mode . sh-basic-offset) ; Shell Script + (toml-ts-mode . toml-ts-mode-indent-offset) + (typescript-mode . typescript-indent-level) ; Typescript + (typescript-ts-mode . typescript-ts-mode-indent-offset) ; Typescript (tree-sitter, Emacs29) + (yaml-mode . yaml-indent-offset) ; YAML + (yang-mode . c-basic-offset) ; YANG (yang-mode) + + (default . standard-indent)) ; default fallback + "A mapping from `major-mode' to its indent variable.") + +(defun lsp--get-indent-width (mode) + "Get indentation offset for MODE." + (or (alist-get mode lsp--formatting-indent-alist) + (lsp--get-indent-width (or (get mode 'derived-mode-parent) 'default)))) + +(defun lsp--make-document-formatting-params () + "Create document formatting params." + (lsp-make-document-formatting-params + :text-document (lsp--text-document-identifier) + :options (lsp-make-formatting-options + :tab-size (symbol-value (lsp--get-indent-width major-mode)) + :insert-spaces (lsp-json-bool (not indent-tabs-mode)) + :trim-trailing-whitespace? (lsp-json-bool lsp-trim-trailing-whitespace) + :insert-final-newline? (lsp-json-bool lsp-insert-final-newline) + :trim-final-newlines? (lsp-json-bool lsp-trim-final-newlines)))) + +(defun lsp-format-buffer () + "Ask the server to format this document." + (interactive "*") + (cond ((lsp-feature? "textDocument/formatting") + (let ((edits (lsp-request "textDocument/formatting" + (lsp--make-document-formatting-params)))) + (if (seq-empty-p edits) + (lsp--info "No formatting changes provided") + (lsp--apply-text-edits edits 'format)))) + ((lsp-feature? "textDocument/rangeFormatting") + (save-restriction + (widen) + (lsp-format-region (point-min) (point-max)))) + (t (signal 'lsp-capability-not-supported (list "documentFormattingProvider"))))) + +(defun lsp-format-region (s e) + "Ask the server to format the region, or if none is selected, the current line." + (interactive "r") + (let ((edits (lsp-request + "textDocument/rangeFormatting" + (lsp--make-document-range-formatting-params s e)))) + (if (seq-empty-p edits) + (lsp--info "No formatting changes provided") + (lsp--apply-text-edits edits 'format)))) + +(defmacro lsp-make-interactive-code-action (func-name code-action-kind) + "Define an interactive function FUNC-NAME that attempts to +execute a CODE-ACTION-KIND action." + `(defun ,(intern (concat "lsp-" (symbol-name func-name))) () + ,(format "Perform the %s code action, if available." code-action-kind) + (interactive) + ;; Even when `lsp-auto-execute-action' is nil, it still makes sense to + ;; auto-execute here: the user has specified exactly what they want. + (let ((lsp-auto-execute-action t)) + (condition-case nil + (lsp-execute-code-action-by-kind ,code-action-kind) + (lsp-no-code-actions + (when (called-interactively-p 'any) + (lsp--info ,(format "%s action not available" code-action-kind)))))))) + +(lsp-make-interactive-code-action organize-imports "source.organizeImports") + +(defun lsp--make-document-range-formatting-params (start end) + "Make DocumentRangeFormattingParams for selected region." + (lsp:set-document-range-formatting-params-range (lsp--make-document-formatting-params) + (lsp--region-to-range start end))) + +(defconst lsp--highlight-kind-face + '((1 . lsp-face-highlight-textual) + (2 . lsp-face-highlight-read) + (3 . lsp-face-highlight-write))) + +(defun lsp--remove-overlays (name) + (save-restriction + (widen) + (remove-overlays (point-min) (point-max) name t))) + +(defun lsp-document-highlight () + "Highlight all relevant references to the symbol under point." + (interactive) + (lsp--remove-overlays 'lsp-highlight) ;; clear any previous highlights + (setq lsp--have-document-highlights nil + lsp--symbol-bounds-of-last-highlight-invocation nil) + (let ((lsp-enable-symbol-highlighting t)) + (lsp--document-highlight))) + +(defun lsp--document-highlight-callback (highlights) + "Create a callback to process the reply of a +`textDocument/documentHighlight' message for the buffer BUF. +A reference is highlighted only if it is visible in a window." + (lsp--remove-overlays 'lsp-highlight) + + (let* ((wins-visible-pos (-map (lambda (win) + (cons (1- (line-number-at-pos (window-start win) t)) + (1+ (line-number-at-pos (window-end win) t)))) + (get-buffer-window-list nil nil 'visible)))) + (setq lsp--have-document-highlights t) + (-map + (-lambda ((&DocumentHighlight :range (&Range :start (start &as &Position :line start-line) + :end (end &as &Position :line end-line)) + :kind?)) + (-map + (-lambda ((start-window . end-window)) + ;; Make the overlay only if the reference is visible + (when (and (> (1+ start-line) start-window) + (< (1+ end-line) end-window)) + (let ((start-point (lsp--position-to-point start)) + (end-point (lsp--position-to-point end))) + (when (not (and lsp-symbol-highlighting-skip-current + (<= start-point (point) end-point))) + (-doto (make-overlay start-point end-point) + (overlay-put 'face (cdr (assq (or kind? 1) lsp--highlight-kind-face))) + (overlay-put 'lsp-highlight t)))))) + wins-visible-pos)) + highlights))) + +(defcustom lsp-symbol-kinds + '((1 . "File") + (2 . "Module") + (3 . "Namespace") + (4 . "Package") + (5 . "Class") + (6 . "Method") + (7 . "Property") + (8 . "Field") + (9 . "Constructor") + (10 . "Enum") + (11 . "Interface") + (12 . "Function") + (13 . "Variable") + (14 . "Constant") + (15 . "String") + (16 . "Number") + (17 . "Boolean") + (18 . "Array") + (19 . "Object") + (20 . "Key") + (21 . "Null") + (22 . "Enum Member") + (23 . "Struct") + (24 . "Event") + (25 . "Operator") + (26 . "Type Parameter")) + "Alist mapping SymbolKinds to human-readable strings. +Various Symbol objects in the LSP protocol have an integral type, +specifying what they are. This alist maps such type integrals to +readable representations of them. See +`https://microsoft.github.io/language-server-protocol/specifications/specification-current/', +namespace SymbolKind." + :group 'lsp-mode + :type '(alist :key-type integer :value-type string)) +(defalias 'lsp--symbol-kind 'lsp-symbol-kinds) + +(lsp-defun lsp--symbol-information-to-xref + ((&SymbolInformation :kind :name + :location (&Location :uri :range (&Range :start + (&Position :line :character))))) + "Return a `xref-item' from SYMBOL information." + (xref-make (format "[%s] %s" (alist-get kind lsp-symbol-kinds) name) + (xref-make-file-location (lsp--uri-to-path uri) + line + character))) + +(defun lsp--get-document-symbols () + "Get document symbols. + +If the buffer has not been modified since symbols were last +retrieved, simply return the latest result. + +Else, if the request was initiated by Imenu updating its menu-bar +entry, perform it asynchronously; i.e., give Imenu the latest +result and then force a refresh when a new one is available. + +Else (e.g., due to interactive use of `imenu' or `xref'), +perform the request synchronously." + (if (= (buffer-chars-modified-tick) lsp--document-symbols-tick) + lsp--document-symbols + (let ((method "textDocument/documentSymbol") + (params `(:textDocument ,(lsp--text-document-identifier))) + (tick (buffer-chars-modified-tick))) + (if (not lsp--document-symbols-request-async) + (prog1 + (setq lsp--document-symbols (lsp-request method params)) + (setq lsp--document-symbols-tick tick)) + (lsp-request-async method params + (lambda (document-symbols) + (setq lsp--document-symbols document-symbols + lsp--document-symbols-tick tick) + (lsp--imenu-refresh)) + :mode 'alive + :cancel-token :document-symbols) + lsp--document-symbols)))) + +(advice-add 'imenu-update-menubar :around + (lambda (oldfun &rest r) + (let ((lsp--document-symbols-request-async t)) + (apply oldfun r)))) + +(defun lsp--document-symbols->document-symbols-hierarchy (document-symbols current-position) + "Convert DOCUMENT-SYMBOLS to symbols hierarchy on CURRENT-POSITION." + (-let (((symbol &as &DocumentSymbol? :children?) + (seq-find (-lambda ((&DocumentSymbol :range)) + (lsp-point-in-range? current-position range)) + document-symbols))) + (if children? + (cons symbol (lsp--document-symbols->document-symbols-hierarchy children? current-position)) + (when symbol + (list symbol))))) + +(lsp-defun lsp--symbol-information->document-symbol ((&SymbolInformation :name :kind :location :container-name? :deprecated?)) + "Convert a SymbolInformation to a DocumentInformation" + (lsp-make-document-symbol :name name + :kind kind + :range (lsp:location-range location) + :children? nil + :deprecated? deprecated? + :selection-range (lsp:location-range location) + :detail? container-name?)) + +(defun lsp--symbols-informations->document-symbols-hierarchy (symbols-informations current-position) + "Convert SYMBOLS-INFORMATIONS to symbols hierarchy on CURRENT-POSITION." + (--> symbols-informations + (-keep (-lambda ((symbol &as &SymbolInformation :location (&Location :range))) + (when (lsp-point-in-range? current-position range) + (lsp--symbol-information->document-symbol symbol))) + it) + (sort it (-lambda ((&DocumentSymbol :range (&Range :start a-start-position :end a-end-position)) + (&DocumentSymbol :range (&Range :start b-start-position :end b-end-position))) + (and (lsp--position-compare b-start-position a-start-position) + (lsp--position-compare a-end-position b-end-position)))))) + +(defun lsp--symbols->document-symbols-hierarchy (symbols) + "Convert SYMBOLS to symbols-hierarchy." + (when-let ((first-symbol (lsp-seq-first symbols))) + (let ((cur-position (lsp-make-position :line (plist-get (lsp--cur-position) :line) + :character (plist-get (lsp--cur-position) :character)))) + (if (lsp-symbol-information? first-symbol) + (lsp--symbols-informations->document-symbols-hierarchy symbols cur-position) + (lsp--document-symbols->document-symbols-hierarchy symbols cur-position))))) + +(defun lsp--xref-backend () 'xref-lsp) + +(cl-defmethod xref-backend-identifier-at-point ((_backend (eql xref-lsp))) + (propertize (or (thing-at-point 'symbol) "") + 'identifier-at-point t)) + +(defun lsp--xref-elements-index (symbols path) + (-mapcat + (-lambda (sym) + (pcase-exhaustive sym + ((lsp-interface DocumentSymbol :name :children? :selection-range (lsp-interface Range :start)) + (cons (cons (concat path name) + (lsp--position-to-point start)) + (lsp--xref-elements-index children? (concat path name " / ")))) + ((lsp-interface SymbolInformation :name :location (lsp-interface Location :range (lsp-interface Range :start))) + (list (cons (concat path name) + (lsp--position-to-point start)))))) + symbols)) + +(defvar-local lsp--symbols-cache nil) + +(cl-defmethod xref-backend-identifier-completion-table ((_backend (eql xref-lsp))) + (if (lsp--find-workspaces-for "textDocument/documentSymbol") + (progn + (setq lsp--symbols-cache (lsp--xref-elements-index + (lsp--get-document-symbols) nil)) + lsp--symbols-cache) + (list (propertize (or (thing-at-point 'symbol) "") + 'identifier-at-point t)))) + +(cl-defmethod xref-backend-definitions ((_backend (eql xref-lsp)) identifier) + (save-excursion + (unless (get-text-property 0 'identifier-at-point identifier) + (goto-char (cl-rest (or (assoc identifier lsp--symbols-cache) + (user-error "Unable to find symbol %s in current document" identifier))))) + (lsp--locations-to-xref-items (lsp-request "textDocument/definition" + (lsp--text-document-position-params))))) + +(cl-defmethod xref-backend-references ((_backend (eql xref-lsp)) identifier) + (save-excursion + (unless (get-text-property 0 'identifier-at-point identifier) + (goto-char (cl-rest (or (assoc identifier lsp--symbols-cache) + (user-error "Unable to find symbol %s" identifier))))) + (lsp--locations-to-xref-items (lsp-request "textDocument/references" + (lsp--make-reference-params nil lsp-references-exclude-definition))))) + +(cl-defmethod xref-backend-apropos ((_backend (eql xref-lsp)) pattern) + (seq-map #'lsp--symbol-information-to-xref + (lsp-request "workspace/symbol" `(:query ,pattern)))) + +(defcustom lsp-rename-use-prepare t + "Whether `lsp-rename' should do a prepareRename first. +For some language servers, textDocument/prepareRename might be +too slow, in which case this variable may be set to nil. +`lsp-rename' will then use `thing-at-point' `symbol' to determine +the symbol to rename at point." + :group 'lsp-mode + :type 'boolean) + +(defun lsp--get-symbol-to-rename () + "Get a symbol to rename and placeholder at point. +Returns a cons ((START . END) . PLACEHOLDER?), and nil if +renaming is generally supported but cannot be done at point. +START and END are the bounds of the identifiers being renamed, +while PLACEHOLDER?, is either nil or a string suggested by the +language server as the initial input of a new-name prompt." + (unless (lsp-feature? "textDocument/rename") + (error "The connected server(s) doesn't support renaming")) + (if (and lsp-rename-use-prepare (lsp-feature? "textDocument/prepareRename")) + (when-let ((response + (lsp-request "textDocument/prepareRename" + (lsp--text-document-position-params)))) + (let* ((bounds (lsp--range-to-region + (if (lsp-range? response) + response + (lsp:prepare-rename-result-range response)))) + (placeholder + (and (not (lsp-range? response)) + (lsp:prepare-rename-result-placeholder response)))) + (cons bounds placeholder))) + (when-let ((bounds (bounds-of-thing-at-point 'symbol))) + (cons bounds nil)))) + +(defface lsp-face-rename '((t :underline t)) + "Face used to highlight the identifier being renamed. +Renaming can be done using `lsp-rename'." + :group 'lsp-mode) + +(defface lsp-rename-placeholder-face '((t :inherit font-lock-variable-name-face)) + "Face used to display the rename placeholder in. +When calling `lsp-rename' interactively, this will be the face of +the new name." + :group 'lsp-mode) + +(defvar lsp-rename-history '() + "History for `lsp--read-rename'.") + +(defun lsp--read-rename (at-point) + "Read a new name for a `lsp-rename' at `point' from the user. +AT-POINT shall be a structure as returned by +`lsp--get-symbol-to-rename'. + +Returns a string, which should be the new name for the identifier +at point. If renaming cannot be done at point (as determined from +AT-POINT), throw a `user-error'. + +This function is for use in `lsp-rename' only, and shall not be +relied upon." + (unless at-point + (user-error "`lsp-rename' is invalid here")) + (-let* ((((start . end) . placeholder?) at-point) + ;; Do the `buffer-substring' first to not include `lsp-face-rename' + (rename-me (buffer-substring start end)) + (placeholder (or placeholder? rename-me)) + (placeholder (propertize placeholder 'face 'lsp-rename-placeholder-face)) + + overlay) + ;; We need unwind protect, as the user might cancel here, causing the + ;; overlay to linger. + (unwind-protect + (progn + (setq overlay (make-overlay start end)) + (overlay-put overlay 'face 'lsp-face-rename) + + (read-string (format "Rename %s to: " rename-me) placeholder + 'lsp-rename-history)) + (and overlay (delete-overlay overlay))))) + +(defun lsp-rename (newname) + "Rename the symbol (and all references to it) under point to NEWNAME." + (interactive (list (lsp--read-rename (lsp--get-symbol-to-rename)))) + (when-let ((edits (lsp-request "textDocument/rename" + `( :textDocument ,(lsp--text-document-identifier) + :position ,(lsp--cur-position) + :newName ,newname)))) + (lsp--apply-workspace-edit edits 'rename))) + +(defun lsp--on-rename-file (old-func old-name new-name &optional ok-if-already-exists?) + "Advice around function `rename-file'. +Applies OLD-FUNC with OLD-NAME, NEW-NAME and OK-IF-ALREADY-EXISTS?. + +This advice sends workspace/willRenameFiles before renaming file +to check if server wants to apply any workspaceEdits after renamed." + (if (and lsp-apply-edits-after-file-operations + (lsp--send-will-rename-files-p old-name)) + (let ((params (lsp-make-rename-files-params + :files (vector (lsp-make-file-rename + :oldUri (lsp--path-to-uri old-name) + :newUri (lsp--path-to-uri new-name)))))) + (when-let ((edits (lsp-request "workspace/willRenameFiles" params))) + (lsp--apply-workspace-edit edits 'rename-file) + (funcall old-func old-name new-name ok-if-already-exists?) + (when (lsp--send-did-rename-files-p) + (lsp-notify "workspace/didRenameFiles" params)))) + (funcall old-func old-name new-name ok-if-already-exists?))) + +(advice-add 'rename-file :around #'lsp--on-rename-file) + +(defcustom lsp-xref-force-references nil + "If non-nil threat everything as references(e. g. jump if only one item.)" + :group 'lsp-mode + :type 'boolean) + +(defun lsp-show-xrefs (xrefs display-action references?) + (unless (region-active-p) (push-mark nil t)) + (if (boundp 'xref-show-definitions-function) + (with-no-warnings + (xref-push-marker-stack) + (funcall (if (and references? (not lsp-xref-force-references)) + xref-show-xrefs-function + xref-show-definitions-function) + (-const xrefs) + `((window . ,(selected-window)) + (display-action . ,display-action) + ,(if (and references? (not lsp-xref-force-references)) + `(auto-jump . ,xref-auto-jump-to-first-xref) + `(auto-jump . ,xref-auto-jump-to-first-definition))))) + (xref--show-xrefs xrefs display-action))) + +(cl-defmethod seq-empty-p ((ht hash-table)) + "Function `seq-empty-p' for hash-table." + (hash-table-empty-p ht)) + +(cl-defun lsp-find-locations (method &optional extra &key display-action references?) + "Send request named METHOD and get cross references of the symbol under point. +EXTRA is a plist of extra parameters. +REFERENCES? t when METHOD returns references." + (let ((loc (lsp-request method + (append (lsp--text-document-position-params) extra)))) + (if (seq-empty-p loc) + (lsp--error "Not found for: %s" (or (thing-at-point 'symbol t) "")) + (lsp-show-xrefs (lsp--locations-to-xref-items loc) display-action references?)))) + +(cl-defun lsp-find-declaration (&key display-action) + "Find declarations of the symbol under point." + (interactive) + (lsp-find-locations "textDocument/declaration" nil :display-action display-action)) + +(cl-defun lsp-find-definition (&key display-action) + "Find definitions of the symbol under point." + (interactive) + (lsp-find-locations "textDocument/definition" nil :display-action display-action)) + +(defun lsp-find-definition-mouse (click) + "Click to start `lsp-find-definition' at clicked point." + (interactive "e") + (let* ((ec (event-start click)) + (p1 (posn-point ec)) + (w1 (posn-window ec))) + (select-window w1) + (goto-char p1) + (lsp-find-definition))) + +(cl-defun lsp-find-implementation (&key display-action) + "Find implementations of the symbol under point." + (interactive) + (lsp-find-locations "textDocument/implementation" + nil + :display-action display-action + :references? t)) + +(cl-defun lsp-find-references (&optional exclude-declaration &key display-action) + "Find references of the symbol under point." + (interactive "P") + (lsp-find-locations "textDocument/references" + (list :context `(:includeDeclaration ,(lsp-json-bool (not (or exclude-declaration lsp-references-exclude-definition))))) + :display-action display-action + :references? t)) + +(cl-defun lsp-find-type-definition (&key display-action) + "Find type definitions of the symbol under point." + (interactive) + (lsp-find-locations "textDocument/typeDefinition" nil :display-action display-action)) + +(defalias 'lsp-find-custom #'lsp-find-locations) +(defalias 'lsp-goto-implementation #'lsp-find-implementation) +(defalias 'lsp-goto-type-definition #'lsp-find-type-definition) + +(with-eval-after-load 'evil + (evil-set-command-property 'lsp-find-definition :jump t) + (evil-set-command-property 'lsp-find-implementation :jump t) + (evil-set-command-property 'lsp-find-references :jump t) + (evil-set-command-property 'lsp-find-type-definition :jump t)) + +(defun lsp--workspace-method-supported? (check-command method capability workspace) + (with-lsp-workspace workspace + (if check-command + (funcall check-command workspace) + (or + (when capability (lsp--capability capability)) + (lsp--registered-capability method) + (and (not capability) (not check-command)))))) + +(defun lsp-disable-method-for-server (method server-id) + "Disable METHOD for SERVER-ID." + (cl-callf + (lambda (reqs) + (-let (((&plist :check-command :capability) reqs)) + (list :check-command + (lambda (workspace) + (unless (-> workspace + lsp--workspace-client + lsp--client-server-id + (eq server-id)) + (lsp--workspace-method-supported? check-command + method + capability + workspace)))))) + (alist-get method lsp-method-requirements nil nil 'string=))) + +(defun lsp--find-workspaces-for (msg-or-method) + "Find all workspaces in the current project that can handle MSG." + (let ((method (if (stringp msg-or-method) + msg-or-method + (plist-get msg-or-method :method)))) + (-if-let (reqs (cdr (assoc method lsp-method-requirements))) + (-let (((&plist :capability :check-command) reqs)) + (-filter + (-partial #'lsp--workspace-method-supported? + check-command method capability) + (lsp-workspaces))) + (lsp-workspaces)))) + +(defun lsp-can-execute-command? (command-name) + "Returns non-nil if current language server(s) can execute COMMAND-NAME. +The command is executed via `workspace/executeCommand'" + (cl-position + command-name + (lsp:execute-command-options-commands + (lsp:server-capabilities-execute-command-provider? + (lsp--server-capabilities))) + :test #'equal)) + +(defalias 'lsp-feature? 'lsp--find-workspaces-for) + +(cl-defmethod lsp-execute-command (_server _command _arguments) + "Dispatch COMMAND execution." + (signal 'cl-no-applicable-method nil)) + +(defun lsp-workspace-command-execute (command &optional args) + "Execute workspace COMMAND with ARGS." + (condition-case-unless-debug err + (let ((params (if args + (list :command command :arguments args) + (list :command command)))) + (lsp-request "workspace/executeCommand" params)) + (error + (error "`workspace/executeCommand' with `%s' failed.\n\n%S" + command err)))) + +(defun lsp-send-execute-command (command &optional args) + "Create and send a `workspace/executeCommand' message having command COMMAND +and optional ARGS." + (lsp-workspace-command-execute command args)) + +(defalias 'lsp-point-to-position #'lsp--point-to-position) +(defalias 'lsp-text-document-identifier #'lsp--text-document-identifier) +(defalias 'lsp--send-execute-command #'lsp-send-execute-command) +(defalias 'lsp-on-open #'lsp--text-document-did-open) +(defalias 'lsp-on-save #'lsp--text-document-did-save) + +(defun lsp--set-configuration (settings) + "Set the SETTINGS for the lsp server." + (lsp-notify "workspace/didChangeConfiguration" `(:settings ,settings))) + +(defun lsp-current-buffer () + (or lsp--virtual-buffer + (current-buffer))) + +(defun lsp-buffer-live-p (buffer-id) + (if-let ((buffer-live (plist-get buffer-id :buffer-live?))) + (funcall buffer-live buffer-id) + (buffer-live-p buffer-id))) + +(defun lsp--on-set-visited-file-name (old-func &rest args) + "Advice around function `set-visited-file-name'. + +This advice sends textDocument/didClose for the old file and +textDocument/didOpen for the new file." + (when lsp--cur-workspace + (lsp--text-document-did-close t)) + (prog1 (apply old-func args) + (when lsp--cur-workspace + (lsp--text-document-did-open)))) + +(advice-add 'set-visited-file-name :around #'lsp--on-set-visited-file-name) + +(defcustom lsp-flush-delayed-changes-before-next-message t + "If non-nil send the document changes update before sending other messages. + +If nil, and `lsp-debounce-full-sync-notifications' is non-nil, + change notifications will be throttled by + `lsp-debounce-full-sync-notifications-interval' regardless of + other messages." + :group 'lsp-mode + :type 'boolean) + +(defvar lsp--not-flushing-delayed-changes t) + +(defun lsp--send-no-wait (message proc) + "Send MESSAGE to PROC without waiting for further output." + + (when (and lsp--not-flushing-delayed-changes + lsp-flush-delayed-changes-before-next-message) + (let ((lsp--not-flushing-delayed-changes nil)) + (lsp--flush-delayed-changes))) + (lsp-process-send proc message)) + +(define-error 'lsp-parse-error + "Error parsing message from language server" 'lsp-error) +(define-error 'lsp-unknown-message-type + "Unknown message type" '(lsp-error lsp-parse-error)) +(define-error 'lsp-unknown-json-rpc-version + "Unknown JSON-RPC protocol version" '(lsp-error lsp-parse-error)) +(define-error 'lsp-no-content-length + "Content-Length header missing in message" '(lsp-error lsp-parse-error)) +(define-error 'lsp-invalid-header-name + "Invalid header name" '(lsp-error lsp-parse-error)) + +;; id method +;; x x request +;; x . response +;; . x notification +(defun lsp--get-message-type (json-data) + "Get the message type from JSON-DATA." + (if (lsp:json-message-id? json-data) + (if (lsp:json-message-error? json-data) + 'response-error + (if (lsp:json-message-method? json-data) + 'request + 'response)) + 'notification)) + +(defconst lsp--default-notification-handlers + (ht ("window/showMessage" #'lsp--window-show-message) + ("window/logMessage" #'lsp--window-log-message) + ("window/showInputBox" #'lsp--window-show-input-box) + ("window/showQuickPick" #'lsp--window-show-quick-pick) + ("textDocument/publishDiagnostics" #'lsp--on-diagnostics) + ("textDocument/diagnosticsEnd" #'ignore) + ("textDocument/diagnosticsBegin" #'ignore) + ("telemetry/event" #'ignore) + ("$/progress" (lambda (workspace params) + (funcall lsp-progress-function workspace params))))) + +(lsp-defun lsp--on-notification (workspace (&JSONNotification :params :method)) + "Call the appropriate handler for NOTIFICATION." + (-let ((client (lsp--workspace-client workspace))) + (when (lsp--log-io-p method) + (lsp--log-entry-new (lsp--make-log-entry method nil params 'incoming-notif) + lsp--cur-workspace)) + (if-let ((handler (or (gethash method (lsp--client-notification-handlers client)) + (gethash method lsp--default-notification-handlers)))) + (funcall handler workspace params) + (when (and method (not (string-prefix-p "$" method))) + (lsp-warn "Unknown notification: %s" method))))) + +(lsp-defun lsp--build-workspace-configuration-response ((&ConfigurationParams :items)) + "Get section configuration. +PARAMS are the `workspace/configuration' request params" + (->> items + (-map (-lambda ((&ConfigurationItem :section?)) + (-let* ((path-parts (split-string section? "\\.")) + (path-without-last (s-join "." (-slice path-parts 0 -1))) + (path-parts-len (length path-parts))) + (cond + ((<= path-parts-len 1) + (ht-get (lsp-configuration-section section?) + (car-safe path-parts) + (ht-create))) + ((> path-parts-len 1) + (when-let ((section (lsp-configuration-section path-without-last)) + (keys path-parts)) + (while (and keys section) + (setf section (ht-get section (pop keys)))) + section)))))) + (apply #'vector))) + +(defun lsp--ms-since (timestamp) + "Integer number of milliseconds since TIMESTAMP. Fractions discarded." + (floor (* 1000 (float-time (time-since timestamp))))) + +(defun lsp--send-request-response (workspace recv-time request response) + "Send the RESPONSE for REQUEST in WORKSPACE and log if needed." + (-let* (((&JSONResponse :params :method :id) request) + (process (lsp--workspace-proc workspace)) + (response (lsp--make-response id response)) + (req-entry (and lsp-log-io + (lsp--make-log-entry method id params 'incoming-req))) + (resp-entry (and lsp-log-io + (lsp--make-log-entry method id response 'outgoing-resp + (lsp--ms-since recv-time))))) + ;; Send response to the server. + (when (lsp--log-io-p method) + (lsp--log-entry-new req-entry workspace) + (lsp--log-entry-new resp-entry workspace)) + (lsp--send-no-wait response process))) + +(lsp-defun lsp--on-request (workspace (request &as &JSONRequest :params :method)) + "Call the appropriate handler for REQUEST, and send the return value to the +server. WORKSPACE is the active workspace." + (-let* ((recv-time (current-time)) + (client (lsp--workspace-client workspace)) + (buffers (lsp--workspace-buffers workspace)) + handler + (response (cond + ((setq handler (gethash method (lsp--client-request-handlers client) nil)) + (funcall handler workspace params)) + ((setq handler (gethash method (lsp--client-async-request-handlers client) nil)) + (funcall handler workspace params + (-partial #'lsp--send-request-response + workspace recv-time request)) + 'delay-response) + ((equal method "client/registerCapability") + (mapc #'lsp--server-register-capability + (lsp:registration-params-registrations params)) + (mapc (lambda (buf) + (when (lsp-buffer-live-p buf) + (lsp-with-current-buffer buf + (lsp-unconfig-buffer) + (lsp-configure-buffer)))) + buffers) + nil) + ((equal method "window/showMessageRequest") + (let ((choice (lsp--window-log-message-request params))) + `(:title ,choice))) + ((equal method "window/showDocument") + (let ((success? (lsp--window-show-document params))) + (lsp-make-show-document-result :success (or success? + :json-false)))) + ((equal method "client/unregisterCapability") + (mapc #'lsp--server-unregister-capability + (lsp:unregistration-params-unregisterations params)) + (mapc (lambda (buf) + (when (lsp-buffer-live-p buf) + (lsp-with-current-buffer buf + (lsp-unconfig-buffer) + (lsp-configure-buffer)))) + buffers) + nil) + ((equal method "workspace/applyEdit") + (list :applied (condition-case err + (prog1 t + (lsp--apply-workspace-edit (lsp:apply-workspace-edit-params-edit params) 'server-requested)) + (error + (lsp--error "Failed to apply edits with message %s" + (error-message-string err)) + :json-false)))) + ((equal method "workspace/configuration") + (with-lsp-workspace workspace + (if-let ((buf (car buffers))) + (lsp-with-current-buffer buf + (lsp--build-workspace-configuration-response params)) + (lsp--with-workspace-temp-buffer (lsp--workspace-root workspace) + (lsp--build-workspace-configuration-response params))))) + ((equal method "workspace/workspaceFolders") + (let ((folders (or (-> workspace + (lsp--workspace-client) + (lsp--client-server-id) + (gethash (lsp-session-server-id->folders (lsp-session)))) + (lsp-session-folders (lsp-session))))) + (->> folders + (-distinct) + (-map (lambda (folder) + (list :uri (lsp--path-to-uri folder)))) + (apply #'vector)))) + ((equal method "window/workDoneProgress/create") + nil ;; no specific reply, no processing required + ) + ((equal method "workspace/semanticTokens/refresh") + (when (and lsp-semantic-tokens-enable + (fboundp 'lsp--semantic-tokens-on-refresh)) + (lsp--semantic-tokens-on-refresh workspace)) + nil) + ((equal method "workspace/codeLens/refresh") + (when (and lsp-lens-enable + (fboundp 'lsp--lens-on-refresh)) + (lsp--lens-on-refresh workspace)) + nil) + (t (lsp-warn "Unknown request method: %s" method) nil)))) + ;; Send response to the server. + (unless (eq response 'delay-response) + (lsp--send-request-response workspace recv-time request response)))) + +(lsp-defun lsp--error-string ((&JSONError :message :code)) + "Format ERR as a user friendly string." + (format "Error from the Language Server: %s (%s)" + message + (or (car (alist-get code lsp--errors)) "Unknown error"))) + +(defun lsp--get-body-length (headers) + (let ((content-length (cdr (assoc "Content-Length" headers)))) + (if content-length + (string-to-number content-length) + + ;; This usually means either the server or our parser is + ;; screwed up with a previous Content-Length + (error "No Content-Length header")))) + +(defun lsp--parse-header (s) + "Parse string S as a LSP (KEY . VAL) header." + (let ((pos (string-match "\:" s)) + key val) + (unless pos + (signal 'lsp-invalid-header-name (list s))) + (setq key (substring s 0 pos) + val (s-trim-left (substring s (+ 1 pos)))) + (when (equal key "Content-Length") + (cl-assert (cl-loop for c across val + when (or (> c ?9) (< c ?0)) return nil + finally return t) + nil (format "Invalid Content-Length value: %s" val))) + (cons key val))) + +(defmacro lsp--read-json (str) + "Read json string STR." + (if (progn + (require 'json) + (fboundp 'json-parse-string)) + `(json-parse-string ,str + :object-type (if lsp-use-plists + 'plist + 'hash-table) + :null-object nil + :false-object nil) + `(let ((json-array-type 'vector) + (json-object-type (if lsp-use-plists + 'plist + 'hash-table)) + (json-false nil)) + (json-read-from-string ,str)))) + +(defmacro lsp-json-read-buffer () + "Read json from the current buffer." + (if (progn + (require 'json) + (fboundp 'json-parse-buffer)) + `(json-parse-buffer :object-type (if lsp-use-plists + 'plist + 'hash-table) + :null-object nil + :false-object nil) + `(let ((json-array-type 'vector) + (json-object-type (if lsp-use-plists + 'plist + 'hash-table)) + (json-false nil)) + (json-read)))) + +(defun lsp--read-json-file (file-path) + "Read json file." + (-> file-path + (f-read-text) + (lsp--read-json))) + +(defun lsp--parser-on-message (json-data workspace) + "Called when the parser P read a complete MSG from the server." + (with-demoted-errors "Error processing message %S." + (with-lsp-workspace workspace + (let* ((client (lsp--workspace-client workspace)) + (id (--when-let (lsp:json-response-id json-data) + (if (stringp it) (string-to-number it) it))) + (data (lsp:json-response-result json-data))) + (pcase (lsp--get-message-type json-data) + ('response + (cl-assert id) + (-let [(callback _ method _ before-send) (gethash id (lsp--client-response-handlers client))] + (when (lsp--log-io-p method) + (lsp--log-entry-new + (lsp--make-log-entry method id data 'incoming-resp + (lsp--ms-since before-send)) + workspace)) + (when callback + (remhash id (lsp--client-response-handlers client)) + (funcall callback (lsp:json-response-result json-data))))) + ('response-error + (cl-assert id) + (-let [(_ callback method _ before-send) (gethash id (lsp--client-response-handlers client))] + (when (lsp--log-io-p method) + (lsp--log-entry-new + (lsp--make-log-entry method id (lsp:json-response-error-error json-data) + 'incoming-resp (lsp--ms-since before-send)) + workspace)) + (when callback + (remhash id (lsp--client-response-handlers client)) + (funcall callback (lsp:json-response-error-error json-data))))) + ('notification + (lsp--on-notification workspace json-data)) + ('request (lsp--on-request workspace json-data))))))) + +(defun lsp--create-filter-function (workspace) + "Make filter for the workspace." + (let ((body-received 0) + leftovers body-length body chunk) + (lambda (_proc input) + (setf chunk (if (s-blank? leftovers) + input + (concat leftovers input))) + + (let (messages) + (while (not (s-blank? chunk)) + (if (not body-length) + ;; Read headers + (if-let ((body-sep-pos (string-match-p "\r\n\r\n" chunk))) + ;; We've got all the headers, handle them all at once: + (setf body-length (lsp--get-body-length + (mapcar #'lsp--parse-header + (split-string + (substring-no-properties chunk + (or (string-match-p "Content-Length" chunk) + (error "Unable to find Content-Length header.")) + body-sep-pos) + "\r\n"))) + body-received 0 + leftovers nil + chunk (substring-no-properties chunk (+ body-sep-pos 4))) + + ;; Haven't found the end of the headers yet. Save everything + ;; for when the next chunk arrives and await further input. + (setf leftovers chunk + chunk nil)) + (let* ((chunk-length (string-bytes chunk)) + (left-to-receive (- body-length body-received)) + (this-body (if (< left-to-receive chunk-length) + (prog1 (substring-no-properties chunk 0 left-to-receive) + (setf chunk (substring-no-properties chunk left-to-receive))) + (prog1 chunk + (setf chunk nil)))) + (body-bytes (string-bytes this-body))) + (push this-body body) + (setf body-received (+ body-received body-bytes)) + (when (>= chunk-length left-to-receive) + (condition-case err + (with-temp-buffer + (apply #'insert + (nreverse + (prog1 body + (setf leftovers nil + body-length nil + body-received nil + body nil)))) + (decode-coding-region (point-min) + (point-max) + 'utf-8) + (goto-char (point-min)) + (push (lsp-json-read-buffer) messages)) + + (error + (lsp-warn "Failed to parse the following chunk:\n'''\n%s\n'''\nwith message %s" + (concat leftovers input) + err))))))) + (mapc (lambda (msg) + (lsp--parser-on-message msg workspace)) + (nreverse messages)))))) + +(defvar-local lsp--line-col-to-point-hash-table nil + "Hash table with keys (line . col) and values that are either point positions +or markers.") + +(defcustom lsp-imenu-detailed-outline t + "Whether `lsp-imenu' should include signatures. +This will be ignored if the server doesn't provide the necessary +information, for example if it doesn't support DocumentSymbols." + :group 'lsp-imenu + :type 'boolean) + +(defcustom lsp-imenu-hide-parent-details t + "Whether `lsp-imenu' should hide signatures of parent nodes." + :group 'lsp-imenu + :type 'boolean) + +(defface lsp-details-face '((t :height 0.8 :inherit shadow)) + "Used to display additional information throughout `lsp'. +Things like line numbers, signatures, ... are considered +additional information. Often, additional faces are defined that +inherit from this face by default, like `lsp-signature-face', and +they may be customized for finer control." + :group 'lsp-mode) + +(defface lsp-signature-face '((t :inherit lsp-details-face)) + "Used to display signatures in `imenu', ...." + :group 'lsp-mode) + +(lsp-defun lsp-render-symbol ((&DocumentSymbol :name :detail? :deprecated?) + show-detail?) + "Render INPUT0, an `&DocumentSymbol', to a string. +If SHOW-DETAIL? is set, make use of its `:detail?' field (often +the signature)." + (let ((detail (and show-detail? (s-present? detail?) + (propertize (concat " " (s-trim-left detail?)) + 'face 'lsp-signature-face))) + (name (if deprecated? + (propertize name 'face 'lsp-face-semhl-deprecated) name))) + (concat name detail))) + +(lsp-defun lsp-render-symbol-information ((&SymbolInformation :name :deprecated? :container-name?) + separator) + "Render a piece of SymbolInformation. +Handle :deprecated?. If SEPARATOR is non-nil, the +symbol's (optional) parent, SEPARATOR and the symbol itself are +concatenated." + (when (and separator container-name? (not (string-empty-p container-name?))) + (setq name (concat name separator container-name?))) + (if deprecated? (propertize name 'face 'lsp-face-semhl-deprecated) name)) + +(defun lsp--symbol-to-imenu-elem (sym) + "Convert SYM to imenu element. + +SYM is a SymbolInformation message. + +Return a cons cell (full-name . start-point)." + (let ((start-point (ht-get lsp--line-col-to-point-hash-table + (lsp--get-line-and-col sym)))) + (cons (lsp-render-symbol-information + sym (and lsp-imenu-show-container-name + lsp-imenu-container-name-separator)) + start-point))) + +(lsp-defun lsp--symbol-to-hierarchical-imenu-elem ((sym &as &DocumentSymbol :children?)) + "Convert SYM to hierarchical imenu elements. + +SYM is a DocumentSymbol message. + +Return cons cell (\"symbol-name (symbol-kind)\" . start-point) if +SYM doesn't have any children. Otherwise return a cons cell with +an alist + + (\"symbol-name\" . ((\"(symbol-kind)\" . start-point) + cons-cells-from-children))" + (let ((filtered-children (lsp--imenu-filter-symbols children?)) + (signature (lsp-render-symbol sym lsp-imenu-detailed-outline))) + (if (seq-empty-p filtered-children) + (cons signature + (ht-get lsp--line-col-to-point-hash-table + (lsp--get-line-and-col sym))) + (cons signature + (lsp--imenu-create-hierarchical-index filtered-children))))) + +(lsp-defun lsp--symbol-ignore ((&SymbolInformation :kind)) + "Determine if SYM is for the current document and is to be shown." + ;; It's a SymbolInformation or DocumentSymbol, which is always in the + ;; current buffer file. + (and lsp-imenu-index-symbol-kinds + (numberp kind) + (let ((clamped-kind (if (< 0 kind (length lsp/symbol-kind-lookup)) + kind + 0))) + (not (memql (aref lsp/symbol-kind-lookup clamped-kind) + lsp-imenu-index-symbol-kinds))))) + +(lsp-defun lsp--get-symbol-type ((&SymbolInformation :kind)) + "The string name of the kind of SYM." + (alist-get kind lsp-symbol-kinds "Other")) + +(defun lsp--get-line-and-col (sym) + "Obtain the line and column corresponding to SYM." + (-let* ((location (lsp:symbol-information-location sym)) + (name-range (or (and location (lsp:location-range location)) + (lsp:document-symbol-selection-range sym))) + ((&Range :start (&Position :line :character)) name-range)) + (cons line character))) + +(defun lsp--collect-lines-and-cols (symbols) + "Return a sorted list ((line . col) ...) of the locations of SYMBOLS." + (let ((stack (mapcar 'identity symbols)) + line-col-list) + (while stack + (let ((sym (pop stack))) + (push (lsp--get-line-and-col sym) line-col-list) + (unless (seq-empty-p (lsp:document-symbol-children? sym)) + (setf stack (nconc (lsp--imenu-filter-symbols (lsp:document-symbol-children? sym)) stack))))) + (-sort #'lsp--line-col-comparator line-col-list))) + +(defun lsp--convert-line-col-to-points-batch (line-col-list) + "Convert a sorted list of positions from line-column +representation to point representation." + (let ((line-col-to-point-map (ht-create)) + (inhibit-field-text-motion t) + (curr-line 0)) + (lsp-save-restriction-and-excursion + (goto-char (point-min)) + (cl-loop for (line . col) in line-col-list do + (forward-line (- line curr-line)) + (setq curr-line line) + (let ((line-end (line-end-position))) + (if (or (not col) (> col (- line-end (point)))) + (goto-char line-end) + (forward-char col))) + (ht-set! line-col-to-point-map (cons line col) (if imenu-use-markers + (point-marker) + (point))))) + line-col-to-point-map)) + +(cl-defun lsp--line-col-comparator ((l1 . c1) (l2 . c2)) + (or (< l1 l2) + (and (= l1 l2) + (cond ((and c1 c2) + (< c1 c2)) + (c1 t))))) + +(defun lsp-imenu-create-uncategorized-index (symbols) + "Create imenu index from document SYMBOLS. +This function, unlike `lsp-imenu-create-categorized-index', does +not categorize by type, but instead returns an `imenu' index +corresponding to the symbol hierarchy returned by the server +directly." + (let* ((lsp--line-col-to-point-hash-table (-> symbols + lsp--collect-lines-and-cols + lsp--convert-line-col-to-points-batch))) + (if (lsp--imenu-hierarchical-p symbols) + (lsp--imenu-create-hierarchical-index symbols) + (lsp--imenu-create-non-hierarchical-index symbols)))) + +(defcustom lsp-imenu-symbol-kinds + '((1 . "Files") + (2 . "Modules") + (3 . "Namespaces") + (4 . "Packages") + (5 . "Classes") + (6 . "Methods") + (7 . "Properties") + (8 . "Fields") + (9 . "Constructors") + (10 . "Enums") + (11 . "Interfaces") + (12 . "Functions") + (13 . "Variables") + (14 . "Constants") + (15 . "Strings") + (16 . "Numbers") + (17 . "Booleans") + (18 . "Arrays") + (19 . "Objects") + (20 . "Keys") + (21 . "Nulls") + (22 . "Enum Members") + (23 . "Structs") + (24 . "Events") + (25 . "Operators") + (26 . "Type Parameters")) + "`lsp-symbol-kinds', but only used by `imenu'. +A new variable is needed, as it is `imenu' convention to use +pluralized categories, which `lsp-symbol-kinds' doesn't. If the +non-pluralized names are preferred, this can be set to +`lsp-symbol-kinds'." + :type '(alist :key-type integer :value-type string)) + +(defun lsp--imenu-kind->name (kind) + (alist-get kind lsp-imenu-symbol-kinds "?")) + +(defun lsp-imenu-create-top-level-categorized-index (symbols) + "Create an `imenu' index categorizing SYMBOLS by type. +Only root symbols are categorized. + +See `lsp-symbol-kinds' to customize the category naming. SYMBOLS +shall be a list of DocumentSymbols or SymbolInformation." + (mapcan + (-lambda ((type . symbols)) + (let ((cat (lsp--imenu-kind->name type)) + (symbols (lsp-imenu-create-uncategorized-index symbols))) + ;; If there is no :kind (this is being defensive), or we couldn't look it + ;; up, just display the symbols inline, without categories. + (if cat (list (cons cat symbols)) symbols))) + (sort (seq-group-by #'lsp:document-symbol-kind symbols) + (-lambda ((kinda) (kindb)) (< kinda kindb))))) + +(lsp-defun lsp--symbol->imenu ((sym &as &DocumentSymbol :selection-range (&RangeToPoint :start))) + "Convert an `&DocumentSymbol' to an `imenu' entry." + (cons (lsp-render-symbol sym lsp-imenu-detailed-outline) start)) + +(defun lsp--imenu-create-categorized-index-1 (symbols) + "Returns an `imenu' index from SYMBOLS categorized by type. +The result looks like this: ((\"Variables\" . (...)))." + (->> + symbols + (mapcan + (-lambda ((sym &as &DocumentSymbol :kind :children?)) + (if (seq-empty-p children?) + (list (list kind (lsp--symbol->imenu sym))) + (let ((parent (lsp-render-symbol sym (and lsp-imenu-detailed-outline + (not lsp-imenu-hide-parent-details))))) + (cons + (list kind (lsp--symbol->imenu sym)) + (mapcar (-lambda ((type . imenu-items)) + (list type (cons parent (mapcan #'cdr imenu-items)))) + (-group-by #'car (lsp--imenu-create-categorized-index-1 children?)))))))) + (-group-by #'car) + (mapcar + (-lambda ((kind . syms)) + (cons kind (mapcan #'cdr syms)))))) + +(defun lsp--imenu-create-categorized-index (symbols) + (let ((syms (lsp--imenu-create-categorized-index-1 symbols))) + (dolist (sym syms) + (setcar sym (lsp--imenu-kind->name (car sym)))) + syms)) + +(lsp-defun lsp--symbol-information->imenu ((sym &as &SymbolInformation :location (&Location :range (&RangeToPoint :start)))) + (cons (lsp-render-symbol-information sym nil) start)) + +(defun lsp--imenu-create-categorized-index-flat (symbols) + "Create a kind-categorized index for SymbolInformation." + (mapcar (-lambda ((kind . syms)) + (cons (lsp--imenu-kind->name kind) + (mapcan (-lambda ((parent . children)) + (let ((children (mapcar #'lsp--symbol-information->imenu children))) + (if parent (list (cons parent children)) children))) + (-group-by #'lsp:symbol-information-container-name? syms)))) + (seq-group-by #'lsp:symbol-information-kind symbols))) + +(defun lsp-imenu-create-categorized-index (symbols) + (if (lsp--imenu-hierarchical-p symbols) + (lsp--imenu-create-categorized-index symbols) + (lsp--imenu-create-categorized-index-flat symbols))) + +(defcustom lsp-imenu-index-function #'lsp-imenu-create-uncategorized-index + "Function that should create an `imenu' index. +It will be called with a list of SymbolInformation or +DocumentSymbols, whose first level is already filtered. It shall +then return an appropriate `imenu' index (see +`imenu-create-index-function'). + +Note that this interface is not stable, and subject to change any +time." + :group 'lsp-imenu + :type '(radio + (const :tag "Categorize by type" + lsp-imenu-create-categorized-index) + (const :tag "Categorize root symbols by type" + lsp-imenu-create-top-level-categorized-index) + (const :tag "Uncategorized, inline entries" + lsp-imenu-create-uncategorized-index) + (function :tag "Custom function"))) + +(defun lsp--imenu-create-index () + "Create an `imenu' index based on the language server. +Respects `lsp-imenu-index-function'." + (let ((symbols (lsp--imenu-filter-symbols (lsp--get-document-symbols)))) + (funcall lsp-imenu-index-function symbols))) + +(defun lsp--imenu-filter-symbols (symbols) + "Filter out unsupported symbols from SYMBOLS." + (seq-remove #'lsp--symbol-ignore symbols)) + +(defun lsp--imenu-hierarchical-p (symbols) + "Determine whether any element in SYMBOLS has children." + (seq-some #'lsp-document-symbol? symbols)) + +(defun lsp--imenu-create-non-hierarchical-index (symbols) + "Create imenu index for non-hierarchical SYMBOLS. + +SYMBOLS are a list of DocumentSymbol messages. + +Return a nested alist keyed by symbol names. e.g. + + ((\"SomeClass\" (\"(Class)\" . 10) + (\"someField (Field)\" . 20) + (\"someFunction (Function)\" . 25) + (\"SomeSubClass\" (\"(Class)\" . 30) + (\"someSubField (Field)\" . 35)) + (\"someFunction (Function)\" . 40))" + (seq-map (lambda (nested-alist) + (cons (car nested-alist) + (seq-map #'lsp--symbol-to-imenu-elem (cdr nested-alist)))) + (seq-group-by #'lsp--get-symbol-type symbols))) + +(defun lsp--imenu-create-hierarchical-index (symbols) + "Create imenu index for hierarchical SYMBOLS. + +SYMBOLS are a list of DocumentSymbol messages. + +Return a nested alist keyed by symbol names. e.g. + + ((\"SomeClass\" (\"(Class)\" . 10) + (\"someField (Field)\" . 20) + (\"someFunction (Function)\" . 25) + (\"SomeSubClass\" (\"(Class)\" . 30) + (\"someSubField (Field)\" . 35)) + (\"someFunction (Function)\" . 40))" + (seq-map #'lsp--symbol-to-hierarchical-imenu-elem + (seq-sort #'lsp--imenu-symbol-lessp symbols))) + +(defun lsp--imenu-symbol-lessp (sym1 sym2) + (let* ((compare-results (mapcar (lambda (method) + (funcall (alist-get method lsp--imenu-compare-function-alist) + sym1 sym2)) + lsp-imenu-sort-methods)) + (result (seq-find (lambda (result) + (not (= result 0))) + compare-results + 0))) + (and (numberp result) (< result 0)))) + +(lsp-defun lsp--imenu-compare-kind ((&SymbolInformation :kind left) + (&SymbolInformation :kind right)) + "Compare SYM1 and SYM2 by kind." + (- left right)) + +(defun lsp--imenu-compare-line-col (sym1 sym2) + (if (lsp--line-col-comparator + (lsp--get-line-and-col sym1) + (lsp--get-line-and-col sym2)) + -1 + 1)) + +(lsp-defun lsp--imenu-compare-name ((&SymbolInformation :name name1) + (&SymbolInformation :name name2)) + "Compare SYM1 and SYM2 by name." + (let ((result (compare-strings name1 0 (length name1) name2 0 (length name2)))) + (if (numberp result) result 0))) + +(defun lsp--imenu-refresh () + "Force Imenu to refresh itself." + (imenu--menubar-select imenu--rescan-item)) + +(defun lsp-enable-imenu () + "Use lsp-imenu for the current buffer." + (imenu--cleanup) + (add-function :override (local 'imenu-create-index-function) #'lsp--imenu-create-index) + (setq-local imenu-menubar-modified-tick -1) + (setq-local imenu--index-alist nil) + (when menu-bar-mode + (lsp--imenu-refresh))) + +(defun lsp-resolve-final-command (command &optional test?) + "Resolve final function COMMAND." + (let* ((command (lsp-resolve-value command)) + (command (cl-etypecase command + (list + (cl-assert (seq-every-p (apply-partially #'stringp) command) nil + "Invalid command list") + command) + (string (list command))))) + (if (and (file-remote-p default-directory) (not test?)) + (list shell-file-name "-c" + (string-join (cons "stty raw > /dev/null;" + (mapcar #'shell-quote-argument command)) + " ")) + command))) + +(defun lsp-server-present? (final-command) + "Check whether FINAL-COMMAND is present." + (let ((binary-found? (executable-find (cl-first final-command) t))) + (if binary-found? + (lsp-log "Command \"%s\" is present on the path." (s-join " " final-command)) + (lsp-log "Command \"%s\" is not present on the path." (s-join " " final-command))) + binary-found?)) + +(defun lsp--value-to-string (value) + "Convert VALUE to a string that can be set as value in an environment +variable." + (cond + ((stringp value) value) + ((booleanp value) (if value + "1" + "0")) + ((and (sequencep value) + (seq-every-p #'stringp value)) (string-join value ":")) + (t (user-error "Only strings, booleans, and sequences of strings are supported as environment variables")))) + +(defun lsp--compute-process-environment (environment-fn) + "Append a list of KEY=VALUE from the alist ENVIRONMENT to `process-environment'. +Ignore non-boolean keys whose value is nil." + (let ((environment (if environment-fn + (funcall environment-fn) + nil))) + (-flatten (cons (cl-loop for (key . value) in environment + if (or (eval value) + (eq (get value 'custom-type) 'boolean)) + collect (concat key "=" (lsp--value-to-string + (eval value)))) + process-environment)))) + +(defun lsp--default-directory-for-connection (&optional path) + "Return path to be used for the working directory of a LSP process. + +If `lsp-use-workspace-root-for-server-default-directory' is +non-nil, uses `lsp-workspace-root' to find the directory +corresponding to PATH, else returns `default-directory'." + (if lsp-use-workspace-root-for-server-default-directory + (lsp-workspace-root path) + default-directory)) + +(defun lsp--fix-remote-cmd (program) + "Helper for `lsp-stdio-connection'. +Originally coppied from eglot." + + (if (file-remote-p default-directory) + (list shell-file-name "-c" + (string-join (cons "stty raw > /dev/null;" + (mapcar #'shell-quote-argument program)) + " ")) + program)) + +(defvar tramp-use-ssh-controlmaster-options) +(defvar tramp-ssh-controlmaster-options) + +(defun lsp-stdio-connection (command &optional test-command) + "Returns a connection property list using COMMAND. +COMMAND can be: A string, denoting the command to launch the +language server. A list of strings, denoting an executable with +its command line arguments. A function, that either returns a +string or a list of strings. In all cases, the launched language +server should send and receive messages on standard I/O. +TEST-COMMAND is a function with no arguments which returns +whether the command is present or not. When not specified +`lsp-mode' will check whether the first element of the list +returned by COMMAND is available via `executable-find'" + (cl-check-type command (or string + function + (and list + (satisfies (lambda (l) + (seq-every-p (lambda (el) + (stringp el)) + l)))))) + (list :connect (lambda (filter sentinel name environment-fn workspace) + (if (and (functionp 'json-rpc-connection) + (not (file-remote-p default-directory))) + (lsp-json-rpc-connection workspace (lsp-resolve-final-command command)) + (let ((final-command (lsp-resolve-final-command command)) + (process-name (generate-new-buffer-name name)) + (process-environment + (lsp--compute-process-environment environment-fn))) + (let* ((stderr-buf (get-buffer-create (format "*%s::stderr*" process-name))) + (default-directory (lsp--default-directory-for-connection)) + (tramp-use-ssh-controlmaster-options 'suppress) + (tramp-ssh-controlmaster-options "-o ControlMaster=no -o ControlPath=none") + (proc (make-process + :name process-name + :connection-type 'pipe + :buffer (format "*%s*" process-name) + :coding 'no-conversion + :command final-command + :filter filter + :sentinel sentinel + :stderr stderr-buf + :noquery t + :file-handler t))) + (set-process-query-on-exit-flag proc nil) + (set-process-query-on-exit-flag (get-buffer-process stderr-buf) nil) + (with-current-buffer (get-buffer stderr-buf) + ;; Make the *NAME::stderr* buffer buffer-read-only, q to bury, etc. + (special-mode)) + (cons proc proc))))) + :test? (or + test-command + (lambda () + (lsp-server-present? (lsp-resolve-final-command command t)))))) + +(defun lsp--open-network-stream (host port name) + "Open network stream to HOST:PORT. + NAME will be passed to `open-network-stream'. + RETRY-COUNT is the number of the retries. + SLEEP-INTERVAL is the sleep interval between each retry." + (let* ((retries 0) + (sleep-interval 0.01) + (number-of-retries (/ lsp-tcp-connection-timeout sleep-interval)) + connection) + (while (and (not connection) (< retries number-of-retries)) + (condition-case err + (setq connection (open-network-stream name nil host port + :type 'plain + :coding 'no-conversion)) + (file-error + (let ((inhibit-message t)) + (lsp--warn "Failed to connect to %s:%s with error message %s" + host + port + (error-message-string err)) + (sleep-for sleep-interval) + (cl-incf retries))))) + (or connection (error "Port %s was never taken. Consider increasing `lsp-tcp-connection-timeout'." port)))) + +(defun lsp--port-available (host port) + "Return non-nil if HOST and PORT are available." + (condition-case _err + (delete-process (open-network-stream "*connection-test*" nil host port :type 'plain)) + (file-error t))) + +(defun lsp--find-available-port (host starting-port) + "Find available port on HOST starting from STARTING-PORT." + (let ((port starting-port)) + (while (not (lsp--port-available host port)) + (cl-incf port)) + port)) + +(defun lsp-tcp-connection (command-fn) + "Returns a connection property list similar to `lsp-stdio-connection'. +COMMAND-FN can only be a function that takes a single argument, a +port number. It should return a command for launches a language server +process listening for TCP connections on the provided port." + (cl-check-type command-fn function) + (list + :connect (lambda (filter sentinel name environment-fn _workspace) + (let* ((host "localhost") + (port (lsp--find-available-port host (cl-incf lsp--tcp-port))) + (command (funcall command-fn port)) + (final-command (if (consp command) command (list command))) + (_ (unless (lsp-server-present? final-command) + (user-error (format "Couldn't find executable %s" (cl-first final-command))))) + (process-environment + (lsp--compute-process-environment environment-fn)) + (proc (make-process :name name :connection-type 'pipe :coding 'no-conversion + :command final-command :sentinel sentinel :stderr (format "*%s::stderr*" name) :noquery t)) + (tcp-proc (lsp--open-network-stream host port (concat name "::tcp")))) + + ;; TODO: Same :noquery issue (see above) + (set-process-query-on-exit-flag proc nil) + (set-process-query-on-exit-flag tcp-proc nil) + (set-process-filter tcp-proc filter) + (cons tcp-proc proc))) + :test? (lambda () (lsp-server-present? (funcall command-fn 0))))) + +(defalias 'lsp-tcp-server 'lsp-tcp-server-command) + +(defun lsp-tcp-server-command (command-fn) + "Create tcp server connection. +In this mode Emacs is TCP server and the language server connects +to it. COMMAND is function with one parameter(the port) and it +should return the command to start the LS server." + (cl-check-type command-fn function) + (list + :connect (lambda (filter sentinel name environment-fn _workspace) + (let* (tcp-client-connection + (tcp-server (make-network-process :name (format "*tcp-server-%s*" name) + :buffer (format "*tcp-server-%s*" name) + :family 'ipv4 + :service lsp--tcp-server-port + :sentinel (lambda (proc _string) + (lsp-log "Language server %s is connected." name) + (setf tcp-client-connection proc)) + :server 't)) + (port (process-contact tcp-server :service)) + (final-command (funcall command-fn port)) + (process-environment + (lsp--compute-process-environment environment-fn)) + (cmd-proc (make-process :name name + :connection-type 'pipe + :coding 'no-conversion + :command final-command + :stderr (format "*tcp-server-%s*::stderr" name) + :noquery t))) + (let ((retries 0)) + ;; wait for the client to connect (we sit-for 500 ms, so have to double lsp--tcp-server-wait-seconds) + (while (and (not tcp-client-connection) (< retries (* 2 lsp--tcp-server-wait-seconds))) + (lsp--info "Waiting for connection for %s, retries: %s" name retries) + (sit-for 0.500) + (cl-incf retries))) + + (unless tcp-client-connection + (condition-case nil (delete-process tcp-server) (error)) + (condition-case nil (delete-process cmd-proc) (error)) + (error "Failed to create connection to %s on port %s" name port)) + (lsp--info "Successfully connected to %s" name) + + (set-process-query-on-exit-flag cmd-proc nil) + (set-process-query-on-exit-flag tcp-client-connection nil) + (set-process-query-on-exit-flag tcp-server nil) + + (set-process-filter tcp-client-connection filter) + (set-process-sentinel tcp-client-connection sentinel) + (cons tcp-client-connection cmd-proc))) + :test? (lambda () (lsp-server-present? (funcall command-fn 0))))) + +(defalias 'lsp-tramp-connection 'lsp-stdio-connection) + +(defun lsp--auto-configure () + "Autoconfigure `company', `flycheck', `lsp-ui', etc if they are installed." + (when (functionp 'lsp-ui-mode) + (lsp-ui-mode)) + + (if lsp-headerline-breadcrumb-enable + (add-hook 'lsp-configure-hook 'lsp-headerline-breadcrumb-mode) + (remove-hook 'lsp-configure-hook 'lsp-headerline-breadcrumb-mode)) + (if lsp-modeline-code-actions-enable + (add-hook 'lsp-configure-hook 'lsp-modeline-code-actions-mode) + (remove-hook 'lsp-configure-hook 'lsp-modeline-code-actions-mode)) + (if lsp-modeline-diagnostics-enable + (add-hook 'lsp-configure-hook 'lsp-modeline-diagnostics-mode) + (remove-hook 'lsp-configure-hook 'lsp-modeline-diagnostics-mode)) + (if lsp-modeline-workspace-status-enable + (add-hook 'lsp-configure-hook 'lsp-modeline-workspace-status-mode) + (remove-hook 'lsp-configure-hook 'lsp-modeline-workspace-status-mode)) + (if lsp-lens-enable + (add-hook 'lsp-configure-hook 'lsp-lens--enable) + (remove-hook 'lsp-configure-hook 'lsp-lens--enable)) + (if lsp-semantic-tokens-enable + (add-hook 'lsp-configure-hook 'lsp-semantic-tokens--enable) + (remove-hook 'lsp-configure-hook 'lsp-semantic-tokens--enable)) + + ;; yas-snippet config + (setq-local yas-inhibit-overlay-modification-protection t)) + +(defun lsp--restart-if-needed (workspace) + "Handler restart for WORKSPACE." + (when (or (eq lsp-restart 'auto-restart) + (eq (lsp--workspace-shutdown-action workspace) 'restart) + (and (eq lsp-restart 'interactive) + (let ((query (format + "Server %s exited (check corresponding stderr buffer for details). Do you want to restart it?" + (lsp--workspace-print workspace)))) + (y-or-n-p query)))) + (--each (lsp--workspace-buffers workspace) + (when (lsp-buffer-live-p it) + (lsp-with-current-buffer it + (if lsp--buffer-deferred + (lsp-deferred) + (lsp--info "Restarting LSP in buffer %s" (buffer-name)) + (lsp))))))) + +(defun lsp--update-key (table key fn) + "Apply FN on value corresponding to KEY in TABLE." + (let ((existing-value (gethash key table))) + (if-let ((new-value (funcall fn existing-value))) + (puthash key new-value table) + (remhash key table)))) + +(defun lsp--process-sentinel (workspace process exit-str) + "Create the sentinel for WORKSPACE." + (unless (process-live-p process) + (lsp--handle-process-exit workspace exit-str))) + +(defun lsp--handle-process-exit (workspace exit-str) + (let* ((folder->workspaces (lsp-session-folder->servers (lsp-session))) + (proc (lsp--workspace-proc workspace))) + (lsp--warn "%s has exited (%s)" + (lsp-process-name proc) + (string-trim-right (or exit-str ""))) + (with-lsp-workspace workspace + ;; Clean workspace related data in each of the buffers + ;; in the workspace. + (--each (lsp--workspace-buffers workspace) + (when (lsp-buffer-live-p it) + (lsp-with-current-buffer it + (setq lsp--buffer-workspaces (delete workspace lsp--buffer-workspaces)) + (lsp--uninitialize-workspace) + (lsp--spinner-stop) + (lsp--remove-overlays 'lsp-highlight)))) + + ;; Cleanup session from references to the closed workspace. + (--each (hash-table-keys folder->workspaces) + (lsp--update-key folder->workspaces it (apply-partially 'delete workspace))) + + (lsp-process-cleanup proc)) + + (run-hook-with-args 'lsp-after-uninitialized-functions workspace) + + (if (eq (lsp--workspace-shutdown-action workspace) 'shutdown) + (lsp--info "Workspace %s shutdown." (lsp--workspace-print workspace)) + (lsp--restart-if-needed workspace)) + (lsp--cleanup-hanging-watches))) + +(defun lsp-workspace-folders (workspace) + "Return all folders associated with WORKSPACE." + (let (result) + (->> (lsp-session) + (lsp-session-folder->servers) + (maphash (lambda (folder workspaces) + (when (-contains? workspaces workspace) + (push folder result))))) + result)) + +(defun lsp--start-workspace (session client-template root &optional initialization-options) + "Create new workspace for CLIENT-TEMPLATE with project root ROOT. +INITIALIZATION-OPTIONS are passed to initialize function. +SESSION is the active session." + (lsp--spinner-start) + (-let* ((default-directory root) + (client (copy-lsp--client client-template)) + (workspace (make-lsp--workspace + :root root + :client client + :status 'starting + :buffers (list (lsp-current-buffer)) + :host-root (file-remote-p root))) + ((&lsp-cln 'server-id 'environment-fn 'new-connection 'custom-capabilities + 'multi-root 'initialized-fn) client) + ((proc . cmd-proc) (funcall + (or (plist-get new-connection :connect) + (user-error "Client %s is configured incorrectly" client)) + (lsp--create-filter-function workspace) + (apply-partially #'lsp--process-sentinel workspace) + (format "%s" server-id) + environment-fn + workspace)) + (workspace-folders (gethash server-id (lsp-session-server-id->folders session)))) + (setf (lsp--workspace-proc workspace) proc + (lsp--workspace-cmd-proc workspace) cmd-proc) + + ;; update (lsp-session-folder->servers) depending on whether we are starting + ;; multi/single folder workspace + (mapc (lambda (project-root) + (->> session + (lsp-session-folder->servers) + (gethash project-root) + (cl-pushnew workspace))) + (or workspace-folders (list root))) + + (with-lsp-workspace workspace + (run-hooks 'lsp-before-initialize-hook) + (lsp-request-async + "initialize" + (append + (list :processId (unless (file-remote-p (buffer-file-name)) + (emacs-pid)) + :rootPath (lsp-file-local-name (expand-file-name root)) + :clientInfo (list :name "emacs" + :version (emacs-version)) + :rootUri (lsp--path-to-uri root) + :capabilities (lsp--client-capabilities custom-capabilities) + :initializationOptions initialization-options + :workDoneToken "1") + (when lsp-server-trace + (list :trace lsp-server-trace)) + (when multi-root + (->> workspace-folders + (-distinct) + (-map (lambda (folder) + (list :uri (lsp--path-to-uri folder) + :name (f-filename folder)))) + (apply 'vector) + (list :workspaceFolders)))) + (-lambda ((&InitializeResult :capabilities)) + ;; we know that Rust Analyzer will send {} which will be parsed as null + ;; when using plists + (when (equal 'rust-analyzer server-id) + (-> capabilities + (lsp:server-capabilities-text-document-sync?) + (lsp:set-text-document-sync-options-save? t))) + + (setf (lsp--workspace-server-capabilities workspace) capabilities + (lsp--workspace-status workspace) 'initialized) + + (with-lsp-workspace workspace + (lsp-notify "initialized" lsp--empty-ht)) + + (when initialized-fn (funcall initialized-fn workspace)) + + (cl-callf2 -filter #'lsp-buffer-live-p (lsp--workspace-buffers workspace)) + (->> workspace + (lsp--workspace-buffers) + (mapc (lambda (buffer) + (lsp-with-current-buffer buffer + (lsp--open-in-workspace workspace))))) + + (with-lsp-workspace workspace + (run-hooks 'lsp-after-initialize-hook)) + (lsp--info "%s initialized successfully in folders: %s" + (lsp--workspace-print workspace) + (lsp-workspace-folders workspace))) + :mode 'detached)) + workspace)) + +(defun lsp--load-default-session () + "Load default session." + (setq lsp--session (or (condition-case err + (lsp--read-from-file lsp-session-file) + (error (lsp--error "Failed to parse the session %s, starting with clean one." + (error-message-string err)) + nil)) + (make-lsp-session)))) + +(defun lsp-session () + "Get the session associated with the current buffer." + (or lsp--session (setq lsp--session (lsp--load-default-session)))) + +(defun lsp--client-disabled-p (buffer-major-mode client) + (seq-some + (lambda (entry) + (pcase entry + ((pred symbolp) (eq entry client)) + (`(,mode . ,client-or-list) + (and (eq mode buffer-major-mode) + (if (listp client-or-list) + (memq client client-or-list) + (eq client client-or-list)))))) + lsp-disabled-clients)) + + +;; download server + +(defcustom lsp-server-install-dir (expand-file-name + (locate-user-emacs-file (f-join ".cache" "lsp"))) + "Directory in which the servers will be installed." + :risky t + :type 'directory + :package-version '(lsp-mode . "6.3") + :group 'lsp-mode) + +(defcustom lsp-verify-signature t + "Whether to check GPG signatures of downloaded files." + :type 'boolean + :package-version '(lsp-mode . "8.0.0") + :group 'lsp-mode) + +(defvar lsp--dependencies (ht)) + +(defun lsp-dependency (name &rest definitions) + "Used to specify a language server DEPENDENCY, the server +executable or other required file path. Typically, the +DEPENDENCY is found by locating it on the system path using +`executable-find'. + +You can explicitly call lsp-dependency in your environment to +specify the absolute path to the DEPENDENCY. For example, the +typescript-language-server requires both the server and the +typescript compiler. If you have installed them in a team shared +read-only location, you can instruct lsp-mode to use them via + + (eval-after-load `lsp-mode + `(progn + (require lsp-javascript) + (lsp-dependency typescript-language-server (:system ,tls-exe)) + (lsp-dependency typescript (:system ,ts-js)))) + +where tls-exe is the absolute path to the typescript-language-server +executable and ts-js is the absolute path to the typescript compiler +JavaScript file, tsserver.js (the *.js is required for Windows)." + (ht-set lsp--dependencies name definitions)) + +(defun lsp--server-binary-present? (client) + (unless (equal (lsp--client-server-id client) 'lsp-pwsh) + (condition-case () + (-some-> client lsp--client-new-connection (plist-get :test?) funcall) + (error nil) + (args-out-of-range nil)))) + +(define-minor-mode lsp-installation-buffer-mode + "Mode used in *lsp-installation* buffers. +It can be used to set-up keybindings, etc. Disabling this mode +detaches the installation buffer from commands like +`lsp-select-installation-buffer'." + :init-value nil + :lighter nil) + +(defface lsp-installation-finished-buffer-face '((t :foreground "orange")) + "Face used for finished installation buffers. +Used in `lsp-select-installation-buffer'." + :group 'lsp-mode) + +(defface lsp-installation-buffer-face '((t :foreground "green")) + "Face used for installation buffers still in progress. +Used in `lsp-select-installation-buffer'." + :group 'lsp-mode) + +(defun lsp--installation-buffer? (buf) + "Check whether BUF is an `lsp-async-start-process' buffer." + (buffer-local-value 'lsp-installation-buffer-mode buf)) + +(defun lsp-select-installation-buffer (&optional show-finished) + "Interactively choose an installation buffer. +If SHOW-FINISHED is set, leftover (finished) installation buffers +are still shown." + (interactive "P") + (let ((bufs (--filter (and (lsp--installation-buffer? it) + (or show-finished (get-buffer-process it))) + (buffer-list)))) + (pcase bufs + (`nil (user-error "No installation buffers")) + (`(,buf) (pop-to-buffer buf)) + (bufs (pop-to-buffer (completing-read "Select installation buffer: " + (--map (propertize (buffer-name it) 'face + (if (get-buffer-process it) + 'lsp-installation-buffer-face + 'lsp-installation-finished-buffer-face)) + bufs))))))) + +(defun lsp-cleanup-installation-buffers () + "Delete finished *lsp-installation* buffers." + (interactive) + (dolist (buf (buffer-list)) + (when (and (lsp--installation-buffer? buf) (not (get-buffer-process buf))) + (kill-buffer buf)))) + +(defun lsp--download-status () + (-some--> #'lsp--client-download-in-progress? + (lsp--filter-clients it) + (-map (-compose #'symbol-name #'lsp--client-server-id) it) + (format "%s" it) + (propertize it 'face 'success) + (format " Installing following servers: %s" it) + (propertize it + 'local-map (make-mode-line-mouse-map + 'mouse-1 #'lsp-select-installation-buffer) + 'mouse-face 'highlight))) + +(defun lsp--install-server-internal (client &optional update?) + (unless (lsp--client-download-server-fn client) + (user-error "There is no automatic installation for `%s', you have to install it manually following lsp-mode's documentation." + (lsp--client-server-id client))) + + (setf (lsp--client-download-in-progress? client) t) + (add-to-list 'global-mode-string '(t (:eval (lsp--download-status)))) + (cl-flet ((done + (success? &optional error-message) + ;; run with idle timer to make sure the lsp command is executed in + ;; the main thread, see #2739. + (run-with-timer + 0.0 + nil + (lambda () + (-let [(&lsp-cln 'server-id 'buffers) client] + (setf (lsp--client-download-in-progress? client) nil + (lsp--client-buffers client) nil) + (if success? + (lsp--info "Server %s downloaded, auto-starting in %s buffers." server-id + (length buffers)) + (lsp--error "Server %s install process failed with the following error message: %s. +Check `*lsp-install*' and `*lsp-log*' buffer." + server-id + error-message)) + (seq-do + (lambda (buffer) + (when (lsp-buffer-live-p buffer) + (lsp-with-current-buffer buffer + (cl-callf2 -remove-item '(t (:eval (lsp--download-status))) + global-mode-string) + (when success? (lsp))))) + buffers) + (unless (lsp--filter-clients #'lsp--client-download-in-progress?) + (cl-callf2 -remove-item '(t (:eval (lsp--download-status))) + global-mode-string))))))) + (lsp--info "Download %s started." (lsp--client-server-id client)) + (condition-case err + (funcall + (lsp--client-download-server-fn client) + client + (lambda () (done t)) + (lambda (msg) (done nil msg)) + update?) + (error + (done nil (error-message-string err)))))) + +(defun lsp--require-packages () + "Load `lsp-client-packages' if needed." + (when (and lsp-auto-configure (not lsp--client-packages-required)) + (seq-do (lambda (package) + ;; loading client is slow and `lsp' can be called repeatedly + (unless (featurep package) + (require package nil t))) + lsp-client-packages) + (setq lsp--client-packages-required t))) + +;;;###autoload +(defun lsp-install-server (update? &optional server-id) + "Interactively install or re-install server. +When prefix UPDATE? is t force installation even if the server is present." + (interactive "P") + (lsp--require-packages) + (let* ((chosen-client (or (gethash server-id lsp-clients) + (lsp--completing-read + "Select server to install/re-install: " + (or (->> lsp-clients + (ht-values) + (-filter (-andfn + (-not #'lsp--client-download-in-progress?) + #'lsp--client-download-server-fn))) + (user-error "There are no servers with automatic installation")) + (lambda (client) + (let ((server-name (-> client lsp--client-server-id symbol-name))) + (if (lsp--server-binary-present? client) + (concat server-name " (Already installed)") + server-name))) + nil + t))) + (update? (or update? + (and (not (lsp--client-download-in-progress? chosen-client)) + (lsp--server-binary-present? chosen-client))))) + (lsp--install-server-internal chosen-client update?))) + +;;;###autoload +(defun lsp-uninstall-server (dir) + "Delete a LSP server from `lsp-server-install-dir'." + (interactive + (list (read-directory-name "Uninstall LSP server: " (f-slash lsp-server-install-dir)))) + (unless (file-directory-p dir) + (user-error "Couldn't find %s directory" dir)) + (delete-directory dir 'recursive) + (message "Server `%s' uninstalled." (file-name-nondirectory (directory-file-name dir)))) + +;;;###autoload +(defun lsp-uninstall-servers () + "Uninstall all installed servers." + (interactive) + (let* ((dir lsp-server-install-dir) + (servers (ignore-errors + (directory-files dir t + directory-files-no-dot-files-regexp)))) + (if (or (not (file-directory-p dir)) (zerop (length servers))) + (user-error "No servers to uninstall") + (when (yes-or-no-p + (format "Servers to uninstall: %d (%s), proceed? " + (length servers) + (mapconcat (lambda (server) + (file-name-nondirectory (directory-file-name server))) + servers " "))) + (mapc #'lsp-uninstall-server servers) + (message "All servers uninstalled"))))) + +;;;###autoload +(defun lsp-update-server (&optional server-id) + "Interactively update (reinstall) a server." + (interactive) + (lsp--require-packages) + (let ((chosen-client (or (gethash server-id lsp-clients) + (lsp--completing-read + "Select server to update (if not on the list, probably you need to `lsp-install-server`): " + (or (->> lsp-clients + (ht-values) + (-filter (-andfn + (-not #'lsp--client-download-in-progress?) + #'lsp--client-download-server-fn + #'lsp--server-binary-present?))) + (user-error "There are no servers to update")) + (lambda (client) + (-> client lsp--client-server-id symbol-name)) + nil + t)))) + (lsp--install-server-internal chosen-client t))) + +;;;###autoload +(defun lsp-update-servers () + "Update (reinstall) all installed servers." + (interactive) + (lsp--require-packages) + (mapc (lambda (client) (lsp--install-server-internal client t)) + (-filter (-andfn + (-not #'lsp--client-download-in-progress?) + #'lsp--client-download-server-fn + #'lsp--server-binary-present?) (hash-table-values lsp-clients)))) + +;;;###autoload +(defun lsp-ensure-server (server-id) + "Ensure server SERVER-ID" + (lsp--require-packages) + (if-let ((client (gethash server-id lsp-clients))) + (unless (lsp--server-binary-present? client) + (lsp--info "Server `%s' is not preset, installing..." server-id) + (lsp-install-server nil server-id)) + (warn "Unable to find server registration with id %s" server-id))) + +(defun lsp-async-start-process (callback error-callback &rest command) + "Start async process COMMAND with CALLBACK and ERROR-CALLBACK." + (let ((name (cl-first command))) + (with-current-buffer (compilation-start (mapconcat #'shell-quote-argument (-filter (lambda (cmd) + (not (null cmd))) + command) + " ") t + (lambda (&rest _) + (generate-new-buffer-name (format "*lsp-install: %s*" name)))) + (lsp-installation-buffer-mode +1) + (view-mode +1) + (add-hook + 'compilation-finish-functions + (lambda (_buf status) + (if (string= "finished\n" status) + (condition-case err + (funcall callback) + (error + (funcall error-callback (error-message-string err)))) + (funcall error-callback (s-trim-right status)))) + nil t)))) + +(defun lsp-resolve-value (value) + "Resolve VALUE's value. +If it is function - call it. +If it is a variable - return it's value +Otherwise returns value itself." + (cond + ((functionp value) (funcall value)) + ((and (symbolp value) (boundp value)) (symbol-value value)) + (value))) + +(defvar lsp-deps-providers + (list :npm (list :path #'lsp--npm-dependency-path + :install #'lsp--npm-dependency-install) + :cargo (list :path #'lsp--cargo-dependency-path + :install #'lsp--cargo-dependency-install) + :system (list :path #'lsp--system-path) + :download (list :path #'lsp-download-path + :install #'lsp-download-install))) + +(defun lsp--system-path (path) + "If PATH is absolute and exists return it as is. Otherwise, +return the absolute path to the executable defined by PATH or +nil." + ;; For node.js 'sub-packages' PATH may point to a *.js file. Consider the + ;; typescript-language-server. When lsp invokes the server, lsp needs to + ;; supply the path to the typescript compiler, tsserver.js, as an argument. To + ;; make code platform independent, one must pass the absolute path to the + ;; tsserver.js file (Windows requires a *.js file - see help on the JavaScript + ;; child process spawn command that is invoked by the + ;; typescript-language-server). This is why we check for existence and not + ;; that the path is executable. + (let ((path (lsp-resolve-value path))) + (cond + ((and (f-absolute? path) + (f-exists? path)) + path) + ((executable-find path t) path)))) + +(defun lsp-package-path (dependency) + "Path to the DEPENDENCY each of the registered providers." + (let (path) + (-first (-lambda ((provider . rest)) + (setq path (-some-> lsp-deps-providers + (plist-get provider) + (plist-get :path) + (apply rest)))) + (gethash dependency lsp--dependencies)) + path)) + +(defun lsp-package-ensure (dependency callback error-callback) + "Asynchronously ensure a package." + (or (-first (-lambda ((provider . rest)) + (-some-> lsp-deps-providers + (plist-get provider) + (plist-get :install) + (apply (cl-list* callback error-callback rest)))) + (gethash dependency lsp--dependencies)) + (funcall error-callback (format "Unable to find a way to install %s" dependency)))) + + +;; npm handling + +;; https://docs.npmjs.com/files/folders#executables +(cl-defun lsp--npm-dependency-path (&key package path &allow-other-keys) + "Return npm dependency PATH for PACKAGE." + (let ((path (executable-find + (f-join lsp-server-install-dir "npm" package + (cond ((eq system-type 'windows-nt) "") + (t "bin")) + path) + t))) + (unless (and path (f-exists? path)) + (error "The package %s is not installed. Unable to find %s" package path)) + path)) + +(cl-defun lsp--npm-dependency-install (callback error-callback &key package &allow-other-keys) + (if-let ((npm-binary (executable-find "npm"))) + (progn + ;; Explicitly `make-directory' to work around NPM bug in + ;; versions 7.0.0 through 7.4.1. See + ;; https://github.com/emacs-lsp/lsp-mode/issues/2364 for + ;; discussion. + (make-directory (f-join lsp-server-install-dir "npm" package "lib") 'parents) + (lsp-async-start-process (lambda () + (if (string-empty-p + (string-trim (shell-command-to-string + (mapconcat #'shell-quote-argument `(,npm-binary "view" ,package "peerDependencies") " ")))) + (funcall callback) + (let ((default-directory (f-dirname (car (last (directory-files-recursively (f-join lsp-server-install-dir "npm" package) "package.json"))))) + (process-environment (append '("npm_config_yes=true") process-environment))) ;; Disable prompting for older versions of npx + (when (f-dir-p default-directory) + (lsp-async-start-process callback + error-callback + (executable-find "npx") + "npm-install-peers"))))) + error-callback + npm-binary + "-g" + "--prefix" + (f-join lsp-server-install-dir "npm" package) + "install" + package)) + (lsp-log "Unable to install %s via `npm' because it is not present" package) + nil)) + + +;; Cargo dependency handling +(cl-defun lsp--cargo-dependency-path (&key package path &allow-other-keys) + (let ((path (executable-find + (f-join lsp-server-install-dir + "cargo" + package + "bin" + path) + t))) + (unless (and path (f-exists? path)) + (error "The package %s is not installed. Unable to find %s" package path)) + path)) + +(cl-defun lsp--cargo-dependency-install (callback error-callback &key package git &allow-other-keys) + (if-let ((cargo-binary (executable-find "cargo"))) + (lsp-async-start-process + callback + error-callback + cargo-binary + "install" + package + (when git + "--git") + git + "--root" + (f-join lsp-server-install-dir "cargo" package)) + (lsp-log "Unable to install %s via `cargo' because it is not present" package) + nil)) + + + +;; Download URL handling +(cl-defun lsp-download-install (callback error-callback &key url asc-url pgp-key store-path decompress &allow-other-keys) + (let* ((url (lsp-resolve-value url)) + (store-path (lsp-resolve-value store-path)) + ;; (decompress (lsp-resolve-value decompress)) + (download-path + (pcase decompress + (:gzip (concat store-path ".gz")) + (:zip (concat store-path ".zip")) + (:targz (concat store-path ".tar.gz")) + (`nil store-path) + (_ (error ":decompress must be `:gzip', `:zip', `:targz' or `nil'"))))) + (make-thread + (lambda () + (condition-case err + (progn + (when (f-exists? download-path) + (f-delete download-path)) + (when (f-exists? store-path) + (f-delete store-path)) + (lsp--info "Starting to download %s to %s..." url download-path) + (mkdir (f-parent download-path) t) + (url-copy-file url download-path) + (lsp--info "Finished downloading %s..." download-path) + (when (and lsp-verify-signature asc-url pgp-key) + (if (executable-find epg-gpg-program) + (let ((asc-download-path (concat download-path ".asc")) + (context (epg-make-context)) + (fingerprint) + (signature)) + (when (f-exists? asc-download-path) + (f-delete asc-download-path)) + (lsp--info "Starting to download %s to %s..." asc-url asc-download-path) + (url-copy-file asc-url asc-download-path) + (lsp--info "Finished downloading %s..." asc-download-path) + (epg-import-keys-from-string context pgp-key) + (setq fingerprint (epg-import-status-fingerprint + (car + (epg-import-result-imports + (epg-context-result-for context 'import))))) + (lsp--info "Verifying signature %s..." asc-download-path) + (epg-verify-file context asc-download-path download-path) + (setq signature (car (epg-context-result-for context 'verify))) + (unless (and + (eq (epg-signature-status signature) 'good) + (equal (epg-signature-fingerprint signature) fingerprint)) + (error "Failed to verify GPG signature: %s" (epg-signature-to-string signature)))) + (lsp--warn "GPG is not installed, skipping the signature check."))) + (when decompress + (lsp--info "Decompressing %s..." download-path) + (pcase decompress + (:gzip + (lsp-gunzip download-path)) + (:zip (lsp-unzip download-path (f-parent store-path))) + (:targz (lsp-tar-gz-decompress download-path (f-parent store-path)))) + (lsp--info "Decompressed %s..." store-path)) + (funcall callback)) + (error (funcall error-callback err))))))) + +(cl-defun lsp-download-path (&key store-path binary-path set-executable? &allow-other-keys) + "Download URL and store it into STORE-PATH. + +SET-EXECUTABLE? when non-nil change the executable flags of +STORE-PATH to make it executable. BINARY-PATH can be specified +when the binary to start does not match the name of the +archive (e.g. when the archive has multiple files)" + (let ((store-path (or (lsp-resolve-value binary-path) + (lsp-resolve-value store-path)))) + (cond + ((executable-find store-path) store-path) + ((and set-executable? (f-exists? store-path)) + (set-file-modes store-path #o0700) + store-path) + ((f-exists? store-path) store-path)))) + +(defun lsp--find-latest-gh-release-url (url regex) + "Fetch the latest version in the releases given by URL by using REGEX." + (let ((url-request-method "GET")) + (with-current-buffer (url-retrieve-synchronously url) + (goto-char (point-min)) + (re-search-forward "\n\n" nil 'noerror) + (delete-region (point-min) (point)) + (let* ((json-result (lsp-json-read-buffer))) + (message "Latest version found: %s" (lsp-get json-result :tag_name)) + (--> json-result + (lsp-get it :assets) + (seq-find (lambda (entry) (string-match-p regex (lsp-get entry :name))) it) + (lsp-get it :browser_download_url)))))) + +;; unzip + +(defconst lsp-ext-pwsh-script "pwsh -noprofile -noninteractive \ +-nologo -ex bypass -c Expand-Archive -Path '%s' -DestinationPath '%s'" + "Pwsh script to unzip file.") + +(defconst lsp-ext-powershell-script "powershell -noprofile -noninteractive \ +-nologo -ex bypass -command Expand-Archive -path '%s' -dest '%s'" + "Powershell script to unzip file.") + +(defconst lsp-ext-unzip-script "bash -c 'mkdir -p %2$s && unzip -qq -o %1$s -d %2$s'" + "Unzip script to unzip file.") + +(defcustom lsp-unzip-script (lambda () + (cond ((and (eq system-type 'windows-nt) + (executable-find "pwsh")) + lsp-ext-pwsh-script) + ((and (eq system-type 'windows-nt) + (executable-find "powershell")) + lsp-ext-powershell-script) + ((executable-find "unzip") lsp-ext-unzip-script) + ((executable-find "pwsh") lsp-ext-pwsh-script) + (t nil))) + "The script to unzip." + :group 'lsp-mode + :type 'string + :package-version '(lsp-mode . "8.0.0")) + +(defun lsp-unzip (zip-file dest) + "Unzip ZIP-FILE to DEST." + (unless lsp-unzip-script + (error "Unable to find `unzip' or `powershell' on the path, please customize `lsp-unzip-script'")) + (shell-command (format (lsp-resolve-value lsp-unzip-script) zip-file dest))) + +;; gunzip + +(defconst lsp-ext-gunzip-script "gzip -d %1$s" + "Script to decompress a gzippped file with gzip.") + +(defcustom lsp-gunzip-script (lambda () + (cond ((executable-find "gzip") lsp-ext-gunzip-script) + (t nil))) + "The script to decompress a gzipped file. +Should be a format string with one argument for the file to be decompressed +in place." + :group 'lsp-mode + :type 'string + :package-version '(lsp-mode . "8.0.0")) + +(defun lsp-gunzip (gz-file) + "Decompress GZ-FILE in place." + (unless lsp-gunzip-script + (error "Unable to find `gzip' on the path, please either customize `lsp-gunzip-script' or manually decompress %s" gz-file)) + (shell-command (format (lsp-resolve-value lsp-gunzip-script) gz-file))) + +;; tar.gz decompression + +(defconst lsp-ext-tar-script "bash -c 'mkdir -p %2$s; tar xf %1$s --directory=%2$s'" + "Script to decompress a .tar.gz file.") + +(defcustom lsp-tar-script (lambda () + (cond ((executable-find "tar") lsp-ext-tar-script) + (t nil))) + "The script to decompress a .tar.gz file. +Should be a format string with one argument for the file to be decompressed +in place." + :group 'lsp-mode + :type 'string) + +(defun lsp-tar-gz-decompress (targz-file dest) + "Decompress TARGZ-FILE in DEST." + (unless lsp-tar-script + (error "Unable to find `tar' on the path, please either customize `lsp-tar-script' or manually decompress %s" targz-file)) + (shell-command (format (lsp-resolve-value lsp-tar-script) targz-file dest))) + + +;; VSCode marketplace + +(defcustom lsp-vscode-ext-url + "https://marketplace.visualstudio.com/_apis/public/gallery/publishers/%s/vsextensions/%s/%s/vspackage%s" + "Vscode extension template url." + :group 'lsp-mode + :type 'string + :package-version '(lsp-mode . "8.0.0")) + +(defun lsp-vscode-extension-url (publisher name version &optional targetPlatform) + "Return the URL to vscode extension. +PUBLISHER is the extension publisher. +NAME is the name of the extension. +VERSION is the version of the extension. +TARGETPLATFORM is the targetPlatform of the extension." + (format lsp-vscode-ext-url publisher name version (or targetPlatform ""))) + + + +;; Queueing prompts + +(defvar lsp--question-queue nil + "List of questions yet to be asked by `lsp-ask-question'.") + +(defun lsp-ask-question (question options callback) + "Prompt the user to answer the QUESTION with one of the OPTIONS from the +minibuffer. Once the user selects an option, the CALLBACK function will be +called, passing the selected option to it. + +If the user is currently being shown a question, the question will be stored in +`lsp--question-queue', and will be asked once the user has answered the current +question." + (add-to-list 'lsp--question-queue `(("question" . ,question) + ("options" . ,options) + ("callback" . ,callback)) t) + (when (eq (length lsp--question-queue) 1) + (lsp--process-question-queue))) + +(defun lsp--process-question-queue () + "Take the first question from `lsp--question-queue', process it, then process +the next question until the queue is empty." + (-let* (((&alist "question" "options" "callback") (car lsp--question-queue)) + (answer (completing-read question options nil t))) + (pop lsp--question-queue) + (funcall callback answer) + (when lsp--question-queue + (lsp--process-question-queue)))) + +(defun lsp--supports-buffer? (client) + (and + ;; both file and client remote or both local + (eq (---truthy? (file-remote-p (buffer-file-name))) + (---truthy? (lsp--client-remote? client))) + + ;; activation function or major-mode match. + (if-let ((activation-fn (lsp--client-activation-fn client))) + (funcall activation-fn (buffer-file-name) major-mode) + (-contains? (lsp--client-major-modes client) major-mode)) + + ;; check whether it is enabled if `lsp-enabled-clients' is not null + (or (null lsp-enabled-clients) + (or (member (lsp--client-server-id client) lsp-enabled-clients) + (ignore (lsp--info "Client %s is not in lsp-enabled-clients" + (lsp--client-server-id client))))) + + ;; check whether it is not disabled. + (not (lsp--client-disabled-p major-mode (lsp--client-server-id client))))) + +(defun lsp--filter-clients (pred) + (->> lsp-clients hash-table-values (-filter pred))) + +(defun lsp--find-clients () + "Find clients which can handle current buffer." + (-when-let (matching-clients (lsp--filter-clients (-andfn #'lsp--supports-buffer? + #'lsp--server-binary-present?))) + (lsp-log "Found the following clients for %s: %s" + (buffer-file-name) + (s-join ", " + (-map (lambda (client) + (format "(server-id %s, priority %s)" + (lsp--client-server-id client) + (lsp--client-priority client))) + matching-clients))) + (-let* (((add-on-clients main-clients) (-separate #'lsp--client-add-on? matching-clients)) + (selected-clients (if-let ((main-client (and main-clients + (--max-by (> (lsp--client-priority it) + (lsp--client-priority other)) + main-clients)))) + (cons main-client add-on-clients) + add-on-clients))) + (lsp-log "The following clients were selected based on priority: %s" + (s-join ", " + (-map (lambda (client) + (format "(server-id %s, priority %s)" + (lsp--client-server-id client) + (lsp--client-priority client))) + selected-clients))) + selected-clients))) + +(defun lsp-workspace-remove-all-folders() + "Delete all lsp tracked folders." + (interactive) + (--each (lsp-session-folders (lsp-session)) + (lsp-workspace-folders-remove it))) + +(defun lsp-register-client (client) + "Registers LSP client CLIENT." + (let ((client-id (lsp--client-server-id client))) + (puthash client-id client lsp-clients) + (setplist (intern (format "lsp-%s-after-open-hook" client-id)) + `( standard-value (nil) custom-type hook + custom-package-version (lsp-mode . "7.0.1") + variable-documentation ,(format "Hooks to run after `%s' server is run." client-id) + custom-requests nil))) + (when (and lsp-auto-register-remote-clients + (not (lsp--client-remote? client))) + (let ((remote-client (copy-lsp--client client))) + (setf (lsp--client-remote? remote-client) t + (lsp--client-server-id remote-client) (intern + (format "%s-tramp" + (lsp--client-server-id client))) + ;; disable automatic download + (lsp--client-download-server-fn remote-client) nil) + (lsp-register-client remote-client)))) + +(defun lsp--create-initialization-options (_session client) + "Create initialization-options from SESSION and CLIENT. +Add workspace folders depending on server being multiroot and +session workspace folder configuration for the server." + (let* ((initialization-options-or-fn (lsp--client-initialization-options client))) + (if (functionp initialization-options-or-fn) + (funcall initialization-options-or-fn) + initialization-options-or-fn))) + +(defvar lsp-client-settings (make-hash-table :test 'equal) + "For internal use, any external users please use + `lsp-register-custom-settings' function instead") + +(defun lsp-register-custom-settings (props) + "Register PROPS. +PROPS is list of triple (path value boolean?) where PATH is the path to the +property; VALUE can be a literal value, symbol to be evaluated, or either a +function or lambda function to be called without arguments; BOOLEAN? is an +optional flag that should be non-nil for boolean settings, when it is nil the +property will be ignored if the VALUE is nil. + +Example: `(lsp-register-custom-settings `((\"foo.bar.buzz.enabled\" t t)))' +\(note the double parentheses)" + (mapc + (-lambda ((path . rest)) + (puthash path rest lsp-client-settings)) + props)) + +(defun lsp-region-text (region) + "Get the text for REGION in current buffer." + (-let (((start . end) (lsp--range-to-region region))) + (buffer-substring-no-properties start end))) + +(defun lsp-ht-set (tbl paths value) + "Set nested hash table value. +TBL - a hash table, PATHS is the path to the nested VALUE." + (pcase paths + (`(,path) (ht-set! tbl path value)) + (`(,path . ,rst) (let ((nested-tbl (or (gethash path tbl) + (let ((temp-tbl (ht))) + (ht-set! tbl path temp-tbl) + temp-tbl)))) + (lsp-ht-set nested-tbl rst value))))) + +;; sections + +(defalias 'defcustom-lsp 'lsp-defcustom) + +(defmacro lsp-defcustom (symbol standard doc &rest args) + "Defines `lsp-mode' server property." + (declare (doc-string 3) (debug (name body)) + (indent defun)) + (let ((path (plist-get args :lsp-path)) + (setter (intern (concat (symbol-name symbol) "--set")))) + (cl-remf args :lsp-path) + `(progn + (lsp-register-custom-settings + (quote ((,path ,symbol ,(equal ''boolean (plist-get args :type)))))) + + (defcustom ,symbol ,standard ,doc ,@args) + + ;; Use a variable watcher instead of registering a `defcustom' + ;; setter since `hack-local-variables' is not aware of custom + ;; setters and won't invoke them. + + (defun ,setter (sym val op _where) + (when (eq op 'set) + (lsp--set-custom-property sym val ,path))) + + (add-variable-watcher ',symbol #',setter)))) + +(defun lsp--set-custom-property (sym val path) + (set sym val) + (let ((section (cl-first (s-split "\\." path)))) + (mapc (lambda (workspace) + (when (-contains? (lsp--client-synchronize-sections (lsp--workspace-client workspace)) + section) + (with-lsp-workspace workspace + (lsp--set-configuration (lsp-configuration-section section))))) + (lsp--session-workspaces (lsp-session))))) + +(defun lsp-configuration-section (section) + "Get settings for SECTION." + (let ((ret (ht-create))) + (maphash (-lambda (path (variable boolean?)) + (when (s-matches? (concat (regexp-quote section) "\\..*") path) + (let* ((symbol-value (-> variable + lsp-resolve-value + lsp-resolve-value)) + (value (if (and boolean? (not symbol-value)) + :json-false + symbol-value))) + (when (or boolean? value) + (lsp-ht-set ret (s-split "\\." path) value))))) + lsp-client-settings) + ret)) + + +(defun lsp--start-connection (session client project-root) + "Initiates connection created from CLIENT for PROJECT-ROOT. +SESSION is the active session." + (when (lsp--client-multi-root client) + (cl-pushnew project-root (gethash (lsp--client-server-id client) + (lsp-session-server-id->folders session)))) + (run-hook-with-args 'lsp-workspace-folders-changed-functions (list project-root) nil) + + (unwind-protect + (lsp--start-workspace session client project-root (lsp--create-initialization-options session client)) + (lsp--spinner-stop))) + +;; lsp-log-io-mode + +(defvar lsp-log-io-mode-map + (let ((map (make-sparse-keymap))) + (define-key map (kbd "M-n") #'lsp-log-io-next) + (define-key map (kbd "M-p") #'lsp-log-io-prev) + (define-key map (kbd "k") #'lsp--erase-log-buffer) + (define-key map (kbd "K") #'lsp--erase-session-log-buffers) + map) + "Keymap for lsp log buffer mode.") + +(define-derived-mode lsp-log-io-mode special-mode "LspLogIo" + "Special mode for viewing IO logs.") + +(defun lsp-workspace-show-log (workspace) + "Display the log buffer of WORKSPACE." + (interactive + (list (if lsp-log-io + (if (eq (length (lsp-workspaces)) 1) + (cl-first (lsp-workspaces)) + (lsp--completing-read "Workspace: " (lsp-workspaces) + #'lsp--workspace-print nil t)) + (user-error "IO logging is disabled")))) + (pop-to-buffer (lsp--get-log-buffer-create workspace))) + +(defalias 'lsp-switch-to-io-log-buffer 'lsp-workspace-show-log) + +(defun lsp--get-log-buffer-create (workspace) + "Return the lsp log buffer of WORKSPACE, creating a new one if needed." + (let* ((server-id (-> workspace lsp--workspace-client lsp--client-server-id symbol-name)) + (pid (-> workspace lsp--workspace-cmd-proc lsp-process-id))) + (get-buffer-create (format "*lsp-log: %s:%s*" server-id pid)))) + +(defun lsp--erase-log-buffer (&optional all) + "Delete contents of current lsp log buffer. +When ALL is t, erase all log buffers of the running session." + (interactive) + (let* ((workspaces (lsp--session-workspaces (lsp-session))) + (current-log-buffer (current-buffer))) + (dolist (w workspaces) + (let ((b (lsp--get-log-buffer-create w))) + (when (or all (eq b current-log-buffer)) + (with-current-buffer b + (let ((inhibit-read-only t)) + (erase-buffer)))))))) + +(defun lsp--erase-session-log-buffers () + "Erase log buffers of the running session." + (interactive) + (lsp--erase-log-buffer t)) + +(defun lsp-log-io-next (arg) + "Move to next log entry." + (interactive "P") + (ewoc-goto-next lsp--log-io-ewoc (or arg 1))) + +(defun lsp-log-io-prev (arg) + "Move to previous log entry." + (interactive "P") + (ewoc-goto-prev lsp--log-io-ewoc (or arg 1))) + + + +(cl-defmethod lsp-process-id ((process process)) + (process-id process)) + +(cl-defmethod lsp-process-name ((process process)) (process-name process)) + +(cl-defmethod lsp-process-status ((process process)) (process-status process)) + +(cl-defmethod lsp-process-kill ((process process)) + (when (process-live-p process) + (kill-process process))) + +(cl-defmethod lsp-process-send ((process process) message) + (condition-case err + (process-send-string process (lsp--make-message message)) + (error (lsp--error "Sending to process failed with the following error: %s" + (error-message-string err))))) + +(cl-defmethod lsp-process-cleanup (process) + ;; Kill standard error buffer only if the process exited normally. + ;; Leave it intact otherwise for debugging purposes. + (let ((buffer (-> process process-name get-buffer))) + (when (and (eq (process-status process) 'exit) + (zerop (process-exit-status process)) + (buffer-live-p buffer)) + (kill-buffer buffer)))) + + +;; native JSONRPC + +(declare-function json-rpc "ext:json") +(declare-function json-rpc-connection "ext:json") +(declare-function json-rpc-send "ext:json") +(declare-function json-rpc-shutdown "ext:json") +(declare-function json-rpc-stderr "ext:json") +(declare-function json-rpc-pid "ext:json") + +(defvar lsp-json-rpc-thread nil) +(defvar lsp-json-rpc-queue nil) +(defvar lsp-json-rpc-done nil) +(defvar lsp-json-rpc-mutex (make-mutex)) +(defvar lsp-json-rpc-condition (make-condition-variable lsp-json-rpc-mutex)) + +(defun lsp-json-rpc-process-queue () + (while (not lsp-json-rpc-done) + (while lsp-json-rpc-queue + (-let (((proc . message) (pop lsp-json-rpc-queue))) + (json-rpc-send + proc message + :null-object nil + :false-object :json-false))) + (with-mutex lsp-json-rpc-mutex + (condition-wait lsp-json-rpc-condition)))) + +(cl-defmethod lsp-process-id (process) (json-rpc-pid process)) + +(cl-defmethod lsp-process-name (_process) "TBD") + +(cl-defmethod lsp-process-kill (process) (json-rpc-shutdown process)) + +(cl-defmethod lsp-process-send (proc message) + (unless lsp-json-rpc-thread + (with-current-buffer (get-buffer-create " *json-rpc*") + (setq lsp-json-rpc-thread (make-thread #'lsp-json-rpc-process-queue "*json-rpc-queue*")))) + + (with-mutex lsp-json-rpc-mutex + (setq lsp-json-rpc-queue (append lsp-json-rpc-queue + (list (cons proc message)))) + (condition-notify lsp-json-rpc-condition))) + +(cl-defmethod lsp-process-cleanup (_proc)) + +(defun lsp-json-rpc-connection (workspace command) + (let ((con (apply #'json-rpc-connection command)) + (object-type (if lsp-use-plists 'plist 'hash-table))) + (with-current-buffer (get-buffer-create " *json-rpc*") + (make-thread + (lambda () + (json-rpc + con + (lambda (result err done) + (run-with-timer + 0.0 + nil + (lambda () + (cond + (result (lsp--parser-on-message result workspace)) + (err (warn "Json parsing failed with the following error: %s" err)) + (done (lsp--handle-process-exit workspace "")))))) + :object-type object-type + :null-object nil + :false-object nil)) + "*json-rpc-connection*")) + (cons con con))) + +(defun lsp-json-rpc-stderr () + (interactive) + (--when-let (pcase (lsp-workspaces) + (`nil (user-error "There are no active servers in the current buffer")) + (`(,workspace) workspace) + (workspaces (lsp--completing-read "Select server: " + workspaces + 'lsp--workspace-print nil t))) + (let ((content (json-rpc-stderr (lsp--workspace-cmd-proc it))) + (buffer (format "*stderr-%s*" (lsp--workspace-print it)) )) + (with-current-buffer (get-buffer-create buffer) + (with-help-window buffer + (insert content)))))) + + +(defun lsp--workspace-print (workspace) + "Visual representation WORKSPACE." + (let* ((proc (lsp--workspace-cmd-proc workspace)) + (status (lsp--workspace-status workspace)) + (server-id (-> workspace lsp--workspace-client lsp--client-server-id symbol-name)) + (pid (lsp-process-id proc))) + + (if (eq 'initialized status) + (format "%s:%s" server-id pid) + (format "%s:%s/%s" server-id pid status)))) + +(defun lsp--map-tree-widget (m) + "Build `tree-widget' from a hash-table or plist M." + (when (lsp-structure-p m) + (let (nodes) + (lsp-map (lambda (k v) + (push `(tree-widget + :tag ,(if (lsp-structure-p v) + (format "%s:" k) + (format "%s: %s" k + (propertize (format "%s" v) + 'face + 'font-lock-string-face))) + :open t + ,@(lsp--map-tree-widget v)) + nodes)) + m) + nodes))) + +(defun lsp-buffer-name (buffer-id) + (if-let ((buffer-name (plist-get buffer-id :buffer-name))) + (funcall buffer-name buffer-id) + (buffer-name buffer-id))) + +(defun lsp--render-workspace (workspace) + "Tree node representation of WORKSPACE." + `(tree-widget :tag ,(lsp--workspace-print workspace) + :open t + (tree-widget :tag ,(propertize "Buffers" 'face 'font-lock-function-name-face) + :open t + ,@(->> workspace + (lsp--workspace-buffers) + (--map `(tree-widget + :tag ,(when (lsp-buffer-live-p it) + (let ((buffer-name (lsp-buffer-name it))) + (if (lsp-with-current-buffer it buffer-read-only) + (propertize buffer-name 'face 'font-lock-constant-face) + buffer-name))))))) + (tree-widget :tag ,(propertize "Capabilities" 'face 'font-lock-function-name-face) + ,@(-> workspace lsp--workspace-server-capabilities lsp--map-tree-widget)))) + +(define-derived-mode lsp-browser-mode special-mode "LspBrowser" + "Define mode for displaying lsp sessions." + (setq-local display-buffer-base-action '(nil . ((inhibit-same-window . t))))) + +(defun lsp-describe-session () + "Describes current `lsp-session'." + (interactive) + (let ((session (lsp-session)) + (buf (get-buffer-create "*lsp session*")) + (root (lsp-workspace-root))) + (with-current-buffer buf + (lsp-browser-mode) + (let ((inhibit-read-only t)) + (erase-buffer) + (--each (lsp-session-folders session) + (widget-create + `(tree-widget + :tag ,(propertize it 'face 'font-lock-keyword-face) + :open t + ,@(->> session + (lsp-session-folder->servers) + (gethash it) + (-map 'lsp--render-workspace))))))) + (pop-to-buffer buf) + (goto-char (point-min)) + (cl-loop for tag = (widget-get (widget-get (widget-at) :node) :tag) + until (or (and root (string= tag root)) (eobp)) + do (goto-char (next-overlay-change (point)))))) + +(defun lsp--session-workspaces (session) + "Get all workspaces that are part of the SESSION." + (-> session lsp-session-folder->servers hash-table-values -flatten -uniq)) + +(defun lsp--find-multiroot-workspace (session client project-root) + "Look for a multiroot connection in SESSION created from CLIENT for +PROJECT-ROOT and BUFFER-MAJOR-MODE." + (when (lsp--client-multi-root client) + (-when-let (multi-root-workspace (->> session + (lsp--session-workspaces) + (--first (eq (-> it lsp--workspace-client lsp--client-server-id) + (lsp--client-server-id client))))) + (with-lsp-workspace multi-root-workspace + (lsp-notify "workspace/didChangeWorkspaceFolders" + (lsp-make-did-change-workspace-folders-params + :event (lsp-make-workspace-folders-change-event + :added (vector (lsp-make-workspace-folder + :uri (lsp--path-to-uri project-root) + :name (f-filename project-root))) + :removed [])))) + + (->> session (lsp-session-folder->servers) (gethash project-root) (cl-pushnew multi-root-workspace)) + (->> session (lsp-session-server-id->folders) (gethash (lsp--client-server-id client)) (cl-pushnew project-root)) + + (lsp--persist-session session) + + (lsp--info "Opened folder %s in workspace %s" project-root (lsp--workspace-print multi-root-workspace)) + (lsp--open-in-workspace multi-root-workspace) + + multi-root-workspace))) + +(defun lsp--ensure-lsp-servers (session clients project-root ignore-multi-folder) + "Ensure that SESSION contain server CLIENTS created for PROJECT-ROOT. +IGNORE-MULTI-FOLDER to ignore multi folder server." + (-map (lambda (client) + (or + (lsp--find-workspace session client project-root) + (unless ignore-multi-folder + (lsp--find-multiroot-workspace session client project-root)) + (lsp--start-connection session client project-root))) + clients)) + +(defun lsp--spinner-stop () + "Stop the spinner in case all of the workspaces are started." + (when (--all? (eq (lsp--workspace-status it) 'initialized) + lsp--buffer-workspaces) + (spinner-stop))) + +(defun lsp--open-in-workspace (workspace) + "Open in existing WORKSPACE." + (if (eq 'initialized (lsp--workspace-status workspace)) + ;; when workspace is initialized just call document did open. + (progn + (with-lsp-workspace workspace + (when-let ((before-document-open-fn (-> workspace + lsp--workspace-client + lsp--client-before-file-open-fn))) + (funcall before-document-open-fn workspace)) + (lsp--text-document-did-open)) + (lsp--spinner-stop)) + ;; when it is not initialized + (lsp--spinner-start) + (cl-pushnew (lsp-current-buffer) (lsp--workspace-buffers workspace)))) + +(defun lsp--find-workspace (session client project-root) + "Find server connection created with CLIENT in SESSION for PROJECT-ROOT." + (when-let ((workspace (->> session + (lsp-session-folder->servers) + (gethash project-root) + (--first (eql (-> it lsp--workspace-client lsp--client-server-id) + (lsp--client-server-id client)))))) + (lsp--open-in-workspace workspace) + workspace)) + +(defun lsp--read-char (prompt &optional options) + "Wrapper for `read-char-from-minibuffer' if Emacs +27. +Fallback to `read-key' otherwise. +PROMPT is the message and OPTIONS the available options." + (if (fboundp 'read-char-from-minibuffer) + (read-char-from-minibuffer prompt options) + (read-key prompt))) + +(defun lsp--find-root-interactively (session) + "Find project interactively. +Returns nil if the project should not be added to the current SESSION." + (condition-case nil + (let* ((project-root-suggestion (or (lsp--suggest-project-root) default-directory)) + (action (lsp--read-char + (format + "%s is not part of any project. + +%s ==> Import project root %s +%s ==> Import project by selecting root directory interactively +%s ==> Import project at current directory %s +%s ==> Do not ask again for the current project by adding %s to lsp-session-folders-blocklist +%s ==> Do not ask again for the current project by selecting ignore path interactively +%s ==> Do nothing: ask again when opening other files from the current project + +Select action: " + (propertize (buffer-name) 'face 'bold) + (propertize "i" 'face 'success) + (propertize project-root-suggestion 'face 'bold) + (propertize "I" 'face 'success) + (propertize "." 'face 'success) + (propertize default-directory 'face 'bold) + (propertize "d" 'face 'warning) + (propertize project-root-suggestion 'face 'bold) + (propertize "D" 'face 'warning) + (propertize "n" 'face 'warning)) + '(?i ?\r ?I ?. ?d ?D ?n)))) + (cl-case action + (?i project-root-suggestion) + (?\r project-root-suggestion) + (?I (read-directory-name "Select workspace folder to add: " + (or project-root-suggestion default-directory) + nil + t)) + (?. default-directory) + (?d (push project-root-suggestion (lsp-session-folders-blocklist session)) + (lsp--persist-session session) + nil) + (?D (push (read-directory-name "Select folder to blocklist: " + (or project-root-suggestion default-directory) + nil + t) + (lsp-session-folders-blocklist session)) + (lsp--persist-session session) + nil) + (t nil))) + (quit))) + +(declare-function tramp-file-name-host "ext:tramp" (file) t) +(declare-function tramp-dissect-file-name "ext:tramp" (file &optional nodefault)) + +(defun lsp--files-same-host (f1 f2) + "Predicate on whether or not two files are on the same host." + (or (not (or (file-remote-p f1) (file-remote-p f2))) + (and (file-remote-p f1) + (file-remote-p f2) + (progn (require 'tramp) + (equal (tramp-file-name-host (tramp-dissect-file-name f1)) + (tramp-file-name-host (tramp-dissect-file-name f2))))))) + +(defun lsp-find-session-folder (session file-name) + "Look in the current SESSION for folder containing FILE-NAME." + (let ((file-name-canonical (lsp-f-canonical file-name))) + (->> session + (lsp-session-folders) + (--filter (and (lsp--files-same-host it file-name-canonical) + (or (lsp-f-same? it file-name-canonical) + (and (f-dir? it) + (lsp-f-ancestor-of? it file-name-canonical))))) + (--max-by (> (length it) + (length other)))))) + +(defun lsp-find-workspace (server-id &optional file-name) + "Find workspace for SERVER-ID for FILE-NAME." + (-when-let* ((session (lsp-session)) + (folder->servers (lsp-session-folder->servers session)) + (workspaces (if file-name + (gethash (lsp-find-session-folder session file-name) folder->servers) + (lsp--session-workspaces session)))) + + (--first (eq (lsp--client-server-id (lsp--workspace-client it)) server-id) workspaces))) + +(defun lsp--calculate-root (session file-name) + "Calculate project root for FILE-NAME in SESSION." + (and + (->> session + (lsp-session-folders-blocklist) + (--first (and (lsp--files-same-host it file-name) + (lsp-f-ancestor-of? it file-name) + (prog1 t + (lsp--info "File %s is in blocklisted directory %s" file-name it)))) + not) + (or + (when lsp-auto-guess-root + (lsp--suggest-project-root)) + (unless lsp-guess-root-without-session + (lsp-find-session-folder session file-name)) + (unless lsp-auto-guess-root + (when-let ((root-folder (lsp--find-root-interactively session))) + (if (or (not (f-equal? root-folder (expand-file-name "~/"))) + (yes-or-no-p + (concat + (propertize "[WARNING] " 'face 'warning) + "You are trying to import your home folder as project root. This may cause performance issue because some language servers (python, lua, etc) will try to scan all files under project root. To avoid that you may: + +1. Use `I' option from the interactive project import to select subfolder(e. g. `~/foo/bar' instead of `~/'). +2. If your file is under `~/' then create a subfolder and move that file in this folder. + +Type `No' to go back to project selection. +Type `Yes' to confirm `HOME' as project root. +Type `C-g' to cancel project import process and stop `lsp'"))) + root-folder + (lsp--calculate-root session file-name))))))) + +(defun lsp--try-open-in-library-workspace () + "Try opening current file as library file in any of the active workspace. +The library folders are defined by each client for each of the active workspace." + (when-let ((workspace (->> (lsp-session) + (lsp--session-workspaces) + ;; Sort the last active workspaces first as they are more likely to be + ;; the correct ones, especially when jumping to a definition. + (-sort (lambda (a _b) + (-contains? lsp--last-active-workspaces a))) + (--first + (and (-> it lsp--workspace-client lsp--supports-buffer?) + (when-let ((library-folders-fn + (-> it lsp--workspace-client lsp--client-library-folders-fn))) + (-first (lambda (library-folder) + (lsp-f-ancestor-of? library-folder (buffer-file-name))) + (funcall library-folders-fn it)))))))) + (lsp--open-in-workspace workspace) + (view-mode t) + (lsp--info "Opening read-only library file %s." (buffer-file-name)) + (list workspace))) + +(defun lsp--persist-session (session) + "Persist SESSION to `lsp-session-file'." + (lsp--persist lsp-session-file (make-lsp-session + :folders (lsp-session-folders session) + :folders-blocklist (lsp-session-folders-blocklist session) + :server-id->folders (lsp-session-server-id->folders session)))) + +(defun lsp--try-project-root-workspaces (ask-for-client ignore-multi-folder) + "Try create opening file as a project file. +When IGNORE-MULTI-FOLDER is t the lsp mode will start new +language server even if there is language server which can handle +current language. When IGNORE-MULTI-FOLDER is nil current file +will be opened in multi folder language server if there is +such." + (-let ((session (lsp-session))) + (-if-let (clients (if ask-for-client + (list (lsp--completing-read "Select server to start: " + (ht-values lsp-clients) + (-compose 'symbol-name 'lsp--client-server-id) nil t)) + (lsp--find-clients))) + (-if-let (project-root (-some-> session + (lsp--calculate-root (buffer-file-name)) + (lsp-f-canonical))) + (progn + ;; update project roots if needed and persist the lsp session + (unless (-contains? (lsp-session-folders session) project-root) + (cl-pushnew project-root (lsp-session-folders session)) + (lsp--persist-session session)) + (lsp--ensure-lsp-servers session clients project-root ignore-multi-folder)) + (lsp--warn "%s not in project or it is blocklisted." (buffer-name)) + nil) + (lsp--warn "No LSP server for %s(check *lsp-log*)." major-mode) + nil))) + +(defun lsp-shutdown-workspace () + "Shutdown language server." + (interactive) + (--when-let (pcase (lsp-workspaces) + (`nil (user-error "There are no active servers in the current buffer")) + (`(,workspace) (when (y-or-n-p (format "Are you sure you want to stop the server %s?" + (lsp--workspace-print workspace))) + workspace)) + (workspaces (lsp--completing-read "Select server: " + workspaces + 'lsp--workspace-print nil t))) + (lsp-workspace-shutdown it))) + +(make-obsolete 'lsp-shutdown-workspace 'lsp-workspace-shutdown "lsp-mode 6.1") + +(defcustom lsp-auto-select-workspace t + "Shutdown or restart a single workspace. +If set and the current buffer has only a single workspace +associated with it, `lsp-shutdown-workspace' and +`lsp-restart-workspace' will act on it without asking." + :type 'boolean + :group 'lsp-mode) + +(defun lsp--read-workspace () + "Ask the user to select a workspace. +Errors if there are none." + (pcase (lsp-workspaces) + (`nil (error "No workspaces associated with the current buffer")) + ((and `(,workspace) (guard lsp-auto-select-workspace)) workspace) + (workspaces (lsp--completing-read "Select workspace: " workspaces + #'lsp--workspace-print nil t)))) + +(defun lsp-workspace-shutdown (workspace) + "Shut the workspace WORKSPACE and the language server associated with it" + (interactive (list (lsp--read-workspace))) + (lsp--warn "Stopping %s" (lsp--workspace-print workspace)) + (with-lsp-workspace workspace (lsp--shutdown-workspace))) + +(defun lsp-disconnect () + "Disconnect the buffer from the language server." + (interactive) + (lsp--text-document-did-close t) + (lsp-managed-mode -1) + (lsp-mode -1) + (setq lsp--buffer-workspaces nil) + (lsp--info "Disconnected")) + +(defun lsp-restart-workspace () + (interactive) + (--when-let (pcase (lsp-workspaces) + (`nil (user-error "There are no active servers in the current buffer")) + (`(,workspace) workspace) + (workspaces (lsp--completing-read "Select server: " + workspaces + 'lsp--workspace-print nil t))) + (lsp-workspace-restart it))) + +(make-obsolete 'lsp-restart-workspace 'lsp-workspace-restart "lsp-mode 6.1") + +(defun lsp-workspace-restart (workspace) + "Restart the workspace WORKSPACE and the language server associated with it" + (interactive (list (lsp--read-workspace))) + (lsp--warn "Restarting %s" (lsp--workspace-print workspace)) + (with-lsp-workspace workspace (lsp--shutdown-workspace t))) + +;;;###autoload +(defun lsp (&optional arg) + "Entry point for the server startup. +When ARG is t the lsp mode will start new language server even if +there is language server which can handle current language. When +ARG is nil current file will be opened in multi folder language +server if there is such. When `lsp' is called with prefix +argument ask the user to select which language server to start." + (interactive "P") + + (lsp--require-packages) + + (when (buffer-file-name) + (let (clients + (matching-clients (lsp--filter-clients + (-andfn #'lsp--supports-buffer? + #'lsp--server-binary-present?)))) + (cond + (matching-clients + (when (setq lsp--buffer-workspaces + (or (and + ;; Don't open as library file if file is part of a project. + (not (lsp-find-session-folder (lsp-session) (buffer-file-name))) + (lsp--try-open-in-library-workspace)) + (lsp--try-project-root-workspaces (equal arg '(4)) + (and arg (not (equal arg 1)))))) + (lsp-mode 1) + (when lsp-auto-configure (lsp--auto-configure)) + (setq lsp-buffer-uri (lsp--buffer-uri)) + (lsp--info "Connected to %s." + (apply 'concat (--map (format "[%s %s]" + (lsp--workspace-print it) + (lsp--workspace-root it)) + lsp--buffer-workspaces))))) + ;; look for servers which are currently being downloaded. + ((setq clients (lsp--filter-clients (-andfn #'lsp--supports-buffer? + #'lsp--client-download-in-progress?))) + (lsp--info "There are language server(%s) installation in progress. +The server(s) will be started in the buffer when it has finished." + (-map #'lsp--client-server-id clients)) + (seq-do (lambda (client) + (cl-pushnew (current-buffer) (lsp--client-buffers client))) + clients)) + ;; look for servers to install + ((setq clients (lsp--filter-clients + (-andfn #'lsp--supports-buffer? + (-const lsp-enable-suggest-server-download) + #'lsp--client-download-server-fn + (-not #'lsp--client-download-in-progress?)))) + (let ((client (lsp--completing-read + (concat "Unable to find installed server supporting this file. " + "The following servers could be installed automatically: ") + clients + (-compose #'symbol-name #'lsp--client-server-id) + nil + t))) + (cl-pushnew (current-buffer) (lsp--client-buffers client)) + (lsp--install-server-internal client))) + ;; ignore other warnings + ((not lsp-warn-no-matched-clients) + nil) + ;; automatic installation disabled + ((setq clients (unless matching-clients + (lsp--filter-clients (-andfn #'lsp--supports-buffer? + #'lsp--client-download-server-fn + (-not (-const lsp-enable-suggest-server-download)) + (-not #'lsp--server-binary-present?))))) + (lsp--warn "The following servers support current file but automatic download is disabled: %s +\(If you have already installed the server check *lsp-log*)." + (mapconcat (lambda (client) + (symbol-name (lsp--client-server-id client))) + clients + " "))) + ;; no clients present + ((setq clients (unless matching-clients + (lsp--filter-clients (-andfn #'lsp--supports-buffer? + (-not #'lsp--server-binary-present?))))) + (lsp--warn "The following servers support current file but do not have automatic installation: %s +You may find the installation instructions at https://emacs-lsp.github.io/lsp-mode/page/languages. +\(If you have already installed the server check *lsp-log*)." + (mapconcat (lambda (client) + (symbol-name (lsp--client-server-id client))) + clients + " "))) + ;; no matches + ((-> #'lsp--supports-buffer? lsp--filter-clients not) + (lsp--error "There are no language servers supporting current mode `%s' registered with `lsp-mode'. +This issue might be caused by: +1. The language you are trying to use does not have built-in support in `lsp-mode'. You must install the required support manually. Examples of this are `lsp-java' or `lsp-metals'. +2. The language server that you expect to run is not configured to run for major mode `%s'. You may check that by checking the `:major-modes' that are passed to `lsp-register-client'. +3. `lsp-mode' doesn't have any integration for the language behind `%s'. Refer to https://emacs-lsp.github.io/lsp-mode/page/languages and https://langserver.org/ . +4. You are over `tramp'. In this case follow https://emacs-lsp.github.io/lsp-mode/page/remote/. +5. You have disabled the `lsp-mode' clients for that file. (Check `lsp-enabled-clients' and `lsp-disabled-clients'). +You can customize `lsp-warn-no-matched-clients' to disable this message." + major-mode major-mode major-mode)))))) + +(defun lsp--buffer-visible-p () + "Return non nil if current buffer is visible." + (or (buffer-modified-p) (get-buffer-window nil t))) + +(defun lsp--init-if-visible () + "Run `lsp' for the current buffer if the buffer is visible. +Returns non nil if `lsp' was run for the buffer." + (when (lsp--buffer-visible-p) + (remove-hook 'window-configuration-change-hook #'lsp--init-if-visible t) + (lsp) + t)) + +;;;###autoload +(defun lsp-deferred () + "Entry point that defers server startup until buffer is visible. +`lsp-deferred' will wait until the buffer is visible before invoking `lsp'. +This avoids overloading the server with many files when starting Emacs." + ;; Workspace may not be initialized yet. Use a buffer local variable to + ;; remember that we deferred loading of this buffer. + (setq lsp--buffer-deferred t) + (let ((buffer (current-buffer))) + ;; Avoid false positives as desktop-mode restores buffers by deferring + ;; visibility check until the stack clears. + (run-with-idle-timer 0 nil (lambda () + (when (buffer-live-p buffer) + (with-current-buffer buffer + (unless (lsp--init-if-visible) + (add-hook 'window-configuration-change-hook #'lsp--init-if-visible nil t)))))))) + + + +(defvar lsp-file-truename-cache (ht)) + +(defmacro lsp-with-cached-filetrue-name (&rest body) + "Executes BODY caching the `file-truename' calls." + `(let ((old-fn (symbol-function 'file-truename))) + (unwind-protect + (progn + (fset 'file-truename + (lambda (file-name &optional counter prev-dirs) + (or (gethash file-name lsp-file-truename-cache) + (puthash file-name (apply old-fn (list file-name counter prev-dirs)) + lsp-file-truename-cache)))) + ,@body) + (fset 'file-truename old-fn)))) + + +(defun lsp-virtual-buffer-call (key &rest args) + (when lsp--virtual-buffer + (when-let ((fn (plist-get lsp--virtual-buffer key))) + (apply fn args)))) + +(defun lsp-translate-column (column) + "Translate COLUMN taking into account virtual buffers." + (or (lsp-virtual-buffer-call :real->virtual-char column) + column)) + +(defun lsp-translate-line (line) + "Translate LINE taking into account virtual buffers." + (or (lsp-virtual-buffer-call :real->virtual-line line) + line)) + + +;; lsp internal validation. + +(defmacro lsp--doctor (&rest checks) + `(-let [buf (current-buffer)] + (with-current-buffer (get-buffer-create "*lsp-performance*") + (with-help-window (current-buffer) + ,@(-map (-lambda ((msg form)) + `(insert (format "%s: %s\n" ,msg + (let ((res (with-current-buffer buf + ,form))) + (cond + ((eq res :optional) (propertize "OPTIONAL" 'face 'warning)) + (res (propertize "OK" 'face 'success)) + (t (propertize "ERROR" 'face 'error))))))) + (-partition 2 checks)))))) + +(define-obsolete-function-alias 'lsp-diagnose + 'lsp-doctor "lsp-mode 8.0.0") + +(defun lsp-doctor () + "Validate performance settings." + (interactive) + (lsp--doctor + "Checking for Native JSON support" (functionp 'json-serialize) + "Check emacs supports `read-process-output-max'" (boundp 'read-process-output-max) + "Check `read-process-output-max' default has been changed from 4k" + (and (boundp 'read-process-output-max) + (> read-process-output-max 4096)) + "Byte compiled against Native JSON (recompile lsp-mode if failing when Native JSON available)" + (condition-case _err + (progn (lsp--make-message (list "a" "b")) + nil) + (error t)) + "`gc-cons-threshold' increased?" (> gc-cons-threshold 800000) + "Using `plist' for deserialized objects? (refer to https://emacs-lsp.github.io/lsp-mode/page/performance/#use-plists-for-deserialization)" (or lsp-use-plists :optional) + "Using emacs 28+ with native compilation?" + (or (and (fboundp 'native-comp-available-p) + (native-comp-available-p)) + :optional))) + +(declare-function package-version-join "ext:package") +(declare-function package-desc-version "ext:package") +(declare-function package--alist "ext:package") + +(defun lsp-version () + "Return string describing current version of `lsp-mode'." + (interactive) + (unless (featurep 'package) + (require 'package)) + (let ((ver (format "lsp-mode %s, Emacs %s, %s" + (package-version-join + (package-desc-version + (car (alist-get 'lsp-mode (package--alist))))) + emacs-version + system-type))) + (if (called-interactively-p 'interactive) + (lsp--info "%s" ver) + ver))) + + + +;; org-mode/virtual-buffer + +(declare-function org-babel-get-src-block-info "ext:ob-core") +(declare-function org-do-remove-indentation "ext:org-macs") +(declare-function org-src-get-lang-mode "ext:org-src") +(declare-function org-element-context "ext:org-element") + +(defun lsp--virtual-buffer-update-position () + (-if-let (virtual-buffer (-first (-lambda ((&plist :in-range)) + (funcall in-range)) + lsp--virtual-buffer-connections)) + (unless (equal virtual-buffer lsp--virtual-buffer) + (lsp-org)) + (when lsp-managed-mode + (lsp-managed-mode -1) + (lsp-mode -1) + (setq lsp--buffer-workspaces nil) + (setq lsp--virtual-buffer nil) + (setq lsp-buffer-uri nil) + + ;; force refresh of diagnostics + (run-hooks 'lsp-after-diagnostics-hook)))) + +(defun lsp-virtual-buffer-on-change (start end length) + "Adjust on change event to be executed against the proper language server." + (let ((max-point (max end + (or (plist-get lsp--before-change-vals :end) 0) + (+ start length)))) + (when-let ((virtual-buffer (-first (lambda (vb) + (let ((lsp--virtual-buffer vb)) + (and (lsp-virtual-buffer-call :in-range start) + (lsp-virtual-buffer-call :in-range max-point)))) + lsp--virtual-buffer-connections))) + (lsp-with-current-buffer virtual-buffer + (lsp-on-change start end length + (lambda (&rest _) + (list :range (lsp--range (list :character 0 :line 0) + lsp--virtual-buffer-point-max) + :text (lsp--buffer-content)))))))) + +(defun lsp-virtual-buffer-before-change (start _end) + (when-let ((virtual-buffer (-first (lambda (vb) + (lsp-with-current-buffer vb + (lsp-virtual-buffer-call :in-range start))) + lsp--virtual-buffer-connections))) + (lsp-with-current-buffer virtual-buffer + (setq lsp--virtual-buffer-point-max + (lsp--point-to-position (lsp-virtual-buffer-call :last-point)))))) + +(defun lsp-patch-on-change-event () + (remove-hook 'after-change-functions #'lsp-on-change t) + (add-hook 'after-change-functions #'lsp-virtual-buffer-on-change nil t) + (add-hook 'before-change-functions #'lsp-virtual-buffer-before-change nil t)) + +(defun lsp-kill-virtual-buffers () + (mapc #'lsp-virtual-buffer-disconnect lsp--virtual-buffer-connections)) + +(defun lsp--move-point-in-indentation (point indentation) + (save-excursion + (goto-char point) + (if (<= point (+ (line-beginning-position) indentation)) + (line-beginning-position) + point))) + +(declare-function flycheck-checker-supports-major-mode-p "ext:flycheck") +(declare-function flycheck-add-mode "ext:flycheck") +(declare-function lsp-diagnostics-lsp-checker-if-needed "lsp-diagnostics") + +(defalias 'lsp-client-download-server-fn 'lsp--client-download-server-fn) + +(defun lsp-flycheck-add-mode (mode) + "Register flycheck support for MODE." + (lsp-diagnostics-lsp-checker-if-needed) + (unless (flycheck-checker-supports-major-mode-p 'lsp mode) + (flycheck-add-mode 'lsp mode))) + +(defun lsp-progress-spinner-type () + "Retrieve the spinner type value, if value is not a symbol of `spinner-types +defaults to `progress-bar." + (or (car (assoc lsp-progress-spinner-type spinner-types)) 'progress-bar)) + +(defun lsp-org () + (interactive) + (-if-let ((virtual-buffer &as &plist :workspaces) (-first (-lambda ((&plist :in-range)) + (funcall in-range)) + lsp--virtual-buffer-connections)) + (unless (equal lsp--virtual-buffer virtual-buffer) + (setq lsp--buffer-workspaces workspaces) + (setq lsp--virtual-buffer virtual-buffer) + (setq lsp-buffer-uri nil) + (lsp-mode 1) + (lsp-managed-mode 1) + (lsp-patch-on-change-event)) + + (save-excursion + (-let* (virtual-buffer + (wcb (lambda (f) + (with-current-buffer (plist-get virtual-buffer :buffer) + (-let* (((&plist :major-mode :buffer-file-name + :goto-buffer :workspaces) virtual-buffer) + (lsp--virtual-buffer virtual-buffer) + (lsp--buffer-workspaces workspaces)) + (save-excursion + (funcall goto-buffer) + (funcall f)))))) + ((&plist :begin :end :post-blank :language) (cl-second (org-element-context))) + ((&alist :tangle file-name) (cl-third (org-babel-get-src-block-info 'light))) + + (file-name (if file-name + (f-expand file-name) + (user-error "You should specify file name in the src block header."))) + (begin-marker (progn + (goto-char begin) + (forward-line) + (set-marker (make-marker) (point)))) + (end-marker (progn + (goto-char end) + (forward-line (1- (- post-blank))) + (set-marker (make-marker) (1+ (point))))) + (buf (current-buffer)) + (src-block (buffer-substring-no-properties begin-marker + (1- end-marker))) + (indentation (with-temp-buffer + (insert src-block) + + (goto-char (point-min)) + (let ((indentation (current-indentation))) + (plist-put lsp--virtual-buffer :indentation indentation) + (org-do-remove-indentation) + (goto-char (point-min)) + (- indentation (current-indentation)))))) + (add-hook 'post-command-hook #'lsp--virtual-buffer-update-position nil t) + + (when (fboundp 'flycheck-add-mode) + (lsp-flycheck-add-mode 'org-mode)) + + (setq lsp--virtual-buffer + (list + :in-range (lambda (&optional point) + (<= begin-marker (or point (point)) (1- end-marker))) + :goto-buffer (lambda () (goto-char begin-marker)) + :buffer-string + (lambda () + (let ((src-block (buffer-substring-no-properties + begin-marker + (1- end-marker)))) + (with-temp-buffer + (insert src-block) + + (goto-char (point-min)) + (while (not (eobp)) + (delete-region (point) (if (> (+ (point) indentation) (line-end-position)) + (line-end-position) + (+ (point) indentation))) + (forward-line)) + (buffer-substring-no-properties (point-min) + (point-max))))) + :buffer buf + :begin begin-marker + :end end-marker + :indentation indentation + :last-point (lambda () (1- end-marker)) + :cur-position (lambda () + (lsp-save-restriction-and-excursion + (list :line (- (lsp--cur-line) + (lsp--cur-line begin-marker)) + :character (let ((character (- (point) + (line-beginning-position) + indentation))) + (if (< character 0) + 0 + character))))) + :line/character->point (-lambda (line character) + (-let [inhibit-field-text-motion t] + (+ indentation + (lsp-save-restriction-and-excursion + (goto-char begin-marker) + (forward-line line) + (-let [line-end (line-end-position)] + (if (> character (- line-end (point))) + line-end + (forward-char character) + (point))))))) + :major-mode (org-src-get-lang-mode language) + :buffer-file-name file-name + :buffer-uri (lsp--path-to-uri file-name) + :with-current-buffer wcb + :buffer-live? (lambda (_) (buffer-live-p buf)) + :buffer-name (lambda (_) + (propertize (format "%s(%s:%s)%s" + (buffer-name buf) + begin-marker + end-marker + language) + 'face 'italic)) + :real->virtual-line (lambda (line) + (+ line (line-number-at-pos begin-marker) -1)) + :real->virtual-char (lambda (char) (+ char indentation)) + :cleanup (lambda () + (set-marker begin-marker nil) + (set-marker end-marker nil)))) + (setf virtual-buffer lsp--virtual-buffer) + (puthash file-name virtual-buffer lsp--virtual-buffer-mappings) + (push virtual-buffer lsp--virtual-buffer-connections) + + ;; TODO: tangle only connected sections + (add-hook 'after-save-hook 'org-babel-tangle nil t) + (add-hook 'lsp-after-open-hook #'lsp-patch-on-change-event nil t) + (add-hook 'kill-buffer-hook #'lsp-kill-virtual-buffers nil t) + + (setq lsp--buffer-workspaces + (lsp-with-current-buffer virtual-buffer + (lsp) + (plist-put virtual-buffer :workspaces (lsp-workspaces)) + (lsp-workspaces))))))) + +(defun lsp-virtual-buffer-disconnect (virtual-buffer) + (interactive (list (or + lsp--virtual-buffer + (when lsp--virtual-buffer-connections + (lsp--completing-read "Select virtual buffer to disconnect: " + lsp--virtual-buffer-connections + (-lambda ((&plist :buffer-file-name)) + buffer-file-name)))))) + (-if-let ((&plist :buffer-file-name file-name :cleanup) virtual-buffer) + (progn + (lsp-with-current-buffer virtual-buffer + (lsp--text-document-did-close)) + (setq lsp--virtual-buffer-connections (-remove-item virtual-buffer lsp--virtual-buffer-connections)) + (when (eq virtual-buffer lsp--virtual-buffer) + (setf lsp--virtual-buffer nil)) + (when cleanup (funcall cleanup)) + (remhash file-name lsp--virtual-buffer-mappings) + + (lsp--virtual-buffer-update-position) + (lsp--info "Disconnected from buffer %s" file-name)) + (lsp--error "Nothing to disconnect from?"))) + + +;; inlay hints + +(defface lsp-inlay-hint-face + '((t :inherit font-lock-comment-face)) + "The face to use for the JavaScript inlays." + :group 'lsp-mode + :package-version '(lsp-mode . "9.0.0")) + +(defface lsp-inlay-hint-type-face + '((t :inherit lsp-inlay-hint-face)) + "Face for inlay type hints (e.g. inferred variable types)." + :group 'lsp-mode + :package-version '(lsp-mode . "9.0.0")) + +(defcustom lsp-inlay-hint-type-format "%s" + "Format string for variable inlays (part of the inlay face)." + :type '(string :tag "String") + :group 'lsp-mode + :package-version '(lsp-mode . "9.0.0")) + +(defface lsp-inlay-hint-parameter-face + '((t :inherit lsp-inlay-hint-face)) + "Face for inlay parameter hints (e.g. function parameter names at +call-site)." + :group 'lsp-mode + :package-version '(lsp-mode . "9.0.0")) + +(defcustom lsp-inlay-hint-param-format "%s" + "Format string for parameter inlays (part of the inlay face)." + :type '(string :tag "String") + :group 'lsp-mode + :package-version '(lsp-mode . "9.0.0")) + +(defcustom lsp-update-inlay-hints-on-scroll t + "If non-nil update inlay hints immediately when scrolling or +modifying window sizes." + :type 'boolean + :package-version '(lsp-mode . "9.0.0")) + +(defun lsp--format-inlay (text kind) + (cond + ((eql kind lsp/inlay-hint-kind-type-hint) (format lsp-inlay-hint-type-format text)) + ((eql kind lsp/inlay-hint-kind-parameter-hint) (format lsp-inlay-hint-param-format text)) + (t text))) + +(defun lsp--face-for-inlay (kind) + (cond + ((eql kind lsp/inlay-hint-kind-type-hint) 'lsp-inlay-hint-type-face) + ((eql kind lsp/inlay-hint-kind-parameter-hint) 'lsp-inlay-hint-parameter-face) + (t 'lsp-inlay-hint-face))) + +(defun lsp--update-inlay-hints-scroll-function (window start) + (lsp-update-inlay-hints start (window-end window t))) + +(defun lsp--update-inlay-hints () + (lsp-update-inlay-hints (window-start) (window-end nil t))) + +(defun lsp--label-from-inlay-hints-response (label) + "Returns a string label built from an array of +InlayHintLabelParts or the argument itself if it's already a +string." + (cl-typecase label + (string label) + (vector + (string-join (mapcar (lambda (part) + (-let (((&InlayHintLabelPart :value) part)) + value)) + label))))) + +(defun lsp-update-inlay-hints (start end) + (lsp-request-async + "textDocument/inlayHint" + (lsp-make-inlay-hints-params + :text-document (lsp--text-document-identifier) + :range (lsp-make-range :start + (lsp-point-to-position start) + :end + (lsp-point-to-position end))) + (lambda (res) + (lsp--remove-overlays 'lsp-inlay-hint) + (dolist (hint res) + (-let* (((&InlayHint :label :position :kind? :padding-left? :padding-right?) hint) + (kind (or kind? lsp/inlay-hint-kind-type-hint)) + (label (lsp--label-from-inlay-hints-response label)) + (pos (lsp--position-to-point position)) + (overlay (make-overlay pos pos nil 'front-advance 'end-advance))) + (when (stringp label) + (overlay-put overlay 'lsp-inlay-hint t) + (overlay-put overlay 'before-string + (format "%s%s%s" + (if padding-left? " " "") + (propertize (lsp--format-inlay label kind) + 'font-lock-face (lsp--face-for-inlay kind)) + (if padding-right? " " ""))))))) + :mode 'tick)) + +(define-minor-mode lsp-inlay-hints-mode + "Mode for displaying inlay hints." + :lighter nil + (cond + ((and lsp-inlay-hints-mode lsp--buffer-workspaces) + (add-hook 'lsp-on-idle-hook #'lsp--update-inlay-hints nil t) + (when lsp-update-inlay-hints-on-scroll + (add-to-list (make-local-variable 'window-scroll-functions) + #'lsp--update-inlay-hints-scroll-function))) + (t + (lsp--remove-overlays 'lsp-inlay-hint) + (remove-hook 'lsp-on-idle-hook #'lsp--update-inlay-hints t) + (setf window-scroll-functions + (delete #'lsp--update-inlay-hints-scroll-function window-scroll-functions))))) + + + +;;;###autoload +(defun lsp-start-plain () + "Start `lsp-mode' using minimal configuration using the latest `melpa' version +of the packages. + +In case the major-mode that you are using for " + (interactive) + (let ((start-plain (make-temp-file "plain" nil ".el"))) + (url-copy-file "https://raw.githubusercontent.com/emacs-lsp/lsp-mode/master/scripts/lsp-start-plain.el" + start-plain t) + (async-shell-command + (format "%s -q -l %s %s" + (expand-file-name invocation-name invocation-directory) + start-plain + (or (buffer-file-name) "")) + (generate-new-buffer " *lsp-start-plain*")))) + + + +(provide 'lsp-mode) +;;; lsp-mode.el ends here diff --git a/emacs/elpa/lsp-mode-20241004.151/lsp-mode.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-mode.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-modeline.el b/emacs/elpa/lsp-mode-20241004.151/lsp-modeline.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-modeline.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-modeline.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-mojo.el b/emacs/elpa/lsp-mode-20241004.151/lsp-mojo.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-mojo.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-mojo.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-move.el b/emacs/elpa/lsp-mode-20241004.151/lsp-move.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-move.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-move.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-nginx.el b/emacs/elpa/lsp-mode-20241004.151/lsp-nginx.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-nginx.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-nginx.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-nim.el b/emacs/elpa/lsp-mode-20241004.151/lsp-nim.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-nim.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-nim.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-nix.el b/emacs/elpa/lsp-mode-20241004.151/lsp-nix.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-nix.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-nix.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-nushell.el b/emacs/elpa/lsp-mode-20241004.151/lsp-nushell.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-nushell.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-nushell.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-ocaml.el b/emacs/elpa/lsp-mode-20241004.151/lsp-ocaml.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-ocaml.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-ocaml.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-openscad.el b/emacs/elpa/lsp-mode-20241004.151/lsp-openscad.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-openscad.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-openscad.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-perl.el b/emacs/elpa/lsp-mode-20241004.151/lsp-perl.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-perl.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-perl.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-perlnavigator.el b/emacs/elpa/lsp-mode-20241004.151/lsp-perlnavigator.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-perlnavigator.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-perlnavigator.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-php.el b/emacs/elpa/lsp-mode-20241004.151/lsp-php.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-php.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-php.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-pls.el b/emacs/elpa/lsp-mode-20241004.151/lsp-pls.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-pls.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-pls.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-prolog.el b/emacs/elpa/lsp-mode-20241004.151/lsp-prolog.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-prolog.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-prolog.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-protocol.el b/emacs/elpa/lsp-mode-20241004.151/lsp-protocol.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-protocol.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-protocol.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-purescript.el b/emacs/elpa/lsp-mode-20241004.151/lsp-purescript.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-purescript.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-purescript.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-pwsh.el b/emacs/elpa/lsp-mode-20241004.151/lsp-pwsh.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-pwsh.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-pwsh.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-pyls.el b/emacs/elpa/lsp-mode-20241004.151/lsp-pyls.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-pyls.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-pyls.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-pylsp.el b/emacs/elpa/lsp-mode-20241004.151/lsp-pylsp.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-pylsp.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-pylsp.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-qml.el b/emacs/elpa/lsp-mode-20241004.151/lsp-qml.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-qml.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-qml.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-r.el b/emacs/elpa/lsp-mode-20241004.151/lsp-r.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-r.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-r.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-racket.el b/emacs/elpa/lsp-mode-20241004.151/lsp-racket.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-racket.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-racket.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-remark.el b/emacs/elpa/lsp-mode-20241004.151/lsp-remark.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-remark.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-remark.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-rf.el b/emacs/elpa/lsp-mode-20241004.151/lsp-rf.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-rf.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-rf.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-roslyn.el b/emacs/elpa/lsp-mode-20241004.151/lsp-roslyn.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-roslyn.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-roslyn.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-rpm-spec.el b/emacs/elpa/lsp-mode-20241004.151/lsp-rpm-spec.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-rpm-spec.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-rpm-spec.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-rubocop.el b/emacs/elpa/lsp-mode-20241004.151/lsp-rubocop.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-rubocop.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-rubocop.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-ruby-lsp.el b/emacs/elpa/lsp-mode-20241004.151/lsp-ruby-lsp.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-ruby-lsp.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-ruby-lsp.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-ruby-syntax-tree.el b/emacs/elpa/lsp-mode-20241004.151/lsp-ruby-syntax-tree.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-ruby-syntax-tree.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-ruby-syntax-tree.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-ruff.el b/emacs/elpa/lsp-mode-20241004.151/lsp-ruff.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-ruff.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-ruff.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-rust.el b/emacs/elpa/lsp-mode-20241004.151/lsp-rust.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-rust.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-rust.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-semantic-tokens.el b/emacs/elpa/lsp-mode-20241004.151/lsp-semantic-tokens.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-semantic-tokens.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-semantic-tokens.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-semgrep.el b/emacs/elpa/lsp-mode-20241004.151/lsp-semgrep.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-semgrep.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-semgrep.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-sml.el b/emacs/elpa/lsp-mode-20241004.151/lsp-sml.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-sml.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-sml.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-solargraph.el b/emacs/elpa/lsp-mode-20241004.151/lsp-solargraph.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-solargraph.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-solargraph.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-solidity.el b/emacs/elpa/lsp-mode-20241004.151/lsp-solidity.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-solidity.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-solidity.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-sorbet.el b/emacs/elpa/lsp-mode-20241004.151/lsp-sorbet.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-sorbet.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-sorbet.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-sql.el b/emacs/elpa/lsp-mode-20241004.151/lsp-sql.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-sql.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-sql.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-sqls.el b/emacs/elpa/lsp-mode-20241004.151/lsp-sqls.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-sqls.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-sqls.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-steep.el b/emacs/elpa/lsp-mode-20241004.151/lsp-steep.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-steep.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-steep.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-svelte.el b/emacs/elpa/lsp-mode-20241004.151/lsp-svelte.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-svelte.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-svelte.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-terraform.el b/emacs/elpa/lsp-mode-20241004.151/lsp-terraform.el diff --git a/emacs/elpa/lsp-mode-20241004.151/lsp-terraform.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-terraform.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-tex.el b/emacs/elpa/lsp-mode-20241004.151/lsp-tex.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-tex.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-tex.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-tilt.el b/emacs/elpa/lsp-mode-20241004.151/lsp-tilt.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-tilt.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-tilt.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-toml.el b/emacs/elpa/lsp-mode-20241004.151/lsp-toml.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-toml.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-toml.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-trunk.el b/emacs/elpa/lsp-mode-20241004.151/lsp-trunk.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-trunk.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-trunk.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-ttcn3.el b/emacs/elpa/lsp-mode-20241004.151/lsp-ttcn3.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-ttcn3.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-ttcn3.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-typeprof.el b/emacs/elpa/lsp-mode-20241004.151/lsp-typeprof.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-typeprof.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-typeprof.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-v.el b/emacs/elpa/lsp-mode-20241004.151/lsp-v.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-v.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-v.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-vala.el b/emacs/elpa/lsp-mode-20241004.151/lsp-vala.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-vala.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-vala.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-verilog.el b/emacs/elpa/lsp-mode-20241004.151/lsp-verilog.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-verilog.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-verilog.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-vetur.el b/emacs/elpa/lsp-mode-20241004.151/lsp-vetur.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-vetur.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-vetur.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-vhdl.el b/emacs/elpa/lsp-mode-20241004.151/lsp-vhdl.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-vhdl.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-vhdl.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-vimscript.el b/emacs/elpa/lsp-mode-20241004.151/lsp-vimscript.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-vimscript.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-vimscript.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-volar.el b/emacs/elpa/lsp-mode-20241004.151/lsp-volar.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-volar.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-volar.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-wgsl.el b/emacs/elpa/lsp-mode-20241004.151/lsp-wgsl.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-wgsl.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-wgsl.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-xml.el b/emacs/elpa/lsp-mode-20241004.151/lsp-xml.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-xml.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-xml.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-yaml.el b/emacs/elpa/lsp-mode-20241004.151/lsp-yaml.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-yaml.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-yaml.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-yang.el b/emacs/elpa/lsp-mode-20241004.151/lsp-yang.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp-yang.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-yang.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241004.151/lsp-zig.el b/emacs/elpa/lsp-mode-20241004.151/lsp-zig.el @@ -0,0 +1,301 @@ +;;; lsp-zig.el --- lsp-mode Zig integration -*- lexical-binding: t; -*- + +;; Copyright (C) 2021 Riccardo Binetti + +;; Author: Riccardo Binetti <rbino@gmx.com> +;; Keywords: languages,tools + +;; This program is free software; you can redistribute it and/or modify +;; it under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. + +;; This program is distributed in the hope that it will be useful, +;; but WITHOUT ANY WARRANTY; without even the implied warranty of +;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +;; GNU General Public License for more details. + +;; You should have received a copy of the GNU General Public License +;; along with this program. If not, see <https://www.gnu.org/licenses/>. + +;;; Commentary: + +;; client for zls, the Zig language server + +;;; Code: + +(require 'lsp-mode) + +(defgroup lsp-zig nil + "LSP support for Zig via zls." + :group 'lsp-mode + :link '(url-link "https://github.com/zigtools/zls")) + +(defcustom lsp-zig-zls-executable "zls" + "The zls executable to use. + +Leave as just the executable name to use the default behavior of finding the +executable with variable `exec-path'." + :group 'lsp-zig + :type 'string) + +(defcustom lsp-zig-trace-server "off" + "Traces the communication between Emacs and the language server." + :group 'lsp-zig + :type '(choice (const "off") + (const "messages") + (const "verbose"))) + +(defcustom lsp-zls-enable-snippets t + "Enables snippet completions when the client also supports them." + :group 'lsp-zig + :type 'boolean) + +(defcustom lsp-zig-enable-argument-placeholders t + "Whether to enable function argument placeholder completions." + :group 'lsp-zig + :type 'boolean) + +(defcustom lsp-zig-enable-build-on-save nil + "Whether to enable build-on-save diagnostics." + :group 'lsp-zig + :type 'boolean) + +(defcustom lsp-zig-build-on-save-step "install" + "Select which step should be executed on build-on-save." + :group 'lsp-zig + :type 'string) + +(defcustom lsp-zig-enable-autofix nil + "Whether to automatically fix errors on save. +Currently supports adding and removing discards." + :group 'lsp-zig + :type 'boolean) + +(defcustom lsp-zig-semantic-tokens "partial" + "Traces the communication between Emacs and the language server." + :group 'lsp-zig + :type '(choice (const "off") + (const "messages") + (const "verbose"))) + +(defcustom lsp-zig-enable-inlay-hints t + "Enables inlay hint support when the client also supports it." + :group 'lsp-zig + :type 'boolean) + +(defcustom lsp-zig-inlay-hints-show-variable-type-hints t + "Enable inlay hints for variable type." + :group 'lsp-zig + :type 'boolean) + +(defcustom lsp-zig-inlay-hints-show-parameter-name t + "Enable inlay hints for parameter names." + :group 'lsp-zig + :type 'boolean) + +(defcustom lsp-zig-inlay-hints-exclude-single-argument t + "Don't show inlay hints for single argument calls." + :group 'lsp-zig + :type 'boolean) + +(defcustom lsp-zig-inlay-hints-show-builtin t + "Don't show inlay hints for single argument calls." + :group 'lsp-zig + :type 'boolean) + +(defcustom lsp-zig-inlay-hints-hide-redundant-param-names nil + "Hides inlay hints when parameter name matches the identifier (e.g. foo: foo)." + :group 'lsp-zig + :type 'boolean) + +(defcustom lsp-zig-inlay-hints-hide-redundant-param-names-last-token nil + "Hides inlay hints when parameter name matches the last token of a parameter +node (e.g. foo: bar.foo, foo: &foo)." + :group 'lsp-zig + :type 'boolean) + +(defcustom lsp-zig-warn-style nil + "Enables warnings for style guideline mismatches." + :group 'lsp-zig + :type 'boolean) + +(defcustom lsp-zig-highlight-global-var-declarations nil + "Whether to highlight global var declarations." + :group 'lsp-zig + :type 'boolean) + +(defcustom lsp-zig-dangerous-comptime-experiments-do-not-enable nil + "When true, skips searching for references in std. +Improves lookup speed for functions in user's code. Renaming and +go-to-definition will continue to work as is." + :group 'lsp-zig + :type 'boolean) + +(defcustom lsp-zig-skip-std-references nil + "hen true, skips searching for references in std. +Improves lookup speed for functions in user's code. Renaming and + go-to-definition will continue to work as is." + :group 'lsp-zig + :type 'boolean) + +(defcustom lsp-zig-prefer-ast-check-as-child-process t + "Favor using `zig ast-check` instead of ZLS's fork." + :group 'lsp-zig + :type 'boolean) + +(defcustom lsp-zig-record-session nil + "When true, zls will record all request is receives and write in into +`record_session_path`, so that they can replayed with `zls replay`." + :group 'lsp-zig + :type 'boolean) + +(defcustom lsp-zig-record-session-path "" + "Output file path when `record_session` is set. +The recommended file extension *.zlsreplay." + :group 'lsp-zig + :type 'string) + +(defcustom lsp-zig-replay-session-path "" + "Used when calling `zls replay` for specifying the replay file. +If no extra argument is given `record_session_path` is used as the default path." + :group 'lsp-zig + :type 'string) + +(defcustom lsp-zig-builtin-path "" + "Path to `builtin'; useful for debugging, automatically set if let null." + :group 'lsp-zig + :type 'string) + +(defcustom lsp-zig-zig-lib-path "" + "Zig library path. +e.g. `/path/to/zig/lib/zig`, used to analyze std library imports." + :group 'lsp-zig + :type 'string) + +(defcustom lsp-zig-zig-exe-path "" + " Zig executable path. +e.g. /path/to/zig/zig, used to run the custom build runner. If null, zig is +looked up in PATH. Will be used to infer the zig standard library path if none +is provided." + :group 'lsp-zig + :type 'string) + +(defcustom lsp-zig-build-runner-path "" + "Path to the `build_runner.zig` file provided by zls. +null is equivalent to `${executable_directory}/build_runner.zig`." + :group 'lsp-zig + :type 'string) + +(defcustom lsp-zig-global-cache-path "" + "Path to a directory that will be used as zig's cache. +null is equivalent to `${KnownFolders.Cache}/zls`." + :group 'lsp-zig + :type 'string) + +(defcustom lsp-zig-build-runner-global-cache-path "" + "Path to a directory that will be used as the global cache path when executing +a projects build.zig. null is equivalent to the path shown by `zig env`." + :group 'lsp-zig + :type 'string) + +(defcustom lsp-zig-completions-with-replace nil + "Completions confirm behavior. +If `true', replace the text after the cursor." + :group 'lsp-zig + :type 'boolean) + +;; +;;; Installation + +(defcustom lsp-zig-server-store-path + (expand-file-name "zig/" lsp-server-install-dir) + "The path to the file in which zls will be stored." + :type 'file + :group 'lsp-zig) + +(defconst lsp-zig-download-url-format + "https://github.com/zigtools/zls/releases/latest/download/zls-%s-%s.%s" + "Format to the download url link.") + +(defun lsp-zig--zls-url () + "Return Url points to the zls' zip/tar file." + (let* ((x86 (string-prefix-p "x86_64" system-configuration)) + (arch (if x86 "x86_64" "aarch64"))) + (cl-case system-type + ((cygwin windows-nt ms-dos) + (format lsp-zig-download-url-format arch "windows" "zip")) + (darwin + (format lsp-zig-download-url-format arch "macos" "tar.gz")) + (gnu/linux + (format lsp-zig-download-url-format arch "linux" "tar.gz"))))) + +(defun lsp-zig--stored-zls-executable () + "Return the stored zls executable. + +This is differ from the variable `lsp-zig-zls-executable'; this is local storage +and not the global storage." + (f-join lsp-zig-server-store-path + (pcase system-type ('windows-nt "zls.exe") (_ "zls")))) + +(lsp-dependency + 'zls + '(:system "zls") + `(:download :url ,(lsp-zig--zls-url) + :decompress ,(pcase system-type ('windows-nt :zip) (_ :targz)) + :store-path ,(f-join lsp-zig-server-store-path "temp") + :set-executable? t) + `(:system ,(lsp-zig--stored-zls-executable))) + +;; +;;; Core + +(lsp-register-custom-settings + '(("zls.enable_snippets" lsp-zls-enable-snippets t) + ("zls.enable_argument_placeholders" lsp-zig-enable-argument-placeholders t) + ("zls.enable_build_on_save" lsp-zig-enable-build-on-save t) + ("zls.build_on_save_step" lsp-zig-build-on-save-step) + ("zls.enable_autofix" lsp-zig-enable-autofix t) + ("zls.semantic_tokens" lsp-zig-semantic-tokens) + ("zls.enable_inlay_hints" lsp-zig-enable-inlay-hints t) + ("zls.inlay_hints_show_variable_type_hints" lsp-zig-inlay-hints-show-variable-type-hints t) + ("zls.inlay_hints_show_parameter_name" lsp-zig-inlay-hints-show-parameter-name t) + ("zls.inlay_hints_show_builtin" lsp-zig-inlay-hints-show-builtin t) + ("zls.inlay_hints_exclude_single_argument" lsp-zig-inlay-hints-exclude-single-argument t) + ("zls.inlay_hints_hide_redundant_param_names" lsp-zig-inlay-hints-hide-redundant-param-names t) + ("zls.inlay_hints_hide_redundant_param_names_last_token" lsp-zig-inlay-hints-hide-redundant-param-names-last-token t) + ("zls.warn_style" lsp-zig-warn-style t) + ("zls.highlight_global_var_declarations" lsp-zig-highlight-global-var-declarations t) + ("zls.dangerous_comptime_experiments_do_not_enable" lsp-zig-dangerous-comptime-experiments-do-not-enable t) + ("zls.skip_std_references" lsp-zig-skip-std-references t) + ("zls.prefer_ast_check_as_child_process" lsp-zig-prefer-ast-check-as-child-process t) + ("zls.record_session" lsp-zig-record-session t) + ("zls.record_session_path" lsp-zig-record-session-path) + ("zls.replay_session_path" lsp-zig-replay-session-path) + ("zls.builtin_path" lsp-zig-builtin-path) + ("zls.zig_lib_path" lsp-zig-zig-lib-path) + ("zls.zig_exe_path" lsp-zig-zig-exe-path) + ("zls.build_runner_path" lsp-zig-build-runner-path) + ("zls.global_cache_path" lsp-zig-global-cache-path) + ("zls.build_runner_global_cache_path" lsp-zig-build-runner-global-cache-path) + ("zls.completion_label_details" lsp-zig-completions-with-replace t))) + +(lsp-register-client + (make-lsp-client + :new-connection (lsp-stdio-connection + (lambda () (or (executable-find lsp-zig-zls-executable) + (lsp-zig--stored-zls-executable))) + (lambda () + (or (executable-find lsp-zig-zls-executable) + (file-executable-p (lsp-zig--stored-zls-executable))))) + :activation-fn (lsp-activate-on "zig") + :priority -1 + :server-id 'zls + :download-server-fn + (lambda (_client callback error-callback _update?) + (lsp-package-ensure 'zls callback error-callback)))) + +(lsp-consistency-check lsp-zig) + +(provide 'lsp-zig) +;;; lsp-zig.el ends here diff --git a/emacs/elpa/lsp-mode-20241004.151/lsp-zig.elc b/emacs/elpa/lsp-mode-20241004.151/lsp-zig.elc Binary files differ. diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp.el b/emacs/elpa/lsp-mode-20241004.151/lsp.el diff --git a/emacs/elpa/lsp-mode-20241003.636/lsp.elc b/emacs/elpa/lsp-mode-20241004.151/lsp.elc Binary files differ. diff --git a/emacs/elpa/magit-20241004.917/AUTHORS.md b/emacs/elpa/magit-20241004.917/AUTHORS.md @@ -0,0 +1,417 @@ +The following people have contributed to Magit. +For statistics see https://magit.vc/stats/magit/authors.html. + +Authors +------- + +- Marius Vollmer +- Jonas Bernoulli + +Active Maintainers +------------------ + +- Jonas Bernoulli +- Kyle Meyer + +Former Maintainers +------------------ + +- Nicolas Dudebout +- Noam Postavsky +- Peter J. Weisberg +- Phil Jackson +- Rémi Vanicat +- Yann Hodique + +All Contributors +---------------- + +- Aaron Culich +- Aaron L. Zeng +- Aaron Madlon-Kay +- Abdo Roig-Maranges +- Adam Benanti +- Adam Jones +- Adam Kruszewski +- Adam Porter +- Adam Spiers +- Adeodato Simó +- Ævar Arnfjörð Bjarmason +- Alan Falloon +- Alban Gruin +- Aleksey Uimanov +- Alexander Gramiak +- Alexander Miller +- Alex Branham +- Alex Dunn +- Alexey Voinov +- Alex Kost +- Alex Kreisher +- Alex Ott +- Allen Li +- Andreas Fuchs +- Andreas Liljeqvist +- Andreas Rottmann +- Andrei Chițu +- Andrew Eggenberger +- Andrew Kirkpatrick +- Andrew Psaltis +- Andrew Schwartzmeyer +- Andrew Zipperer +- Andrey Smirnov +- Andriy Kmit' +- Andy Sawyer +- Angel de Vicente +- Aria Edmonds +- Arialdo Martini +- Arnau Roig Ninerola +- Ashlynn Anderson +- Barak A. Pearlmutter +- Bar Magal +- Bart Bakker +- Basil L. Contovounesios +- Bastian Beischer +- Bastian Beranek +- Benjamin Motz +- Ben North +- Ben Walton +- Ben Zanin +- Bob Uhl +- Boruch Baum +- Bradley Wright +- Brandon W Maister +- Brennan Vincent +- Brian Leung +- Brian Warner +- Bryan Shell +- Buster Copley +- Cameron Chaparro +- Carl Lieberman +- Chillar Anand +- Chris Bernard +- Chris Done +- Chris LaRose +- Chris Moore +- Chris Ring +- Chris Shoemaker +- Christian Dietrich +- Christian Kluge +- Christian Tietze +- Christophe Junke +- Christopher Carlile +- Christopher Monsanto +- Clément Pit-Claudel +- Cornelius Mika +- Craig Andera +- Daanturo +- Dale Hagglund +- Damien Cassou +- Dan Davison +- Dan Erikson +- Daniel Brockman +- Daniel Farina +- Daniel Fleischer +- Daniel Gröber +- Daniel Hackney +- Daniel Kraus +- Daniel Mai +- Daniel Martín +- Daniel Mendler +- Daniel Nagy +- Dan Kessler +- Dan LaManna +- Danny Zhu +- Dato Simó +- David Abrahams +- David Ellison +- David Hull +- David L. Rager +- David Wallin +- Dean Kariniemi +- Dennis Paskorz +- Divye Kapoor +- Dominique Quatravaux +- Duianto Vebotci +- Eli Barzilay +- Ellis Kenyo +- Eric +- Eric Davis +- Eric Prud'hommeaux +- Eric Schulte +- Erik Anderson +- Eugene Mikhaylov +- Evan Torrie +- Evgkeni Sampelnikof +- Eyal Lotem +- Eyal Soha +- Fabian Wiget +- Felix Geller +- Felix Yan +- Feng Li +- Florian Ragwitz +- Franklin Delehelle +- Frédéric Giquel +- Fritz Grabo +- Fritz Stelzer +- Geoff Shannon +- George Kadianakis +- Géza Herman +- Graham Clark +- Graham Dobbins +- Greg A. Woods +- Greg Lucas +- Gregory Heytings +- Greg Sexton +- Greg Steuck +- Guillaume Martres +- Hannu Koivisto +- Hans-Peter Deifel +- hokomo +- Hussein Ait-Lahcen +- Ian Eure +- Ian Milligan +- Ilya Grigoriev +- Ingmar Sittl +- Ingo Lohmar +- Ioan-Adrian Ratiu +- Ivan Brennan +- Jan Tatarik +- Jasper St. Pierre +- JD Smith +- Jean-Louis Giordano +- Jeff Bellegarde +- Jeff Dairiki +- Jeremy Meng +- Jeremy Sowden +- Jesse Alama +- Jim Blandy +- Joakim Jalap +- Johannes Altmanninger +- Johannes Maier +- Johann Klähn +- John Mastro +- John Morris +- John Wiegley +- Jonas Bernoulli +- Jonas Galvão Xavier +- Jonathan Arnett +- Jonathan del Strother +- Jonathan Leech-Pepin +- Jonathan Roes +- Jonathon McKitrick +- Jon Vanderwijk +- Jordan Galby +- Jordan Greenberg +- Jorge Israel Peña +- Josh Elsasser +- Josiah Schwab +- Julien Danjou +- Justin Burkett +- Justin Caratzas +- Justin Guenther +- Justin Thomas +- Kan-Ru Chen +- Kenny Ballou +- Keshav Kini +- Kevin Brubeck Unhammer +- Kevin J. Foley +- Kévin Le Gouguec +- Kimberly Wolk +- Knut Olav Bøhmer +- Kyle Meyer +- Laurent Laffont +- Laverne Schrock +- Leandro Facchinetti +- Lele Gaifax +- Lénaïc Huard +- Leo Liu +- Leonardo Etcheverry +- Leo Vivier +- Li Chen +- Lingchao Xin +- Lin Sun +- Li-Yun Chang +- Lluís Vilanova +- Loic Dachary +- Louis Roché +- Luís Oliveira +- Luke Amdor +- Magnar Sveen +- Magnus Malm +- Mak Kolybabi +- Manuel Vázquez Acosta +- Marcel Wolf +- Marc Herbert +- Marcin Bachry +- Marco Craveiro +- Marco Wahl +- Marc Sherry +- Marian Schubert +- Mario Rodas +- Marius Vollmer +- Mark Hepburn +- Mark Karpov +- Mark Oteiza +- Markus Beppler +- Martin Joerg +- Martin Polden +- Matt Beshara +- Matthew Fluet +- Matthew Kraai +- Matthieu Hauglustaine +- Matus Goljer +- Maxim Cournoyer +- Michael Fogleman +- Michael Griffiths +- Michael Heerdegen +- Michal Sojka +- Miciah Masters +- Miles Bader +- Miloš Mošić +- Mitchel Humpherys +- Moritz Bunkus +- Nacho Barrientos +- Naoya Yamashita +- Natalie Weizenbaum +- Nguyễn Tuấn Anh +- Nic Ferier +- Nicholas Vollmer +- Nick Alcock +- Nick Alexander +- Nick Dimiduk +- Nicklas Lindgren +- Nicolas Dudebout +- Nicolas Petton +- Nicolas Richard +- Nikolay Martynov +- Noam Postavsky +- N. Troy de Freitas +- Ola Nilsson +- Ole Arndt +- Oleh Krehel +- Orivej Desh +- Óscar Fuentes +- Pancho Horrillo +- Park Zhou +- Paul Pogonyshev +- Paul Stadig +- Pavel Holejsovsky +- Pekka Pessi +- Peter Eisentraut +- Peter Jaros +- Peter J. Weisberg +- Peter Vasil +- Philippe Cavalaria +- Philippe Vaucher +- Philipp Fehre +- Philipp Haselwarter +- Philipp Stephani +- Philip Weaver +- Phil Jackson +- Phil Sainty +- Pierre Neidhardt +- Pieter Praet +- Pieter van Oostrum +- Prathamesh Sonpatki +- Pratyush Yadav +- Pritam Baral +- rabio +- Radon Rosborough +- Rafael Laboissiere +- Rahul Rameshbabu +- Raimon Grau +- Ramkumar Ramachandra +- Remco van 't Veer +- Rémi Vanicat +- René Stadler +- Richard Kim +- Robert Boone +- Robert Irelan +- Robin Green +- Roey Darwish Dror +- Roger Crew +- Roland Marchand +- Romain Francoise +- Ron Parker +- Roy Crihfield +- Rüdiger Sonderfeld +- Russell Black +- Ryan C. Thompson +- Sam Cedarbaum +- Samuel Bronson +- Samuel W. Flint +- Sanjoy Das +- Sean Allred +- Sean Bryant +- Sean Farley +- Sean Whitton +- Sebastian Wiesner +- Sébastien Gross +- Seong-Kook Shin +- Sergey Pashinin +- Sergey Vinokurov +- Servilio Afre Puentes +- shoefone +- Shuguang Sun +- Siavash Askari Nasr +- Silent Sphere +- Simon Pintarelli +- Stefan Kangas +- Štěpán Němec +- Steven Chow +- Steven E. Harris +- Steven Thomas +- Steven Vancoillie +- Steve Purcell +- StrawberryTea +- Suhail Shergill +- Sylvain Rousseau +- Syohei Yoshida +- Szunti +- Takafumi Arakaki +- Tassilo Horn +- TEC +- Teemu Likonen +- Teruki Shigitani +- Thierry Volpiatto +- Thomas A Caswell +- Thomas Fini Hansen +- Thomas Frössman +- Thomas Jost +- Thomas Riccardi +- Tibor Simko +- Timo Juhani Lindfors +- Tim Perkins +- Tim Wraight +- Ting-Yu Lin +- Tom Feist +- Toon Claes +- Topi Miettinen +- Troy Hinckley +- Tsuyoshi Kitamoto +- Tunc Uzlu +- Ulrich Müller +- Vineet Naik +- Vitaly Ostashov +- Vladimir Ivanov +- Vladimir Panteleev +- Vladimir Sedach +- Waqar Hameed +- Wei Huang +- Wilfred Hughes +- Win Treese +- Wojciech Siewierski +- Wouter Bolsterlee +- Xavier Noria +- Xu Chunyang +- Yann Herklotz +- Yann Hodique +- Ynilu +- York Zhao +- Yuichi Higashi +- Yuri Khan +- Zach Latta +- zakora +- Zhu Zihao +- ziggy +- zilongshanren diff --git a/emacs/elpa/magit-20241004.917/LICENSE b/emacs/elpa/magit-20241004.917/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + <program> Copyright (C) <year> <name of author> + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +<https://www.gnu.org/licenses/>. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +<https://www.gnu.org/licenses/why-not-lgpl.html>. diff --git a/emacs/elpa/magit-20241004.917/dir b/emacs/elpa/magit-20241004.917/dir @@ -0,0 +1,18 @@ +This is the file .../info/dir, which contains the +topmost node of the Info hierarchy, called (dir)Top. +The first time you invoke Info you start off looking at this node. + +File: dir, Node: Top This is the top of the INFO tree + + This (the Directory node) gives a menu of major topics. + Typing "q" exits, "H" lists all Info commands, "d" returns here, + "h" gives a primer for first-timers, + "mEmacs<Return>" visits the Emacs manual, etc. + + In Emacs, you can click mouse button 2 on a menu item or cross reference + to select it. + +* Menu: + +Emacs +* Magit: (magit). Using Git from Emacs with Magit. diff --git a/emacs/elpa/magit-20241004.917/git-commit.el b/emacs/elpa/magit-20241004.917/git-commit.el @@ -0,0 +1,1222 @@ +;;; git-commit.el --- Edit Git commit messages -*- lexical-binding:t; coding:utf-8 -*- + +;; Copyright (C) 2008-2024 The Magit Project Contributors + +;; Author: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> +;; Sebastian Wiesner <lunaryorn@gmail.com> +;; Florian Ragwitz <rafl@debian.org> +;; Marius Vollmer <marius.vollmer@gmail.com> +;; Maintainer: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> + +;; SPDX-License-Identifier: GPL-3.0-or-later + +;; Magit is free software: you can redistribute it and/or modify +;; it under the terms of the GNU General Public License as published +;; by the Free Software Foundation, either version 3 of the License, +;; or (at your option) any later version. +;; +;; Magit is distributed in the hope that it will be useful, +;; but WITHOUT ANY WARRANTY; without even the implied warranty of +;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +;; GNU General Public License for more details. +;; +;; You should have received a copy of the GNU General Public License +;; along with Magit. If not, see <https://www.gnu.org/licenses/>. + +;; You should have received a copy of the AUTHORS.md file, which +;; lists all contributors. If not, see https://magit.vc/authors. + +;;; Commentary: + +;; This package assists the user in writing good Git commit messages. + +;; While Git allows for the message to be provided on the command +;; line, it is preferable to tell Git to create the commit without +;; actually passing it a message. Git then invokes the `$GIT_EDITOR' +;; (or if that is undefined `$EDITOR') asking the user to provide the +;; message by editing the file ".git/COMMIT_EDITMSG" (or another file +;; in that directory, e.g., ".git/MERGE_MSG" for merge commits). + +;; When `global-git-commit-mode' is enabled, which it is by default, +;; then opening such a file causes the features described below, to +;; be enabled in that buffer. Normally this would be done using a +;; major-mode but to allow the use of any major-mode, as the user sees +;; fit, it is done here by running a setup function, which among other +;; things turns on the preferred major-mode, by default `text-mode'. + +;; Git waits for the `$EDITOR' to finish and then either creates the +;; commit using the contents of the file as commit message, or, if the +;; editor process exited with a non-zero exit status, aborts without +;; creating a commit. Unfortunately Emacsclient (which is what Emacs +;; users should be using as `$EDITOR' or at least as `$GIT_EDITOR') +;; does not differentiate between "successfully" editing a file and +;; aborting; not out of the box that is. + +;; By making use of the `with-editor' package this package provides +;; both ways of finish an editing session. In either case the file +;; is saved, but Emacseditor's exit code differs. +;; +;; C-c C-c Finish the editing session successfully by returning +;; with exit code 0. Git then creates the commit using +;; the message it finds in the file. +;; +;; C-c C-k Aborts the edit editing session by returning with exit +;; code 1. Git then aborts the commit. + +;; Aborting the commit does not cause the message to be lost, but +;; relying solely on the file not being tampered with is risky. This +;; package additionally stores all aborted messages for the duration +;; of the current session (i.e., until you close Emacs). To get back +;; an aborted message use M-p and M-n while editing a message. +;; +;; M-p Replace the buffer contents with the previous message +;; from the message ring. Of course only after storing +;; the current content there too. +;; +;; M-n Replace the buffer contents with the next message from +;; the message ring, after storing the current content. + +;; Support for inserting Git trailers (as described in the manpage +;; git-interpret-trailers(1)) is available. +;; +;; C-c C-i Insert a trailer selected from a transient menu. + +;; When Git requests a commit message from the user, it does so by +;; having her edit a file which initially contains some comments, +;; instructing her what to do, and providing useful information, such +;; as which files were modified. These comments, even when left +;; intact by the user, do not become part of the commit message. This +;; package ensures these comments are propertizes as such and further +;; prettifies them by using different faces for various parts, such as +;; files. + +;; Finally this package highlights style errors, like lines that are +;; too long, or when the second line is not empty. It may even nag +;; you when you attempt to finish the commit without having fixed +;; these issues. The style checks and many other settings can easily +;; be configured: +;; +;; M-x customize-group RET git-commit RET + +;;; Code: + +(require 'magit-mode) + +(require 'log-edit) +(require 'ring) +(require 'server) +(require 'transient) +(require 'with-editor) + +(defvar diff-default-read-only) +(defvar flyspell-generic-check-word-predicate) +(defvar font-lock-beg) +(defvar font-lock-end) +(defvar recentf-exclude) + +(defvar git-commit-need-summary-line) + +(define-obsolete-variable-alias + 'git-commit-known-pseudo-headers + 'git-commit-trailers + "git-commit 4.0.0") + +;;; Options +;;;; Variables + +(defgroup git-commit nil + "Edit Git commit messages." + :prefix "git-commit-" + :link '(info-link "(magit)Editing Commit Messages") + :group 'tools) + +(define-minor-mode global-git-commit-mode + "Edit Git commit messages. + +This global mode arranges for `git-commit-setup' to be called +when a Git commit message file is opened. That usually happens +when Git uses the Emacsclient as $GIT_EDITOR to have the user +provide such a commit message. + +Loading the library `git-commit' by default enables this mode, +but the library is not automatically loaded because doing that +would pull in many dependencies and increase startup time too +much. You can either rely on `magit' loading this library or +you can load it explicitly. Autoloading is not an alternative +because in this case autoloading would immediately trigger +full loading." + :group 'git-commit + :type 'boolean + :global t + :init-value t + :initialize + (lambda (symbol exp) + (custom-initialize-default symbol exp) + (when global-git-commit-mode + (add-hook 'find-file-hook #'git-commit-setup-check-buffer) + (remove-hook 'after-change-major-mode-hook + #'git-commit-setup-font-lock-in-buffer))) + (cond + (global-git-commit-mode + (add-hook 'find-file-hook #'git-commit-setup-check-buffer) + (add-hook 'after-change-major-mode-hook + #'git-commit-setup-font-lock-in-buffer)) + (t + (remove-hook 'find-file-hook #'git-commit-setup-check-buffer) + (remove-hook 'after-change-major-mode-hook + #'git-commit-setup-font-lock-in-buffer)))) + +(defcustom git-commit-major-mode #'text-mode + "Major mode used to edit Git commit messages. + +The major mode configured here is turned on by the minor mode +`git-commit-mode'." + :group 'git-commit + :type '(choice (function-item text-mode) + (function-item markdown-mode) + (function-item org-mode) + (function-item fundamental-mode) + (function-item git-commit-elisp-text-mode) + (function :tag "Another mode") + (const :tag "No major mode"))) +;;;###autoload(put 'git-commit-major-mode 'safe-local-variable +;;;###autoload (lambda (val) +;;;###autoload (memq val '(text-mode +;;;###autoload markdown-mode +;;;###autoload org-mode +;;;###autoload fundamental-mode +;;;###autoload git-commit-elisp-text-mode)))) + +(defvaralias 'git-commit-mode-hook 'git-commit-setup-hook + "This variable is an alias for `git-commit-setup-hook' (which see). +Also note that `git-commit-mode' (which see) is not a major-mode.") + +(defcustom git-commit-setup-hook + '(git-commit-ensure-comment-gap + git-commit-save-message + git-commit-setup-changelog-support + git-commit-turn-on-auto-fill + git-commit-propertize-diff + bug-reference-mode) + "Hook run at the end of `git-commit-setup'." + :group 'git-commit + :type 'hook + :get #'magit-hook-custom-get + :options '(git-commit-ensure-comment-gap + git-commit-save-message + git-commit-setup-changelog-support + magit-generate-changelog + git-commit-turn-on-auto-fill + git-commit-turn-on-orglink + git-commit-turn-on-flyspell + git-commit-propertize-diff + bug-reference-mode)) + +(defcustom git-commit-post-finish-hook nil + "Hook run after the user finished writing a commit message. + +\\<with-editor-mode-map>\ +This hook is only run after pressing \\[with-editor-finish] in a buffer used +to edit a commit message. If a commit is created without the +user typing a message into a buffer, then this hook is not run. + +This hook is not run until the new commit has been created. If +that takes Git longer than `git-commit-post-finish-hook-timeout' +seconds, then this hook isn't run at all. For certain commands +such as `magit-rebase-continue' this hook is never run because +doing so would lead to a race condition. + +Also see `magit-post-commit-hook'." + :group 'git-commit + :type 'hook + :get #'magit-hook-custom-get) + +(defcustom git-commit-post-finish-hook-timeout 1 + "Time in seconds to wait for git to create a commit. + +The hook `git-commit-post-finish-hook' (which see) is run only +after git is done creating a commit. If it takes longer than +`git-commit-post-finish-hook-timeout' seconds to create the +commit, then the hook is not run at all." + :group 'git-commit + :safe 'numberp + :type 'number) + +(defcustom git-commit-finish-query-functions + '(git-commit-check-style-conventions) + "List of functions called to query before performing commit. + +The commit message buffer is current while the functions are +called. If any of them returns nil, then the commit is not +performed and the buffer is not killed. The user should then +fix the issue and try again. + +The functions are called with one argument. If it is non-nil, +then that indicates that the user used a prefix argument to +force finishing the session despite issues. Functions should +usually honor this wish and return non-nil." + :options '(git-commit-check-style-conventions) + :type 'hook + :group 'git-commit) + +(defcustom git-commit-style-convention-checks '(non-empty-second-line) + "List of checks performed by `git-commit-check-style-conventions'. + +Valid members are `non-empty-second-line' and `overlong-summary-line'. +That function is a member of `git-commit-finish-query-functions'." + :options '(non-empty-second-line overlong-summary-line) + :type '(list :convert-widget custom-hook-convert-widget) + :group 'git-commit) + +(defcustom git-commit-summary-max-length 68 + "Column beyond which characters in the summary lines are highlighted. + +The highlighting indicates that the summary is getting too long +by some standards. It does in no way imply that going over the +limit a few characters or in some cases even many characters is +anything that deserves shaming. It's just a friendly reminder +that if you can make the summary shorter, then you might want +to consider doing so." + :group 'git-commit + :safe 'numberp + :type 'number) + +(defcustom git-commit-trailers + '("Acked-by" + "Modified-by" + "Reviewed-by" + "Signed-off-by" + "Tested-by" + "Cc" + "Reported-by" + "Suggested-by" + "Co-authored-by" + "Co-developed-by") + "A list of Git trailers to be highlighted. + +See also manpage git-interpret-trailer(1). This package does +not use that Git command, but the initial description still +serves as a good introduction." + :group 'git-commit + :safe (lambda (val) (and (listp val) (seq-every-p #'stringp val))) + :type '(repeat string)) + +(defcustom git-commit-use-local-message-ring nil + "Whether to use a local message ring instead of the global one. + +This can be set globally, in which case every repository gets its +own commit message ring, or locally for a single repository." + :group 'git-commit + :safe 'booleanp + :type 'boolean) + +(defcustom git-commit-cd-to-toplevel nil + "Whether to set `default-directory' to the worktree in message buffer. + +Editing a commit message is done by visiting a file located in the git +directory, usually \"COMMIT_EDITMSG\". As is done when visiting any +file, the local value of `default-directory' is set to the directory +that contains the file. + +If this option is non-nil, then the local `default-directory' is changed +to the working tree from which the commit command was invoked. You may +wish to do that, to make it easier to open a file that is located in the +working tree, directly from the commit message buffer. + +If the git variable `safe.bareRepository' is set to \"explicit\", then +you have to enable this, to be able to commit at all. See issue #5100. + +This option only has an effect if the commit was initiated from Magit." + :group 'git-commit + :type 'boolean) + +;;;; Faces + +(defgroup git-commit-faces nil + "Faces used for highlighting Git commit messages." + :prefix "git-commit-" + :group 'git-commit + :group 'faces) + +(defface git-commit-summary + '((t :inherit font-lock-type-face)) + "Face used for the summary in commit messages." + :group 'git-commit-faces) + +(defface git-commit-overlong-summary + '((t :inherit font-lock-warning-face)) + "Face used for the tail of overlong commit message summaries." + :group 'git-commit-faces) + +(defface git-commit-nonempty-second-line + '((t :inherit font-lock-warning-face)) + "Face used for non-whitespace on the second line of commit messages." + :group 'git-commit-faces) + +(defface git-commit-keyword + '((t :inherit font-lock-string-face)) + "Face used for keywords in commit messages. +In this context a \"keyword\" is text surrounded by brackets." + :group 'git-commit-faces) + +(defface git-commit-trailer-token + '((t :inherit font-lock-keyword-face)) + "Face used for Git trailer tokens in commit messages." + :group 'git-commit-faces) + +(defface git-commit-trailer-value + '((t :inherit font-lock-string-face)) + "Face used for Git trailer values in commit messages." + :group 'git-commit-faces) + +(defface git-commit-comment-branch-local + '((t :inherit magit-branch-local)) + "Face used for names of local branches in commit message comments." + :group 'git-commit-faces) + +(defface git-commit-comment-branch-remote + '((t :inherit magit-branch-remote)) + "Face used for names of remote branches in commit message comments." + :group 'git-commit-faces) + +(defface git-commit-comment-detached + '((t :inherit git-commit-comment-branch-local)) + "Face used for detached `HEAD' in commit message comments." + :group 'git-commit-faces) + +(defface git-commit-comment-heading + '((t :inherit git-commit-trailer-token)) + "Face used for headings in commit message comments." + :group 'git-commit-faces) + +(defface git-commit-comment-file + '((t :inherit git-commit-trailer-value)) + "Face used for file names in commit message comments." + :group 'git-commit-faces) + +(defface git-commit-comment-action + '((t :inherit bold)) + "Face used for actions in commit message comments." + :group 'git-commit-faces) + +;;; Keymap + +(defvar-keymap git-commit-redundant-bindings + :doc "Bindings made redundant by `git-commit-insert-trailer'. +This keymap is used as the parent of `git-commit-mode-map', +to avoid upsetting muscle-memory. If you would rather avoid +the redundant bindings, then set this to nil, before loading +`git-commit'." + "C-c C-a" #'git-commit-ack + "C-c M-i" #'git-commit-suggested + "C-c C-m" #'git-commit-modified + "C-c C-o" #'git-commit-cc + "C-c C-p" #'git-commit-reported + "C-c C-r" #'git-commit-review + "C-c C-s" #'git-commit-signoff + "C-c C-t" #'git-commit-test) + +(defvar-keymap git-commit-mode-map + :doc "Keymap used by `git-commit-mode'." + :parent git-commit-redundant-bindings + "M-p" #'git-commit-prev-message + "M-n" #'git-commit-next-message + "C-c M-p" #'git-commit-search-message-backward + "C-c M-n" #'git-commit-search-message-forward + "C-c C-i" #'git-commit-insert-trailer + "C-c M-s" #'git-commit-save-message + "C-c C-d" 'magit-diff-while-committing + "C-c C-w" 'magit-pop-revision-stack) + +;;; Menu + +(require 'easymenu) +(easy-menu-define git-commit-mode-menu git-commit-mode-map + "Git Commit Mode Menu" + '("Commit" + ["Previous" git-commit-prev-message t] + ["Next" git-commit-next-message t] + "-" + ["Ack" git-commit-ack t + :help "Insert an 'Acked-by' trailer"] + ["Modified-by" git-commit-modified t + :help "Insert a 'Modified-by' trailer"] + ["Reviewed-by" git-commit-review t + :help "Insert a 'Reviewed-by' trailer"] + ["Sign-Off" git-commit-signoff t + :help "Insert a 'Signed-off-by' trailer"] + ["Tested-by" git-commit-test t + :help "Insert a 'Tested-by' trailer"] + "-" + ["CC" git-commit-cc t + :help "Insert a 'Cc' trailer"] + ["Reported" git-commit-reported t + :help "Insert a 'Reported-by' trailer"] + ["Suggested" git-commit-suggested t + :help "Insert a 'Suggested-by' trailer"] + ["Co-authored-by" git-commit-co-authored t + :help "Insert a 'Co-authored-by' trailer"] + ["Co-developed-by" git-commit-co-developed t + :help "Insert a 'Co-developed-by' trailer"] + "-" + ["Save" git-commit-save-message t] + ["Cancel" with-editor-cancel t] + ["Commit" with-editor-finish t])) + +;;; Hooks + +(defconst git-commit-filename-regexp "/\\(\ +\\(\\(COMMIT\\|NOTES\\|PULLREQ\\|MERGEREQ\\|TAG\\)_EDIT\\|MERGE_\\|\\)MSG\ +\\|\\(BRANCH\\|EDIT\\)_DESCRIPTION\\)\\'") + +(with-eval-after-load 'recentf + (add-to-list 'recentf-exclude git-commit-filename-regexp)) + +(add-to-list 'with-editor-file-name-history-exclude git-commit-filename-regexp) + +(defun git-commit-setup-font-lock-in-buffer () + (when (and buffer-file-name + (string-match-p git-commit-filename-regexp buffer-file-name)) + (git-commit-setup-font-lock))) + +(defun git-commit-setup-check-buffer () + (when (and buffer-file-name + (string-match-p git-commit-filename-regexp buffer-file-name)) + (git-commit-setup))) + +(defvar git-commit-mode) + +(defun git-commit-file-not-found () + ;; cygwin git will pass a cygwin path (/cygdrive/c/foo/.git/...), + ;; try to handle this in window-nt Emacs. + (when-let + ((file (and (or (string-match-p git-commit-filename-regexp + buffer-file-name) + (and (boundp 'git-rebase-filename-regexp) + (string-match-p git-rebase-filename-regexp + buffer-file-name))) + (not (file-accessible-directory-p + (file-name-directory buffer-file-name))) + (magit-expand-git-file-name (substring buffer-file-name 2))))) + (when (file-accessible-directory-p (file-name-directory file)) + (let ((inhibit-read-only t)) + (insert-file-contents file t) + t)))) + +(when (eq system-type 'windows-nt) + (add-hook 'find-file-not-found-functions #'git-commit-file-not-found)) + +(defconst git-commit-default-usage-message "\ +Type \\[with-editor-finish] to finish, \ +\\[with-editor-cancel] to cancel, and \ +\\[git-commit-prev-message] and \\[git-commit-next-message] \ +to recover older messages") + +(defvar git-commit-usage-message git-commit-default-usage-message + "Message displayed when editing a commit message. +When this is nil, then `with-editor-usage-message' is displayed +instead. One of these messages has to be displayed; otherwise +the user gets to see the message displayed by `server-execute'. +That message is misleading and because we cannot prevent it from +being displayed, we have to immediately show another message to +prevent the user from seeing it.") + +(defvar git-commit-header-line-format nil + "If non-nil, header line format used by `git-commit-mode'. +Used as the local value of `header-line-format', in buffer using +`git-commit-mode'. If it is a string, then it is passed through +`substitute-command-keys' first. A useful setting may be: + (setq git-commit-header-line-format git-commit-default-usage-message) + (setq git-commit-usage-message nil) ; show a shorter message") + +(defun git-commit-setup () + (let ((gitdir default-directory) + (cd (and git-commit-cd-to-toplevel + (or (car (rassoc default-directory magit--separated-gitdirs)) + (magit-toplevel))))) + ;; Pretend that git-commit-mode is a major-mode, + ;; so that directory-local settings can be used. + (let ((default-directory + (or (and (not (file-exists-p + (expand-file-name ".dir-locals.el" gitdir))) + ;; When $GIT_DIR/.dir-locals.el doesn't exist, + ;; fallback to $GIT_WORK_TREE/.dir-locals.el, + ;; because the maintainer can use the latter + ;; to enforce conventions, while s/he has no + ;; control over the former. + (or cd (magit-toplevel))) + gitdir))) + (let ((buffer-file-name nil) ; trick hack-dir-local-variables + (major-mode 'git-commit-mode)) ; trick dir-locals-collect-variables + (hack-dir-local-variables) + (hack-local-variables-apply))) + (when cd + (setq default-directory cd))) + (when git-commit-major-mode + (let ((auto-mode-alist + ;; `set-auto-mode--apply-alist' removes the remote part from + ;; the file-name before looking it up in `auto-mode-alist'. + ;; For our temporary entry to be found, we have to modify the + ;; file-name the same way. + (list (cons (concat "\\`" + (regexp-quote + (or (file-remote-p buffer-file-name 'localname) + buffer-file-name)) + "\\'") + git-commit-major-mode))) + ;; The major-mode hook might want to consult these minor + ;; modes, while the minor-mode hooks might want to consider + ;; the major mode. + (git-commit-mode t) + (with-editor-mode t)) + (normal-mode t))) + ;; Below we instead explicitly show a message. + (setq with-editor-show-usage nil) + (unless with-editor-mode + ;; Maybe already enabled when using `shell-command' or an Emacs shell. + (with-editor-mode 1)) + (add-hook 'with-editor-finish-query-functions + #'git-commit-finish-query-functions nil t) + (add-hook 'with-editor-pre-finish-hook #'git-commit-save-message nil t) + (add-hook 'with-editor-pre-cancel-hook #'git-commit-save-message nil t) + (when (fboundp 'magit-commit--reset-command) + (add-hook 'with-editor-post-finish-hook #'magit-commit--reset-command) + (add-hook 'with-editor-post-cancel-hook #'magit-commit--reset-command)) + (unless (memq last-command + '(magit-sequencer-continue + magit-sequencer-skip + magit-am-continue + magit-am-skip + magit-rebase-continue + magit-rebase-skip)) + (add-hook 'with-editor-post-finish-hook + (apply-partially #'git-commit-run-post-finish-hook + (magit-rev-parse "HEAD")) + nil t) + (when (fboundp 'magit-wip-maybe-add-commit-hook) + (magit-wip-maybe-add-commit-hook))) + (setq with-editor-cancel-message + #'git-commit-cancel-message) + (git-commit-setup-font-lock) + (git-commit-prepare-message-ring) + (when (boundp 'save-place) + (setq save-place nil)) + (let ((git-commit-mode-hook nil)) + (git-commit-mode 1)) + (with-demoted-errors "Error running git-commit-setup-hook: %S" + (run-hooks 'git-commit-setup-hook)) + (set-buffer-modified-p nil) + (when-let ((format git-commit-header-line-format)) + (setq header-line-format + (if (stringp format) (substitute-command-keys format) format))) + (when git-commit-usage-message + (setq with-editor-usage-message git-commit-usage-message)) + (with-editor-usage-message)) + +(defun git-commit-run-post-finish-hook (previous) + (when git-commit-post-finish-hook + (cl-block nil + (let ((break (time-add (current-time) + (seconds-to-time + git-commit-post-finish-hook-timeout)))) + (while (equal (magit-rev-parse "HEAD") previous) + (if (time-less-p (current-time) break) + (sit-for 0.01) + (message "No commit created after 1 second. Not running %s." + 'git-commit-post-finish-hook) + (cl-return)))) + (run-hooks 'git-commit-post-finish-hook)))) + +(define-minor-mode git-commit-mode + "Auxiliary minor mode used when editing Git commit messages. +This mode is only responsible for setting up some key bindings. +Don't use it directly; instead enable `global-git-commit-mode'. +Variable `git-commit-major-mode' controls which major-mode is +used." + :lighter "") + +(put 'git-commit-mode 'permanent-local t) + +(defun git-commit-ensure-comment-gap () + "Separate initial empty line from initial comment. +If the buffer begins with an empty line followed by a comment, insert +an additional newline in between, so that once the users start typing, +the input isn't tacked to the comment." + (save-excursion + (goto-char (point-min)) + (when (looking-at (format "\\`\n%s" comment-start)) + (open-line 1)))) + +(defun git-commit-setup-changelog-support () + "Treat ChangeLog entries as unindented paragraphs." + (when (fboundp 'log-indent-fill-entry) ; New in Emacs 27. + (setq-local fill-paragraph-function #'log-indent-fill-entry)) + (setq-local fill-indent-according-to-mode t) + (setq-local paragraph-start (concat paragraph-start "\\|\\*\\|("))) + +(defun git-commit-turn-on-auto-fill () + "Unconditionally turn on Auto Fill mode. +Ensure auto filling happens everywhere, except in the summary line." + (turn-on-auto-fill) + (setq-local comment-auto-fill-only-comments nil) + (when git-commit-need-summary-line + (setq-local auto-fill-function #'git-commit-auto-fill-except-summary))) + +(defun git-commit-auto-fill-except-summary () + (unless (eq (line-beginning-position) 1) + (do-auto-fill))) + +(defun git-commit-turn-on-orglink () + "Turn on Orglink mode if it is available. +If `git-commit-major-mode' is `org-mode', then silently forgo +turning on `orglink-mode'." + (when (and (not (derived-mode-p 'org-mode)) + (boundp 'orglink-match-anywhere) + (fboundp 'orglink-mode)) + (setq-local orglink-match-anywhere t) + (orglink-mode 1))) + +(defun git-commit-turn-on-flyspell () + "Unconditionally turn on Flyspell mode. +Also check text that is already in the buffer, while avoiding to check +most text that Git will strip from the final message, such as the last +comment and anything below the cut line (\"--- >8 ---\")." + (require 'flyspell) + (turn-on-flyspell) + (setq flyspell-generic-check-word-predicate + #'git-commit-flyspell-verify) + (let ((end nil) + ;; The "cut line" is defined in "git/wt-status.c". It appears + ;; in the commit message when `commit.verbose' is set to true. + (cut-line-regex (format "^%s -\\{8,\\} >8 -\\{8,\\}$" comment-start)) + (comment-start-regex (format "^\\(%s\\|$\\)" comment-start))) + (save-excursion + (goto-char (or (re-search-forward cut-line-regex nil t) + (point-max))) + (while (and (not (bobp)) (looking-at comment-start-regex)) + (forward-line -1)) + (unless (looking-at comment-start-regex) + (forward-line)) + (setq end (point))) + (flyspell-region (point-min) end))) + +(defun git-commit-flyspell-verify () + (not (= (char-after (line-beginning-position)) + (aref comment-start 0)))) + +(defun git-commit-finish-query-functions (force) + (run-hook-with-args-until-failure + 'git-commit-finish-query-functions force)) + +(defun git-commit-check-style-conventions (force) + "Check for violations of certain basic style conventions. + +For each violation ask the user if she wants to proceed anyway. +Option `git-commit-style-convention-checks' controls which +conventions are checked." + (or force + (save-excursion + (goto-char (point-min)) + (re-search-forward (git-commit-summary-regexp) nil t) + (if (equal (match-string 1) "") + t ; Just try; we don't know whether --allow-empty-message was used. + (and (or (not (memq 'overlong-summary-line + git-commit-style-convention-checks)) + (equal (match-string 2) "") + (y-or-n-p "Summary line is too long. Commit anyway? ")) + (or (not (memq 'non-empty-second-line + git-commit-style-convention-checks)) + (not (match-string 3)) + (y-or-n-p "Second line is not empty. Commit anyway? "))))))) + +(defun git-commit-cancel-message () + (message + (concat "Commit canceled" + (and (memq 'git-commit-save-message with-editor-pre-cancel-hook) + ". Message saved to `log-edit-comment-ring'")))) + +;;; History + +(defun git-commit-prev-message (arg) + "Cycle backward through message history, after saving current message. +With a numeric prefix ARG, go back ARG comments." + (interactive "*p") + (let ((len (ring-length log-edit-comment-ring))) + (if (<= len 0) + (progn (message "Empty comment ring") (ding)) + ;; Unlike `log-edit-previous-comment' we save the current + ;; non-empty and newly written comment, because otherwise + ;; it would be irreversibly lost. + (when-let ((message (git-commit-buffer-message))) + (unless (ring-member log-edit-comment-ring message) + (ring-insert log-edit-comment-ring message) + (cl-incf arg) + (setq len (ring-length log-edit-comment-ring)))) + ;; Delete the message but not the instructions at the end. + (save-restriction + (goto-char (point-min)) + (narrow-to-region + (point) + (if (re-search-forward (concat "^" comment-start) nil t) + (max 1 (- (point) 2)) + (point-max))) + (delete-region (point-min) (point))) + (setq log-edit-comment-ring-index (log-edit-new-comment-index arg len)) + (message "Comment %d" (1+ log-edit-comment-ring-index)) + (insert (ring-ref log-edit-comment-ring log-edit-comment-ring-index))))) + +(defun git-commit-next-message (arg) + "Cycle forward through message history, after saving current message. +With a numeric prefix ARG, go forward ARG comments." + (interactive "*p") + (git-commit-prev-message (- arg))) + +(defun git-commit-search-message-backward (string) + "Search backward through message history for a match for STRING. +Save current message first." + (interactive + (list (read-string (format-prompt "Comment substring" + log-edit-last-comment-match) + nil nil log-edit-last-comment-match))) + (cl-letf (((symbol-function #'log-edit-previous-comment) + (symbol-function #'git-commit-prev-message))) + (log-edit-comment-search-backward string))) + +(defun git-commit-search-message-forward (string) + "Search forward through message history for a match for STRING. +Save current message first." + (interactive + (list (read-string (format-prompt "Comment substring" + log-edit-last-comment-match) + nil nil log-edit-last-comment-match))) + (cl-letf (((symbol-function #'log-edit-previous-comment) + (symbol-function #'git-commit-prev-message))) + (log-edit-comment-search-forward string))) + +(defun git-commit-save-message () + "Save current message to `log-edit-comment-ring'." + (interactive) + (if-let ((message (git-commit-buffer-message))) + (progn + (when-let ((index (ring-member log-edit-comment-ring message))) + (ring-remove log-edit-comment-ring index)) + (ring-insert log-edit-comment-ring message) + (when git-commit-use-local-message-ring + (magit-repository-local-set 'log-edit-comment-ring + log-edit-comment-ring)) + (message "Message saved")) + (message "Only whitespace and/or comments; message not saved"))) + +(defun git-commit-prepare-message-ring () + (make-local-variable 'log-edit-comment-ring-index) + (when git-commit-use-local-message-ring + (setq-local log-edit-comment-ring + (magit-repository-local-get + 'log-edit-comment-ring + (make-ring log-edit-maximum-comment-ring-size))))) + +(defun git-commit-buffer-message () + (let ((flush (concat "^" comment-start)) + (str (buffer-substring-no-properties (point-min) (point-max)))) + (with-temp-buffer + (insert str) + (goto-char (point-min)) + (when (re-search-forward (concat flush " -+ >8 -+$") nil t) + (delete-region (line-beginning-position) (point-max))) + (goto-char (point-min)) + (flush-lines flush) + (goto-char (point-max)) + (unless (eq (char-before) ?\n) + (insert ?\n)) + (setq str (buffer-string))) + (and (not (string-match "\\`[ \t\n\r]*\\'" str)) + (progn + (when (string-match "\\`\n\\{2,\\}" str) + (setq str (replace-match "\n" t t str))) + (when (string-match "\n\\{2,\\}\\'" str) + (setq str (replace-match "\n" t t str))) + str)))) + +;;; Trailers + +(transient-define-prefix git-commit-insert-trailer () + "Insert a commit message trailer. + +See also manpage git-interpret-trailer(1). This command does +not use that Git command, but the initial description still +serves as a good introduction." + [[:description (lambda () + (cond (prefix-arg + "Insert ... by someone ") + ("Insert ... by yourself"))) + ("a" "Ack" git-commit-ack) + ("m" "Modified" git-commit-modified) + ("r" "Reviewed" git-commit-review) + ("s" "Signed-off" git-commit-signoff) + ("t" "Tested" git-commit-test)] + ["Insert ... by someone" + ("C-c" "Cc" git-commit-cc) + ("C-r" "Reported" git-commit-reported) + ("C-i" "Suggested" git-commit-suggested) + ("C-a" "Co-authored" git-commit-co-authored) + ("C-d" "Co-developed" git-commit-co-developed)]]) + +(defun git-commit-ack (name mail) + "Insert a trailer acknowledging that you have looked at the commit." + (interactive (git-commit-get-ident "Acked-by")) + (git-commit--insert-ident-trailer "Acked-by" name mail)) + +(defun git-commit-modified (name mail) + "Insert a trailer to signal that you have modified the commit." + (interactive (git-commit-get-ident "Modified-by")) + (git-commit--insert-ident-trailer "Modified-by" name mail)) + +(defun git-commit-review (name mail) + "Insert a trailer acknowledging that you have reviewed the commit. +With a prefix argument, prompt for another person who performed a +review." + (interactive (git-commit-get-ident "Reviewed-by")) + (git-commit--insert-ident-trailer "Reviewed-by" name mail)) + +(defun git-commit-signoff (name mail) + "Insert a trailer to sign off the commit. +With a prefix argument, prompt for another person who signed off." + (interactive (git-commit-get-ident "Signed-off-by")) + (git-commit--insert-ident-trailer "Signed-off-by" name mail)) + +(defun git-commit-test (name mail) + "Insert a trailer acknowledging that you have tested the commit. +With a prefix argument, prompt for another person who tested." + (interactive (git-commit-get-ident "Tested-by")) + (git-commit--insert-ident-trailer "Tested-by" name mail)) + +(defun git-commit-cc (name mail) + "Insert a trailer mentioning someone who might be interested." + (interactive (git-commit-read-ident "Cc")) + (git-commit--insert-ident-trailer "Cc" name mail)) + +(defun git-commit-reported (name mail) + "Insert a trailer mentioning the person who reported the issue." + (interactive (git-commit-read-ident "Reported-by")) + (git-commit--insert-ident-trailer "Reported-by" name mail)) + +(defun git-commit-suggested (name mail) + "Insert a trailer mentioning the person who suggested the change." + (interactive (git-commit-read-ident "Suggested-by")) + (git-commit--insert-ident-trailer "Suggested-by" name mail)) + +(defun git-commit-co-authored (name mail) + "Insert a trailer mentioning the person who co-authored the commit." + (interactive (git-commit-read-ident "Co-authored-by")) + (git-commit--insert-ident-trailer "Co-authored-by" name mail)) + +(defun git-commit-co-developed (name mail) + "Insert a trailer mentioning the person who co-developed the commit." + (interactive (git-commit-read-ident "Co-developed-by")) + (git-commit--insert-ident-trailer "Co-developed-by" name mail)) + +(defun git-commit-get-ident (&optional prompt) + "Return name and email of the user or read another name and email. +If PROMPT and `current-prefix-arg' are both non-nil, read name +and email using `git-commit-read-ident' (which see), otherwise +return name and email of the current user (you)." + (if (and prompt current-prefix-arg) + (git-commit-read-ident prompt) + (list (or (getenv "GIT_AUTHOR_NAME") + (getenv "GIT_COMMITTER_NAME") + (with-demoted-errors "Error running 'git config user.name': %S" + (magit-get "user.name")) + user-full-name + (read-string "Name: ")) + (or (getenv "GIT_AUTHOR_EMAIL") + (getenv "GIT_COMMITTER_EMAIL") + (getenv "EMAIL") + (with-demoted-errors "Error running 'git config user.email': %S" + (magit-get "user.email")) + (read-string "Email: "))))) + +(defalias 'git-commit-self-ident #'git-commit-get-ident) + +(defvar git-commit-read-ident-history nil) + +(defun git-commit-read-ident (prompt) + "Read a name and email, prompting with PROMPT, and return them. +Read them using a single prompt, offering past commit authors as +completion candidates. The input must have the form \"NAME <EMAIL>\"." + (let ((str (magit-completing-read + prompt + (sort (delete-dups + (magit-git-lines "log" "-n9999" "--format=%aN <%ae>")) + #'string<) + nil nil nil 'git-commit-read-ident-history))) + (save-match-data + (if (string-match "\\`\\([^<]+\\) *<\\([^>]+\\)>\\'" str) + (list (save-match-data (string-trim (match-string 1 str))) + (string-trim (match-string 2 str))) + (user-error "Invalid input"))))) + +(defun git-commit--insert-ident-trailer (trailer name email) + (git-commit--insert-trailer trailer (format "%s <%s>" name email))) + +(defun git-commit--insert-trailer (trailer value) + (save-excursion + (let ((string (format "%s: %s" trailer value)) + (leading-comment-end nil)) + ;; Make sure we skip forward past any leading comments. + (goto-char (point-min)) + (while (looking-at comment-start) + (forward-line)) + (setq leading-comment-end (point)) + (goto-char (point-max)) + (cond + ;; Look backwards for existing trailers. + ((re-search-backward (git-commit--trailer-regexp) nil t) + (end-of-line) + (insert ?\n string) + (unless (= (char-after) ?\n) + (insert ?\n))) + ;; Or place the new trailer right before the first non-leading + ;; comments. + (t + (while (re-search-backward (concat "^" comment-start) + leading-comment-end t)) + (unless (looking-back "\n\n" nil) + (insert ?\n)) + (insert string ?\n)))) + (unless (or (eobp) (= (char-after) ?\n)) + (insert ?\n)))) + +;;; Font-Lock + +(defvar-local git-commit-need-summary-line t + "Whether the text should have a heading that is separated from the body. + +For commit messages that is a convention that should not +be violated. For notes it is up to the user. If you do +not want to insist on an empty second line here, then use +something like: + + (add-hook \\='git-commit-setup-hook + (lambda () + (when (equal (file-name-nondirectory (buffer-file-name)) + \"NOTES_EDITMSG\") + (setq git-commit-need-summary-line nil))))") + +(defun git-commit--trailer-regexp () + (format + "^\\(?:\\(%s:\\)\\( .*\\)\\|\\([-a-zA-Z]+\\): \\([^<\n]+? <[^>\n]+>\\)\\)" + (regexp-opt git-commit-trailers))) + +(defun git-commit-summary-regexp () + (if git-commit-need-summary-line + (concat + ;; Leading empty lines and comments + (format "\\`\\(?:^\\(?:\\s-*\\|%s.*\\)\n\\)*" comment-start) + ;; Summary line + (format "\\(.\\{0,%d\\}\\)\\(.*\\)" git-commit-summary-max-length) + ;; Non-empty non-comment second line + (format "\\(?:\n%s\\|\n\\(.+\\)\\)?" comment-start)) + "\\(EASTER\\) \\(EGG\\)")) + +(defun git-commit-extend-region-summary-line () + "Identify the multiline summary-regexp construct. +Added to `font-lock-extend-region-functions'." + (save-excursion + (save-match-data + (goto-char (point-min)) + (when (looking-at (git-commit-summary-regexp)) + (let ((summary-beg (match-beginning 0)) + (summary-end (match-end 0))) + (when (or (< summary-beg font-lock-beg summary-end) + (< summary-beg font-lock-end summary-end)) + (setq font-lock-beg (min font-lock-beg summary-beg)) + (setq font-lock-end (max font-lock-end summary-end)))))))) + +(defvar-local git-commit--branch-name-regexp nil) + +(defconst git-commit-comment-headings + '("Changes to be committed:" + "Untracked files:" + "Changed but not updated:" + "Changes not staged for commit:" + "Unmerged paths:" + "Author:" + "Date:") + "Also fontified outside of comments in `git-commit-font-lock-keywords-2'.") + +(defconst git-commit-font-lock-keywords-1 + '(;; Trailers + (eval . `(,(git-commit--trailer-regexp) + (1 'git-commit-trailer-token) + (2 'git-commit-trailer-value) + (3 'git-commit-trailer-token) + (4 'git-commit-trailer-value))) + ;; Summary + (eval . `(,(git-commit-summary-regexp) + (1 'git-commit-summary))) + ;; - Keyword [aka "text in brackets"] (overrides summary) + ("\\[[^][]+?\\]" + (0 'git-commit-keyword t)) + ;; - Non-empty second line (overrides summary and note) + (eval . `(,(git-commit-summary-regexp) + (2 'git-commit-overlong-summary t t) + (3 'git-commit-nonempty-second-line t t))))) + +(defconst git-commit-font-lock-keywords-2 + `(,@git-commit-font-lock-keywords-1 + ;; Comments + (eval . `(,(format "^%s.*" comment-start) + (0 'font-lock-comment-face append))) + (eval . `(,(format "^%s On branch \\(.*\\)" comment-start) + (1 'git-commit-comment-branch-local t))) + (eval . `(,(format "^%s \\(HEAD\\) detached at" comment-start) + (1 'git-commit-comment-detached t))) + (eval . `(,(format "^%s %s" comment-start + (regexp-opt git-commit-comment-headings t)) + (1 'git-commit-comment-heading t))) + (eval . `(,(format "^%s\t\\(?:\\([^:\n]+\\):\\s-+\\)?\\(.*\\)" comment-start) + (1 'git-commit-comment-action t t) + (2 'git-commit-comment-file t))) + ;; "commit HASH" + (eval . '("^commit [[:alnum:]]+$" + (0 'git-commit-trailer-value))) + ;; `git-commit-comment-headings' (but not in commented lines) + (eval . `(,(format "\\(?:^%s[[:blank:]]+.+$\\)" + (regexp-opt git-commit-comment-headings)) + (0 'git-commit-trailer-value))))) + +(defconst git-commit-font-lock-keywords-3 + `(,@git-commit-font-lock-keywords-2 + ;; More comments + (eval + ;; Your branch is ahead of 'master' by 3 commits. + ;; Your branch is behind 'master' by 2 commits, and can be fast-forwarded. + . `(,(format + "^%s Your branch is \\(?:ahead\\|behind\\) of '%s' by \\([0-9]*\\)" + comment-start git-commit--branch-name-regexp) + (1 'git-commit-comment-branch-local t) + (2 'git-commit-comment-branch-remote t) + (3 'bold t))) + (eval + ;; Your branch is up to date with 'master'. + ;; Your branch and 'master' have diverged, + . `(,(format + "^%s Your branch \\(?:is up[- ]to[- ]date with\\|and\\) '%s'" + comment-start git-commit--branch-name-regexp) + (1 'git-commit-comment-branch-local t) + (2 'git-commit-comment-branch-remote t))) + (eval + ;; and have 1 and 2 different commits each, respectively. + . `(,(format + "^%s and have \\([0-9]*\\) and \\([0-9]*\\) commits each" + comment-start) + (1 'bold t) + (2 'bold t))))) + +(defvar git-commit-font-lock-keywords git-commit-font-lock-keywords-3 + "Font-Lock keywords for Git-Commit mode.") + +(defun git-commit-setup-font-lock () + (with-demoted-errors "Error running git-commit-setup-font-lock: %S" + (let ((table (make-syntax-table (syntax-table)))) + (when comment-start + (modify-syntax-entry (string-to-char comment-start) "." table)) + (modify-syntax-entry ?# "." table) + (modify-syntax-entry ?\" "." table) + (modify-syntax-entry ?\' "." table) + (modify-syntax-entry ?` "." table) + (set-syntax-table table)) + (setq-local comment-start (or (magit-get "core.commentchar") "#")) + (setq-local comment-start-skip (format "^%s+[\s\t]*" comment-start)) + (setq-local comment-end "") + (setq-local comment-end-skip "\n") + (setq-local comment-use-syntax nil) + (when (and (derived-mode-p 'markdown-mode) + (fboundp 'markdown-fill-paragraph)) + (setq-local fill-paragraph-function + (lambda (&optional justify) + (and (not (= (char-after (line-beginning-position)) + (aref comment-start 0))) + (markdown-fill-paragraph justify))))) + (setq-local git-commit--branch-name-regexp + ;; When using cygwin git, we may end up in a + ;; non-existing directory, which would cause + ;; any git calls to signal an error. + (if (file-accessible-directory-p default-directory) + ;; Font-Lock wants every submatch to succeed, so + ;; also match the empty string. Avoid listing + ;; remote branches and using `regexp-quote', + ;; because in repositories that have thousands of + ;; branches that would be very slow. See #4353. + (format "\\(\\(?:%s\\)\\|\\)\\([^']+\\)" + (string-join (magit-list-local-branch-names) "\\|")) + "\\([^']*\\)")) + (setq-local font-lock-multiline t) + (add-hook 'font-lock-extend-region-functions + #'git-commit-extend-region-summary-line + t t) + (font-lock-add-keywords nil git-commit-font-lock-keywords))) + +(defun git-commit-propertize-diff () + (require 'diff-mode) + (save-excursion + (goto-char (point-min)) + (when (re-search-forward "^diff --git" nil t) + (beginning-of-line) + (let ((buffer (current-buffer))) + (insert + (with-temp-buffer + (insert + (with-current-buffer buffer + (prog1 (buffer-substring-no-properties (point) (point-max)) + (delete-region (point) (point-max))))) + (let ((diff-default-read-only nil)) + (diff-mode)) + (let ((font-lock-verbose nil) + (font-lock-support-mode nil)) + (font-lock-ensure)) + (let ((pos (point-min))) + (while-let ((next (next-single-property-change pos 'face))) + (put-text-property pos next 'font-lock-face + (get-text-property pos 'face)) + (setq pos next)) + (put-text-property pos (point-max) 'font-lock-face + (get-text-property pos 'face))) + (buffer-string))))))) + +;;; Elisp Text Mode + +(define-derived-mode git-commit-elisp-text-mode text-mode "ElText" + "Major mode for editing commit messages of elisp projects. +This is intended for use as `git-commit-major-mode' for projects +that expect `symbols' to look like this. I.e., like they look in +Elisp doc-strings, including this one. Unlike in doc-strings, +\"strings\" also look different than the other text." + (setq font-lock-defaults '(git-commit-elisp-text-mode-keywords))) + +(defvar git-commit-elisp-text-mode-keywords + `((,(concat "[`‘]\\(" lisp-mode-symbol-regexp "\\)['’]") + (1 font-lock-constant-face prepend)) + ("\"[^\"]*\"" (0 font-lock-string-face prepend)))) + +;;; _ + +(define-obsolete-function-alias + 'git-commit-insert-pseudo-header + 'git-commit-insert-trailer + "git-commit 4.0.0") +(define-obsolete-function-alias + 'git-commit-insert-header + 'git-commit--insert-ident-trailer + "git-commit 4.0.0") +(define-obsolete-face-alias + 'git-commit-pseudo-header + 'git-commit-trailer-value + "git-commit 4.0.0") +(define-obsolete-face-alias + 'git-commit-known-pseudo-header + 'git-commit-trailer-token + "git-commit 4.0.0") + +(provide 'git-commit) +;;; git-commit.el ends here diff --git a/emacs/elpa/magit-20241004.917/git-rebase.el b/emacs/elpa/magit-20241004.917/git-rebase.el @@ -0,0 +1,874 @@ +;;; git-rebase.el --- Edit Git rebase files -*- lexical-binding:t -*- + +;; Copyright (C) 2008-2024 The Magit Project Contributors + +;; Author: Phil Jackson <phil@shellarchive.co.uk> +;; Maintainer: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> + +;; SPDX-License-Identifier: GPL-3.0-or-later + +;; Magit is free software: you can redistribute it and/or modify it +;; under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. +;; +;; Magit is distributed in the hope that it will be useful, but WITHOUT +;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +;; or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public +;; License for more details. +;; +;; You should have received a copy of the GNU General Public License +;; along with Magit. If not, see <https://www.gnu.org/licenses/>. + +;;; Commentary: + +;; This package assists the user in editing the list of commits to be +;; rewritten during an interactive rebase. + +;; When the user initiates an interactive rebase, e.g., using "r e" in +;; a Magit buffer or on the command line using "git rebase -i REV", +;; Git invokes the `$GIT_SEQUENCE_EDITOR' (or if that is undefined +;; `$GIT_EDITOR' or even `$EDITOR') letting the user rearrange, drop, +;; reword, edit, and squash commits. + +;; This package provides the major-mode `git-rebase-mode' which makes +;; doing so much more fun, by making the buffer more colorful and +;; providing the following commands: +;; +;; C-c C-c Tell Git to make it happen. +;; C-c C-k Tell Git that you changed your mind, i.e., abort. +;; +;; p Move point to previous line. +;; n Move point to next line. +;; +;; M-p Move the commit at point up. +;; M-n Move the commit at point down. +;; +;; k Drop the commit at point. +;; c Don't drop the commit at point. +;; r Change the message of the commit at point. +;; e Edit the commit at point. +;; s Squash the commit at point, into the one above. +;; f Like "s" but don't also edit the commit message. +;; b Break for editing at this point in the sequence. +;; x Add a script to be run with the commit at point +;; being checked out. +;; z Add noop action at point. +;; +;; SPC Show the commit at point in another buffer. +;; RET Show the commit at point in another buffer and +;; select its window. +;; C-/ Undo last change. +;; +;; Commands for --rebase-merges: +;; l Associate label with current HEAD in sequence. +;; MM Merge specified revisions into HEAD. +;; Mt Toggle whether the merge will invoke an editor +;; before committing. +;; t Reset HEAD to the specified label. + +;; You should probably also read the `git-rebase' manpage. + +;;; Code: + +(require 'magit) + +(require 'easymenu) +(require 'server) +(require 'with-editor) + +(defvar recentf-exclude) + +;;; Options +;;;; Variables + +(defgroup git-rebase nil + "Edit Git rebase sequences." + :link '(info-link "(magit)Editing Rebase Sequences") + :group 'tools) + +(defcustom git-rebase-auto-advance t + "Whether to move to next line after changing a line." + :group 'git-rebase + :type 'boolean) + +(defcustom git-rebase-show-instructions t + "Whether to show usage instructions inside the rebase buffer." + :group 'git-rebase + :type 'boolean) + +(defcustom git-rebase-confirm-cancel t + "Whether confirmation is required to cancel." + :group 'git-rebase + :type 'boolean) + +;;;; Faces + +(defgroup git-rebase-faces nil + "Faces used by Git-Rebase mode." + :group 'faces + :group 'git-rebase) + +(defface git-rebase-hash '((t :inherit magit-hash)) + "Face for commit hashes." + :group 'git-rebase-faces) + +(defface git-rebase-label '((t :inherit magit-refname)) + "Face for labels in label, merge, and reset lines." + :group 'git-rebase-faces) + +(defface git-rebase-description '((t nil)) + "Face for commit descriptions." + :group 'git-rebase-faces) + +(defface git-rebase-action + '((t :inherit font-lock-keyword-face)) + "Face for action keywords." + :group 'git-rebase-faces) + +(defface git-rebase-killed-action + '((t :inherit font-lock-comment-face :strike-through t)) + "Face for commented commit action lines." + :group 'git-rebase-faces) + +(defface git-rebase-comment-hash + '((t :inherit git-rebase-hash :weight bold)) + "Face for commit hashes in commit message comments." + :group 'git-rebase-faces) + +(defface git-rebase-comment-heading + '((t :inherit font-lock-keyword-face)) + "Face for headings in rebase message comments." + :group 'git-rebase-faces) + +;;; Keymaps + +(defvar-keymap git-rebase-mode-map + :doc "Keymap for Git-Rebase mode." + :parent special-mode-map + "C-m" #'git-rebase-show-commit + "p" #'git-rebase-backward-line + "n" #'forward-line + "M-p" #'git-rebase-move-line-up + "M-n" #'git-rebase-move-line-down + "c" #'git-rebase-pick + "k" #'git-rebase-kill-line + "C-k" #'git-rebase-kill-line + "b" #'git-rebase-break + "e" #'git-rebase-edit + "l" #'git-rebase-label + "M M" #'git-rebase-merge + "M t" #'git-rebase-merge-toggle-editmsg + "m" #'git-rebase-edit + "f" #'git-rebase-fixup + "q" #'undefined + "r" #'git-rebase-reword + "w" #'git-rebase-reword + "s" #'git-rebase-squash + "t" #'git-rebase-reset + "u" #'git-rebase-update-ref + "x" #'git-rebase-exec + "y" #'git-rebase-insert + "z" #'git-rebase-noop + "SPC" #'git-rebase-show-or-scroll-up + "DEL" #'git-rebase-show-or-scroll-down + "C-x C-t" #'git-rebase-move-line-up + "M-<up>" #'git-rebase-move-line-up + "M-<down>" #'git-rebase-move-line-down + "<remap> <undo>" #'git-rebase-undo) +(put 'git-rebase-reword :advertised-binding (kbd "r")) +(put 'git-rebase-move-line-up :advertised-binding (kbd "M-p")) +(put 'git-rebase-kill-line :advertised-binding (kbd "k")) + +(easy-menu-define git-rebase-mode-menu git-rebase-mode-map + "Git-Rebase mode menu" + '("Rebase" + ["Pick" git-rebase-pick t] + ["Reword" git-rebase-reword t] + ["Edit" git-rebase-edit t] + ["Squash" git-rebase-squash t] + ["Fixup" git-rebase-fixup t] + ["Kill" git-rebase-kill-line t] + ["Noop" git-rebase-noop t] + ["Execute" git-rebase-exec t] + ["Move Down" git-rebase-move-line-down t] + ["Move Up" git-rebase-move-line-up t] + "---" + ["Cancel" with-editor-cancel t] + ["Finish" with-editor-finish t])) + +(defvar git-rebase-command-descriptions + '((with-editor-finish . "tell Git to make it happen") + (with-editor-cancel . "tell Git that you changed your mind, i.e., abort") + (git-rebase-backward-line . "move point to previous line") + (forward-line . "move point to next line") + (git-rebase-move-line-up . "move the commit at point up") + (git-rebase-move-line-down . "move the commit at point down") + (git-rebase-show-or-scroll-up . "show the commit at point in another buffer") + (git-rebase-show-commit + . "show the commit at point in another buffer and select its window") + (undo . "undo last change") + (git-rebase-kill-line . "drop the commit at point") + (git-rebase-insert . "insert a line for an arbitrary commit") + (git-rebase-noop . "add noop action at point"))) + +;;; Commands + +(defun git-rebase-pick () + "Use commit on current line. +If the region is active, act on all lines touched by the region." + (interactive) + (git-rebase-set-action "pick")) + +(defun git-rebase-reword () + "Edit message of commit on current line. +If the region is active, act on all lines touched by the region." + (interactive) + (git-rebase-set-action "reword")) + +(defun git-rebase-edit () + "Stop at the commit on the current line. +If the region is active, act on all lines touched by the region." + (interactive) + (git-rebase-set-action "edit")) + +(defun git-rebase-squash () + "Meld commit on current line into previous commit, edit message. +If the region is active, act on all lines touched by the region." + (interactive) + (git-rebase-set-action "squash")) + +(defun git-rebase-fixup () + "Meld commit on current line into previous commit, discard its message. +If the region is active, act on all lines touched by the region." + (interactive) + (git-rebase-set-action "fixup")) + +(defvar-local git-rebase-comment-re nil) + +(defvar git-rebase-short-options + '((?b . "break") + (?e . "edit") + (?f . "fixup") + (?l . "label") + (?m . "merge") + (?p . "pick") + (?r . "reword") + (?s . "squash") + (?t . "reset") + (?u . "update-ref") + (?x . "exec")) + "Alist mapping single key of an action to the full name.") + +(defclass git-rebase-action () + (;; action-type: commit, exec, bare, label, merge + (action-type :initarg :action-type :initform nil) + ;; Examples for each action type: + ;; | action | action options | target | trailer | + ;; |--------+----------------+---------+---------| + ;; | pick | | hash | subject | + ;; | exec | | command | | + ;; | noop | | | | + ;; | reset | | name | subject | + ;; | merge | -C hash | name | subject | + (action :initarg :action :initform nil) + (action-options :initarg :action-options :initform nil) + (target :initarg :target :initform nil) + (trailer :initarg :trailer :initform nil) + (comment-p :initarg :comment-p :initform nil))) + +(defvar git-rebase-line-regexps + `((commit . ,(concat + (regexp-opt '("e" "edit" + "f" "fixup" + "p" "pick" + "r" "reword" + "s" "squash") + "\\(?1:") + " \\(?3:[^ \n]+\\) ?\\(?4:.*\\)")) + (exec . "\\(?1:x\\|exec\\) \\(?3:.*\\)") + (bare . ,(concat (regexp-opt '("b" "break" "noop") "\\(?1:") + " *$")) + (label . ,(concat (regexp-opt '("l" "label" + "t" "reset" + "u" "update-ref") + "\\(?1:") + " \\(?3:[^ \n]+\\) ?\\(?4:.*\\)")) + (merge . ,(concat "\\(?1:m\\|merge\\) " + "\\(?:\\(?2:-[cC] [^ \n]+\\) \\)?" + "\\(?3:[^ \n]+\\)" + " ?\\(?4:.*\\)")))) + +;;;###autoload +(defun git-rebase-current-line () + "Parse current line into a `git-rebase-action' instance. +If the current line isn't recognized as a rebase line, an +instance with all nil values is returned." + (save-excursion + (goto-char (line-beginning-position)) + (if-let ((re-start (concat "^\\(?5:" (regexp-quote comment-start) + "\\)? *")) + (type (seq-some (lambda (arg) + (let ((case-fold-search nil)) + (and (looking-at (concat re-start (cdr arg))) + (car arg)))) + git-rebase-line-regexps))) + (git-rebase-action + :action-type type + :action (and-let* ((action (match-string-no-properties 1))) + (or (cdr (assoc action git-rebase-short-options)) + action)) + :action-options (match-string-no-properties 2) + :target (match-string-no-properties 3) + :trailer (match-string-no-properties 4) + :comment-p (and (match-string 5) t)) + ;; Use default empty class rather than nil to ease handling. + (git-rebase-action)))) + +(defun git-rebase-set-action (action) + "Set action of commit line to ACTION. +If the region is active, operate on all lines that it touches. +Otherwise, operate on the current line. As a special case, an +ACTION of nil comments the rebase line, regardless of its action +type." + (pcase (git-rebase-region-bounds t) + (`(,beg ,end) + (let ((end-marker (copy-marker end)) + (pt-below-p (and mark-active (< (mark) (point))))) + (set-marker-insertion-type end-marker t) + (goto-char beg) + (while (< (point) end-marker) + (with-slots (action-type target trailer comment-p) + (git-rebase-current-line) + (cond + ((and action (eq action-type 'commit)) + (let ((inhibit-read-only t)) + (magit-delete-line) + (insert (concat action " " target " " trailer "\n")))) + ((and action-type (not (or action comment-p))) + (let ((inhibit-read-only t)) + (insert comment-start " ")) + (forward-line)) + (t + ;; In the case of --rebase-merges, commit lines may have + ;; other lines with other action types, empty lines, and + ;; "Branch" comments interspersed. Move along. + (forward-line))))) + (goto-char + (if git-rebase-auto-advance + end-marker + (if pt-below-p (1- end-marker) beg))) + (goto-char (line-beginning-position)))) + (_ (ding)))) + +(defun git-rebase-line-p (&optional pos) + (save-excursion + (when pos (goto-char pos)) + (and (oref (git-rebase-current-line) action-type) + t))) + +(defun git-rebase-region-bounds (&optional fallback) + "Return region bounds if both ends touch rebase lines. +Each bound is extended to include the entire line touched by the +point or mark. If the region isn't active and FALLBACK is +non-nil, return the beginning and end of the current rebase line, +if any." + (cond + ((use-region-p) + (let ((beg (save-excursion (goto-char (region-beginning)) + (line-beginning-position))) + (end (save-excursion (goto-char (region-end)) + (line-end-position)))) + (when (and (git-rebase-line-p beg) + (git-rebase-line-p end)) + (list beg (1+ end))))) + ((and fallback (git-rebase-line-p)) + (list (line-beginning-position) + (1+ (line-end-position)))))) + +(defun git-rebase-move-line-down (n) + "Move the current commit (or command) N lines down. +If N is negative, move the commit up instead. With an active +region, move all the lines that the region touches, not just the +current line." + (interactive "p") + (pcase-let* ((`(,beg ,end) + (or (git-rebase-region-bounds) + (list (line-beginning-position) + (1+ (line-end-position))))) + (pt-offset (- (point) beg)) + (mark-offset (and mark-active (- (mark) beg)))) + (save-restriction + (narrow-to-region + (point-min) + (1- + (if git-rebase-show-instructions + (save-excursion + (goto-char (point-min)) + (while (or (git-rebase-line-p) + ;; The output for --rebase-merges has empty + ;; lines and "Branch" comments interspersed. + (looking-at-p "^$") + (looking-at-p (concat git-rebase-comment-re + " Branch"))) + (forward-line)) + (line-beginning-position)) + (point-max)))) + (if (or (and (< n 0) (= beg (point-min))) + (and (> n 0) (= end (point-max))) + (> end (point-max))) + (ding) + (goto-char (if (< n 0) beg end)) + (forward-line n) + (atomic-change-group + (let ((inhibit-read-only t)) + (insert (delete-and-extract-region beg end))) + (let ((new-beg (- (point) (- end beg)))) + (when (use-region-p) + (setq deactivate-mark nil) + (set-mark (+ new-beg mark-offset))) + (goto-char (+ new-beg pt-offset)))))))) + +(defun git-rebase-move-line-up (n) + "Move the current commit (or command) N lines up. +If N is negative, move the commit down instead. With an active +region, move all the lines that the region touches, not just the +current line." + (interactive "p") + (git-rebase-move-line-down (- n))) + +(defun git-rebase-highlight-region (start end window rol) + (let ((inhibit-read-only t) + (deactivate-mark nil) + (bounds (git-rebase-region-bounds))) + (mapc #'delete-overlay magit-section-highlight-overlays) + (when bounds + (magit-section-make-overlay (car bounds) (cadr bounds) + 'magit-section-heading-selection)) + (if (and bounds (not magit-section-keep-region-overlay)) + (funcall (default-value 'redisplay-unhighlight-region-function) rol) + (funcall (default-value 'redisplay-highlight-region-function) + start end window rol)))) + +(defun git-rebase-unhighlight-region (rol) + (mapc #'delete-overlay magit-section-highlight-overlays) + (funcall (default-value 'redisplay-unhighlight-region-function) rol)) + +(defun git-rebase-kill-line () + "Kill the current action line. +If the region is active, act on all lines touched by the region." + (interactive) + (git-rebase-set-action nil)) + +(defun git-rebase-insert (rev) + "Read an arbitrary commit and insert it below current line." + (interactive (list (magit-read-branch-or-commit "Insert revision"))) + (forward-line) + (if-let ((info (magit-rev-format "%h %s" rev))) + (let ((inhibit-read-only t)) + (insert "pick " info ?\n)) + (user-error "Unknown revision"))) + +(defun git-rebase-set-noncommit-action (action value-fn arg) + (goto-char (line-beginning-position)) + (pcase-let* ((inhibit-read-only t) + (`(,initial ,trailer ,comment-p) + (and (not arg) + (with-slots ((ln-action action) + target trailer comment-p) + (git-rebase-current-line) + (and (equal ln-action action) + (list target trailer comment-p))))) + (value (funcall value-fn initial))) + (pcase (list value initial comment-p) + (`("" nil ,_) + (ding)) + (`("" ,_ ,_) + (magit-delete-line)) + (_ + (if initial + (magit-delete-line) + (forward-line)) + (insert (concat action " " value + (and (equal value initial) + trailer + (concat " " trailer)) + "\n")) + (unless git-rebase-auto-advance + (forward-line -1)))))) + +(defun git-rebase-exec (arg) + "Insert a shell command to be run after the current commit. + +If there already is such a command on the current line, then edit +that instead. With a prefix argument insert a new command even +when there already is one on the current line. With empty input +remove the command on the current line, if any." + (interactive "P") + (git-rebase-set-noncommit-action + "exec" + (lambda (initial) (read-shell-command "Execute: " initial)) + arg)) + +(defun git-rebase-label (arg) + "Add a label after the current commit. +If there already is a label on the current line, then edit that +instead. With a prefix argument, insert a new label even when +there is already a label on the current line. With empty input, +remove the label on the current line, if any." + (interactive "P") + (git-rebase-set-noncommit-action + "label" + (lambda (initial) + (read-from-minibuffer + "Label: " initial magit-minibuffer-local-ns-map)) + arg)) + +(defun git-rebase-buffer-labels () + (let (labels) + (save-excursion + (goto-char (point-min)) + (while (re-search-forward "^\\(?:l\\|label\\) \\([^ \n]+\\)" nil t) + (push (match-string-no-properties 1) labels))) + (nreverse labels))) + +(defun git-rebase-reset (arg) + "Reset the current HEAD to a label. +If there already is a reset command on the current line, then +edit that instead. With a prefix argument, insert a new reset +line even when point is already on a reset line. With empty +input, remove the reset command on the current line, if any." + (interactive "P") + (git-rebase-set-noncommit-action + "reset" + (lambda (initial) + (or (magit-completing-read "Label" (git-rebase-buffer-labels) + nil t initial) + "")) + arg)) + +(defun git-rebase-update-ref (arg) + "Insert an update-ref action after the current line. +If there is already an update-ref action on the current line, +then edit that instead. With a prefix argument, insert a new +action even when there is already one on the current line. With +empty input, remove the action on the current line, if any." + (interactive "P") + (git-rebase-set-noncommit-action + "update-ref" + (lambda (initial) + (or (magit-completing-read "Ref" (magit-list-refs) nil nil initial) + "")) + arg)) + +(defun git-rebase-merge (arg) + "Add a merge command after the current commit. +If there is already a merge command on the current line, then +replace that command instead. With a prefix argument, insert a +new merge command even when there is already one on the current +line. With empty input, remove the merge command on the current +line, if any." + (interactive "P") + (git-rebase-set-noncommit-action + "merge" + (lambda (_) + (or (magit-completing-read "Merge" (git-rebase-buffer-labels)) + "")) + arg)) + +(defun git-rebase-merge-toggle-editmsg () + "Toggle whether an editor is invoked when performing the merge at point. +When a merge command uses a lower-case -c, the message for the +specified commit will be opened in an editor before creating the +commit. For an upper-case -C, the message will be used as is." + (interactive) + (with-slots (action-type target action-options trailer) + (git-rebase-current-line) + (if (eq action-type 'merge) + (let ((inhibit-read-only t)) + (magit-delete-line) + (insert + (format "merge %s %s %s\n" + (replace-regexp-in-string + "-[cC]" (lambda (c) + (if (equal c "-c") "-C" "-c")) + action-options t t) + target + trailer))) + (ding)))) + +(defun git-rebase-set-bare-action (action arg) + (goto-char (line-beginning-position)) + (with-slots ((ln-action action) comment-p) + (git-rebase-current-line) + (let ((same-action-p (equal action ln-action)) + (inhibit-read-only t)) + (when (or arg + (not ln-action) + (not same-action-p) + (and same-action-p comment-p)) + (unless (or arg (not same-action-p)) + (magit-delete-line)) + (insert action ?\n) + (unless git-rebase-auto-advance + (forward-line -1)))))) + +(defun git-rebase-noop (&optional arg) + "Add noop action at point. + +If the current line already contains a noop action, leave it +unchanged. If there is a commented noop action present, remove +the comment. Otherwise add a new noop action. With a prefix +argument insert a new noop action regardless of what is already +present on the current line. + +A noop action can be used to make git perform a rebase even if +no commits are selected. Without the noop action present, git +would see an empty file and therefore do nothing." + (interactive "P") + (git-rebase-set-bare-action "noop" arg)) + +(defun git-rebase-break (&optional arg) + "Add break action at point. + +If there is a commented break action present, remove the comment. +If the current line already contains a break action, add another +break action only if a prefix argument is given. + +A break action can be used to interrupt the rebase at the +specified point. It is particularly useful for pausing before +the first commit in the sequence. For other cases, the +equivalent behavior can be achieved with `git-rebase-edit'." + (interactive "P") + (git-rebase-set-bare-action "break" arg)) + +(defun git-rebase-undo (&optional arg) + "Undo some previous changes. +Like `undo' but works in read-only buffers." + (interactive "P") + (let ((inhibit-read-only t)) + (undo arg))) + +(defun git-rebase--show-commit (&optional scroll) + (let ((magit--disable-save-buffers t)) + (save-excursion + (goto-char (line-beginning-position)) + (if-let ((rev (with-slots (action-type target) + (git-rebase-current-line) + (and (eq action-type 'commit) + target)))) + (pcase scroll + ('up (magit-diff-show-or-scroll-up)) + ('down (magit-diff-show-or-scroll-down)) + (_ (apply #'magit-show-commit rev + (magit-diff-arguments 'magit-revision-mode)))) + (ding))))) + +(defun git-rebase-show-commit () + "Show the commit on the current line if any." + (interactive) + (git-rebase--show-commit)) + +(defun git-rebase-show-or-scroll-up () + "Update the commit buffer for commit on current line. + +Either show the commit at point in the appropriate buffer, or if +that buffer is already being displayed in the current frame and +contains information about that commit, then instead scroll the +buffer up." + (interactive) + (git-rebase--show-commit 'up)) + +(defun git-rebase-show-or-scroll-down () + "Update the commit buffer for commit on current line. + +Either show the commit at point in the appropriate buffer, or if +that buffer is already being displayed in the current frame and +contains information about that commit, then instead scroll the +buffer down." + (interactive) + (git-rebase--show-commit 'down)) + +(defun git-rebase-backward-line (&optional n) + "Move N lines backward (forward if N is negative). +Like `forward-line' but go into the opposite direction." + (interactive "p") + (forward-line (- (or n 1)))) + +;;; Mode + +;;;###autoload +(define-derived-mode git-rebase-mode special-mode "Git Rebase" + "Major mode for editing of a Git rebase file. + +Rebase files are generated when you run \"git rebase -i\" or run +`magit-interactive-rebase'. They describe how Git should perform +the rebase. See the documentation for git-rebase (e.g., by +running \"man git-rebase\" at the command line) for details." + :interactive nil + :group 'git-rebase + (setq comment-start (or (magit-get "core.commentChar") "#")) + (setq git-rebase-comment-re (concat "^" (regexp-quote comment-start))) + (setq font-lock-defaults (list (git-rebase-mode-font-lock-keywords) t t)) + (unless git-rebase-show-instructions + (let ((inhibit-read-only t)) + (flush-lines git-rebase-comment-re))) + (unless with-editor-mode + ;; Maybe already enabled when using `shell-command' or an Emacs shell. + (with-editor-mode 1)) + (when git-rebase-confirm-cancel + (add-hook 'with-editor-cancel-query-functions + #'git-rebase-cancel-confirm nil t)) + (setq-local redisplay-highlight-region-function + #'git-rebase-highlight-region) + (setq-local redisplay-unhighlight-region-function + #'git-rebase-unhighlight-region) + (add-hook 'with-editor-pre-cancel-hook #'git-rebase-autostash-save nil t) + (add-hook 'with-editor-post-cancel-hook #'git-rebase-autostash-apply nil t) + (setq imenu-prev-index-position-function + #'magit-imenu--rebase-prev-index-position-function) + (setq imenu-extract-index-name-function + #'magit-imenu--rebase-extract-index-name-function) + (when (boundp 'save-place) + (setq save-place nil))) + +(defun git-rebase-cancel-confirm (force) + (or (not (buffer-modified-p)) + force + (magit-confirm 'abort-rebase "Abort this rebase" nil 'noabort))) + +(defun git-rebase-autostash-save () + (when-let ((rev (magit-file-line + (expand-file-name "rebase-merge/autostash" (magit-gitdir))))) + (push (cons 'stash rev) with-editor-cancel-alist))) + +(defun git-rebase-autostash-apply () + (when-let ((rev (cdr (assq 'stash with-editor-cancel-alist)))) + (magit-stash-apply rev))) + +(defun git-rebase-match-comment-line (limit) + (re-search-forward (concat git-rebase-comment-re ".*") limit t)) + +(defun git-rebase-mode-font-lock-keywords () + "Font lock keywords for Git-Rebase mode." + `((,(concat "^" (cdr (assq 'commit git-rebase-line-regexps))) + (1 'git-rebase-action) + (3 'git-rebase-hash) + (4 'git-rebase-description)) + (,(concat "^" (cdr (assq 'exec git-rebase-line-regexps))) + (1 'git-rebase-action) + (3 'git-rebase-description)) + (,(concat "^" (cdr (assq 'bare git-rebase-line-regexps))) + (1 'git-rebase-action)) + (,(concat "^" (cdr (assq 'label git-rebase-line-regexps))) + (1 'git-rebase-action) + (3 'git-rebase-label) + (4 'font-lock-comment-face)) + ("^\\(m\\(?:erge\\)?\\) -[Cc] \\([^ \n]+\\) \\([^ \n]+\\)\\( #.*\\)?" + (1 'git-rebase-action) + (2 'git-rebase-hash) + (3 'git-rebase-label) + (4 'font-lock-comment-face)) + ("^\\(m\\(?:erge\\)?\\) \\([^ \n]+\\)" + (1 'git-rebase-action) + (2 'git-rebase-label)) + (,(concat git-rebase-comment-re " *" + (cdr (assq 'commit git-rebase-line-regexps))) + 0 'git-rebase-killed-action t) + (git-rebase-match-comment-line 0 'font-lock-comment-face) + ("\\[[^[]*\\]" + 0 'magit-keyword t) + ("\\(?:fixup!\\|squash!\\)" + 0 'magit-keyword-squash t) + (,(format "^%s Rebase \\([^ ]*\\) onto \\([^ ]*\\)" comment-start) + (1 'git-rebase-comment-hash t) + (2 'git-rebase-comment-hash t)) + (,(format "^%s \\(Commands:\\)" comment-start) + (1 'git-rebase-comment-heading t)) + (,(format "^%s Branch \\(.*\\)" comment-start) + (1 'git-rebase-label t)))) + +(defun git-rebase-mode-show-keybindings () + "Modify the \"Commands:\" section of the comment Git generates +at the bottom of the file so that in place of the one-letter +abbreviation for the command, it shows the command's keybinding. +By default, this is the same except for the \"pick\" command." + (let ((inhibit-read-only t)) + (save-excursion + (goto-char (point-min)) + (when (and git-rebase-show-instructions + (re-search-forward + (concat git-rebase-comment-re "\\s-+p, pick") + nil t)) + (goto-char (line-beginning-position)) + (pcase-dolist (`(,cmd . ,desc) git-rebase-command-descriptions) + (insert (format (propertize "%s %s %s\n" + 'font-lock-face 'font-lock-comment-face) + comment-start + (string-pad + (substitute-command-keys (format "\\[%s]" cmd)) 8) + desc))) + (while (re-search-forward + (concat git-rebase-comment-re "\\(?:" + "\\( \\.? *\\)\\|" + "\\( +\\)\\([^\n,],\\) \\([^\n ]+\\) \\)") + nil t) + (if (match-string 1) + (replace-match (make-string 10 ?\s) t t nil 1) + (let ((cmd (intern (concat "git-rebase-" (match-string 4))))) + (if (not (fboundp cmd)) + (delete-region (line-beginning-position) + (1+ (line-end-position))) + (add-text-properties (line-beginning-position) + (1+ (line-end-position)) + '(font-lock-face font-lock-comment-face)) + (replace-match " " t t nil 2) + (replace-match + (string-pad + (save-match-data + (substitute-command-keys (format "\\[%s]" cmd))) + 8) + t t nil 3))))))))) + +(add-hook 'git-rebase-mode-hook #'git-rebase-mode-show-keybindings t) + +(defun git-rebase-mode-disable-before-save-hook () + (setq-local before-save-hook nil)) + +(add-hook 'git-rebase-mode-hook #'git-rebase-mode-disable-before-save-hook) + +;;;###autoload +(defconst git-rebase-filename-regexp "/git-rebase-todo\\'") +;;;###autoload +(add-to-list 'auto-mode-alist + (cons git-rebase-filename-regexp #'git-rebase-mode)) + +(add-to-list 'with-editor-server-window-alist + (cons git-rebase-filename-regexp #'switch-to-buffer)) + +(with-eval-after-load 'recentf + (add-to-list 'recentf-exclude git-rebase-filename-regexp)) + +(add-to-list 'with-editor-file-name-history-exclude git-rebase-filename-regexp) + +;;; Imenu Support + +(defun magit-imenu--rebase-prev-index-position-function () + "Move point to previous commit in git-rebase buffer. +Used as a value for `imenu-prev-index-position-function'." + (catch 'found + (while (not (bobp)) + (git-rebase-backward-line) + (when (git-rebase-line-p) + (throw 'found t))))) + +(defun magit-imenu--rebase-extract-index-name-function () + "Return imenu name for line at point. +Point should be at the beginning of the line. This function +is used as a value for `imenu-extract-index-name-function'." + (buffer-substring-no-properties (line-beginning-position) + (line-end-position))) + +;;; _ +(provide 'git-rebase) +;;; git-rebase.el ends here diff --git a/emacs/elpa/magit-20241004.917/magit-apply.el b/emacs/elpa/magit-20241004.917/magit-apply.el @@ -0,0 +1,855 @@ +;;; magit-apply.el --- Apply Git diffs -*- lexical-binding:t -*- + +;; Copyright (C) 2008-2024 The Magit Project Contributors + +;; Author: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> +;; Maintainer: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> + +;; SPDX-License-Identifier: GPL-3.0-or-later + +;; Magit is free software: you can redistribute it and/or modify it +;; under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. +;; +;; Magit is distributed in the hope that it will be useful, but WITHOUT +;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +;; or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public +;; License for more details. +;; +;; You should have received a copy of the GNU General Public License +;; along with Magit. If not, see <https://www.gnu.org/licenses/>. + +;;; Commentary: + +;; This library implements commands for applying Git diffs or parts +;; of such a diff. The supported "apply variants" are apply, stage, +;; unstage, discard, and reverse - more than Git itself knows about, +;; at least at the porcelain level. + +;;; Code: + +(require 'magit-core) +(require 'magit-diff) +(require 'magit-wip) + +(require 'transient) ; See #3732. + +;; For `magit-apply' +(declare-function magit-am "magit-sequence" () t) +(declare-function magit-patch-apply "magit-patch" () t) +;; For `magit-discard-files' +(declare-function magit-checkout-stage "magit-merge" (file arg)) +(declare-function magit-checkout-read-stage "magit-merge" (file)) +(defvar auto-revert-verbose) +;; For `magit-stage-untracked' +(declare-function magit-submodule-add-1 "magit-submodule" + (url &optional path name args)) +(declare-function magit-submodule-read-name-for-path "magit-submodule" + (path &optional prefer-short)) +(defvar borg-user-emacs-directory) + +;;; Options + +(defcustom magit-delete-by-moving-to-trash t + "Whether Magit uses the system's trash can. + +You should absolutely not disable this and also remove `discard' +from `magit-no-confirm'. You shouldn't do that even if you have +all of the Magit-Wip modes enabled, because those modes do not +track any files that are not tracked in the proper branch." + :package-version '(magit . "2.1.0") + :group 'magit-essentials + :type 'boolean) + +(defcustom magit-unstage-committed t + "Whether unstaging a committed change reverts it instead. + +A committed change cannot be unstaged, because staging and +unstaging are actions that are concerned with the differences +between the index and the working tree, not with committed +changes. + +If this option is non-nil (the default), then typing \"u\" +\(`magit-unstage') on a committed change, causes it to be +reversed in the index but not the working tree. For more +information see command `magit-reverse-in-index'." + :package-version '(magit . "2.4.1") + :group 'magit-commands + :type 'boolean) + +(defcustom magit-reverse-atomically nil + "Whether to reverse changes atomically. + +If some changes can be reversed while others cannot, then nothing +is reversed if the value of this option is non-nil. But when it +is nil, then the changes that can be reversed are reversed and +for the other changes diff files are created that contain the +rejected reversals." + :package-version '(magit . "2.7.0") + :group 'magit-commands + :type 'boolean) + +(defcustom magit-post-stage-hook nil + "Hook run after staging changes. +This hook is run by `magit-refresh' if `this-command' +is a member of `magit-post-stage-hook-commands'." + :package-version '(magit . "2.90.0") + :group 'magit-commands + :type 'hook) + +(defcustom magit-post-unstage-hook nil + "Hook run after unstaging changes. +This hook is run by `magit-refresh' if `this-command' +is a member of `magit-post-unstage-hook-commands'." + :package-version '(magit . "2.90.0") + :group 'magit-commands + :type 'hook) + +;;; Commands +;;;; Apply + +(defun magit-apply (&rest args) + "Apply the change at point to the working tree. +With a prefix argument fallback to a 3-way merge. Doing +so causes the change to be applied to the index as well." + (interactive (and current-prefix-arg (list "--3way"))) + (when-let ((s (magit-apply--get-selection))) + (pcase (list (magit-diff-type) (magit-diff-scope)) + (`(,(or 'unstaged 'staged) ,_) + (user-error "Change is already in the working tree")) + (`(untracked ,(or 'file 'files)) + (call-interactively #'magit-am)) + (`(,_ region) (magit-apply-region s args)) + (`(,_ hunk) (magit-apply-hunk s args)) + (`(,_ hunks) (magit-apply-hunks s args)) + (`(rebase-sequence file) + (call-interactively #'magit-patch-apply)) + (`(,_ file) (magit-apply-diff s args)) + (`(,_ files) (magit-apply-diffs s args))))) + +(defun magit-apply--section-content (section) + (buffer-substring-no-properties (if (magit-hunk-section-p section) + (oref section start) + (oref section content)) + (oref section end))) + +(defun magit-apply-diffs (sections &rest args) + (setq sections (magit-apply--get-diffs sections)) + (magit-apply-patch sections args + (mapconcat + (lambda (s) + (concat (magit-diff-file-header s) + (magit-apply--section-content s))) + sections ""))) + +(defun magit-apply-diff (section &rest args) + (setq section (car (magit-apply--get-diffs (list section)))) + (magit-apply-patch section args + (concat (magit-diff-file-header section) + (magit-apply--section-content section)))) + +(defun magit-apply--adjust-hunk-new-starts (hunks) + "Adjust new line numbers in headers of HUNKS for partial application. +HUNKS should be a list of ordered, contiguous hunks to be applied +from a file. For example, if there is a sequence of hunks with +the headers + + @@ -2,6 +2,7 @@ + @@ -10,6 +11,7 @@ + @@ -18,6 +20,7 @@ + +and only the second and third are to be applied, they would be +adjusted as \"@@ -10,6 +10,7 @@\" and \"@@ -18,6 +19,7 @@\"." + (let* ((first-hunk (car hunks)) + (offset (if (string-match diff-hunk-header-re-unified first-hunk) + (- (string-to-number (match-string 3 first-hunk)) + (string-to-number (match-string 1 first-hunk))) + (error "Header hunks have to be applied individually")))) + (if (= offset 0) + hunks + (mapcar (lambda (hunk) + (if (string-match diff-hunk-header-re-unified hunk) + (replace-match (number-to-string + (- (string-to-number (match-string 3 hunk)) + offset)) + t t hunk 3) + (error "Hunk does not have expected header"))) + hunks)))) + +(defun magit-apply--adjust-hunk-new-start (hunk) + (car (magit-apply--adjust-hunk-new-starts (list hunk)))) + +(defun magit-apply-hunks (hunks &rest args) + (let ((file (oref (car hunks) parent))) + (when (magit-diff--combined-p file) + (user-error "Cannot un-/stage resolution hunks. Stage the whole file")) + (magit-apply-patch + file args + (concat (oref file header) + (string-join (magit-apply--adjust-hunk-new-starts + (mapcar #'magit-apply--section-content hunks))))))) + +(defun magit-apply-hunk (hunk &rest args) + (let ((file (oref hunk parent))) + (when (magit-diff--combined-p file) + (user-error "Cannot un-/stage resolution hunks. Stage the whole file")) + (let* ((header (car (oref hunk value))) + (header (and (symbolp header) header)) + (content (magit-apply--section-content hunk))) + (magit-apply-patch + file args + (concat (magit-diff-file-header hunk (not (eq header 'rename))) + (if header + content + (magit-apply--adjust-hunk-new-start content))))))) + +(defun magit-apply-region (hunk &rest args) + (let ((file (oref hunk parent))) + (when (magit-diff--combined-p file) + (user-error "Cannot un-/stage resolution hunks. Stage the whole file")) + (magit-apply-patch + file args + (concat (magit-diff-file-header hunk) + (magit-apply--adjust-hunk-new-start + (magit-diff-hunk-region-patch hunk args)))))) + +(defun magit-apply-patch (section:s args patch) + (let* ((files (if (atom section:s) + (list (oref section:s value)) + (--map (oref it value) section:s))) + (command (symbol-name this-command)) + (command (if (and command (string-match "^magit-\\([^-]+\\)" command)) + (match-string 1 command) + "apply")) + (ignore-context (magit-diff-ignore-any-space-p))) + (unless (magit-diff-context-p) + (user-error "Not enough context to apply patch. Increase the context")) + (when (and magit-wip-before-change-mode (not magit-inhibit-refresh)) + (magit-wip-commit-before-change files (concat " before " command))) + (with-temp-buffer + (insert patch) + (magit-run-git-with-input + "apply" args "-p0" + (and ignore-context "-C0") + "--ignore-space-change" "-")) + (unless magit-inhibit-refresh + (when magit-wip-after-apply-mode + (magit-wip-commit-after-apply files (concat " after " command))) + (magit-refresh)))) + +(defun magit-apply--get-selection () + (or (magit-region-sections '(hunk file module) t) + (let ((section (magit-current-section))) + (pcase (oref section type) + ((or 'hunk 'file 'module) section) + ((or 'staged 'unstaged 'untracked + 'stashed-index 'stashed-worktree 'stashed-untracked) + (oref section children)) + (_ (user-error "Cannot apply this, it's not a change")))))) + +(defun magit-apply--get-diffs (sections) + (magit-section-case + ([file diffstat] + (--map (or (magit-get-section + (append `((file . ,(oref it value))) + (magit-section-ident magit-root-section))) + (error "Cannot get required diff headers")) + sections)) + (t sections))) + +(defun magit-apply--ignore-whitespace-p (selection type scope) + "Return t if it is necessary and possible to ignore whitespace. +It is necessary to do so when the diff ignores whitespace changes +and whole files are being applied. It is possible when no binary +files are involved. If it is both necessary and impossible, then +return nil, possibly causing whitespace changes to be applied." + (and (memq type '(unstaged staged)) + (memq scope '(file files list)) + (cl-find-if (lambda (arg) + (member arg '("--ignore-space-at-eol" + "--ignore-space-change" + "--ignore-all-space" + "--ignore-blank-lines"))) + magit-buffer-diff-args) + (not (cl-find-if (lambda (section) + (oref section binary)) + (ensure-list selection))))) + +;;;; Stage + +(defun magit-stage (&optional intent) + "Add the change at point to the staging area. +With a prefix argument, INTENT, and an untracked file (or files) +at point, stage the file but not its content." + (interactive "P") + (if-let ((s (and (derived-mode-p 'magit-mode) + (magit-apply--get-selection))) + (type (magit-diff-type)) + (scope (magit-diff-scope))) + (pcase (list type scope + (magit-apply--ignore-whitespace-p s type scope)) + (`(untracked ,_ ,_) (magit-stage-untracked intent)) + (`(unstaged region ,_) (magit-apply-region s "--cached")) + (`(unstaged hunk ,_) (magit-apply-hunk s "--cached")) + (`(unstaged hunks ,_) (magit-apply-hunks s "--cached")) + ('(unstaged file t) (magit-apply-diff s "--cached")) + ('(unstaged files t) (magit-apply-diffs s "--cached")) + ('(unstaged list t) (magit-apply-diffs s "--cached")) + ('(unstaged file nil) (magit-stage-1 "-u" (list (oref s value)))) + ('(unstaged files nil) (magit-stage-1 "-u" (magit-region-values nil t))) + ('(unstaged list nil) (magit-stage-modified)) + (`(staged ,_ ,_) (user-error "Already staged")) + (`(committed ,_ ,_) (user-error "Cannot stage committed changes")) + (`(undefined ,_ ,_) (user-error "Cannot stage this change"))) + (call-interactively #'magit-stage-file))) + +;;;###autoload +(defun magit-stage-buffer-file () + "Stage all changes to the file being visited in the current buffer." + (interactive) + (unless buffer-file-name + (user-error "Not visiting a file")) + (magit-with-toplevel + (magit-stage-1 (and (magit-file-ignored-p buffer-file-name) + (if (y-or-n-p "Visited file is ignored; stage anyway?") + "--force" + (user-error "Abort"))) + (list (magit-file-relative-name))))) + +;;;###autoload +(defun magit-stage-file (files &optional force) + "Read one or more files and stage all changes in those files. +With prefix argument FORCE, offer ignored files for completion." + (interactive + (let* ((choices (if current-prefix-arg + (magit-ignored-files) + (nconc (magit-unstaged-files) + (magit-untracked-files)))) + (default (or (magit-section-value-if 'file) + (magit-file-relative-name))) + (default (car (member default choices)))) + (list (magit-completing-read-multiple + (if current-prefix-arg "Stage ignored file,s: " "Stage file,s: ") + choices nil t nil nil default) + current-prefix-arg))) + (magit-with-toplevel + ;; For backward compatibility, and because of + ;; the function's name, don't require a list. + (magit-stage-1 (and force "--force") + (ensure-list files)))) + +;;;###autoload +(defun magit-stage-modified (&optional all) + "Stage all changes to files modified in the worktree. +Stage all new content of tracked files and remove tracked files +that no longer exist in the working tree from the index also. +With a prefix argument also stage previously untracked (but not +ignored) files." + (interactive "P") + (when (magit-anything-staged-p) + (magit-confirm 'stage-all-changes)) + (magit-with-toplevel + (magit-stage-1 (if all "--all" "-u") magit-buffer-diff-files))) + +(defun magit-stage-1 (arg &optional files) + (magit-wip-commit-before-change files " before stage") + (magit-run-git "add" arg (if files (cons "--" files) ".")) + (when magit-auto-revert-mode + (mapc #'magit-turn-on-auto-revert-mode-if-desired files)) + (magit-wip-commit-after-apply files " after stage")) + +(defun magit-stage-untracked (&optional intent) + (let* ((section (magit-current-section)) + (files (pcase (magit-diff-scope) + ('file (list (oref section value))) + ('files (magit-region-values nil t)) + ('list (magit-untracked-files)))) + plain repos) + (dolist (file files) + (if (and (not (file-symlink-p file)) + (magit-git-repo-p file t)) + (push file repos) + (push file plain))) + (magit-wip-commit-before-change files " before stage") + (when plain + (magit-run-git "add" (and intent "--intent-to-add") + "--" plain) + (when magit-auto-revert-mode + (mapc #'magit-turn-on-auto-revert-mode-if-desired plain))) + (dolist (repo repos) + (save-excursion + (goto-char (oref (magit-get-section + `((file . ,repo) (untracked) (status))) + start)) + (when (and (fboundp 'borg-assimilate) + (fboundp 'borg--maybe-absorb-gitdir) + (fboundp 'borg--sort-submodule-sections)) + (let* ((topdir (magit-toplevel)) + (url (let ((default-directory + (file-name-as-directory (expand-file-name repo)))) + (or (magit-get "remote" (magit-get-some-remote) "url") + (concat (file-name-as-directory ".") repo)))) + (package + (and (equal borg-user-emacs-directory topdir) + (file-name-nondirectory (directory-file-name repo))))) + (if (and package + (y-or-n-p (format "Also assimilate `%s' drone?" package))) + (borg-assimilate package url) + (magit-submodule-add-1 + url repo (magit-submodule-read-name-for-path repo package)) + (when package + (borg--sort-submodule-sections + (expand-file-name ".gitmodules" topdir)) + (let ((default-directory borg-user-emacs-directory)) + (borg--maybe-absorb-gitdir package)))))))) + (magit-wip-commit-after-apply files " after stage"))) + +(defvar magit-post-stage-hook-commands + '(magit-stage + magit-stage-buffer-file + magit-stage-file + magit-stage-modified)) + +(defun magit-run-post-stage-hook () + (when (memq this-command magit-post-stage-hook-commands) + (magit-run-hook-with-benchmark 'magit-post-stage-hook))) + +;;;; Unstage + +(defun magit-unstage () + "Remove the change at point from the staging area." + (interactive) + (when-let ((s (magit-apply--get-selection)) + (type (magit-diff-type)) + (scope (magit-diff-scope))) + (pcase (list type scope + (magit-apply--ignore-whitespace-p s type scope)) + (`(untracked ,_ ,_) (user-error "Cannot unstage untracked changes")) + (`(unstaged file ,_) (magit-unstage-intent (list (oref s value)))) + (`(unstaged files ,_) (magit-unstage-intent (magit-region-values nil t))) + (`(unstaged ,_ ,_) (user-error "Already unstaged")) + (`(staged region ,_) (magit-apply-region s "--reverse" "--cached")) + (`(staged hunk ,_) (magit-apply-hunk s "--reverse" "--cached")) + (`(staged hunks ,_) (magit-apply-hunks s "--reverse" "--cached")) + ('(staged file t) (magit-apply-diff s "--reverse" "--cached")) + ('(staged files t) (magit-apply-diffs s "--reverse" "--cached")) + ('(staged list t) (magit-apply-diffs s "--reverse" "--cached")) + ('(staged file nil) (magit-unstage-1 (list (oref s value)))) + ('(staged files nil) (magit-unstage-1 (magit-region-values nil t))) + ('(staged list nil) (magit-unstage-all)) + (`(committed ,_ ,_) (if magit-unstage-committed + (magit-reverse-in-index) + (user-error "Cannot unstage committed changes"))) + (`(undefined ,_ ,_) (user-error "Cannot unstage this change"))))) + +;;;###autoload +(defun magit-unstage-buffer-file () + "Unstage all changes to the file being visited in the current buffer." + (interactive) + (unless buffer-file-name + (user-error "Not visiting a file")) + (magit-with-toplevel + (magit-unstage-1 (list (magit-file-relative-name))))) + +;;;###autoload +(defun magit-unstage-file (files) + "Read one or more files and unstage all changes to those files." + (interactive + (let* ((choices (magit-staged-files)) + (default (or (magit-section-value-if 'file) + (magit-file-relative-name))) + (default (car (member default choices)))) + (list (magit-completing-read-multiple "Unstage file,s: " choices + nil t nil nil default)))) + (magit-with-toplevel + ;; For backward compatibility, and because of + ;; the function's name, don't require a list. + (magit-unstage-1 (ensure-list files)))) + +(defun magit-unstage-1 (files) + (magit-wip-commit-before-change files " before unstage") + (if (magit-no-commit-p) + (magit-run-git "rm" "--cached" "--" files) + (magit-run-git "reset" "HEAD" "--" files)) + (magit-wip-commit-after-apply files " after unstage")) + +(defun magit-unstage-intent (files) + (if-let ((staged (magit-staged-files)) + (intent (--filter (member it staged) files))) + (magit-unstage-1 intent) + (user-error "Already unstaged"))) + +;;;###autoload +(defun magit-unstage-all () + "Remove all changes from the staging area." + (interactive) + (unless (magit-anything-staged-p) + (user-error "Nothing to unstage")) + (when (or (magit-anything-unstaged-p) + (magit-untracked-files)) + (magit-confirm 'unstage-all-changes)) + (magit-wip-commit-before-change nil " before unstage") + (magit-run-git "reset" "HEAD" "--" magit-buffer-diff-files) + (magit-wip-commit-after-apply nil " after unstage")) + +(defvar magit-post-unstage-hook-commands + '(magit-unstage + magit-unstage-buffer-file + magit-unstage-file + magit-unstage-all)) + +(defun magit-run-post-unstage-hook () + (when (memq this-command magit-post-unstage-hook-commands) + (magit-run-hook-with-benchmark 'magit-post-unstage-hook))) + +;;;; Discard + +(defun magit-discard () + "Remove the change at point. + +On a hunk or file with unresolved conflicts prompt which side to +keep (while discarding the other). If point is within the text +of a side, then keep that side without prompting." + (interactive) + (when-let ((s (magit-apply--get-selection))) + (pcase (list (magit-diff-type) (magit-diff-scope)) + (`(committed ,_) (user-error "Cannot discard committed changes")) + (`(undefined ,_) (user-error "Cannot discard this change")) + (`(,_ region) (magit-discard-region s)) + (`(,_ hunk) (magit-discard-hunk s)) + (`(,_ hunks) (magit-discard-hunks s)) + (`(,_ file) (magit-discard-file s)) + (`(,_ files) (magit-discard-files s)) + (`(,_ list) (magit-discard-files s))))) + +(defun magit-discard-region (section) + (magit-confirm 'discard "Discard region") + (magit-discard-apply section 'magit-apply-region)) + +(defun magit-discard-hunk (section) + (magit-confirm 'discard "Discard hunk") + (let ((file (magit-section-parent-value section))) + (pcase (cddr (car (magit-file-status file))) + ('(?U ?U) (magit-smerge-keep-current)) + (_ (magit-discard-apply section #'magit-apply-hunk))))) + +(defun magit-discard-apply (section apply) + (if (eq (magit-diff-type section) 'unstaged) + (funcall apply section "--reverse") + (if (magit-anything-unstaged-p + nil (if (magit-file-section-p section) + (oref section value) + (magit-section-parent-value section))) + (progn (let ((magit-inhibit-refresh t)) + (funcall apply section "--reverse" "--cached") + (funcall apply section "--reverse" "--reject")) + (magit-refresh)) + (funcall apply section "--reverse" "--index")))) + +(defun magit-discard-hunks (sections) + (magit-confirm 'discard + (list "Discard %d hunks from %s" + (length sections) + (magit-section-parent-value (car sections)))) + (magit-discard-apply-n sections #'magit-apply-hunks)) + +(defun magit-discard-apply-n (sections apply) + (let ((section (car sections))) + (if (eq (magit-diff-type section) 'unstaged) + (funcall apply sections "--reverse") + (if (magit-anything-unstaged-p + nil (if (magit-file-section-p section) + (oref section value) + (magit-section-parent-value section))) + (progn (let ((magit-inhibit-refresh t)) + (funcall apply sections "--reverse" "--cached") + (funcall apply sections "--reverse" "--reject")) + (magit-refresh)) + (funcall apply sections "--reverse" "--index"))))) + +(defun magit-discard-file (section) + (magit-discard-files (list section))) + +(defun magit-discard-files (sections) + (let ((auto-revert-verbose nil) + (type (magit-diff-type (car sections))) + (status (magit-file-status)) + files delete resurrect rename discard discard-new resolve) + (dolist (section sections) + (let ((file (oref section value))) + (push file files) + (pcase (cons (pcase type + (`staged ?X) + (`unstaged ?Y) + (`untracked ?Z)) + (cddr (assoc file status))) + ('(?Z) (dolist (f (magit-untracked-files nil file)) + (push f delete))) + ((or '(?Z ?? ??) '(?Z ?! ?!)) (push file delete)) + ('(?Z ?D ? ) (push file delete)) + (`(,_ ?D ?D) (push file resolve)) + ((or `(,_ ?U ,_) `(,_ ,_ ?U)) (push file resolve)) + (`(,_ ?A ?A) (push file resolve)) + (`(?X ?M ,(or ? ?M ?D)) (push section discard)) + (`(?Y ,_ ?M ) (push section discard)) + ('(?X ?A ?M ) (push file discard-new)) + ('(?X ?C ?M ) (push file discard-new)) + (`(?X ?A ,(or ? ?D)) (push file delete)) + (`(?X ?C ,(or ? ?D)) (push file delete)) + (`(?X ?D ,(or ? ?M )) (push file resurrect)) + (`(?Y ,_ ?D ) (push file resurrect)) + (`(?X ?R ,(or ? ?M ?D)) (push file rename))))) + (unwind-protect + (let ((magit-inhibit-refresh t)) + (magit-wip-commit-before-change files " before discard") + (when resolve + (magit-discard-files--resolve (nreverse resolve))) + (when resurrect + (magit-discard-files--resurrect (nreverse resurrect))) + (when delete + (magit-discard-files--delete (nreverse delete) status)) + (when rename + (magit-discard-files--rename (nreverse rename) status)) + (when (or discard discard-new) + (magit-discard-files--discard (nreverse discard) + (nreverse discard-new))) + (magit-wip-commit-after-apply files " after discard")) + (magit-refresh)))) + +(defun magit-discard-files--resolve (files) + (if-let ((arg (and (cdr files) + (magit-read-char-case + (format "For these %d files\n%s\ncheckout:\n" + (length files) + (mapconcat (lambda (file) + (concat " " file)) + files "\n")) + t + (?o "[o]ur stage" "--ours") + (?t "[t]heir stage" "--theirs") + (?c "[c]onflict" "--merge") + (?i "decide [i]ndividually" nil))))) + (dolist (file files) + (magit-checkout-stage file arg)) + (dolist (file files) + (magit-checkout-stage file (magit-checkout-read-stage file))))) + +(defun magit-discard-files--resurrect (files) + (magit-confirm-files 'resurrect files) + (if (eq (magit-diff-type) 'staged) + (magit-call-git "reset" "--" files) + (magit-call-git "checkout" "--" files))) + +(defun magit-discard-files--delete (files status) + (magit-confirm-files (if magit-delete-by-moving-to-trash 'trash 'delete) + files) + (let ((delete-by-moving-to-trash magit-delete-by-moving-to-trash)) + (dolist (file files) + (when (string-match-p "\\`\\\\?~" file) + (error "Refusing to delete %S, too dangerous" file)) + (pcase (nth 3 (assoc file status)) + ((guard (memq (magit-diff-type) '(unstaged untracked))) + (dired-delete-file file dired-recursive-deletes + magit-delete-by-moving-to-trash) + (dired-clean-up-after-deletion file)) + (?\s (delete-file file t) + (magit-call-git "rm" "--cached" "--" file)) + (?M (let ((temp (magit-git-string "checkout-index" "--temp" file))) + (string-match + (format "\\(.+?\\)\t%s" (regexp-quote file)) temp) + (rename-file (match-string 1 temp) + (setq temp (concat file ".~{index}~"))) + (delete-file temp t)) + (magit-call-git "rm" "--cached" "--force" "--" file)) + (?D (magit-call-git "checkout" "--" file) + (delete-file file t) + (magit-call-git "rm" "--cached" "--force" "--" file)))))) + +(defun magit-discard-files--rename (files status) + (magit-confirm 'rename "Undo rename %s" "Undo %d renames" nil + (mapcar (lambda (file) + (setq file (assoc file status)) + (format "%s -> %s" (cadr file) (car file))) + files)) + (dolist (file files) + (let ((orig (cadr (assoc file status)))) + (if (file-exists-p file) + (progn + (when-let ((path (file-name-directory orig))) + (make-directory path t)) + (magit-call-git "mv" file orig)) + (magit-call-git "rm" "--cached" "--" file) + (magit-call-git "reset" "--" orig))))) + +(defun magit-discard-files--discard (sections new-files) + (let ((files (--map (oref it value) sections))) + (magit-confirm-files 'discard (append files new-files) + (format "Discard %s changes in" (magit-diff-type))) + (if (eq (magit-diff-type (car sections)) 'unstaged) + (magit-call-git "checkout" "--" files) + (when new-files + (magit-call-git "add" "--" new-files) + (magit-call-git "reset" "--" new-files)) + (let ((binaries (magit-binary-files "--cached"))) + (when binaries + (setq sections + (--remove (member (oref it value) binaries) + sections))) + (cond ((length= sections 1) + (magit-discard-apply (car sections) 'magit-apply-diff)) + (sections + (magit-discard-apply-n sections #'magit-apply-diffs))) + (when binaries + (let ((modified (magit-unstaged-files t))) + (setq binaries (--separate (member it modified) binaries))) + (when (cadr binaries) + (magit-call-git "reset" "--" (cadr binaries))) + (when (car binaries) + (user-error + (concat + "Cannot discard staged changes to binary files, " + "which also have unstaged changes. Unstage instead.")))))))) + +;;;; Reverse + +(defun magit-reverse (&rest args) + "Reverse the change at point in the working tree. +With a prefix argument fallback to a 3-way merge. Doing +so causes the change to be applied to the index as well." + (interactive (and current-prefix-arg (list "--3way"))) + (when-let ((s (magit-apply--get-selection))) + (pcase (list (magit-diff-type) (magit-diff-scope)) + (`(untracked ,_) (user-error "Cannot reverse untracked changes")) + (`(unstaged ,_) (user-error "Cannot reverse unstaged changes")) + (`(,_ region) (magit-reverse-region s args)) + (`(,_ hunk) (magit-reverse-hunk s args)) + (`(,_ hunks) (magit-reverse-hunks s args)) + (`(,_ file) (magit-reverse-file s args)) + (`(,_ files) (magit-reverse-files s args)) + (`(,_ list) (magit-reverse-files s args))))) + +(defun magit-reverse-region (section args) + (magit-confirm 'reverse "Reverse region") + (magit-reverse-apply section #'magit-apply-region args)) + +(defun magit-reverse-hunk (section args) + (magit-confirm 'reverse "Reverse hunk") + (magit-reverse-apply section #'magit-apply-hunk args)) + +(defun magit-reverse-hunks (sections args) + (magit-confirm 'reverse + (list "Reverse %d hunks from %s" + (length sections) + (magit-section-parent-value (car sections)))) + (magit-reverse-apply sections #'magit-apply-hunks args)) + +(defun magit-reverse-file (section args) + (magit-reverse-files (list section) args)) + +(defun magit-reverse-files (sections args) + (pcase-let ((`(,binaries ,sections) + (let ((bs (magit-binary-files + (cond ((derived-mode-p 'magit-revision-mode) + magit-buffer-range) + ((derived-mode-p 'magit-diff-mode) + magit-buffer-range) + (t + "--cached"))))) + (--separate (member (oref it value) bs) + sections)))) + (magit-confirm-files 'reverse (--map (oref it value) sections)) + (cond ((length= sections 1) + (magit-reverse-apply (car sections) #'magit-apply-diff args)) + (sections + (magit-reverse-apply sections #'magit-apply-diffs args))) + (when binaries + (user-error "Cannot reverse binary files")))) + +(defun magit-reverse-apply (section:s apply args) + (funcall apply section:s "--reverse" args + (and (not magit-reverse-atomically) + (not (member "--3way" args)) + "--reject"))) + +(defun magit-reverse-in-index (&rest args) + "Reverse the change at point in the index but not the working tree. + +Use this command to extract a change from `HEAD', while leaving +it in the working tree, so that it can later be committed using +a separate commit. A typical workflow would be: + +0. Optionally make sure that there are no uncommitted changes. +1. Visit the `HEAD' commit and navigate to the change that should + not have been included in that commit. +2. Type \"u\" (`magit-unstage') to reverse it in the index. + This assumes that `magit-unstage-committed' is non-nil. +3. Type \"c e\" to extend `HEAD' with the staged changes, + including those that were already staged before. +4. Optionally stage the remaining changes using \"s\" or \"S\" + and then type \"c c\" to create a new commit." + (interactive) + (magit-reverse (cons "--cached" args))) + +;;; Smerge Support + +(defun magit-smerge-keep-current () + "Keep the current version of the conflict at point." + (interactive) + (magit-call-smerge #'smerge-keep-current)) + +(defun magit-smerge-keep-upper () + "Keep the upper/our version of the conflict at point." + (interactive) + (magit-call-smerge #'smerge-keep-upper)) + +(defun magit-smerge-keep-base () + "Keep the base version of the conflict at point." + (interactive) + (magit-call-smerge #'smerge-keep-base)) + +(defun magit-smerge-keep-lower () + "Keep the lower/their version of the conflict at point." + (interactive) + (magit-call-smerge #'smerge-keep-lower)) + +(defun magit-smerge-keep-all () + "Keep all versions of the conflict at point." + (interactive) + (magit-call-smerge #'smerge-keep-all)) + +(defun magit-call-smerge (fn) + (pcase-let* ((file (magit-file-at-point t t)) + (keep (get-file-buffer file)) + (`(,buf ,pos) + (let ((magit-diff-visit-jump-to-change nil)) + (magit-diff-visit-file--noselect file)))) + (with-current-buffer buf + (save-excursion + (save-restriction + (unless (<= (point-min) pos (point-max)) + (widen)) + (goto-char pos) + (condition-case nil + (smerge-match-conflict) + (error + (if (eq fn #'smerge-keep-current) + (when (eq this-command #'magit-discard) + (re-search-forward smerge-begin-re nil t) + (setq fn + (magit-read-char-case "Keep side: " t + (?o "[o]urs/upper" #'smerge-keep-upper) + (?b "[b]ase" #'smerge-keep-base) + (?t "[t]heirs/lower" #'smerge-keep-lower)))) + (re-search-forward smerge-begin-re nil t)))) + (funcall fn))) + (when (and keep (magit-anything-unmerged-p file)) + (smerge-start-session)) + (save-buffer)) + (unless keep + (kill-buffer buf)) + (magit-refresh))) + +;;; _ +(provide 'magit-apply) +;;; magit-apply.el ends here diff --git a/emacs/elpa/magit-20241004.917/magit-autorevert.el b/emacs/elpa/magit-20241004.917/magit-autorevert.el @@ -0,0 +1,264 @@ +;;; magit-autorevert.el --- Revert buffers when files in repository change -*- lexical-binding:t -*- + +;; Copyright (C) 2008-2024 The Magit Project Contributors + +;; Author: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> +;; Maintainer: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> + +;; SPDX-License-Identifier: GPL-3.0-or-later + +;; Magit is free software: you can redistribute it and/or modify it +;; under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. +;; +;; Magit is distributed in the hope that it will be useful, but WITHOUT +;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +;; or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public +;; License for more details. +;; +;; You should have received a copy of the GNU General Public License +;; along with Magit. If not, see <https://www.gnu.org/licenses/>. + +;;; Code: + +(require 'magit-git) + +(require 'autorevert) + +;;; Options + +(defgroup magit-auto-revert nil + "Revert buffers when files in repository change." + :link '(custom-group-link auto-revert) + :link '(info-link "(magit)Automatic Reverting of File-Visiting Buffers") + :group 'auto-revert + :group 'magit-essentials + :group 'magit-modes) + +(defcustom auto-revert-buffer-list-filter nil + "Filter that determines which buffers `auto-revert-buffers' reverts. + +This option is provided by Magit, which also advises +`auto-revert-buffers' to respect it. Magit users who do not turn +on the local mode `auto-revert-mode' themselves, are best served +by setting the value to `magit-auto-revert-repository-buffer-p'. + +However the default is nil, so as not to disturb users who do use +the local mode directly. If you experience delays when running +Magit commands, then you should consider using one of the +predicates provided by Magit - especially if you also use Tramp. + +Users who do turn on `auto-revert-mode' in buffers in which Magit +doesn't do that for them, should likely not use any filter. +Users who turn on `global-auto-revert-mode', do not have to worry +about this option, because it is disregarded if the global mode +is enabled." + :package-version '(magit . "2.4.2") + :group 'auto-revert + :group 'magit-auto-revert + :group 'magit-related + :type '(radio (const :tag "No filter" nil) + (function-item magit-auto-revert-buffer-p) + (function-item magit-auto-revert-repository-buffer-p) + function)) + +(defcustom magit-auto-revert-tracked-only t + "Whether `magit-auto-revert-mode' only reverts tracked files." + :package-version '(magit . "2.4.0") + :group 'magit-auto-revert + :type 'boolean + :set (lambda (var val) + (set var val) + (when (and (bound-and-true-p magit-auto-revert-mode) + (featurep 'magit-autorevert)) + (magit-auto-revert-mode -1) + (magit-auto-revert-mode)))) + +(defcustom magit-auto-revert-immediately t + "Whether Magit reverts buffers immediately. + +If this is non-nil and either `global-auto-revert-mode' or +`magit-auto-revert-mode' is enabled, then Magit immediately +reverts buffers by explicitly calling `auto-revert-buffers' +after running Git for side-effects. + +If `auto-revert-use-notify' is non-nil (and file notifications +are actually supported), then `magit-auto-revert-immediately' +does not have to be non-nil, because the reverts happen +immediately anyway. + +If `magit-auto-revert-immediately' and `auto-revert-use-notify' +are both nil, then reverts happen after `auto-revert-interval' +seconds of user inactivity. That is not desirable." + :package-version '(magit . "2.4.0") + :group 'magit-auto-revert + :type 'boolean) + +;;; Mode + +(defun magit-turn-on-auto-revert-mode-if-desired (&optional file) + (cond (file + (when-let ((buffer (find-buffer-visiting file))) + (with-current-buffer buffer + (magit-turn-on-auto-revert-mode-if-desired)))) + ((and (not auto-revert-mode) ; see #3014 + (not global-auto-revert-mode) ; see #3460 + buffer-file-name + (or auto-revert-remote-files ; see #5422 + (not (file-remote-p buffer-file-name))) + (file-readable-p buffer-file-name) + (compat-call executable-find (magit-git-executable) t) + (magit-toplevel) + (or (not magit-auto-revert-tracked-only) + (magit-file-tracked-p buffer-file-name))) + (auto-revert-mode 1)))) + +;;;###autoload +(define-globalized-minor-mode magit-auto-revert-mode auto-revert-mode + magit-turn-on-auto-revert-mode-if-desired + :package-version '(magit . "2.4.0") + :link '(info-link "(magit)Automatic Reverting of File-Visiting Buffers") + :group 'magit-auto-revert + :group 'magit-essentials + ;; - When `global-auto-revert-mode' is enabled, then this mode is + ;; redundant. + ;; - In all other cases enable the mode because if buffers are not + ;; automatically reverted that would make many very common tasks + ;; much more cumbersome. + :init-value (not (or global-auto-revert-mode + noninteractive))) +;; - Unfortunately `:init-value t' only sets the value of the mode +;; variable but does not cause the mode function to be called. +;; - I don't think it works like this on purpose, but since one usually +;; should not enable global modes by default, it is understandable. +;; - If the user has set the variable `magit-auto-revert-mode' to nil +;; after loading magit (instead of doing so before loading magit or +;; by using the function), then we should still respect that setting. +;; - If the user enables `global-auto-revert-mode' after loading magit +;; and after `after-init-hook' has run, then `magit-auto-revert-mode' +;; remains enabled; and there is nothing we can do about it. +;; - However if the init file causes `magit-autorevert' to be loaded +;; and only later it enables `global-auto-revert-mode', then we can +;; and should leave `magit-auto-revert-mode' disabled. +(defun magit-auto-revert-mode--init-kludge () + "This is an internal kludge to be used on `after-init-hook'. +Do not use this function elsewhere, and don't remove it from +the `after-init-hook'. For more information see the comments +and code surrounding the definition of this function." + (if (or (not magit-auto-revert-mode) + (and global-auto-revert-mode (not after-init-time))) + (magit-auto-revert-mode -1) + (let ((start (current-time))) + (magit-message "Turning on magit-auto-revert-mode...") + (magit-auto-revert-mode 1) + (magit-message + "Turning on magit-auto-revert-mode...done%s" + (let ((elapsed (float-time (time-since start)))) + (if (> elapsed 0.2) + (format " (%.3fs, %s buffers checked)" elapsed + (length (buffer-list))) + "")))))) +(if after-init-time + ;; Since `after-init-hook' has already been + ;; run, turn the mode on or off right now. + (magit-auto-revert-mode--init-kludge) + ;; By the time the init file has been fully loaded the + ;; values of the relevant variables might have changed. + (add-hook 'after-init-hook #'magit-auto-revert-mode--init-kludge t)) + +(put 'magit-auto-revert-mode 'function-documentation + "Toggle Magit Auto Revert mode. +If called interactively, enable Magit Auto Revert mode if ARG is +positive, and disable it if ARG is zero or negative. If called +from Lisp, also enable the mode if ARG is omitted or nil, and +toggle it if ARG is `toggle'; disable the mode otherwise. + +Magit Auto Revert mode is a global minor mode that reverts +buffers associated with a file that is located inside a Git +repository when the file changes on disk. Use `auto-revert-mode' +to revert a particular buffer. Or use `global-auto-revert-mode' +to revert all file-visiting buffers, not just those that visit +a file located inside a Git repository. + +This global mode works by turning on the buffer-local mode +`auto-revert-mode' at the time a buffer is first created. The +local mode is turned on if the visited file is being tracked in +a Git repository at the time when the buffer is created. + +If `magit-auto-revert-tracked-only' is non-nil (the default), +then only tracked files are reverted. But if you stage a +previously untracked file using `magit-stage', then this mode +notices that. + +Unlike `global-auto-revert-mode', this mode never reverts any +buffers that are not visiting files. + +The behavior of this mode can be customized using the options +in the `autorevert' and `magit-autorevert' groups. + +This function calls the hook `magit-auto-revert-mode-hook'. + +Like nearly every mode, this mode should be enabled or disabled +by calling the respective mode function, the reason being that +changing the state of a mode involves more than merely toggling +a single switch, so setting the mode variable is not enough. +Also, you should not use `after-init-hook' to disable this mode.") + +(defun magit-auto-revert-buffers () + (when (and magit-auto-revert-immediately + (or global-auto-revert-mode + (and magit-auto-revert-mode auto-revert-buffer-list))) + (let ((auto-revert-buffer-list-filter + (or auto-revert-buffer-list-filter + #'magit-auto-revert-repository-buffer-p))) + (auto-revert-buffers)))) + +(defvar magit-auto-revert-toplevel nil) + +(defvar magit-auto-revert-counter 1 + "Incremented each time `auto-revert-buffers' is called.") + +(defun magit-auto-revert-buffer-p (buffer) + "Return non-nil if BUFFER visits a file inside the current repository. +The current repository is the one containing `default-directory'. +If there is no current repository, then return t for any BUFFER." + (magit-auto-revert-repository-buffer-p buffer t)) + +(defun magit-auto-revert-repository-buffer-p (buffer &optional fallback) + "Return non-nil if BUFFER visits a file inside the current repository. +The current repository is the one containing `default-directory'. +If there is no current repository, then return FALLBACK (which +defaults to nil) for any BUFFER." + ;; Call `magit-toplevel' just once per cycle. + (unless (and magit-auto-revert-toplevel + (= (cdr magit-auto-revert-toplevel) + magit-auto-revert-counter)) + (setq magit-auto-revert-toplevel + (cons (or (magit-toplevel) 'no-repo) + magit-auto-revert-counter))) + (let ((top (car magit-auto-revert-toplevel))) + (if (eq top 'no-repo) + fallback + (let ((dir (buffer-local-value 'default-directory buffer))) + (and (equal (file-remote-p dir) + (file-remote-p top)) + ;; ^ `tramp-handle-file-in-directory-p' lacks this optimization. + (file-in-directory-p dir top)))))) + +(define-advice auto-revert-buffers (:around (fn) buffer-list-filter) + (cl-incf magit-auto-revert-counter) + (if (or global-auto-revert-mode + (not auto-revert-buffer-list) + (not auto-revert-buffer-list-filter)) + (funcall fn) + (let ((auto-revert-buffer-list + (seq-filter auto-revert-buffer-list-filter + auto-revert-buffer-list))) + (funcall fn)) + (unless auto-revert-timer + (auto-revert-set-timer)))) + +;;; _ +(provide 'magit-autorevert) +;;; magit-autorevert.el ends here diff --git a/emacs/elpa/magit-20241004.917/magit-base.el b/emacs/elpa/magit-20241004.917/magit-base.el @@ -0,0 +1,1277 @@ +;;; magit-base.el --- Early birds -*- lexical-binding:t; coding:utf-8 -*- + +;; Copyright (C) 2008-2024 The Magit Project Contributors + +;; Author: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> +;; Maintainer: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> + +;; SPDX-License-Identifier: GPL-3.0-or-later + +;; Magit is free software: you can redistribute it and/or modify it +;; under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. +;; +;; Magit is distributed in the hope that it will be useful, but WITHOUT +;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +;; or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public +;; License for more details. +;; +;; You should have received a copy of the GNU General Public License +;; along with Magit. If not, see <https://www.gnu.org/licenses/>. + +;; This file contains code taken from GNU Emacs, which is +;; Copyright (C) 1976-2023 Free Software Foundation, Inc. + +;;; Commentary: + +;; This library defines utility functions, options and other things that +;; have to be available early on because they are used by several other +;; libraries, which cannot depend on one another, because that would lead +;; to circular dependencies. + +;;; Code: + +(defconst magit--minimal-git "2.2.0") +(defconst magit--minimal-emacs "26.1") + +(require 'cl-lib) +(require 'compat) +(require 'dash) +(require 'eieio) +(require 'subr-x) + +;; For older Emacs releases we depend on an updated `seq' release from +;; GNU ELPA, for `seq-keep'. Unfortunately something else may already +;; have required `seq', before `package' had a chance to put the more +;; recent version earlier on the `load-path'. +(when (and (featurep 'seq) + (not (fboundp 'seq-keep))) + (unload-feature 'seq 'force)) +(require 'seq) + +(require 'crm) + +(require 'magit-section) + +(eval-when-compile (require 'info)) +(declare-function Info-get-token "info" (pos start all &optional errorstring)) + +(eval-when-compile (require 'vc-git)) +(declare-function vc-git--run-command-string "vc-git" (file &rest args)) + +(eval-when-compile (require 'which-func)) +(declare-function which-function "which-func" ()) + +;;; Options + +(defcustom magit-completing-read-function #'magit-builtin-completing-read + "Function to be called when requesting input from the user. + +If you have enabled `ivy-mode' or `helm-mode', then you don't +have to customize this option; `magit-builtin-completing-read' +will work just fine. However, if you use Ido completion, then +you do have to use `magit-ido-completing-read', because Ido is +less well behaved than the former, more modern alternatives. + +If you would like to use Ivy or Helm completion with Magit but +not enable the respective modes globally, then customize this +option to use `ivy-completing-read' or +`helm--completing-read-default'. If you choose to use +`ivy-completing-read', note that the items may always be shown in +alphabetical order, depending on your version of Ivy." + :group 'magit-essentials + :type '(radio (function-item magit-builtin-completing-read) + (function-item magit-ido-completing-read) + (function-item ivy-completing-read) + (function-item helm--completing-read-default) + (function :tag "Other function"))) + +(defcustom magit-dwim-selection + '((magit-stash-apply nil t) + (magit-ediff-resolve-all nil t) + (magit-ediff-resolve-rest nil t) + (magit-stash-branch nil t) + (magit-stash-branch-here nil t) + (magit-stash-format-patch nil t) + (magit-stash-drop nil ask) + (magit-stash-pop nil ask)) + "When not to offer alternatives and ask for confirmation. + +Many commands by default ask the user to select from a list of +possible candidates. They do so even when there is a thing at +point that they can act on, which is then offered as the default. + +This option can be used to tell certain commands to use the thing +at point instead of asking the user to select a candidate to act +on, with or without confirmation. + +The value has the form ((COMMAND nil|PROMPT DEFAULT)...). + +- COMMAND is the command that should not prompt for a choice. + To have an effect, the command has to use the function + `magit-completing-read' or a utility function which in turn uses + that function. + +- If the command uses `magit-completing-read' multiple times, then + PROMPT can be used to only affect one of these uses. PROMPT, if + non-nil, is a regular expression that is used to match against + the PROMPT argument passed to `magit-completing-read'. + +- DEFAULT specifies how to use the default. If it is t, then + the DEFAULT argument passed to `magit-completing-read' is used + without confirmation. If it is `ask', then the user is given + a chance to abort. DEFAULT can also be nil, in which case the + entry has no effect." + :package-version '(magit . "2.12.0") + :group 'magit-commands + :type '(repeat + (list (symbol :tag "Command") ; It might not be fboundp yet. + (choice (const :tag "for all prompts" nil) + (regexp :tag "for prompts matching regexp")) + (choice (const :tag "offer other choices" nil) + (const :tag "require confirmation" ask) + (const :tag "use default without confirmation" t))))) + +(defconst magit--confirm-actions + '((const discard) + (const reverse) + (const stage-all-changes) + (const unstage-all-changes) + (const delete) + (const trash) + (const resurrect) + (const untrack) + (const rename) + (const reset-bisect) + (const abort-cherry-pick) + (const abort-revert) + (const abort-rebase) + (const abort-merge) + (const merge-dirty) + (const delete-unmerged-branch) + (const delete-branch-on-remote) + (const delete-pr-remote) + (const drop-stashes) + (const set-and-push) + (const amend-published) + (const rebase-published) + (const edit-published) + (const remove-modules) + (const remove-dirty-modules) + (const trash-module-gitdirs) + (const stash-apply-3way) + (const kill-process) + (const safe-with-wip))) + +(defcustom magit-no-confirm '(set-and-push) + "A list of symbols for actions Magit should not confirm, or t. + +Many potentially dangerous commands by default ask the user for +confirmation. Each of the below symbols stands for an action +which, when invoked unintentionally or without being fully aware +of the consequences, could lead to tears. In many cases there +are several commands that perform variations of a certain action, +so we don't use the command names but more generic symbols. + +Applying changes: + + `discard' Discarding one or more changes (i.e., hunks or the + complete diff for a file) loses that change, obviously. + + `reverse' Reverting one or more changes can usually be undone + by reverting the reversion. + + `stage-all-changes', `unstage-all-changes' When there are both + staged and unstaged changes, then un-/staging everything would + destroy that distinction. Of course that also applies when + un-/staging a single change, but then less is lost and one does + that so often that having to confirm every time would be + unacceptable. + +Files: + + `delete' When a file that isn't yet tracked by Git is deleted + then it is completely lost, not just the last changes. Very + dangerous. + + `trash' Instead of deleting a file it can also be move to the + system trash. Obviously much less dangerous than deleting it. + + Also see option `magit-delete-by-moving-to-trash'. + + `resurrect' A deleted file can easily be resurrected by + \"deleting\" the deletion, which is done using the same command + that was used to delete the same file in the first place. + + `untrack' Untracking a file can be undone by tracking it again. + + `rename' Renaming a file can easily be undone. + +Sequences: + + `reset-bisect' Aborting (known to Git as \"resetting\") a + bisect operation loses all information collected so far. + + `abort-cherry-pick' Aborting a cherry-pick throws away all + conflict resolutions which has already been carried out by the + user. + + `abort-revert' Aborting a revert throws away all conflict + resolutions which has already been carried out by the user. + + `abort-rebase' Aborting a rebase throws away all already + modified commits, but it's possible to restore those from the + reflog. + + `abort-merge' Aborting a merge throws away all conflict + resolutions which has already been carried out by the user. + + `merge-dirty' Merging with a dirty worktree can make it hard to + go back to the state before the merge was initiated. + +References: + + `delete-unmerged-branch' Once a branch has been deleted it can + only be restored using low-level recovery tools provided by + Git. And even then the reflog is gone. The user always has + to confirm the deletion of a branch by accepting the default + choice (or selecting another branch), but when a branch has + not been merged yet, also make sure the user is aware of that. + + `delete-branch-on-remote' Deleting a \"remote branch\" may mean + deleting the (local) \"remote-tracking\" branch only, or also + removing it from the remote itself. The latter often makes more + sense because otherwise simply fetching from the remote would + restore the remote-tracking branch, but doing that can be + surprising and hard to recover from, so we ask. + + `delete-pr-remote' When deleting a branch that was created from + a pull-request and if no other branches still exist on that + remote, then `magit-branch-delete' offers to delete the remote + as well. This should be safe because it only happens if no + other refs exist in the remotes namespace, and you can recreate + the remote if necessary. + + `drop-stashes' Dropping a stash is dangerous because Git stores + stashes in the reflog. Once a stash is removed, there is no + going back without using low-level recovery tools provided by + Git. When a single stash is dropped, then the user always has + to confirm by accepting the default (or selecting another). + This action only concerns the deletion of multiple stashes at + once. + +Publishing: + + `set-and-push' When pushing to the upstream or the push-remote + and that isn't actually configured yet, then the user can first + set the target. If s/he confirms the default too quickly, then + s/he might end up pushing to the wrong branch and if the remote + repository is configured to disallow fixing such mistakes, then + that can be quite embarrassing and annoying. + +Edit published history: + + Without adding these symbols here, you will be warned before + editing commits that have already been pushed to one of the + branches listed in `magit-published-branches'. + + `amend-published' Affects most commands that amend to `HEAD'. + + `rebase-published' Affects commands that perform interactive + rebases. This includes commands from the commit popup that + modify a commit other than `HEAD', namely the various fixup + and squash variants. + + `edit-published' Affects the commands `magit-edit-line-commit' + and `magit-diff-edit-hunk-commit'. These two commands make + it quite easy to accidentally edit a published commit, so you + should think twice before configuring them not to ask for + confirmation. + + To disable confirmation completely, add all three symbols here + or set `magit-published-branches' to nil. + +Removing modules: + + `remove-modules' When you remove the working directory of a + module that does not contain uncommitted changes, then that is + safer than doing so when there are uncommitted changes and/or + when you also remove the gitdir. Still, you don't want to do + that by accident. + + `remove-dirty-modules' When you remove the working directory of + a module that contains uncommitted changes, then those changes + are gone for good. It is better to go to the module, inspect + these changes and only if appropriate discard them manually. + + `trash-module-gitdirs' When you remove the gitdir of a module, + then all unpushed changes are gone for good. It is very easy + to forget that you have some unfinished work on an unpublished + feature branch or even in a stash. + + Actually there are some safety precautions in place, that might + help you out if you make an unwise choice here, but don't count + on it. In case of emergency, stay calm and check the stash and + the `trash-directory' for traces of lost work. + +Various: + + `stash-apply-3way' When a stash cannot be applied using \"git + stash apply\", then Magit uses \"git apply\" instead, possibly + using the \"--3way\" argument, which isn't always perfectly + safe. See also `magit-stash-apply'. + + `kill-process' There seldom is a reason to kill a process. + +Global settings: + + Instead of adding all of the above symbols to the value of this + option you can also set it to the atom `t', which has the same + effect as adding all of the above symbols. Doing that most + certainly is a bad idea, especially because other symbols might + be added in the future. So even if you don't want to be asked + for confirmation for any of these actions, you are still better + of adding all of the respective symbols individually. + + When `magit-wip-before-change-mode' is enabled then these actions + can fairly easily be undone: `discard', `reverse', + `stage-all-changes', and `unstage-all-changes'. If and only if + this mode is enabled, then `safe-with-wip' has the same effect + as adding all of these symbols individually." + :package-version '(magit . "2.1.0") + :group 'magit-essentials + :group 'magit-commands + :type `(choice (const :tag "Always require confirmation" nil) + (const :tag "Never require confirmation" t) + (set :tag "Require confirmation except for" + ;; `remove-dirty-modules' and + ;; `trash-module-gitdirs' intentionally + ;; omitted. + ,@magit--confirm-actions))) + +(defcustom magit-slow-confirm '(drop-stashes) + "Whether to ask user \"y or n\" or \"yes or no\" questions. + +When this is nil, then `y-or-n-p' is used when the user has to +confirm a potentially destructive action. When this is t, then +`yes-or-no-p' is used instead. If this is a list of symbols +identifying actions, then `yes-or-no-p' is used for those, +`y-or-no-p' for all others. The list of actions is the same as +for `magit-no-confirm' (which see)." + :package-version '(magit . "2.9.0") + :group 'magit-miscellaneous + :type `(choice (const :tag "Always ask \"yes or no\" questions" t) + (const :tag "Always ask \"y or n\" questions" nil) + (set :tag "Ask \"yes or no\" questions only for" + ,@magit--confirm-actions))) + +(defcustom magit-no-message nil + "A list of messages Magit should not display. + +Magit displays most echo area messages using `message', but a few +are displayed using `magit-message' instead, which takes the same +arguments as the former, FORMAT-STRING and ARGS. `magit-message' +forgoes printing a message if any member of this list is a prefix +of the respective FORMAT-STRING. + +If Magit prints a message which causes you grief, then please +first investigate whether there is another option which can be +used to suppress it. If that is not the case, then ask the Magit +maintainers to start using `magit-message' instead of `message' +in that case. We are not proactively replacing all uses of +`message' with `magit-message', just in case someone *might* find +some of these messages useless. + +Messages which can currently be suppressed using this option are: +* \"Turning on magit-auto-revert-mode...\"" + :package-version '(magit . "2.8.0") + :group 'magit-miscellaneous + :type '(repeat string)) + +(defcustom magit-verbose-messages nil + "Whether to make certain prompts and messages more verbose. + +Occasionally a user suggests that a certain prompt or message +should be more verbose, but I would prefer to keep it as-is +because I don't think that the fact that that one user did not +understand the existing prompt/message means that a large number +of users would have the same difficulty, and that making it more +verbose would actually do a disservice to users who understand +the shorter prompt well enough. + +Going forward I will start offering both messages when I feel the +suggested longer message is reasonable enough, and the value of +this option decides which will be used. Note that changing the +value of this option affects all such messages and that I do not +intend to add an option per prompt." + :package-version '(magit . "4.0.0") + :group 'magit-miscellaneous + :type 'boolean) + +(defcustom magit-ellipsis + '((margin (?… . ">")) + (t (?… . "..."))) + "Characters or strings used to abbreviate text in some buffers. + +Each element has the form (WHERE (FANCY . UNIVERSAL)). + +FANCY is a single character or nil whereas UNIVERSAL is a string +of any length. The ellipsis produced by `magit--ellipsis' will +be FANCY if it's a non-nil character that can be displayed with +the available fonts, otherwise UNIVERSAL will be used. FANCY is +meant to be a rich character like a horizontal ellipsis symbol or +an emoji whereas UNIVERSAL something simpler available in a less +rich environment like the CLI. WHERE determines the use-case for +the ellipsis definition. Currently the only acceptable values +for WHERE are `margin' or t (representing the default). + +Whether collapsed sections are indicated using ellipsis is +controlled by `magit-section-visibility-indicator'." + :package-version '(magit . "4.0.0") + :group 'magit-miscellaneous + :type '(repeat (list (symbol :tag "Where") + (cons (choice :tag "Fancy" character (const nil)) + (string :tag "Universal"))))) + +(defcustom magit-update-other-window-delay 0.2 + "Delay before automatically updating the other window. + +When moving around in certain buffers, then certain other +buffers, which are being displayed in another window, may +optionally be updated to display information about the +section at point. + +When holding down a key to move by more than just one section, +then that would update that buffer for each section on the way. +To prevent that, updating the revision buffer is delayed, and +this option controls for how long. For optimal experience you +might have to adjust this delay and/or the keyboard repeat rate +and delay of your graphical environment or operating system." + :package-version '(magit . "2.3.0") + :group 'magit-miscellaneous + :type 'number) + +(defcustom magit-view-git-manual-method 'info + "How links to Git documentation are followed from Magit's Info manuals. + +`info' Follow the link to the node in the `gitman' Info manual + as usual. Unfortunately that manual is not installed by + default on some platforms, and when it is then the nodes + look worse than the actual manpages. + +`man' View the respective man-page using the `man' package. + +`woman' View the respective man-page using the `woman' package." + :package-version '(magit . "2.9.0") + :group 'magit-miscellaneous + :type '(choice (const :tag "view info manual" info) + (const :tag "view manpage using `man'" man) + (const :tag "view manpage using `woman'" woman))) + +;;; Section Classes + +(defclass magit-commit-section (magit-section) + ((keymap :initform 'magit-commit-section-map))) + +(setf (alist-get 'commit magit--section-type-alist) 'magit-commit-section) + +(defclass magit-diff-section (magit-section) + ((keymap :initform 'magit-diff-section-map)) + :abstract t) + +(defclass magit-file-section (magit-diff-section) + ((keymap :initform 'magit-file-section-map) + (source :initform nil :initarg :source) + (header :initform nil :initarg :header) + (binary :initform nil :initarg :binary))) + +(defclass magit-module-section (magit-file-section) + ((keymap :initform 'magit-module-section-map) + (range :initform nil :initarg :range))) + +(defclass magit-hunk-section (magit-diff-section) + ((keymap :initform 'magit-hunk-section-map) + (refined :initform nil) + (combined :initform nil :initarg :combined) + (from-range :initform nil :initarg :from-range) + (from-ranges :initform nil) + (to-range :initform nil :initarg :to-range) + (about :initform nil :initarg :about))) + +(setf (alist-get 'file magit--section-type-alist) 'magit-file-section) +(setf (alist-get 'module magit--section-type-alist) 'magit-module-section) +(setf (alist-get 'hunk magit--section-type-alist) 'magit-hunk-section) + +(defclass magit-log-section (magit-section) + ((keymap :initform 'magit-log-section-map)) + :abstract t) +(defclass magit-unpulled-section (magit-log-section) ()) +(defclass magit-unpushed-section (magit-log-section) ()) +(defclass magit-unmerged-section (magit-log-section) ()) + +(setf (alist-get 'unpulled magit--section-type-alist) 'magit-unpulled-section) +(setf (alist-get 'unpushed magit--section-type-alist) 'magit-unpushed-section) +(setf (alist-get 'unmerged magit--section-type-alist) 'magit-unmerged-section) + +;;; User Input + +(defvar helm-completion-in-region-default-sort-fn) +(defvar helm-crm-default-separator) +(defvar ivy-sort-functions-alist) +(defvar ivy-sort-matches-functions-alist) +(defvar vertico-sort-function) + +(defvar magit-completing-read--silent-default nil) + +(defvar magit-completing-read-default-prompt-predicate + (lambda () + (and (eq magit-completing-read-function + 'magit-builtin-completing-read) + (not (or (bound-and-true-p helm-mode) + (bound-and-true-p ivy-mode) + (bound-and-true-p selectrum-mode) + (bound-and-true-p vertico-mode))))) + "Function used to determine whether to add default to prompt. + +This is used by `magit-completing-read' (which see). + +The default function returns nil, when a completion frameworks is used +for which this is undesirable. More precisely, it returns nil, when +`magit-completing-read-function' is not `magit-builtin-completing-read', +or one of `helm-mode', `ivy-mode', `selectrum-mode' or `vertico-mode' +is enabled. When this function returns nil, then nil is passed to +`format-prompt' (which see), instead of the default (DEF or FALLBACK).") + +(defun magit-completing-read ( prompt collection &optional + predicate require-match initial-input + hist def fallback) + "Read a choice in the minibuffer, or use the default choice. + +This is the function that Magit commands use when they need the +user to select a single thing to act on. The arguments have the +same meaning as for `completing-read', except for FALLBACK, which +is unique to this function and is described below. + +Instead of asking the user to choose from a list of possible +candidates, this function may instead just return the default +specified by DEF, with or without requiring user confirmation. +Whether that is the case depends on PROMPT, `this-command' and +`magit-dwim-selection'. See the documentation of the latter for +more information. + +If it does use the default without the user even having to +confirm that, then `magit-completing-read--silent-default' is set +to t, otherwise nil. + +If it does read a value in the minibuffer, then this function +acts similarly to `completing-read', except for the following: + +- COLLECTION must be a list of choices. A function is not + supported. + +- If REQUIRE-MATCH is nil and the user exits without a choice, + then nil is returned instead of an empty string. + +- If REQUIRE-MATCH is non-nil and the user exits without a + choice, `user-error' is raised. + +- FALLBACK specifies a secondary default that is only used if + the primary default DEF is nil. The secondary default is not + subject to `magit-dwim-selection' — if DEF is nil but FALLBACK + is not, then this function always asks the user to choose a + candidate, just as if both defaults were nil. + +- `format-prompt' is called on PROMPT and DEF (or FALLBACK if + DEF is nil). This appends \": \" to the prompt and may also + add the default to the prompt, using the format specified by + `minibuffer-default-prompt-format' and depending on + `magit-completing-read-default-prompt-predicate'." + (setq magit-completing-read--silent-default nil) + (if-let ((dwim (and def + (nth 2 (seq-find (pcase-lambda (`(,cmd ,re ,_)) + (and (eq this-command cmd) + (or (not re) + (string-match-p re prompt)))) + magit-dwim-selection))))) + (if (eq dwim 'ask) + (if (y-or-n-p (format "%s %s? " prompt def)) + def + (user-error "Abort")) + (setq magit-completing-read--silent-default t) + def) + (unless def + (setq def fallback)) + (let ((command this-command) + (reply (funcall + magit-completing-read-function + (magit--format-prompt prompt def) + (if (and (not (functionp collection)) + def + (not (member def collection))) + (cons def collection) + collection) + predicate + require-match initial-input hist def))) + (setq this-command command) + ;; Note: Avoid `string=' to support `helm-comp-read-use-marked'. + (if (equal reply "") + (if require-match + (user-error "Nothing selected") + nil) + reply)))) + +(defun magit--format-prompt (prompt default) + (format-prompt (if (string-suffix-p ": " prompt) + (substring prompt 0 -2) + prompt) + (and (funcall magit-completing-read-default-prompt-predicate) + default))) + +(defun magit--completion-table (collection) + (lambda (string pred action) + (if (eq action 'metadata) + '(metadata (display-sort-function . identity)) + (complete-with-action action collection string pred)))) + +(defun magit-builtin-completing-read + (prompt choices &optional predicate require-match initial-input hist def) + "Magit wrapper for standard `completing-read' function." + (unless (or (bound-and-true-p helm-mode) + (bound-and-true-p ivy-mode)) + (setq choices (magit--completion-table choices))) + (let ((ivy-sort-functions-alist nil) + (vertico-sort-function nil)) + (completing-read prompt choices + predicate require-match + initial-input hist def))) + +(define-obsolete-function-alias 'magit-completing-read-multiple* + 'magit-completing-read-multiple "Magit-Section 4.0.0") + +(defun magit-completing-read-multiple + ( prompt table &optional predicate require-match initial-input + hist def inherit-input-method + no-split) + "Read multiple strings in the minibuffer, with completion. +Like `completing-read-multiple' but don't mess with order of +TABLE and take an additional argument NO-SPLIT, which causes +the user input to be returned as a single unmodified string. +Also work around various incompatible features of various +third-party completion frameworks." + (cl-letf* + (;; To implement NO-SPLIT we have to manipulate the respective + ;; `split-string' invocation. We cannot simply advice it to + ;; return the input string because `SELECTRUM' would choke on + ;; that string. Use a variable to pass along the raw user + ;; input string. aa5f098ab + (input nil) + (split-string (symbol-function #'split-string)) + ((symbol-function #'split-string) + (lambda (string &optional separators omit-nulls trim) + (when (and no-split + (equal separators crm-separator) + (equal omit-nulls t)) + (setq input string)) + (funcall split-string string separators omit-nulls trim))) + ;; Prevent `BUILT-IN' completion from messing up our existing + ;; order of the completion candidates. aa5f098ab + (table (magit--completion-table table)) + ;; Prevent `IVY' from messing up our existing order. c7af78726 + (ivy-sort-matches-functions-alist nil) + ;; Prevent `HELM' from messing up our existing order. 6fcf994bd + (helm-completion-in-region-default-sort-fn nil) + ;; Prevent `HELM' from automatically appending the separator, + ;; which is counterproductive when NO-SPLIT is non-nil and/or + ;; when reading commit ranges. 798aff564 + (helm-crm-default-separator + (if no-split nil (bound-and-true-p helm-crm-default-separator))) + ;; And now, the moment we have all been waiting for... + (values (completing-read-multiple + (magit--format-prompt prompt def) + table predicate require-match initial-input + hist def inherit-input-method))) + (if no-split input values))) + +(defun magit-ido-completing-read + (prompt choices &optional predicate require-match initial-input hist def) + "Ido-based `completing-read' almost-replacement. + +Unfortunately `ido-completing-read' is not suitable as a +drop-in replacement for `completing-read', instead we use +`ido-completing-read+' from the third-party package by the +same name." + (if (and (require 'ido-completing-read+ nil t) + (fboundp 'ido-completing-read+)) + (ido-completing-read+ prompt choices predicate require-match + initial-input hist + (or def (and require-match (car choices)))) + (display-warning 'magit "ido-completing-read+ is not installed + +To use Ido completion with Magit you need to install the +third-party `ido-completing-read+' packages. Falling +back to built-in `completing-read' for now." :error) + (magit-builtin-completing-read prompt choices predicate require-match + initial-input hist def))) + +(defvar-keymap magit-minibuffer-local-ns-map + :parent minibuffer-local-map + "SPC" #'magit-whitespace-disallowed + "TAB" #'magit-whitespace-disallowed) + +(defun magit-whitespace-disallowed () + "Beep to tell the user that whitespace is not allowed." + (interactive) + (ding) + (message "Whitespace isn't allowed here") + (setq defining-kbd-macro nil) + (force-mode-line-update)) + +(defun magit-read-string ( prompt &optional initial-input history default-value + inherit-input-method no-whitespace) + "Read a string from the minibuffer, prompting with string PROMPT. + +This is similar to `read-string', but +* empty input is only allowed if DEFAULT-VALUE is non-nil in + which case that is returned, +* whitespace is not allowed and leading and trailing whitespace is + removed automatically if NO-WHITESPACE is non-nil, +* `format-prompt' is used internally. +* an invalid DEFAULT-VALUE is silently ignored." + (when default-value + (when (consp default-value) + (setq default-value (car default-value))) + (unless (stringp default-value) + (setq default-value nil))) + (let* ((minibuffer-completion-table nil) + (val (read-from-minibuffer + (format-prompt prompt default-value) + initial-input (and no-whitespace magit-minibuffer-local-ns-map) + nil history default-value inherit-input-method)) + (trim (lambda (regexp string) + (save-match-data + (if (string-match regexp string) + (replace-match "" t t string) + string))))) + (when (and (string= val "") default-value) + (setq val default-value)) + (when no-whitespace + (setq val (funcall trim "\\`\\(?:[ \t\n\r]+\\)" + (funcall trim "\\(?:[ \t\n\r]+\\)\\'" val)))) + (cond ((string= val "") + (user-error "Need non-empty input")) + ((and no-whitespace (string-match-p "[\s\t\n]" val)) + (user-error "Input contains whitespace")) + (t val)))) + +(defun magit-read-string-ns ( prompt &optional initial-input history + default-value inherit-input-method) + "Call `magit-read-string' with non-nil NO-WHITESPACE." + (magit-read-string prompt initial-input history default-value + inherit-input-method t)) + +(defmacro magit-read-char-case (prompt verbose &rest clauses) + (declare (indent 2) + (debug (form form &rest (characterp form body)))) + `(prog1 (pcase (read-char-choice + (let ((parts (nconc (list ,@(mapcar #'cadr clauses)) + ,(and verbose '(list "[C-g] to abort"))))) + (concat ,prompt + (string-join (butlast parts) ", ") + ", or " (car (last parts)) " ")) + ',(mapcar #'car clauses)) + ,@(--map `(,(car it) ,@(cddr it)) clauses)) + (message ""))) + +(defun magit-y-or-n-p (prompt &optional action) + "Ask user a \"y or n\" or a \"yes or no\" question using PROMPT. +Which kind of question is used depends on whether +ACTION is a member of option `magit-slow-confirm'." + (if (or (eq magit-slow-confirm t) + (and action (member action magit-slow-confirm))) + (yes-or-no-p prompt) + (y-or-n-p prompt))) + +(defvar magit--no-confirm-alist + '((safe-with-wip magit-wip-before-change-mode + discard reverse stage-all-changes unstage-all-changes))) + +(cl-defun magit-confirm ( action &optional prompt prompt-n noabort + (items nil sitems) prompt-suffix) + (declare (indent defun)) + (when (and prompt (listp prompt)) + (setq prompt + (apply #'format (car prompt) + (mapcar (lambda (a) (if (stringp a) (string-replace "%" "%%" a) a)) + (cdr prompt))))) + (when (and prompt-n (listp prompt-n)) + (setq prompt-n + (apply #'format (car prompt-n) + (mapcar (lambda (a) (if (stringp a) (string-replace "%" "%%" a) a)) + (cdr prompt-n))))) + (setq prompt-n (format (concat (or prompt-n prompt) "? ") (length items))) + (setq prompt (format (concat (or prompt (magit-confirm-make-prompt action)) + "? ") + (car items))) + (when prompt-suffix + (setq prompt (concat prompt prompt-suffix))) + (or (cond ((and (not (eq action t)) + (or (eq magit-no-confirm t) + (memq action magit-no-confirm) + (cl-member-if (pcase-lambda (`(,key ,var . ,sub)) + (and (memq key magit-no-confirm) + (memq action sub) + (or (not var) + (and (boundp var) + (symbol-value var))))) + magit--no-confirm-alist))) + (or (not sitems) items)) + ((not sitems) + (magit-y-or-n-p prompt action)) + ((length= items 1) + (and (magit-y-or-n-p prompt action) items)) + ((length> items 1) + (and (magit-y-or-n-p (concat (string-join items "\n") + "\n\n" prompt-n) + action) + items))) + (if noabort nil (user-error "Abort")))) + +(defun magit-confirm-files (action files &optional prompt prompt-suffix noabort) + (when files + (unless prompt + (setq prompt (magit-confirm-make-prompt action))) + (magit-confirm action + (concat prompt " \"%s\"") + (concat prompt " %d files") + noabort files prompt-suffix))) + +(defun magit-confirm-make-prompt (action) + (let ((prompt (symbol-name action))) + (string-replace "-" " " + (concat (upcase (substring prompt 0 1)) + (substring prompt 1))))) + +(defun magit-read-number-string (prompt &optional default _history) + "Like `read-number' but return value is a string. +DEFAULT may be a number or a numeric string." + (number-to-string + (read-number prompt (if (stringp default) + (string-to-number default) + default)))) + +;;; Debug Utilities + +;;;###autoload +(defun magit-emacs-Q-command () + "Show a shell command that runs an uncustomized Emacs with only Magit loaded. +See info node `(magit)Debugging Tools' for more information." + (interactive) + (let ((cmd (mapconcat + #'shell-quote-argument + `(,(concat invocation-directory invocation-name) + "-Q" "--eval" "(setq debug-on-error t)" + ,@(cl-mapcan + (lambda (dir) (list "-L" dir)) + (delete-dups + (cl-mapcan + (lambda (lib) + (if-let ((path (locate-library lib))) + (list (file-name-directory path)) + (error "Cannot find mandatory dependency %s" lib))) + '(;; Like `LOAD_PATH' in `default.mk'. + "compat" + "dash" + "transient" + "with-editor" + ;; Obviously `magit' itself is needed too. + "magit" + ;; While these are part of the Magit repository, + ;; they are distributed as separate packages. + "magit-section" + "git-commit" + )))) + ;; Avoid Emacs bug#16406 by using full path. + "-l" ,(file-name-sans-extension (locate-library "magit"))) + " "))) + (message "Uncustomized Magit command saved to kill-ring, %s" + "please run it in a terminal.") + (kill-new cmd))) + +;;; Text Utilities + +(defmacro magit-bind-match-strings (varlist string &rest body) + "Bind variables to submatches according to VARLIST then evaluate BODY. +Bind the symbols in VARLIST to submatches of the current match +data, starting with 1 and incrementing by 1 for each symbol. If +the last match was against a string, then that has to be provided +as STRING." + (declare (indent 2) (debug (listp form body))) + (let ((s (cl-gensym "string")) + (i 0)) + `(let ((,s ,string)) + (let ,(save-match-data + (cl-mapcan (lambda (sym) + (cl-incf i) + (and (not (eq (aref (symbol-name sym) 0) ?_)) + (list (list sym (list 'match-string i s))))) + varlist)) + ,@body)))) + +(defun magit-delete-line () + "Delete the rest of the current line." + (delete-region (point) (1+ (line-end-position)))) + +(defun magit-delete-match (&optional num) + "Delete text matched by last search. +If optional NUM is specified, only delete that subexpression." + (delete-region (match-beginning (or num 0)) + (match-end (or num 0)))) + +(defun magit-file-line (file) + "Return the first line of FILE as a string." + (when (file-regular-p file) + (with-temp-buffer + (insert-file-contents file) + (buffer-substring-no-properties (point-min) + (line-end-position))))) + +(defun magit-file-lines (file &optional keep-empty-lines) + "Return a list of strings containing one element per line in FILE. +Unless optional argument KEEP-EMPTY-LINES is t, trim all empty lines." + (when (file-regular-p file) + (with-temp-buffer + (insert-file-contents file) + (split-string (buffer-string) "\n" (not keep-empty-lines))))) + +(defun magit-set-header-line-format (string) + "Set `header-line-format' in the current buffer based on STRING. +Pad the left side of STRING so that it aligns with the text area." + (setq header-line-format + (concat (propertize " " 'display '(space :align-to 0)) + string))) + +(defun magit--format-spec (format specification) + "Like `format-spec' but preserve text properties in SPECIFICATION." + (with-temp-buffer + (insert format) + (goto-char (point-min)) + (while (search-forward "%" nil t) + (cond + ;; Quoted percent sign. + ((eq (char-after) ?%) + (delete-char 1)) + ;; Valid format spec. + ((looking-at "\\([-0-9.]*\\)\\([a-zA-Z]\\)") + (let* ((num (match-string 1)) + (spec (string-to-char (match-string 2))) + (val (assq spec specification))) + (unless val + (error "Invalid format character: `%%%c'" spec)) + (setq val (cdr val)) + ;; Pad result to desired length. + (let ((text (format (concat "%" num "s") val))) + ;; Insert first, to preserve text properties. + (if (next-property-change 0 (concat " " text)) + ;; If the inserted text has properties, then preserve those. + (insert text) + ;; Otherwise preserve FORMAT's properties, like `format-spec'. + (insert-and-inherit text)) + ;; Delete the specifier body. + (delete-region (+ (match-beginning 0) (length text)) + (+ (match-end 0) (length text))) + ;; Delete the percent sign. + (delete-region (1- (match-beginning 0)) (match-beginning 0))))) + ;; Signal an error on bogus format strings. + (t + (error "Invalid format string")))) + (buffer-string))) + +;;; Missing from Emacs + +(defun magit-kill-this-buffer () + "Kill the current buffer." + (interactive) + (kill-buffer (current-buffer))) + +(defun magit--buffer-string (&optional min max trim) + "Like `buffer-substring-no-properties' but the arguments are optional. + +This combines the benefits of `buffer-string', `buffer-substring' +and `buffer-substring-no-properties' into one function that is +not as painful to use as the latter. I.e., you can write + (magit--buffer-string) +instead of + (buffer-substring-no-properties (point-min) + (point-max)) + +Optional MIN defaults to the value of `point-min'. +Optional MAX defaults to the value of `point-max'. + +If optional TRIM is non-nil, then all leading and trailing +whitespace is remove. If it is the newline character, then +one trailing newline is added." + ;; Lets write that one last time and be done with it: + (let ((str (buffer-substring-no-properties (or min (point-min)) + (or max (point-max))))) + (if trim + (concat (string-trim str) + (and (eq trim ?\n) "\n")) + str))) + +(defun magit--version> (v1 v2) + "Return t if version V1 is higher (younger) than V2. +This function should be named `version>' and be part of Emacs." + (version-list-< (version-to-list v2) (version-to-list v1))) + +(defun magit--version>= (v1 v2) + "Return t if version V1 is higher (younger) than or equal to V2. +This function should be named `version>=' and be part of Emacs." + (version-list-<= (version-to-list v2) (version-to-list v1))) + +;;; Kludges for Emacs Bugs + +(when (< emacs-major-version 27) + ;; Work around https://debbugs.gnu.org/cgi/bugreport.cgi?bug=21559. + ;; Fixed by cb55ccae8be946f1562d74718086a4c8c8308ee5 in Emacs 27.1. + (with-eval-after-load 'vc-git + (defun vc-git-conflicted-files (directory) + "Return the list of files with conflicts in DIRECTORY." + (let* ((status + (vc-git--run-command-string directory "diff-files" + "--name-status")) + (lines (when status (split-string status "\n" 'omit-nulls))) + files) + (dolist (line lines files) + (when (string-match "\\([ MADRCU?!]\\)[ \t]+\\(.+\\)" line) + (let ((state (match-string 1 line)) + (file (match-string 2 line))) + (when (equal state "U") + (push (expand-file-name file directory) files))))))))) + +(when (< emacs-major-version 27) + (defun vc-git--call@bug21559 (fn buffer command &rest args) + "Backport https://debbugs.gnu.org/cgi/bugreport.cgi?bug=21559." + (let ((process-environment process-environment)) + (when revert-buffer-in-progress-p + (push "GIT_OPTIONAL_LOCKS=0" process-environment)) + (apply fn buffer command args))) + (advice-add 'vc-git--call :around 'vc-git--call@bug21559) + + (defun vc-git-command@bug21559 + (fn buffer okstatus file-or-list &rest flags) + "Backport https://debbugs.gnu.org/cgi/bugreport.cgi?bug=21559." + (let ((process-environment process-environment)) + (when revert-buffer-in-progress-p + (push "GIT_OPTIONAL_LOCKS=0" process-environment)) + (apply fn buffer okstatus file-or-list flags))) + (advice-add 'vc-git-command :around 'vc-git-command@bug21559) + + (defun auto-revert-handler@bug21559 (fn) + "Backport https://debbugs.gnu.org/cgi/bugreport.cgi?bug=21559." + (let ((revert-buffer-in-progress-p t)) + (funcall fn))) + (advice-add 'auto-revert-handler :around 'auto-revert-handler@bug21559) + ) + +(defun magit-which-function () + "Return current function name based on point. + +This is a simple wrapper around `which-function', that resets +Imenu's potentially outdated and therefore unreliable cache by +setting `imenu--index-alist' to nil before calling that function." + (setq imenu--index-alist nil) + (which-function)) + +;;; Kludges for Custom + +(defun magit-custom-initialize-reset (symbol exp) + "Initialize SYMBOL based on EXP. +Set the value of the variable SYMBOL, using `set-default' +\(unlike `custom-initialize-reset', which uses the `:set' +function if any). The value is either the symbol's current +value (as obtained using the `:get' function), if any, or +the value in the symbol's `saved-value' property if any, or +\(last of all) the value of EXP." + (set-default-toplevel-value + symbol + (condition-case nil + (let ((def (default-toplevel-value symbol)) + (getter (get symbol 'custom-get))) + (if getter (funcall getter symbol) def)) + (error + (eval (let ((sv (get symbol 'saved-value))) + (if sv (car sv) exp))))))) + +(defun magit-hook-custom-get (symbol) + (if (symbol-file symbol 'defvar) + (default-toplevel-value symbol) + ;; + ;; Called by `custom-initialize-reset' on behalf of `symbol's + ;; `defcustom', which is being evaluated for the first time to + ;; set the initial value, but there's already a default value, + ;; which most likely was established by one or more `add-hook' + ;; calls. + ;; + ;; We combine the `standard-value' and the current value, while + ;; preserving the order established by `:options', and return + ;; the result of that to be used as the "initial" default value. + ;; + (let ((standard (eval (car (get symbol 'standard-value)))) + (current (default-toplevel-value symbol)) + (value nil)) + (dolist (fn (get symbol 'custom-options)) + (when (or (memq fn standard) + (memq fn current)) + (push fn value))) + (dolist (fn current) + (unless (memq fn value) + (push fn value))) + (nreverse value)))) + +;;; Kludges for Info Manuals + +;;;###autoload +(define-advice Info-follow-nearest-node (:around (fn &optional fork) gitman) + (let ((node (Info-get-token + (point) "\\*note[ \n\t]+" + "\\*note[ \n\t]+\\([^:]*\\):\\(:\\|[ \n\t]*(\\)?"))) + (if (and node (string-match "^(gitman)\\(.+\\)" node)) + (pcase magit-view-git-manual-method + ('info (funcall fn fork)) + ('man (require 'man) + (man (match-string 1 node))) + ('woman (require 'woman) + (woman (match-string 1 node))) + (_ (user-error "Invalid value for `magit-view-git-manual-method'"))) + (funcall fn fork)))) + +;; When making changes here, then also adjust the copy in docs/Makefile. +;;;###autoload +(define-advice org-man-export (:around (fn link description format) gitman) + (if (and (eq format 'texinfo) + (string-prefix-p "git" link)) + (string-replace "%s" link " +@ifinfo +@ref{%s,,,gitman,}. +@end ifinfo +@ifhtml +@html +the <a href=\"http://git-scm.com/docs/%s\">%s(1)</a> manpage. +@end html +@end ifhtml +@iftex +the %s(1) manpage. +@end iftex +") + (funcall fn link description format))) + +;;; Kludges for Package Managers + +(defun magit--chase-links (filename) + "Chase links in FILENAME until a name that is not a link. + +This is the same as `file-chase-links', except that it also handles +fake symlinks that are created by some source based package managers +\(Elpaca and Straight) on Windows. + +See <https://github.com/raxod502/straight.el/issues/520>." + (when-let* + ((manager (cond ((bound-and-true-p straight-symlink-mode) 'straight) + ((bound-and-true-p elpaca-no-symlink-mode) 'elpaca))) + (build (pcase manager + ('straight (bound-and-true-p straight-build-dir)) + ('elpaca (bound-and-true-p elpaca-builds-directory)))) + ((string-prefix-p build filename)) + (repo (pcase manager + ('straight + (and (bound-and-true-p straight-base-dir) + (expand-file-name "repos/magit/lisp/" straight-base-dir))) + ('elpaca + (and (bound-and-true-p elpaca-repos-directory) + (expand-file-name "magit/lisp/" elpaca-repos-directory)))))) + (setq filename (expand-file-name (file-name-nondirectory filename) repo))) + (file-chase-links filename)) + +;;; Kludges for older Emacs versions + +(if (fboundp 'with-connection-local-variables) + (defalias 'magit--with-connection-local-variables + #'with-connection-local-variables) + (defmacro magit--with-connection-local-variables (&rest body) + "Abridged `with-connection-local-variables' for pre Emacs 27 compatibility. +Bind shell file name and switch for remote execution. +`with-connection-local-variables' isn't available until Emacs 27. +This kludge provides the minimal functionality required by +Magit." + `(if (file-remote-p default-directory) + (pcase-let ((`(,shell-file-name ,shell-command-switch) + (with-no-warnings ; about unknown tramp functions + (require 'tramp) + (let ((vec (tramp-dissect-file-name + default-directory))) + (list (tramp-get-method-parameter + vec 'tramp-remote-shell) + (string-join (tramp-get-method-parameter + vec 'tramp-remote-shell-args) + " ")))))) + ,@body) + ,@body))) + +(put 'magit--with-connection-local-variables 'lisp-indent-function 'defun) + +;;; Miscellaneous + +(defun magit-message (format-string &rest args) + "Display a message at the bottom of the screen, or not. +Like `message', except that if the users configured option +`magit-no-message' to prevent the message corresponding to +FORMAT-STRING to be displayed, then don't." + (unless (--first (string-prefix-p it format-string) magit-no-message) + (apply #'message format-string args))) + +(defun magit-msg (format-string &rest args) + "Display a message at the bottom of the screen, but don't log it. +Like `message', except that `message-log-max' is bound to nil." + (let ((message-log-max nil)) + (apply #'message format-string args))) + +(defmacro magit--with-temp-position (buf pos &rest body) + (declare (indent 2)) + `(with-current-buffer ,buf + (save-excursion + (save-restriction + (widen) + (goto-char (or ,pos 1)) + ,@body)))) + +(defun magit--ellipsis (&optional where) + "Build an ellipsis always as string, depending on WHERE." + (if (stringp magit-ellipsis) + magit-ellipsis + (if-let ((pair (car (or + (alist-get (or where t) magit-ellipsis) + (alist-get t magit-ellipsis))))) + (pcase-let ((`(,fancy . ,universal) pair)) + (let ((ellipsis (if (and fancy (char-displayable-p fancy)) + fancy + universal))) + (if (characterp ellipsis) + (char-to-string ellipsis) + ellipsis))) + (user-error "Variable magit-ellipsis is invalid")))) + +(defun magit--ext-regexp-quote (str) + "Like `reqexp-quote', but for Extended Regular Expressions." + (let ((special (string-to-list "[*.\\?+^$({")) + (quoted nil)) + (mapc (lambda (c) + (when (memq c special) + (push ?\\ quoted)) + (push c quoted)) + str) + (concat (nreverse quoted)))) + +;;; _ +(provide 'magit-base) +;;; magit-base.el ends here diff --git a/emacs/elpa/magit-20241004.917/magit-bisect.el b/emacs/elpa/magit-20241004.917/magit-bisect.el @@ -0,0 +1,322 @@ +;;; magit-bisect.el --- Bisect support for Magit -*- lexical-binding:t -*- + +;; Copyright (C) 2008-2024 The Magit Project Contributors + +;; Author: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> +;; Maintainer: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> + +;; SPDX-License-Identifier: GPL-3.0-or-later + +;; Magit is free software: you can redistribute it and/or modify it +;; under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. +;; +;; Magit is distributed in the hope that it will be useful, but WITHOUT +;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +;; or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public +;; License for more details. +;; +;; You should have received a copy of the GNU General Public License +;; along with Magit. If not, see <https://www.gnu.org/licenses/>. + +;;; Commentary: + +;; Use a binary search to find the commit that introduced a bug. + +;;; Code: + +(require 'magit) + +;;; Options + +(defcustom magit-bisect-show-graph t + "Whether to use `--graph' in the log showing commits yet to be bisected." + :package-version '(magit . "2.8.0") + :group 'magit-status + :type 'boolean) + +(defface magit-bisect-good + '((t :foreground "DarkOliveGreen")) + "Face for good bisect revisions." + :group 'magit-faces) + +(defface magit-bisect-skip + '((t :foreground "DarkGoldenrod")) + "Face for skipped bisect revisions." + :group 'magit-faces) + +(defface magit-bisect-bad + '((t :foreground "IndianRed4")) + "Face for bad bisect revisions." + :group 'magit-faces) + +;;; Commands + +;;;###autoload (autoload 'magit-bisect "magit-bisect" nil t) +(transient-define-prefix magit-bisect () + "Narrow in on the commit that introduced a bug." + :man-page "git-bisect" + [:class transient-subgroups + :if-not magit-bisect-in-progress-p + ["Arguments" + ("-n" "Don't checkout commits" "--no-checkout") + ("-p" "Follow only first parent of a merge" "--first-parent" + :if (lambda () (magit-git-version>= "2.29"))) + (6 magit-bisect:--term-old + :if (lambda () (magit-git-version>= "2.7"))) + (6 magit-bisect:--term-new + :if (lambda () (magit-git-version>= "2.7")))] + ["Actions" + ("B" "Start" magit-bisect-start) + ("s" "Start script" magit-bisect-run)]] + ["Actions" + :if magit-bisect-in-progress-p + ("B" "Bad" magit-bisect-bad) + ("g" "Good" magit-bisect-good) + (6 "m" "Mark" magit-bisect-mark + :if (lambda () (magit-git-version>= "2.7"))) + ("k" "Skip" magit-bisect-skip) + ("r" "Reset" magit-bisect-reset) + ("s" "Run script" magit-bisect-run)]) + +(transient-define-argument magit-bisect:--term-old () + :description "Old/good term" + :class 'transient-option + :key "=o" + :argument "--term-old=") + +(transient-define-argument magit-bisect:--term-new () + :description "New/bad term" + :class 'transient-option + :key "=n" + :argument "--term-new=") + +;;;###autoload +(defun magit-bisect-start (bad good args) + "Start a bisect session. + +Bisecting a bug means to find the commit that introduced it. +This command starts such a bisect session by asking for a known +good and a known bad commit. To move the session forward use the +other actions from the bisect transient command (\ +\\<magit-status-mode-map>\\[magit-bisect])." + (interactive (if (magit-bisect-in-progress-p) + (user-error "Already bisecting") + (magit-bisect-start-read-args))) + (magit-bisect-start--assert bad good args) + (magit-repository-local-set 'bisect--first-parent + (transient-arg-value "--first-parent" args)) + (magit-git-bisect "start" (list args bad good) t)) + +(defun magit-bisect-start-read-args () + (let* ((args (transient-args 'magit-bisect)) + (bad (magit-read-branch-or-commit + (format "Start bisect with %s revision" + (or (transient-arg-value "--term-new=" args) + "bad"))))) + (list bad + (magit-read-other-branch-or-commit + (format "%s revision" (or (transient-arg-value "--term-old=" args) + "Good")) + bad) + args))) + +(defun magit-bisect-start--assert (bad good args) + (unless (magit-rev-ancestor-p good bad) + (user-error + "The %s revision (%s) has to be an ancestor of the %s one (%s)" + (or (transient-arg-value "--term-old=" args) "good") + good + (or (transient-arg-value "--term-new=" args) "bad") + bad)) + (when (magit-anything-modified-p) + (user-error "Cannot bisect with uncommitted changes"))) + +;;;###autoload +(defun magit-bisect-reset () + "After bisecting, cleanup bisection state and return to original `HEAD'." + (interactive) + (magit-confirm 'reset-bisect) + (magit-run-git "bisect" "reset") + (magit-repository-local-delete 'bisect--first-parent) + (ignore-errors + (delete-file (expand-file-name "BISECT_CMD_OUTPUT" (magit-gitdir))))) + +;;;###autoload +(defun magit-bisect-good () + "While bisecting, mark the current commit as good. +Use this after you have asserted that the commit does not contain +the bug in question." + (interactive) + (magit-git-bisect (or (cadr (magit-bisect-terms)) + (user-error "Not bisecting")))) + +;;;###autoload +(defun magit-bisect-bad () + "While bisecting, mark the current commit as bad. +Use this after you have asserted that the commit does contain the +bug in question." + (interactive) + (magit-git-bisect (or (car (magit-bisect-terms)) + (user-error "Not bisecting")))) + +;;;###autoload +(defun magit-bisect-mark () + "While bisecting, mark the current commit with a bisect term. +During a bisect using alternate terms, commits can still be +marked with `magit-bisect-good' and `magit-bisect-bad', as those +commands map to the correct term (\"good\" to --term-old's value +and \"bad\" to --term-new's). However, in some cases, it can be +difficult to keep that mapping straight in your head; this +command provides an interface that exposes the underlying terms." + (interactive) + (magit-git-bisect + (pcase-let ((`(,term-new ,term-old) (or (magit-bisect-terms) + (user-error "Not bisecting")))) + (pcase (read-char-choice + (format "Mark HEAD as %s ([n]ew) or %s ([o]ld)" + term-new term-old) + (list ?n ?o)) + (?n term-new) + (?o term-old))))) + +;;;###autoload +(defun magit-bisect-skip () + "While bisecting, skip the current commit. +Use this if for some reason the current commit is not a good one +to test. This command lets Git choose a different one." + (interactive) + (magit-git-bisect "skip")) + +;;;###autoload +(defun magit-bisect-run (cmdline &optional bad good args) + "Bisect automatically by running commands after each step. + +Unlike `git bisect run' this can be used before bisecting has +begun. In that case it behaves like `git bisect start; git +bisect run'." + (interactive (let ((args (and (not (magit-bisect-in-progress-p)) + (magit-bisect-start-read-args)))) + (cons (read-shell-command "Bisect shell command: ") args))) + (when (and bad good) + (magit-bisect-start--assert bad good args) + ;; Avoid `magit-git-bisect' because it's asynchronous, but the + ;; next `git bisect run' call requires the bisect to be started. + (magit-with-toplevel + (magit-process-git + (list :file (expand-file-name "BISECT_CMD_OUTPUT" (magit-gitdir))) + (magit-process-git-arguments + (list "bisect" "start" bad good args))) + (magit-refresh))) + (magit--with-connection-local-variables + (magit-git-bisect "run" (list shell-file-name + shell-command-switch cmdline)))) + +(defun magit-git-bisect (subcommand &optional args no-assert) + (unless (or no-assert (magit-bisect-in-progress-p)) + (user-error "Not bisecting")) + (message "Bisecting...") + (magit-with-toplevel + (magit-run-git-async "bisect" subcommand args)) + (set-process-sentinel + magit-this-process + (lambda (process event) + (when (memq (process-status process) '(exit signal)) + (if (> (process-exit-status process) 0) + (magit-process-sentinel process event) + (process-put process 'inhibit-refresh t) + (magit-process-sentinel process event) + (when (buffer-live-p (process-buffer process)) + (with-current-buffer (process-buffer process) + (when-let* ((section (magit-section-at)) + (output (buffer-substring-no-properties + (oref section content) + (oref section end)))) + (with-temp-file + (expand-file-name "BISECT_CMD_OUTPUT" (magit-gitdir)) + (insert output))))) + (magit-refresh)) + (message "Bisecting...done"))))) + +;;; Sections + +(defun magit-bisect-in-progress-p () + (file-exists-p (expand-file-name "BISECT_LOG" (magit-gitdir)))) + +(defun magit-bisect-terms () + (magit-file-lines (expand-file-name "BISECT_TERMS" (magit-gitdir)))) + +(defun magit-insert-bisect-output () + "While bisecting, insert section with output from `git bisect'." + (when (magit-bisect-in-progress-p) + (let* ((lines + (or (magit-file-lines + (expand-file-name "BISECT_CMD_OUTPUT" (magit-gitdir))) + (list "Bisecting: (no saved bisect output)" + "It appears you have invoked `git bisect' from a shell." + "There is nothing wrong with that, we just cannot display" + "anything useful here. Consult the shell output instead."))) + (done-re "^\\([a-z0-9]\\{40,\\}\\) is the first bad commit$") + (bad-line (or (and (string-match done-re (car lines)) + (pop lines)) + (--first (string-match done-re it) lines)))) + (magit-insert-section ((eval (if bad-line 'commit 'bisect-output)) + (and bad-line (match-string 1 bad-line))) + (magit-insert-heading + (propertize (or bad-line (pop lines)) + 'font-lock-face 'magit-section-heading)) + (dolist (line lines) + (insert line "\n")))) + (insert "\n"))) + +(defun magit-insert-bisect-rest () + "While bisecting, insert section visualizing the bisect state." + (when (magit-bisect-in-progress-p) + (magit-insert-section (bisect-view) + (magit-insert-heading t "Bisect Rest") + (magit-git-wash (apply-partially #'magit-log-wash-log 'bisect-vis) + "bisect" "visualize" "git" "log" + "--format=%h%x00%D%x00%s" "--decorate=full" + (and magit-bisect-show-graph "--graph") + (and (magit-repository-local-get 'bisect--first-parent) + "--first-parent"))))) + +(defun magit-insert-bisect-log () + "While bisecting, insert section logging bisect progress." + (when (magit-bisect-in-progress-p) + (magit-insert-section (bisect-log) + (magit-insert-heading t "Bisect Log") + (magit-git-wash #'magit-wash-bisect-log "bisect" "log") + (insert ?\n)))) + +(defun magit-wash-bisect-log (_args) + (let (beg) + (while (progn (setq beg (point-marker)) + (re-search-forward + "^\\(\\(?:git bisect\\|# status:\\) [^\n]+\n\\)" nil t)) + (if (string-prefix-p "# status:" (match-string 1)) + (magit-delete-match) + (magit-bind-match-strings (heading) nil + (magit-delete-match) + (save-restriction + (narrow-to-region beg (point)) + (goto-char (point-min)) + (magit-insert-section (bisect-item heading t) + (insert (propertize heading 'font-lock-face + 'magit-section-secondary-heading)) + (magit-insert-heading) + (magit-wash-sequence + (apply-partially #'magit-log-wash-rev 'bisect-log + (magit-abbrev-length))) + (insert ?\n)))))) + (when (re-search-forward + "# first bad commit: \\[\\([a-z0-9]\\{40,\\}\\)\\] [^\n]+\n" nil t) + (magit-bind-match-strings (hash) nil + (magit-delete-match) + (magit-insert-section (bisect-item) + (insert hash " is the first bad commit\n")))))) + +;;; _ +(provide 'magit-bisect) +;;; magit-bisect.el ends here diff --git a/emacs/elpa/magit-20241004.917/magit-blame.el b/emacs/elpa/magit-20241004.917/magit-blame.el @@ -0,0 +1,997 @@ +;;; magit-blame.el --- Blame support for Magit -*- lexical-binding:t -*- + +;; Copyright (C) 2008-2024 The Magit Project Contributors + +;; Author: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> +;; Maintainer: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> + +;; SPDX-License-Identifier: GPL-3.0-or-later + +;; Magit is free software: you can redistribute it and/or modify it +;; under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. +;; +;; Magit is distributed in the hope that it will be useful, but WITHOUT +;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +;; or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public +;; License for more details. +;; +;; You should have received a copy of the GNU General Public License +;; along with Magit. If not, see <https://www.gnu.org/licenses/>. + +;;; Commentary: + +;; Annotates each line in file-visiting buffer with information from +;; the revision which last modified the line. + +;;; Code: + +(require 'magit) + +;;; Options + +(defgroup magit-blame nil + "Blame support for Magit." + :link '(info-link "(magit)Blaming") + :group 'magit-modes) + +(defcustom magit-blame-styles + '((headings + (heading-format . "%-20a %C %s\n")) + (highlight + (highlight-face . magit-blame-highlight)) + (lines + (show-lines . t) + (show-message . t))) + "List of styles used to visualize blame information. + +The style used in the current buffer can be cycled from the blame +popup. Blame commands (except `magit-blame-echo') use the first +style as the initial style when beginning to blame in a buffer. + +Each entry has the form (IDENT (KEY . VALUE)...). IDENT has +to be a symbol uniquely identifying the style. The following +KEYs are recognized: + + `show-lines' + Whether to prefix each chunk of lines with a thin line. + This has no effect if `heading-format' is non-nil. + `show-message' + Whether to display a commit's summary line in the echo area + when crossing chunks. + `highlight-face' + Face used to highlight the first line of each chunk. + If this is nil, then those lines are not highlighted. + `heading-format' + String specifying the information to be shown above each + chunk of lines. It must end with a newline character. + `margin-format' + String specifying the information to be shown in the left + buffer margin. It must NOT end with a newline character. + This can also be a list of formats used for the lines at + the same positions within the chunk. If the chunk has + more lines than formats are specified, then the last is + repeated. WARNING: Adding this key affects performance; + see the note at the end of this docstring. + `margin-width' + Width of the margin, provided `margin-format' is non-nil. + `margin-face' + Face used in the margin, provided `margin-format' is + non-nil. This face is used in combination with the faces + that are specific to the used %-specs. If this is nil, + then `magit-blame-margin' is used. + `margin-body-face' + Face used in the margin for all but first line of a chunk. + This face is used in combination with the faces that are + specific to the used %-specs. This can also be a list of + faces (usually one face), in which case only these faces + are used and the %-spec faces are ignored. A good value + might be `(magit-blame-dimmed)'. If this is nil, then + the same face as for the first line is used. + +The following %-specs can be used in `heading-format' and +`margin-format': + + %H hash using face `magit-blame-hash' + %s summary using face `magit-blame-summary' + %a author using face `magit-blame-name' + %A author time using face `magit-blame-date' + %c committer using face `magit-blame-name' + %C committer time using face `magit-blame-date' + +Additionally if `margin-format' ends with %f, then the string +that is displayed in the margin is made at least `margin-width' +characters wide, which may be desirable if the used face sets +the background color. + +Blame information is displayed using overlays. Such extensive +use of overlays is known to slow down even basic operations, such +as moving the cursor. To reduce the number of overlays the margin +style had to be removed from the default value of this option. + +Note that the margin overlays are created even if another style +is currently active. This can only be prevented by not even +defining a style that uses the margin. If you want to use this +style anyway, you can restore this definition, which used to be +part of the default value: + + (margin + (margin-format . (\" %s%f\" \" %C %a\" \" %H\")) + (margin-width . 42) + (margin-face . magit-blame-margin) + (margin-body-face . (magit-blame-dimmed)))" + :package-version '(magit . "2.13.0") + :group 'magit-blame + :type 'string) + +(defcustom magit-blame-echo-style 'lines + "The blame visualization style used by `magit-blame-echo'. +A symbol that has to be used as the identifier for one of the +styles defined in `magit-blame-styles'." + :package-version '(magit . "2.13.0") + :group 'magit-blame + :type 'symbol) + +(defcustom magit-blame-time-format "%F %H:%M" + "Format for time strings in blame headings." + :group 'magit-blame + :type 'string) + +(defcustom magit-blame-read-only t + "Whether to initially make the blamed buffer read-only." + :package-version '(magit . "2.13.0") + :group 'magit-blame + :type 'boolean) + +(defcustom magit-blame-disable-modes '(fci-mode yascroll-bar-mode) + "List of modes not compatible with Magit-Blame mode. +This modes are turned off when Magit-Blame mode is turned on, +and then turned on again when turning off the latter." + :group 'magit-blame + :type '(repeat (symbol :tag "Mode"))) + +(defcustom magit-blame-mode-lighter " Blame" + "The mode-line lighter of the Magit-Blame mode." + :group 'magit-blame + :type '(choice (const :tag "No lighter" "") string)) + +(defcustom magit-blame-goto-chunk-hook + '(magit-blame-maybe-update-revision-buffer + magit-blame-maybe-show-message) + "Hook run after point entered another chunk." + :package-version '(magit . "2.13.0") + :group 'magit-blame + :type 'hook + :get #'magit-hook-custom-get + :options '(magit-blame-maybe-update-revision-buffer + magit-blame-maybe-show-message)) + +;;; Faces + +(defface magit-blame-highlight + `((((class color) (background light)) + ,@(and (>= emacs-major-version 27) '(:extend t)) + :background "grey80" + :foreground "black") + (((class color) (background dark)) + ,@(and (>= emacs-major-version 27) '(:extend t)) + :background "grey25" + :foreground "white")) + "Face used for highlighting when blaming. +Also see option `magit-blame-styles'." + :group 'magit-faces) + +(defface magit-blame-margin + '((t :inherit magit-blame-highlight + :weight normal + :slant normal)) + "Face used for the blame margin by default when blaming. +Also see option `magit-blame-styles'." + :group 'magit-faces) + +(defface magit-blame-dimmed + '((t :inherit magit-dimmed + :weight normal + :slant normal)) + "Face used for the blame margin in some cases when blaming. +Also see option `magit-blame-styles'." + :group 'magit-faces) + +(defface magit-blame-heading + `((t ,@(and (>= emacs-major-version 27) '(:extend t)) + :inherit magit-blame-highlight + :weight normal + :slant normal)) + "Face used for blame headings by default when blaming. +Also see option `magit-blame-styles'." + :group 'magit-faces) + +(defface magit-blame-summary '((t nil)) + "Face used for commit summaries when blaming." + :group 'magit-faces) + +(defface magit-blame-hash '((t nil)) + "Face used for commit hashes when blaming." + :group 'magit-faces) + +(defface magit-blame-name '((t nil)) + "Face used for author and committer names when blaming." + :group 'magit-faces) + +(defface magit-blame-date '((t nil)) + "Face used for dates when blaming." + :group 'magit-faces) + +;;; Variables + +(defvar-local magit-blame-buffer-read-only nil) +(defvar-local magit-blame-cache nil) +(defvar-local magit-blame-disabled-modes nil) +(defvar-local magit-blame-process nil) +(defvar-local magit-blame-recursive-p nil) +(defvar-local magit-blame-type nil) +(defvar-local magit-blame-separator nil) +(defvar-local magit-blame-previous-chunk nil) + +(defvar-local magit-blame--make-margin-overlays nil) +(defvar-local magit-blame--style nil) + +;;; Chunks + +(defclass magit-blame-chunk () + (;; <orig-rev> <orig-line> <final-line> <num-lines> + (orig-rev :initarg :orig-rev) + (orig-line :initarg :orig-line) + (final-line :initarg :final-line) + (num-lines :initarg :num-lines) + ;; previous <prev-rev> <prev-file> + (prev-rev :initform nil) + (prev-file :initform nil) + ;; filename <orig-file> + (orig-file))) + +(defun magit-current-blame-chunk (&optional type noerror) + (or (and (not (and type (not (eq type magit-blame-type)))) + (magit-blame-chunk-at (point))) + (and type + (let ((rev (or magit-buffer-refname magit-buffer-revision)) + (file (and (not (derived-mode-p 'dired-mode)) + (magit-file-relative-name + nil (not magit-buffer-file-name)))) + (line (format "%d,+1" (line-number-at-pos)))) + (cond (file (with-temp-buffer + (magit-with-toplevel + (magit-git-insert + "blame" "--porcelain" + (if (memq magit-blame-type '(final removal)) + (cons "--reverse" (magit-blame-arguments)) + (magit-blame-arguments)) + "-L" line rev "--" file) + (goto-char (point-min)) + (if (eobp) + (unless noerror + (error "Cannot get blame chunk at eob")) + (car (magit-blame--parse-chunk type)))))) + (noerror nil) + ((error "Buffer does not visit a tracked file"))))))) + +(defun magit-blame-chunk-at (pos) + (--some (overlay-get it 'magit-blame-chunk) + (overlays-at pos))) + +(defun magit-blame--overlay-at (&optional pos key) + (unless pos + (setq pos (point))) + (--first (overlay-get it (or key 'magit-blame-chunk)) + (nconc (overlays-at pos) + (overlays-in pos pos)))) + +;;; Keymaps + +(defvar-keymap magit-blame-mode-map + :doc "Keymap for `magit-blame-mode'. +Note that most blaming key bindings are defined +in `magit-blame-read-only-mode-map' instead." + "C-c C-q" #'magit-blame-quit) + +(defvar-keymap magit-blame-read-only-mode-map + :doc "Keymap for `magit-blame-read-only-mode'." + "C-m" #'magit-show-commit + "p" #'magit-blame-previous-chunk + "P" #'magit-blame-previous-chunk-same-commit + "n" #'magit-blame-next-chunk + "N" #'magit-blame-next-chunk-same-commit + "b" #'magit-blame-addition + "r" #'magit-blame-removal + "f" #'magit-blame-reverse + "B" #'magit-blame + "c" #'magit-blame-cycle-style + "q" #'magit-blame-quit + "M-w" #'magit-blame-copy-hash + "SPC" #'magit-diff-show-or-scroll-up + "S-SPC" #'magit-diff-show-or-scroll-down + "DEL" #'magit-diff-show-or-scroll-down) + +;;; Modes +;;;; Base Mode + +(define-minor-mode magit-blame-mode + "Display blame information inline." + :lighter magit-blame-mode-lighter + :interactive nil + (cond (magit-blame-mode + (unless arg + ;; Emacs < 28.1 doesn't support `:interactive'. + (setq magit-blame-mode nil) + (user-error + (concat "Don't call `magit-blame-mode' directly; " + "instead use `magit-blame'"))) + (add-hook 'after-save-hook #'magit-blame--refresh t t) + (add-hook 'post-command-hook #'magit-blame-goto-chunk-hook t t) + (add-hook 'before-revert-hook #'magit-blame--remove-overlays t t) + (add-hook 'after-revert-hook #'magit-blame--refresh t t) + (add-hook 'read-only-mode-hook #'magit-blame-toggle-read-only t t) + (setq magit-blame-buffer-read-only buffer-read-only) + (when (or magit-blame-read-only magit-buffer-file-name) + (read-only-mode 1)) + (dolist (mode magit-blame-disable-modes) + (when (and (boundp mode) (symbol-value mode)) + (funcall mode -1) + (push mode magit-blame-disabled-modes))) + (setq magit-blame-separator (magit-blame--format-separator)) + (unless magit-blame--style + (setq magit-blame--style (car magit-blame-styles))) + (setq magit-blame--make-margin-overlays + (and (cl-find-if (lambda (style) + (assq 'margin-format (cdr style))) + magit-blame-styles))) + (magit-blame--update-margin 'enable)) + (t + (when (process-live-p magit-blame-process) + (kill-process magit-blame-process) + (while magit-blame-process + (sit-for 0.01))) ; avoid racing the sentinel + (remove-hook 'after-save-hook #'magit-blame--refresh t) + (remove-hook 'post-command-hook #'magit-blame-goto-chunk-hook t) + (remove-hook 'before-revert-hook #'magit-blame--remove-overlays t) + (remove-hook 'after-revert-hook #'magit-blame--refresh t) + (remove-hook 'read-only-mode-hook #'magit-blame-toggle-read-only t) + (unless magit-blame-buffer-read-only + (read-only-mode -1)) + (magit-blame-read-only-mode -1) + (dolist (mode magit-blame-disabled-modes) + (funcall mode 1)) + (kill-local-variable 'magit-blame-disabled-modes) + (kill-local-variable 'magit-blame-type) + (kill-local-variable 'magit-blame--style) + (magit-blame--update-margin 'disable) + (magit-blame--remove-overlays)))) + +(defun magit-blame--refresh () + (magit-blame--run (magit-blame-arguments))) + +(defun magit-blame-goto-chunk-hook () + (let ((chunk (magit-blame-chunk-at (point)))) + (when (cl-typep chunk 'magit-blame-chunk) + (unless (eq chunk magit-blame-previous-chunk) + (run-hooks 'magit-blame-goto-chunk-hook)) + (setq magit-blame-previous-chunk chunk)))) + +(defun magit-blame-toggle-read-only () + (magit-blame-read-only-mode (if buffer-read-only 1 -1))) + +;;;; Read-Only Mode + +(define-minor-mode magit-blame-read-only-mode + "Provide keybindings for Magit-Blame mode. + +This minor-mode provides the key bindings for Magit-Blame mode, +but only when Read-Only mode is also enabled because these key +bindings would otherwise conflict badly with regular bindings. + +When both Magit-Blame mode and Read-Only mode are enabled, then +this mode gets automatically enabled too and when one of these +modes is toggled, then this mode also gets toggled automatically. + +\\{magit-blame-read-only-mode-map}") + +;;;; Kludges + +(defun magit-blame-put-keymap-before-view-mode () + "Put `magit-blame-read-only-mode' ahead of `view-mode' in `minor-mode-map-alist'." + (when-let ((entry (assq 'magit-blame-read-only-mode + (cl-member 'view-mode minor-mode-map-alist + :key #'car)))) + (setq minor-mode-map-alist + (cons entry + (delq entry minor-mode-map-alist)))) + (remove-hook 'view-mode-hook #'magit-blame-put-keymap-before-view-mode)) + +(add-hook 'view-mode-hook #'magit-blame-put-keymap-before-view-mode) + +;;; Process + +(defun magit-blame--run (args) + (magit-with-toplevel + (unless magit-blame-mode + (magit-blame-mode 1)) + (message "Blaming...") + (magit-blame-run-process + (or magit-buffer-refname magit-buffer-revision) + (magit-file-relative-name nil (not magit-buffer-file-name)) + (if (memq magit-blame-type '(final removal)) + (cons "--reverse" args) + args) + (list (line-number-at-pos (window-start)) + (line-number-at-pos (1- (window-end nil t))))) + (set-process-sentinel magit-this-process + #'magit-blame-process-quickstart-sentinel))) + +(defun magit-blame-run-process (revision file args &optional lines) + (let ((process (magit-parse-git-async + "blame" "--incremental" args + (and lines (list "-L" (apply #'format "%s,%s" lines))) + revision "--" file))) + (set-process-filter process #'magit-blame-process-filter) + (set-process-sentinel process #'magit-blame-process-sentinel) + (process-put process 'arguments (list revision file args)) + (setq magit-blame-cache (make-hash-table :test #'equal)) + (setq magit-blame-process process))) + +(defun magit-blame-process-quickstart-sentinel (process event) + (when (memq (process-status process) '(exit signal)) + (magit-blame-process-sentinel process event t) + (magit-blame-assert-buffer process) + (with-current-buffer (process-get process 'command-buf) + (when magit-blame-mode + (let ((default-directory (magit-toplevel))) + (apply #'magit-blame-run-process + (process-get process 'arguments))))))) + +(defun magit-blame-process-sentinel (process _event &optional quiet) + (let ((status (process-status process))) + (when (memq status '(exit signal)) + (kill-buffer (process-buffer process)) + (kill-buffer (process-get process 'stderr-buf)) + (if (and (eq status 'exit) + (zerop (process-exit-status process))) + (unless quiet + (message "Blaming...done")) + (magit-blame-assert-buffer process) + (with-current-buffer (process-get process 'command-buf) + (if magit-blame-mode + (progn (magit-blame-mode -1) + (message "Blaming...failed")) + (message "Blaming...aborted")))) + (kill-local-variable 'magit-blame-process)))) + +(defun magit-blame-process-filter (process string) + (internal-default-process-filter process string) + (let ((buf (process-get process 'command-buf)) + (pos (process-get process 'parsed)) + (mark (process-mark process)) + type cache) + (with-current-buffer buf + (setq type magit-blame-type) + (setq cache magit-blame-cache)) + (with-current-buffer (process-buffer process) + (goto-char pos) + (while (and (< (point) mark) + (save-excursion (re-search-forward "^filename .+\n" nil t))) + (pcase-let* ((`(,chunk ,revinfo) + (magit-blame--parse-chunk type)) + (rev (oref chunk orig-rev))) + (if revinfo + (puthash rev revinfo cache) + (setq revinfo + (or (gethash rev cache) + (puthash rev (magit-blame--commit-alist rev) cache)))) + (magit-blame--make-overlays buf chunk revinfo)) + (process-put process 'parsed (point)))))) + +(defun magit-blame--parse-chunk (type) + (let (chunk revinfo) + (unless (looking-at "^\\(.\\{40,\\}\\) \\([0-9]+\\) \\([0-9]+\\) \\([0-9]+\\)") + (error "Blaming failed due to unexpected output: %s" + (buffer-substring-no-properties (point) (line-end-position)))) + (with-slots (orig-rev orig-file prev-rev prev-file) + (setq chunk (magit-blame-chunk + :orig-rev (match-string 1) + :orig-line (string-to-number (match-string 2)) + :final-line (string-to-number (match-string 3)) + :num-lines (string-to-number (match-string 4)))) + (forward-line) + (let (done) + (while (not done) + (cond ((looking-at "^filename \\(.+\\)") + (setq done t) + (setf orig-file (magit-decode-git-path (match-string 1)))) + ((looking-at "^previous \\(.\\{40,\\}\\) \\(.+\\)") + (setf prev-rev (match-string 1)) + (setf prev-file (magit-decode-git-path (match-string 2)))) + ((looking-at "^\\([^ ]+\\) \\(.+\\)") + (push (cons (match-string 1) + (match-string 2)) + revinfo))) + (forward-line))) + (when (and (eq type 'removal) prev-rev) + (cl-rotatef orig-rev prev-rev) + (cl-rotatef orig-file prev-file) + (setq revinfo nil))) + (list chunk revinfo))) + +(defun magit-blame--commit-alist (rev) + (cl-mapcar 'cons + '("summary" + "author" "author-time" "author-tz" + "committer" "committer-time" "committer-tz") + (split-string (magit-rev-format "%s\v%an\v%ad\v%cn\v%cd" rev + "--date=format:%s\v%z") + "\v"))) + +(defun magit-blame-assert-buffer (process) + (unless (buffer-live-p (process-get process 'command-buf)) + (kill-process process) + (user-error "Buffer being blamed has been killed"))) + +;;; Display + +(defvar-local magit-blame--previous-margin-width nil) + +(defsubst magit-blame--style-get (key) + (cdr (assoc key (cdr magit-blame--style)))) + +(defun magit-blame--make-overlays (buf chunk revinfo) + (with-current-buffer buf + (save-excursion + (save-restriction + (widen) + (let* ((line (oref chunk final-line)) + (beg (magit-blame--line-beginning-position line)) + (end (magit-blame--line-beginning-position + (+ line (oref chunk num-lines)))) + (before (magit-blame-chunk-at (1- beg)))) + (when (and before + (equal (oref before orig-rev) + (oref chunk orig-rev))) + (setq beg (magit-blame--line-beginning-position + (oset chunk final-line (oref before final-line)))) + (cl-incf (oref chunk num-lines) + (oref before num-lines))) + (magit-blame--remove-overlays beg end) + (when magit-blame--make-margin-overlays + (magit-blame--make-margin-overlays chunk revinfo beg end)) + (magit-blame--make-heading-overlay chunk revinfo beg end) + (magit-blame--make-highlight-overlay chunk beg)))))) + +(defun magit-blame--line-beginning-position (line) + (save-excursion + (goto-char (point-min)) + (forward-line (1- line)) + (point))) + +(defun magit-blame--make-margin-overlays (chunk revinfo beg end) + (save-excursion + (let ((line 0)) + (goto-char beg) + (while (< (point) end) + (magit-blame--make-margin-overlay chunk revinfo line) + (forward-line) + (cl-incf line))))) + +(defun magit-blame--make-margin-overlay (chunk revinfo line) + (let* ((end (line-end-position)) + ;; If possible avoid putting this on the first character + ;; of the line to avoid a conflict with the line overlay. + (beg (min (1+ (line-beginning-position)) end)) + (ov (make-overlay beg end))) + (overlay-put ov 'magit-blame-chunk chunk) + (overlay-put ov 'magit-blame-revinfo revinfo) + (overlay-put ov 'magit-blame-margin line) + (magit-blame--update-margin-overlay ov))) + +(defun magit-blame--make-heading-overlay (chunk revinfo beg end) + (let ((ov (make-overlay beg end))) + (overlay-put ov 'magit-blame-chunk chunk) + (overlay-put ov 'magit-blame-revinfo revinfo) + (overlay-put ov 'magit-blame-heading t) + (magit-blame--update-heading-overlay ov))) + +(defun magit-blame--make-highlight-overlay (chunk beg) + (let ((ov (make-overlay beg (save-excursion + (goto-char beg) + (1+ (line-end-position)))))) + (overlay-put ov 'magit-blame-chunk chunk) + (overlay-put ov 'magit-blame-highlight t) + (magit-blame--update-highlight-overlay ov))) + +(defun magit-blame--update-margin (&optional action) + (when (eq action 'enable) + (setq magit-blame--previous-margin-width left-margin-width)) + (setq left-margin-width + (if (eq action 'disable) + (prog1 magit-blame--previous-margin-width + (setq magit-blame--previous-margin-width nil)) + (or (magit-blame--style-get 'margin-width) + magit-blame--previous-margin-width))) + (set-window-buffer (selected-window) (current-buffer))) + +(defun magit-blame--update-overlays () + (save-restriction + (widen) + (dolist (ov (overlays-in (point-min) (point-max))) + (cond ((overlay-get ov 'magit-blame-heading) + (magit-blame--update-heading-overlay ov)) + ((overlay-get ov 'magit-blame-margin) + (magit-blame--update-margin-overlay ov)) + ((overlay-get ov 'magit-blame-highlight) + (magit-blame--update-highlight-overlay ov)))))) + +(defun magit-blame--update-margin-overlay (ov) + (overlay-put + ov 'before-string + (and (magit-blame--style-get 'margin-width) + (propertize + "o" 'display + (list (list 'margin 'left-margin) + (let ((line (overlay-get ov 'magit-blame-margin)) + (format (magit-blame--style-get 'margin-format)) + (face (magit-blame--style-get 'margin-face))) + (magit-blame--format-string + ov + (or (and (atom format) + format) + (nth line format) + (car (last format))) + (or (and (not (zerop line)) + (magit-blame--style-get 'margin-body-face)) + face + 'magit-blame-margin)))))))) + +(defun magit-blame--update-heading-overlay (ov) + (overlay-put + ov 'before-string + (if-let ((format (magit-blame--style-get 'heading-format))) + ;; Use `default' as the last face to avoid picking up any face + ;; attributes from the first character of the text on which we + ;; put the overlay. See #5233. + (magit-blame--format-string ov format '(magit-blame-heading default)) + (and (magit-blame--style-get 'show-lines) + (or (not (magit-blame--style-get 'margin-format)) + (save-excursion + (goto-char (overlay-start ov)) + ;; Special case of the special case described in + ;; `magit-blame--make-margin-overlay'. For empty + ;; lines it is not possible to show both overlays + ;; without the line being too high. + (not (= (point) (line-end-position))))) + magit-blame-separator)))) + +(defun magit-blame--update-highlight-overlay (ov) + (overlay-put ov 'font-lock-face (magit-blame--style-get 'highlight-face))) + +(defun magit-blame--format-string (ov format face) + (let* ((chunk (overlay-get ov 'magit-blame-chunk)) + (revinfo (overlay-get ov 'magit-blame-revinfo)) + (key (list format face)) + (string (cdr (assoc key revinfo)))) + (unless string + (setq string + (and format + (magit-blame--format-string-1 (oref chunk orig-rev) + revinfo format face))) + (nconc revinfo (list (cons key string)))) + string)) + +(defun magit-blame--format-string-1 (rev revinfo format face) + (let ((str + (if (string-match-p "\\`0\\{40,\\}\\'" rev) + (propertize (concat (if (string-prefix-p "\s" format) "\s" "") + "Not Yet Committed" + (if (string-suffix-p "\n" format) "\n" "")) + 'font-lock-face face) + (magit--format-spec + (propertize format 'font-lock-face face) + (cl-flet* ((p0 (s f) + (propertize s 'font-lock-face + (if face (cons f (ensure-list face)) f))) + (p1 (k f) + (p0 (cdr (assoc k revinfo)) f)) + (p2 (k1 k2 f) + (p0 (magit-blame--format-time-string + (cdr (assoc k1 revinfo)) + (cdr (assoc k2 revinfo))) + f))) + `((?H . ,(p0 rev 'magit-blame-hash)) + (?s . ,(p1 "summary" 'magit-blame-summary)) + (?a . ,(p1 "author" 'magit-blame-name)) + (?c . ,(p1 "committer" 'magit-blame-name)) + (?A . ,(p2 "author-time" "author-tz" 'magit-blame-date)) + (?C . ,(p2 "committer-time" "committer-tz" 'magit-blame-date)) + (?f . ""))))))) + (if-let ((width (and (string-suffix-p "%f" format) + (magit-blame--style-get 'margin-width)))) + (concat str + (propertize (make-string (max 0 (- width (length str))) ?\s) + 'font-lock-face face)) + str))) + +(defun magit-blame--format-separator () + (propertize + (concat (propertize "\s" 'display '(space :height (2))) + (propertize "\n" 'line-height t)) + 'font-lock-face `(:background + ,(face-attribute 'magit-blame-heading + :background nil t) + ,@(and (>= emacs-major-version 27) '(:extend t))))) + +(defun magit-blame--format-time-string (time tz) + (let* ((time-format (or (magit-blame--style-get 'time-format) + magit-blame-time-format)) + (tz-in-second (and (string-search "%z" time-format) + (car (last (parse-time-string tz)))))) + (format-time-string time-format + (seconds-to-time (string-to-number time)) + tz-in-second))) + +(defun magit-blame--remove-overlays (&optional beg end) + (save-restriction + (widen) + (dolist (ov (overlays-in (or beg (point-min)) + (or end (point-max)))) + (when (overlay-get ov 'magit-blame-chunk) + (delete-overlay ov))))) + +(defun magit-blame-maybe-show-message () + (when (magit-blame--style-get 'show-message) + (let ((message-log-max 0)) + (if-let ((msg (cdr (assoc "summary" + (gethash (oref (magit-current-blame-chunk) + orig-rev) + magit-blame-cache))))) + (progn (set-text-properties 0 (length msg) nil msg) + (message msg)) + (message "Commit data not available yet. Still blaming."))))) + +;;; Commands + +;;;###autoload (autoload 'magit-blame-echo "magit-blame" nil t) +(transient-define-suffix magit-blame-echo (args) + "For each line show the revision in which it was added. +Show the information about the chunk at point in the echo area +when moving between chunks. Unlike other blaming commands, do +not turn on `read-only-mode'." + :if (lambda () + (and buffer-file-name + (or (not magit-blame-mode) + buffer-read-only))) + (interactive (list (magit-blame-arguments))) + (when magit-buffer-file-name + (user-error "Blob buffers aren't supported")) + (setq-local magit-blame--style + (assq magit-blame-echo-style magit-blame-styles)) + (setq-local magit-blame-disable-modes + (cons 'eldoc-mode magit-blame-disable-modes)) + (if (not magit-blame-mode) + (let ((magit-blame-read-only nil)) + (magit-blame--pre-blame-assert 'addition) + (magit-blame--pre-blame-setup 'addition) + (magit-blame--run args)) + (read-only-mode -1) + (magit-blame--update-overlays))) + +;;;###autoload (autoload 'magit-blame-addition "magit-blame" nil t) +(transient-define-suffix magit-blame-addition (args) + "For each line show the revision in which it was added." + (interactive (list (magit-blame-arguments))) + (magit-blame--pre-blame-assert 'addition) + (magit-blame--pre-blame-setup 'addition) + (magit-blame--run args)) + +;;;###autoload (autoload 'magit-blame-removal "magit-blame" nil t) +(transient-define-suffix magit-blame-removal (args) + "For each line show the revision in which it was removed." + :if-nil 'buffer-file-name + (interactive (list (magit-blame-arguments))) + (unless magit-buffer-file-name + (user-error "Only blob buffers can be blamed in reverse")) + (magit-blame--pre-blame-assert 'removal) + (magit-blame--pre-blame-setup 'removal) + (magit-blame--run args)) + +;;;###autoload (autoload 'magit-blame-reverse "magit-blame" nil t) +(transient-define-suffix magit-blame-reverse (args) + "For each line show the last revision in which it still exists." + :if-nil 'buffer-file-name + (interactive (list (magit-blame-arguments))) + (unless magit-buffer-file-name + (user-error "Only blob buffers can be blamed in reverse")) + (magit-blame--pre-blame-assert 'final) + (magit-blame--pre-blame-setup 'final) + (magit-blame--run args)) + +(defun magit-blame--pre-blame-assert (type) + (unless (magit-toplevel) + (magit--not-inside-repository-error)) + (if (and magit-blame-mode + (eq type magit-blame-type)) + (if-let ((chunk (magit-current-blame-chunk))) + (unless (oref chunk prev-rev) + (user-error "Chunk has no further history")) + (user-error "Commit data not available yet. Still blaming.")) + (unless (magit-file-relative-name nil (not magit-buffer-file-name)) + (if buffer-file-name + (user-error "Buffer isn't visiting a tracked file") + (user-error "Buffer isn't visiting a file"))))) + +(defun magit-blame--pre-blame-setup (type) + (when magit-blame-mode + (if (eq type magit-blame-type) + (let ((style magit-blame--style)) + (magit-blame-visit-other-file) + (setq-local magit-blame--style style) + (setq-local magit-blame-recursive-p t) + ;; Set window-start for the benefit of quickstart. + (redisplay)) + (magit-blame--remove-overlays))) + (setq magit-blame-type type)) + +(defun magit-blame-visit-other-file () + "Visit another blob related to the current chunk." + (interactive) + (with-slots (prev-rev prev-file orig-line) + (magit-current-blame-chunk) + (unless prev-rev + (user-error "Chunk has no further history")) + (magit-with-toplevel + (magit-find-file prev-rev prev-file)) + ;; TODO Adjust line like magit-diff-visit-file. + (goto-char (point-min)) + (forward-line (1- orig-line)))) + +(defun magit-blame-visit-file () + "Visit the blob related to the current chunk." + (interactive) + (with-slots (orig-rev orig-file orig-line) + (magit-current-blame-chunk) + (magit-with-toplevel + (magit-find-file orig-rev orig-file)) + (goto-char (point-min)) + (forward-line (1- orig-line)))) + +(transient-define-suffix magit-blame-quit () + "Turn off Magit-Blame mode. +If the buffer was created during a recursive blame, +then also kill the buffer." + :if-non-nil 'magit-blame-mode + (interactive) + (magit-blame-mode -1) + (when magit-blame-recursive-p + (kill-buffer))) + +(defun magit-blame-next-chunk () + "Move to the next chunk." + (interactive) + (if-let ((next (next-single-char-property-change + (point) 'magit-blame-chunk))) + (goto-char next) + (user-error "No more chunks"))) + +(defun magit-blame-previous-chunk () + "Move to the previous chunk." + (interactive) + (if-let ((prev (previous-single-char-property-change + (point) 'magit-blame-chunk))) + (goto-char prev) + (user-error "No more chunks"))) + +(defun magit-blame-next-chunk-same-commit (&optional previous) + "Move to the next chunk from the same commit.\n\n(fn)" + (interactive) + (if-let ((rev (oref (magit-current-blame-chunk) orig-rev))) + (let ((pos (point)) ov) + (save-excursion + (while (and (not ov) + (not (= pos (if previous (point-min) (point-max)))) + (setq pos (funcall + (if previous + #'previous-single-char-property-change + #'next-single-char-property-change) + pos 'magit-blame-chunk))) + (when-let ((o (magit-blame--overlay-at pos))) + (when (equal (oref (magit-blame-chunk-at pos) orig-rev) rev) + (setq ov o))))) + (if ov + (goto-char (overlay-start ov)) + (user-error "No more chunks from same commit"))) + (user-error "This chunk hasn't been blamed yet"))) + +(defun magit-blame-previous-chunk-same-commit () + "Move to the previous chunk from the same commit." + (interactive) + (magit-blame-next-chunk-same-commit #'previous-single-char-property-change)) + +(defun magit-blame-cycle-style () + "Change how blame information is visualized. +Cycle through the elements of option `magit-blame-styles'." + (interactive) + (setq magit-blame--style + (or (cadr (cl-member (car magit-blame--style) + magit-blame-styles :key #'car)) + (car magit-blame-styles))) + (magit-blame--update-margin) + (magit-blame--update-overlays)) + +(defun magit-blame-copy-hash () + "Save hash of the current chunk's commit to the kill ring. + +When the region is active, then save the region's content +instead of the hash, like `kill-ring-save' would." + (interactive) + (if (use-region-p) + (call-interactively #'copy-region-as-kill) + (kill-new (message "%s" (oref (magit-current-blame-chunk) orig-rev))))) + +;;; Popup + +;;;###autoload (autoload 'magit-blame "magit-blame" nil t) +(transient-define-prefix magit-blame () + "Show the commits that added or removed lines in the visited file." + :man-page "git-blame" + :value '("-w") + ["Arguments" + ("-w" "Ignore whitespace" "-w") + ("-r" "Do not treat root commits as boundaries" "--root") + ("-P" "Follow only first parent" "--first-parent") + (magit-blame:-M) + (magit-blame:-C)] + ["Actions" + ("b" "Show commits adding lines" magit-blame-addition) + ("r" "Show commits removing lines" magit-blame-removal) + ("f" "Show last commits that still have lines" magit-blame-reverse) + ("m" "Blame echo" magit-blame-echo) + ("q" "Quit blaming" magit-blame-quit)] + ["Refresh" + :if-non-nil magit-blame-mode + ("c" "Cycle style" magit-blame-cycle-style :transient t)]) + +(defun magit-blame-arguments () + (transient-args 'magit-blame)) + +(transient-define-argument magit-blame:-M () + :description "Detect lines moved or copied within a file" + :class 'transient-option + :argument "-M" + :allow-empty t + :reader #'transient-read-number-N+) + +(transient-define-argument magit-blame:-C () + :description "Detect lines moved or copied between files" + :class 'transient-option + :argument "-C" + :allow-empty t + :reader #'transient-read-number-N+) + +;;; Utilities + +(defun magit-blame-maybe-update-revision-buffer () + (when-let* ((chunk (magit-current-blame-chunk)) + (commit (oref chunk orig-rev)) + (buffer (magit-get-mode-buffer 'magit-revision-mode nil t))) + (if magit--update-revision-buffer + (setq magit--update-revision-buffer (list commit buffer)) + (setq magit--update-revision-buffer (list commit buffer)) + (run-with-idle-timer + magit-update-other-window-delay nil + (lambda () + (pcase-let ((`(,rev ,buf) magit--update-revision-buffer)) + (setq magit--update-revision-buffer nil) + (when (buffer-live-p buf) + (let ((magit-display-buffer-noselect t)) + (apply #'magit-show-commit rev + (magit-diff-arguments 'magit-revision-mode)))))))))) + +;;; _ +(provide 'magit-blame) +;;; magit-blame.el ends here diff --git a/emacs/elpa/magit-20241004.917/magit-bookmark.el b/emacs/elpa/magit-20241004.917/magit-bookmark.el @@ -0,0 +1,154 @@ +;;; magit-bookmark.el --- Bookmarks for Magit buffers -*- lexical-binding:t -*- + +;; Copyright (C) 2008-2024 The Magit Project Contributors + +;; Inspired by an earlier implementation by Yuri Khan. + +;; Author: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> +;; Maintainer: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> + +;; SPDX-License-Identifier: GPL-3.0-or-later + +;; Magit is free software: you can redistribute it and/or modify it +;; under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. +;; +;; Magit is distributed in the hope that it will be useful, but WITHOUT +;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +;; or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public +;; License for more details. +;; +;; You should have received a copy of the GNU General Public License +;; along with Magit. If not, see <https://www.gnu.org/licenses/>. + +;;; Commentary: + +;; Support for bookmarks for most Magit buffers. + +;;; Code: + +(require 'magit) + +(require 'bookmark) + +;;; Common + +(cl-defmethod magit-bookmark-get-filename (&context (major-mode magit-mode)) + (magit-toplevel)) + +(cl-defmethod magit-bookmark-get-buffer-create + (bookmark (mode (derived-mode magit-mode))) + (let ((default-directory (bookmark-get-filename bookmark)) + (magit-display-buffer-function #'identity) + (magit-display-buffer-noselect t)) + (apply (intern (format "%s-setup-buffer" + (substring (symbol-name mode) 0 -5))) + (--map (bookmark-prop-get bookmark it) + (get mode 'magit-bookmark-variables))))) + +;;; Diff +;;;; Diff + +(put 'magit-diff-mode 'magit-bookmark-variables + '(magit-buffer-range-hashed + magit-buffer-typearg + magit-buffer-diff-args + magit-buffer-diff-files)) + +(cl-defmethod magit-bookmark-name (&context (major-mode magit-diff-mode)) + (format "magit-diff(%s%s)" + (pcase (magit-diff-type) + ('staged "staged") + ('unstaged "unstaged") + ('committed magit-buffer-range) + ('undefined + (delq nil (list magit-buffer-typearg magit-buffer-range-hashed)))) + (if magit-buffer-diff-files + (concat " -- " (string-join magit-buffer-diff-files " ")) + ""))) + +;;;; Revision + +(put 'magit-revision-mode 'magit-bookmark-variables + '(magit-buffer-revision-hash + magit-buffer-diff-args + magit-buffer-diff-files)) + +(cl-defmethod magit-bookmark-name (&context (major-mode magit-revision-mode)) + (format "magit-revision(%s %s)" + (magit-rev-abbrev magit-buffer-revision) + (if magit-buffer-diff-files + (string-join magit-buffer-diff-files " ") + (magit-rev-format "%s" magit-buffer-revision)))) + +;;;; Stash + +(put 'magit-stash-mode 'magit-bookmark-variables + '(magit-buffer-revision-hash + magit-buffer-diff-args + magit-buffer-diff-files)) + +(cl-defmethod magit-bookmark-name (&context (major-mode magit-stash-mode)) + (format "magit-stash(%s %s)" + (magit-rev-abbrev magit-buffer-revision) + (if magit-buffer-diff-files + (string-join magit-buffer-diff-files " ") + (magit-rev-format "%s" magit-buffer-revision)))) + +(cl-defmethod magit-bookmark--get-child-value + (section &context (major-mode magit-stash-mode)) + (string-replace magit-buffer-revision + magit-buffer-revision-hash + (oref section value))) + +;;; Log +;;;; Log + +(put 'magit-log-mode 'magit-bookmark-variables + '(magit-buffer-revisions + magit-buffer-log-args + magit-buffer-log-files)) + +(cl-defmethod magit-bookmark-name (&context (major-mode magit-log-mode)) + (format "magit-log(%s%s)" + (string-join magit-buffer-revisions " ") + (if magit-buffer-log-files + (concat " -- " (string-join magit-buffer-log-files " ")) + ""))) + +;;;; Cherry + +(put 'magit-cherry-mode 'magit-bookmark-variables + '(magit-buffer-refname + magit-buffer-upstream)) + +(cl-defmethod magit-bookmark-name (&context (major-mode magit-cherry-mode)) + (format "magit-cherry(%s > %s)" + magit-buffer-refname + magit-buffer-upstream)) + +;;;; Reflog + +(put 'magit-reflog-mode 'magit-bookmark-variables + '(magit-buffer-refname)) + +(cl-defmethod magit-bookmark-name (&context (major-mode magit-reflog-mode)) + (format "magit-reflog(%s)" magit-buffer-refname)) + +;;; Misc + +(put 'magit-status-mode 'magit-bookmark-variables nil) + +(put 'magit-refs-mode 'magit-bookmark-variables + '(magit-buffer-upstream + magit-buffer-arguments)) + +(put 'magit-stashes-mode 'magit-bookmark-variables nil) + +(cl-defmethod magit-bookmark-name (&context (major-mode magit-stashes-mode)) + (format "magit-states(%s)" magit-buffer-refname)) + +;;; _ +(provide 'magit-bookmark) +;;; magit-bookmark.el ends here diff --git a/emacs/elpa/magit-20241004.917/magit-branch.el b/emacs/elpa/magit-20241004.917/magit-branch.el @@ -0,0 +1,982 @@ +;;; magit-branch.el --- Branch support -*- lexical-binding:t -*- + +;; Copyright (C) 2008-2024 The Magit Project Contributors + +;; Author: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> +;; Maintainer: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> + +;; SPDX-License-Identifier: GPL-3.0-or-later + +;; Magit is free software: you can redistribute it and/or modify it +;; under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. +;; +;; Magit is distributed in the hope that it will be useful, but WITHOUT +;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +;; or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public +;; License for more details. +;; +;; You should have received a copy of the GNU General Public License +;; along with Magit. If not, see <https://www.gnu.org/licenses/>. + +;;; Commentary: + +;; This library implements support for branches. It defines commands +;; for creating, checking out, manipulating, and configuring branches. +;; Commands defined here are mainly concerned with branches as +;; pointers, commands that deal with what a branch points at, are +;; defined elsewhere. + +;;; Code: + +(require 'magit) +(require 'magit-reset) + +;;; Options + +(defcustom magit-branch-read-upstream-first t + "Whether to read upstream before name of new branch when creating a branch. + +`nil' Read the branch name first. +`t' Read the upstream first. +`fallback' Read the upstream first, but if it turns out that the chosen + value is not a valid upstream (because it cannot be resolved + as an existing revision), then treat it as the name of the + new branch and continue by reading the upstream next." + :package-version '(magit . "2.2.0") + :group 'magit-commands + :type '(choice (const :tag "read branch name first" nil) + (const :tag "read upstream first" t) + (const :tag "read upstream first, with fallback" fallback))) + +(defcustom magit-branch-prefer-remote-upstream nil + "Whether to favor remote upstreams when creating new branches. + +When a new branch is created, then the branch, commit, or stash +at point is suggested as the default starting point of the new +branch, or if there is no such revision at point the current +branch. In either case the user may choose another starting +point. + +If the chosen starting point is a branch, then it may also be set +as the upstream of the new branch, depending on the value of the +Git variable `branch.autoSetupMerge'. By default this is done +for remote branches, but not for local branches. + +You might prefer to always use some remote branch as upstream. +If the chosen starting point is (1) a local branch, (2) whose +name matches a member of the value of this option, (3) the +upstream of that local branch is a remote branch with the same +name, and (4) that remote branch can be fast-forwarded to the +local branch, then the chosen branch is used as starting point, +but its own upstream is used as the upstream of the new branch. + +Members of this option's value are treated as branch names that +have to match exactly unless they contain a character that makes +them invalid as a branch name. Recommended characters to use +to trigger interpretation as a regexp are \"*\" and \"^\". Some +other characters which you might expect to be invalid, actually +are not, e.g., \".+$\" are all perfectly valid. More precisely, +if `git check-ref-format --branch STRING' exits with a non-zero +status, then treat STRING as a regexp. + +Assuming the chosen branch matches these conditions you would end +up with with e.g.: + + feature --upstream--> origin/master + +instead of + + feature --upstream--> master --upstream--> origin/master + +Which you prefer is a matter of personal preference. If you do +prefer the former, then you should add branches such as \"master\", +\"next\", and \"maint\" to the value of this options." + :package-version '(magit . "2.4.0") + :group 'magit-commands + :type '(repeat string)) + +(defcustom magit-branch-adjust-remote-upstream-alist nil + "Alist of upstreams to be used when branching from remote branches. + +When creating a local branch from an ephemeral branch located +on a remote, e.g., a feature or hotfix branch, then that remote +branch should usually not be used as the upstream branch, since +the push-remote already allows accessing it and having both the +upstream and the push-remote reference the same related branch +would be wasteful. Instead a branch like \"maint\" or \"master\" +should be used as the upstream. + +This option allows specifying the branch that should be used as +the upstream when branching certain remote branches. The value +is an alist of the form ((UPSTREAM . RULE)...). The first +element is used whose UPSTREAM exists and whose RULE matches +the name of the new branch. Subsequent elements are ignored. + +UPSTREAM is the branch to be used as the upstream for branches +specified by RULE. It can be a local or a remote branch. + +RULE can either be a regular expression, matching branches whose +upstream should be the one specified by UPSTREAM. Or it can be +a list of the only branches that should *not* use UPSTREAM; all +other branches will. Matching is done after stripping the remote +part of the name of the branch that is being branched from. + +If you use a finite set of non-ephemeral branches across all your +repositories, then you might use something like: + + ((\"origin/master\" . (\"master\" \"next\" \"maint\"))) + +Or if the names of all your ephemeral branches contain a slash, +at least in some repositories, then a good value could be: + + ((\"origin/master\" . \"/\")) + +Of course you can also fine-tune: + + ((\"origin/maint\" . \"\\\\\\=`hotfix/\") + (\"origin/master\" . \"\\\\\\=`feature/\")) + +UPSTREAM can be a local branch: + + ((\"master\" . (\"master\" \"next\" \"maint\"))) + +Because the main branch is no longer almost always named \"master\" +you should also account for other common names: + + ((\"main\" . (\"main\" \"master\" \"next\" \"maint\")) + (\"master\" . (\"main\" \"master\" \"next\" \"maint\"))) + +If you use remote branches as UPSTREAM, then you might also want +to set `magit-branch-prefer-remote-upstream' to a non-nil value. +However, I recommend that you use local branches as UPSTREAM." + :package-version '(magit . "2.9.0") + :group 'magit-commands + :type '(repeat (cons (string :tag "Use upstream") + (choice :tag "for branches" + (regexp :tag "matching") + (repeat :tag "except" + (string :tag "branch")))))) + +(defcustom magit-branch-rename-push-target t + "Whether the push-remote setup is preserved when renaming a branch. + +The command `magit-branch-rename' renames a branch named OLD to +NEW. This option controls how much of the push-remote setup is +preserved when doing so. + +When nil, then preserve nothing and unset `branch.OLD.pushRemote'. + +When `local-only', then first set `branch.NEW.pushRemote' to the + same value as `branch.OLD.pushRemote', provided the latter is + actually set and unless the former already has another value. + +When t, then rename the branch named OLD on the remote specified + by `branch.OLD.pushRemote' to NEW, provided OLD exists on that + remote and unless NEW already exists on the remote. + +When `forge-only' and the `forge' package is available, then + behave like `t' if the remote points to a repository on a forge + (currently Github or Gitlab), otherwise like `local-only'." + :package-version '(magit . "2.90.0") + :group 'magit-commands + :type '(choice + (const :tag "Don't preserve push-remote setup" nil) + (const :tag "Preserve push-remote setup" local-only) + (const :tag "... and rename corresponding branch on remote" t) + (const :tag "... but only if remote is on a forge" forge-only))) + +(defcustom magit-branch-direct-configure t + "Whether the command `magit-branch' shows Git variables. +When set to nil, no variables are displayed by this transient +command, instead the sub-transient `magit-branch-configure' +has to be used to view and change branch related variables." + :package-version '(magit . "2.7.0") + :group 'magit-commands + :type 'boolean) + +(defcustom magit-published-branches '("origin/master") + "List of branches that are considered to be published." + :package-version '(magit . "2.13.0") + :group 'magit-commands + :type '(repeat string)) + +;;; Commands + +;;;###autoload (autoload 'magit-branch "magit" nil t) +(transient-define-prefix magit-branch (branch) + "Add, configure or remove a branch." + :man-page "git-branch" + [:if (lambda () + (and magit-branch-direct-configure + (oref (transient-prefix-object) scope))) + :description + (lambda () + (concat (propertize "Configure " 'face 'transient-heading) + (propertize (oref (transient-prefix-object) scope) + 'face 'magit-branch-local))) + ("d" magit-branch.<branch>.description) + ("u" magit-branch.<branch>.merge/remote) + ("r" magit-branch.<branch>.rebase) + ("p" magit-branch.<branch>.pushRemote)] + [:if-non-nil magit-branch-direct-configure + :description "Configure repository defaults" + ("R" magit-pull.rebase) + ("P" magit-remote.pushDefault) + ("B" "Update default branch" magit-update-default-branch + :inapt-if-not magit-get-some-remote)] + ["Arguments" + (7 "-r" "Recurse submodules when checking out an existing branch" + "--recurse-submodules" + :if (lambda () (magit-git-version>= "2.13")))] + [["Checkout" + ("b" "branch/revision" magit-checkout) + ("l" "local branch" magit-branch-checkout) + (6 "o" "new orphan" magit-branch-orphan)] + ["" + ("c" "new branch" magit-branch-and-checkout) + ("s" "new spin-off" magit-branch-spinoff) + (5 "w" "new worktree" magit-worktree-checkout)] + ["Create" + ("n" "new branch" magit-branch-create) + ("S" "new spin-out" magit-branch-spinout) + (5 "W" "new worktree" magit-worktree-branch)] + ["Do" + ("C" "configure..." magit-branch-configure) + ("m" "rename" magit-branch-rename) + ("x" "reset" magit-branch-reset) + ("k" "delete" magit-branch-delete)] + ["" + (7 "h" "shelve" magit-branch-shelve) + (7 "H" "unshelve" magit-branch-unshelve)]] + (interactive (list (magit-get-current-branch))) + (transient-setup 'magit-branch nil nil :scope branch)) + +(defun magit-branch-arguments () + (transient-args 'magit-branch)) + +;;;###autoload +(defun magit-checkout (revision &optional args) + "Checkout REVISION, updating the index and the working tree. +If REVISION is a local branch, then that becomes the current +branch. If it is something else, then `HEAD' becomes detached. +Checkout fails if the working tree or the staging area contain +changes. +\n(git checkout REVISION)." + (declare (interactive-only magit--checkout)) + (interactive (list (magit-read-other-branch-or-commit "Checkout") + (magit-branch-arguments))) + (when (string-match "\\`heads/\\(.+\\)" revision) + (setq revision (match-string 1 revision))) + (magit-run-git-async "checkout" args revision)) + +(defun magit--checkout (revision &optional args) + (when (string-match "\\`heads/\\(.+\\)" revision) + (setq revision (match-string 1 revision))) + (magit-call-git "checkout" args revision)) + +;;;###autoload +(defun magit-branch-create (branch start-point) + "Create BRANCH at branch or revision START-POINT." + (declare (interactive-only magit-call-git)) + (interactive (magit-branch-read-args "Create branch")) + (magit-run-git-async "branch" branch start-point) + (set-process-sentinel + magit-this-process + (lambda (process event) + (when (memq (process-status process) '(exit signal)) + (magit-branch-maybe-adjust-upstream branch start-point) + (magit-process-sentinel process event))))) + +;;;###autoload +(defun magit-branch-and-checkout (branch start-point &optional args) + "Create and checkout BRANCH at branch or revision START-POINT." + (declare (interactive-only magit-call-git)) + (interactive (append (magit-branch-read-args "Create and checkout branch") + (list (magit-branch-arguments)))) + (if (string-match-p "^stash@{[0-9]+}$" start-point) + (magit-run-git "stash" "branch" branch start-point) + (magit-run-git-async "checkout" args "-b" branch start-point) + (set-process-sentinel + magit-this-process + (lambda (process event) + (when (memq (process-status process) '(exit signal)) + (magit-branch-maybe-adjust-upstream branch start-point) + (magit-process-sentinel process event)))))) + +;;;###autoload +(defun magit-branch-or-checkout (arg &optional start-point) + "Hybrid between `magit-checkout' and `magit-branch-and-checkout'. + +Ask the user for an existing branch or revision. If the user +input actually can be resolved as a branch or revision, then +check that out, just like `magit-checkout' would. + +Otherwise create and checkout a new branch using the input as +its name. Before doing so read the starting-point for the new +branch. This is similar to what `magit-branch-and-checkout' +does." + (declare (interactive-only magit-call-git)) + (interactive + (let ((arg (magit-read-other-branch-or-commit "Checkout"))) + (list arg + (and (not (magit-commit-p arg)) + (magit-read-starting-point "Create and checkout branch" arg))))) + (when (string-match "\\`heads/\\(.+\\)" arg) + (setq arg (match-string 1 arg))) + (if start-point + (with-suppressed-warnings ((interactive-only magit-branch-and-checkout)) + (magit-branch-and-checkout arg start-point)) + (magit--checkout arg) + (magit-refresh))) + +;;;###autoload +(defun magit-branch-checkout (branch &optional start-point) + "Checkout an existing or new local branch. + +Read a branch name from the user offering all local branches and +a subset of remote branches as candidates. Omit remote branches +for which a local branch by the same name exists from the list +of candidates. The user can also enter a completely new branch +name. + +- If the user selects an existing local branch, then check that + out. + +- If the user selects a remote branch, then create and checkout + a new local branch with the same name. Configure the selected + remote branch as push target. + +- If the user enters a new branch name, then create and check + that out, after also reading the starting-point from the user. + +In the latter two cases the upstream is also set. Whether it is +set to the chosen START-POINT or something else depends on the +value of `magit-branch-adjust-remote-upstream-alist', just like +when using `magit-branch-and-checkout'." + (declare (interactive-only magit-call-git)) + (interactive + (let* ((current (magit-get-current-branch)) + (local (magit-list-local-branch-names)) + (remote (--filter (and (string-match "[^/]+/" it) + (not (member (substring it (match-end 0)) + (cons "HEAD" local)))) + (magit-list-remote-branch-names))) + (choices (nconc (delete current local) remote)) + (atpoint (magit-branch-at-point)) + (choice (magit-completing-read + "Checkout branch" choices + nil nil nil 'magit-revision-history + (or (car (member atpoint choices)) + (and atpoint + (car (member (and (string-match "[^/]+/" atpoint) + (substring atpoint (match-end 0))) + choices))))))) + (cond ((member choice remote) + (list (and (string-match "[^/]+/" choice) + (substring choice (match-end 0))) + choice)) + ((member choice local) + (list choice)) + (t + (list choice (magit-read-starting-point "Create" choice)))))) + (cond + ((not start-point) + (magit--checkout branch (magit-branch-arguments)) + (magit-refresh)) + (t + (when (magit-anything-modified-p t) + (user-error "Cannot checkout when there are uncommitted changes")) + (magit-run-git-async "checkout" (magit-branch-arguments) + "-b" branch start-point) + (set-process-sentinel + magit-this-process + (lambda (process event) + (when (memq (process-status process) '(exit signal)) + (magit-branch-maybe-adjust-upstream branch start-point) + (when (magit-remote-branch-p start-point) + (pcase-let ((`(,remote . ,remote-branch) + (magit-split-branch-name start-point))) + (when (and (equal branch remote-branch) + (not (equal remote (magit-get "remote.pushDefault")))) + (magit-set remote "branch" branch "pushRemote")))) + (magit-process-sentinel process event))))))) + +(defun magit-branch-maybe-adjust-upstream (branch start-point) + (when-let ((upstream + (or (and (magit-get-upstream-branch branch) + (magit-get-indirect-upstream-branch start-point)) + (and (magit-remote-branch-p start-point) + (let ((name (cdr (magit-split-branch-name start-point)))) + (seq-some + (pcase-lambda (`(,upstream . ,rule)) + (and (magit-branch-p upstream) + (if (listp rule) + (not (member name rule)) + (string-match-p rule name)) + upstream)) + magit-branch-adjust-remote-upstream-alist)))))) + (magit-call-git "branch" (concat "--set-upstream-to=" upstream) branch))) + +;;;###autoload +(defun magit-branch-orphan (branch start-point) + "Create and checkout an orphan BRANCH with contents from revision START-POINT." + (interactive (magit-branch-read-args "Create and checkout orphan branch")) + (magit-run-git "checkout" "--orphan" branch start-point)) + +(defun magit-branch-read-args (prompt &optional default-start) + (if magit-branch-read-upstream-first + (let ((choice (magit-read-starting-point prompt nil default-start))) + (cond + ((magit-rev-verify choice) + (list (magit-read-string-ns + (if magit-completing-read--silent-default + (format "%s (starting at `%s')" prompt choice) + "Name for new branch") + (let ((def (string-join (cdr (split-string choice "/")) "/"))) + (and (member choice (magit-list-remote-branch-names)) + (not (member def (magit-list-local-branch-names))) + def))) + choice)) + ((eq magit-branch-read-upstream-first 'fallback) + (list choice + (magit-read-starting-point prompt choice default-start))) + ((user-error "Not a valid starting-point: %s" choice)))) + (let ((branch (magit-read-string-ns (concat prompt " named")))) + (if (magit-branch-p branch) + (magit-branch-read-args + (format "Branch `%s' already exists; pick another name" branch) + default-start) + (list branch (magit-read-starting-point prompt branch default-start)))))) + +;;;###autoload +(defun magit-branch-spinout (branch &optional from) + "Create new branch from the unpushed commits. +Like `magit-branch-spinoff' but remain on the current branch. +If there are any uncommitted changes, then behave exactly like +`magit-branch-spinoff'." + (interactive (list (magit-read-string-ns "Spin out branch") + (car (last (magit-region-values 'commit))))) + (magit--branch-spinoff branch from nil)) + +;;;###autoload +(defun magit-branch-spinoff (branch &optional from) + "Create new branch from the unpushed commits. + +Create and checkout a new branch starting at and tracking the +current branch. That branch in turn is reset to the last commit +it shares with its upstream. If the current branch has no +upstream or no unpushed commits, then the new branch is created +anyway and the previously current branch is not touched. + +This is useful to create a feature branch after work has already +began on the old branch (likely but not necessarily \"master\"). + +If the current branch is a member of the value of option +`magit-branch-prefer-remote-upstream' (which see), then the +current branch will be used as the starting point as usual, but +the upstream of the starting-point may be used as the upstream +of the new branch, instead of the starting-point itself. + +If optional FROM is non-nil, then the source branch is reset +to `FROM~', instead of to the last commit it shares with its +upstream. Interactively, FROM is only ever non-nil, if the +region selects some commits, and among those commits, FROM is +the commit that is the fewest commits ahead of the source +branch. + +The commit at the other end of the selection actually does not +matter, all commits between FROM and `HEAD' are moved to the new +branch. If FROM is not reachable from `HEAD' or is reachable +from the source branch's upstream, then an error is raised." + (interactive (list (magit-read-string-ns "Spin off branch") + (car (last (magit-region-values 'commit))))) + (magit--branch-spinoff branch from t)) + +(defun magit--branch-spinoff (branch from checkout) + (when (magit-branch-p branch) + (user-error "Cannot spin off %s. It already exists" branch)) + (when (and (not checkout) + (magit-anything-modified-p)) + (message "Staying on HEAD due to uncommitted changes") + (setq checkout t)) + (if-let ((current (magit-get-current-branch))) + (let ((tracked (magit-get-upstream-branch current)) + base) + (when from + (unless (magit-rev-ancestor-p from current) + (user-error "Cannot spin off %s. %s is not reachable from %s" + branch from current)) + (when (and tracked + (magit-rev-ancestor-p from tracked)) + (user-error "Cannot spin off %s. %s is ancestor of upstream %s" + branch from tracked))) + (let ((magit-process-raise-error t)) + (if checkout + (magit-call-git "checkout" "-b" branch current) + (magit-call-git "branch" branch current))) + (when-let ((upstream (magit-get-indirect-upstream-branch current))) + (magit-call-git "branch" "--set-upstream-to" upstream branch)) + (when (and tracked + (setq base + (if from + (concat from "^") + (magit-git-string "merge-base" current tracked))) + (not (magit-rev-eq base current))) + (if checkout + (magit-call-git "update-ref" "-m" + (format "reset: moving to %s" base) + (concat "refs/heads/" current) base) + (magit-call-git "reset" "--hard" base)))) + (if checkout + (magit-call-git "checkout" "-b" branch) + (magit-call-git "branch" branch))) + (magit-refresh)) + +;;;###autoload +(defun magit-branch-reset (branch to &optional set-upstream) + "Reset a branch to the tip of another branch or any other commit. + +When the branch being reset is the current branch, then do a +hard reset. If there are any uncommitted changes, then the user +has to confirm the reset because those changes would be lost. + +This is useful when you have started work on a feature branch but +realize it's all crap and want to start over. + +When resetting to another branch and a prefix argument is used, +then also set the target branch as the upstream of the branch +that is being reset." + (interactive + (let ((branch (magit-read-local-branch "Reset branch" + (magit-local-branch-at-point)))) + (list branch + (magit-read-branch-or-commit (format "Reset %s to" branch) + (magit-get-upstream-branch branch) + branch) + current-prefix-arg))) + (let ((magit-inhibit-refresh t)) + (if (equal branch (magit-get-current-branch)) + (if (and (magit-anything-modified-p) + (not (yes-or-no-p + "Uncommitted changes will be lost. Proceed? "))) + (user-error "Abort") + (magit-reset-hard to)) + (magit-call-git "update-ref" + "-m" (format "reset: moving to %s" to) + (magit-git-string "rev-parse" "--symbolic-full-name" + branch) + to)) + (when (and set-upstream (magit-branch-p to)) + (magit-set-upstream-branch branch to) + (magit-branch-maybe-adjust-upstream branch to))) + (magit-refresh)) + +(defvar magit-branch-delete-never-verify nil + "Whether `magit-branch-delete' always pushes with \"--no-verify\".") + +;;;###autoload +(defun magit-branch-delete (branches &optional force) + "Delete one or multiple branches. + +If the region marks multiple branches, then offer to delete +those, otherwise prompt for a single branch to be deleted, +defaulting to the branch at point. + +Require confirmation when deleting branches is dangerous in some +way. Option `magit-no-confirm' can be customized to not require +confirmation in certain cases. See its docstring to learn why +confirmation is required by default in certain cases or if a +prompt is confusing." + ;; One would expect this to be a command as simple as, for example, + ;; `magit-branch-rename'; but it turns out everyone wants to squeeze + ;; a bit of extra functionality into this one, including myself. + (interactive + (let ((branches (magit-region-values 'branch t)) + (force current-prefix-arg)) + (if (length> branches 1) + (magit-confirm t nil "Delete %d branches" nil branches) + (setq branches + (list (magit-read-branch-prefer-other + (if force "Force delete branch" "Delete branch"))))) + (unless force + (when-let ((unmerged (seq-remove #'magit-branch-merged-p branches))) + (if (magit-confirm 'delete-unmerged-branch + "Delete unmerged branch %s" + "Delete %d unmerged branches" + 'noabort unmerged) + (setq force branches) + (or (setq branches + (cl-set-difference branches unmerged :test #'equal)) + (user-error "Abort"))))) + (list branches force))) + (let* ((refs (mapcar #'magit-ref-fullname branches)) + (ambiguous (--remove it refs))) + (when ambiguous + (user-error + "%s ambiguous. Please cleanup using git directly." + (let ((len (length ambiguous))) + (cond + ((= len 1) + (format "%s is" (seq-find #'magit-ref-ambiguous-p branches))) + ((= len (length refs)) + (format "These %s names are" len)) + (t + (format "%s of these names are" len)))))) + (cond + ((string-match "^refs/remotes/\\([^/]+\\)" (car refs)) + (let* ((remote (match-string 1 (car refs))) + (offset (1+ (length remote)))) + (cond + ((magit-confirm 'delete-branch-on-remote + (list "Deleting local %s. Also delete on %s" + (magit-ref-fullname (car branches)) + remote) + (list "Deleting %d local refs. Also delete on %s" + (length refs) + remote) + 'noabort refs) + ;; The ref may actually point at another rev on the remote, + ;; but this is better than nothing. + (dolist (ref refs) + (message "Delete %s (was %s)" ref + (magit-rev-parse "--short" ref))) + ;; Assume the branches actually still exist on the remote. + (magit-run-git-async + "push" + (and (or force magit-branch-delete-never-verify) "--no-verify") + remote + (--map (concat ":" (substring it offset)) branches)) + ;; If that is not the case, then this deletes the tracking branches. + (set-process-sentinel + magit-this-process + (apply-partially #'magit-delete-remote-branch-sentinel remote refs))) + (t + (dolist (ref refs) + (message "Delete %s (was %s)" ref + (magit-rev-parse "--short" ref)) + (magit-call-git "update-ref" "-d" ref)) + (magit-refresh))))) + ((length> branches 1) + (setq branches (delete (magit-get-current-branch) branches)) + (mapc #'magit-branch-maybe-delete-pr-remote branches) + (mapc #'magit-branch-unset-pushRemote branches) + (magit-run-git "branch" (if force "-D" "-d") branches)) + (t ; And now for something completely different. + (let* ((branch (car branches)) + (prompt (format "Branch %s is checked out. " branch)) + (target (magit-get-indirect-upstream-branch branch t))) + (when (equal branch (magit-get-current-branch)) + (when (or (equal branch target) + (not target)) + (setq target (magit-main-branch))) + (pcase (if (or (equal branch target) + (not target)) + (magit-read-char-case prompt nil + (?d "[d]etach HEAD & delete" 'detach) + (?a "[a]bort" 'abort)) + (magit-read-char-case prompt nil + (?d "[d]etach HEAD & delete" 'detach) + (?c (format "[c]heckout %s & delete" target) 'target) + (?a "[a]bort" 'abort))) + (`detach (unless (or (equal force '(4)) + (member branch force) + (magit-branch-merged-p branch t)) + (magit-confirm 'delete-unmerged-branch + "Delete unmerged branch %s" "" + nil (list branch))) + (magit-call-git "checkout" "--detach")) + (`target (unless (or (equal force '(4)) + (member branch force) + (magit-branch-merged-p branch target)) + (magit-confirm 'delete-unmerged-branch + "Delete unmerged branch %s" "" + nil (list branch))) + (magit-call-git "checkout" target)) + (`abort (user-error "Abort"))) + (setq force t)) + (magit-branch-maybe-delete-pr-remote branch) + (magit-branch-unset-pushRemote branch) + (magit-run-git "branch" (if force "-D" "-d") branch)))))) + +(put 'magit-branch-delete 'interactive-only t) + +(defun magit-branch-maybe-delete-pr-remote (branch) + (when-let ((remote (magit-get "branch" branch "pullRequestRemote"))) + (let* ((variable (format "remote.%s.fetch" remote)) + (refspecs (magit-get-all variable))) + (unless (member (format "+refs/heads/*:refs/remotes/%s/*" remote) + refspecs) + (let ((refspec + (if (equal (magit-get "branch" branch "pushRemote") remote) + (format "+refs/heads/%s:refs/remotes/%s/%s" + branch remote branch) + (let ((merge (magit-get "branch" branch "merge"))) + (and merge + (string-prefix-p "refs/heads/" merge) + (setq merge (substring merge 11)) + (format "+refs/heads/%s:refs/remotes/%s/%s" + merge remote merge)))))) + (when (member refspec refspecs) + (if (and (length= refspecs 1) + (magit-confirm 'delete-pr-remote + (list "Also delete remote %s (%s)" remote + "no pull-request branch remains") + nil t)) + (magit-call-git "remote" "rm" remote) + (magit-call-git "config" "--unset-all" variable + (format "^%s$" (regexp-quote refspec)))))))))) + +(defun magit-branch-unset-pushRemote (branch) + (magit-set nil "branch" branch "pushRemote")) + +(defun magit-delete-remote-branch-sentinel (remote refs process event) + (when (memq (process-status process) '(exit signal)) + (if (= (process-exit-status process) 1) + (if-let ((on-remote (--map (concat "refs/remotes/" remote "/" it) + (magit-remote-list-branches remote))) + (rest (--filter (and (not (member it on-remote)) + (magit-ref-exists-p it)) + refs))) + (progn + (process-put process 'inhibit-refresh t) + (magit-process-sentinel process event) + (setq magit-this-error nil) + (message "Some remote branches no longer exist. %s" + "Deleting just the local tracking refs instead...") + (dolist (ref rest) + (magit-call-git "update-ref" "-d" ref)) + (magit-refresh) + (message "Deleting local remote-tracking refs...done")) + (magit-process-sentinel process event)) + (magit-process-sentinel process event)))) + +;;;###autoload +(defun magit-branch-rename (old new &optional force) + "Rename the branch named OLD to NEW. + +With a prefix argument FORCE, rename even if a branch named NEW +already exists. + +If `branch.OLD.pushRemote' is set, then unset it. Depending on +the value of `magit-branch-rename-push-target' (which see) maybe +set `branch.NEW.pushRemote' and maybe rename the push-target on +the remote." + (interactive + (let ((branch (magit-read-local-branch "Rename branch"))) + (list branch + (magit-read-string-ns (format "Rename branch '%s' to" branch) + nil 'magit-revision-history) + current-prefix-arg))) + (when (string-match "\\`heads/\\(.+\\)" old) + (setq old (match-string 1 old))) + (when (equal old new) + (user-error "Old and new branch names are the same")) + (magit-call-git "branch" (if force "-M" "-m") old new) + (when magit-branch-rename-push-target + (let ((remote (magit-get-push-remote old)) + (old-specified (magit-get "branch" old "pushRemote")) + (new-specified (magit-get "branch" new "pushRemote"))) + (when (and old-specified (or force (not new-specified))) + ;; Keep the target setting branch specified, even if that is + ;; redundant. But if a branch by the same name existed before + ;; and the rename isn't forced, then do not change a leftover + ;; setting. Such a leftover setting may or may not conform to + ;; what we expect here... + (magit-set old-specified "branch" new "pushRemote")) + (when (and (equal (magit-get-push-remote new) remote) + ;; ...and if it does not, then we must abort. + (not (eq magit-branch-rename-push-target 'local-only)) + (or (not (eq magit-branch-rename-push-target 'forge-only)) + (and (require (quote forge) nil t) + (fboundp 'forge--split-forge-url) + (and-let* ((url (magit-git-string + "remote" "get-url" remote))) + (forge--split-forge-url url))))) + (let ((old-target (magit-get-push-branch old t)) + (new-target (magit-get-push-branch new t)) + (remote (magit-get-push-remote new))) + (when (and old-target + (not new-target) + (magit-y-or-n-p (format "Also rename %S to %S on \"%s\"" + old new remote))) + ;; Rename on (i.e., within) the remote, but only if the + ;; destination ref doesn't exist yet. If that ref already + ;; exists, then it probably is of some value and we better + ;; not touch it. Ignore what the local ref points at, + ;; i.e., if the local and the remote ref didn't point at + ;; the same commit before the rename then keep it that way. + (magit-call-git "push" "-v" remote + (format "%s:refs/heads/%s" old-target new) + (format ":refs/heads/%s" old))))))) + (magit-branch-unset-pushRemote old) + (magit-refresh)) + +;;;###autoload +(defun magit-branch-shelve (branch) + "Shelve a BRANCH. +Rename \"refs/heads/BRANCH\" to \"refs/shelved/BRANCH\", +and also rename the respective reflog file." + (interactive (list (magit-read-other-local-branch "Shelve branch"))) + (let ((old (concat "refs/heads/" branch)) + (new (concat "refs/shelved/" branch))) + (magit-git "update-ref" new old "") + (magit--rename-reflog-file old new) + (magit-branch-unset-pushRemote branch) + (magit-run-git "branch" "-D" branch))) + +;;;###autoload +(defun magit-branch-unshelve (branch) + "Unshelve a BRANCH +Rename \"refs/shelved/BRANCH\" to \"refs/heads/BRANCH\", +and also rename the respective reflog file." + (interactive + (list (magit-completing-read + "Unshelve branch" + (--map (substring it 8) + (magit-list-refnames "refs/shelved")) + nil t))) + (let ((old (concat "refs/shelved/" branch)) + (new (concat "refs/heads/" branch))) + (magit-git "update-ref" new old "") + (magit--rename-reflog-file old new) + (magit-run-git "update-ref" "-d" old))) + +(defun magit--rename-reflog-file (old new) + (let* ((dir (magit-gitdir)) + (old (expand-file-name (concat "logs/" old) dir)) + (new (expand-file-name (concat "logs/" new) dir))) + (when (file-exists-p old) + (make-directory (file-name-directory new) t) + (rename-file old new t)))) + +;;; Configure + +;;;###autoload (autoload 'magit-branch-configure "magit-branch" nil t) +(transient-define-prefix magit-branch-configure (branch) + "Configure a branch." + :man-page "git-branch" + [:description + (lambda () + (concat (propertize "Configure " 'face 'transient-heading) + (propertize (oref (transient-prefix-object) scope) + 'face 'magit-branch-local))) + ("d" magit-branch.<branch>.description) + ("u" magit-branch.<branch>.merge/remote) + ("r" magit-branch.<branch>.rebase) + ("p" magit-branch.<branch>.pushRemote)] + ["Configure repository defaults" + ("R" magit-pull.rebase) + ("P" magit-remote.pushDefault) + ("B" "Update default branch" magit-update-default-branch + :inapt-if-not magit-get-some-remote)] + ["Configure branch creation" + ("a m" magit-branch.autoSetupMerge) + ("a r" magit-branch.autoSetupRebase)] + (interactive + (list (or (and (not current-prefix-arg) + (not (and magit-branch-direct-configure + (eq transient-current-command 'magit-branch))) + (magit-get-current-branch)) + (magit--read-branch-scope)))) + (transient-setup 'magit-branch-configure nil nil :scope branch)) + +(defun magit--read-branch-scope (&optional obj) + (magit-read-local-branch + (if obj + (format "Set %s for branch" + (format (oref obj variable) "<name>")) + "Configure branch"))) + +(transient-define-suffix magit-branch.<branch>.description (branch) + "Edit the description of BRANCH." + :class 'magit--git-variable + :transient nil + :variable "branch.%s.description" + (interactive (list (oref transient-current-prefix scope))) + (magit-run-git-with-editor "branch" "--edit-description" branch)) + +(defclass magit--git-branch:upstream (magit--git-variable) + ((format :initform " %k %m %M\n %r %R"))) + +(transient-define-infix magit-branch.<branch>.merge/remote () + :class 'magit--git-branch:upstream) + +(cl-defmethod transient-init-value ((obj magit--git-branch:upstream)) + (when-let* ((branch (oref (transient-prefix-object) scope)) + (remote (magit-get "branch" branch "remote")) + (merge (magit-get "branch" branch "merge"))) + (oset obj value (list remote merge)))) + +(cl-defmethod transient-infix-read ((obj magit--git-branch:upstream)) + (if (oref obj value) + (oset obj value nil) + (magit-read-upstream-branch (oref (transient-prefix-object) scope) + "Upstream"))) + +(cl-defmethod transient-infix-set ((obj magit--git-branch:upstream) refname) + (magit-set-upstream-branch (oref (transient-prefix-object) scope) refname) + (oset obj value + (and-let* ((branch (oref (transient-prefix-object) scope)) + (r (magit-get "branch" branch "remote")) + (m (magit-get "branch" branch "merge"))) + (list r m))) + (magit-refresh)) + +(cl-defmethod transient-format ((obj magit--git-branch:upstream)) + (let ((branch (oref (transient-prefix-object) scope))) + (format-spec + (oref obj format) + `((?k . ,(transient-format-key obj)) + (?r . ,(format "branch.%s.remote" branch)) + (?m . ,(format "branch.%s.merge" branch)) + (?R . ,(transient-format-value obj #'car)) + (?M . ,(transient-format-value obj #'cadr)))))) + +(cl-defmethod transient-format-value ((obj magit--git-branch:upstream) key) + (if-let ((value (funcall key (oref obj value)))) + (propertize value 'face 'transient-argument) + (propertize "unset" 'face 'transient-inactive-argument))) + +(transient-define-infix magit-branch.<branch>.rebase () + :class 'magit--git-variable:choices + :scope #'magit--read-branch-scope + :variable "branch.%s.rebase" + :fallback "pull.rebase" + :choices '("true" "false") + :default "false") + +(transient-define-infix magit-branch.<branch>.pushRemote () + :class 'magit--git-variable:choices + :scope #'magit--read-branch-scope + :variable "branch.%s.pushRemote" + :fallback "remote.pushDefault" + :choices #'magit-list-remotes) + +(transient-define-infix magit-pull.rebase () + :class 'magit--git-variable:choices + :variable "pull.rebase" + :choices '("true" "false") + :default "false") + +(transient-define-infix magit-remote.pushDefault () + :class 'magit--git-variable:choices + :variable "remote.pushDefault" + :choices #'magit-list-remotes) + +(transient-define-infix magit-branch.autoSetupMerge () + :class 'magit--git-variable:choices + :variable "branch.autoSetupMerge" + :choices '("always" "true" "false") + :default "true") + +(transient-define-infix magit-branch.autoSetupRebase () + :class 'magit--git-variable:choices + :variable "branch.autoSetupRebase" + :choices '("always" "local" "remote" "never") + :default "never") + +;;; _ +(provide 'magit-branch) +;;; magit-branch.el ends here diff --git a/emacs/elpa/magit-20241004.917/magit-bundle.el b/emacs/elpa/magit-20241004.917/magit-bundle.el @@ -0,0 +1,132 @@ +;;; magit-bundle.el --- Bundle support for Magit -*- lexical-binding:t -*- + +;; Copyright (C) 2008-2024 The Magit Project Contributors + +;; Author: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> +;; Maintainer: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> + +;; SPDX-License-Identifier: GPL-3.0-or-later + +;; Magit is free software: you can redistribute it and/or modify it +;; under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. +;; +;; Magit is distributed in the hope that it will be useful, but WITHOUT +;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +;; or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public +;; License for more details. +;; +;; You should have received a copy of the GNU General Public License +;; along with Magit. If not, see <https://www.gnu.org/licenses/>. + +;;; Code: + +(require 'magit) + +;;; Commands + +;;;###autoload (autoload 'magit-bundle "magit-bundle" nil t) +(transient-define-prefix magit-bundle () + "Create or verify Git bundles." + :man-page "git-bundle" + ["Actions" + ("c" "create" magit-bundle-create) + ("v" "verify" magit-bundle-verify) + ("l" "list-heads" magit-bundle-list-heads)]) + +;;;###autoload (autoload 'magit-bundle-import "magit-bundle" nil t) +(transient-define-prefix magit-bundle-create (&optional file refs args) + "Create a bundle." + :man-page "git-bundle" + ["Arguments" + ("-a" "Include all refs" "--all") + ("-b" "Include branches" "--branches=" :allow-empty t) + ("-t" "Include tags" "--tags=" :allow-empty t) + ("-r" "Include remotes" "--remotes=" :allow-empty t) + ("-g" "Include refs" "--glob=") + ("-e" "Exclude refs" "--exclude=") + (magit-log:-n) + (magit-log:--since) + (magit-log:--until)] + ["Actions" + ("c" "create regular bundle" magit-bundle-create) + ("t" "create tracked bundle" magit-bundle-create-tracked) + ("u" "update tracked bundle" magit-bundle-update-tracked)] + (interactive + (and (eq transient-current-command 'magit-bundle-create) + (list (read-file-name "Create bundle: " nil nil nil + (concat (file-name-nondirectory + (directory-file-name (magit-toplevel))) + ".bundle")) + (magit-completing-read-multiple "Refnames (zero or more): " + (magit-list-refnames)) + (transient-args 'magit-bundle-create)))) + (if file + (magit-git-bundle "create" file refs args) + (transient-setup 'magit-bundle-create))) + +;;;###autoload +(defun magit-bundle-create-tracked (file tag branch refs args) + "Create and track a new bundle." + (interactive + (let ((tag (magit-read-tag "Track bundle using tag")) + (branch (magit-read-branch "Bundle branch")) + (refs (magit-completing-read-multiple + "Additional refnames (zero or more): " + (magit-list-refnames)))) + (list (read-file-name "File: " nil nil nil (concat tag ".bundle")) + tag branch + (if (equal branch (magit-get-current-branch)) + (cons "HEAD" refs) + refs) + (transient-args 'magit-bundle-create)))) + (magit-git-bundle "create" file (cons branch refs) args) + (magit-git "tag" "--force" tag branch + "-m" (concat ";; git-bundle tracking\n" + (pp-to-string `((file . ,file) + (branch . ,branch) + (refs . ,refs) + (args . ,args)))))) + +;;;###autoload +(defun magit-bundle-update-tracked (tag) + "Update a bundle that is being tracked using TAG." + (interactive (list (magit-read-tag "Update bundle tracked by tag" t))) + (let (msg) + (let-alist (magit--with-temp-process-buffer + (save-excursion + (magit-git-insert "for-each-ref" "--format=%(contents)" + (concat "refs/tags/" tag))) + (setq msg (buffer-string)) + (ignore-errors (read (current-buffer)))) + (unless (and .file .branch) + (error "Tag %s does not appear to track a bundle" tag)) + (magit-git-bundle "create" .file + (cons (concat tag ".." .branch) .refs) + .args) + (magit-git "tag" "--force" tag .branch "-m" msg)))) + +;;;###autoload +(defun magit-bundle-verify (file) + "Check whether FILE is valid and applies to the current repository." + (interactive (list (magit-bundle--read-file-name "Verify bundle: "))) + (magit-process-buffer) + (magit-git-bundle "verify" file)) + +;;;###autoload +(defun magit-bundle-list-heads (file) + "List the refs in FILE." + (interactive (list (magit-bundle--read-file-name "List heads of bundle: "))) + (magit-process-buffer) + (magit-git-bundle "list-heads" file)) + +(defun magit-bundle--read-file-name (prompt) + (read-file-name prompt nil nil t (magit-file-at-point) #'file-regular-p)) + +(defun magit-git-bundle (command file &optional refs args) + (magit-git "bundle" command (magit-convert-filename-for-git file) refs args)) + +;;; _ +(provide 'magit-bundle) +;;; magit-bundle.el ends here diff --git a/emacs/elpa/magit-20241004.917/magit-clone.el b/emacs/elpa/magit-20241004.917/magit-clone.el @@ -0,0 +1,358 @@ +;;; magit-clone.el --- Clone a repository -*- lexical-binding:t -*- + +;; Copyright (C) 2008-2024 The Magit Project Contributors + +;; Author: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> +;; Maintainer: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> + +;; SPDX-License-Identifier: GPL-3.0-or-later + +;; Magit is free software: you can redistribute it and/or modify it +;; under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. +;; +;; Magit is distributed in the hope that it will be useful, but WITHOUT +;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +;; or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public +;; License for more details. +;; +;; You should have received a copy of the GNU General Public License +;; along with Magit. If not, see <https://www.gnu.org/licenses/>. + +;;; Commentary: + +;; This library implements clone commands. + +;;; Code: + +(require 'magit) + +;;; Options + +(defcustom magit-clone-set-remote-head nil + "Whether cloning creates the symbolic-ref `<remote>/HEAD'." + :package-version '(magit . "2.4.2") + :group 'magit-commands + :type 'boolean) + +(defcustom magit-clone-set-remote.pushDefault 'ask + "Whether to set the value of `remote.pushDefault' after cloning. + +If t, then set without asking. If nil, then don't set. If +`ask', then ask." + :package-version '(magit . "2.4.0") + :group 'magit-commands + :type '(choice (const :tag "set" t) + (const :tag "ask" ask) + (const :tag "don't set" nil))) + +(defcustom magit-clone-default-directory nil + "Default directory to use when `magit-clone' reads destination. +If nil (the default), then use the value of `default-directory'. +If a directory, then use that. If a function, then call that +with the remote url as only argument and use the returned value." + :package-version '(magit . "2.90.0") + :group 'magit-commands + :type '(choice (const :tag "value of default-directory") + (directory :tag "constant directory") + (function :tag "function's value"))) + +(defcustom magit-clone-always-transient nil + "Whether `magit-clone' always acts as a transient prefix command. +If nil, then a prefix argument has to be used to show the transient +popup instead of invoking the default suffix `magit-clone-regular' +directly." + :package-version '(magit . "3.0.0") + :group 'magit-commands + :type 'boolean) + +(defcustom magit-clone-name-alist + '(("\\`\\(?:github:\\|gh:\\)?\\([^:]+\\)\\'" "github.com" "github.user") + ("\\`\\(?:gitlab:\\|gl:\\)\\([^:]+\\)\\'" "gitlab.com" "gitlab.user") + ("\\`\\(?:sourcehut:\\|sh:\\)\\([^:]+\\)\\'" "git.sr.ht" "sourcehut.user")) + "Alist mapping repository names to repository urls. + +Each element has the form (REGEXP HOSTNAME USER). When the user +enters a name when a cloning command asks for a name or url, then +that is looked up in this list. The first element whose REGEXP +matches is used. + +The format specified by option `magit-clone-url-format' is used +to turn the name into an url, using HOSTNAME and the repository +name. If the provided name contains a slash, then that is used. +Otherwise if the name omits the owner of the repository, then the +default user specified in the matched entry is used. + +If USER contains a dot, then it is treated as a Git variable and +the value of that is used as the username. Otherwise it is used +as the username itself." + :package-version '(magit . "4.0.0") + :group 'magit-commands + :type '(repeat (list regexp + (string :tag "Hostname") + (string :tag "User name or git variable")))) + +(defcustom magit-clone-url-format + '(("git.sr.ht" . "git@%h:%n") + (t . "git@%h:%n.git")) + "Format(s) used when turning repository names into urls. + +In a format string, %h is the hostname and %n is the repository +name, including the name of the owner. + +The value can be a string (representing a single static format) +or an alist with elements (HOSTNAME . FORMAT) mapping hostnames +to formats. When an alist is used, the t key represents the +default. Also see `magit-clone-name-alist'." + :package-version '(magit . "4.0.0") + :group 'magit-commands + :type '(choice (string :tag "Format") + (alist :key-type (choice (string :tag "Host") + (const :tag "Default" t)) + :value-type (string :tag "Format")))) + +(defcustom magit-post-clone-hook nil + "Hook run after the repository has been successfully cloned. + +When the hook is called, `default-directory' is let-bound to the +directory where the repository has been cloned." + :package-version '(magit . "4.0.0") + :group 'magit-commands + :type 'hook) + +;;; Commands + +;;;###autoload (autoload 'magit-clone "magit-clone" nil t) +(transient-define-prefix magit-clone (&optional transient) + "Clone a repository." + :man-page "git-clone" + ["Fetch arguments" + ("-B" "Clone a single branch" "--single-branch") + ("-n" "Do not clone tags" "--no-tags") + ("-S" "Clones submodules" "--recurse-submodules" :level 6) + ("-l" "Do not optimize" "--no-local" :level 7)] + ["Setup arguments" + ("-o" "Set name of remote" ("-o" "--origin=")) + ("-b" "Set HEAD branch" ("-b" "--branch=")) + (magit-clone:--filter + :if (lambda () (magit-git-version>= "2.17.0")) + :level 7) + ("-g" "Separate git directory" "--separate-git-dir=" + transient-read-directory :level 7) + ("-t" "Use template directory" "--template=" + transient-read-existing-directory :level 6)] + ["Local sharing arguments" + ("-s" "Share objects" ("-s" "--shared" :level 7)) + ("-h" "Do not use hardlinks" "--no-hardlinks")] + ["Clone" + ("C" "regular" magit-clone-regular) + ("s" "shallow" magit-clone-shallow) + ("d" "shallow since date" magit-clone-shallow-since :level 7) + ("e" "shallow excluding" magit-clone-shallow-exclude :level 7) + (">" "sparse checkout" magit-clone-sparse + :if (lambda () (magit-git-version>= "2.25.0")) + :level 6) + ("b" "bare" magit-clone-bare) + ("m" "mirror" magit-clone-mirror)] + (interactive (list (or magit-clone-always-transient current-prefix-arg))) + (if transient + (transient-setup 'magit-clone) + (call-interactively #'magit-clone-regular))) + +(transient-define-argument magit-clone:--filter () + :description "Filter some objects" + :class 'transient-option + :key "-f" + :argument "--filter=" + :reader #'magit-clone-read-filter) + +(defun magit-clone-read-filter (prompt initial-input history) + (magit-completing-read prompt + (list "blob:none" "tree:0") + nil nil initial-input history)) + +;;;###autoload +(defun magit-clone-regular (repository directory args) + "Create a clone of REPOSITORY in DIRECTORY. +Then show the status buffer for the new repository." + (interactive (magit-clone-read-args)) + (magit-clone-internal repository directory args)) + +;;;###autoload +(defun magit-clone-shallow (repository directory args depth) + "Create a shallow clone of REPOSITORY in DIRECTORY. +Then show the status buffer for the new repository. +With a prefix argument read the DEPTH of the clone; +otherwise use 1." + (interactive (append (magit-clone-read-args) + (list (if current-prefix-arg + (read-number "Depth: " 1) + 1)))) + (magit-clone-internal repository directory + (cons (format "--depth=%s" depth) args))) + +;;;###autoload +(defun magit-clone-shallow-since (repository directory args date) + "Create a shallow clone of REPOSITORY in DIRECTORY. +Then show the status buffer for the new repository. +Exclude commits before DATE, which is read from the +user." + (interactive (append (magit-clone-read-args) + (list (transient-read-date "Exclude commits before: " + nil nil)))) + (magit-clone-internal repository directory + (cons (format "--shallow-since=%s" date) args))) + +;;;###autoload +(defun magit-clone-shallow-exclude (repository directory args exclude) + "Create a shallow clone of REPOSITORY in DIRECTORY. +Then show the status buffer for the new repository. +Exclude commits reachable from EXCLUDE, which is a +branch or tag read from the user." + (interactive (append (magit-clone-read-args) + (list (read-string "Exclude commits reachable from: ")))) + (magit-clone-internal repository directory + (cons (format "--shallow-exclude=%s" exclude) args))) + +;;;###autoload +(defun magit-clone-bare (repository directory args) + "Create a bare clone of REPOSITORY in DIRECTORY. +Then show the status buffer for the new repository." + (interactive (magit-clone-read-args)) + (magit-clone-internal repository directory (cons "--bare" args))) + +;;;###autoload +(defun magit-clone-mirror (repository directory args) + "Create a mirror of REPOSITORY in DIRECTORY. +Then show the status buffer for the new repository." + (interactive (magit-clone-read-args)) + (magit-clone-internal repository directory (cons "--mirror" args))) + +;;;###autoload +(defun magit-clone-sparse (repository directory args) + "Clone REPOSITORY into DIRECTORY and create a sparse checkout." + (interactive (magit-clone-read-args)) + (magit-clone-internal repository directory (cons "--no-checkout" args) + 'sparse)) + +(defun magit-clone-internal (repository directory args &optional sparse) + (let* ((checkout (not (member (car args) '("--bare" "--mirror")))) + (remote (or (transient-arg-value "--origin=" args) + (magit-get "clone.defaultRemote") + "origin")) + (set-push-default + (and checkout + (or (eq magit-clone-set-remote.pushDefault t) + (and magit-clone-set-remote.pushDefault + (y-or-n-p (format "Set `remote.pushDefault' to %S? " + remote))))))) + (run-hooks 'magit-credential-hook) + (setq directory (file-name-as-directory (expand-file-name directory))) + (when (file-exists-p directory) + (if (file-directory-p directory) + (when (length> (directory-files directory) 2) + (let ((name (magit-clone--url-to-name repository))) + (unless (and name + (setq directory (file-name-as-directory + (expand-file-name name directory))) + (not (file-exists-p directory))) + (user-error "%s already exists" directory)))) + (user-error "%s already exists and is not a directory" directory))) + (magit-run-git-async "clone" args "--" repository + (magit-convert-filename-for-git directory)) + ;; Don't refresh the buffer we're calling from. + (process-put magit-this-process 'inhibit-refresh t) + (set-process-sentinel + magit-this-process + (lambda (process event) + (when (memq (process-status process) '(exit signal)) + (let ((magit-process-raise-error t)) + (magit-process-sentinel process event))) + (when (and (eq (process-status process) 'exit) + (= (process-exit-status process) 0)) + (when checkout + (let ((default-directory directory)) + (when set-push-default + (setf (magit-get "remote.pushDefault") remote)) + (unless magit-clone-set-remote-head + (magit-remote-unset-head remote)))) + (when (and sparse checkout) + (when (magit-git-version< "2.25.0") + (user-error + "`git sparse-checkout' not available until Git v2.25")) + (let ((default-directory directory)) + (magit-call-git "sparse-checkout" "init" "--cone") + (magit-call-git "checkout" (magit-get-current-branch)))) + (let ((default-directory directory)) + (run-hooks 'magit-post-clone-hook)) + (with-current-buffer (process-get process 'command-buf) + (magit-status-setup-buffer directory))))))) + +(defun magit-clone-read-args () + (let ((repo (magit-clone-read-repository))) + (list repo + (read-directory-name + "Clone to: " + (if (functionp magit-clone-default-directory) + (funcall magit-clone-default-directory repo) + magit-clone-default-directory) + nil nil + (magit-clone--url-to-name repo)) + (transient-args 'magit-clone)))) + +(defun magit-clone-read-repository () + (magit-read-char-case "Clone from " nil + (?u "[u]rl or name" + (let ((str (magit-read-string-ns "Clone from url or name"))) + (if (string-match-p "\\(://\\|@\\)" str) + str + (magit-clone--name-to-url str)))) + (?p "[p]ath" + (magit-convert-filename-for-git + (read-directory-name "Clone repository: "))) + (?l "[l]ocal url" + (concat "file://" + (magit-convert-filename-for-git + (read-directory-name "Clone repository: file://")))) + (?b "or [b]undle" + (magit-convert-filename-for-git + (read-file-name "Clone from bundle: "))))) + +(defun magit-clone--url-to-name (url) + (and (string-match "\\([^/:]+?\\)\\(/?\\.git\\)?$" url) + (match-string 1 url))) + +(defun magit-clone--name-to-url (name) + (or (seq-some + (pcase-lambda (`(,re ,host ,user)) + (and (string-match re name) + (let ((repo (match-string 1 name))) + (magit-clone--format-url host user repo)))) + magit-clone-name-alist) + (user-error "Not an url and no matching entry in `%s'" + 'magit-clone-name-alist))) + +(defun magit-clone--format-url (host user repo) + (if-let ((url-format + (cond ((listp magit-clone-url-format) + (cdr (or (assoc host magit-clone-url-format) + (assoc t magit-clone-url-format)))) + ((stringp magit-clone-url-format) + magit-clone-url-format)))) + (format-spec + url-format + `((?h . ,host) + (?n . ,(if (string-search "/" repo) + repo + (if (string-search "." user) + (if-let ((user (magit-get user))) + (concat user "/" repo) + (user-error "Set %S or specify owner explicitly" user)) + (concat user "/" repo)))))) + (user-error + "Bogus `magit-clone-url-format' (bad type or missing default)"))) + +;;; _ +(provide 'magit-clone) +;;; magit-clone.el ends here diff --git a/emacs/elpa/magit-20241004.917/magit-commit.el b/emacs/elpa/magit-20241004.917/magit-commit.el @@ -0,0 +1,718 @@ +;;; magit-commit.el --- Create Git commits -*- lexical-binding:t -*- + +;; Copyright (C) 2008-2024 The Magit Project Contributors + +;; Author: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> +;; Maintainer: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> + +;; SPDX-License-Identifier: GPL-3.0-or-later + +;; Magit is free software: you can redistribute it and/or modify it +;; under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. +;; +;; Magit is distributed in the hope that it will be useful, but WITHOUT +;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +;; or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public +;; License for more details. +;; +;; You should have received a copy of the GNU General Public License +;; along with Magit. If not, see <https://www.gnu.org/licenses/>. + +;;; Commentary: + +;; This library implements commands for creating Git commits. These +;; commands just initiate the commit, support for writing the commit +;; messages is implemented in `git-commit.el'. + +;;; Code: + +(require 'magit) +(require 'magit-sequence) + +;;; Options + +(defcustom magit-commit-ask-to-stage 'verbose + "Whether to ask to stage everything when committing and nothing is staged." + :package-version '(magit . "2.3.0") + :group 'magit-commands + :type '(choice (const :tag "Ask" t) + (const :tag "Ask showing diff" verbose) + (const :tag "Stage without confirmation" stage) + (const :tag "Don't ask" nil))) + +(defcustom magit-commit-show-diff t + "Whether the relevant diff is automatically shown when committing." + :package-version '(magit . "2.3.0") + :group 'magit-commands + :type 'boolean) + +(defcustom magit-commit-extend-override-date t + "Whether using `magit-commit-extend' changes the committer date." + :package-version '(magit . "2.3.0") + :group 'magit-commands + :type 'boolean) + +(defcustom magit-commit-reword-override-date t + "Whether using `magit-commit-reword' changes the committer date." + :package-version '(magit . "2.3.0") + :group 'magit-commands + :type 'boolean) + +(defcustom magit-commit-squash-confirm t + "Whether the commit targeted by squash and fixup has to be confirmed. +When non-nil then the commit at point (if any) is used as default +choice, otherwise it has to be confirmed. This option only +affects `magit-commit-squash' and `magit-commit-fixup'. The +\"instant\" variants always require confirmation because making +an error while using those is harder to recover from." + :package-version '(magit . "2.1.0") + :group 'magit-commands + :type 'boolean) + +(defcustom magit-post-commit-hook nil + "Hook run after creating a commit without the user editing a message. + +This hook is run by `magit-refresh' if `this-command' is a member +of `magit-post-commit-hook-commands'. This only includes commands +named `magit-commit-*' that do *not* require that the user edits +the commit message in a buffer and then finishes by pressing +\\<with-editor-mode-map>\\[with-editor-finish]. + +Also see `git-commit-post-finish-hook'." + :package-version '(magit . "2.90.0") + :group 'magit-commands + :type 'hook) + +(defcustom magit-commit-diff-inhibit-same-window nil + "Whether to inhibit use of same window when showing diff while committing. + +When writing a commit, then a diff of the changes to be committed +is automatically shown. The idea is that the diff is shown in a +different window of the same frame and for most users that just +works. In other words most users can completely ignore this +option because its value doesn't make a difference for them. + +However for users who configured Emacs to never create a new +window even when the package explicitly tries to do so, then +displaying two new buffers necessarily means that the first is +immediately replaced by the second. In our case the message +buffer is immediately replaced by the diff buffer, which is of +course highly undesirable. + +A workaround is to suppress this user configuration in this +particular case. Users have to explicitly opt-in by toggling +this option. We cannot enable the workaround unconditionally +because that again causes issues for other users: if the frame +is too tiny or the relevant settings too aggressive, then the +diff buffer would end up being displayed in a new frame. + +Also see https://github.com/magit/magit/issues/4132." + :package-version '(magit . "3.3.0") + :group 'magit-commands + :type 'boolean) + +;;; Popup + +;;;###autoload (autoload 'magit-commit "magit-commit" nil t) +(transient-define-prefix magit-commit () + "Create a new commit or replace an existing commit." + :info-manual "(magit)Initiating a Commit" + :man-page "git-commit" + ["Arguments" + ("-a" "Stage all modified and deleted files" ("-a" "--all")) + ("-e" "Allow empty commit" "--allow-empty") + ("-v" "Show diff of changes to be committed" ("-v" "--verbose")) + ("-n" "Disable hooks" ("-n" "--no-verify")) + ("-R" "Claim authorship and reset author date" "--reset-author") + (magit:--author :description "Override the author") + (7 "-D" "Override the author date" "--date=" transient-read-date) + ("-s" "Add Signed-off-by line" ("-s" "--signoff")) + (5 magit:--gpg-sign) + (magit-commit:--reuse-message)] + [["Create" + ("c" "Commit" magit-commit-create)] + ["Edit HEAD" + ("e" "Extend" magit-commit-extend) + ("w" "Reword" magit-commit-reword) + ("a" "Amend" magit-commit-amend) + (6 "n" "Reshelve" magit-commit-reshelve)] + ["Edit" + ("f" "Fixup" magit-commit-fixup) + ("s" "Squash" magit-commit-squash) + ("A" "Augment" magit-commit-augment) + (6 "x" "Absorb changes" magit-commit-autofixup) + (6 "X" "Absorb modules" magit-commit-absorb-modules)] + ["" + ("F" "Instant fixup" magit-commit-instant-fixup) + ("S" "Instant squash" magit-commit-instant-squash)]] + (interactive) + (if-let ((buffer (magit-commit-message-buffer))) + (switch-to-buffer buffer) + (transient-setup 'magit-commit))) + +(defun magit-commit-arguments nil + (transient-args 'magit-commit)) + +(transient-define-argument magit-commit:--reuse-message () + :description "Reuse commit message" + :class 'transient-option + :shortarg "-C" + :argument "--reuse-message=" + :reader #'magit-read-reuse-message + :history-key 'magit-revision-history) + +(defun magit-read-reuse-message (prompt &optional default history) + (magit-completing-read prompt (magit-list-refnames) + nil nil nil history + (or default + (and (magit-rev-verify "ORIG_HEAD") + "ORIG_HEAD")))) + +;;; Commands + +;;;###autoload +(defun magit-commit-create (&optional args) + "Create a new commit on `HEAD'. +With a prefix argument, amend to the commit at `HEAD' instead. +\n(git commit [--amend] ARGS)" + (interactive (if current-prefix-arg + (list (cons "--amend" (magit-commit-arguments))) + (list (magit-commit-arguments)))) + (cond ((member "--all" args) + (setq this-command 'magit-commit--all)) + ((member "--allow-empty" args) + (setq this-command 'magit-commit--allow-empty))) + (when (setq args (magit-commit-assert args)) + (let ((default-directory (magit-toplevel))) + (magit-run-git-with-editor "commit" args)))) + +;;;###autoload +(defun magit-commit-amend (&optional args) + "Amend the last commit. +\n(git commit --amend ARGS)" + (interactive (list (magit-commit-arguments))) + (magit-commit-amend-assert) + (magit-run-git-with-editor "commit" "--amend" args)) + +;;;###autoload +(defun magit-commit-extend (&optional args override-date) + "Amend the last commit, without editing the message. + +With a prefix argument keep the committer date, otherwise change +it. The option `magit-commit-extend-override-date' can be used +to inverse the meaning of the prefix argument. +\n(git commit --amend --no-edit)" + (interactive (list (magit-commit-arguments) + (if current-prefix-arg + (not magit-commit-extend-override-date) + magit-commit-extend-override-date))) + (when (setq args (magit-commit-assert args)) + (magit-commit-amend-assert) + (if override-date + (magit-run-git-with-editor "commit" "--amend" "--no-edit" args) + (with-environment-variables + (("GIT_COMMITTER_DATE" (magit-rev-format "%cD"))) + (magit-run-git-with-editor "commit" "--amend" "--no-edit" args))))) + +;;;###autoload +(defun magit-commit-reword (&optional args override-date) + "Reword the last commit, ignoring staged changes. + +With a prefix argument keep the committer date, otherwise change +it. The option `magit-commit-reword-override-date' can be used +to inverse the meaning of the prefix argument. + +Non-interactively respect the optional OVERRIDE-DATE argument +and ignore the option. +\n(git commit --amend --only)" + (interactive (list (magit-commit-arguments) + (if current-prefix-arg + (not magit-commit-reword-override-date) + magit-commit-reword-override-date))) + (magit-commit-amend-assert) + (cl-pushnew "--allow-empty" args :test #'equal) + (if override-date + (magit-run-git-with-editor "commit" "--amend" "--only" args) + (with-environment-variables + (("GIT_COMMITTER_DATE" (magit-rev-format "%cD"))) + (magit-run-git-with-editor "commit" "--amend" "--only" args)))) + +;;;###autoload +(defun magit-commit-fixup (&optional commit args) + "Create a fixup commit. + +With a prefix argument the target COMMIT has to be confirmed. +Otherwise the commit at point may be used without confirmation +depending on the value of option `magit-commit-squash-confirm'." + (interactive (list (magit-commit-at-point) + (magit-commit-arguments))) + (magit-commit-squash-internal "--fixup" commit args)) + +;;;###autoload +(defun magit-commit-squash (&optional commit args) + "Create a squash commit, without editing the squash message. + +With a prefix argument the target COMMIT has to be confirmed. +Otherwise the commit at point may be used without confirmation +depending on the value of option `magit-commit-squash-confirm'. + +If you want to immediately add a message to the squash commit, +then use `magit-commit-augment' instead of this command." + (interactive (list (magit-commit-at-point) + (magit-commit-arguments))) + (magit-commit-squash-internal "--squash" commit args)) + +;;;###autoload +(defun magit-commit-augment (&optional commit args) + "Create a squash commit, editing the squash message. + +With a prefix argument the target COMMIT has to be confirmed. +Otherwise the commit at point may be used without confirmation +depending on the value of option `magit-commit-squash-confirm'." + (interactive (list (magit-commit-at-point) + (magit-commit-arguments))) + (magit-commit-squash-internal "--squash" commit args nil t)) + +;;;###autoload +(defun magit-commit-instant-fixup (&optional commit args) + "Create a fixup commit targeting COMMIT and instantly rebase." + (interactive (list (magit-commit-at-point) + (magit-commit-arguments))) + (magit-commit-squash-internal "--fixup" commit args t)) + +;;;###autoload +(defun magit-commit-instant-squash (&optional commit args) + "Create a squash commit targeting COMMIT and instantly rebase." + (interactive (list (magit-commit-at-point) + (magit-commit-arguments))) + (magit-commit-squash-internal "--squash" commit args t)) + +(defun magit-commit-squash-internal + (option commit &optional args rebase edit confirmed) + (when-let ((args (magit-commit-assert args (not edit)))) + (when commit + (when (and rebase (not (magit-rev-ancestor-p commit "HEAD"))) + (magit-read-char-case + (format "%s isn't an ancestor of HEAD. " commit) nil + (?c "[c]reate without rebasing" (setq rebase nil)) + (?s "[s]elect other" (setq commit nil)) + (?a "[a]bort" (user-error "Quit"))))) + (when commit + (setq commit (magit-rebase-interactive-assert commit t))) + (if (and commit + (or confirmed + (not (or rebase + current-prefix-arg + magit-commit-squash-confirm)))) + (let ((magit-commit-show-diff nil)) + (push (concat option "=" commit) args) + (unless edit + (push "--no-edit" args)) + (if rebase + (magit-with-editor + (magit-call-git + "commit" "--no-gpg-sign" + (seq-remove (apply-partially #'string-prefix-p "--gpg-sign=") + args))) + (magit-run-git-with-editor "commit" args)) + t) ; The commit was created; used by below lambda. + (let ((winconf (and magit-commit-show-diff + (current-window-configuration)))) + (magit-log-select + (lambda (commit) + (when (and (magit-commit-squash-internal option commit args + rebase edit t) + rebase) + (magit-commit-amend-assert commit) + (magit-rebase-interactive-1 commit + (list "--autosquash" "--autostash" "--keep-empty") + "" "true" nil t)) + (when winconf + (set-window-configuration winconf))) + (format "Type %%p on a commit to %s into it," + (substring option 2)) + nil nil nil commit)) + (when magit-commit-show-diff + (let ((magit-display-buffer-noselect t)) + (apply #'magit-diff-staged nil (magit-diff-arguments))))))) + +(defun magit-commit-amend-assert (&optional commit) + (when-let ((branches (magit-list-publishing-branches commit))) + (let ((m1 "This commit has already been published to ") + (m2 ".\nDo you really want to modify it")) + (magit-confirm 'amend-published + (concat m1 "%s" m2) + (concat m1 "%d public branches" m2) + nil branches)))) + +(defun magit-commit-assert (args &optional strict) + (cond + ((or (magit-anything-staged-p) + (and (magit-anything-unstaged-p) + ;; ^ Everything of nothing is still nothing. + (member "--all" args)) + (and (not strict) + ;; ^ For amend variants that don't make sense otherwise. + (or (member "--amend" args) + (member "--allow-empty" args) + (member "--reset-author" args) + (member "--signoff" args) + (transient-arg-value "--author=" args) + (transient-arg-value "--date=" args)))) + (or args (list "--"))) + ((and (magit-rebase-in-progress-p) + (not (magit-anything-unstaged-p)) + (y-or-n-p "Nothing staged. Continue in-progress rebase? ")) + (setq this-command #'magit-rebase-continue) + (magit-run-git-sequencer "rebase" "--continue") + nil) + ((file-exists-p (expand-file-name "MERGE_MSG" (magit-gitdir))) + (cond ((magit-anything-unmerged-p) + (user-error "Unresolved conflicts")) + ((and (magit-anything-unstaged-p) + (not (y-or-n-p + "Proceed with merge despite unstaged changes? "))) + (user-error "Abort")) + ((or args (list "--"))))) + ((not (magit-anything-unstaged-p)) + (user-error "Nothing staged (or unstaged)")) + (magit-commit-ask-to-stage + (when (eq magit-commit-ask-to-stage 'verbose) + (magit-diff-unstaged)) + (prog1 (when (or (eq magit-commit-ask-to-stage 'stage) + (y-or-n-p + "Nothing staged. Commit all uncommitted changes? ")) + (setq this-command 'magit-commit--all) + (cons "--all" (or args (list "--")))) + (when (and (eq magit-commit-ask-to-stage 'verbose) + (derived-mode-p 'magit-diff-mode)) + (magit-mode-bury-buffer)))) + (t + (user-error "Nothing staged")))) + +(defvar magit--reshelve-history nil) + +;;;###autoload +(defun magit-commit-reshelve (date update-author &optional args) + "Change the committer date and possibly the author date of `HEAD'. + +The current time is used as the initial minibuffer input and the +original author or committer date is available as the previous +history element. + +Both the author and the committer dates are changed, unless one +of the following is true, in which case only the committer date +is updated: +- You are not the author of the commit that is being reshelved. +- The command was invoked with a prefix argument. +- Non-interactively if UPDATE-AUTHOR is nil." + (interactive + (let ((update-author (and (magit-rev-author-p "HEAD") + (not current-prefix-arg)))) + (push (magit-rev-format (if update-author "%ad" "%cd") "HEAD" + (concat "--date=format:%F %T %z")) + magit--reshelve-history) + (list (read-string (if update-author + "Change author and committer dates to: " + "Change committer date to: ") + (cons (format-time-string "%F %T %z") 17) + 'magit--reshelve-history) + update-author + (magit-commit-arguments)))) + (with-environment-variables (("GIT_COMMITTER_DATE" date)) + (magit-run-git "commit" "--amend" "--no-edit" + (and update-author (concat "--date=" date)) + args))) + +;;;###autoload +(defun magit-commit-absorb-modules (phase commit) + "Spread modified modules across recent commits." + (interactive (list 'select (magit-get-upstream-branch))) + (let ((modules (magit-list-modified-modules))) + (unless modules + (user-error "There are no modified modules that could be absorbed")) + (when commit + (setq commit (magit-rebase-interactive-assert commit t))) + (if (and commit (eq phase 'run)) + (progn + (dolist (module modules) + (when-let ((msg (magit-git-string + "log" "-1" "--format=%s" + (concat commit "..") "--" module))) + (magit-git "commit" "-m" (concat "fixup! " msg) + "--only" "--" module))) + (magit-refresh) + t) + (magit-log-select + (lambda (commit) + (magit-commit-absorb-modules 'run commit)) + nil nil nil nil commit)))) + +;;;###autoload (autoload 'magit-commit-absorb "magit-commit" nil t) +(transient-define-prefix magit-commit-absorb (phase commit args) + "Spread staged changes across recent commits. +With a prefix argument use a transient command to select infix +arguments. This command requires git-absorb executable, which +is available from https://github.com/tummychow/git-absorb. +See `magit-commit-autofixup' for an alternative implementation." + ["Arguments" + ("-f" "Skip safety checks" ("-f" "--force")) + ("-v" "Display more output" ("-v" "--verbose"))] + ["Actions" + ("x" "Absorb" magit-commit-absorb)] + (interactive (if current-prefix-arg + (list 'transient nil nil) + (list 'select + (magit-get-upstream-branch) + (transient-args 'magit-commit-absorb)))) + (if (eq phase 'transient) + (transient-setup 'magit-commit-absorb) + (unless (magit-git-executable-find "git-absorb") + (user-error "This command requires the git-absorb executable, which %s" + "is available from https://github.com/tummychow/git-absorb")) + (unless (magit-anything-staged-p) + (if (magit-anything-unstaged-p) + (if (y-or-n-p "Nothing staged. Absorb all unstaged changes? ") + (magit-with-toplevel + (magit-run-git "add" "-u" ".")) + (user-error "Abort")) + (user-error "There are no changes that could be absorbed"))) + (when commit + (setq commit (magit-rebase-interactive-assert commit t))) + (if (and commit (eq phase 'run)) + (progn (magit-run-git-async "absorb" "-v" args "-b" commit) t) + (magit-log-select + (lambda (commit) + (with-no-warnings ; about non-interactive use + (magit-commit-absorb 'run commit args))) + nil nil nil nil commit)))) + +;;;###autoload (autoload 'magit-commit-autofixup "magit-commit" nil t) +(transient-define-prefix magit-commit-autofixup (phase commit args) + "Spread staged or unstaged changes across recent commits. + +If there are any staged then spread only those, otherwise +spread all unstaged changes. With a prefix argument use a +transient command to select infix arguments. + +This command requires the git-autofixup script, which is +available from https://github.com/torbiak/git-autofixup. +See `magit-commit-absorb' for an alternative implementation." + ["Arguments" + (magit-autofixup:--context) + (magit-autofixup:--strict)] + ["Actions" + ("x" "Absorb" magit-commit-autofixup)] + (interactive (if current-prefix-arg + (list 'transient nil nil) + (list 'select + (magit-get-upstream-branch) + (transient-args 'magit-commit-autofixup)))) + (if (eq phase 'transient) + (transient-setup 'magit-commit-autofixup) + (unless (magit-git-executable-find "git-autofixup") + (user-error "This command requires the git-autofixup script, which %s" + "is available from https://github.com/torbiak/git-autofixup")) + (unless (magit-anything-modified-p) + (user-error "There are no changes that could be absorbed")) + (when commit + (setq commit (magit-rebase-interactive-assert commit t))) + (if (and commit (eq phase 'run)) + (progn (magit-run-git-async "autofixup" "-vv" args commit) t) + (magit-log-select + (lambda (commit) + (with-no-warnings ; about non-interactive use + (magit-commit-autofixup 'run commit args))) + nil nil nil nil commit)))) + +(transient-define-argument magit-autofixup:--context () + :description "Diff context lines" + :class 'transient-option + :shortarg "-c" + :argument "--context=" + :reader #'transient-read-number-N0) + +(transient-define-argument magit-autofixup:--strict () + :description "Strictness" + :class 'transient-option + :shortarg "-s" + :argument "--strict=" + :reader #'transient-read-number-N0) + +(defvar magit-post-commit-hook-commands + '(magit-commit-extend + magit-commit-fixup + magit-commit-augment + magit-commit-instant-fixup + magit-commit-instant-squash)) + +(defun magit-run-post-commit-hook () + (when (and (not this-command) + (memq last-command magit-post-commit-hook-commands)) + (run-hooks 'magit-post-commit-hook))) + +;;; Pending Diff + +(defun magit-commit-diff () + (magit-repository-local-set 'this-commit-command + (if (eq this-command 'with-editor-finish) + 'magit-commit--rebase + last-command)) + (when (and git-commit-mode magit-commit-show-diff) + (when-let ((diff-buffer (magit-get-mode-buffer 'magit-diff-mode))) + ;; This window just started displaying the commit message + ;; buffer. Without this that buffer would immediately be + ;; replaced with the diff buffer. See #2632. + (unrecord-window-buffer nil diff-buffer)) + (message "Diffing changes to be committed (C-g to abort diffing)") + (let ((inhibit-quit nil)) + (condition-case nil + (magit-commit-diff-1) + (quit))))) + +(defun magit-commit-diff-1 () + (let ((rev nil) + (arg "--cached") + (command (magit-repository-local-get 'this-commit-command)) + (staged (magit-anything-staged-p)) + (unstaged + ;; Escape $GIT_DIR because `magit-anything-unstaged-p' + ;; requires a working tree. + (magit-with-toplevel + (magit-anything-unstaged-p))) + (squash (let ((f (expand-file-name "rebase-merge/rewritten-pending" + (magit-gitdir)))) + (and (file-exists-p f) (length (magit-file-lines f))))) + (noalt nil)) + (pcase (list staged unstaged command) + ((and `(,_ ,_ magit-commit--rebase) + (guard (integerp squash))) + (setq rev (format "HEAD~%s" squash))) + (`(,_ ,_ magit-commit-amend) + (setq rev "HEAD^")) + (`(nil nil magit-commit--allow-empty) + (setq rev "HEAD") + (setq arg nil)) + ((or `(,_ ,_ magit-commit-reword) + `(nil nil ,_)) + (setq rev "HEAD^..HEAD") + (setq arg nil)) + (`(,_ t magit-commit--all) + (setq rev "HEAD") + (setq arg nil)) + (`(nil t handle-switch-frame) + ;; Either --all or --allow-empty. Assume it is the former. + (setq rev "HEAD") + (setq arg nil))) + (cond + ((not + (and (eq this-command 'magit-diff-while-committing) + (and-let* ((buf (magit-get-mode-buffer + 'magit-diff-mode nil 'selected))) + (and (equal rev (buffer-local-value 'magit-buffer-range buf)) + (equal arg (buffer-local-value 'magit-buffer-typearg buf))))))) + ((eq command 'magit-commit-amend) + (setq rev nil)) + ((or squash + (file-exists-p (expand-file-name "rebase-merge/amend" (magit-gitdir)))) + (setq rev "HEAD^")) + (t + (message "No alternative diff while committing") + (setq noalt t))) + (unless noalt + (let ((magit-inhibit-save-previous-winconf 'unset) + (magit-display-buffer-noselect t) + (display-buffer-overriding-action + display-buffer-overriding-action)) + (when magit-commit-diff-inhibit-same-window + (setq display-buffer-overriding-action + '(nil (inhibit-same-window . t)))) + (magit-diff-setup-buffer rev arg (car (magit-diff-arguments)) nil + (cond ((equal rev "HEAD") 'staged) + ((equal rev "HEAD^..HEAD") 'committed) + ('undefined))))))) + +(add-hook 'server-switch-hook #'magit-commit-diff) +(add-hook 'with-editor-filter-visit-hook #'magit-commit-diff) + +(add-to-list 'with-editor-server-window-alist + (cons git-commit-filename-regexp #'switch-to-buffer)) + +(defun magit-commit--reset-command () + (magit-repository-local-delete 'this-commit-command)) + +;;; Message Utilities + +(defun magit-commit-message-buffer () + (let* ((find-file-visit-truename t) ; git uses truename of COMMIT_EDITMSG + (topdir (magit-toplevel))) + (--first (equal topdir (with-current-buffer it + (and git-commit-mode (magit-toplevel)))) + (append (buffer-list (selected-frame)) + (buffer-list))))) + +(defvar magit-commit-add-log-insert-function #'magit-commit-add-log-insert + "Used by `magit-commit-add-log' to insert a single entry.") + +(defun magit-commit-add-log () + "Add a stub for the current change into the commit message buffer. +If no commit is in progress, then initiate it. Use the function +specified by variable `magit-commit-add-log-insert-function' to +actually insert the entry." + (interactive) + (pcase-let* ((hunk (and (magit-section-match 'hunk) + (magit-current-section))) + (log (magit-commit-message-buffer)) + (`(,buf ,pos) (magit-diff-visit-file--noselect))) + (unless log + (unless (magit-commit-assert nil) + (user-error "Abort")) + (magit-commit-create) + (while (not (setq log (magit-commit-message-buffer))) + (sit-for 0.01))) + (magit--with-temp-position buf pos + (funcall magit-commit-add-log-insert-function log + (magit-file-relative-name) + (and hunk (add-log-current-defun)))))) + +(defun magit-commit-add-log-insert (buffer file defun) + (with-current-buffer buffer + (undo-boundary) + (goto-char (point-max)) + (while (re-search-backward (concat "^" comment-start) nil t)) + (save-restriction + (narrow-to-region (point-min) (point)) + (cond ((re-search-backward (format "* %s\\(?: (\\([^)]+\\))\\)?: " file) + nil t) + (when (equal (match-string 1) defun) + (setq defun nil)) + (re-search-forward ": ")) + (t + (when (re-search-backward "^[\\*(].+\n" nil t) + (goto-char (match-end 0))) + (while (re-search-forward "^[^\\*\n].*\n" nil t)) + (if defun + (progn (insert (format "* %s (%s): \n" file defun)) + (setq defun nil)) + (insert (format "* %s: \n" file))) + (backward-char) + (unless (looking-at "\n[\n\\']") + (insert ?\n) + (backward-char)))) + (when defun + (forward-line) + (let ((limit (save-excursion + (and (re-search-forward "^\\*" nil t) + (point))))) + (unless (or (looking-back (format "(%s): " defun) + (line-beginning-position)) + (re-search-forward (format "^(%s): " defun) limit t)) + (while (re-search-forward "^[^\\*\n].*\n" limit t)) + (insert (format "(%s): \n" defun)) + (backward-char))))))) + +;;; _ +(provide 'magit-commit) +;;; magit-commit.el ends here diff --git a/emacs/elpa/magit-20241004.917/magit-core.el b/emacs/elpa/magit-20241004.917/magit-core.el @@ -0,0 +1,123 @@ +;;; magit-core.el --- Core functionality -*- lexical-binding:t -*- + +;; Copyright (C) 2008-2024 The Magit Project Contributors + +;; Author: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> +;; Maintainer: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> + +;; SPDX-License-Identifier: GPL-3.0-or-later + +;; Magit is free software: you can redistribute it and/or modify it +;; under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. +;; +;; Magit is distributed in the hope that it will be useful, but WITHOUT +;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +;; or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public +;; License for more details. +;; +;; You should have received a copy of the GNU General Public License +;; along with Magit. If not, see <https://www.gnu.org/licenses/>. + +;;; Commentary: + +;; This library requires several other libraries, so that yet other +;; libraries can just require this one, instead of having to require +;; all the other ones. In other words this separates the low-level +;; stuff from the rest. It also defines some Custom groups. + +;;; Code: + +(require 'magit-base) +(require 'magit-git) +(require 'magit-mode) +(require 'magit-margin) +(require 'magit-process) +(require 'magit-transient) +(require 'magit-autorevert) + +;;; Options + +(defgroup magit nil + "Controlling Git from Emacs." + :link '(url-link "https://magit.vc") + :link '(info-link "(magit)FAQ") + :link '(info-link "(magit)") + :group 'tools) + +(defgroup magit-essentials nil + "Options that every Magit user should briefly think about. + +Each of these options falls into one or more of these categories: + +* Options that affect Magit's behavior in fundamental ways. +* Options that affect safety. +* Options that affect performance. +* Options that are of a personal nature." + :link '(info-link "(magit)Essential Settings") + :group 'magit) + +(defgroup magit-miscellaneous nil + "Miscellaneous Magit options." + :group 'magit) + +(defgroup magit-commands nil + "Options controlling behavior of certain commands." + :group 'magit) + +(defgroup magit-modes nil + "Modes used or provided by Magit." + :group 'magit) + +(defgroup magit-buffers nil + "Options concerning Magit buffers." + :link '(info-link "(magit)Modes and Buffers") + :group 'magit) + +(defgroup magit-refresh nil + "Options controlling how Magit buffers are refreshed." + :link '(info-link "(magit)Automatic Refreshing of Magit Buffers") + :group 'magit + :group 'magit-buffers) + +(defgroup magit-faces nil + "Faces used by Magit." + :group 'magit + :group 'faces) + +(custom-add-to-group 'magit-faces 'diff-refine-added 'custom-face) +(custom-add-to-group 'magit-faces 'diff-refine-removed 'custom-face) + +(defgroup magit-extensions nil + "Extensions to Magit." + :group 'magit) + +(custom-add-to-group 'magit-modes 'git-commit 'custom-group) +(custom-add-to-group 'magit-faces 'git-commit-faces 'custom-group) +(custom-add-to-group 'magit-modes 'git-rebase 'custom-group) +(custom-add-to-group 'magit-faces 'git-rebase-faces 'custom-group) +(custom-add-to-group 'magit 'magit-section 'custom-group) +(custom-add-to-group 'magit-faces 'magit-section-faces 'custom-group) +(custom-add-to-group 'magit-process 'with-editor 'custom-group) + +(defgroup magit-related nil + "Options that are relevant to Magit but that are defined elsewhere." + :link '(custom-group-link vc) + :link '(custom-group-link smerge) + :link '(custom-group-link ediff) + :link '(custom-group-link auto-revert) + :group 'magit + :group 'magit-extensions + :group 'magit-essentials) + +(custom-add-to-group 'magit-related 'auto-revert-check-vc-info 'custom-variable) +(custom-add-to-group 'magit-auto-revert 'auto-revert-check-vc-info 'custom-variable) + +(custom-add-to-group 'magit-related 'ediff-window-setup-function 'custom-variable) +(custom-add-to-group 'magit-related 'smerge-refine-ignore-whitespace 'custom-variable) +(custom-add-to-group 'magit-related 'vc-follow-symlinks 'custom-variable) + +;;; _ +(provide 'magit-core) +;;; magit-core.el ends here diff --git a/emacs/elpa/magit-20241004.917/magit-diff.el b/emacs/elpa/magit-20241004.917/magit-diff.el @@ -0,0 +1,3572 @@ +;;; magit-diff.el --- Inspect Git diffs -*- lexical-binding:t -*- + +;; Copyright (C) 2008-2024 The Magit Project Contributors + +;; Author: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> +;; Maintainer: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> + +;; SPDX-License-Identifier: GPL-3.0-or-later + +;; Magit is free software: you can redistribute it and/or modify it +;; under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. +;; +;; Magit is distributed in the hope that it will be useful, but WITHOUT +;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +;; or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public +;; License for more details. +;; +;; You should have received a copy of the GNU General Public License +;; along with Magit. If not, see <https://www.gnu.org/licenses/>. + +;;; Commentary: + +;; This library implements support for looking at Git diffs and +;; commits. + +;;; Code: + +(require 'magit-core) +(require 'git-commit) + +(eval-when-compile (require 'ansi-color)) +(require 'diff-mode) +(require 'image) +(require 'smerge-mode) + +;; For `magit-diff-popup' +(declare-function magit-stash-show "magit-stash" (stash &optional args files)) +;; For `magit-diff-visit-file' +(declare-function magit-find-file-noselect "magit-files" (rev file)) +(declare-function magit-status-setup-buffer "magit-status" (&optional directory)) +;; For `magit-diff-while-committing' +(declare-function magit-commit-diff-1 "magit-commit" ()) +(declare-function magit-commit-message-buffer "magit-commit" ()) +;; For `magit-insert-revision-gravatar' +(defvar gravatar-size) +;; For `magit-show-commit' and `magit-diff-show-or-scroll' +(declare-function magit-current-blame-chunk "magit-blame" (&optional type noerror)) +(declare-function magit-blame-mode "magit-blame" (&optional arg)) +(defvar magit-blame-mode) +;; For `magit-diff-show-or-scroll' +(declare-function git-rebase-current-line "git-rebase" ()) +;; For `magit-diff-unmerged' +(declare-function magit-merge-in-progress-p "magit-merge" ()) +(declare-function magit--merge-range "magit-merge" (&optional head)) +;; For `magit-diff--dwim' +(declare-function forge--pullreq-range "forge-pullreq" + (pullreq &optional endpoints)) +(declare-function forge--pullreq-ref "forge-pullreq" (pullreq)) +;; For `magit-diff-wash-diff' +(declare-function ansi-color-apply-on-region "ansi-color") +;; For `magit-diff-wash-submodule' +(declare-function magit-log-wash-log "magit-log" (style args)) +;; For keymaps and menus +(declare-function magit-apply "magit-apply" (&rest args)) +(declare-function magit-stage "magit-apply" (&optional indent)) +(declare-function magit-unstage "magit-apply" ()) +(declare-function magit-discard "magit-apply" ()) +(declare-function magit-reverse "magit-apply" (&rest args)) +(declare-function magit-file-rename "magit-files" (file newname)) +(declare-function magit-file-untrack "magit-files" (files &optional force)) +(declare-function magit-commit-add-log "magit-commit" ()) +(declare-function magit-diff-trace-definition "magit-log" ()) +(declare-function magit-patch-save "magit-patch" (files &optional arg)) +(declare-function magit-do-async-shell-command "magit-extras" (file)) +(declare-function magit-add-change-log-entry "magit-extras" + (&optional whoami file-name other-window)) +(declare-function magit-add-change-log-entry-other-window "magit-extras" + (&optional whoami file-name)) +(declare-function magit-diff-edit-hunk-commit "magit-extras" (file)) +(declare-function magit-smerge-keep-current "magit-apply" ()) +(declare-function magit-smerge-keep-all "magit-apply" ()) +(declare-function magit-smerge-keep-upper "magit-apply" ()) +(declare-function magit-smerge-keep-base "magit-apply" ()) +(declare-function magit-smerge-keep-lower "magit-apply" ()) + +(eval-when-compile + (cl-pushnew 'orig-rev eieio--known-slot-names) + (cl-pushnew 'action-type eieio--known-slot-names) + (cl-pushnew 'target eieio--known-slot-names)) + +;;; Options +;;;; Diff Mode + +(defgroup magit-diff nil + "Inspect and manipulate Git diffs." + :link '(info-link "(magit)Diffing") + :group 'magit-commands + :group 'magit-modes) + +(defcustom magit-diff-mode-hook nil + "Hook run after entering Magit-Diff mode." + :group 'magit-diff + :type 'hook) + +(defcustom magit-diff-sections-hook + '(magit-insert-diff + magit-insert-xref-buttons) + "Hook run to insert sections into a `magit-diff-mode' buffer." + :package-version '(magit . "2.3.0") + :group 'magit-diff + :type 'hook) + +(defcustom magit-diff-expansion-threshold 60 + "After how many seconds not to expand anymore diffs. + +Except in status buffers, diffs usually start out fully expanded. +Because that can take a long time, all diffs that haven't been +fontified during a refresh before the threshold defined here are +instead displayed with their bodies collapsed. + +Note that this can cause sections that were previously expanded +to be collapsed. So you should not pick a very low value here. + +The hook function `magit-diff-expansion-threshold' has to be a +member of `magit-section-set-visibility-hook' for this option +to have any effect." + :package-version '(magit . "2.9.0") + :group 'magit-diff + :type 'float) + +(defcustom magit-diff-highlight-hunk-body t + "Whether to highlight bodies of selected hunk sections. +This only has an effect if `magit-diff-highlight' is a +member of `magit-section-highlight-hook', which see." + :package-version '(magit . "2.1.0") + :group 'magit-diff + :type 'boolean) + +(defcustom magit-diff-highlight-hunk-region-functions + '(magit-diff-highlight-hunk-region-dim-outside + magit-diff-highlight-hunk-region-using-overlays) + "The functions used to highlight the hunk-internal region. + +`magit-diff-highlight-hunk-region-dim-outside' overlays the outside +of the hunk internal selection with a face that causes the added and +removed lines to have the same background color as context lines. +This function should not be removed from the value of this option. + +`magit-diff-highlight-hunk-region-using-overlays' and +`magit-diff-highlight-hunk-region-using-underline' emphasize the +region by placing delimiting horizontal lines before and after it. +The underline variant was implemented because Eli said that is +how we should do it. However the overlay variant actually works +better. Also see https://github.com/magit/magit/issues/2758. + +Instead of, or in addition to, using delimiting horizontal lines, +to emphasize the boundaries, you may wish to emphasize the text +itself, using `magit-diff-highlight-hunk-region-using-face'. + +In terminal frames it's not possible to draw lines as the overlay +and underline variants normally do, so there they fall back to +calling the face function instead." + :package-version '(magit . "2.9.0") + :set-after '(magit-diff-show-lines-boundaries) + :group 'magit-diff + :type 'hook + :options '(magit-diff-highlight-hunk-region-dim-outside + magit-diff-highlight-hunk-region-using-underline + magit-diff-highlight-hunk-region-using-overlays + magit-diff-highlight-hunk-region-using-face)) + +(defcustom magit-diff-unmarked-lines-keep-foreground t + "Whether `magit-diff-highlight-hunk-region-dim-outside' preserves foreground. +When this is set to nil, then that function only adjusts the +foreground color but added and removed lines outside the region +keep their distinct foreground colors." + :package-version '(magit . "2.9.0") + :group 'magit-diff + :type 'boolean) + +(defcustom magit-diff-refine-hunk nil + "Whether to show word-granularity differences within diff hunks. + +nil Never show fine differences. +t Show fine differences for the current diff hunk only. +`all' Show fine differences for all displayed diff hunks." + :group 'magit-diff + :safe (lambda (val) (memq val '(nil t all))) + :type '(choice (const :tag "Never" nil) + (const :tag "Current" t) + (const :tag "All" all))) + +(defcustom magit-diff-refine-ignore-whitespace smerge-refine-ignore-whitespace + "Whether to ignore whitespace changes in word-granularity differences." + :package-version '(magit . "3.0.0") + :set-after '(smerge-refine-ignore-whitespace) + :group 'magit-diff + :safe 'booleanp + :type 'boolean) + +(put 'magit-diff-refine-hunk 'permanent-local t) + +(defcustom magit-diff-adjust-tab-width nil + "Whether to adjust the width of tabs in diffs. + +Determining the correct width can be expensive if it requires +opening large and/or many files, so the widths are cached in +the variable `magit-diff--tab-width-cache'. Set that to nil +to invalidate the cache. + +nil Never adjust tab width. Use `tab-width's value from + the Magit buffer itself instead. + +t If the corresponding file-visiting buffer exits, then + use `tab-width's value from that buffer. Doing this is + cheap, so this value is used even if a corresponding + cache entry exists. + +`always' If there is no such buffer, then temporarily visit the + file to determine the value. + +NUMBER Like `always', but don't visit files larger than NUMBER + bytes." + :package-version '(magit . "2.12.0") + :group 'magit-diff + :type '(choice (const :tag "Never" nil) + (const :tag "If file-visiting buffer exists" t) + (integer :tag "If file isn't larger than N bytes") + (const :tag "Always" always))) + +(defcustom magit-diff-paint-whitespace t + "Specify where to highlight whitespace errors. + +nil Never highlight whitespace errors. +t Highlight whitespace errors everywhere. +`uncommitted' Only highlight whitespace errors in diffs + showing uncommitted changes. + +For backward compatibility `status' is treated as a synonym +for `uncommitted'. + +The option `magit-diff-paint-whitespace-lines' controls for +what lines (added/remove/context) errors are highlighted. + +The options `magit-diff-highlight-trailing' and +`magit-diff-highlight-indentation' control what kind of +whitespace errors are highlighted." + :group 'magit-diff + :safe (lambda (val) (memq val '(t nil uncommitted status))) + :type '(choice (const :tag "In all diffs" t) + (const :tag "Only in uncommitted changes" uncommitted) + (const :tag "Never" nil))) + +(defcustom magit-diff-paint-whitespace-lines t + "Specify in what kind of lines to highlight whitespace errors. + +t Highlight only in added lines. +`both' Highlight in added and removed lines. +`all' Highlight in added, removed and context lines." + :package-version '(magit . "3.0.0") + :group 'magit-diff + :safe (lambda (val) (memq val '(t both all))) + :type '(choice (const :tag "in added lines" t) + (const :tag "in added and removed lines" both) + (const :tag "in added, removed and context lines" all))) + +(defcustom magit-diff-highlight-trailing t + "Whether to highlight whitespace at the end of a line in diffs. +Used only when `magit-diff-paint-whitespace' is non-nil." + :group 'magit-diff + :safe 'booleanp + :type 'boolean) + +(defcustom magit-diff-highlight-indentation nil + "Highlight the \"wrong\" indentation style. +Used only when `magit-diff-paint-whitespace' is non-nil. + +The value is an alist of the form ((REGEXP . INDENT)...). The +path to the current repository is matched against each element +in reverse order. Therefore if a REGEXP matches, then earlier +elements are not tried. + +If the used INDENT is `tabs', highlight indentation with tabs. +If INDENT is an integer, highlight indentation with at least +that many spaces. Otherwise, highlight neither." + :group 'magit-diff + :type `(repeat (cons (string :tag "Directory regexp") + (choice (const :tag "Tabs" tabs) + (integer :tag "Spaces" :value ,tab-width) + (const :tag "Neither" nil))))) + +(defcustom magit-diff-hide-trailing-cr-characters + (and (memq system-type '(ms-dos windows-nt)) t) + "Whether to hide ^M characters at the end of a line in diffs." + :package-version '(magit . "2.6.0") + :group 'magit-diff + :type 'boolean) + +(defcustom magit-diff-highlight-keywords t + "Whether to highlight bracketed keywords in commit messages." + :package-version '(magit . "2.12.0") + :group 'magit-diff + :type 'boolean) + +(defcustom magit-diff-extra-stat-arguments nil + "Additional arguments to be used alongside `--stat'. + +A list of zero or more arguments or a function that takes no +argument and returns such a list. These arguments are allowed +here: `--stat-width', `--stat-name-width', `--stat-graph-width' +and `--compact-summary'. See the git-diff(1) manpage." + :package-version '(magit . "3.0.0") + :group 'magit-diff + :type '(radio (function-item magit-diff-use-window-width-as-stat-width) + function + (list string) + (const :tag "None" nil))) + +;;;; File Diff + +(defcustom magit-diff-buffer-file-locked t + "Whether `magit-diff-buffer-file' uses a dedicated buffer." + :package-version '(magit . "2.7.0") + :group 'magit-commands + :group 'magit-diff + :type 'boolean) + +;;;; Revision Mode + +(defgroup magit-revision nil + "Inspect and manipulate Git commits." + :link '(info-link "(magit)Revision Buffer") + :group 'magit-modes) + +(defcustom magit-revision-mode-hook + '(bug-reference-mode + goto-address-mode) + "Hook run after entering Magit-Revision mode." + :group 'magit-revision + :type 'hook + :options '(bug-reference-mode + goto-address-mode)) + +(defcustom magit-revision-sections-hook + '(magit-insert-revision-tag + magit-insert-revision-headers + magit-insert-revision-message + magit-insert-revision-notes + magit-insert-revision-diff + magit-insert-xref-buttons) + "Hook run to insert sections into a `magit-revision-mode' buffer." + :package-version '(magit . "2.3.0") + :group 'magit-revision + :type 'hook) + +(defcustom magit-revision-headers-format "\ +Author: %aN <%aE> +AuthorDate: %ad +Commit: %cN <%cE> +CommitDate: %cd +" + "Format string used to insert headers in revision buffers. + +All headers in revision buffers are inserted by the section +inserter `magit-insert-revision-headers'. Some of the headers +are created by calling `git show --format=FORMAT' where FORMAT +is the format specified here. Other headers are hard coded or +subject to option `magit-revision-insert-related-refs'." + :package-version '(magit . "2.3.0") + :group 'magit-revision + :type 'string) + +(defcustom magit-revision-insert-related-refs t + "Whether to show related branches in revision buffers + +`nil' Don't show any related branches. +`t' Show related local branches. +`all' Show related local and remote branches. +`mixed' Show all containing branches and local merged branches. + +See user option `magit-revision-insert-related-refs-display-alist' +to hide specific sets of related branches." + :package-version '(magit . "2.1.0") + :group 'magit-revision + :type '(choice (const :tag "don't" nil) + (const :tag "local only" t) + (const :tag "all related" all) + (const :tag "all containing, local merged" mixed))) + +(defcustom magit-revision-insert-related-refs-display-alist nil + "How `magit-insert-revision-headers' displays related branch types. + +This is an alist, with recognised keys being the symbols +`parents', `merged', `contained', `follows', and `precedes'; +and the supported values for each key being: + +`nil' Hide these related branches. +`t' Show these related branches. + +Keys which are not present in the alist have an implicit value `t' +\(so the default alist value of nil means all related branch types +will be shown.) + +The types to be shown are additionally subject to user option +`magit-revision-insert-related-refs'." + :package-version '(magit . "3.3.1") + :group 'magit-revision + :type '(alist :key-type (symbol :tag "Type of related branch") + :value-type (boolean :tag "Display")) + :options (mapcar (lambda (sym) + `(,sym (choice (const :tag "Hide" nil) + (const :tag "Show" t)))) + '(parents merged contained follows precedes))) + +(defcustom magit-revision-use-hash-sections 'quicker + "Whether to turn hashes inside the commit message into sections. + +If non-nil, then hashes inside the commit message are turned into +`commit' sections. There is a trade off to be made between +performance and reliability: + +- `slow' calls git for every word to be absolutely sure. +- `quick' skips words less than seven characters long. +- `quicker' additionally skips words that don't contain a number. +- `quickest' uses all words that are at least seven characters + long and which contain at least one number as well as at least + one letter. + +If nil, then no hashes are turned into sections, but you can +still visit the commit at point using \"RET\"." + :package-version '(magit . "2.12.0") + :group 'magit-revision + :type '(choice (const :tag "Use sections, quickest" quickest) + (const :tag "Use sections, quicker" quicker) + (const :tag "Use sections, quick" quick) + (const :tag "Use sections, slow" slow) + (const :tag "Don't use sections" nil))) + +(defcustom magit-revision-show-gravatars nil + "Whether to show gravatar images in revision buffers. + +If nil, then don't insert any gravatar images. If t, then insert +both images. If `author' or `committer', then insert only the +respective image. + +If you have customized the option `magit-revision-header-format' +and want to insert the images then you might also have to specify +where to do so. In that case the value has to be a cons-cell of +two regular expressions. The car specifies where to insert the +author's image. The top half of the image is inserted right +after the matched text, the bottom half on the next line in the +same column. The cdr specifies where to insert the committer's +image, accordingly. Either the car or the cdr may be nil." + :package-version '(magit . "2.3.0") + :group 'magit-revision + :type '(choice + (const :tag "Don't show gravatars" nil) + (const :tag "Show gravatars" t) + (const :tag "Show author gravatar" author) + (const :tag "Show committer gravatar" committer) + (cons :tag "Show gravatars using custom regexps" + (choice (const :tag "No author image" nil) + (regexp :tag "Author regexp" "^Author: ")) + (choice (const :tag "No committer image" nil) + (regexp :tag "Committer regexp" "^Commit: "))))) + +(defcustom magit-revision-fill-summary-line nil + "Whether to fill excessively long summary lines. + +If this is an integer, then the summary line is filled if it is +longer than either the limit specified here or `window-width'. + +You may want to only set this locally in \".dir-locals-2.el\" for +repositories known to contain bad commit messages. + +The body of the message is left alone because (a) most people who +write excessively long summary lines usually don't add a body and +\(b) even people who have the decency to wrap their lines may have +a good reason to include a long line in the body sometimes." + :package-version '(magit . "2.90.0") + :group 'magit-revision + :type '(choice (const :tag "Don't fill" nil) + (integer :tag "Fill if longer than"))) + +(defcustom magit-revision-filter-files-on-follow nil + "Whether to honor file filter if log arguments include --follow. + +When a commit is displayed from a log buffer, the resulting +revision buffer usually shares the log's file arguments, +restricting the diff to those files. However, there's a +complication when the log arguments include --follow: if the log +follows a file across a rename event, keeping the file +restriction would mean showing an empty diff in revision buffers +for commits before the rename event. + +When this option is nil, the revision buffer ignores the log's +filter if the log arguments include --follow. If non-nil, the +log's file filter is always honored." + :package-version '(magit . "3.0.0") + :group 'magit-revision + :type 'boolean) + +;;;; Visit Commands + +(defcustom magit-diff-visit-previous-blob t + "Whether `magit-diff-visit-file' may visit the previous blob. + +When this is t and point is on a removed line in a diff for a +committed change, then `magit-diff-visit-file' visits the blob +from the last revision which still had that line. + +Currently this is only supported for committed changes, for +staged and unstaged changes `magit-diff-visit-file' always +visits the file in the working tree." + :package-version '(magit . "2.9.0") + :group 'magit-diff + :type 'boolean) + +(defcustom magit-diff-visit-avoid-head-blob nil + "Whether `magit-diff-visit-file' avoids visiting a blob from `HEAD'. + +By default `magit-diff-visit-file' always visits the blob that +added the current line, while `magit-diff-visit-worktree-file' +visits the respective file in the working tree. For the `HEAD' +commit, the former command used to visit the worktree file too, +but that made it impossible to visit a blob from `HEAD'. + +When point is on a removed line and that change has not been +committed yet, then `magit-diff-visit-file' now visits the last +blob that still had that line, which is a blob from `HEAD'. +Previously this function used to visit the worktree file not +only for added lines but also for such removed lines. + +If you prefer the old behaviors, then set this to t." + :package-version '(magit . "3.0.0") + :group 'magit-diff + :type 'boolean) + +;;; Faces + +(defface magit-diff-file-heading + `((t ,@(and (>= emacs-major-version 27) '(:extend t)) + :weight bold)) + "Face for diff file headings." + :group 'magit-faces) + +(defface magit-diff-file-heading-highlight + `((t ,@(and (>= emacs-major-version 27) '(:extend t)) + :inherit magit-section-highlight)) + "Face for current diff file headings." + :group 'magit-faces) + +(defface magit-diff-file-heading-selection + `((((class color) (background light)) + ,@(and (>= emacs-major-version 27) '(:extend t)) + :inherit magit-diff-file-heading-highlight + :foreground "salmon4") + (((class color) (background dark)) + ,@(and (>= emacs-major-version 27) '(:extend t)) + :inherit magit-diff-file-heading-highlight + :foreground "LightSalmon3")) + "Face for selected diff file headings." + :group 'magit-faces) + +(defface magit-diff-hunk-heading + `((((class color) (background light)) + ,@(and (>= emacs-major-version 27) '(:extend t)) + :background "grey90" + :foreground "grey20") + (((class color) (background dark)) + ,@(and (>= emacs-major-version 27) '(:extend t)) + :background "grey25" + :foreground "grey95")) + "Face for diff hunk headings." + :group 'magit-faces) + +(defface magit-diff-hunk-heading-highlight + `((((class color) (background light)) + ,@(and (>= emacs-major-version 27) '(:extend t)) + :background "grey80" + :foreground "grey20") + (((class color) (background dark)) + ,@(and (>= emacs-major-version 27) '(:extend t)) + :background "grey35" + :foreground "grey95")) + "Face for current diff hunk headings." + :group 'magit-faces) + +(defface magit-diff-hunk-heading-selection + `((((class color) (background light)) + ,@(and (>= emacs-major-version 27) '(:extend t)) + :inherit magit-diff-hunk-heading-highlight + :foreground "salmon4") + (((class color) (background dark)) + ,@(and (>= emacs-major-version 27) '(:extend t)) + :inherit magit-diff-hunk-heading-highlight + :foreground "LightSalmon3")) + "Face for selected diff hunk headings." + :group 'magit-faces) + +(defface magit-diff-hunk-region + `((t :inherit bold + ,@(and (>= emacs-major-version 27) + (list :extend (ignore-errors (face-attribute 'region :extend)))))) + "Face used by `magit-diff-highlight-hunk-region-using-face'. + +This face is overlaid over text that uses other hunk faces, +and those normally set the foreground and background colors. +The `:foreground' and especially the `:background' properties +should be avoided here. Setting the latter would cause the +loss of information. Good properties to set here are `:weight' +and `:slant'." + :group 'magit-faces) + +(defface magit-diff-revision-summary + '((t :inherit magit-diff-hunk-heading)) + "Face for commit message summaries." + :group 'magit-faces) + +(defface magit-diff-revision-summary-highlight + '((t :inherit magit-diff-hunk-heading-highlight)) + "Face for highlighted commit message summaries." + :group 'magit-faces) + +(defface magit-diff-lines-heading + `((((class color) (background light)) + ,@(and (>= emacs-major-version 27) '(:extend t)) + :inherit magit-diff-hunk-heading-highlight + :background "LightSalmon3") + (((class color) (background dark)) + ,@(and (>= emacs-major-version 27) '(:extend t)) + :inherit magit-diff-hunk-heading-highlight + :foreground "grey80" + :background "salmon4")) + "Face for diff hunk heading when lines are marked." + :group 'magit-faces) + +(defface magit-diff-lines-boundary + `((t ,@(and (>= emacs-major-version 27) '(:extend t)) ; !important + :inherit magit-diff-lines-heading)) + "Face for boundary of marked lines in diff hunk." + :group 'magit-faces) + +(defface magit-diff-conflict-heading + '((t :inherit magit-diff-hunk-heading)) + "Face for conflict markers." + :group 'magit-faces) + +(defface magit-diff-added + `((((class color) (background light)) + ,@(and (>= emacs-major-version 27) '(:extend t)) + :background "#ddffdd" + :foreground "#22aa22") + (((class color) (background dark)) + ,@(and (>= emacs-major-version 27) '(:extend t)) + :background "#335533" + :foreground "#ddffdd")) + "Face for lines in a diff that have been added." + :group 'magit-faces) + +(defface magit-diff-removed + `((((class color) (background light)) + ,@(and (>= emacs-major-version 27) '(:extend t)) + :background "#ffdddd" + :foreground "#aa2222") + (((class color) (background dark)) + ,@(and (>= emacs-major-version 27) '(:extend t)) + :background "#553333" + :foreground "#ffdddd")) + "Face for lines in a diff that have been removed." + :group 'magit-faces) + +(defface magit-diff-our + '((t :inherit magit-diff-removed)) + "Face for lines in a diff for our side in a conflict." + :group 'magit-faces) + +(defface magit-diff-base + `((((class color) (background light)) + ,@(and (>= emacs-major-version 27) '(:extend t)) + :background "#ffffcc" + :foreground "#aaaa11") + (((class color) (background dark)) + ,@(and (>= emacs-major-version 27) '(:extend t)) + :background "#555522" + :foreground "#ffffcc")) + "Face for lines in a diff for the base side in a conflict." + :group 'magit-faces) + +(defface magit-diff-their + '((t :inherit magit-diff-added)) + "Face for lines in a diff for their side in a conflict." + :group 'magit-faces) + +(defface magit-diff-context + `((((class color) (background light)) + ,@(and (>= emacs-major-version 27) '(:extend t)) + :foreground "grey50") + (((class color) (background dark)) + ,@(and (>= emacs-major-version 27) '(:extend t)) + :foreground "grey70")) + "Face for lines in a diff that are unchanged." + :group 'magit-faces) + +(defface magit-diff-added-highlight + `((((class color) (background light)) + ,@(and (>= emacs-major-version 27) '(:extend t)) + :background "#cceecc" + :foreground "#22aa22") + (((class color) (background dark)) + ,@(and (>= emacs-major-version 27) '(:extend t)) + :background "#336633" + :foreground "#cceecc")) + "Face for lines in a diff that have been added." + :group 'magit-faces) + +(defface magit-diff-removed-highlight + `((((class color) (background light)) + ,@(and (>= emacs-major-version 27) '(:extend t)) + :background "#eecccc" + :foreground "#aa2222") + (((class color) (background dark)) + ,@(and (>= emacs-major-version 27) '(:extend t)) + :background "#663333" + :foreground "#eecccc")) + "Face for lines in a diff that have been removed." + :group 'magit-faces) + +(defface magit-diff-our-highlight + '((t :inherit magit-diff-removed-highlight)) + "Face for lines in a diff for our side in a conflict." + :group 'magit-faces) + +(defface magit-diff-base-highlight + `((((class color) (background light)) + ,@(and (>= emacs-major-version 27) '(:extend t)) + :background "#eeeebb" + :foreground "#aaaa11") + (((class color) (background dark)) + ,@(and (>= emacs-major-version 27) '(:extend t)) + :background "#666622" + :foreground "#eeeebb")) + "Face for lines in a diff for the base side in a conflict." + :group 'magit-faces) + +(defface magit-diff-their-highlight + '((t :inherit magit-diff-added-highlight)) + "Face for lines in a diff for their side in a conflict." + :group 'magit-faces) + +(defface magit-diff-context-highlight + `((((class color) (background light)) + ,@(and (>= emacs-major-version 27) '(:extend t)) + :background "grey95" + :foreground "grey50") + (((class color) (background dark)) + ,@(and (>= emacs-major-version 27) '(:extend t)) + :background "grey20" + :foreground "grey70")) + "Face for lines in the current context in a diff." + :group 'magit-faces) + +(defface magit-diff-whitespace-warning + '((t :inherit trailing-whitespace)) + "Face for highlighting whitespace errors added lines." + :group 'magit-faces) + +(defface magit-diffstat-added + '((((class color) (background light)) :foreground "#22aa22") + (((class color) (background dark)) :foreground "#448844")) + "Face for plus sign in diffstat." + :group 'magit-faces) + +(defface magit-diffstat-removed + '((((class color) (background light)) :foreground "#aa2222") + (((class color) (background dark)) :foreground "#aa4444")) + "Face for minus sign in diffstat." + :group 'magit-faces) + +;;; Arguments +;;;; Prefix Classes + +(defclass magit-diff-prefix (transient-prefix) + ((history-key :initform 'magit-diff) + (major-mode :initform 'magit-diff-mode))) + +(defclass magit-diff-refresh-prefix (magit-diff-prefix) + ((history-key :initform 'magit-diff) + (major-mode :initform nil))) + +;;;; Prefix Methods + +(cl-defmethod transient-init-value ((obj magit-diff-prefix)) + (pcase-let ((`(,args ,files) + (magit-diff--get-value 'magit-diff-mode + magit-prefix-use-buffer-arguments))) + (unless (eq transient-current-command 'magit-dispatch) + (when-let ((file (magit-file-relative-name))) + (setq files (list file)))) + (oset obj value (if files `(("--" ,@files) ,args) args)))) + +(cl-defmethod transient-init-value ((obj magit-diff-refresh-prefix)) + (oset obj value (if magit-buffer-diff-files + `(("--" ,@magit-buffer-diff-files) + ,magit-buffer-diff-args) + magit-buffer-diff-args))) + +(cl-defmethod transient-set-value ((obj magit-diff-prefix)) + (magit-diff--set-value obj)) + +(cl-defmethod transient-save-value ((obj magit-diff-prefix)) + (magit-diff--set-value obj 'save)) + +;;;; Argument Access + +(defun magit-diff-arguments (&optional mode) + "Return the current diff arguments." + (if (memq transient-current-command '(magit-diff magit-diff-refresh)) + (magit--transient-args-and-files) + (magit-diff--get-value (or mode 'magit-diff-mode)))) + +(defun magit-diff--get-value (mode &optional use-buffer-args) + (unless use-buffer-args + (setq use-buffer-args magit-direct-use-buffer-arguments)) + (let (args files) + (cond + ((and (memq use-buffer-args '(always selected current)) + (eq major-mode mode)) + (setq args magit-buffer-diff-args) + (setq files magit-buffer-diff-files)) + ((and (memq use-buffer-args '(always selected)) + (when-let ((buffer (magit-get-mode-buffer + mode nil + (eq use-buffer-args 'selected)))) + (setq args (buffer-local-value 'magit-buffer-diff-args buffer)) + (setq files (buffer-local-value 'magit-buffer-diff-files buffer)) + t))) + ((plist-member (symbol-plist mode) 'magit-diff-current-arguments) + (setq args (get mode 'magit-diff-current-arguments))) + ((when-let ((elt (assq (intern (format "magit-diff:%s" mode)) + transient-values))) + (setq args (cdr elt)) + t)) + (t + (setq args (get mode 'magit-diff-default-arguments)))) + (list args files))) + +(defun magit-diff--set-value (obj &optional save) + (pcase-let* ((obj (oref obj prototype)) + (mode (or (oref obj major-mode) major-mode)) + (key (intern (format "magit-diff:%s" mode))) + (`(,args ,files) (magit--transient-args-and-files))) + (put mode 'magit-diff-current-arguments args) + (when save + (setf (alist-get key transient-values) args) + (transient-save-values)) + (transient--history-push obj) + (setq magit-buffer-diff-args args) + (setq magit-buffer-diff-files files) + (magit-refresh))) + +;;; Commands +;;;; Prefix Commands + +;;;###autoload (autoload 'magit-diff "magit-diff" nil t) +(transient-define-prefix magit-diff () + "Show changes between different versions." + :man-page "git-diff" + :class 'magit-diff-prefix + ["Limit arguments" + (magit:--) + (magit-diff:--ignore-submodules) + ("-b" "Ignore whitespace changes" ("-b" "--ignore-space-change")) + ("-w" "Ignore all whitespace" ("-w" "--ignore-all-space")) + (5 "-D" "Omit preimage for deletes" ("-D" "--irreversible-delete"))] + ["Context arguments" + (magit-diff:-U) + ("-W" "Show surrounding functions" ("-W" "--function-context"))] + ["Tune arguments" + (magit-diff:--diff-algorithm) + (magit-diff:--diff-merges) + (magit-diff:-M) + (magit-diff:-C) + (5 "-R" "Reverse sides" "-R") + (5 magit-diff:--color-moved) + (5 magit-diff:--color-moved-ws) + ("-x" "Disallow external diff drivers" "--no-ext-diff") + ("-s" "Show stats" "--stat") + ("=g" "Show signature" "--show-signature")] + ["Actions" + [("d" "Dwim" magit-diff-dwim) + ("r" "Diff range" magit-diff-range) + ("p" "Diff paths" magit-diff-paths)] + [("u" "Diff unstaged" magit-diff-unstaged) + ("s" "Diff staged" magit-diff-staged) + ("w" "Diff worktree" magit-diff-working-tree)] + [("c" "Show commit" magit-show-commit) + ("t" "Show stash" magit-stash-show)]]) + +;;;###autoload (autoload 'magit-diff-refresh "magit-diff" nil t) +(transient-define-prefix magit-diff-refresh () + "Change the arguments used for the diff(s) in the current buffer." + :man-page "git-diff" + :class 'magit-diff-refresh-prefix + ["Limit arguments" + (magit:--) + (magit-diff:--ignore-submodules) + ("-b" "Ignore whitespace changes" ("-b" "--ignore-space-change")) + ("-w" "Ignore all whitespace" ("-w" "--ignore-all-space")) + (5 "-D" "Omit preimage for deletes" ("-D" "--irreversible-delete"))] + ["Context arguments" + (magit-diff:-U) + ("-W" "Show surrounding functions" ("-W" "--function-context"))] + ["Tune arguments" + (magit-diff:--diff-algorithm) + (magit-diff:--diff-merges) + (magit-diff:-M) + (magit-diff:-C) + (5 "-R" "Reverse sides" "-R" + :if-derived magit-diff-mode) + (5 magit-diff:--color-moved) + (5 magit-diff:--color-moved-ws) + ("-x" "Disallow external diff drivers" "--no-ext-diff") + ("-s" "Show stats" "--stat" + :if-derived magit-diff-mode) + ("=g" "Show signature" "--show-signature" + :if-derived magit-diff-mode)] + [["Refresh" + ("g" "buffer" magit-diff-refresh) + ("s" "buffer and set defaults" transient-set-and-exit) + ("w" "buffer and save defaults" transient-save-and-exit)] + ["Toggle" + ("t" "hunk refinement" magit-diff-toggle-refine-hunk) + ("F" "file filter" magit-diff-toggle-file-filter) + ("b" "buffer lock" magit-toggle-buffer-lock + :if-mode (magit-diff-mode magit-revision-mode magit-stash-mode))] + [:if-mode magit-diff-mode + :description "Do" + ("r" "switch range type" magit-diff-switch-range-type) + ("f" "flip revisions" magit-diff-flip-revs)]] + (interactive) + (when (derived-mode-p 'magit-merge-preview-mode) + (user-error "Cannot use %s in %s" this-command major-mode)) + (if (not (eq transient-current-command 'magit-diff-refresh)) + (transient-setup 'magit-diff-refresh) + (pcase-let ((`(,args ,files) (magit-diff-arguments))) + (setq magit-buffer-diff-args args) + (setq magit-buffer-diff-files files)) + (magit-refresh))) + +;;;; Infix Commands + +(transient-define-argument magit:-- () + :description "Limit to files" + :class 'transient-files + :key "--" + :argument "--" + :prompt "Limit to file,s: " + :reader #'magit-read-files + :multi-value t) + +(defun magit-read-files (prompt initial-input history &optional list-fn) + (magit-with-toplevel + (magit-completing-read-multiple prompt + (funcall (or list-fn #'magit-list-files)) + nil nil + (or initial-input (magit-file-at-point)) + history))) + +(transient-define-argument magit-diff:-U () + :description "Context lines" + :class 'transient-option + :argument "-U" + :reader #'transient-read-number-N0) + +(transient-define-argument magit-diff:-M () + :description "Detect renames" + :class 'transient-option + :argument "-M" + :allow-empty t + :reader #'transient-read-number-N+) + +(transient-define-argument magit-diff:-C () + :description "Detect copies" + :class 'transient-option + :argument "-C" + :allow-empty t + :reader #'transient-read-number-N+) + +(transient-define-argument magit-diff:--diff-algorithm () + :description "Diff algorithm" + :class 'transient-option + :key "-A" + :argument "--diff-algorithm=" + :reader #'magit-diff-select-algorithm + :always-read t) + +(defun magit-diff-select-algorithm (&rest _ignore) + (magit-read-char-case nil t + (?u "[u]nspecified" nil) + (?d "[d]efault" "default") + (?m "[m]inimal" "minimal") + (?p "[p]atience" "patience") + (?h "[h]istogram" "histogram"))) + +(transient-define-argument magit-diff:--diff-merges () + :description "Diff merges" + :class 'transient-option + :key "-X" + :argument "--diff-merges=" + :reader #'magit-diff-select-merges + :always-read t) + +(defun magit-diff-select-merges (&rest _ignore) + (magit-read-char-case nil t + (?u "[u]nspecified" nil) + (?o "[o]ff" "off") + (?f "[f]irst-parent" "first-parent") + (?c "[c]ombined" "combined") + (?d "[d]ense-combined" "dense-combined"))) + +(transient-define-argument magit-diff:--ignore-submodules () + :description "Ignore submodules" + :class 'transient-option + :key "-i" + :argument "--ignore-submodules=" + :reader #'magit-diff-select-ignore-submodules) + +(defun magit-diff-select-ignore-submodules (&rest _ignored) + (magit-read-char-case "Ignore submodules " t + (?u "[u]ntracked" "untracked") + (?d "[d]irty" "dirty") + (?a "[a]ll" "all"))) + +(transient-define-argument magit-diff:--color-moved () + :description "Color moved lines" + :class 'transient-option + :key "-m" + :argument "--color-moved=" + :reader #'magit-diff-select-color-moved-mode) + +(defun magit-diff-select-color-moved-mode (&rest _ignore) + (magit-read-char-case "Color moved " t + (?d "[d]efault" "default") + (?p "[p]lain" "plain") + (?b "[b]locks" "blocks") + (?z "[z]ebra" "zebra") + (?Z "[Z] dimmed-zebra" "dimmed-zebra"))) + +(transient-define-argument magit-diff:--color-moved-ws () + :description "Whitespace treatment for --color-moved" + :class 'transient-option + :key "=w" + :argument "--color-moved-ws=" + :reader #'magit-diff-select-color-moved-ws-mode) + +(defun magit-diff-select-color-moved-ws-mode (&rest _ignore) + (magit-read-char-case "Ignore whitespace " t + (?i "[i]ndentation" "allow-indentation-change") + (?e "[e]nd of line" "ignore-space-at-eol") + (?s "[s]pace change" "ignore-space-change") + (?a "[a]ll space" "ignore-all-space") + (?n "[n]o" "no"))) + +;;;; Setup Commands + +;;;###autoload +(defun magit-diff-dwim (&optional args files) + "Show changes for the thing at point." + (interactive (magit-diff-arguments)) + (let ((default-directory default-directory) + (section (magit-current-section))) + (cond + ((magit-section-match 'module section) + (setq default-directory + (expand-file-name + (file-name-as-directory (oref section value)))) + (magit-diff-range (oref section range))) + (t + (when (magit-section-match 'module-commit section) + (setq args nil) + (setq files nil) + (setq default-directory + (expand-file-name + (file-name-as-directory (magit-section-parent-value section))))) + (pcase (magit-diff--dwim) + ('unmerged (magit-diff-unmerged args files)) + ('unstaged (magit-diff-unstaged args files)) + ('staged + (let ((file (magit-file-at-point))) + (if (and file (equal (cddr (car (magit-file-status file))) '(?D ?U))) + ;; File was deleted by us and modified by them. Show the latter. + (magit-diff-unmerged args (list file)) + (magit-diff-staged nil args files)))) + (`(stash . ,value) (magit-stash-show value args)) + (`(commit . ,value) + (magit-diff-range (format "%s^..%s" value value) args files)) + ((and range (pred stringp)) + (magit-diff-range range args files)) + (_ (call-interactively #'magit-diff-range))))))) + +(defun magit-diff--dwim () + "Return information for performing DWIM diff. + +The information can be in three forms: +1. TYPE + A symbol describing a type of diff where no additional information + is needed to generate the diff. Currently, this includes `staged', + `unstaged' and `unmerged'. +2. (TYPE . VALUE) + Like #1 but the diff requires additional information, which is + given by VALUE. Currently, this includes `commit' and `stash', + where VALUE is the given commit or stash, respectively. +3. RANGE + A string indicating a diff range. + +If no DWIM context is found, nil is returned." + (cond + ((and-let* ((commits (magit-region-values '(commit branch) t))) + (progn + (deactivate-mark) + (concat (car (last commits)) ".." (car commits))))) + (magit-buffer-refname + (cons 'commit magit-buffer-refname)) + ((derived-mode-p 'magit-stash-mode) + (cons 'commit + (magit-section-case + (commit (oref it value)) + (file (thread-first it + (oref parent) + (oref value))) + (hunk (thread-first it + (oref parent) + (oref parent) + (oref value)))))) + ((derived-mode-p 'magit-revision-mode) + (cons 'commit magit-buffer-revision)) + ((derived-mode-p 'magit-diff-mode) + magit-buffer-range) + (t + (magit-section-case + ([* unstaged] 'unstaged) + ([* staged] 'staged) + (unmerged 'unmerged) + (unpushed (magit-diff--range-to-endpoints (oref it value))) + (unpulled (magit-diff--range-to-endpoints (oref it value))) + (branch (let ((current (magit-get-current-branch)) + (atpoint (oref it value))) + (if (equal atpoint current) + (if-let ((upstream (magit-get-upstream-branch))) + (format "%s...%s" upstream current) + (if (magit-anything-modified-p) + current + (cons 'commit current))) + (format "%s...%s" + (or current "HEAD") + atpoint)))) + (commit (cons 'commit (oref it value))) + ([file commit] (cons 'commit (oref (oref it parent) value))) + ([hunk file commit] + (cons 'commit (oref (oref (oref it parent) parent) value))) + (stash (cons 'stash (oref it value))) + (pullreq (forge--pullreq-range (oref it value) t)))))) + +(defun magit-diff--range-to-endpoints (range) + (cond ((string-match "\\.\\.\\." range) (replace-match ".." nil nil range)) + ((string-match "\\.\\." range) (replace-match "..." nil nil range)) + (t range))) + +(defun magit-diff--region-range (&optional interactive mbase) + (and-let* ((commits (magit-region-values '(commit branch) t)) + (revA (car (last commits))) + (revB (car commits))) + (progn + (when interactive + (deactivate-mark)) + (if mbase + (let ((base (magit-git-string "merge-base" revA revB))) + (cond + ((string= (magit-rev-parse revA) base) + (format "%s..%s" revA revB)) + ((string= (magit-rev-parse revB) base) + (format "%s..%s" revB revA)) + (interactive + (let ((main (magit-completing-read "View changes along" + (list revA revB) + nil t nil nil revB))) + (format "%s...%s" + (if (string= main revB) revA revB) main))) + (t "%s...%s" revA revB))) + (format "%s..%s" revA revB))))) + +(defun magit-diff-read-range-or-commit (prompt &optional secondary-default mbase) + "Read range or revision with special diff range treatment. +If MBASE is non-nil, prompt for which rev to place at the end of +a \"revA...revB\" range. Otherwise, always construct +\"revA..revB\" range." + (or (magit-diff--region-range t mbase) + (magit-read-range prompt + (or (pcase (magit-diff--dwim) + (`(commit . ,value) + (format "%s^..%s" value value)) + ((and range (pred stringp)) + range)) + secondary-default + (magit-get-current-branch))))) + +;;;###autoload +(defun magit-diff-range (rev-or-range &optional args files) + "Show differences between two commits. + +REV-OR-RANGE should be a range or a single revision. If it is a +revision, then show changes in the working tree relative to that +revision. If it is a range, but one side is omitted, then show +changes relative to `HEAD'. + +If the region is active, use the revisions on the first and last +line of the region as the two sides of the range. With a prefix +argument, instead of diffing the revisions, choose a revision to +view changes along, starting at the common ancestor of both +revisions (i.e., use a \"...\" range)." + (interactive (cons (magit-diff-read-range-or-commit "Diff for range" + nil current-prefix-arg) + (magit-diff-arguments))) + (magit-diff-setup-buffer rev-or-range nil args files 'committed)) + +;;;###autoload +(defun magit-diff-working-tree (&optional rev args files) + "Show changes between the current working tree and the `HEAD' commit. +With a prefix argument show changes between the working tree and +a commit read from the minibuffer." + (interactive + (cons (and current-prefix-arg + (magit-read-branch-or-commit "Diff working tree and commit")) + (magit-diff-arguments))) + (magit-diff-setup-buffer (or rev "HEAD") nil args files 'committed)) + +;;;###autoload +(defun magit-diff-staged (&optional rev args files) + "Show changes between the index and the `HEAD' commit. +With a prefix argument show changes between the index and +a commit read from the minibuffer." + (interactive + (cons (and current-prefix-arg + (magit-read-branch-or-commit "Diff index and commit")) + (magit-diff-arguments))) + (magit-diff-setup-buffer rev "--cached" args files 'staged)) + +;;;###autoload +(defun magit-diff-unstaged (&optional args files) + "Show changes between the working tree and the index." + (interactive (magit-diff-arguments)) + (magit-diff-setup-buffer nil nil args files 'unstaged)) + +;;;###autoload +(defun magit-diff-unmerged (&optional args files) + "Show changes that are being merged." + (interactive (magit-diff-arguments)) + (unless (magit-merge-in-progress-p) + (user-error "No merge is in progress")) + (magit-diff-setup-buffer (magit--merge-range) nil args files 'committed)) + +;;;###autoload +(defun magit-diff-while-committing () + "While committing, show the changes that are about to be committed. +While amending, invoking the command again toggles between +showing just the new changes or all the changes that will +be committed." + (interactive) + (unless (magit-commit-message-buffer) + (user-error "No commit in progress")) + (magit-commit-diff-1)) + +;;;###autoload +(defun magit-diff-buffer-file () + "Show diff for the blob or file visited in the current buffer. + +When the buffer visits a blob, then show the respective commit. +When the buffer visits a file, then show the differences between +`HEAD' and the working tree. In both cases limit the diff to +the file or blob." + (interactive) + (require 'magit) + (if-let ((file (magit-file-relative-name))) + (if magit-buffer-refname + (magit-show-commit magit-buffer-refname + (car (magit-show-commit--arguments)) + (list file)) + (save-buffer) + (let ((line (line-number-at-pos)) + (col (current-column))) + (with-current-buffer + (magit-diff-setup-buffer (or (magit-get-current-branch) "HEAD") + nil + (car (magit-diff-arguments)) + (list file) + 'unstaged + magit-diff-buffer-file-locked) + (magit-diff--goto-position file line col)))) + (user-error "Buffer isn't visiting a file"))) + +;;;###autoload +(defun magit-diff-paths (a b) + "Show changes between any two files on disk." + (interactive (list (read-file-name "First file: " nil nil t) + (read-file-name "Second file: " nil nil t))) + (magit-diff-setup-buffer nil "--no-index" nil + (list (magit-convert-filename-for-git + (expand-file-name a)) + (magit-convert-filename-for-git + (expand-file-name b))) + 'undefined)) + +(defun magit-show-commit--arguments () + (pcase-let ((`(,args ,diff-files) + (magit-diff-arguments 'magit-revision-mode))) + (list args (if (derived-mode-p 'magit-log-mode) + (and (or magit-revision-filter-files-on-follow + (not (member "--follow" magit-buffer-log-args))) + magit-buffer-log-files) + diff-files)))) + +;;;###autoload +(defun magit-show-commit (rev &optional args files module) + "Visit the revision at point in another buffer. +If there is no revision at point or with a prefix argument prompt +for a revision." + (interactive + (pcase-let* ((mcommit (magit-section-value-if 'module-commit)) + (atpoint (or mcommit + (magit-thing-at-point 'git-revision t) + (magit-branch-or-commit-at-point))) + (`(,args ,files) (magit-show-commit--arguments))) + (list (or (and (not current-prefix-arg) atpoint) + (magit-read-branch-or-commit "Show commit" atpoint)) + args + files + (and mcommit + (magit-section-parent-value (magit-current-section)))))) + (require 'magit) + (let* ((file (magit-file-relative-name)) + (ln (and file (line-number-at-pos)))) + (magit-with-toplevel + (when module + (setq default-directory + (expand-file-name (file-name-as-directory module)))) + (unless (magit-commit-p rev) + (user-error "%s is not a commit" rev)) + (when file + (save-buffer)) + (let ((buf (magit-revision-setup-buffer rev args files))) + (when file + (let ((line (magit-diff-visit--offset file (list "-R" rev) ln)) + (col (current-column))) + (with-current-buffer buf + (magit-diff--goto-position file line col)))))))) + +(defun magit-diff--locate-hunk (file line &optional parent) + (and-let* ((diff (cl-find-if (lambda (section) + (and (cl-typep section 'magit-file-section) + (equal (oref section value) file))) + (oref (or parent magit-root-section) children)))) + (let ((hunks (oref diff children))) + (cl-block nil + (while-let ((hunk (pop hunks))) + (when-let ((range (oref hunk to-range))) + (pcase-let* ((`(,beg ,len) range) + (end (+ beg len))) + (cond ((> beg line) (cl-return (list diff nil))) + ((<= beg line end) (cl-return (list hunk t))) + ((null hunks) (cl-return (list hunk nil))))))))))) + +(defun magit-diff--goto-position (file line column &optional parent) + (when-let ((pos (magit-diff--locate-hunk file line parent))) + (pcase-let ((`(,section ,exact) pos)) + (cond ((cl-typep section 'magit-file-section) + (goto-char (oref section start))) + (exact + (goto-char (oref section content)) + (let ((pos (car (oref section to-range)))) + (while (or (< pos line) + (= (char-after) ?-)) + (unless (= (char-after) ?-) + (cl-incf pos)) + (forward-line))) + (forward-char (1+ column))) + (t + (goto-char (oref section start)) + (setq section (oref section parent)))) + (while section + (when (oref section hidden) + (magit-section-show section)) + (setq section (oref section parent)))) + (magit-section-update-highlight) + t)) + +;;;; Setting Commands + +(defun magit-diff-switch-range-type () + "Convert diff range type. +Change \"revA..revB\" to \"revA...revB\", or vice versa." + (interactive) + (if (and magit-buffer-range + (derived-mode-p 'magit-diff-mode) + (string-match magit-range-re magit-buffer-range)) + (setq magit-buffer-range + (replace-match (if (string= (match-string 2 magit-buffer-range) "..") + "..." + "..") + t t magit-buffer-range 2)) + (user-error "No range to change")) + (magit-refresh)) + +(defun magit-diff-flip-revs () + "Swap revisions in diff range. +Change \"revA..revB\" to \"revB..revA\"." + (interactive) + (if (and magit-buffer-range + (derived-mode-p 'magit-diff-mode) + (string-match magit-range-re magit-buffer-range)) + (progn + (setq magit-buffer-range + (concat (match-string 3 magit-buffer-range) + (match-string 2 magit-buffer-range) + (match-string 1 magit-buffer-range))) + (magit-refresh)) + (user-error "No range to swap"))) + +(defun magit-diff-toggle-file-filter () + "Toggle the file restriction of the current buffer's diffs. +If the current buffer's mode is derived from `magit-log-mode', +toggle the file restriction in the repository's revision buffer +instead." + (interactive) + (cl-flet ((toggle () + (if (or magit-buffer-diff-files + magit-buffer-diff-files-suspended) + (cl-rotatef magit-buffer-diff-files + magit-buffer-diff-files-suspended) + (setq magit-buffer-diff-files + (transient-infix-read 'magit:--))) + (magit-refresh))) + (cond + ((derived-mode-p 'magit-log-mode + 'magit-cherry-mode + 'magit-reflog-mode) + (if-let ((buffer (magit-get-mode-buffer 'magit-revision-mode))) + (with-current-buffer buffer (toggle)) + (message "No revision buffer"))) + ((local-variable-p 'magit-buffer-diff-files) + (toggle)) + (t + (user-error "Cannot toggle file filter in this buffer"))))) + +(defun magit-diff-less-context (&optional count) + "Decrease the context for diff hunks by COUNT lines." + (interactive "p") + (magit-diff-set-context (lambda (cur) (max 0 (- (or cur 0) count))))) + +(defun magit-diff-more-context (&optional count) + "Increase the context for diff hunks by COUNT lines." + (interactive "p") + (magit-diff-set-context (lambda (cur) (+ (or cur 0) count)))) + +(defun magit-diff-default-context () + "Reset context for diff hunks to the default height." + (interactive) + (magit-diff-set-context #'ignore)) + +(defun magit-diff-set-context (fn) + (when (derived-mode-p 'magit-merge-preview-mode) + (user-error "Cannot use %s in %s" this-command major-mode)) + (let* ((def (if-let ((context (magit-get "diff.context"))) + (string-to-number context) + 3)) + (val magit-buffer-diff-args) + (arg (--first (string-match "^-U\\([0-9]+\\)?$" it) val)) + (num (if-let ((str (and arg (match-string 1 arg)))) + (string-to-number str) + def)) + (val (delete arg val)) + (num (funcall fn num)) + (arg (and num (not (= num def)) (format "-U%d" num))) + (val (if arg (cons arg val) val))) + (setq magit-buffer-diff-args val)) + (magit-refresh)) + +(defun magit-diff-context-p () + (if-let ((arg (--first (string-match "^-U\\([0-9]+\\)$" it) + magit-buffer-diff-args))) + (not (equal arg "-U0")) + t)) + +(defun magit-diff-ignore-any-space-p () + (--any-p (member it magit-buffer-diff-args) + '("--ignore-cr-at-eol" + "--ignore-space-at-eol" + "--ignore-space-change" "-b" + "--ignore-all-space" "-w" + "--ignore-blank-space"))) + +(defun magit-diff-toggle-refine-hunk (&optional style) + "Turn diff-hunk refining on or off. + +If hunk refining is currently on, then hunk refining is turned off. +If hunk refining is off, then hunk refining is turned on, in +`selected' mode (only the currently selected hunk is refined). + +With a prefix argument, the \"third choice\" is used instead: +If hunk refining is currently on, then refining is kept on, but +the refining mode (`selected' or `all') is switched. +If hunk refining is off, then hunk refining is turned on, in +`all' mode (all hunks refined). + +Customize variable `magit-diff-refine-hunk' to change the default mode." + (interactive "P") + (setq-local magit-diff-refine-hunk + (if style + (if (eq magit-diff-refine-hunk 'all) t 'all) + (not magit-diff-refine-hunk))) + (magit-diff-update-hunk-refinement)) + +;;;; Visit Commands +;;;;; Dwim Variants + +(defun magit-diff-visit-file (file &optional other-window) + "From a diff visit the appropriate version of FILE. + +Display the buffer in the selected window. With a prefix +argument OTHER-WINDOW display the buffer in another window +instead. + +Visit the worktree version of the appropriate file. The location +of point inside the diff determines which file is being visited. +The visited version depends on what changes the diff is about. + +1. If the diff shows uncommitted changes (i.e., stage or unstaged + changes), then visit the file in the working tree (i.e., the + same \"real\" file that `find-file' would visit). In all + other cases visit a \"blob\" (i.e., the version of a file as + stored in some commit). + +2. If point is on a removed line, then visit the blob for the + first parent of the commit that removed that line, i.e., the + last commit where that line still exists. + +3. If point is on an added or context line, then visit the blob + that adds that line, or if the diff shows from more than a + single commit, then visit the blob from the last of these + commits. + +In the file-visiting buffer also go to the line that corresponds +to the line that point is on in the diff. + +Note that this command only works if point is inside a diff. +In other cases `magit-find-file' (which see) has to be used." + (interactive (list (magit-diff--file-at-point t t) current-prefix-arg)) + (magit-diff-visit-file--internal file nil + (if other-window + #'switch-to-buffer-other-window + #'pop-to-buffer-same-window))) + +(defun magit-diff-visit-file-other-window (file) + "From a diff visit the appropriate version of FILE in another window. +Like `magit-diff-visit-file' but use +`switch-to-buffer-other-window'." + (interactive (list (magit-diff--file-at-point t t))) + (magit-diff-visit-file--internal file nil #'switch-to-buffer-other-window)) + +(defun magit-diff-visit-file-other-frame (file) + "From a diff visit the appropriate version of FILE in another frame. +Like `magit-diff-visit-file' but use +`switch-to-buffer-other-frame'." + (interactive (list (magit-diff--file-at-point t t))) + (magit-diff-visit-file--internal file nil #'switch-to-buffer-other-frame)) + +;;;;; Worktree Variants + +(defun magit-diff-visit-worktree-file (file &optional other-window) + "From a diff visit the worktree version of FILE. + +Display the buffer in the selected window. With a prefix +argument OTHER-WINDOW display the buffer in another window +instead. + +Visit the worktree version of the appropriate file. The location +of point inside the diff determines which file is being visited. + +Unlike `magit-diff-visit-file' always visits the \"real\" file in +the working tree, i.e the \"current version\" of the file. + +In the file-visiting buffer also go to the line that corresponds +to the line that point is on in the diff. Lines that were added +or removed in the working tree, the index and other commits in +between are automatically accounted for." + (interactive (list (magit-file-at-point t t) current-prefix-arg)) + (magit-diff-visit-file--internal file t + (if other-window + #'switch-to-buffer-other-window + #'pop-to-buffer-same-window))) + +(defun magit-diff-visit-worktree-file-other-window (file) + "From a diff visit the worktree version of FILE in another window. +Like `magit-diff-visit-worktree-file' but use +`switch-to-buffer-other-window'." + (interactive (list (magit-file-at-point t t))) + (magit-diff-visit-file--internal file t #'switch-to-buffer-other-window)) + +(defun magit-diff-visit-worktree-file-other-frame (file) + "From a diff visit the worktree version of FILE in another frame. +Like `magit-diff-visit-worktree-file' but use +`switch-to-buffer-other-frame'." + (interactive (list (magit-file-at-point t t))) + (magit-diff-visit-file--internal file t #'switch-to-buffer-other-frame)) + +;;;;; Internal + +(defun magit-diff-visit-file--internal (file force-worktree fn) + "From a diff visit the appropriate version of FILE. +If FORCE-WORKTREE is non-nil, then visit the worktree version of +the file, even if the diff is about a committed change. Use FN +to display the buffer in some window." + (if (file-accessible-directory-p file) + (magit-diff-visit-directory file force-worktree) + (pcase-let ((`(,buf ,pos) + (magit-diff-visit-file--noselect file force-worktree))) + (funcall fn buf) + (magit-diff-visit-file--setup buf pos) + buf))) + +(defun magit-diff-visit-directory (directory &optional other-window) + "Visit DIRECTORY in some window. +Display the buffer in the selected window unless OTHER-WINDOW is +non-nil. If DIRECTORY is the top-level directory of the current +repository, then visit the containing directory using Dired and +in the Dired buffer put point on DIRECTORY. Otherwise display +the Magit-Status buffer for DIRECTORY." + (if (equal (magit-toplevel directory) + (magit-toplevel)) + (dired-jump other-window (concat directory "/.")) + (let ((display-buffer-overriding-action + (if other-window + '(nil (inhibit-same-window . t)) + '(display-buffer-same-window)))) + (magit-status-setup-buffer directory)))) + +(defun magit-diff-visit-file--setup (buf pos) + (if-let ((win (get-buffer-window buf 'visible))) + (with-selected-window win + (when pos + (unless (<= (point-min) pos (point-max)) + (widen)) + (goto-char pos)) + (when (and buffer-file-name + (magit-anything-unmerged-p buffer-file-name)) + (smerge-start-session)) + (run-hooks 'magit-diff-visit-file-hook)) + (error "File buffer is not visible"))) + +(defun magit-diff-visit-file--noselect (&optional file goto-worktree) + (unless file + (setq file (magit-diff--file-at-point t t))) + (let* ((hunk (magit-diff-visit--hunk)) + (goto-from (and hunk + (magit-diff-visit--goto-from-p hunk goto-worktree))) + (line (and hunk (magit-diff-hunk-line hunk goto-from))) + (col (and hunk (magit-diff-hunk-column hunk goto-from))) + (spec (magit-diff--dwim)) + (rev (if goto-from + (magit-diff-visit--range-from spec) + (magit-diff-visit--range-to spec))) + (buf (if (or goto-worktree + (equal magit-buffer-typearg "--no-index") + (and (not (stringp rev)) + (or magit-diff-visit-avoid-head-blob + (not goto-from)))) + (or (get-file-buffer file) + (find-file-noselect file)) + (magit-find-file-noselect (if (stringp rev) rev "HEAD") + file)))) + (if line + (with-current-buffer buf + (cond ((eq rev 'staged) + (setq line (magit-diff-visit--offset file nil line))) + ((and goto-worktree + (stringp rev)) + (setq line (magit-diff-visit--offset file rev line)))) + (list buf (save-restriction + (widen) + (goto-char (point-min)) + (forward-line (1- line)) + (move-to-column col) + (point)))) + (list buf nil)))) + +(defun magit-diff--file-at-point (&optional expand assert) + ;; This is a variation of magit-file-at-point. + (if-let* ((file-section (magit-section-case + (file it) + (hunk (oref it parent)))) + (file (or (and (magit-section-match 'hunk) + (magit-diff-visit--goto-from-p + (magit-current-section) nil) + (oref file-section source)) + (oref file-section value)))) + (cond ((equal magit-buffer-typearg "--no-index") + (concat "/" file)) + (expand (expand-file-name file (magit-toplevel))) + (file)) + (when assert + (user-error "No file at point")))) + +(defun magit-diff-visit--hunk () + (and-let* ((scope (magit-diff-scope)) + (section (magit-current-section))) + (progn + (cl-case scope + ((file files) + (setq section (car (oref section children)))) + (list + (setq section (car (oref section children))) + (when section + (setq section (car (oref section children)))))) + (and + ;; Unmerged files appear in the list of staged changes + ;; but unlike in the list of unstaged changes no diffs + ;; are shown here. In that case `section' is nil. + section + ;; Currently the `hunk' type is also abused for file + ;; mode changes, which we are not interested in here. + (not (equal (oref section value) '(chmod))) + section)))) + +(defun magit-diff-visit--goto-from-p (section in-worktree) + (and magit-diff-visit-previous-blob + (not in-worktree) + (not (oref section combined)) + (not (< (magit-point) (oref section content))) + (= (char-after (line-beginning-position)) ?-))) + +(defvar magit-diff-visit-jump-to-change t) + +(defun magit-diff-hunk-line (section goto-from) + (save-excursion + (goto-char (line-beginning-position)) + (with-slots (content combined from-ranges from-range to-range) section + (when (or from-range to-range) + (when (and magit-diff-visit-jump-to-change (< (point) content)) + (goto-char content) + (re-search-forward "^[-+]")) + (+ (car (if goto-from from-range to-range)) + (let ((prefix (if combined (length from-ranges) 1)) + (target (point)) + (offset 0)) + (goto-char content) + (while (< (point) target) + (unless (string-search + (if goto-from "+" "-") + (buffer-substring (point) (+ (point) prefix))) + (cl-incf offset)) + (forward-line)) + offset)))))) + +(defun magit-diff-hunk-column (section goto-from) + (if (or (< (magit-point) + (oref section content)) + (and (not goto-from) + (= (char-after (line-beginning-position)) ?-))) + 0 + (max 0 (- (+ (current-column) 2) + (length (oref section value)))))) + +(defun magit-diff-visit--range-from (spec) + (cond ((consp spec) + (concat (cdr spec) "^")) + ((stringp spec) + (car (magit-split-range spec))) + (t + spec))) + +(defun magit-diff-visit--range-to (spec) + (if (symbolp spec) + spec + (let ((rev (if (consp spec) + (cdr spec) + (cdr (magit-split-range spec))))) + (if (and magit-diff-visit-avoid-head-blob + (magit-rev-head-p rev)) + 'unstaged + rev)))) + +(defun magit-diff-visit--offset (file rev line) + (let ((offset 0)) + (with-temp-buffer + (save-excursion + (magit-with-toplevel + (magit-git-insert "diff" rev "--" file))) + (catch 'found + (while (re-search-forward + "^@@ -\\([0-9]+\\),\\([0-9]+\\) \\+\\([0-9]+\\),\\([0-9]+\\) @@.*\n" + nil t) + (let ((from-beg (string-to-number (match-string 1))) + (from-len (string-to-number (match-string 2))) + ( to-len (string-to-number (match-string 4)))) + (if (<= from-beg line) + (if (< (+ from-beg from-len) line) + (cl-incf offset (- to-len from-len)) + (let ((rest (- line from-beg))) + (while (> rest 0) + (pcase (char-after) + (?\s (cl-decf rest)) + (?- (cl-decf offset) (cl-decf rest)) + (?+ (cl-incf offset))) + (forward-line)))) + (throw 'found nil)))))) + (+ line offset))) + +;;;; Scroll Commands + +(defun magit-diff-show-or-scroll-up () + "Update the commit or diff buffer for the thing at point. + +Either show the commit or stash at point in the appropriate +buffer, or if that buffer is already being displayed in the +current frame and contains information about that commit or +stash, then instead scroll the buffer up. If there is no +commit or stash at point, then prompt for a commit." + (interactive) + (magit-diff-show-or-scroll #'scroll-up)) + +(defun magit-diff-show-or-scroll-down () + "Update the commit or diff buffer for the thing at point. + +Either show the commit or stash at point in the appropriate +buffer, or if that buffer is already being displayed in the +current frame and contains information about that commit or +stash, then instead scroll the buffer down. If there is no +commit or stash at point, then prompt for a commit." + (interactive) + (magit-diff-show-or-scroll #'scroll-down)) + +(defun magit-diff-show-or-scroll (fn) + (let (rev cmd buf win) + (cond + ((and (bound-and-true-p magit-blame-mode) + (fboundp 'magit-current-blame-chunk)) + (setq rev (oref (magit-current-blame-chunk) orig-rev)) + (setq cmd #'magit-show-commit) + (setq buf (magit-get-mode-buffer 'magit-revision-mode))) + ((derived-mode-p 'git-rebase-mode) + (with-slots (action-type target) + (git-rebase-current-line) + (if (not (eq action-type 'commit)) + (user-error "No commit on this line") + (setq rev target) + (setq cmd #'magit-show-commit) + (setq buf (magit-get-mode-buffer 'magit-revision-mode))))) + (t + (magit-section-case + (branch + (setq rev (magit-ref-maybe-qualify (oref it value))) + (setq cmd #'magit-show-commit) + (setq buf (magit-get-mode-buffer 'magit-revision-mode))) + (commit + (setq rev (oref it value)) + (setq cmd #'magit-show-commit) + (setq buf (magit-get-mode-buffer 'magit-revision-mode))) + (tag + (setq rev (magit-rev-hash (oref it value))) + (setq cmd #'magit-show-commit) + (setq buf (magit-get-mode-buffer 'magit-revision-mode))) + (stash + (setq rev (oref it value)) + (setq cmd #'magit-stash-show) + (setq buf (magit-get-mode-buffer 'magit-stash-mode)))))) + (if rev + (if (and buf + (setq win (get-buffer-window buf)) + (with-current-buffer buf + (and (equal rev magit-buffer-revision) + (equal (magit-rev-parse rev) + magit-buffer-revision-hash)))) + (with-selected-window win + (condition-case nil + (funcall fn) + (error + (goto-char (pcase fn + ('scroll-up (point-min)) + ('scroll-down (point-max))))))) + (let ((magit-display-buffer-noselect t)) + (if (eq cmd #'magit-show-commit) + (apply #'magit-show-commit rev (magit-show-commit--arguments)) + (funcall cmd rev)))) + (call-interactively #'magit-show-commit)))) + +;;;; Section Commands + +(defun magit-section-cycle-diffs () + "Cycle visibility of diff-related sections in the current buffer." + (interactive) + (when-let ((sections + (cond ((derived-mode-p 'magit-status-mode) + (--mapcat + (when it + (when (oref it hidden) + (magit-section-show it)) + (oref it children)) + (list (magit-get-section '((staged) (status))) + (magit-get-section '((unstaged) (status)))))) + ((derived-mode-p 'magit-diff-mode) + (seq-filter #'magit-file-section-p + (oref magit-root-section children)))))) + (if (--any-p (oref it hidden) sections) + (dolist (s sections) + (magit-section-show s) + (magit-section-hide-children s)) + (let ((children (--mapcat (oref it children) sections))) + (cond ((and (--any-p (oref it hidden) children) + (--any-p (oref it children) children)) + (mapc #'magit-section-show-headings sections)) + ((seq-some #'magit-section-hidden-body children) + (mapc #'magit-section-show-children sections)) + (t + (mapc #'magit-section-hide sections))))))) + +;;; Diff Mode + +(defvar-keymap magit-diff-mode-map + :doc "Keymap for `magit-diff-mode'." + :parent magit-mode-map + "C-c C-d" #'magit-diff-while-committing + "C-c C-b" #'magit-go-backward + "C-c C-f" #'magit-go-forward + "SPC" #'scroll-up + "DEL" #'scroll-down + "j" #'magit-jump-to-diffstat-or-diff + "<remap> <write-file>" #'magit-patch-save) + +(define-derived-mode magit-diff-mode magit-mode "Magit Diff" + "Mode for looking at a Git diff. + +This mode is documented in info node `(magit)Diff Buffer'. + +\\<magit-mode-map>\ +Type \\[magit-refresh] to refresh the current buffer. +Type \\[magit-section-toggle] to expand or hide the section at point. +Type \\[magit-visit-thing] to visit the hunk or file at point. + +Staging and applying changes is documented in info node +`(magit)Staging and Unstaging' and info node `(magit)Applying'. + +\\<magit-hunk-section-map>Type \ +\\[magit-apply] to apply the change at point, \ +\\[magit-stage] to stage, +\\[magit-unstage] to unstage, \ +\\[magit-discard] to discard, or \ +\\[magit-reverse] to reverse it. + +\\{magit-diff-mode-map}" + :interactive nil + :group 'magit-diff + (magit-hack-dir-local-variables) + (setq magit--imenu-item-types 'file)) + +(put 'magit-diff-mode 'magit-diff-default-arguments + '("--stat" "--no-ext-diff")) + +(defun magit-diff-setup-buffer ( range typearg args files + &optional type locked) + (require 'magit) + (magit-setup-buffer #'magit-diff-mode locked + (magit-buffer-range range) + (magit-buffer-typearg typearg) + (magit-buffer-diff-type type) + (magit-buffer-diff-args args) + (magit-buffer-diff-files files) + (magit-buffer-diff-files-suspended nil))) + +(defun magit-diff-refresh-buffer () + "Refresh the current `magit-diff-mode' buffer." + (magit-set-header-line-format + (if (equal magit-buffer-typearg "--no-index") + (apply #'format "Differences between %s and %s" magit-buffer-diff-files) + (concat (if magit-buffer-range + (if (string-match-p "\\(\\.\\.\\|\\^-\\)" + magit-buffer-range) + (format "Changes in %s" magit-buffer-range) + (let ((msg "Changes from %s to %s") + (end (if (equal magit-buffer-typearg "--cached") + "index" + "working tree"))) + (if (member "-R" magit-buffer-diff-args) + (format msg end magit-buffer-range) + (format msg magit-buffer-range end)))) + (cond ((equal magit-buffer-typearg "--cached") + "Staged changes") + ((and (magit-repository-local-get 'this-commit-command) + (not (magit-anything-staged-p))) + "Uncommitting changes") + (t "Unstaged changes"))) + (pcase (length magit-buffer-diff-files) + (0) + (1 (concat " in file " (car magit-buffer-diff-files))) + (_ (concat " in files " + (string-join magit-buffer-diff-files ", "))))))) + (setq magit-buffer-range-hashed + (and magit-buffer-range (magit-hash-range magit-buffer-range))) + (magit-insert-section (diffbuf) + (magit-run-section-hook 'magit-diff-sections-hook))) + +(cl-defmethod magit-buffer-value (&context (major-mode magit-diff-mode)) + (nconc (cond (magit-buffer-range + (delq nil (list magit-buffer-range magit-buffer-typearg))) + ((equal magit-buffer-typearg "--cached") + (list 'staged)) + (t + (list 'unstaged magit-buffer-typearg))) + (and magit-buffer-diff-files (cons "--" magit-buffer-diff-files)))) + +(cl-defmethod magit-menu-common-value ((_section magit-diff-section)) + (magit-diff-scope)) + +(define-obsolete-variable-alias 'magit-diff-section-base-map + 'magit-diff-section-map "Magit-Section 4.0.0") + +(defvar-keymap magit-diff-section-map + :doc "Keymap for diff sections. +The classes `magit-file-section' and `magit-hunk-section' derive +from the abstract `magit-diff-section' class. Accordingly this +keymap is the parent of their keymaps." + "C-j" #'magit-diff-visit-worktree-file + "C-<return>" #'magit-diff-visit-worktree-file + "C-x 4 <return>" #'magit-diff-visit-file-other-window + "C-x 5 <return>" #'magit-diff-visit-file-other-frame + "&" #'magit-do-async-shell-command + "C" #'magit-commit-add-log + "C-x a" #'magit-add-change-log-entry + "C-x 4 a" #'magit-add-change-log-entry-other-window + "C-c C-t" #'magit-diff-trace-definition + "C-c C-e" #'magit-diff-edit-hunk-commit + "<remap> <magit-file-rename>" #'magit-file-rename + "<remap> <magit-file-untrack>" #'magit-file-untrack + "<remap> <magit-visit-thing>" #'magit-diff-visit-file + "<remap> <magit-revert-no-commit>" #'magit-reverse + "<remap> <magit-delete-thing>" #'magit-discard + "<remap> <magit-unstage-file>" #'magit-unstage + "<remap> <magit-stage-file>" #'magit-stage + "<remap> <magit-cherry-apply>" #'magit-apply + "<8>" (magit-menu-item "Rename file" #'magit-file-rename + '(:enable (eq (magit-diff-scope) 'file))) + "<7>" (magit-menu-item "Untrack %x" #'magit-file-untrack) + "<6>" (magit-menu-item "Visit file" #'magit-diff-visit-file + '(:enable (memq (magit-diff-scope) '(file files)))) + "<5>" (magit-menu-item "Reverse %x" #'magit-reverse + '(:enable (not (memq (magit-diff-type) + '(untracked unstaged))))) + "<4>" (magit-menu-item "Discard %x" #'magit-discard + '(:enable (not (memq (magit-diff-type) + '(committed undefined))))) + "<3>" (magit-menu-item "Unstage %x" #'magit-unstage + '(:enable (eq (magit-diff-type) 'staged))) + "<2>" (magit-menu-item "Stage %x" #'magit-stage + '(:enable (eq (magit-diff-type) 'unstaged))) + "<1>" (magit-menu-item "Apply %x" #'magit-apply + '(:enable (not (memq (magit-diff-type) + '(unstaged staged)))))) + +(defvar-keymap magit-file-section-map + ;; Even though this derived map doesn't add any bindings by default, + ;; it is quite possible that some users would want to add their own. + :doc "Keymap for `file' sections." + :parent magit-diff-section-base-map) + +(defvar-keymap magit-hunk-section-smerge-map + :doc "Keymap bound to `smerge-command-prefix' in `magit-hunk-section-map'." + "RET" #'magit-smerge-keep-current + "a" #'magit-smerge-keep-all + "u" #'magit-smerge-keep-upper + "b" #'magit-smerge-keep-base + "l" #'magit-smerge-keep-lower) + +(defvar-keymap magit-hunk-section-map + :doc "Keymap for `hunk' sections." + :parent magit-diff-section-base-map + (key-description smerge-command-prefix) magit-hunk-section-smerge-map) + +(defconst magit-diff-conflict-headline-re + (concat "^" (regexp-opt + ;; Defined in merge-tree.c in this order. + '("merged" + "added in remote" + "added in both" + "added in local" + "removed in both" + "changed in both" + "removed in local" + "removed in remote")))) + +(defconst magit-diff-headline-re + (concat "^\\(@@@?\\|diff\\|Submodule\\|" + "\\* Unmerged path\\|" + (substring magit-diff-conflict-headline-re 1) + "\\)")) + +(defconst magit-diff-statline-re + (concat "^ ?" + "\\(.*\\)" ; file + "\\( +| +\\)" ; separator + "\\([0-9]+\\|Bin\\(?: +[0-9]+ -> [0-9]+ bytes\\)?$\\) ?" + "\\(\\+*\\)" ; add + "\\(-*\\)$")) ; del + +(defvar magit-diff--reset-non-color-moved + (list + "-c" "color.diff.context=normal" + "-c" "color.diff.plain=normal" ; historical synonym for context + "-c" "color.diff.meta=normal" + "-c" "color.diff.frag=normal" + "-c" "color.diff.func=normal" + "-c" "color.diff.old=normal" + "-c" "color.diff.new=normal" + "-c" "color.diff.commit=normal" + "-c" "color.diff.whitespace=normal" + ;; "git-range-diff" does not support "--color-moved", so we don't + ;; need to reset contextDimmed, oldDimmed, newDimmed, contextBold, + ;; oldBold, and newBold. + )) + +(defun magit-insert-diff () + "Insert the diff into this `magit-diff-mode' buffer." + (magit--insert-diff t + "diff" magit-buffer-range "-p" "--no-prefix" + (and (member "--stat" magit-buffer-diff-args) "--numstat") + magit-buffer-typearg + magit-buffer-diff-args "--" + magit-buffer-diff-files)) + +(defun magit--insert-diff (keep-error &rest args) + (declare (indent 1)) + (pcase-let ((`(,cmd . ,args) + (flatten-tree args)) + (magit-git-global-arguments + (remove "--literal-pathspecs" magit-git-global-arguments))) + ;; As of Git 2.19.0, we need to generate diffs with + ;; --ita-visible-in-index so that `magit-stage' can work with + ;; intent-to-add files (see #4026). + (when (and (not (equal cmd "merge-tree")) + (magit-git-version>= "2.19.0")) + (push "--ita-visible-in-index" args)) + (setq args (magit-diff--maybe-add-stat-arguments args)) + (when (cl-member-if (lambda (arg) (string-prefix-p "--color-moved" arg)) args) + (push "--color=always" args) + (setq magit-git-global-arguments + (append magit-diff--reset-non-color-moved + magit-git-global-arguments))) + (magit--git-wash #'magit-diff-wash-diffs + (if (member "--no-index" args) 'wash-anyway keep-error) + cmd args))) + +(defun magit-diff--maybe-add-stat-arguments (args) + (if (member "--stat" args) + (append (if (functionp magit-diff-extra-stat-arguments) + (funcall magit-diff-extra-stat-arguments) + magit-diff-extra-stat-arguments) + args) + args)) + +(defun magit-diff-use-window-width-as-stat-width () + "Use the `window-width' as the value of `--stat-width'." + (and-let* ((window (get-buffer-window (current-buffer) 'visible))) + (list (format "--stat-width=%d" (window-width window))))) + +(defun magit-diff-wash-diffs (args &optional limit) + (run-hooks 'magit-diff-wash-diffs-hook) + (when (member "--show-signature" args) + (magit-diff-wash-signature magit-buffer-revision-hash)) + (when (member "--stat" args) + (magit-diff-wash-diffstat)) + (when (re-search-forward magit-diff-headline-re limit t) + (goto-char (line-beginning-position)) + (magit-wash-sequence (apply-partially #'magit-diff-wash-diff args)) + (insert ?\n))) + +(defun magit-jump-to-diffstat-or-diff () + "Jump to the diffstat or diff. +When point is on a file inside the diffstat section, then jump +to the respective diff section, otherwise jump to the diffstat +section or a child thereof." + (interactive) + (if-let ((section (magit-get-section + (append (magit-section-case + ([file diffstat] `((file . ,(oref it value)))) + (file `((file . ,(oref it value)) (diffstat))) + (t '((diffstat)))) + (magit-section-ident magit-root-section))))) + (magit-section-goto section) + (user-error "No diffstat in this buffer"))) + +(defun magit-diff-wash-signature (object) + (cond + ((looking-at "^No signature") + (delete-line)) + ((looking-at "^gpg: ") + (let (title end) + (save-excursion + (while (looking-at "^gpg: ") + (cond + ((looking-at "^gpg: Good signature from") + (setq title (propertize + (buffer-substring (point) (line-end-position)) + 'face 'magit-signature-good))) + ((looking-at "^gpg: Can't check signature") + (setq title (propertize + (buffer-substring (point) (line-end-position)) + 'face '(italic bold))))) + (forward-line)) + (setq end (point-marker))) + (magit-insert-section (signature object title) + (when title + (magit-insert-heading title)) + (goto-char end) + (set-marker end nil) + (insert "\n")))))) + +(defun magit-diff-wash-diffstat () + (let (heading (beg (point))) + (when (re-search-forward "^ ?\\([0-9]+ +files? change[^\n]*\n\\)" nil t) + (setq heading (match-string 1)) + (magit-delete-match) + (goto-char beg) + (magit-insert-section (diffstat) + (insert (propertize heading 'font-lock-face 'magit-diff-file-heading)) + (magit-insert-heading) + (let (files) + (while (looking-at "^[-0-9]+\t[-0-9]+\t\\(.+\\)$") + (push (magit-decode-git-path + (let ((f (match-string 1))) + (cond + ((string-match "{.* => \\(.*\\)}" f) + (replace-match (match-string 1 f) nil t f)) + ((string-match " => " f) + (substring f (match-end 0))) + (t f)))) + files) + (magit-delete-line)) + (setq files (nreverse files)) + (while (looking-at magit-diff-statline-re) + (magit-bind-match-strings (file sep cnt add del) nil + (magit-delete-line) + (when (string-match " +$" file) + (setq sep (concat (match-string 0 file) sep)) + (setq file (substring file 0 (match-beginning 0)))) + (let ((le (length file)) ld) + (setq file (magit-decode-git-path file)) + (setq ld (length file)) + (when (> le ld) + (setq sep (concat (make-string (- le ld) ?\s) sep)))) + (magit-insert-section (file (pop files)) + (insert (propertize file 'font-lock-face 'magit-filename) + sep cnt " ") + (when add + (insert (propertize add 'font-lock-face + 'magit-diffstat-added))) + (when del + (insert (propertize del 'font-lock-face + 'magit-diffstat-removed))) + (insert "\n"))))) + (if (looking-at "^$") (forward-line) (insert "\n")))))) + +(defun magit-diff-wash-diff (args) + (when (cl-member-if (lambda (arg) (string-prefix-p "--color-moved" arg)) args) + (require 'ansi-color) + (ansi-color-apply-on-region (point-min) (point-max))) + (cond + ((looking-at "^Submodule") + (magit-diff-wash-submodule)) + ((looking-at "^\\* Unmerged path \\(.*\\)") + (let ((file (magit-decode-git-path (match-string 1)))) + (magit-delete-line) + (unless (and (derived-mode-p 'magit-status-mode) + (not (member "--cached" args))) + (magit-insert-section (file file) + (insert (propertize + (format "unmerged %s%s" file + (pcase (cddr (car (magit-file-status file))) + ('(?D ?D) " (both deleted)") + ('(?D ?U) " (deleted by us)") + ('(?U ?D) " (deleted by them)") + ('(?A ?A) " (both added)") + ('(?A ?U) " (added by us)") + ('(?U ?A) " (added by them)") + ('(?U ?U) ""))) + 'font-lock-face 'magit-diff-file-heading)) + (insert ?\n)))) + t) + ((looking-at magit-diff-conflict-headline-re) + (let ((long-status (match-string 0)) + (status "BUG") + file orig base) + (if (equal long-status "merged") + (progn (setq status long-status) + (setq long-status nil)) + (setq status (pcase-exhaustive long-status + ("added in remote" "new file") + ("added in both" "new file") + ("added in local" "new file") + ("removed in both" "removed") + ("changed in both" "changed") + ("removed in local" "removed") + ("removed in remote" "removed")))) + (magit-delete-line) + (while (looking-at + "^ \\([^ ]+\\) +[0-9]\\{6\\} \\([a-z0-9]\\{40,\\}\\) \\(.+\\)$") + (magit-bind-match-strings (side _blob name) nil + (pcase side + ("result" (setq file name)) + ("our" (setq orig name)) + ("their" (setq file name)) + ("base" (setq base name)))) + (magit-delete-line)) + (when orig (setq orig (magit-decode-git-path orig))) + (when file (setq file (magit-decode-git-path file))) + (magit-diff-insert-file-section + (or file base) orig status nil nil nil nil long-status))) + ;; The files on this line may be ambiguous due to whitespace. + ;; That's okay. We can get their names from subsequent headers. + ((looking-at "^diff --\ +\\(?:\\(?1:git\\) \\(?:\\(?2:.+?\\) \\2\\)?\ +\\|\\(?:cc\\|combined\\) \\(?3:.+\\)\\)") + (let ((status (cond ((equal (match-string 1) "git") "modified") + ((derived-mode-p 'magit-revision-mode) "resolved") + (t "unmerged"))) + (orig nil) + (file (or (match-string 2) (match-string 3))) + (header (list (buffer-substring-no-properties + (line-beginning-position) (1+ (line-end-position))))) + (modes nil) + (rename nil) + (binary nil)) + (magit-delete-line) + (while (not (or (eobp) (looking-at magit-diff-headline-re))) + (cond + ((looking-at "old mode \\(?:[^\n]+\\)\nnew mode \\(?:[^\n]+\\)\n") + (setq modes (match-string 0))) + ((looking-at "deleted file .+\n") + (setq status "deleted")) + ((looking-at "new file .+\n") + (setq status "new file")) + ((looking-at "rename from \\(.+\\)\nrename to \\(.+\\)\n") + (setq rename (match-string 0)) + (setq orig (match-string 1)) + (setq file (match-string 2)) + (setq status "renamed")) + ((looking-at "copy from \\(.+\\)\ncopy to \\(.+\\)\n") + (setq orig (match-string 1)) + (setq file (match-string 2)) + (setq status "new file")) + ((looking-at "similarity index .+\n")) + ((looking-at "dissimilarity index .+\n")) + ((looking-at "index .+\n")) + ((looking-at "--- \\(.+?\\)\t?\n") + (unless (equal (match-string 1) "/dev/null") + (setq orig (match-string 1)))) + ((looking-at "\\+\\+\\+ \\(.+?\\)\t?\n") + (unless (equal (match-string 1) "/dev/null") + (setq file (match-string 1)))) + ((looking-at "Binary files .+ and .+ differ\n") + (setq binary t)) + ((looking-at "Binary files differ\n") + (setq binary t)) + ;; TODO Use all combined diff extended headers. + ((looking-at "mode .+\n")) + ((error "BUG: Unknown extended header: %S" + (buffer-substring (point) (line-end-position))))) + ;; These headers are treated as some sort of special hunk. + (unless (or (string-prefix-p "old mode" (match-string 0)) + (string-prefix-p "rename" (match-string 0))) + (push (match-string 0) header)) + (magit-delete-match)) + (when orig + (setq orig (magit-decode-git-path orig))) + (setq file (magit-decode-git-path file)) + (setq header (nreverse header)) + ;; KLUDGE `git-log' ignores `--no-prefix' when `-L' is used. + (when (and (derived-mode-p 'magit-log-mode) + (seq-some (lambda (arg) (string-prefix-p "-L" arg)) + magit-buffer-log-args)) + (when orig + (setq orig (substring orig 2))) + (setq file (substring file 2)) + (setq header (list (save-excursion + (string-match "diff [^ ]+" (car header)) + (format "%s %s %s\n" + (match-string 0 (car header)) + (or orig file) + (or file orig))) + (format "--- %s\n" (or orig "/dev/null")) + (format "+++ %s\n" (or file "/dev/null"))))) + (setq header (string-join header)) + (magit-diff-insert-file-section + file orig status modes rename header binary nil))))) + +(defun magit-diff-insert-file-section + (file orig status modes rename header binary long-status) + (magit-insert-section + ( file file + (or (equal status "deleted") (derived-mode-p 'magit-status-mode)) + :source (and (not (equal orig file)) orig) + :header header + :binary binary) + (insert (propertize (format "%-10s %s" status + (if (or (not orig) (equal orig file)) + file + (format "%s -> %s" orig file))) + 'font-lock-face 'magit-diff-file-heading)) + (cond ((and binary long-status) + (insert (format " (%s, binary)" long-status))) + ((or binary long-status) + (insert (format " (%s)" (if binary "binary" long-status))))) + (magit-insert-heading) + (when modes + (magit-insert-section (hunk '(chmod)) + (insert modes) + (magit-insert-heading))) + (when rename + (magit-insert-section (hunk '(rename)) + (insert rename) + (magit-insert-heading))) + (magit-wash-sequence #'magit-diff-wash-hunk))) + +(defun magit-diff-wash-submodule () + ;; See `show_submodule_summary' in submodule.c and "this" commit. + (when (looking-at "^Submodule \\([^ ]+\\)") + (let ((module (match-string 1)) + untracked modified) + (when (looking-at "^Submodule [^ ]+ contains untracked content$") + (magit-delete-line) + (setq untracked t)) + (when (looking-at "^Submodule [^ ]+ contains modified content$") + (magit-delete-line) + (setq modified t)) + (cond + ((and (looking-at "^Submodule \\([^ ]+\\) \\([^ :]+\\)\\( (rewind)\\)?:$") + (equal (match-string 1) module)) + (magit-bind-match-strings (_module range rewind) nil + (magit-delete-line) + (while (looking-at "^ \\([<>]\\) \\(.*\\)$") + (magit-delete-line)) + (when rewind + (setq range (replace-regexp-in-string "[^.]\\(\\.\\.\\)[^.]" + "..." range t t 1))) + (magit-insert-section (module module t) + (magit-insert-heading + (propertize (concat "modified " module) + 'font-lock-face 'magit-diff-file-heading) + " (" + (cond (rewind "rewind") + ((string-search "..." range) "non-ff") + (t "new commits")) + (and (or modified untracked) + (concat ", " + (and modified "modified") + (and modified untracked " and ") + (and untracked "untracked") + " content")) + ")") + (magit-insert-section-body + (let ((default-directory + (file-name-as-directory + (expand-file-name module (magit-toplevel))))) + (magit-git-wash (apply-partially #'magit-log-wash-log 'module) + "log" "--oneline" "--left-right" range) + (delete-char -1)))))) + ((and (looking-at "^Submodule \\([^ ]+\\) \\([^ ]+\\) (\\([^)]+\\))$") + (equal (match-string 1) module)) + (magit-bind-match-strings (_module _range msg) nil + (magit-delete-line) + (magit-insert-section (module module) + (magit-insert-heading + (propertize (concat "submodule " module) + 'font-lock-face 'magit-diff-file-heading) + " (" msg ")")))) + (t + (magit-insert-section (module module) + (magit-insert-heading + (propertize (concat "modified " module) + 'font-lock-face 'magit-diff-file-heading) + " (" + (and modified "modified") + (and modified untracked " and ") + (and untracked "untracked") + " content)"))))))) + +(defun magit-diff-wash-hunk () + (when (looking-at "^@\\{2,\\} \\(.+?\\) @\\{2,\\}\\(?: \\(.*\\)\\)?") + (let* ((heading (match-string 0)) + (ranges (mapcar + (lambda (str) + (let ((range + (mapcar #'string-to-number + (split-string (substring str 1) ",")))) + ;; A single line is +1 rather than +1,1. + (if (length= range 1) + (nconc range (list 1)) + range))) + (split-string (match-string 1)))) + (about (match-string 2)) + (combined (length= ranges 3)) + (value (cons about ranges))) + (magit-delete-line) + (magit-insert-section + ( hunk value nil + :washer #'magit-diff-paint-hunk + :combined combined + :from-range (if combined (butlast ranges) (car ranges)) + :to-range (car (last ranges)) + :about about) + (insert (propertize (concat heading "\n") + 'font-lock-face 'magit-diff-hunk-heading)) + (magit-insert-heading) + (while (not (or (eobp) (looking-at "^[^-+\s\\]"))) + (forward-line)))) + t)) + +(defun magit-diff-expansion-threshold (section) + "Keep new diff sections collapsed if washing takes too long." + (and (magit-file-section-p section) + (> (float-time (time-since magit-refresh-start-time)) + magit-diff-expansion-threshold) + 'hide)) + +(add-hook 'magit-section-set-visibility-hook #'magit-diff-expansion-threshold) + +;;; Revision Mode + +(define-derived-mode magit-revision-mode magit-diff-mode "Magit Rev" + "Mode for looking at a Git commit. + +This mode is documented in info node `(magit)Revision Buffer'. + +\\<magit-mode-map>\ +Type \\[magit-refresh] to refresh the current buffer. +Type \\[magit-section-toggle] to expand or hide the section at point. +Type \\[magit-visit-thing] to visit the hunk or file at point. + +Staging and applying changes is documented in info node +`(magit)Staging and Unstaging' and info node `(magit)Applying'. + +\\<magit-hunk-section-map>Type \ +\\[magit-apply] to apply the change at point, \ +\\[magit-stage] to stage, +\\[magit-unstage] to unstage, \ +\\[magit-discard] to discard, or \ +\\[magit-reverse] to reverse it. + +\\{magit-revision-mode-map}" + :interactive nil + :group 'magit-revision + (magit-hack-dir-local-variables)) + +(put 'magit-revision-mode 'magit-diff-default-arguments + '("--stat" "--no-ext-diff")) + +(defun magit-revision-setup-buffer (rev args files) + (magit-setup-buffer #'magit-revision-mode nil + (magit-buffer-revision rev) + (magit-buffer-range (format "%s^..%s" rev rev)) + (magit-buffer-diff-type 'committed) + (magit-buffer-diff-args args) + (magit-buffer-diff-files files) + (magit-buffer-diff-files-suspended nil))) + +(defun magit-revision-refresh-buffer () + (setq magit-buffer-revision-hash (magit-rev-hash magit-buffer-revision)) + (magit-set-header-line-format + (concat (magit-object-type magit-buffer-revision-hash) + " " magit-buffer-revision + (pcase (length magit-buffer-diff-files) + (0) + (1 (concat " limited to file " (car magit-buffer-diff-files))) + (_ (concat " limited to files " + (string-join magit-buffer-diff-files ", ")))))) + (magit-insert-section (commitbuf) + (magit-run-section-hook 'magit-revision-sections-hook))) + +(cl-defmethod magit-buffer-value (&context (major-mode magit-revision-mode)) + (cons magit-buffer-revision magit-buffer-diff-files)) + +(defun magit-insert-revision-diff () + "Insert the diff into this `magit-revision-mode' buffer." + (magit--insert-diff t + "show" "-p" "--format=" "--no-prefix" + (and (member "--stat" magit-buffer-diff-args) "--numstat") + magit-buffer-diff-args + (magit--rev-dereference magit-buffer-revision) + "--" magit-buffer-diff-files)) + +(defun magit-insert-revision-tag () + "Insert tag message and headers into a revision buffer. +This function only inserts anything when `magit-show-commit' is +called with a tag as argument, when that is called with a commit +or a ref which is not a branch, then it inserts nothing." + (when (equal (magit-object-type magit-buffer-revision) "tag") + (magit-insert-section (taginfo) + (let ((beg (point))) + ;; "git verify-tag -v" would output what we need, but the gpg + ;; output is send to stderr and we have no control over the + ;; order in which stdout and stderr are inserted, which would + ;; make parsing hard. We are forced to use "git cat-file tag" + ;; instead, which inserts the signature instead of verifying + ;; it. We remove that later and then insert the verification + ;; output using "git verify-tag" (without the "-v"). + (magit-git-insert "cat-file" "tag" magit-buffer-revision) + (goto-char beg) + (forward-line 3) + (delete-region beg (point))) + (looking-at "^tagger \\([^<]+\\) <\\([^>]+\\)") + (let ((heading (format "Tagger: %s <%s>" + (match-string 1) + (match-string 2)))) + (magit-delete-line) + (insert (propertize heading 'font-lock-face + 'magit-section-secondary-heading))) + (magit-insert-heading) + (forward-line) + (magit-insert-section + ( message nil nil + :heading-highlight-face 'magit-diff-revision-summary-highlight) + (let ((beg (point))) + (forward-line) + (magit--add-face-text-property + beg (point) 'magit-diff-revision-summary)) + (magit-insert-heading) + (if (re-search-forward "-----BEGIN PGP SIGNATURE-----" nil t) + (goto-char (match-beginning 0)) + (goto-char (point-max))) + (insert ?\n)) + (if (re-search-forward "-----BEGIN PGP SIGNATURE-----" nil t) + (progn + (let ((beg (match-beginning 0))) + (re-search-forward "-----END PGP SIGNATURE-----\n") + (delete-region beg (point))) + (save-excursion + (magit-process-git t "verify-tag" magit-buffer-revision)) + (magit-diff-wash-signature magit-buffer-revision)) + (goto-char (point-max))) + (insert ?\n)))) + +(defvar-keymap magit-commit-message-section-map + :doc "Keymap for `commit-message' sections." + "<remap> <magit-visit-thing>" #'magit-show-commit + "<1>" (magit-menu-item "Visit %t" #'magit-show-commit + '(:enable (magit-thing-at-point 'git-revision t)))) + +(defun magit-insert-revision-message () + "Insert the commit message into a revision buffer." + (magit-insert-section + ( commit-message nil nil + :heading-highlight-face 'magit-diff-revision-summary-highlight) + (if-let* ((rev magit-buffer-revision) + (msg (with-temp-buffer + (save-excursion (magit-rev-insert-format "%B" rev)) + (magit-revision--wash-message)))) + (progn + (save-excursion (insert msg)) + (magit-revision--wash-message-hashes) + (save-excursion + (magit--add-face-text-property (point) + (progn (forward-line) (point)) + 'magit-diff-revision-summary) + (magit-insert-heading)) + (goto-char (point-max))) + (insert "(no message)\n")))) + +(defun magit-insert-revision-notes () + "Insert commit notes into a revision buffer." + (let ((default (or (magit-get "core.notesRef") "refs/notes/commits"))) + (dolist (ref (magit-list-active-notes-refs)) + (when-let* ((rev magit-buffer-revision) + (msg (with-temp-buffer + (save-excursion + (magit-git-insert "-c" (concat "core.notesRef=" ref) + "notes" "show" rev)) + (magit-revision--wash-message)))) + (magit-insert-section + ( notes ref (not (equal ref default)) + :heading-highlight-face 'magit-diff-hunk-heading-highlight) + (save-excursion (insert msg)) + (magit-revision--wash-message-hashes) + (save-excursion + (end-of-line) + (insert (format " (%s)" + (propertize (if (string-prefix-p "refs/notes/" ref) + (substring ref 11) + ref) + 'font-lock-face 'magit-refname)))) + (magit--add-face-text-property (point) + (progn (forward-line) (point)) + 'magit-diff-revision-summary) + (magit-insert-heading) + (goto-char (point-max)) + (insert ?\n)))))) + +(defun magit-revision--wash-message () + (let ((major-mode 'git-commit-mode)) + (hack-dir-local-variables) + (hack-local-variables-apply)) + (unless (memq git-commit-major-mode '(nil text-mode)) + (funcall git-commit-major-mode) + (font-lock-ensure)) + (when (> (point-max) (point-min)) + (save-excursion + (while (search-forward "\r\n" nil t) ; Remove trailing CRs. + (delete-region (match-beginning 0) (1+ (match-beginning 0))))) + (when magit-revision-fill-summary-line + (let ((fill-column (min magit-revision-fill-summary-line + (window-width (get-buffer-window nil t))))) + (fill-region (point) (line-end-position)))) + (when magit-diff-highlight-keywords + (save-excursion + (while (re-search-forward "\\[[^[]*\\]" nil t) + (put-text-property (match-beginning 0) + (match-end 0) + 'font-lock-face 'magit-keyword)))) + (run-hook-wrapped 'magit-wash-message-hook + (lambda (fn) (save-excursion (funcall fn)))) + (buffer-string))) + +(defun magit-revision--wash-message-hashes () + (when magit-revision-use-hash-sections + (save-excursion + ;; Start after beg to prevent a (commit text) section from + ;; starting at the same point as the (commit-message) + ;; section. + (while (not (eobp)) + (re-search-forward "\\_<" nil 'move) + (let ((beg (point))) + (re-search-forward "\\_>" nil t) + (when (> (point) beg) + (let ((text (buffer-substring-no-properties beg (point)))) + (when (pcase magit-revision-use-hash-sections + ('quickest ; false negatives and positives + (and (>= (length text) 7) + (string-match-p "[0-9]" text) + (string-match-p "[a-z]" text))) + ('quicker ; false negatives (number-less hashes) + (and (>= (length text) 7) + (string-match-p "[0-9]" text) + (magit-commit-p text))) + ('quick ; false negatives (short hashes) + (and (>= (length text) 7) + (magit-commit-p text))) + ('slow + (magit-commit-p text))) + (put-text-property beg (point) + 'font-lock-face 'magit-hash) + (let ((end (point))) + (goto-char beg) + (magit-insert-section (commit text) + (goto-char end))))))))))) + +(defun magit-insert-revision-headers () + "Insert headers about the commit into a revision buffer." + (magit-insert-section (headers) + (when-let ((string (magit-rev-format "%D" magit-buffer-revision + "--decorate=full"))) + (insert (magit-format-ref-labels string) ?\s)) + (insert (propertize + (magit-rev-parse (magit--rev-dereference magit-buffer-revision)) + 'font-lock-face 'magit-hash)) + (magit-insert-heading) + (let ((beg (point))) + (magit-rev-insert-format magit-revision-headers-format + magit-buffer-revision) + (magit-insert-revision-gravatars magit-buffer-revision beg)) + (when magit-revision-insert-related-refs + (when (magit-revision-insert-related-refs-display-p 'parents) + (dolist (parent (magit-commit-parents magit-buffer-revision)) + (magit-insert-section (commit parent) + (let ((line (magit-rev-format "%h %s" parent))) + (string-match "^\\([^ ]+\\) \\(.*\\)" line) + (magit-bind-match-strings (hash msg) line + (insert "Parent: ") + (insert (propertize hash 'font-lock-face 'magit-hash)) + (insert " " msg "\n")))))) + (when (magit-revision-insert-related-refs-display-p 'merged) + (magit--insert-related-refs + magit-buffer-revision "--merged" "Merged" + (eq magit-revision-insert-related-refs 'all))) + (when (magit-revision-insert-related-refs-display-p 'contained) + (magit--insert-related-refs + magit-buffer-revision "--contains" "Contained" + (memq magit-revision-insert-related-refs '(all mixed)))) + (when (magit-revision-insert-related-refs-display-p 'follows) + (when-let ((follows (magit-get-current-tag magit-buffer-revision t))) + (let ((tag (car follows)) + (cnt (cadr follows))) + (magit-insert-section (tag tag) + (insert + (format "Follows: %s (%s)\n" + (propertize tag 'font-lock-face 'magit-tag) + (propertize (number-to-string cnt) + 'font-lock-face 'magit-branch-local))))))) + (when (magit-revision-insert-related-refs-display-p 'precedes) + (when-let ((precedes (magit-get-next-tag magit-buffer-revision t))) + (let ((tag (car precedes)) + (cnt (cadr precedes))) + (magit-insert-section (tag tag) + (insert (format "Precedes: %s (%s)\n" + (propertize tag 'font-lock-face 'magit-tag) + (propertize (number-to-string cnt) + 'font-lock-face 'magit-tag))))))) + (insert ?\n)))) + +(defun magit-revision-insert-related-refs-display-p (sym) + "Whether to display related branches of type SYM. +Refer to user option `magit-revision-insert-related-refs-display-alist'." + (if-let ((elt (assq sym magit-revision-insert-related-refs-display-alist))) + (cdr elt) + t)) + +(defun magit--insert-related-refs (rev arg title remote) + (when-let ((refs (magit-list-related-branches arg rev (and remote "-a")))) + (insert title ":" (make-string (- 10 (length title)) ?\s)) + (dolist (branch refs) + (if (<= (+ (current-column) 1 (length branch)) + (window-width)) + (insert ?\s) + (insert ?\n (make-string 12 ?\s))) + (magit-insert-section (branch branch) + (insert (propertize branch 'font-lock-face + (if (string-prefix-p "remotes/" branch) + 'magit-branch-remote + 'magit-branch-local))))) + (insert ?\n))) + +(defun magit-insert-revision-gravatars (rev beg) + (when (and magit-revision-show-gravatars + (window-system)) + (require 'gravatar) + (pcase-let ((`(,author . ,committer) + (pcase magit-revision-show-gravatars + ('t '("^Author: " . "^Commit: ")) + ('author '("^Author: " . nil)) + ('committer '(nil . "^Commit: ")) + (_ magit-revision-show-gravatars)))) + (when-let ((email (and author (magit-rev-format "%aE" rev)))) + (magit-insert-revision-gravatar beg rev email author)) + (when-let ((email (and committer (magit-rev-format "%cE" rev)))) + (magit-insert-revision-gravatar beg rev email committer))))) + +(defun magit-insert-revision-gravatar (beg rev email regexp) + (save-excursion + (goto-char beg) + (when (re-search-forward regexp nil t) + (when-let ((window (get-buffer-window))) + (let* ((column (length (match-string 0))) + (font-obj (query-font (font-at (point) window))) + (size (* 2 (+ (aref font-obj 4) + (aref font-obj 5)))) + (align-to (+ column + (ceiling (/ size (aref font-obj 7) 1.0)) + 1)) + (gravatar-size (- size 2))) + (ignore-errors ; service may be unreachable + (gravatar-retrieve email #'magit-insert-revision-gravatar-cb + (list gravatar-size rev + (point-marker) + align-to column)))))))) + +(defun magit-insert-revision-gravatar-cb (image size rev marker align-to column) + (unless (eq image 'error) + (when-let ((buffer (marker-buffer marker))) + (with-current-buffer buffer + (save-excursion + (goto-char marker) + ;; The buffer might display another revision by now or + ;; it might have been refreshed, in which case another + ;; process might already have inserted the image. + (when (and (equal rev magit-buffer-revision) + (not (eq (car-safe + (car-safe + (get-text-property (point) 'display))) + 'image))) + (setf (image-property image :ascent) 'center) + (setf (image-property image :relief) 1) + (setf (image-property image :scale) 1) + (setf (image-property image :height) size) + (let ((top (list image '(slice 0.0 0.0 1.0 0.5))) + (bot (list image '(slice 0.0 0.5 1.0 1.0))) + (align `((space :align-to ,align-to)))) + (let ((inhibit-read-only t)) + (insert (propertize " " 'display top)) + (insert (propertize " " 'display align)) + (forward-line) + (forward-char column) + (insert (propertize " " 'display bot)) + (insert (propertize " " 'display align)))))))))) + +;;; Merge-Preview Mode + +(define-derived-mode magit-merge-preview-mode magit-diff-mode "Magit Merge" + "Mode for previewing a merge." + :interactive nil + :group 'magit-diff + (magit-hack-dir-local-variables)) + +(put 'magit-merge-preview-mode 'magit-diff-default-arguments + '("--no-ext-diff")) + +(defun magit-merge-preview-setup-buffer (rev) + (magit-setup-buffer #'magit-merge-preview-mode nil + (magit-buffer-revision rev) + (magit-buffer-range (format "%s^..%s" rev rev)))) + +(defun magit-merge-preview-refresh-buffer () + (let* ((branch (magit-get-current-branch)) + (head (or branch (magit-rev-verify "HEAD")))) + (magit-set-header-line-format (format "Preview merge of %s into %s" + magit-buffer-revision + (or branch "HEAD"))) + (magit-insert-section (diffbuf) + (magit--insert-diff t + "merge-tree" (magit-git-string "merge-base" head magit-buffer-revision) + head magit-buffer-revision)))) + +(cl-defmethod magit-buffer-value (&context (major-mode magit-merge-preview-mode)) + magit-buffer-revision) + +;;; Hunk Section + +(defun magit-hunk-set-window-start (section) + "When SECTION is a `hunk', ensure that its beginning is visible. +It the SECTION has a different type, then do nothing." + (when (magit-hunk-section-p section) + (magit-section-set-window-start section))) + +(add-hook 'magit-section-movement-hook #'magit-hunk-set-window-start) + +(cl-defmethod magit-section-get-relative-position ((_section magit-hunk-section)) + (nconc (cl-call-next-method) + (and (region-active-p) + (progn + (goto-char (line-beginning-position)) + (when (looking-at "^[-+]") (forward-line)) + (while (looking-at "^[ @]") (forward-line)) + (let ((beg (magit-point))) + (list (cond + ((looking-at "^[-+]") + (forward-line) + (while (looking-at "^[-+]") (forward-line)) + (while (looking-at "^ ") (forward-line)) + (forward-line -1) + (regexp-quote (buffer-substring-no-properties + beg (line-end-position)))) + (t t)))))))) + +(cl-defmethod magit-section-goto-successor ((section magit-hunk-section) + line char &optional arg) + (or (magit-section-goto-successor--same section line char) + (and-let* ((parent (magit-get-section + (magit-section-ident + (oref section parent))))) + (let* ((children (oref parent children)) + (siblings (magit-section-siblings section 'prev)) + (previous (nth (length siblings) children))) + (if (not arg) + (when-let ((sibling (or previous (car (last children))))) + (magit-section-goto sibling) + t) + (when previous + (magit-section-goto previous)) + (if (and (stringp arg) + (re-search-forward arg (oref parent end) t)) + (goto-char (match-beginning 0)) + (goto-char (oref (car (last children)) end)) + (forward-line -1) + (while (looking-at "^ ") (forward-line -1)) + (while (looking-at "^[-+]") (forward-line -1)) + (forward-line))))) + (magit-section-goto-successor--related section))) + +;;; Diff Sections + +(defvar-keymap magit-unstaged-section-map + :doc "Keymap for the `unstaged' section." + "<remap> <magit-visit-thing>" #'magit-diff-unstaged + "<remap> <magit-stage-file>" #'magit-stage + "<remap> <magit-delete-thing>" #'magit-discard + "<3>" (magit-menu-item "Discard all" #'magit-discard) + "<2>" (magit-menu-item "Stage all" #'magit-stage) + "<1>" (magit-menu-item "Visit diff" #'magit-diff-unstaged)) + +(magit-define-section-jumper magit-jump-to-unstaged + "Unstaged changes" unstaged nil magit-insert-unstaged-changes) + +(defun magit-insert-unstaged-changes () + "Insert section showing unstaged changes." + (magit-insert-section (unstaged) + (magit-insert-heading t "Unstaged changes") + (magit--insert-diff nil + "diff" magit-buffer-diff-args "--no-prefix" + "--" magit-buffer-diff-files))) + +(defvar-keymap magit-staged-section-map + :doc "Keymap for the `staged' section." + "<remap> <magit-revert-no-commit>" #'magit-reverse + "<remap> <magit-delete-thing>" #'magit-discard + "<remap> <magit-unstage-file>" #'magit-unstage + "<remap> <magit-visit-thing>" #'magit-diff-staged + "<4>" (magit-menu-item "Reverse all" #'magit-reverse) + "<3>" (magit-menu-item "Discard all" #'magit-discard) + "<2>" (magit-menu-item "Unstage all" #'magit-unstage) + "<1>" (magit-menu-item "Visit diff" #'magit-diff-staged)) + +(magit-define-section-jumper magit-jump-to-staged + "Staged changes" staged nil magit-insert-staged-changes) + +(defun magit-insert-staged-changes () + "Insert section showing staged changes." + ;; Avoid listing all files as deleted when visiting a bare repo. + (unless (magit-bare-repo-p) + (magit-insert-section (staged) + (magit-insert-heading t "Staged changes") + (magit--insert-diff nil + "diff" "--cached" magit-buffer-diff-args "--no-prefix" + "--" magit-buffer-diff-files)))) + +;;; Diff Type + +(defvar magit--diff-use-recorded-type-p t) + +(defun magit-diff-type (&optional section) + "Return the diff type of SECTION. + +The returned type is one of the symbols `staged', `unstaged', +`committed', or `undefined'. This type serves a similar purpose +as the general type common to all sections (which is stored in +the `type' slot of the corresponding `magit-section' struct) but +takes additional information into account. When the SECTION +isn't related to diffs and the buffer containing it also isn't +a diff-only buffer, then return nil. + +Currently the type can also be one of `tracked' and `untracked' +but these values are not handled explicitly everywhere they +should be and a possible fix could be to just return nil here. + +The section has to be a `diff' or `hunk' section, or a section +whose children are of type `diff'. If optional SECTION is nil, +return the diff type for the current section. In buffers whose +major mode is `magit-diff-mode' SECTION is ignored and the type +is determined using other means. In `magit-revision-mode' +buffers the type is always `committed'. + +Do not confuse this with `magit-diff-scope' (which see)." + (when-let ((section (or section (magit-current-section)))) + (cond ((derived-mode-p 'magit-revision-mode 'magit-stash-mode) 'committed) + ((derived-mode-p 'magit-diff-mode) + (let ((range magit-buffer-range) + (const magit-buffer-typearg)) + (cond ((and magit--diff-use-recorded-type-p + magit-buffer-diff-type)) + ((equal const "--no-index") 'undefined) + ((or (not range) + (equal range "HEAD") + (magit-rev-eq range "HEAD")) + (if (equal const "--cached") + 'staged + 'unstaged)) + ((equal const "--cached") + (if (magit-rev-head-p range) + 'staged + 'undefined)) ; i.e., committed and staged + (t 'committed)))) + ((derived-mode-p 'magit-status-mode) + (let ((stype (oref section type))) + (if (memq stype '(staged unstaged tracked untracked)) + stype + (pcase stype + ((or 'file 'module) + (let* ((parent (oref section parent)) + (type (oref parent type))) + (if (memq type '(file module)) + (magit-diff-type parent) + type))) + ('hunk (thread-first section + (oref parent) + (oref parent) + (oref type))))))) + ((derived-mode-p 'magit-log-mode) + (if (or (and (magit-section-match 'commit section) + (oref section children)) + (magit-section-match [* file commit] section)) + 'committed + 'undefined)) + (t 'undefined)))) + +(cl-defun magit-diff-scope (&optional (section nil ssection) strict) + "Return the diff scope of SECTION or the selected section(s). + +A diff's \"scope\" describes what part of a diff is selected, it is +a symbol, one of `region', `hunk', `hunks', `file', `files', or +`list'. Do not confuse this with the diff \"type\", as returned by +`magit-diff-type'. + +If optional SECTION is non-nil, then return the scope of that, +ignoring the sections selected by the region. Otherwise return +the scope of the current section, or if the region is active and +selects a valid group of diff related sections, the type of these +sections, i.e., `hunks' or `files'. If SECTION, or if that is nil +the current section, is a `hunk' section; and the region region +starts and ends inside the body of a that section, then the type +is `region'. If the region is empty after a mouse click, then +`hunk' is returned instead of `region'. + +If optional STRICT is non-nil, then return nil if the diff type of +the section at point is `untracked' or the section at point is not +actually a `diff' but a `diffstat' section." + (let ((siblings (and (not ssection) (magit-region-sections nil t)))) + (setq section (or section (car siblings) (magit-current-section))) + (when (and section + (or (not strict) + (and (not (eq (magit-diff-type section) 'untracked)) + (not (eq (and-let* ((parent (oref section parent))) + (oref parent type)) + 'diffstat))))) + (pcase (list (oref section type) + (and siblings t) + (magit-diff-use-hunk-region-p) + ssection) + (`(hunk nil t ,_) + (if (magit-section-internal-region-p section) 'region 'hunk)) + ('(hunk t t nil) 'hunks) + (`(hunk ,_ ,_ ,_) 'hunk) + ('(file t t nil) 'files) + (`(file ,_ ,_ ,_) 'file) + ('(module t t nil) 'files) + (`(module ,_ ,_ ,_) 'file) + (`(,(or 'staged 'unstaged 'untracked) nil ,_ ,_) 'list))))) + +(defun magit-diff-use-hunk-region-p () + (and (region-active-p) + ;; TODO implement this from first principals + ;; currently it's trial-and-error + (not (and (or (eq this-command #'mouse-drag-region) + (eq last-command #'mouse-drag-region) + ;; When another window was previously + ;; selected then the last-command is + ;; some byte-code function. + (byte-code-function-p last-command)) + (eq (region-end) (region-beginning)))))) + +;;; Diff Highlight + +(add-hook 'magit-section-unhighlight-hook #'magit-diff-unhighlight) +(add-hook 'magit-section-highlight-hook #'magit-diff-highlight) + +(defun magit-diff-unhighlight (section selection) + "Remove the highlighting of the diff-related SECTION." + (when (magit-hunk-section-p section) + (magit-diff-paint-hunk section selection nil) + t)) + +(defun magit-diff-highlight (section selection) + "Highlight the diff-related SECTION. +If SECTION is not a diff-related section, then do nothing and +return nil. If SELECTION is non-nil, then it is a list of sections +selected by the region, including SECTION. All of these sections +are highlighted." + (if (and (magit-section-match 'commit section) + (oref section children)) + (progn (if selection + (dolist (section selection) + (magit-diff-highlight-list section selection)) + (magit-diff-highlight-list section)) + t) + (when-let ((scope (magit-diff-scope section t))) + (cond ((eq scope 'region) + (magit-diff-paint-hunk section selection t)) + (selection + (dolist (section selection) + (magit-diff-highlight-recursive section selection))) + (t + (magit-diff-highlight-recursive section))) + t))) + +(defun magit-diff-highlight-recursive (section &optional selection) + (pcase (magit-diff-scope section) + ('list (magit-diff-highlight-list section selection)) + ('file (magit-diff-highlight-file section selection)) + ('hunk (magit-diff-highlight-heading section selection) + (magit-diff-paint-hunk section selection t)) + (_ (magit-section-highlight section nil)))) + +(defun magit-diff-highlight-list (section &optional selection) + (let ((beg (oref section start)) + (cnt (oref section content)) + (end (oref section end))) + (when (or (eq this-command #'mouse-drag-region) + (not selection)) + (unless (and (region-active-p) + (<= (region-beginning) beg)) + (magit-section-make-overlay beg cnt 'magit-section-highlight)) + (if (oref section hidden) + (oset section washer #'ignore) + (dolist (child (oref section children)) + (when (or (eq this-command #'mouse-drag-region) + (not (and (region-active-p) + (<= (region-beginning) + (oref child start))))) + (magit-diff-highlight-recursive child selection))))) + (when magit-diff-highlight-hunk-body + (magit-section-make-overlay (1- end) end 'magit-section-highlight)))) + +(defun magit-diff-highlight-file (section &optional selection) + (magit-diff-highlight-heading section selection) + (when (or (not (oref section hidden)) + (cl-typep section 'magit-module-section)) + (dolist (child (oref section children)) + (magit-diff-highlight-recursive child selection)))) + +(defun magit-diff-highlight-heading (section &optional selection) + (magit-section-make-overlay + (oref section start) + (or (oref section content) + (oref section end)) + (pcase (list (oref section type) + (and (member section selection) + (not (eq this-command #'mouse-drag-region)))) + ('(file t) 'magit-diff-file-heading-selection) + ('(file nil) 'magit-diff-file-heading-highlight) + ('(module t) 'magit-diff-file-heading-selection) + ('(module nil) 'magit-diff-file-heading-highlight) + ('(hunk t) 'magit-diff-hunk-heading-selection) + ('(hunk nil) 'magit-diff-hunk-heading-highlight)))) + +;;; Hunk Paint + +(cl-defun magit-diff-paint-hunk + (section &optional selection + (highlight (magit-section-selected-p section selection))) + (let (paint) + (unless magit-diff-highlight-hunk-body + (setq highlight nil)) + (cond (highlight + (unless (oref section hidden) + (add-to-list 'magit-section-highlighted-sections section) + (cond ((memq section magit-section-unhighlight-sections) + (setq magit-section-unhighlight-sections + (delq section magit-section-unhighlight-sections))) + (magit-diff-highlight-hunk-body + (setq paint t))))) + (t + (cond ((and (oref section hidden) + (memq section magit-section-unhighlight-sections)) + (add-to-list 'magit-section-highlighted-sections section) + (setq magit-section-unhighlight-sections + (delq section magit-section-unhighlight-sections))) + (t + (setq paint t))))) + (when paint + (save-excursion + (goto-char (oref section start)) + (let ((end (oref section end)) + (merging (looking-at "@@@")) + (diff-type (magit-diff-type)) + (stage nil) + (tab-width (magit-diff-tab-width + (magit-section-parent-value section)))) + (forward-line) + (while (< (point) end) + (when (and magit-diff-hide-trailing-cr-characters + (char-equal ?\r (char-before (line-end-position)))) + (put-text-property (1- (line-end-position)) (line-end-position) + 'invisible t)) + (put-text-property + (point) (1+ (line-end-position)) 'font-lock-face + (cond + ((looking-at "^\\+\\+?\\([<=|>]\\)\\{7\\}") + (setq stage (pcase (list (match-string 1) highlight) + ('("<" nil) 'magit-diff-our) + ('("<" t) 'magit-diff-our-highlight) + ('("|" nil) 'magit-diff-base) + ('("|" t) 'magit-diff-base-highlight) + ('("=" nil) 'magit-diff-their) + ('("=" t) 'magit-diff-their-highlight) + ('(">" nil) nil))) + 'magit-diff-conflict-heading) + ((looking-at (if merging "^\\(\\+\\| \\+\\)" "^\\+")) + (magit-diff-paint-tab merging tab-width) + (magit-diff-paint-whitespace merging 'added diff-type) + (or stage + (if highlight 'magit-diff-added-highlight 'magit-diff-added))) + ((looking-at (if merging "^\\(-\\| -\\)" "^-")) + (magit-diff-paint-tab merging tab-width) + (magit-diff-paint-whitespace merging 'removed diff-type) + (if highlight 'magit-diff-removed-highlight 'magit-diff-removed)) + (t + (magit-diff-paint-tab merging tab-width) + (magit-diff-paint-whitespace merging 'context diff-type) + (if highlight 'magit-diff-context-highlight 'magit-diff-context)))) + (forward-line)))))) + (magit-diff-update-hunk-refinement section)) + +(defvar magit-diff--tab-width-cache nil) + +(defun magit-diff-tab-width (file) + (setq file (expand-file-name file)) + (cl-flet ((cache (value) + (let ((elt (assoc file magit-diff--tab-width-cache))) + (if elt + (setcdr elt value) + (setq magit-diff--tab-width-cache + (cons (cons file value) + magit-diff--tab-width-cache)))) + value)) + (cond + ((not magit-diff-adjust-tab-width) + tab-width) + ((and-let* ((buffer (find-buffer-visiting file))) + (cache (buffer-local-value 'tab-width buffer)))) + ((and-let* ((elt (assoc file magit-diff--tab-width-cache))) + (or (cdr elt) + tab-width))) + ((or (eq magit-diff-adjust-tab-width 'always) + (and (numberp magit-diff-adjust-tab-width) + (>= magit-diff-adjust-tab-width + (nth 7 (file-attributes file))))) + (cache (buffer-local-value 'tab-width (find-file-noselect file)))) + (t + (cache nil) + tab-width)))) + +(defun magit-diff-paint-tab (merging width) + (save-excursion + (forward-char (if merging 2 1)) + (while (= (char-after) ?\t) + (put-text-property (point) (1+ (point)) + 'display (list (list 'space :width width))) + (forward-char)))) + +(defun magit-diff-paint-whitespace (merging line-type diff-type) + (when (and magit-diff-paint-whitespace + (or (not (memq magit-diff-paint-whitespace '(uncommitted status))) + (memq diff-type '(staged unstaged))) + (cl-case line-type + (added t) + (removed (memq magit-diff-paint-whitespace-lines '(all both))) + (context (memq magit-diff-paint-whitespace-lines '(all))))) + (let ((prefix (if merging "^[-\\+\s]\\{2\\}" "^[-\\+\s]")) + (indent + (if (local-variable-p 'magit-diff-highlight-indentation) + magit-diff-highlight-indentation + (setq-local + magit-diff-highlight-indentation + (cdr (--first (string-match-p (car it) default-directory) + (nreverse + (default-value + 'magit-diff-highlight-indentation)))))))) + (when (and magit-diff-highlight-trailing + (looking-at (concat prefix ".*?\\([ \t]+\\)?$"))) + (let ((ov (make-overlay (match-beginning 1) (match-end 1) nil t))) + (overlay-put ov 'font-lock-face 'magit-diff-whitespace-warning) + (overlay-put ov 'priority 2) + (overlay-put ov 'evaporate t))) + (when (or (and (eq indent 'tabs) + (looking-at (concat prefix "\\( *\t[ \t]*\\)"))) + (and (integerp indent) + (looking-at (format "%s\\([ \t]* \\{%s,\\}[ \t]*\\)" + prefix indent)))) + (let ((ov (make-overlay (match-beginning 1) (match-end 1) nil t))) + (overlay-put ov 'font-lock-face 'magit-diff-whitespace-warning) + (overlay-put ov 'priority 2) + (overlay-put ov 'evaporate t)))))) + +(defun magit-diff-update-hunk-refinement (&optional section) + (if section + (unless (oref section hidden) + (pcase (list magit-diff-refine-hunk + (oref section refined) + (eq section (magit-current-section))) + ((or `(all nil ,_) '(t nil t)) + (oset section refined t) + (save-excursion + (goto-char (oref section start)) + ;; `diff-refine-hunk' does not handle combined diffs. + (unless (looking-at "@@@") + (let ((smerge-refine-ignore-whitespace + magit-diff-refine-ignore-whitespace) + ;; Avoid fsyncing many small temp files + (write-region-inhibit-fsync t)) + (diff-refine-hunk))))) + ((or `(nil t ,_) '(t t nil)) + (oset section refined nil) + (remove-overlays (oref section start) + (oref section end) + 'diff-mode 'fine)))) + (cl-labels ((recurse (section) + (if (magit-section-match 'hunk section) + (magit-diff-update-hunk-refinement section) + (dolist (child (oref section children)) + (recurse child))))) + (recurse magit-root-section)))) + + +;;; Hunk Region + +(defun magit-diff-hunk-region-beginning () + (save-excursion (goto-char (region-beginning)) + (line-beginning-position))) + +(defun magit-diff-hunk-region-end () + (save-excursion (goto-char (region-end)) + (line-end-position))) + +(defun magit-diff-update-hunk-region (section) + "Highlight the hunk-internal region if any." + (when (and (eq (oref section type) 'hunk) + (eq (magit-diff-scope section t) 'region)) + (magit-diff--make-hunk-overlay + (oref section start) + (1- (oref section content)) + 'font-lock-face 'magit-diff-lines-heading + 'display (magit-diff-hunk-region-header section) + 'after-string (magit-diff--hunk-after-string 'magit-diff-lines-heading)) + (run-hook-with-args 'magit-diff-highlight-hunk-region-functions section) + t)) + +(defun magit-diff-highlight-hunk-region-dim-outside (section) + "Dim the parts of the hunk that are outside the hunk-internal region. +This is done by using the same foreground and background color +for added and removed lines as for context lines." + (let ((face (if magit-diff-highlight-hunk-body + 'magit-diff-context-highlight + 'magit-diff-context))) + (when magit-diff-unmarked-lines-keep-foreground + (setq face `(,@(and (>= emacs-major-version 27) '(:extend t)) + :background ,(face-attribute face :background)))) + (magit-diff--make-hunk-overlay (oref section content) + (magit-diff-hunk-region-beginning) + 'font-lock-face face + 'priority 2) + (magit-diff--make-hunk-overlay (1+ (magit-diff-hunk-region-end)) + (oref section end) + 'font-lock-face face + 'priority 2))) + +(defun magit-diff-highlight-hunk-region-using-face (_section) + "Highlight the hunk-internal region by making it bold. +Or rather highlight using the face `magit-diff-hunk-region', though +changing only the `:weight' and/or `:slant' is recommended for that +face." + (magit-diff--make-hunk-overlay (magit-diff-hunk-region-beginning) + (1+ (magit-diff-hunk-region-end)) + 'font-lock-face 'magit-diff-hunk-region)) + +(defun magit-diff-highlight-hunk-region-using-overlays (section) + "Emphasize the hunk-internal region using delimiting horizontal lines. +This is implemented as single-pixel newlines places inside overlays." + (if (window-system) + (let ((beg (magit-diff-hunk-region-beginning)) + (end (magit-diff-hunk-region-end)) + (str (propertize + (concat (propertize "\s" 'display '(space :height (1))) + (propertize "\n" 'line-height t)) + 'font-lock-face 'magit-diff-lines-boundary))) + (magit-diff--make-hunk-overlay beg (1+ beg) 'before-string str) + (magit-diff--make-hunk-overlay end (1+ end) 'after-string str)) + (magit-diff-highlight-hunk-region-using-face section))) + +(defun magit-diff-highlight-hunk-region-using-underline (section) + "Emphasize the hunk-internal region using delimiting horizontal lines. +This is implemented by overlining and underlining the first and +last (visual) lines of the region." + (if (window-system) + (let* ((beg (magit-diff-hunk-region-beginning)) + (end (magit-diff-hunk-region-end)) + (beg-eol (save-excursion (goto-char beg) + (end-of-visual-line) + (point))) + (end-bol (save-excursion (goto-char end) + (beginning-of-visual-line) + (point))) + (color (face-background 'magit-diff-lines-boundary nil t))) + (cl-flet ((ln (b e &rest face) + (magit-diff--make-hunk-overlay + b e 'font-lock-face face 'after-string + (magit-diff--hunk-after-string face)))) + (if (= beg end-bol) + (ln beg beg-eol :overline color :underline color) + (ln beg beg-eol :overline color) + (ln end-bol end :underline color)))) + (magit-diff-highlight-hunk-region-using-face section))) + +(defun magit-diff--make-hunk-overlay (start end &rest args) + (let ((ov (make-overlay start end nil t))) + (overlay-put ov 'evaporate t) + (while args (overlay-put ov (pop args) (pop args))) + (push ov magit-section--region-overlays) + ov)) + +(defun magit-diff--hunk-after-string (face) + (propertize "\s" + 'font-lock-face face + 'display (list 'space :align-to + `(+ (0 . right) + ,(min (window-hscroll) + (- (line-end-position) + (line-beginning-position))))) + ;; This prevents the cursor from being rendered at the + ;; edge of the window. + 'cursor t)) + +;;; Utilities + +(defun magit-diff-inside-hunk-body-p () + "Return non-nil if point is inside the body of a hunk." + (and (magit-section-match 'hunk) + (and-let* ((content (oref (magit-current-section) content))) + (> (magit-point) content)))) + +(defun magit-diff--combined-p (section) + (cl-assert (cl-typep section 'magit-file-section)) + (string-match-p "\\`diff --\\(combined\\|cc\\)" (oref section value))) + +;;; Diff Extract + +(defun magit-diff-file-header (section &optional no-rename) + (when (magit-hunk-section-p section) + (setq section (oref section parent))) + (and (magit-file-section-p section) + (let ((header (oref section header))) + (if no-rename + (replace-regexp-in-string + "^--- \\(.+\\)" (oref section value) header t t 1) + header)))) + +(defun magit-diff-hunk-region-header (section) + (let ((patch (magit-diff-hunk-region-patch section))) + (string-match "\n" patch) + (substring patch 0 (1- (match-end 0))))) + +(defun magit-diff-hunk-region-patch (section &optional args) + (let ((op (if (member "--reverse" args) "+" "-")) + (sbeg (oref section start)) + (rbeg (magit-diff-hunk-region-beginning)) + (rend (region-end)) + (send (oref section end)) + (patch nil)) + (save-excursion + (goto-char sbeg) + (while (< (point) send) + (looking-at "\\(.\\)\\([^\n]*\n\\)") + (cond ((or (string-match-p "[@ ]" (match-string-no-properties 1)) + (and (>= (point) rbeg) + (<= (point) rend))) + (push (match-string-no-properties 0) patch)) + ((equal op (match-string-no-properties 1)) + (push (concat " " (match-string-no-properties 2)) patch))) + (forward-line))) + (let ((buffer-list-update-hook nil)) ; #3759 + (with-temp-buffer + (insert (string-join (reverse patch))) + (diff-fixup-modifs (point-min) (point-max)) + (setq patch (buffer-string)))) + patch)) + +;;; _ +(provide 'magit-diff) +;;; magit-diff.el ends here diff --git a/emacs/elpa/magit-20241004.917/magit-ediff.el b/emacs/elpa/magit-20241004.917/magit-ediff.el @@ -0,0 +1,606 @@ +;;; magit-ediff.el --- Ediff extension for Magit -*- lexical-binding:t -*- + +;; Copyright (C) 2008-2024 The Magit Project Contributors + +;; Author: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> +;; Maintainer: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> + +;; SPDX-License-Identifier: GPL-3.0-or-later + +;; Magit is free software: you can redistribute it and/or modify it +;; under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. +;; +;; Magit is distributed in the hope that it will be useful, but WITHOUT +;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +;; or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public +;; License for more details. +;; +;; You should have received a copy of the GNU General Public License +;; along with Magit. If not, see <https://www.gnu.org/licenses/>. + +;;; Commentary: + +;; This library provides basic support for Ediff. + +;;; Code: + +(require 'magit) + +(require 'ediff) +(require 'smerge-mode) + +(defvar smerge-ediff-buf) +(defvar smerge-ediff-windows) + +;;; Options + +(defgroup magit-ediff nil + "Ediff support for Magit." + :link '(info-link "(magit)Ediffing") + :group 'magit-extensions) + +(defcustom magit-ediff-quit-hook + '(magit-ediff-cleanup-auxiliary-buffers + magit-ediff-restore-previous-winconf) + "Hooks to run after finishing Ediff, when that was invoked using Magit. +The hooks are run in the Ediff control buffer. This is similar +to `ediff-quit-hook' but takes the needs of Magit into account. +The `ediff-quit-hook' is ignored by Ediff sessions which were +invoked using Magit." + :package-version '(magit . "2.2.0") + :group 'magit-ediff + :type 'hook + :get #'magit-hook-custom-get + :options '(magit-ediff-cleanup-auxiliary-buffers + magit-ediff-restore-previous-winconf)) + +(defcustom magit-ediff-dwim-resolve-function #'magit-ediff-resolve-rest + "The function `magit-ediff-dwim' uses to resolve conflicts." + :package-version '(magit . "4.0.0") + :group 'magit-ediff + :type '(choice (const magit-ediff-resolve-rest) + (const magit-ediff-resolve-all) + (const magit-git-mergetool))) + +(defcustom magit-ediff-dwim-show-on-hunks nil + "Whether `magit-ediff-dwim' runs show variants on hunks. +If non-nil, `magit-ediff-show-staged' or +`magit-ediff-show-unstaged' are called based on what section the +hunk is in. Otherwise, `magit-ediff-dwim' runs +`magit-ediff-stage' when point is on an uncommitted hunk." + :package-version '(magit . "2.2.0") + :group 'magit-ediff + :type 'boolean) + +(defcustom magit-ediff-show-stash-with-index t + "Whether `magit-ediff-show-stash' shows the state of the index. + +If non-nil, use a third Ediff buffer to distinguish which changes +in the stash were staged. In cases where the stash contains no +staged changes, fall back to a two-buffer Ediff. + +More specifically, a stash is a merge commit, stash@{N}, with +potentially three parents. + +* stash@{N}^1 represents the `HEAD' commit at the time the stash + was created. + +* stash@{N}^2 records any changes that were staged when the stash + was made. + +* stash@{N}^3, if it exists, contains files that were untracked + when stashing. + +If this option is non-nil, `magit-ediff-show-stash' will run +Ediff on a file using three buffers: one for stash@{N}, another +for stash@{N}^1, and a third for stash@{N}^2. + +Otherwise, Ediff uses two buffers, comparing +stash@{N}^1..stash@{N}. Along with any unstaged changes, changes +in the index commit, stash@{N}^2, will be shown in this +comparison unless they conflicted with changes in the working +tree at the time of stashing." + :package-version '(magit . "2.6.0") + :group 'magit-ediff + :type 'boolean) + +(defvar magit-ediff-use-indirect-buffers nil + "Whether to use indirect buffers. +Ediff already does a lot of buffer and file shuffling and I +recommend you do not further complicate that by enabling this.") + +;;; Commands + +(defvar magit-ediff-previous-winconf nil) + +;;;###autoload (autoload 'magit-ediff "magit-ediff" nil) +(transient-define-prefix magit-ediff () + "Show differences using the Ediff package." + :info-manual "(ediff)" + ["Ediff" + [("E" "Dwim" magit-ediff-dwim) + ("s" "Stage" magit-ediff-stage)] + [("m" "Resolve rest" magit-ediff-resolve-rest) + ("M" "Resolve all conflicts" magit-ediff-resolve-all) + ("t" "Resolve using mergetool" magit-git-mergetool)] + [("u" "Show unstaged" magit-ediff-show-unstaged) + ("i" "Show staged" magit-ediff-show-staged) + ("w" "Show worktree" magit-ediff-show-working-tree)] + [("c" "Show commit" magit-ediff-show-commit) + ("r" "Show range" magit-ediff-compare) + ("z" "Show stash" magit-ediff-show-stash)]]) + +(defmacro magit-ediff-buffers (a b &optional c setup quit file) + "Run Ediff on two or three buffers. +This is a wrapper around `ediff-buffers-internal'. + +A, B and C have the form (GET-BUFFER CREATE-BUFFER). If +GET-BUFFER returns a non-nil value, then that buffer is used and +it is not killed when exiting Ediff. Otherwise CREATE-BUFFER +must return a buffer and that is killed when exiting Ediff. + +If non-nil, SETUP must be a function. It is called without +arguments after Ediff is done setting up buffers. + +If non-nil, QUIT must be a function. It is added to +`ediff-quit-hook' and is called without arguments. + +If FILE is non-nil, then perform a merge. The merge result +is put in FILE." + (let (get make kill (char ?A)) + (dolist (spec (list a b c)) + (if (not spec) + (push nil make) + (pcase-let ((`(,g ,m) spec)) + (let ((b (intern (format "buf%c" char)))) + (push `(,b ,g) get) + ;; This is an unfortunate complication that I have added for + ;; the benefit of one user. Pretend we used this instead: + ;; (push `(or ,b ,m) make) + (push `(if ,b + (if magit-ediff-use-indirect-buffers + (prog1 (make-indirect-buffer + ,b + (generate-new-buffer-name (buffer-name ,b)) + t) + (setq ,b nil)) + ,b) + ,m) + make) + (push `(unless ,b + ;; For merge jobs Ediff switches buffer names around. + ;; See (if ediff-merge-job ...) in `ediff-setup'. + (let ((var ,(if (and file (= char ?C)) + 'ediff-ancestor-buffer + (intern (format "ediff-buffer-%c" char))))) + (ediff-kill-buffer-carefully var))) + kill)) + (cl-incf char)))) + (setq get (nreverse get)) + (setq make (nreverse make)) + (setq kill (nreverse kill)) + (let ((mconf (cl-gensym "conf")) + (mfile (cl-gensym "file"))) + `(magit-with-toplevel + (let ((,mconf (current-window-configuration)) + (,mfile ,file) + ,@get) + (ediff-buffers-internal + ,@make + (list ,@(and setup (list setup)) + (lambda () + ;; We do not want to kill buffers that existed before + ;; Ediff was invoked, so we cannot use Ediff's default + ;; quit functions. Ediff splits quitting across two + ;; hooks for merge jobs but we only ever use one. + (setq-local ediff-quit-merge-hook nil) + (setq-local ediff-quit-hook + (list + ,@(and quit (list quit)) + (lambda () + ,@kill + (let ((magit-ediff-previous-winconf ,mconf)) + (run-hooks 'magit-ediff-quit-hook))))))) + (pcase (list ,(and c t) (and ,mfile t)) + ('(nil nil) 'ediff-buffers) + ('(nil t) 'ediff-merge-buffers) + ('(t nil) 'ediff-buffers3) + ('(t t) 'ediff-merge-buffers-with-ancestor)) + ,mfile)))))) + +;;;###autoload +(defun magit-ediff-resolve-all (file) + "Resolve all conflicts in the FILE at point using Ediff. + +If there is no file at point or if it doesn't have any unmerged +changes, then prompt for a file. + +See info node `(magit) Ediffing' for more information about this +and alternative commands." + (interactive (list (magit-read-unmerged-file))) + (magit-with-toplevel + (let* ((dir (magit-gitdir)) + (revA (or (magit-name-branch "HEAD") + (magit-commit-p "HEAD"))) + (revB (cl-find-if (lambda (head) + (file-exists-p (expand-file-name head dir))) + '("MERGE_HEAD" "CHERRY_PICK_HEAD" "REVERT_HEAD"))) + (revB (or (magit-name-branch revB) + (magit-commit-p revB))) + (revC (magit-commit-p (magit-git-string "merge-base" revA revB))) + (fileA (magit--rev-file-name file revA revB)) + (fileB (magit--rev-file-name file revB revA)) + (fileC (or (magit--rev-file-name file revC revA) + (magit--rev-file-name file revC revB)))) + ;; Ediff assumes that the FILE where it is going to store the merge + ;; result does not exist yet, so move the existing file out of the + ;; way. If a buffer visits FILE, then we have to kill that upfront. + (when-let ((buffer (find-buffer-visiting file))) + (when (and (buffer-modified-p buffer) + (not (y-or-n-p (format "Save buffer %s %s? " + (buffer-name buffer) + "(cannot continue otherwise)")))) + (user-error "Abort")) + (kill-buffer buffer)) + (let ((orig (concat file ".ORIG"))) + (when (file-exists-p orig) + (rename-file orig (make-temp-name (concat orig "_")))) + (rename-file file orig)) + (let ((setup (lambda () + ;; Use the same conflict marker style as Git uses. + (setq-local ediff-combination-pattern + '("<<<<<<< HEAD" A + ,(format "||||||| %s" revC) Ancestor + "=======" B + ,(format ">>>>>>> %s" revB))))) + (quit (lambda () + ;; For merge jobs Ediff switches buffer names around. + ;; At this point `ediff-buffer-C' no longer refer to + ;; the ancestor buffer but to the merge result buffer. + ;; See (if ediff-merge-job ...) in `ediff-setup'. + (when (buffer-live-p ediff-buffer-C) + (with-current-buffer ediff-buffer-C + (save-buffer) + (save-excursion + (goto-char (point-min)) + (unless (re-search-forward "^<<<<<<< " nil t) + (magit-stage-file file)))))))) + (if fileC + (magit-ediff-buffers + ((magit-get-revision-buffer revA fileA) + (magit-find-file-noselect revA fileA)) + ((magit-get-revision-buffer revB fileB) + (magit-find-file-noselect revB fileB)) + ((magit-get-revision-buffer revC fileC) + (magit-find-file-noselect revC fileC)) + setup quit file) + (magit-ediff-buffers + ((magit-get-revision-buffer revA fileA) + (magit-find-file-noselect revA fileA)) + ((magit-get-revision-buffer revB fileB) + (magit-find-file-noselect revB fileB)) + nil setup quit file)))))) + +;;;###autoload +(defun magit-ediff-resolve-rest (file) + "Resolve outstanding conflicts in the FILE at point using Ediff. + +If there is no file at point or if it doesn't have any unmerged +changes, then prompt for a file. + +See info node `(magit) Ediffing' for more information about this +and alternative commands." + (interactive (list (magit-read-unmerged-file))) + (magit-with-toplevel + (with-current-buffer (find-file-noselect file) + (smerge-ediff) + (setq-local + ediff-quit-hook + (lambda () + (let ((bufC ediff-buffer-C) + (bufS smerge-ediff-buf)) + (with-current-buffer bufS + (when (yes-or-no-p (format "Conflict resolution finished; save %s? " + buffer-file-name)) + (erase-buffer) + (insert-buffer-substring bufC) + (save-buffer)))) + (when (buffer-live-p ediff-buffer-A) (kill-buffer ediff-buffer-A)) + (when (buffer-live-p ediff-buffer-B) (kill-buffer ediff-buffer-B)) + (when (buffer-live-p ediff-buffer-C) (kill-buffer ediff-buffer-C)) + (when (buffer-live-p ediff-ancestor-buffer) + (kill-buffer ediff-ancestor-buffer)) + (let ((magit-ediff-previous-winconf smerge-ediff-windows)) + (run-hooks 'magit-ediff-quit-hook))))))) + +;;;###autoload +(defun magit-ediff-stage (file) + "Stage and unstage changes to FILE using Ediff. +FILE has to be relative to the top directory of the repository." + (interactive + (let ((files (magit-tracked-files))) + (list (magit-completing-read "Selectively stage file" files nil t nil nil + (car (member (magit-current-file) files)))))) + (magit-with-toplevel + (let* ((bufA (magit-get-revision-buffer "HEAD" file)) + (bufB (magit-get-revision-buffer "{index}" file)) + (lockB (and bufB (buffer-local-value 'buffer-read-only bufB))) + (bufC (get-file-buffer file)) + ;; Use the same encoding for all three buffers or we + ;; may end up changing the file in an unintended way. + (bufC* (or bufC (find-file-noselect file))) + (coding-system-for-read + (buffer-local-value 'buffer-file-coding-system bufC*)) + (bufA* (magit-find-file-noselect-1 "HEAD" file t)) + (bufB* (magit-find-file-index-noselect file t))) + (with-current-buffer bufB* (setq buffer-read-only nil)) + (magit-ediff-buffers + (bufA bufA*) + (bufB bufB*) + (bufC bufC*) + nil + (lambda () + (when (buffer-live-p ediff-buffer-B) + (when lockB + (with-current-buffer bufB (setq buffer-read-only t))) + (when (buffer-modified-p ediff-buffer-B) + (with-current-buffer ediff-buffer-B + (magit-update-index)))) + (when (and (buffer-live-p ediff-buffer-C) + (buffer-modified-p ediff-buffer-C)) + (with-current-buffer ediff-buffer-C + (when (y-or-n-p (format "Save file %s? " buffer-file-name)) + (save-buffer))))))))) + +;;;###autoload +(defun magit-ediff-compare (revA revB fileA fileB) + "Compare REVA:FILEA with REVB:FILEB using Ediff. + +FILEA and FILEB have to be relative to the top directory of the +repository. If REVA or REVB is nil, then this stands for the +working tree state. + +If the region is active, use the revisions on the first and last +line of the region. With a prefix argument, instead of diffing +the revisions, choose a revision to view changes along, starting +at the common ancestor of both revisions (i.e., use a \"...\" +range)." + (interactive + (pcase-let ((`(,revA ,revB) (magit-ediff-compare--read-revisions + nil current-prefix-arg))) + (nconc (list revA revB) + (magit-ediff-read-files revA revB)))) + (magit-ediff-buffers + ((if revA (magit-get-revision-buffer revA fileA) (get-file-buffer fileA)) + (if revA (magit-find-file-noselect revA fileA) (find-file-noselect fileA))) + ((if revB (magit-get-revision-buffer revB fileB) (get-file-buffer fileB)) + (if revB (magit-find-file-noselect revB fileB) (find-file-noselect fileB))))) + +(defun magit-ediff-compare--read-revisions (&optional arg mbase) + (let ((input (or arg (magit-diff-read-range-or-commit + "Compare range or commit" + nil mbase)))) + (if-let ((range (magit-split-range input))) + (list (car range) (cdr range)) + (list input nil)))) + +(defun magit-ediff-read-files (revA revB &optional fileB) + "Read file in REVB, return it and the corresponding file in REVA. +When FILEB is non-nil, use this as REVB's file instead of +prompting for it." + (unless (and fileB (member fileB (magit-revision-files revB))) + (setq fileB + (or (and fileB + magit-buffer-log-files + (derived-mode-p 'magit-log-mode) + (member "--follow" magit-buffer-log-args) + (cdr (assoc fileB + (magit-renamed-files + revB + (oref (car (oref magit-root-section children)) + value))))) + (magit-read-file-choice + (format "File to compare between %s and %s" + revA (or revB "the working tree")) + (magit-changed-files revA revB) + (format "No changed files between %s and %s" + revA (or revB "the working tree")))))) + (list (or (car (member fileB (magit-revision-files revA))) + (cdr (assoc fileB (magit-renamed-files revB revA))) + (magit-read-file-choice + (format "File in %s to compare with %s in %s" + revA fileB (or revB "the working tree")) + (magit-changed-files revB revA) + (format "No files have changed between %s and %s" + revA revB))) + fileB)) + +;;;###autoload +(defun magit-ediff-dwim () + "Compare, stage, or resolve using Ediff. +This command tries to guess what file, and what commit or range +the user wants to compare, stage, or resolve using Ediff. It +might only be able to guess either the file, or range or commit, +in which case the user is asked about the other. It might not +always guess right, in which case the appropriate `magit-ediff-*' +command has to be used explicitly. If it cannot read the user's +mind at all, then it asks the user for a command to run." + (interactive) + (magit-section-case + (hunk (save-excursion + (goto-char (oref (oref it parent) start)) + (magit-ediff-dwim))) + (t + (let ((range (magit-diff--dwim)) + (file (magit-current-file)) + command revA revB) + (pcase range + ((and (guard (not magit-ediff-dwim-show-on-hunks)) + (or 'unstaged 'staged)) + (setq command (if (magit-anything-unmerged-p) + magit-ediff-dwim-resolve-function + #'magit-ediff-stage))) + ('unstaged (setq command #'magit-ediff-show-unstaged)) + ('staged (setq command #'magit-ediff-show-staged)) + (`(commit . ,value) + (setq command #'magit-ediff-show-commit) + (setq revB value)) + (`(stash . ,value) + (setq command #'magit-ediff-show-stash) + (setq revB value)) + ((pred stringp) + (pcase-let ((`(,a ,b) (magit-ediff-compare--read-revisions range))) + (setq command #'magit-ediff-compare) + (setq revA a) + (setq revB b))) + (_ + (when (derived-mode-p 'magit-diff-mode) + (pcase (magit-diff-type) + ('committed (pcase-let ((`(,a ,b) + (magit-ediff-compare--read-revisions + magit-buffer-range))) + (setq revA a) + (setq revB b))) + ((guard (not magit-ediff-dwim-show-on-hunks)) + (setq command #'magit-ediff-stage)) + ('unstaged (setq command #'magit-ediff-show-unstaged)) + ('staged (setq command #'magit-ediff-show-staged)) + ('undefined (setq command nil)) + (_ (setq command nil)))))) + (cond ((not command) + (call-interactively + (magit-read-char-case + "Failed to read your mind; do you want to " t + (?c "[c]ommit" #'magit-ediff-show-commit) + (?r "[r]ange" #'magit-ediff-compare) + (?s "[s]tage" #'magit-ediff-stage) + (?m "[m] resolve remaining conflicts" + #'magit-ediff-resolve-rest) + (?M "[M] resolve all conflicts" + #'magit-ediff-resolve-all)))) + ((eq command #'magit-ediff-compare) + (apply #'magit-ediff-compare revA revB + (magit-ediff-read-files revA revB file))) + ((eq command #'magit-ediff-show-commit) + (magit-ediff-show-commit revB)) + ((eq command #'magit-ediff-show-stash) + (magit-ediff-show-stash revB)) + (file + (funcall command file)) + (t + (call-interactively command))))))) + +;;;###autoload +(defun magit-ediff-show-staged (file) + "Show staged changes using Ediff. + +This only allows looking at the changes; to stage, unstage, +and discard changes using Ediff, use `magit-ediff-stage'. + +FILE must be relative to the top directory of the repository." + (interactive + (list (magit-read-file-choice "Show staged changes for file" + (magit-staged-files) + "No staged files"))) + (magit-ediff-buffers ((magit-get-revision-buffer "HEAD" file) + (magit-find-file-noselect "HEAD" file)) + ((get-buffer (concat file ".~{index}~")) + (magit-find-file-index-noselect file t)))) + +;;;###autoload +(defun magit-ediff-show-unstaged (file) + "Show unstaged changes using Ediff. + +This only allows looking at the changes; to stage, unstage, +and discard changes using Ediff, use `magit-ediff-stage'. + +FILE must be relative to the top directory of the repository." + (interactive + (list (magit-read-file-choice "Show unstaged changes for file" + (magit-unstaged-files) + "No unstaged files"))) + (magit-ediff-buffers ((get-buffer (concat file ".~{index}~")) + (magit-find-file-index-noselect file t)) + ((get-file-buffer file) + (find-file-noselect file)))) + +;;;###autoload +(defun magit-ediff-show-working-tree (file) + "Show changes between `HEAD' and working tree using Ediff. +FILE must be relative to the top directory of the repository." + (interactive + (list (magit-read-file-choice "Show changes in file" + (magit-changed-files "HEAD") + "No changed files"))) + (magit-ediff-buffers ((magit-get-revision-buffer "HEAD" file) + (magit-find-file-noselect "HEAD" file)) + ((get-file-buffer file) + (find-file-noselect file)))) + +;;;###autoload +(defun magit-ediff-show-commit (commit) + "Show changes introduced by COMMIT using Ediff." + (interactive (list (magit-read-branch-or-commit "Revision"))) + (let ((revA (concat commit "^")) + (revB commit)) + (apply #'magit-ediff-compare + revA revB + (magit-ediff-read-files revA revB (magit-current-file))))) + +;;;###autoload +(defun magit-ediff-show-stash (stash) + "Show changes introduced by STASH using Ediff. +`magit-ediff-show-stash-with-index' controls whether a +three-buffer Ediff is used in order to distinguish changes in the +stash that were staged." + (interactive (list (magit-read-stash "Stash"))) + (pcase-let* ((revA (concat stash "^1")) + (revB (concat stash "^2")) + (revC stash) + (`(,fileA ,fileC) (magit-ediff-read-files revA revC)) + (fileB fileC)) + (if (and magit-ediff-show-stash-with-index + (member fileA (magit-changed-files revB revA))) + (magit-ediff-buffers + ((magit-get-revision-buffer revA fileA) + (magit-find-file-noselect revA fileA)) + ((magit-get-revision-buffer revB fileB) + (magit-find-file-noselect revB fileB)) + ((magit-get-revision-buffer revC fileC) + (magit-find-file-noselect revC fileC))) + (magit-ediff-compare revA revC fileA fileC)))) + +(defun magit-ediff-cleanup-auxiliary-buffers () + (let* ((ctl-buf ediff-control-buffer) + (ctl-win (ediff-get-visible-buffer-window ctl-buf)) + (ctl-frm ediff-control-frame) + (main-frame (cond ((window-live-p ediff-window-A) + (window-frame ediff-window-A)) + ((window-live-p ediff-window-B) + (window-frame ediff-window-B))))) + (ediff-kill-buffer-carefully ediff-diff-buffer) + (ediff-kill-buffer-carefully ediff-custom-diff-buffer) + (ediff-kill-buffer-carefully ediff-fine-diff-buffer) + (ediff-kill-buffer-carefully ediff-tmp-buffer) + (ediff-kill-buffer-carefully ediff-error-buffer) + (ediff-kill-buffer-carefully ediff-msg-buffer) + (ediff-kill-buffer-carefully ediff-debug-buffer) + (when (boundp 'ediff-patch-diagnostics) + (ediff-kill-buffer-carefully ediff-patch-diagnostics)) + (cond ((and (display-graphic-p) + (frame-live-p ctl-frm)) + (delete-frame ctl-frm)) + ((window-live-p ctl-win) + (delete-window ctl-win))) + (ediff-kill-buffer-carefully ctl-buf) + (when (frame-live-p main-frame) + (select-frame main-frame)))) + +(defun magit-ediff-restore-previous-winconf () + (set-window-configuration magit-ediff-previous-winconf)) + +;;; _ +(provide 'magit-ediff) +;;; magit-ediff.el ends here diff --git a/emacs/elpa/magit-20241004.917/magit-extras.el b/emacs/elpa/magit-20241004.917/magit-extras.el @@ -0,0 +1,922 @@ +;;; magit-extras.el --- Additional functionality for Magit -*- lexical-binding:t -*- + +;; Copyright (C) 2008-2024 The Magit Project Contributors + +;; Author: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> +;; Maintainer: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> + +;; SPDX-License-Identifier: GPL-3.0-or-later + +;; Magit is free software: you can redistribute it and/or modify it +;; under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. +;; +;; Magit is distributed in the hope that it will be useful, but WITHOUT +;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +;; or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public +;; License for more details. +;; +;; You should have received a copy of the GNU General Public License +;; along with Magit. If not, see <https://www.gnu.org/licenses/>. + +;;; Commentary: + +;; Additional functionality for Magit. + +;;; Code: + +(require 'magit) + +;; For `magit-do-async-shell-command'. +(declare-function dired-read-shell-command "dired-aux" (prompt arg files)) +;; For `magit-project-status'. +(declare-function vc-git-command "vc-git" + (buffer okstatus file-or-list &rest flags)) + +(defvar ido-exit) +(defvar ido-fallback) +(defvar project-prefix-map) +(defvar project-switch-commands) + +(defgroup magit-extras nil + "Additional functionality for Magit." + :group 'magit-extensions) + +;;; Git Tools +;;;; Git-Mergetool + +;;;###autoload (autoload 'magit-git-mergetool "magit-extras" nil t) +(transient-define-prefix magit-git-mergetool (file args &optional transient) + "Resolve conflicts in FILE using \"git mergetool --gui\". +With a prefix argument allow changing ARGS using a transient +popup. See info node `(magit) Ediffing' for information about +alternative commands." + :man-page "git-mergetool" + ["Settings" + ("-t" magit-git-mergetool:--tool) + ("=t" magit-merge.guitool) + ("=T" magit-merge.tool) + ("-r" magit-mergetool.hideResolved) + ("-b" magit-mergetool.keepBackup) + ("-k" magit-mergetool.keepTemporaries) + ("-w" magit-mergetool.writeToTemp)] + ["Actions" + (" m" "Invoke mergetool" magit-git-mergetool)] + (interactive + (if (and (not (eq transient-current-prefix 'magit-git-mergetool)) + current-prefix-arg) + (list nil nil t) + (list (magit-read-unmerged-file "Resolve") + (transient-args 'magit-git-mergetool)))) + (if transient + (transient-setup 'magit-git-mergetool) + (magit-run-git-async "mergetool" "--gui" args "--" file))) + +(transient-define-infix magit-git-mergetool:--tool () + :description "Override mergetool" + :class 'transient-option + :shortarg "-t" + :argument "--tool=" + :reader #'magit--read-mergetool) + +(transient-define-infix magit-merge.guitool () + :class 'magit--git-variable + :variable "merge.guitool" + :global t + :reader #'magit--read-mergetool) + +(transient-define-infix magit-merge.tool () + :class 'magit--git-variable + :variable "merge.tool" + :global t + :reader #'magit--read-mergetool) + +(defun magit--read-mergetool (prompt _initial-input history) + (let ((choices nil) + (lines (cdr (magit-git-lines "mergetool" "--tool-help")))) + (while (string-prefix-p "\t\t" (car lines)) + (push (substring (pop lines) 2) choices)) + (setq choices (nreverse choices)) + (magit-completing-read (or prompt "Select mergetool") + choices nil t nil history))) + +(transient-define-infix magit-mergetool.hideResolved () + :class 'magit--git-variable:boolean + :variable "mergetool.hideResolved" + :default "false" + :global t) + +(transient-define-infix magit-mergetool.keepBackup () + :class 'magit--git-variable:boolean + :variable "mergetool.keepBackup" + :default "true" + :global t) + +(transient-define-infix magit-mergetool.keepTemporaries () + :class 'magit--git-variable:boolean + :variable "mergetool.keepTemporaries" + :default "false" + :global t) + +(transient-define-infix magit-mergetool.writeToTemp () + :class 'magit--git-variable:boolean + :variable "mergetool.writeToTemp" + :default "false" + :global t) + +;;;; Git-Gui + +;;;###autoload +(defun magit-run-git-gui-blame (commit filename &optional linenum) + "Run `git gui blame' on the given FILENAME and COMMIT. +Interactively run it for the current file and the `HEAD', with a +prefix or when the current file cannot be determined let the user +choose. When the current buffer is visiting FILENAME instruct +blame to center around the line point is on." + (interactive + (let (revision filename) + (when (or current-prefix-arg + (progn + (setq revision "HEAD") + (not (setq filename (magit-file-relative-name nil 'tracked))))) + (setq revision (magit-read-branch-or-commit "Blame from revision")) + (setq filename (magit-read-file-from-rev revision "Blame file"))) + (list revision filename + (and (equal filename + (ignore-errors + (magit-file-relative-name buffer-file-name))) + (line-number-at-pos))))) + (magit-with-toplevel + (magit-process-git 0 "gui" "blame" + (and linenum (list (format "--line=%d" linenum))) + commit + filename))) + +;;;; Gitk + +(defcustom magit-gitk-executable + (or (and (eq system-type 'windows-nt) + (let ((exe (magit-git-string + "-c" "alias.X=!x() { which \"$1\" | cygpath -mf -; }; x" + "X" "gitk.exe"))) + (and exe (file-executable-p exe) exe))) + (executable-find "gitk") "gitk") + "The Gitk executable." + :group 'magit-extras + :set-after '(magit-git-executable) + :type 'string) + +;;;###autoload +(defun magit-run-git-gui () + "Run `git gui' for the current git repository." + (interactive) + (magit-with-toplevel (magit-process-git 0 "gui"))) + +;;;###autoload +(defun magit-run-gitk () + "Run `gitk' in the current repository." + (interactive) + (magit-process-file magit-gitk-executable nil 0)) + +;;;###autoload +(defun magit-run-gitk-branches () + "Run `gitk --branches' in the current repository." + (interactive) + (magit-process-file magit-gitk-executable nil 0 nil "--branches")) + +;;;###autoload +(defun magit-run-gitk-all () + "Run `gitk --all' in the current repository." + (interactive) + (magit-process-file magit-gitk-executable nil 0 nil "--all")) + +;;; Emacs Tools + +;;;###autoload +(defun ido-enter-magit-status () + "Drop into `magit-status' from file switching. + +To make this command available use something like: + + (keymap-set ido-common-completion-map + \"C-x g\" \\='ido-enter-magit-status) + +This command does not work in Emacs 26.1. +See https://github.com/magit/magit/issues/3634 +and https://debbugs.gnu.org/cgi/bugreport.cgi?bug=31707." + (interactive) + (setq ido-exit 'fallback) + (setq ido-fallback #'magit-status) + (exit-minibuffer)) + +;;;###autoload +(defun magit-project-status () + "Run `magit-status' in the current project's root." + (interactive) + (if (fboundp 'project-root) + (magit-status-setup-buffer (project-root (project-current t))) + (user-error "`magit-project-status' requires `project' 0.3.0 or greater"))) + +(defvar magit-bind-magit-project-status t + "Whether to bind \"m\" to `magit-project-status' in `project-prefix-map'. +If so, then an entry is added to `project-switch-commands' as +well. If you want to use another key, then you must set this +to nil before loading Magit to prevent \"m\" from being bound.") + +(with-eval-after-load 'project + (when (and magit-bind-magit-project-status + ;; Added in Emacs 28.1. + (boundp 'project-prefix-map) + (boundp 'project-switch-commands) + ;; Only modify if it hasn't already been modified. + (equal project-switch-commands + (eval (car (get 'project-switch-commands 'standard-value)) + t))) + (keymap-set project-prefix-map "m" #'magit-project-status) + (add-to-list 'project-switch-commands '(magit-project-status "Magit") t))) + +;;;###autoload +(defun magit-dired-jump (&optional other-window) + "Visit file at point using Dired. +With a prefix argument, visit in another window. If there +is no file at point, then instead visit `default-directory'." + (interactive "P") + (dired-jump other-window + (and-let* ((file (magit-file-at-point))) + (expand-file-name (if (file-directory-p file) + (file-name-as-directory file) + file))))) + +;;;###autoload +(defun magit-dired-log (&optional follow) + "Show log for all marked files, or the current file." + (interactive "P") + (if-let ((topdir (magit-toplevel default-directory))) + (let ((args (car (magit-log-arguments))) + (files (dired-get-marked-files nil nil #'magit-file-tracked-p))) + (unless files + (user-error "No marked file is being tracked by Git")) + (when (and follow + (not (member "--follow" args)) + (not (cdr files))) + (push "--follow" args)) + (magit-log-setup-buffer + (list (or (magit-get-current-branch) "HEAD")) + args + (let ((default-directory topdir)) + (mapcar #'file-relative-name files)) + magit-log-buffer-file-locked)) + (magit--not-inside-repository-error))) + +;;;###autoload +(defun magit-dired-am-apply-patches (repo &optional arg) + "In Dired, apply the marked (or next ARG) files as patches. +If inside a repository, then apply in that. Otherwise prompt +for a repository." + (interactive (list (or (magit-toplevel) + (magit-read-repository t)) + current-prefix-arg)) + ;; Note: The ERROR argument of `dired-get-marked-files' isn't + ;; available until Emacs 27. + (let ((files (or (dired-get-marked-files nil arg) + (user-error "No files specified")))) + (magit-status-setup-buffer repo) + (magit-am-apply-patches files))) + +;;;###autoload +(defun magit-do-async-shell-command (file) + "Open FILE with `dired-do-async-shell-command'. +Interactively, open the file at point." + (interactive (list (or (magit-file-at-point) + (magit-read-file "Act on file")))) + (require 'dired-aux) + (dired-do-async-shell-command + (dired-read-shell-command "& on %s: " current-prefix-arg (list file)) + nil (list file))) + +;;; Shift Selection + +(defun magit--turn-on-shift-select-mode-p () + (and shift-select-mode + this-command-keys-shift-translated + (not mark-active) + (not (eq (car-safe transient-mark-mode) 'only)))) + +;;;###autoload +(defun magit-previous-line (&optional arg try-vscroll) + "Like `previous-line' but with Magit-specific shift-selection. + +Magit's selection mechanism is based on the region but selects an +area that is larger than the region. This causes `previous-line' +when invoked while holding the shift key to move up one line and +thereby select two lines. When invoked inside a hunk body this +command does not move point on the first invocation and thereby +it only selects a single line. Which inconsistency you prefer +is a matter of preference." + (declare (interactive-only + "use `forward-line' with negative argument instead.")) + (interactive "p\np") + (unless arg (setq arg 1)) + (let ((stay (or (magit-diff-inside-hunk-body-p) + (magit-section-position-in-heading-p)))) + (if (and stay (= arg 1) (magit--turn-on-shift-select-mode-p)) + (push-mark nil nil t) + (with-no-warnings + (handle-shift-selection) + (previous-line (if stay (max (1- arg) 1) arg) try-vscroll))))) + +;;;###autoload +(defun magit-next-line (&optional arg try-vscroll) + "Like `next-line' but with Magit-specific shift-selection. + +Magit's selection mechanism is based on the region but selects +an area that is larger than the region. This causes `next-line' +when invoked while holding the shift key to move down one line +and thereby select two lines. When invoked inside a hunk body +this command does not move point on the first invocation and +thereby it only selects a single line. Which inconsistency you +prefer is a matter of preference." + (declare (interactive-only forward-line)) + (interactive "p\np") + (unless arg (setq arg 1)) + (let ((stay (or (magit-diff-inside-hunk-body-p) + (magit-section-position-in-heading-p)))) + (if (and stay (= arg 1) (magit--turn-on-shift-select-mode-p)) + (push-mark nil nil t) + (with-no-warnings + (handle-shift-selection) + (next-line (if stay (max (1- arg) 1) arg) try-vscroll))))) + +;;; Clean + +;;;###autoload +(defun magit-clean (&optional arg) + "Remove untracked files from the working tree. +With a prefix argument also remove ignored files, +with two prefix arguments remove ignored files only. +\n(git clean -f -d [-x|-X])" + (interactive "p") + (when (yes-or-no-p (format "Remove %s files? " + (pcase arg + (1 "untracked") + (4 "untracked and ignored") + (_ "ignored")))) + (magit-wip-commit-before-change) + (magit-run-git "clean" "-f" "-d" (pcase arg (4 "-x") (16 "-X"))))) + +(put 'magit-clean 'disabled t) + +;;; ChangeLog + +;;;###autoload +(defun magit-generate-changelog (&optional amending) + "Insert ChangeLog entries into the current buffer. + +The entries are generated from the diff being committed. +If prefix argument, AMENDING, is non-nil, include changes +in HEAD as well as staged changes in the diff to check." + (interactive "P") + (unless (magit-commit-message-buffer) + (user-error "No commit in progress")) + (require 'diff-mode) ; `diff-add-log-current-defuns'. + (require 'vc-git) ; `vc-git-diff'. + (require 'add-log) ; `change-log-insert-entries'. + (cond + ((and (fboundp 'change-log-insert-entries) + (fboundp 'diff-add-log-current-defuns)) + (setq default-directory + (if (and (file-regular-p "gitdir") + (not (magit-git-true "rev-parse" "--is-inside-work-tree")) + (magit-git-true "rev-parse" "--is-inside-git-dir")) + (file-name-directory (magit-file-line "gitdir")) + (magit-toplevel))) + (let ((rev1 (if amending "HEAD^1" "HEAD")) + (rev2 nil)) + ;; Magit may have updated the files without notifying vc, but + ;; `diff-add-log-current-defuns' relies on vc being up-to-date. + (mapc #'vc-file-clearprops (magit-staged-files)) + (change-log-insert-entries + (with-temp-buffer + (vc-git-command (current-buffer) 1 nil + "diff-index" "--exit-code" "--patch" + (and (magit-anything-staged-p) "--cached") + rev1 "--") + ;; `diff-find-source-location' consults these vars. + (defvar diff-vc-revisions) + (setq-local diff-vc-revisions (list rev1 rev2)) + (setq-local diff-vc-backend 'Git) + (diff-add-log-current-defuns))))) + ((user-error "`magit-generate-changelog' requires Emacs 27 or greater")))) + +;;;###autoload +(defun magit-add-change-log-entry (&optional whoami file-name other-window) + "Find change log file and add date entry and item for current change. +This differs from `add-change-log-entry' (which see) in that +it acts on the current hunk in a Magit buffer instead of on +a position in a file-visiting buffer." + (interactive (list current-prefix-arg + (prompt-for-change-log-name))) + (pcase-let ((`(,buf ,pos) (magit-diff-visit-file--noselect))) + (magit--with-temp-position buf pos + (let ((add-log-buffer-file-name-function + (lambda () + (or magit-buffer-file-name + (buffer-file-name))))) + (add-change-log-entry whoami file-name other-window))))) + +;;;###autoload +(defun magit-add-change-log-entry-other-window (&optional whoami file-name) + "Find change log file in other window and add entry and item. +This differs from `add-change-log-entry-other-window' (which see) +in that it acts on the current hunk in a Magit buffer instead of +on a position in a file-visiting buffer." + (interactive (and current-prefix-arg + (list current-prefix-arg + (prompt-for-change-log-name)))) + (magit-add-change-log-entry whoami file-name t)) + +;;; Edit Line Commit + +;;;###autoload +(defun magit-edit-line-commit (&optional type) + "Edit the commit that added the current line. + +With a prefix argument edit the commit that removes the line, +if any. The commit is determined using `git blame' and made +editable using `git rebase --interactive' if it is reachable +from `HEAD', or by checking out the commit (or a branch that +points at it) otherwise." + (interactive (list (and current-prefix-arg 'removal))) + (let* ((chunk (magit-current-blame-chunk (or type 'addition))) + (rev (oref chunk orig-rev))) + (if (string-match-p "\\`0\\{40,\\}\\'" rev) + (message "This line has not been committed yet") + (let ((rebase (magit-rev-ancestor-p rev "HEAD")) + (file (expand-file-name (oref chunk orig-file) + (magit-toplevel)))) + (if rebase + (let ((magit--rebase-published-symbol 'edit-published)) + (magit-rebase-edit-commit rev (magit-rebase-arguments))) + (magit--checkout (or (magit-rev-branch rev) rev))) + (unless (and buffer-file-name + (file-equal-p file buffer-file-name)) + (let ((blame-type (and magit-blame-mode magit-blame-type))) + (if rebase + (set-process-sentinel + magit-this-process + (lambda (process event) + (magit-sequencer-process-sentinel process event) + (when (eq (process-status process) 'exit) + (find-file file) + (when blame-type + (magit-blame--pre-blame-setup blame-type) + (magit-blame--run (magit-blame-arguments)))))) + (find-file file) + (when blame-type + (magit-blame--pre-blame-setup blame-type) + (magit-blame--run (magit-blame-arguments)))))))))) + +(put 'magit-edit-line-commit 'disabled t) + +;;;###autoload +(defun magit-diff-edit-hunk-commit (file) + "From a hunk, edit the respective commit and visit the file. + +First visit the file being modified by the hunk at the correct +location using `magit-diff-visit-file'. This actually visits a +blob. When point is on a diff header, not within an individual +hunk, then this visits the blob the first hunk is about. + +Then invoke `magit-edit-line-commit', which uses an interactive +rebase to make the commit editable, or if that is not possible +because the commit is not reachable from `HEAD' by checking out +that commit directly. This also causes the actual worktree file +to be visited. + +Neither the blob nor the file buffer are killed when finishing +the rebase. If that is undesirable, then it might be better to +use `magit-rebase-edit-commit' instead of this command." + (interactive (list (magit-file-at-point t t))) + (let ((magit-diff-visit-previous-blob nil)) + (with-current-buffer + (magit-diff-visit-file--internal file nil #'pop-to-buffer-same-window) + (magit-edit-line-commit)))) + +(put 'magit-diff-edit-hunk-commit 'disabled t) + +;;; Reshelve + +(defcustom magit-reshelve-since-committer-only nil + "Whether `magit-reshelve-since' changes only the committer dates. +Otherwise the author dates are also changed." + :package-version '(magit . "3.0.0") + :group 'magit-commands + :type 'boolean) + +;;;###autoload +(defun magit-reshelve-since (rev keyid) + "Change the author and committer dates of the commits since REV. + +Ask the user for the first reachable commit whose dates should +be changed. Then read the new date for that commit. The initial +minibuffer input and the previous history element offer good +values. The next commit will be created one minute later and so +on. + +This command is only intended for interactive use and should only +be used on highly rearranged and unpublished history. + +If KEYID is non-nil, then use that to sign all reshelved commits. +Interactively use the value of the \"--gpg-sign\" option in the +list returned by `magit-rebase-arguments'." + (interactive (list nil + (transient-arg-value "--gpg-sign=" + (magit-rebase-arguments)))) + (let* ((current (or (magit-get-current-branch) + (user-error "Refusing to reshelve detached head"))) + (backup (concat "refs/original/refs/heads/" current))) + (cond + ((not rev) + (when (and (magit-ref-p backup) + (not (magit-y-or-n-p + (format "Backup ref %s already exists. Override? " + backup)))) + (user-error "Abort")) + (magit-log-select + (lambda (rev) + (magit-reshelve-since rev keyid)) + "Type %p on a commit to reshelve it and the commits above it,")) + (t + (cl-flet ((adjust (time offset) + (format-time-string + "%F %T %z" + (+ (floor time) + (* offset 60) + (- (car (decode-time time))))))) + (let* ((start (concat rev "^")) + (range (concat start ".." current)) + (time-rev (adjust (float-time (string-to-number + (magit-rev-format "%at" start))) + 1)) + (time-now (adjust (float-time) + (- (string-to-number + (magit-git-string "rev-list" "--count" + range)))))) + (push time-rev magit--reshelve-history) + (let ((date (floor + (float-time + (date-to-time + (read-string "Date for first commit: " + time-now 'magit--reshelve-history)))))) + (with-environment-variables (("FILTER_BRANCH_SQUELCH_WARNING" "1")) + (magit-with-toplevel + (magit-run-git-async + "filter-branch" "--force" "--env-filter" + (format + "case $GIT_COMMIT in %s\nesac" + (mapconcat + (lambda (rev) + (prog1 + (concat + (format "%s) " rev) + (and (not magit-reshelve-since-committer-only) + (format "export GIT_AUTHOR_DATE=\"%s\"; " date)) + (format "export GIT_COMMITTER_DATE=\"%s\";;" date)) + (cl-incf date 60))) + (magit-git-lines "rev-list" "--reverse" range) + " ")) + (and keyid + (list "--commit-filter" + (format "git commit-tree --gpg-sign=%s \"$@\";" + keyid))) + range "--")) + (set-process-sentinel + magit-this-process + (lambda (process event) + (when (memq (process-status process) '(exit signal)) + (if (> (process-exit-status process) 0) + (magit-process-sentinel process event) + (process-put process 'inhibit-refresh t) + (magit-process-sentinel process event) + (magit-run-git "update-ref" "-d" backup))))))))))))) + +;;; Revision Stack + +(defvar magit-revision-stack nil) + +(defcustom magit-pop-revision-stack-format + '("[%N: %h] " + "%N: %cs %H\n %s\n" + "\\[\\([0-9]+\\)[]:]") + "Control how `magit-pop-revision-stack' inserts a revision. + +The command `magit-pop-revision-stack' inserts a representation +of the revision last pushed to the `magit-revision-stack' into +the current buffer. It inserts text at point and/or near the end +of the buffer, and removes the consumed revision from the stack. + +The entries on the stack have the format (HASH TOPLEVEL) and this +option has the format (POINT-FORMAT EOB-FORMAT INDEX-REGEXP), all +of which may be nil or a string (though either one of EOB-FORMAT +or POINT-FORMAT should be a string, and if INDEX-REGEXP is +non-nil, then the two formats should be too). + +First INDEX-REGEXP is used to find the previously inserted entry, +by searching backward from point. The first submatch must match +the index number. That number is incremented by one, and becomes +the index number of the entry to be inserted. If you don't want +to number the inserted revisions, then use nil for INDEX-REGEXP. + +If INDEX-REGEXP is non-nil, then both POINT-FORMAT and EOB-FORMAT +should contain \"%N\", which is replaced with the number that was +determined in the previous step. + +Both formats, if non-nil and after removing %N, are then expanded +using `git show --format=FORMAT ...' inside TOPLEVEL. + +The expansion of POINT-FORMAT is inserted at point, and the +expansion of EOB-FORMAT is inserted at the end of the buffer (if +the buffer ends with a comment, then it is inserted right before +that)." + :package-version '(magit . "3.2.0") + :group 'magit-commands + :type '(list (choice (string :tag "Insert at point format") + (cons (string :tag "Insert at point format") + (repeat (string :tag "Argument to git show"))) + (const :tag "Don't insert at point" nil)) + (choice (string :tag "Insert at eob format") + (cons (string :tag "Insert at eob format") + (repeat (string :tag "Argument to git show"))) + (const :tag "Don't insert at eob" nil)) + (choice (regexp :tag "Find index regexp") + (const :tag "Don't number entries" nil)))) + +(defcustom magit-copy-revision-abbreviated nil + "Whether to save abbreviated revision to `kill-ring' and `magit-revision-stack'." + :package-version '(magit . "3.0.0") + :group 'magit-miscellaneous + :type 'boolean) + +;;;###autoload +(defun magit-pop-revision-stack (rev toplevel) + "Insert a representation of a revision into the current buffer. + +Pop a revision from the `magit-revision-stack' and insert it into +the current buffer according to `magit-pop-revision-stack-format'. +Revisions can be put on the stack using `magit-copy-section-value' +and `magit-copy-buffer-revision'. + +If the stack is empty or with a prefix argument, instead read a +revision in the minibuffer. By using the minibuffer history this +allows selecting an item which was popped earlier or to insert an +arbitrary reference or revision without first pushing it onto the +stack. + +When reading the revision from the minibuffer, then it might not +be possible to guess the correct repository. When this command +is called inside a repository (e.g., while composing a commit +message), then that repository is used. Otherwise (e.g., while +composing an email) then the repository recorded for the top +element of the stack is used (even though we insert another +revision). If not called inside a repository and with an empty +stack, or with two prefix arguments, then read the repository in +the minibuffer too." + (interactive + (if (or current-prefix-arg (not magit-revision-stack)) + (let ((default-directory + (or (and (not (= (prefix-numeric-value current-prefix-arg) 16)) + (or (magit-toplevel) + (cadr (car magit-revision-stack)))) + (magit-read-repository)))) + (list (magit-read-branch-or-commit "Insert revision") + default-directory)) + (push (caar magit-revision-stack) magit-revision-history) + (pop magit-revision-stack))) + (if rev + (pcase-let ((`(,pnt-format ,eob-format ,idx-format) + magit-pop-revision-stack-format)) + (let ((default-directory toplevel) + (idx (and idx-format + (save-excursion + (if (re-search-backward idx-format nil t) + (number-to-string + (1+ (string-to-number (match-string 1)))) + "1")))) + pnt-args eob-args) + (when (listp pnt-format) + (setq pnt-args (cdr pnt-format)) + (setq pnt-format (car pnt-format))) + (when (listp eob-format) + (setq eob-args (cdr eob-format)) + (setq eob-format (car eob-format))) + (when pnt-format + (when idx-format + (setq pnt-format + (string-replace "%N" idx pnt-format))) + (magit-rev-insert-format pnt-format rev pnt-args) + (delete-char -1)) + (when eob-format + (when idx-format + (setq eob-format + (string-replace "%N" idx eob-format))) + (save-excursion + (goto-char (point-max)) + (skip-syntax-backward ">-") + (beginning-of-line) + (if (and comment-start (looking-at comment-start)) + (while (looking-at comment-start) + (forward-line -1)) + (forward-line) + (unless (= (current-column) 0) + (insert ?\n))) + (insert ?\n) + (magit-rev-insert-format eob-format rev eob-args) + (delete-char -1))))) + (user-error "Revision stack is empty"))) + +;;;###autoload +(defun magit-copy-section-value (arg) + "Save the value of the current section for later use. + +Save the section value to the `kill-ring', and, provided that +the current section is a commit, branch, or tag section, push +the (referenced) revision to the `magit-revision-stack' for use +with `magit-pop-revision-stack'. + +When `magit-copy-revision-abbreviated' is non-nil, save the +abbreviated revision to the `kill-ring' and the +`magit-revision-stack'. + +When the current section is a branch or a tag, and a prefix +argument is used, then save the revision at its tip to the +`kill-ring' instead of the reference name. + +When the region is active, then save that to the `kill-ring', +like `kill-ring-save' would, instead of behaving as described +above. If a prefix argument is used and the region is within +a hunk, then strip the diff marker column and keep only either +the added or removed lines, depending on the sign of the prefix +argument." + (interactive "P") + (cond + ((and arg + (magit-section-internal-region-p) + (magit-section-match 'hunk)) + (kill-new + (thread-last (buffer-substring-no-properties + (region-beginning) + (region-end)) + (replace-regexp-in-string + (format "^\\%c.*\n?" (if (< (prefix-numeric-value arg) 0) ?+ ?-)) + "") + (replace-regexp-in-string "^[ +-]" ""))) + (deactivate-mark)) + ((use-region-p) + (call-interactively #'copy-region-as-kill)) + (t + (when-let* ((section (magit-current-section)) + (value (oref section value))) + (magit-section-case + ((branch commit module-commit tag) + (let ((default-directory default-directory) ref) + (magit-section-case + ((branch tag) + (setq ref value)) + (module-commit + (setq default-directory + (file-name-as-directory + (expand-file-name (magit-section-parent-value section) + (magit-toplevel)))))) + (setq value (magit-rev-parse + (and magit-copy-revision-abbreviated "--short") + value)) + (push (list value default-directory) magit-revision-stack) + (kill-new (message "%s" (or (and current-prefix-arg ref) + value))))) + ((kill-new (message "%s" value)))))))) + +;;;###autoload +(defun magit-copy-buffer-revision () + "Save the revision of the current buffer for later use. + +Save the revision shown in the current buffer to the `kill-ring' +and push it to the `magit-revision-stack'. + +This command is mainly intended for use in `magit-revision-mode' +buffers, the only buffers where it is always unambiguous exactly +which revision should be saved. + +Most other Magit buffers usually show more than one revision, in +some way or another, so this command has to select one of them, +and that choice might not always be the one you think would have +been the best pick. + +In such buffers it is often more useful to save the value of +the current section instead, using `magit-copy-section-value'. + +When the region is active, then save that to the `kill-ring', +like `kill-ring-save' would, instead of behaving as described +above. + +When `magit-copy-revision-abbreviated' is non-nil, save the +abbreviated revision to the `kill-ring' and the +`magit-revision-stack'." + (interactive) + (if (use-region-p) + (call-interactively #'copy-region-as-kill) + (when-let ((rev (or magit-buffer-revision + (cl-case major-mode + (magit-diff-mode + (if (string-match "\\.\\.\\.?\\(.+\\)" + magit-buffer-range) + (match-string 1 magit-buffer-range) + magit-buffer-range)) + (magit-status-mode "HEAD"))))) + (when (magit-commit-p rev) + (setq rev (magit-rev-parse + (and magit-copy-revision-abbreviated "--short") + rev)) + (push (list rev default-directory) magit-revision-stack) + (kill-new (message "%s" rev)))))) + +;;; Buffer Switching + +;;;###autoload +(defun magit-display-repository-buffer (buffer) + "Display a Magit buffer belonging to the current Git repository. +The buffer is displayed using `magit-display-buffer', which see." + (interactive (list (magit--read-repository-buffer + "Display magit buffer: "))) + (magit-display-buffer (get-buffer buffer))) + +;;;###autoload +(defun magit-switch-to-repository-buffer (buffer) + "Switch to a Magit buffer belonging to the current Git repository." + (interactive (list (magit--read-repository-buffer + "Switch to magit buffer: "))) + (switch-to-buffer buffer)) + +;;;###autoload +(defun magit-switch-to-repository-buffer-other-window (buffer) + "Switch to a Magit buffer belonging to the current Git repository." + (interactive (list (magit--read-repository-buffer + "Switch to magit buffer in another window: "))) + (switch-to-buffer-other-window buffer)) + +;;;###autoload +(defun magit-switch-to-repository-buffer-other-frame (buffer) + "Switch to a Magit buffer belonging to the current Git repository." + (interactive (list (magit--read-repository-buffer + "Switch to magit buffer in another frame: "))) + (switch-to-buffer-other-frame buffer)) + +(defun magit--read-repository-buffer (prompt) + (if-let ((topdir (magit-rev-parse-safe "--show-toplevel"))) + (read-buffer + prompt (magit-get-mode-buffer 'magit-status-mode) t + (pcase-lambda (`(,_ . ,buf)) + (and buf + (with-current-buffer buf + (and (or (derived-mode-p 'magit-mode + 'magit-repolist-mode + 'magit-submodule-list-mode + 'git-rebase-mode) + (and buffer-file-name + (string-match-p git-commit-filename-regexp + buffer-file-name))) + (equal (magit-rev-parse-safe "--show-toplevel") + topdir)))))) + (user-error "Not inside a Git repository"))) + +;;; Miscellaneous + +;;;###autoload +(defun magit-abort-dwim () + "Abort current operation. +Depending on the context, this will abort a merge, a rebase, a +patch application, a cherry-pick, a revert, or a bisect." + (interactive) + (cond ((magit-merge-in-progress-p) (magit-merge-abort)) + ((magit-rebase-in-progress-p) (magit-rebase-abort)) + ((magit-am-in-progress-p) (magit-am-abort)) + ((magit-sequencer-in-progress-p) (magit-sequencer-abort)) + ((magit-bisect-in-progress-p) (magit-bisect-reset)))) + +;;;###autoload +(defun magit-back-to-indentation () + "Move point to the first non-whitespace character on this line. +In Magit diffs, also skip over - and + at the beginning of the line." + (interactive "^") + (beginning-of-line 1) + (when (and (magit-section-match 'hunk) + (looking-at (if (oref (magit-current-section) combined) + "^ ?[-+]+" + "^[-+]"))) + (goto-char (match-end 0))) + (skip-syntax-forward " " (line-end-position)) + (backward-prefix-chars)) + +;;; _ +(provide 'magit-extras) +;;; magit-extras.el ends here diff --git a/emacs/elpa/magit-20241004.917/magit-fetch.el b/emacs/elpa/magit-20241004.917/magit-fetch.el @@ -0,0 +1,191 @@ +;;; magit-fetch.el --- Download objects and refs -*- lexical-binding:t -*- + +;; Copyright (C) 2008-2024 The Magit Project Contributors + +;; Author: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> +;; Maintainer: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> + +;; SPDX-License-Identifier: GPL-3.0-or-later + +;; Magit is free software: you can redistribute it and/or modify it +;; under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. +;; +;; Magit is distributed in the hope that it will be useful, but WITHOUT +;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +;; or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public +;; License for more details. +;; +;; You should have received a copy of the GNU General Public License +;; along with Magit. If not, see <https://www.gnu.org/licenses/>. + +;;; Commentary: + +;; This library implements fetch commands. + +;;; Code: + +(require 'magit) + +;;; Commands + +;;;###autoload (autoload 'magit-fetch "magit-fetch" nil t) +(transient-define-prefix magit-fetch () + "Fetch from another repository." + :man-page "git-fetch" + ["Arguments" + ("-p" "Prune deleted branches" ("-p" "--prune")) + ("-t" "Fetch all tags" ("-t" "--tags")) + ("-u" "Fetch full history" "--unshallow" :level 7) + ("-F" "Force" ("-f" "--force"))] + ["Fetch from" + ("p" magit-fetch-from-pushremote) + ("u" magit-fetch-from-upstream) + ("e" "elsewhere" magit-fetch-other) + ("a" "all remotes" magit-fetch-all)] + ["Fetch" + ("o" "another branch" magit-fetch-branch) + ("r" "explicit refspec" magit-fetch-refspec) + ("m" "submodules" magit-fetch-modules)] + ["Configure" + ("C" "variables..." magit-branch-configure)]) + +(defun magit-fetch-arguments () + (transient-args 'magit-fetch)) + +(defun magit-git-fetch (remote args) + (run-hooks 'magit-credential-hook) + (magit-run-git-async "fetch" remote args)) + +;;;###autoload (autoload 'magit-fetch-from-pushremote "magit-fetch" nil t) +(transient-define-suffix magit-fetch-from-pushremote (args) + "Fetch from the current push-remote. + +With a prefix argument or when the push-remote is either not +configured or unusable, then let the user first configure the +push-remote." + :description #'magit-fetch--pushremote-description + (interactive (list (magit-fetch-arguments))) + (let ((remote (magit-get-push-remote))) + (when (or current-prefix-arg + (not (member remote (magit-list-remotes)))) + (let ((var (magit--push-remote-variable))) + (setq remote + (magit-read-remote (format "Set %s and fetch from there" var))) + (magit-set remote var))) + (magit-git-fetch remote args))) + +(defun magit-fetch--pushremote-description () + (let* ((branch (magit-get-current-branch)) + (remote (magit-get-push-remote branch)) + (v (magit--push-remote-variable branch t))) + (cond + ((member remote (magit-list-remotes)) remote) + (remote + (format "%s, replacing invalid" v)) + (t + (format "%s, setting that" v))))) + +;;;###autoload (autoload 'magit-fetch-from-upstream "magit-fetch" nil t) +(transient-define-suffix magit-fetch-from-upstream (remote args) + "Fetch from the \"current\" remote, usually the upstream. + +If the upstream is configured for the current branch and names +an existing remote, then use that. Otherwise try to use another +remote: If only a single remote is configured, then use that. +Otherwise if a remote named \"origin\" exists, then use that. + +If no remote can be determined, then this command is not available +from the `magit-fetch' transient prefix and invoking it directly +results in an error." + :if (lambda () (magit-get-current-remote t)) + :description (lambda () (magit-get-current-remote t)) + (interactive (list (magit-get-current-remote t) + (magit-fetch-arguments))) + (unless remote + (error "The \"current\" remote could not be determined")) + (magit-git-fetch remote args)) + +;;;###autoload +(defun magit-fetch-other (remote args) + "Fetch from another repository." + (interactive (list (magit-read-remote "Fetch remote") + (magit-fetch-arguments))) + (magit-git-fetch remote args)) + +;;;###autoload +(defun magit-fetch-branch (remote branch args) + "Fetch a BRANCH from a REMOTE." + (interactive + (let ((remote (magit-read-remote-or-url "Fetch from remote or url"))) + (list remote + (magit-read-remote-branch "Fetch branch" remote) + (magit-fetch-arguments)))) + (magit-git-fetch remote (cons branch args))) + +;;;###autoload +(defun magit-fetch-refspec (remote refspec args) + "Fetch a REFSPEC from a REMOTE." + (interactive + (let ((remote (magit-read-remote-or-url "Fetch from remote or url"))) + (list remote + (magit-read-refspec "Fetch using refspec" remote) + (magit-fetch-arguments)))) + (magit-git-fetch remote (cons refspec args))) + +;;;###autoload +(defun magit-fetch-all (args) + "Fetch from all remotes." + (interactive (list (magit-fetch-arguments))) + (magit-git-fetch nil (cons "--all" args))) + +;;;###autoload +(defun magit-fetch-all-prune () + "Fetch from all remotes, and prune. +Prune remote tracking branches for branches that have been +removed on the respective remote." + (interactive) + (run-hooks 'magit-credential-hook) + (magit-run-git-async "remote" "update" "--prune")) + +;;;###autoload +(defun magit-fetch-all-no-prune () + "Fetch from all remotes." + (interactive) + (run-hooks 'magit-credential-hook) + (magit-run-git-async "remote" "update")) + +;;;###autoload (autoload 'magit-fetch-modules "magit-fetch" nil t) +(transient-define-prefix magit-fetch-modules (&optional transient args) + "Fetch all populated submodules. + +Fetching is done using \"git fetch --recurse-submodules\", which +means that the super-repository and recursively all submodules +are also fetched. + +To set and potentially save other arguments invoke this command +with a prefix argument." + :man-page "git-fetch" + :value (list "--verbose" "--jobs=4") + ["Arguments" + ("-v" "verbose" "--verbose") + ("-j" "number of jobs" "--jobs=" :reader transient-read-number-N+)] + ["Action" + ("m" "fetch modules" magit-fetch-modules)] + (interactive (if current-prefix-arg + (list t) + (list nil (transient-args 'magit-fetch-modules)))) + (if transient + (transient-setup 'magit-fetch-modules) + (when (magit-git-version< "2.8.0") + (when-let ((value (transient-arg-value "--jobs=" args))) + (message "Dropping --jobs; not supported by Git v%s" + (magit-git-version)) + (setq args (remove (format "--jobs=%s" value) args)))) + (magit-with-toplevel + (magit-run-git-async "fetch" "--recurse-submodules" args)))) + +;;; _ +(provide 'magit-fetch) +;;; magit-fetch.el ends here diff --git a/emacs/elpa/magit-20241004.917/magit-files.el b/emacs/elpa/magit-20241004.917/magit-files.el @@ -0,0 +1,560 @@ +;;; magit-files.el --- Finding files -*- lexical-binding:t -*- + +;; Copyright (C) 2008-2024 The Magit Project Contributors + +;; Author: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> +;; Maintainer: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> + +;; SPDX-License-Identifier: GPL-3.0-or-later + +;; Magit is free software: you can redistribute it and/or modify it +;; under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. +;; +;; Magit is distributed in the hope that it will be useful, but WITHOUT +;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +;; or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public +;; License for more details. +;; +;; You should have received a copy of the GNU General Public License +;; along with Magit. If not, see <https://www.gnu.org/licenses/>. + +;;; Commentary: + +;; This library implements support for finding blobs, staged files, +;; and Git configuration files. It also implements modes useful in +;; buffers visiting files and blobs, and the commands used by those +;; modes. + +;;; Code: + +(require 'magit) + +;;; Find Blob + +(defvar magit-find-file-hook nil) +(add-hook 'magit-find-file-hook #'magit-blob-mode) + +;;;###autoload +(defun magit-find-file (rev file) + "View FILE from REV. +Switch to a buffer visiting blob REV:FILE, creating one if none +already exists. If prior to calling this command the current +buffer and/or cursor position is about the same file, then go +to the line and column corresponding to that location." + (interactive (magit-find-file-read-args "Find file")) + (magit-find-file--internal rev file #'pop-to-buffer-same-window)) + +;;;###autoload +(defun magit-find-file-other-window (rev file) + "View FILE from REV, in another window. +Switch to a buffer visiting blob REV:FILE, creating one if none +already exists. If prior to calling this command the current +buffer and/or cursor position is about the same file, then go to +the line and column corresponding to that location." + (interactive (magit-find-file-read-args "Find file in other window")) + (magit-find-file--internal rev file #'switch-to-buffer-other-window)) + +;;;###autoload +(defun magit-find-file-other-frame (rev file) + "View FILE from REV, in another frame. +Switch to a buffer visiting blob REV:FILE, creating one if none +already exists. If prior to calling this command the current +buffer and/or cursor position is about the same file, then go to +the line and column corresponding to that location." + (interactive (magit-find-file-read-args "Find file in other frame")) + (magit-find-file--internal rev file #'switch-to-buffer-other-frame)) + +(defun magit-find-file-read-args (prompt) + (let ((pseudo-revs '("{worktree}" "{index}"))) + (if-let ((rev (magit-completing-read "Find file from revision" + (append pseudo-revs + (magit-list-refnames nil t)) + nil nil nil 'magit-revision-history + (or (magit-branch-or-commit-at-point) + (magit-get-current-branch))))) + (list rev (magit-read-file-from-rev (if (member rev pseudo-revs) + "HEAD" + rev) + prompt)) + (user-error "Nothing selected")))) + +(defun magit-find-file--internal (rev file fn) + (let ((buf (magit-find-file-noselect rev file)) + line col) + (when-let ((visited-file (magit-file-relative-name))) + (setq line (line-number-at-pos)) + (setq col (current-column)) + (cond + ((not (equal visited-file file))) + ((equal magit-buffer-revision rev)) + ((equal rev "{worktree}") + (setq line (magit-diff-visit--offset file magit-buffer-revision line))) + ((equal rev "{index}") + (setq line (magit-diff-visit--offset file nil line))) + (magit-buffer-revision + (setq line (magit-diff-visit--offset + file (concat magit-buffer-revision ".." rev) line))) + (t + (setq line (magit-diff-visit--offset file (list "-R" rev) line))))) + (funcall fn buf) + (when line + (with-current-buffer buf + (widen) + (goto-char (point-min)) + (forward-line (1- line)) + (move-to-column col))) + buf)) + +(defun magit-find-file-noselect (rev file) + "Read FILE from REV into a buffer and return the buffer. +REV is a revision or one of \"{worktree}\" or \"{index}\". +FILE must be relative to the top directory of the repository." + (magit-find-file-noselect-1 rev file)) + +(defun magit-find-file-noselect-1 (rev file &optional revert) + "Read FILE from REV into a buffer and return the buffer. +REV is a revision or one of \"{worktree}\" or \"{index}\". +FILE must be relative to the top directory of the repository. +Non-nil REVERT means to revert the buffer. If `ask-revert', +then only after asking. A non-nil value for REVERT is ignored if REV is +\"{worktree}\"." + (if (equal rev "{worktree}") + (find-file-noselect (expand-file-name file (magit-toplevel))) + (let ((topdir (magit-toplevel))) + (when (file-name-absolute-p file) + (setq file (file-relative-name file topdir))) + (with-current-buffer (magit-get-revision-buffer-create rev file) + (when (or (not magit-buffer-file-name) + (if (eq revert 'ask-revert) + (y-or-n-p (format "%s already exists; revert it? " + (buffer-name)))) + revert) + (setq magit-buffer-revision + (if (equal rev "{index}") + "{index}" + (magit-rev-format "%H" rev))) + (setq magit-buffer-refname rev) + (setq magit-buffer-file-name (expand-file-name file topdir)) + (setq default-directory + (let ((dir (file-name-directory magit-buffer-file-name))) + (if (file-exists-p dir) dir topdir))) + (setq-local revert-buffer-function #'magit-revert-rev-file-buffer) + (revert-buffer t t) + (run-hooks (if (equal rev "{index}") + 'magit-find-index-hook + 'magit-find-file-hook))) + (current-buffer))))) + +(defun magit-get-revision-buffer-create (rev file) + (magit-get-revision-buffer rev file t)) + +(defun magit-get-revision-buffer (rev file &optional create) + (funcall (if create #'get-buffer-create #'get-buffer) + (format "%s.~%s~" file (subst-char-in-string ?/ ?_ rev)))) + +(defun magit-revert-rev-file-buffer (_ignore-auto noconfirm) + (when (or noconfirm + (and (not (buffer-modified-p)) + (catch 'found + (dolist (regexp revert-without-query) + (when (string-match regexp magit-buffer-file-name) + (throw 'found t))))) + (yes-or-no-p (format "Revert buffer from Git %s? " + (if (equal magit-buffer-refname "{index}") + "index" + (concat "revision " magit-buffer-refname))))) + (let* ((inhibit-read-only t) + (default-directory (magit-toplevel)) + (file (file-relative-name magit-buffer-file-name)) + (coding-system-for-read (or coding-system-for-read 'undecided))) + (erase-buffer) + (magit-git-insert "cat-file" "-p" + (if (equal magit-buffer-refname "{index}") + (concat ":" file) + (concat magit-buffer-refname ":" file))) + (setq buffer-file-coding-system last-coding-system-used)) + (let ((buffer-file-name magit-buffer-file-name) + (after-change-major-mode-hook + (seq-difference after-change-major-mode-hook + '(global-diff-hl-mode-enable-in-buffer ; Emacs >= 30 + global-diff-hl-mode-enable-in-buffers ; Emacs < 30 + eglot--maybe-activate-editing-mode) + #'eq))) + (normal-mode t)) + (setq buffer-read-only t) + (set-buffer-modified-p nil) + (goto-char (point-min)))) + +(define-advice lsp (:around (fn &rest args) magit-find-file) + "Do nothing when visiting blob using `magit-find-file' and similar. +See also https://github.com/doomemacs/doomemacs/pull/6309." + (unless magit-buffer-revision + (apply fn args))) + +;;; Find Index + +(defvar magit-find-index-hook nil) + +(defun magit-find-file-index-noselect (file &optional revert) + "Read FILE from the index into a buffer and return the buffer. +FILE must to be relative to the top directory of the repository." + (magit-find-file-noselect-1 "{index}" file (or revert 'ask-revert))) + +(defun magit-update-index () + "Update the index with the contents of the current buffer. +The current buffer has to be visiting a file in the index, which +is done using `magit-find-index-noselect'." + (interactive) + (let ((file (magit-file-relative-name))) + (unless (equal magit-buffer-refname "{index}") + (user-error "%s isn't visiting the index" file)) + (if (y-or-n-p (format "Update index with contents of %s" (buffer-name))) + (let ((index (make-temp-name + (expand-file-name "magit-update-index-" (magit-gitdir)))) + (buffer (current-buffer))) + (when magit-wip-before-change-mode + (magit-wip-commit-before-change (list file) " before un-/stage")) + (unwind-protect + (progn + (let ((coding-system-for-write buffer-file-coding-system)) + (with-temp-file index + (insert-buffer-substring buffer))) + (magit-with-toplevel + (magit-call-git + "update-index" "--cacheinfo" + (substring (magit-git-string "ls-files" "-s" file) + 0 6) + (magit-git-string "hash-object" "-t" "blob" "-w" + (concat "--path=" file) + "--" (magit-convert-filename-for-git index)) + file))) + (ignore-errors (delete-file index))) + (set-buffer-modified-p nil) + (when magit-wip-after-apply-mode + (magit-wip-commit-after-apply (list file) " after un-/stage"))) + (message "Abort"))) + (when-let ((buffer (magit-get-mode-buffer 'magit-status-mode))) + (with-current-buffer buffer + (magit-refresh))) + t) + +;;; Find Config File + +(defun magit-find-git-config-file (filename &optional wildcards) + "Edit a file located in the current repository's git directory. + +When \".git\", located at the root of the working tree, is a +regular file, then that makes it cumbersome to open a file +located in the actual git directory. + +This command is like `find-file', except that it temporarily +binds `default-directory' to the actual git directory, while +reading the FILENAME." + (interactive + (let ((default-directory (magit-gitdir))) + (find-file-read-args "Find file: " + (confirm-nonexistent-file-or-buffer)))) + (find-file filename wildcards)) + +(defun magit-find-git-config-file-other-window (filename &optional wildcards) + "Edit a file located in the current repo's git directory, in another window. + +When \".git\", located at the root of the working tree, is a +regular file, then that makes it cumbersome to open a file +located in the actual git directory. + +This command is like `find-file-other-window', except that it +temporarily binds `default-directory' to the actual git +directory, while reading the FILENAME." + (interactive + (let ((default-directory (magit-gitdir))) + (find-file-read-args "Find file in other window: " + (confirm-nonexistent-file-or-buffer)))) + (find-file-other-window filename wildcards)) + +(defun magit-find-git-config-file-other-frame (filename &optional wildcards) + "Edit a file located in the current repo's git directory, in another frame. + +When \".git\", located at the root of the working tree, is a +regular file, then that makes it cumbersome to open a file +located in the actual git directory. + +This command is like `find-file-other-frame', except that it +temporarily binds `default-directory' to the actual git +directory, while reading the FILENAME." + (interactive + (let ((default-directory (magit-gitdir))) + (find-file-read-args "Find file in other frame: " + (confirm-nonexistent-file-or-buffer)))) + (find-file-other-frame filename wildcards)) + +;;; File Dispatch + +;;;###autoload (autoload 'magit-file-dispatch "magit" nil t) +(transient-define-prefix magit-file-dispatch () + "Invoke a Magit command that acts on the visited file. +When invoked outside a file-visiting buffer, then fall back +to `magit-dispatch'." + :info-manual "(magit) Minor Mode for Buffers Visiting Files" + [:if magit-file-relative-name + ["File actions" + (" s" "Stage" magit-stage-buffer-file) + (" u" "Unstage" magit-unstage-buffer-file) + (", x" "Untrack" magit-file-untrack) + (", r" "Rename" magit-file-rename) + (", k" "Delete" magit-file-delete) + (", c" "Checkout" magit-file-checkout)] + ["Inspect" + ("D" "Diff..." magit-diff) + ("d" "Diff" magit-diff-buffer-file)] + ["" + ("L" "Log..." magit-log) + ("l" "Log" magit-log-buffer-file) + ("t" "Trace" magit-log-trace-definition) + (7 "M" "Merged" magit-log-merged)] + ["" + ("B" "Blame..." magit-blame) + ("b" "Blame" magit-blame-addition) + ("r" "...removal" magit-blame-removal) + ("f" "...reverse" magit-blame-reverse) + ("m" "Blame echo" magit-blame-echo) + ("q" "Quit blame" magit-blame-quit)] + ["Navigate" + ("p" "Prev blob" magit-blob-previous) + ("n" "Next blob" magit-blob-next) + ("v" "Goto blob" magit-find-file) + ("V" "Goto file" magit-blob-visit-file) + ("g" "Goto status" magit-status-here) + ("G" "Goto magit" magit-display-repository-buffer)] + ["More actions" + ("c" "Commit" magit-commit) + ("e" "Edit line" magit-edit-line-commit)]] + [:if-not magit-file-relative-name + ["File actions" + ("s" "Stage" magit-stage-file) + ("u" "Unstage" magit-unstage-file) + ("x" "Untrack" magit-file-untrack) + ("r" "Rename" magit-file-rename) + ("k" "Delete" magit-file-delete) + ("c" "Checkout" magit-file-checkout)] + ["Navigate" + ("g" "Goto status" magit-status-here :if-not-mode magit-status-mode) + ("G" "Goto magit" magit-display-repository-buffer)]]) + +;;; Blob Mode + +(defvar-keymap magit-blob-mode-map + :doc "Keymap for `magit-blob-mode'." + "p" #'magit-blob-previous + "n" #'magit-blob-next + "b" #'magit-blame-addition + "r" #'magit-blame-removal + "f" #'magit-blame-reverse + "q" #'magit-kill-this-buffer) + +(define-minor-mode magit-blob-mode + "Enable some Magit features in blob-visiting buffers. + +Currently this only adds the following key bindings. +\n\\{magit-blob-mode-map}" + :package-version '(magit . "2.3.0")) + +(defun magit-blob-next () + "Visit the next blob which modified the current file." + (interactive) + (if magit-buffer-file-name + (magit-blob-visit (or (magit-blob-successor magit-buffer-revision + magit-buffer-file-name) + magit-buffer-file-name)) + (if (buffer-file-name (buffer-base-buffer)) + (user-error "You have reached the end of time") + (user-error "Buffer isn't visiting a file or blob")))) + +(defun magit-blob-previous () + "Visit the previous blob which modified the current file." + (interactive) + (if-let ((file (or magit-buffer-file-name + (buffer-file-name (buffer-base-buffer))))) + (if-let ((ancestor (magit-blob-ancestor magit-buffer-revision file))) + (magit-blob-visit ancestor) + (user-error "You have reached the beginning of time")) + (user-error "Buffer isn't visiting a file or blob"))) + +;;;###autoload +(defun magit-blob-visit-file () + "View the file from the worktree corresponding to the current blob. +When visiting a blob or the version from the index, then go to +the same location in the respective file in the working tree." + (interactive) + (if-let ((file (magit-file-relative-name))) + (magit-find-file--internal "{worktree}" file #'pop-to-buffer-same-window) + (user-error "Not visiting a blob"))) + +(defun magit-blob-visit (blob-or-file) + (if (stringp blob-or-file) + (find-file blob-or-file) + (pcase-let ((`(,rev ,file) blob-or-file)) + (magit-find-file rev file) + (apply #'message "%s (%s %s ago)" + (magit-rev-format "%s" rev) + (magit--age (magit-rev-format "%ct" rev)))))) + +(defun magit-blob-ancestor (rev file) + (let ((lines (magit-with-toplevel + (magit-git-lines "log" "-2" "--format=%H" "--name-only" + "--follow" (or rev "HEAD") "--" file)))) + (if rev (cddr lines) (butlast lines 2)))) + +(defun magit-blob-successor (rev file) + (let ((lines (magit-with-toplevel + (magit-git-lines "log" "--format=%H" "--name-only" "--follow" + "HEAD" "--" file)))) + (catch 'found + (while lines + (if (equal (nth 2 lines) rev) + (throw 'found (list (nth 0 lines) (nth 1 lines))) + (setq lines (nthcdr 2 lines))))))) + +;;; File Commands + +(defun magit-file-rename (file newname) + "Rename or move FILE to NEWNAME. +NEWNAME may be a file or directory name. If FILE isn't tracked in +Git, fallback to using `rename-file'." + (interactive + (let* ((file (magit-read-file "Rename file")) + (path (expand-file-name file (magit-toplevel)))) + (list path (expand-file-name + (read-file-name (format "Move %s to destination: " file) + (file-name-directory path)))))) + (let ((oldbuf (get-file-buffer file)) + (dstdir (file-name-directory newname)) + (dstfile (if (directory-name-p newname) + (concat newname (file-name-nondirectory file)) + newname))) + (when (and oldbuf (buffer-modified-p oldbuf)) + (user-error "Save %s before moving it" file)) + (when (file-exists-p dstfile) + (user-error "%s already exists" dstfile)) + (unless (file-exists-p dstdir) + (user-error "Destination directory %s does not exist" dstdir)) + (if (magit-file-tracked-p file) + (magit-call-git "mv" + (magit-convert-filename-for-git file) + (magit-convert-filename-for-git newname)) + (rename-file file newname current-prefix-arg)) + (when oldbuf + (with-current-buffer oldbuf + (let ((buffer-read-only buffer-read-only)) + (set-visited-file-name dstfile nil t)) + (if (fboundp 'vc-refresh-state) + (vc-refresh-state) + (with-no-warnings + (vc-find-file-hook)))))) + (magit-refresh)) + +(defun magit-file-untrack (files &optional force) + "Untrack the selected FILES or one file read in the minibuffer. + +With a prefix argument FORCE do so even when the files have +staged as well as unstaged changes." + (interactive (list (or (if-let ((files (magit-region-values 'file t))) + (if (magit-file-tracked-p (car files)) + (magit-confirm-files 'untrack files "Untrack") + (user-error "Already untracked")) + (list (magit-read-tracked-file "Untrack file")))) + current-prefix-arg)) + (magit-with-toplevel + (magit-run-git "rm" "--cached" (and force "--force") "--" files))) + +(defun magit-file-delete (files &optional force) + "Delete the selected FILES or one file read in the minibuffer. + +With a prefix argument FORCE do so even when the files have +uncommitted changes. When the files aren't being tracked in +Git, then fallback to using `delete-file'." + (interactive (list (if-let ((files (magit-region-values 'file t))) + (magit-confirm-files 'delete files "Delete") + (list (magit-read-file "Delete file"))) + current-prefix-arg)) + (if (magit-file-tracked-p (car files)) + (magit-call-git "rm" (and force "--force") "--" files) + (let ((topdir (magit-toplevel))) + (dolist (file files) + (delete-file (expand-file-name file topdir) t)))) + (magit-refresh)) + +;;;###autoload +(defun magit-file-checkout (rev file) + "Checkout FILE from REV." + (interactive + (let ((rev (magit-read-branch-or-commit + "Checkout from revision" magit-buffer-revision))) + (list rev (magit-read-file-from-rev rev "Checkout file" nil t)))) + (magit-with-toplevel + (magit-run-git "checkout" rev "--" file))) + +;;; Read File + +(defvar magit-read-file-hist nil) + +(defun magit-read-file-from-rev (rev prompt &optional default include-dirs) + (let ((files (magit-revision-files rev))) + (when include-dirs + (setq files (sort (nconc files (magit-revision-directories rev)) + #'string<))) + (magit-completing-read + prompt files nil t nil 'magit-read-file-hist + (car (member (or default (magit-current-file)) files))))) + +(defun magit-read-file (prompt &optional tracked-only) + (magit-with-toplevel + (let ((choices (nconc (magit-list-files) + (and (not tracked-only) + (magit-untracked-files))))) + (magit-completing-read + prompt choices nil t nil nil + (car (member (or (magit-section-value-if '(file submodule)) + (magit-file-relative-name nil tracked-only)) + choices)))))) + +(defun magit-read-tracked-file (prompt) + (magit-read-file prompt t)) + +(defun magit-read-unmerged-file (&optional prompt) + (let ((current (magit-current-file)) + (unmerged (magit-unmerged-files))) + (unless unmerged + (user-error "There are no unresolved conflicts")) + (magit-completing-read (or prompt "Resolve file") + unmerged nil t nil nil + (car (member current unmerged))))) + +(defun magit-read-file-choice (prompt files &optional error default) + "Read file from FILES. + +If FILES has only one member, return that instead of prompting. +If FILES has no members, give a user error. ERROR can be given +to provide a more informative error. + +If DEFAULT is non-nil, use this as the default value instead of +`magit-current-file'." + (pcase (length files) + (0 (user-error (or error "No file choices"))) + (1 (car files)) + (_ (magit-completing-read + prompt files nil t nil 'magit-read-file-hist + (car (member (or default (magit-current-file)) files)))))) + +(defun magit-read-changed-file (rev-or-range prompt &optional default) + (magit-read-file-choice + prompt + (magit-changed-files rev-or-range) + default + (concat "No file changed in " rev-or-range))) + +;;; _ +(provide 'magit-files) +;;; magit-files.el ends here diff --git a/emacs/elpa/magit-20241004.917/magit-git.el b/emacs/elpa/magit-20241004.917/magit-git.el @@ -0,0 +1,2889 @@ +;;; magit-git.el --- Git functionality -*- lexical-binding:t -*- + +;; Copyright (C) 2008-2024 The Magit Project Contributors + +;; Author: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> +;; Maintainer: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> + +;; SPDX-License-Identifier: GPL-3.0-or-later + +;; Magit is free software: you can redistribute it and/or modify it +;; under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. +;; +;; Magit is distributed in the hope that it will be useful, but WITHOUT +;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +;; or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public +;; License for more details. +;; +;; You should have received a copy of the GNU General Public License +;; along with Magit. If not, see <https://www.gnu.org/licenses/>. + +;;; Commentary: + +;; This library implements wrappers for various Git plumbing commands. + +;;; Code: + +(require 'magit-base) + +(require 'format-spec) + +;; From `magit-branch'. +(defvar magit-branch-prefer-remote-upstream) +(defvar magit-published-branches) + +;; From `magit-margin'. +(declare-function magit-maybe-make-margin-overlay "magit-margin" ()) + +;; From `magit-mode'. +(declare-function magit-get-mode-buffer "magit-mode" + (mode &optional value frame)) +(declare-function magit-refresh "magit-mode" ()) +(defvar magit-buffer-diff-type) +(defvar magit-buffer-diff-args) +(defvar magit-buffer-file-name) +(defvar magit-buffer-log-args) +(defvar magit-buffer-log-files) +(defvar magit-buffer-refname) +(defvar magit-buffer-revision) + +;; From `magit-process'. +(declare-function magit-call-git "magit-process" (&rest args)) +(declare-function magit-git "magit-process" (&rest args)) +(declare-function magit-process-buffer "magit-process" (&optional nodisplay)) +(declare-function magit-process-file "magit-process" + (process &optional infile buffer display &rest args)) +(declare-function magit-process-git "magit-process" (destination &rest args)) +(declare-function magit-process-insert-section "magit-process" + (pwd program args &optional errcode errlog)) +(defvar magit-this-error) +(defvar magit-process-error-message-regexps) + +(eval-when-compile + (cl-pushnew 'orig-rev eieio--known-slot-names) + (cl-pushnew 'number eieio--known-slot-names)) + +;;; Options + +;; For now this is shared between `magit-process' and `magit-git'. +(defgroup magit-process nil + "Git and other external processes used by Magit." + :group 'magit) + +(defvar magit-git-environment + (list (format "INSIDE_EMACS=%s,magit" emacs-version)) + "Prepended to `process-environment' while running git.") + +(defcustom magit-git-output-coding-system + (and (eq system-type 'windows-nt) 'utf-8) + "Coding system for receiving output from Git. + +If non-nil, the Git config value `i18n.logOutputEncoding' should +be set via `magit-git-global-arguments' to value consistent with +this." + :package-version '(magit . "2.9.0") + :group 'magit-process + :type '(choice (coding-system :tag "Coding system to decode Git output") + (const :tag "Use system default" nil))) + +(defvar magit-git-w32-path-hack nil + "Alist of (EXE . (PATHENTRY)). +This specifies what additional PATH setting needs to be added to +the environment in order to run the non-wrapper git executables +successfully.") + +(defcustom magit-git-executable + (or (and (eq system-type 'windows-nt) + ;; Avoid the wrappers "cmd/git.exe" and "cmd/git.cmd", + ;; which are much slower than using "bin/git.exe" directly. + (and-let* ((exec (executable-find "git"))) + (ignore-errors + ;; Git for Windows 2.x provides cygpath so we can + ;; ask it for native paths. + (let* ((core-exe + (car + (process-lines + exec "-c" + "alias.X=!x() { which \"$1\" | cygpath -mf -; }; x" + "X" "git"))) + (hack-entry (assoc core-exe magit-git-w32-path-hack)) + ;; Running the libexec/git-core executable + ;; requires some extra PATH entries. + (path-hack + (list (concat "PATH=" + (car (process-lines + exec "-c" + "alias.P=!cygpath -wp \"$PATH\"" + "P")))))) + ;; The defcustom STANDARD expression can be + ;; evaluated many times, so make sure it is + ;; idempotent. + (if hack-entry + (setcdr hack-entry path-hack) + (push (cons core-exe path-hack) magit-git-w32-path-hack)) + core-exe)))) + (and (eq system-type 'darwin) + (executable-find "git")) + "git") + "The Git executable used by Magit on the local host. +On remote machines `magit-remote-git-executable' is used instead." + :package-version '(magit . "3.2.0") + :group 'magit-process + :type 'string) + +(defcustom magit-remote-git-executable "git" + "The Git executable used by Magit on remote machines. +On the local host `magit-git-executable' is used instead. +Consider customizing `tramp-remote-path' instead of this +option." + :package-version '(magit . "3.2.0") + :group 'magit-process + :type 'string) + +(defcustom magit-git-global-arguments + `("--no-pager" "--literal-pathspecs" + "-c" "core.preloadindex=true" + "-c" "log.showSignature=false" + "-c" "color.ui=false" + "-c" "color.diff=false" + ,@(and (eq system-type 'windows-nt) + (list "-c" "i18n.logOutputEncoding=UTF-8"))) + "Global Git arguments. + +The arguments set here are used every time the git executable is +run as a subprocess. They are placed right after the executable +itself and before the git command - as in `git HERE... COMMAND +REST'. See the manpage `git(1)' for valid arguments. + +Be careful what you add here, especially if you are using Tramp +to connect to servers with ancient Git versions. Never remove +anything that is part of the default value, unless you really +know what you are doing. And think very hard before adding +something; it will be used every time Magit runs Git for any +purpose." + :package-version '(magit . "2.9.0") + :group 'magit-commands + :group 'magit-process + :type '(repeat string)) + +(defcustom magit-prefer-remote-upstream nil + "Whether to favor remote branches when reading the upstream branch. + +This controls whether commands that read a branch from the user +and then set it as the upstream branch, offer a local or a remote +branch as default completion candidate, when they have the choice. + +This affects all commands that use `magit-read-upstream-branch' +or `magit-read-starting-point', which includes most commands +that change the upstream and many that create new branches." + :package-version '(magit . "2.4.2") + :group 'magit-commands + :type 'boolean) + +(defcustom magit-list-refs-namespaces + '("refs/heads" + "refs/remotes" + "refs/tags" + "refs/pullreqs") + "List of ref namespaces considered when reading a ref. + +This controls the order of refs returned by `magit-list-refs', +which is called by functions like `magit-list-branch-names' to +generate the collection of refs." + :package-version '(magit . "3.1.0") + :group 'magit-commands + :type '(repeat string)) + +(defcustom magit-list-refs-sortby nil + "How to sort the ref collection in the prompt. + +This affects commands that read a ref. More specifically, it +controls the order of refs returned by `magit-list-refs', which +is called by functions like `magit-list-branch-names' to generate +the collection of refs. By default, refs are sorted according to +their full refname (i.e., \"refs/...\"). + +Any value accepted by the `--sort' flag of \"git for-each-ref\" can +be used. For example, \"-creatordate\" places refs with more +recent committer or tagger dates earlier in the list. A list of +strings can also be given in order to pass multiple sort keys to +\"git for-each-ref\". + +Note that, depending on the completion framework you use, this +may not be sufficient to change the order in which the refs are +displayed. It only controls the order of the collection passed +to `magit-completing-read' or, for commands that support reading +multiple strings, `read-from-minibuffer'. The completion +framework ultimately determines how the collection is displayed." + :package-version '(magit . "2.11.0") + :group 'magit-miscellaneous + :type '(choice string (repeat string))) + +;;; Git + +(defvar magit-git-debug nil + "Whether to enable additional reporting of git errors. + +Magit basically calls git for one of these two reasons: for +side-effects or to do something with its standard output. + +When git is run for side-effects then its output, including error +messages, go into the process buffer which is shown when using \ +\\<magit-status-mode-map>\\[magit-process-buffer]. + +When git's output is consumed in some way, then it would be too +expensive to also insert it into this buffer, but when this +option is non-nil and git returns with a non-zero exit status, +then at least its standard error is inserted into this buffer. + +This is only intended for debugging purposes. Do not enable this +permanently, that would negatively affect performance. Also note +that just because git exits with a non-zero exit status and prints +an error message that usually doesn't mean that it is an error as +far as Magit is concerned, which is another reason we usually hide +these error messages. Whether some error message is relevant in +the context of some unexpected behavior has to be judged on a case +by case basis. + +The command `magit-toggle-git-debug' changes the value of this +variable. + +Also see `magit-process-extreme-logging'.") + +(defun magit-toggle-git-debug () + "Toggle whether additional git errors are reported. +See info node `(magit)Debugging Tools' for more information." + (interactive) + (setq magit-git-debug (not magit-git-debug)) + (message "Additional reporting of Git errors %s" + (if magit-git-debug "enabled" "disabled"))) + +(defvar magit--refresh-cache nil) + +(defmacro magit--with-refresh-cache (key &rest body) + (declare (indent 1) (debug (form body))) + (let ((k (cl-gensym)) + (hit (cl-gensym))) + `(if magit--refresh-cache + (let ((,k ,key)) + (if-let ((,hit (assoc ,k (cdr magit--refresh-cache)))) + (progn (cl-incf (caar magit--refresh-cache)) + (cdr ,hit)) + (cl-incf (cdar magit--refresh-cache)) + (let ((value ,(macroexp-progn body))) + (push (cons ,k value) + (cdr magit--refresh-cache)) + value))) + ,@body))) + +(defvar magit-with-editor-envvar "GIT_EDITOR" + "The environment variable exported by `magit-with-editor'. +Set this to \"GIT_SEQUENCE_EDITOR\" if you do not want to use +Emacs to edit commit messages but would like to do so to edit +rebase sequences.") + +(defmacro magit-with-editor (&rest body) + "Like `with-editor*' but let-bind some more variables. +Also respect the value of `magit-with-editor-envvar'." + (declare (indent 0) (debug (body))) + `(let ((magit-process-popup-time -1) + ;; The user may have customized `shell-file-name' to + ;; something which results in `w32-shell-dos-semantics' nil + ;; (which changes the quoting style used by + ;; `shell-quote-argument'), but Git for Windows expects shell + ;; quoting in the dos style. + (shell-file-name (if (and (eq system-type 'windows-nt) + ;; If we have Cygwin mount points, + ;; the git flavor is cygwin, so dos + ;; shell quoting is probably wrong. + (not magit-cygwin-mount-points)) + "cmdproxy" + shell-file-name))) + (with-editor* magit-with-editor-envvar + ,@body))) + +(defmacro magit--with-temp-process-buffer (&rest body) + "Like `with-temp-buffer', but always propagate `process-environment'. +When that var is buffer-local in the calling buffer, it is not +propagated by `with-temp-buffer', so we explicitly ensure that +happens, so that processes will be invoked consistently. BODY is +as for that macro." + (declare (indent 0) (debug (body))) + (let ((p (cl-gensym))) + `(let ((,p process-environment)) + (with-temp-buffer + (setq-local process-environment ,p) + ,@body)))) + +(defsubst magit-git-executable () + "Return value of `magit-git-executable' or `magit-remote-git-executable'. +The variable is chosen depending on whether `default-directory' +is remote." + (if (file-remote-p default-directory) + magit-remote-git-executable + magit-git-executable)) + +(defun magit-process-git-arguments (args) + "Prepare ARGS for a function that invokes Git. + +Magit has many specialized functions for running Git; they all +pass arguments through this function before handing them to Git, +to do the following. + +* Flatten ARGS, removing nil arguments. +* Prepend `magit-git-global-arguments' to ARGS. +* On w32 systems, encode to `w32-ansi-code-page'." + (setq args (append magit-git-global-arguments (flatten-tree args))) + (if (and (eq system-type 'windows-nt) (boundp 'w32-ansi-code-page)) + ;; On w32, the process arguments *must* be encoded in the + ;; current code-page (see #3250). + (mapcar (lambda (arg) + (encode-coding-string + arg (intern (format "cp%d" w32-ansi-code-page)))) + args) + args)) + +(defun magit-git-exit-code (&rest args) + "Execute Git with ARGS, returning its exit code." + (magit-process-git nil args)) + +(defun magit-git-success (&rest args) + "Execute Git with ARGS, returning t if its exit code is 0." + (= (magit-git-exit-code args) 0)) + +(defun magit-git-failure (&rest args) + "Execute Git with ARGS, returning t if its exit code is 1." + (= (magit-git-exit-code args) 1)) + +(defun magit-git-string-p (&rest args) + "Execute Git with ARGS, returning the first line of its output. +If the exit code isn't zero or if there is no output, then return +nil. Neither of these results is considered an error; if that is +what you want, then use `magit-git-string-ng' instead. + +This is an experimental replacement for `magit-git-string', and +still subject to major changes." + (magit--with-refresh-cache (cons default-directory args) + (magit--with-temp-process-buffer + (and (zerop (magit-process-git t args)) + (not (bobp)) + (progn + (goto-char (point-min)) + (buffer-substring-no-properties (point) (line-end-position))))))) + +(defun magit-git-string-ng (&rest args) + "Execute Git with ARGS, returning the first line of its output. +If the exit code isn't zero or if there is no output, then that +is considered an error, but instead of actually signaling an +error, return nil. Additionally the output is put in the process +buffer (creating it if necessary) and the error message is shown +in the status buffer (provided it exists). + +This is an experimental replacement for `magit-git-string', and +still subject to major changes. Also see `magit-git-string-p'." + (magit--with-refresh-cache + (list default-directory 'magit-git-string-ng args) + (magit--with-temp-process-buffer + (let* ((args (magit-process-git-arguments args)) + (status (magit-process-git t args))) + (if (zerop status) + (and (not (bobp)) + (progn + (goto-char (point-min)) + (buffer-substring-no-properties + (point) (line-end-position)))) + (let ((buf (current-buffer))) + (with-current-buffer (magit-process-buffer t) + (magit-process-insert-section default-directory + magit-git-executable args + status buf))) + (when-let ((status-buf (magit-get-mode-buffer 'magit-status-mode))) + (let ((msg (magit--locate-error-message))) + (with-current-buffer status-buf + (setq magit-this-error msg)))) + nil))))) + +(defun magit-git-str (&rest args) + "Execute Git with ARGS, returning the first line of its output. +If there is no output, return nil. If the output begins with a +newline, return an empty string. Like `magit-git-string' but +ignore `magit-git-debug'." + (setq args (flatten-tree args)) + (magit--with-refresh-cache (cons default-directory args) + (magit--with-temp-process-buffer + (magit-process-git (list t nil) args) + (unless (bobp) + (goto-char (point-min)) + (buffer-substring-no-properties (point) (line-end-position)))))) + +(defun magit-git-output (&rest args) + "Execute Git with ARGS, returning its output." + (setq args (flatten-tree args)) + (magit--with-refresh-cache (cons default-directory args) + (magit--with-temp-process-buffer + (magit-process-git (list t nil) args) + (buffer-substring-no-properties (point-min) (point-max))))) + +(define-error 'magit-invalid-git-boolean "Not a Git boolean") + +(defun magit-git-true (&rest args) + "Execute Git with ARGS, returning t if it prints \"true\". +If it prints \"false\", then return nil. For any other output +signal `magit-invalid-git-boolean'." + (pcase (magit-git-output args) + ((or "true" "true\n") t) + ((or "false" "false\n") nil) + (output (signal 'magit-invalid-git-boolean (list output))))) + +(defun magit-git-false (&rest args) + "Execute Git with ARGS, returning t if it prints \"false\". +If it prints \"true\", then return nil. For any other output +signal `magit-invalid-git-boolean'." + (pcase (magit-git-output args) + ((or "true" "true\n") nil) + ((or "false" "false\n") t) + (output (signal 'magit-invalid-git-boolean (list output))))) + +(defun magit-git-config-p (variable &optional default) + "Return the boolean value of the Git variable VARIABLE. +VARIABLE has to be specified as a string. Return DEFAULT (which +defaults to nil) if VARIABLE is unset. If VARIABLE's value isn't +a boolean, then raise an error." + (let ((args (list "config" "--bool" "--default" (if default "true" "false") + variable))) + (magit--with-refresh-cache (cons default-directory args) + (magit--with-temp-process-buffer + (let ((status (magit-process-git t args)) + (output (buffer-substring (point-min) (1- (point-max))))) + (if (zerop status) + (equal output "true") + (signal 'magit-invalid-git-boolean (list output)))))))) + +(defun magit-git-insert (&rest args) + "Execute Git with ARGS, inserting its output at point. +If Git exits with a non-zero exit status, then show a message and +add a section in the respective process buffer." + (apply #'magit--git-insert nil args)) + +(defun magit--git-insert (return-error &rest args) + (setq args (magit-process-git-arguments args)) + (if (or return-error magit-git-debug) + (let (log) + (unwind-protect + (let (exit errmsg) + (setq log (make-temp-file "magit-stderr")) + (delete-file log) + (setq exit (magit-process-git (list t log) args)) + (when (> exit 0) + (when (file-exists-p log) + (with-temp-buffer + (insert-file-contents log) + (goto-char (point-max)) + (setq errmsg + (if (functionp magit-git-debug) + (funcall magit-git-debug (buffer-string)) + (magit--locate-error-message)))) + (unless return-error + (let ((magit-git-debug nil)) + (with-current-buffer (magit-process-buffer t) + (magit-process-insert-section default-directory + magit-git-executable + args exit log))))) + (unless return-error + (if errmsg + (message "%s" errmsg) + (message "Git returned with exit-code %s" exit)))) + (or errmsg exit)) + (ignore-errors (delete-file log)))) + (magit-process-git (list t nil) args))) + +(defun magit--locate-error-message () + (goto-char (point-max)) + (and (run-hook-wrapped 'magit-process-error-message-regexps + (lambda (re) (re-search-backward re nil t))) + (match-string-no-properties 1))) + +(defun magit-git-string (&rest args) + "Execute Git with ARGS, returning the first line of its output. +If there is no output, return nil. If the output begins with a +newline, return an empty string." + (setq args (flatten-tree args)) + (magit--with-refresh-cache (cons default-directory args) + (magit--with-temp-process-buffer + (apply #'magit-git-insert args) + (unless (bobp) + (goto-char (point-min)) + (buffer-substring-no-properties (point) (line-end-position)))))) + +(defun magit-git-lines (&rest args) + "Execute Git with ARGS, returning its output as a list of lines. +Empty lines anywhere in the output are omitted. + +If Git exits with a non-zero exit status, then report show a +message and add a section in the respective process buffer." + (magit--with-temp-process-buffer + (apply #'magit-git-insert args) + (split-string (buffer-string) "\n" t))) + +(defun magit-git-items (&rest args) + "Execute Git with ARGS, returning its null-separated output as a list. +Empty items anywhere in the output are omitted. + +If Git exits with a non-zero exit status, then report show a +message and add a section in the respective process buffer." + (magit--with-temp-process-buffer + (apply #'magit-git-insert args) + (split-string (buffer-string) "\0" t))) + +(defvar magit--git-wash-keep-error nil) ; experimental + +(defun magit-git-wash (washer &rest args) + "Execute Git with ARGS, inserting washed output at point. +Actually first insert the raw output at point. If there is no +output, call `magit-cancel-section'. Otherwise temporarily narrow +the buffer to the inserted text, move to its beginning, and then +call function WASHER with ARGS as its sole argument." + (declare (indent 1)) + (apply #'magit--git-wash washer magit--git-wash-keep-error args)) + +(defun magit--git-wash (washer keep-error &rest args) + (declare (indent 2)) + (setq args (flatten-tree args)) + (let ((beg (point)) + (exit (magit--git-insert keep-error args))) + (when (stringp exit) + (goto-char beg) + (insert (propertize exit 'face 'error)) + (unless (bolp) + (insert "\n"))) + (if (= (point) beg) + (magit-cancel-section) + (unless (bolp) + (insert "\n")) + (when (or (equal exit 0) + (eq keep-error 'wash-anyway)) + (save-restriction + (narrow-to-region beg (point)) + (goto-char beg) + (funcall washer args)) + (when (or (= (point) beg) + (= (point) (1+ beg))) + (magit-cancel-section)) + (magit-maybe-make-margin-overlay))) + exit)) + +(defun magit-git-executable-find (command) + "Search for COMMAND in Git's exec path, falling back to `exec-path'. +Like `executable-find', return the absolute file name of the +executable." + (or (locate-file command + (list (concat + (file-remote-p default-directory) + (or (magit-git-string "--exec-path") + (error "`git --exec-path' failed")))) + exec-suffixes + #'file-executable-p) + (compat-call executable-find command t))) + +;;; Git Version + +(defconst magit--git-version-regexp + "\\`git version \\([0-9]+\\(\\.[0-9]+\\)\\{1,2\\}\\)") + +(defvar magit--host-git-version-cache nil) + +(defun magit-git-version>= (n) + "Return t if `magit-git-version's value is greater than or equal to N." + (magit--version>= (magit-git-version) n)) + +(defun magit-git-version< (n) + "Return t if `magit-git-version's value is smaller than N." + (version< (magit-git-version) n)) + +(defun magit-git-version () + "Return the Git version used for `default-directory'. +Raise an error if Git cannot be found, if it exits with a +non-zero status, or the output does not have the expected +format." + (magit--with-refresh-cache default-directory + (let ((host (file-remote-p default-directory))) + (or (cdr (assoc host magit--host-git-version-cache)) + (magit--with-temp-process-buffer + ;; Unset global arguments for ancient Git versions. + (let* ((magit-git-global-arguments nil) + (status (magit-process-git t "version")) + (output (buffer-string))) + (cond + ((not (zerop status)) + (display-warning + 'magit + (format "%S\n\nRunning \"%s --version\" failed with output:\n\n%s" + (if host + (format "Magit cannot find Git on host %S.\n +Check the value of `magit-remote-git-executable' using +`magit-debug-git-executable' and consult the info node +`(tramp)Remote programs'." host) + "Magit cannot find Git.\n +Check the values of `magit-git-executable' and `exec-path' +using `magit-debug-git-executable'.") + (magit-git-executable) + output))) + ((save-match-data + (and (string-match magit--git-version-regexp output) + (let ((version (match-string 1 output))) + (push (cons host version) + magit--host-git-version-cache) + version)))) + ((error "Unexpected \"%s --version\" output: %S" + (magit-git-executable) + output))))))))) + +(defun magit-git-version-assert (&optional minimal who) + "Assert that the used Git version is greater than or equal to MINIMAL. +If optional MINIMAL is nil, compare with `magit--minimal-git' +instead. Optional WHO if non-nil specifies what functionality +needs at least MINIMAL, otherwise it defaults to \"Magit\"." + (when (magit-git-version< (or minimal magit--minimal-git)) + (let* ((host (file-remote-p default-directory)) + (msg (format-spec + (cond (host "\ +%w requires Git %m or greater, but on %h the version is %v. + +If multiple Git versions are installed on the host, then the +problem might be that TRAMP uses the wrong executable. + +Check the value of `magit-remote-git-executable' and consult +the info node `(tramp)Remote programs'.\n") + (t "\ +%w requires Git %m or greater, but you are using %v. + +If you have multiple Git versions installed, then check the +values of `magit-remote-git-executable' and `exec-path'.\n")) + `((?w . ,(or who "Magit")) + (?m . ,(or minimal magit--minimal-git)) + (?v . ,(magit-git-version)) + (?h . ,host))))) + (display-warning 'magit msg :error)))) + +(defun magit--safe-git-version () + "Return the Git version used for `default-directory' or an error message." + (magit--with-temp-process-buffer + (let* ((magit-git-global-arguments nil) + (status (magit-process-git t "version")) + (output (buffer-string))) + (cond ((not (zerop status)) output) + ((save-match-data + (and (string-match magit--git-version-regexp output) + (match-string 1 output)))) + (t output))))) + +(defun magit-debug-git-executable () + "Display a buffer with information about `magit-git-executable'. +Also include information about `magit-remote-git-executable'. +See info node `(magit)Debugging Tools' for more information." + (interactive) + (with-current-buffer (get-buffer-create "*magit-git-debug*") + (pop-to-buffer (current-buffer)) + (erase-buffer) + (insert (format "magit-remote-git-executable: %S\n" + magit-remote-git-executable)) + (insert (concat + (format "magit-git-executable: %S" magit-git-executable) + (and (not (file-name-absolute-p magit-git-executable)) + (format " [%S]" (executable-find magit-git-executable))) + (format " (%s)\n" (magit--safe-git-version)))) + (insert (format "exec-path: %S\n" exec-path)) + (when-let ((diff (cl-set-difference + (seq-filter #'file-exists-p (remq nil (parse-colon-path + (getenv "PATH")))) + (seq-filter #'file-exists-p (remq nil exec-path)) + :test #'file-equal-p))) + (insert (format " entries in PATH, but not in exec-path: %S\n" diff))) + (dolist (execdir exec-path) + (insert (format " %s (%s)\n" execdir (car (file-attributes execdir)))) + (when (file-directory-p execdir) + (dolist (exec (directory-files + execdir t (concat + "\\`git" (regexp-opt exec-suffixes) "\\'"))) + (insert (format " %s (%s)\n" exec + (magit--safe-git-version)))))))) + +;;; Variables + +(defun magit-config-get-from-cached-list (key) + (gethash + ;; `git config --list' downcases first and last components of the key. + (let* ((key (replace-regexp-in-string "\\`[^.]+" #'downcase key t t)) + (key (replace-regexp-in-string "[^.]+\\'" #'downcase key t t))) + key) + (magit--with-refresh-cache (cons (magit-toplevel) 'config) + (let ((configs (make-hash-table :test #'equal))) + (dolist (conf (magit-git-items "config" "--list" "-z")) + (let* ((nl-pos (cl-position ?\n conf)) + (key (substring conf 0 nl-pos)) + (val (if nl-pos (substring conf (1+ nl-pos)) ""))) + (puthash key (nconc (gethash key configs) (list val)) configs))) + configs)))) + +(defun magit-get (&rest keys) + "Return the value of the Git variable specified by KEYS." + (car (last (apply #'magit-get-all keys)))) + +(defun magit-get-all (&rest keys) + "Return all values of the Git variable specified by KEYS." + (let ((magit-git-debug nil) + (arg (and (or (null (car keys)) + (string-prefix-p "--" (car keys))) + (pop keys))) + (key (string-join keys "."))) + (if (and magit--refresh-cache (not arg)) + (magit-config-get-from-cached-list key) + (magit-git-items "config" arg "-z" "--get-all" "--include" key)))) + +(defun magit-get-boolean (&rest keys) + "Return the boolean value of the Git variable specified by KEYS. +Also see `magit-git-config-p'." + (let ((arg (and (or (null (car keys)) + (string-prefix-p "--" (car keys))) + (pop keys))) + (key (string-join keys "."))) + (equal (if magit--refresh-cache + (car (last (magit-config-get-from-cached-list key))) + (magit-git-str "config" arg "--bool" "--include" key)) + "true"))) + +(defun magit-set (value &rest keys) + "Set the value of the Git variable specified by KEYS to VALUE." + (let ((arg (and (or (null (car keys)) + (string-prefix-p "--" (car keys))) + (pop keys))) + (key (string-join keys "."))) + (if value + (magit-git-success "config" arg key value) + (magit-git-success "config" arg "--unset" key)) + value)) + +(gv-define-setter magit-get (val &rest keys) + `(magit-set ,val ,@keys)) + +(defun magit-set-all (values &rest keys) + "Set all values of the Git variable specified by KEYS to VALUES." + (let ((arg (and (or (null (car keys)) + (string-prefix-p "--" (car keys))) + (pop keys))) + (var (string-join keys "."))) + (when (magit-get var) + (magit-call-git "config" arg "--unset-all" var)) + (dolist (v values) + (magit-call-git "config" arg "--add" var v)))) + +;;; Files + +(defun magit--safe-default-directory (&optional file) + (catch 'unsafe-default-dir + (let ((dir (file-name-as-directory + (expand-file-name (or file default-directory)))) + (previous nil)) + (while (not (file-accessible-directory-p dir)) + (setq dir (file-name-directory (directory-file-name dir))) + (when (equal dir previous) + (throw 'unsafe-default-dir nil)) + (setq previous dir)) + dir))) + +(defmacro magit--with-safe-default-directory (file &rest body) + (declare (indent 1) (debug (form body))) + `(when-let ((default-directory (magit--safe-default-directory ,file))) + ,@body)) + +(defun magit-git-dir (&optional path) + "Like (expand-file-name PATH (magit-gitdir)) or just (magit-gitdir)." + (declare (obsolete 'magit-gitdir "Magit 4.0.0")) + (and-let* ((dir (magit-gitdir))) + (if path + (expand-file-name (convert-standard-filename path) dir) + dir))) + +(defun magit-gitdir (&optional directory) + "Return the absolute and resolved path of the .git directory. + +If the `GIT_DIR' environment variable is defined, return that. +Otherwise return the .git directory for DIRECTORY, or if that is +nil, then for `default-directory' instead. If the directory is +not located inside a Git repository, then return nil." + (let ((default-directory (or directory default-directory))) + (magit--with-refresh-cache (list default-directory 'magit-gitdir) + (magit--with-safe-default-directory nil + (and-let* + ((dir (magit-rev-parse-safe "--git-dir")) + (dir (file-name-as-directory (magit-expand-git-file-name dir)))) + (if (file-remote-p dir) + dir + (concat (file-remote-p default-directory) dir))))))) + +(defvar magit--separated-gitdirs nil) + +(defun magit--record-separated-gitdir () + (let ((topdir (magit-toplevel)) + (gitdir (magit-gitdir))) + ;; Kludge: git-annex converts submodule gitdirs to symlinks. See #3599. + (when (file-symlink-p (directory-file-name gitdir)) + (setq gitdir (file-truename gitdir))) + ;; We want to delete the entry for `topdir' here, rather than within + ;; (unless ...), in case a `--separate-git-dir' repository was switched to + ;; the standard structure (i.e., "topdir/.git/"). + (setq magit--separated-gitdirs (cl-delete topdir + magit--separated-gitdirs + :key #'car :test #'equal)) + (unless (equal (file-name-as-directory (expand-file-name ".git" topdir)) + gitdir) + (push (cons topdir gitdir) magit--separated-gitdirs)))) + +(defun magit-toplevel (&optional directory) + "Return the absolute path to the toplevel of the current repository. + +From within the working tree or control directory of a repository +return the absolute path to the toplevel directory of the working +tree. As a special case, from within a bare repository return +the control directory instead. When called outside a repository +then return nil. + +When optional DIRECTORY is non-nil then return the toplevel for +that directory instead of the one for `default-directory'. + +Try to respect the option `find-file-visit-truename', i.e., when +the value of that option is nil, then avoid needlessly returning +the truename. When a symlink to a sub-directory of the working +tree is involved, or when called from within a sub-directory of +the gitdir or from the toplevel of a gitdir, which itself is not +located within the working tree, then it is not possible to avoid +returning the truename." + (or + (magit--with-refresh-cache + (cons (or directory default-directory) 'magit-toplevel) + (magit--with-safe-default-directory directory + (if-let ((topdir (magit-rev-parse-safe "--show-toplevel"))) + (let (updir) + (setq topdir (magit-expand-git-file-name topdir)) + (cond + ((and + ;; Always honor these settings. + (not find-file-visit-truename) + (not (getenv "GIT_WORK_TREE")) + ;; `--show-cdup' is the relative path to the toplevel + ;; from `(file-truename default-directory)'. Here we + ;; pretend it is relative to `default-directory', and + ;; go to that directory. Then we check whether + ;; `--show-toplevel' still returns the same value and + ;; whether `--show-cdup' now is the empty string. If + ;; both is the case, then we are at the toplevel of + ;; the same working tree, but also avoided needlessly + ;; following any symlinks. + (progn + (setq updir (file-name-as-directory + (magit-rev-parse-safe "--show-cdup"))) + (setq updir (if (file-name-absolute-p updir) + (concat (file-remote-p default-directory) + updir) + (expand-file-name updir))) + (and-let* + ((default-directory updir) + (top (and (string-equal + (magit-rev-parse-safe "--show-cdup") "") + (magit-rev-parse-safe "--show-toplevel")))) + (string-equal (magit-expand-git-file-name top) topdir)))) + updir) + ((concat (file-remote-p default-directory) + (file-name-as-directory topdir))))) + (and-let* ((gitdir (magit-rev-parse-safe "--git-dir")) + (gitdir (file-name-as-directory + (if (file-name-absolute-p gitdir) + ;; We might have followed a symlink. + (concat (file-remote-p default-directory) + (magit-expand-git-file-name gitdir)) + (expand-file-name gitdir))))) + (if (magit-bare-repo-p) + gitdir + (let* ((link (expand-file-name "gitdir" gitdir)) + (wtree (and (file-exists-p link) + (magit-file-line link)))) + (cond + ((and wtree + ;; Ignore .git/gitdir files that result from a + ;; Git bug. See #2364. + (not (equal wtree ".git"))) + ;; Return the linked working tree. + (concat (file-remote-p default-directory) + (file-name-directory wtree))) + ;; The working directory may not be the parent + ;; directory of .git if it was set up with + ;; "git init --separate-git-dir". See #2955. + ((car (rassoc gitdir magit--separated-gitdirs))) + (;; Step outside the control directory to enter the + ;; working tree. + (file-name-directory (directory-file-name gitdir)))))))))))) + +(defun magit--toplevel-safe () + (or (magit-toplevel) + (magit--not-inside-repository-error))) + +(defmacro magit-with-toplevel (&rest body) + (declare (indent defun) (debug (body))) + `(let ((default-directory (magit--toplevel-safe))) + ,@body)) + +(define-error 'magit-outside-git-repo "Not inside Git repository") +(define-error 'magit-corrupt-git-config "Corrupt Git configuration") +(define-error 'magit-git-executable-not-found + (concat "Git executable cannot be found " + "(see https://magit.vc/goto/e6a78ed2)")) + +(defun magit--assert-usable-git () + (if (not (compat-call executable-find (magit-git-executable) t)) + (signal 'magit-git-executable-not-found (magit-git-executable)) + (let ((magit-git-debug + (lambda (err) + (signal 'magit-corrupt-git-config + (format "%s: %s" default-directory err))))) + ;; This should always succeed unless there's a corrupt config + ;; (or at least a similarly severe failing state). Note that + ;; git-config's --default is avoided because it's not available + ;; until Git 2.18. + (magit-git-string "config" "--get-color" "" "reset")) + nil)) + +(defun magit--not-inside-repository-error () + (magit--assert-usable-git) + (signal 'magit-outside-git-repo default-directory)) + +(defun magit-inside-gitdir-p (&optional noerror) + "Return t if `default-directory' is below the repository directory. +If it is below the working directory, then return nil. +If it isn't below either, then signal an error unless NOERROR +is non-nil, in which case return nil." + (and (magit--assert-default-directory noerror) + ;; Below a repository directory that is not located below the + ;; working directory "git rev-parse --is-inside-git-dir" prints + ;; "false", which is wrong. + (let ((gitdir (magit-gitdir))) + (cond (gitdir (file-in-directory-p default-directory gitdir)) + (noerror nil) + ((signal 'magit-outside-git-repo default-directory)))))) + +(defun magit-inside-worktree-p (&optional noerror) + "Return t if `default-directory' is below the working directory. +If it is below the repository directory, then return nil. +If it isn't below either, then signal an error unless NOERROR +is non-nil, in which case return nil." + (and (magit--assert-default-directory noerror) + (condition-case nil + (magit-rev-parse-true "--is-inside-work-tree") + (magit-invalid-git-boolean + (and (not noerror) + (signal 'magit-outside-git-repo default-directory)))))) + +(cl-defgeneric magit-bare-repo-p (&optional noerror) + "Return t if the current repository is bare. +If it is non-bare, then return nil. If `default-directory' +isn't below a Git repository, then signal an error unless +NOERROR is non-nil, in which case return nil." + (and (magit--assert-default-directory noerror) + (condition-case nil + (magit-rev-parse-true "--is-bare-repository") + (magit-invalid-git-boolean + (and (not noerror) + (signal 'magit-outside-git-repo default-directory)))))) + +(defun magit--assert-default-directory (&optional noerror) + (or (file-directory-p default-directory) + (and (not noerror) + (let ((exists (file-exists-p default-directory))) + (signal (if exists 'file-error 'file-missing) + (list "Running git in directory" + (if exists + "Not a directory" + "No such file or directory") + default-directory)))))) + +(defun magit-git-repo-p (directory &optional non-bare) + "Return t if DIRECTORY is a Git repository. +When optional NON-BARE is non-nil also return nil if DIRECTORY is +a bare repository." + (and (file-directory-p directory) ; Avoid archives, see #3397. + (or (file-regular-p (expand-file-name ".git" directory)) + (file-directory-p (expand-file-name ".git" directory)) + (and (not non-bare) + (file-regular-p (expand-file-name "HEAD" directory)) + (file-directory-p (expand-file-name "refs" directory)) + (file-directory-p (expand-file-name "objects" directory)))))) + +(defun magit-file-relative-name (&optional file tracked) + "Return the path of FILE relative to the repository root. + +If optional FILE is nil or omitted, return the relative path of +the file being visited in the current buffer, if any, else nil. +If the file is not inside a Git repository, then return nil. + +If TRACKED is non-nil, return the path only if it matches a +tracked file." + (unless file + (with-current-buffer (or (buffer-base-buffer) + (current-buffer)) + (setq file (or magit-buffer-file-name buffer-file-name + (and (derived-mode-p 'dired-mode) default-directory))))) + (when (and file (or (not tracked) + (magit-file-tracked-p (file-relative-name file)))) + (and-let* ((dir (magit-toplevel + (magit--safe-default-directory + (directory-file-name (file-name-directory file)))))) + (file-relative-name file dir)))) + +(defun magit-file-ignored-p (file) + (magit-git-string-p "ls-files" "--others" "--ignored" "--exclude-standard" + "--" (magit-convert-filename-for-git file))) + +(defun magit-file-tracked-p (file) + (magit-git-success "ls-files" "--error-unmatch" + "--" (magit-convert-filename-for-git file))) + +(defun magit-list-files (&rest args) + (apply #'magit-git-items "ls-files" "-z" "--full-name" args)) + +(defun magit-tracked-files () + (magit-list-files "--cached")) + +(defun magit-untracked-files (&optional all files compact) + (if compact + (--mapcat (and (eq (aref it 0) ??) + (list (substring it 3))) + (magit-git-items "status" "-z" "--porcelain" + (magit-ignore-submodules-p t) + "--" files)) + (magit-list-files "--other" + (and (not all) "--exclude-standard") + "--" files))) + +(defun magit-modified-files (&optional nomodules files) + (magit-git-items "diff-index" "-z" "--name-only" + ;; Work around a bug in Git v2.46.0. See #5212 and #5221. + (if nomodules "--ignore-submodules" "--submodule=short") + (magit-headish) "--" files)) + +(defun magit-unstaged-files (&optional nomodules files) + (magit-git-items "diff-files" "-z" "--name-only" "--diff-filter=u" + ;; Work around a bug in Git v2.46.0. See #5212 and #5221. + (if nomodules "--ignore-submodules" "--submodule=short") + "--" files)) + +(defun magit-staged-files (&optional nomodules files) + (magit-git-items "diff-index" "-z" "--name-only" "--cached" + ;; Work around a bug in Git v2.46.0. See #5212 and #5221. + (if nomodules "--ignore-submodules" "--submodule=short") + (magit-headish) "--" files)) + +(defun magit-binary-files (&rest args) + (--mapcat (and (string-match "^-\t-\t\\(.+\\)" it) + (list (match-string 1 it))) + (apply #'magit-git-items + "diff" "-z" "--numstat" "--ignore-submodules" + args))) + +(defun magit-unmerged-files () + (magit-git-items "diff-files" "-z" "--name-only" "--diff-filter=U")) + +(defun magit-ignored-files () + (magit-git-items "ls-files" "-z" "--others" "--ignored" + "--exclude-standard" "--directory")) + +(defun magit-stashed-files (stash) + (magit-git-items "stash" "show" "-z" "--name-only" stash)) + +(defun magit-skip-worktree-files () + (--keep (and (= (aref it 0) ?S) + (substring it 2)) + (magit-list-files "-t"))) + +(defun magit-assume-unchanged-files () + (--keep (and (memq (aref it 0) '(?h ?s ?m ?r ?c ?k)) + (substring it 2)) + (magit-list-files "-v"))) + +(defun magit-revision-files (rev) + (magit-with-toplevel + (magit-git-items "ls-tree" "-z" "-r" "--name-only" rev))) + +(defun magit-revision-directories (rev) + "List directories that contain a tracked file in revision REV." + (magit-with-toplevel + (mapcar #'file-name-as-directory + (magit-git-items "ls-tree" "-z" "-r" "-d" "--name-only" rev)))) + +(defun magit-changed-files (rev-or-range &optional other-rev) + "Return list of files the have changed between two revisions. +If OTHER-REV is non-nil, REV-OR-RANGE should be a revision, not a +range. Otherwise, it can be any revision or range accepted by +\"git diff\" (i.e., <rev>, <revA>..<revB>, or <revA>...<revB>)." + (magit-with-toplevel + (magit-git-items "diff" "-z" "--name-only" rev-or-range other-rev))) + +(defun magit-renamed-files (revA revB) + (mapcar (pcase-lambda (`(,_status ,fileA ,fileB)) + (cons fileA fileB)) + (seq-partition (magit-git-items "diff" "-z" "--name-status" + "--find-renames" + "--diff-filter=R" revA revB) + 3))) + +(defun magit--rev-file-name (file rev other-rev) + "For FILE, potentially renamed between REV and OTHER-REV, return name in REV. +Return nil, if FILE appears neither in REV nor OTHER-REV, +or if no rename is detected." + (or (car (member file (magit-revision-files rev))) + (and-let* ((renamed (magit-renamed-files rev other-rev))) + (car (rassoc file renamed))))) + +(defun magit-file-status (&rest args) + (magit--with-temp-process-buffer + (save-excursion (magit-git-insert "status" "-z" args)) + (let ((pos (point)) status) + (while (> (skip-chars-forward "[:print:]") 0) + (let ((x (char-after pos)) + (y (char-after (1+ pos))) + (file (buffer-substring (+ pos 3) (point)))) + (forward-char) + (if (memq x '(?R ?C)) + (progn + (setq pos (point)) + (skip-chars-forward "[:print:]") + (push (list file (buffer-substring pos (point)) x y) status) + (forward-char)) + (push (list file nil x y) status))) + (setq pos (point))) + status))) + +(defcustom magit-cygwin-mount-points + (and (eq system-type 'windows-nt) + (cl-sort (--map (if (string-match "^\\(.*\\) on \\(.*\\) type" it) + (cons (file-name-as-directory (match-string 2 it)) + (file-name-as-directory (match-string 1 it))) + (lwarn '(magit) :error + "Failed to parse Cygwin mount: %S" it)) + ;; If --exec-path is not a native Windows path, + ;; then we probably have a cygwin git. + (let ((process-environment + (append magit-git-environment + process-environment))) + (and (not (string-match-p + "\\`[a-zA-Z]:" + (car (process-lines + magit-git-executable "--exec-path")))) + (ignore-errors (process-lines "mount"))))) + #'> :key (pcase-lambda (`(,cyg . ,_win)) (length cyg)))) + "Alist of (CYGWIN . WIN32) directory names. +Sorted from longest to shortest CYGWIN name." + :package-version '(magit . "2.3.0") + :group 'magit-process + :type '(alist :key-type string :value-type directory)) + +(defun magit-expand-git-file-name (filename) + (unless (file-name-absolute-p filename) + (setq filename (expand-file-name filename))) + (if-let ((cyg:win (and (not (file-remote-p default-directory)) ; see #4976 + (cl-assoc filename magit-cygwin-mount-points + :test (lambda (f cyg) (string-prefix-p cyg f)))))) + (concat (cdr cyg:win) + (substring filename (length (car cyg:win)))) + filename)) + +(defun magit-convert-filename-for-git (filename) + "Convert FILENAME so that it can be passed to git. +1. If it is a absolute filename, then pass it through + `expand-file-name' to replace things such as \"~/\" that + Git does not understand. +2. If it is a remote filename, then remove the remote part. +3. Deal with an `windows-nt' Emacs vs. Cygwin Git incompatibility." + (if (file-name-absolute-p filename) + (if-let ((cyg:win (cl-rassoc filename magit-cygwin-mount-points + :test (lambda (f win) (string-prefix-p win f))))) + (concat (car cyg:win) + (substring filename (length (cdr cyg:win)))) + (let ((expanded (expand-file-name filename))) + (or (file-remote-p expanded 'localname) + expanded))) + filename)) + +(defun magit-decode-git-path (path) + (if (eq (aref path 0) ?\") + (decode-coding-string (read path) + (or magit-git-output-coding-system + (car default-process-coding-system)) + t) + path)) + +(defun magit-file-at-point (&optional expand assert) + (if-let ((file (magit-section-case + (file (oref it value)) + (hunk (magit-section-parent-value it))))) + (if expand + (expand-file-name file (magit-toplevel)) + file) + (when assert + (user-error "No file at point")))) + +(defun magit-current-file () + (or (magit-file-relative-name) + (magit-file-at-point) + (and (derived-mode-p 'magit-log-mode) + (car magit-buffer-log-files)))) + +;;; Predicates + +(defun magit-no-commit-p () + "Return t if there is no commit in the current Git repository." + (not (magit-rev-verify "HEAD"))) + +(defun magit-merge-commit-p (commit) + "Return t if COMMIT is a merge commit." + (length> (magit-commit-parents commit) 1)) + +(defun magit-anything-staged-p (&optional ignore-submodules &rest files) + "Return t if there are any staged changes. +If optional FILES is non-nil, then only changes to those files +are considered." + (magit-git-failure "diff" "--quiet" "--cached" + (if ignore-submodules + "--ignore-submodules" + ;; Work around a bug in Git v2.46.0. See #5212 and #5221. + "--submodule=short") + "--" files)) + +(defun magit-anything-unstaged-p (&optional ignore-submodules &rest files) + "Return t if there are any unstaged changes. +If optional FILES is non-nil, then only changes to those files +are considered." + (magit-git-failure "diff" "--quiet" + (if ignore-submodules + "--ignore-submodules" + ;; Work around a bug in Git v2.46.0. See #5212 and #5221. + "--submodule=short") + "--" files)) + +(defun magit-anything-modified-p (&optional ignore-submodules &rest files) + "Return t if there are any staged or unstaged changes. +If optional FILES is non-nil, then only changes to those files +are considered." + (or (apply #'magit-anything-staged-p ignore-submodules files) + (apply #'magit-anything-unstaged-p ignore-submodules files))) + +(defun magit-anything-unmerged-p (&rest files) + "Return t if there are any merge conflicts. +If optional FILES is non-nil, then only conflicts in those files +are considered." + (and (magit-git-string "ls-files" "--unmerged" files) t)) + +(defun magit-module-worktree-p (module) + (magit-with-toplevel + (file-exists-p (expand-file-name ".git" module)))) + +(defun magit-module-no-worktree-p (module) + (not (magit-module-worktree-p module))) + +(defun magit-ignore-submodules-p (&optional return-argument) + (or (cl-find-if (lambda (arg) + (string-prefix-p "--ignore-submodules" arg)) + magit-buffer-diff-args) + (and-let* ((value (magit-get "diff.ignoreSubmodules"))) + (if return-argument + (concat "--ignore-submodules=" value) + (concat "diff.ignoreSubmodules=" value))))) + +;;; Revisions and References + +(defun magit-rev-parse (&rest args) + "Execute `git rev-parse ARGS', returning first line of output. +If there is no output, return nil." + (apply #'magit-git-string "rev-parse" args)) + +(defun magit-rev-parse-safe (&rest args) + "Execute `git rev-parse ARGS', returning first line of output. +If there is no output, return nil. Like `magit-rev-parse' but +ignore `magit-git-debug'." + (apply #'magit-git-str "rev-parse" args)) + +(defun magit-rev-parse-true (&rest args) + "Execute `git rev-parse ARGS', returning t if it prints \"true\". +If it prints \"false\", then return nil. For any other output +signal an error." + (magit-git-true "rev-parse" args)) + +(defun magit-rev-parse-false (&rest args) + "Execute `git rev-parse ARGS', returning t if it prints \"false\". +If it prints \"true\", then return nil. For any other output +signal an error." + (magit-git-false "rev-parse" args)) + +(defun magit-rev-parse-p (&rest args) + "Execute `git rev-parse ARGS', returning t if it prints \"true\". +Return t if the first (and usually only) output line is the +string \"true\", otherwise return nil." + (equal (magit-git-str "rev-parse" args) "true")) + +(defun magit-rev-verify (rev) + (magit-git-string-p "rev-parse" "--verify" rev)) + +(defun magit-commit-p (rev) + "Return full hash for REV if it names an existing commit." + (magit-rev-verify (magit--rev-dereference rev))) + +(defalias 'magit-rev-verify-commit #'magit-commit-p) + +(defalias 'magit-rev-hash #'magit-commit-p) + +(defun magit--rev-dereference (rev) + "Return a rev that forces Git to interpret REV as a commit. +If REV is nil or has the form \":/TEXT\", return REV itself." + (cond ((not rev) nil) + ((string-match-p "^:/" rev) rev) + ((concat rev "^{commit}")))) + +(defun magit-rev-equal (a b) + "Return t if there are no differences between the commits A and B." + (magit-git-success "diff" "--quiet" a b)) + +(defun magit-rev-eq (a b) + "Return t if A and B refer to the same commit." + (let ((a (magit-commit-p a)) + (b (magit-commit-p b))) + (and a b (equal a b)))) + +(defun magit-rev-ancestor-p (a b) + "Return non-nil if commit A is an ancestor of commit B." + (magit-git-success "merge-base" "--is-ancestor" a b)) + +(defun magit-rev-head-p (rev) + (or (equal rev "HEAD") + (and rev + (not (string-search ".." rev)) + (equal (magit-rev-parse rev) + (magit-rev-parse "HEAD"))))) + +(defun magit-rev-author-p (rev) + "Return t if the user is the author of REV. +More precisely return t if `user.name' is equal to the author +name of REV and/or `user.email' is equal to the author email +of REV." + (or (equal (magit-get "user.name") (magit-rev-format "%an" rev)) + (equal (magit-get "user.email") (magit-rev-format "%ae" rev)))) + +(defun magit-rev-name (rev &optional pattern not-anchored) + "Return a symbolic name for REV using `git-name-rev'. + +PATTERN can be used to limit the result to a matching ref. +Unless NOT-ANCHORED is non-nil, the beginning of the ref must +match PATTERN. + +An anchored lookup is done using the arguments +\"--exclude=*/<PATTERN> --exclude=*/HEAD\" in addition to +\"--refs=<PATTERN>\", provided at least version v2.13 of Git is +used. Older versions did not support the \"--exclude\" argument. +When \"--exclude\" cannot be used and `git-name-rev' returns a +ref that should have been excluded, then that is discarded and +this function returns nil instead. This is unfortunate because +there might be other refs that do match. To fix that, update +Git." + (if (magit-git-version< "2.13") + (and-let* + ((ref (magit-git-string "name-rev" "--name-only" "--no-undefined" + (and pattern (concat "--refs=" pattern)) + rev))) + (if (and pattern + (string-match-p "\\`refs/[^/]+/\\*\\'" pattern)) + (let ((namespace (substring pattern 0 -1))) + (and (not (or (string-suffix-p "HEAD" ref) + (and (string-match-p namespace ref) + (not (magit-rev-verify + (concat namespace ref)))))) + ref)) + ref)) + (magit-git-string "name-rev" "--name-only" "--no-undefined" + (and pattern (concat "--refs=" pattern)) + (and pattern + (not not-anchored) + (list "--exclude=*/HEAD" + (concat "--exclude=*/" pattern))) + rev))) + +(defun magit-rev-branch (rev) + (and-let* ((name (magit-rev-name rev "refs/heads/*"))) + (and (not (string-match-p "[~^]" name)) name))) + +(defun magit-rev-fixup-target (rev) + (let ((msg (magit-rev-format "%s" rev))) + (save-match-data + (and (string-match "\\`\\(fixup\\|squash\\)! \\(.+\\)" msg) + (magit-rev-format + "%h" (format "%s^{/^%s}" rev + (magit--ext-regexp-quote (match-string 2 msg)))))))) + +(defun magit-get-shortname (rev) + (let* ((fn (apply-partially #'magit-rev-name rev)) + (name (or (funcall fn "refs/tags/*") + (funcall fn "refs/heads/*") + (funcall fn "refs/remotes/*")))) + (cond ((not name) + (magit-rev-parse "--short" rev)) + ((string-match "^\\(?:tags\\|remotes\\)/\\(.+\\)" name) + (if (magit-ref-ambiguous-p (match-string 1 name)) + name + (match-string 1 name))) + ((magit-ref-maybe-qualify name))))) + +(defun magit-name-branch (rev &optional lax) + (or (magit-name-local-branch rev) + (magit-name-remote-branch rev) + (and lax (or (magit-name-local-branch rev t) + (magit-name-remote-branch rev t))))) + +(defun magit-name-local-branch (rev &optional lax) + (and-let* ((name (magit-rev-name rev "refs/heads/*"))) + (and (or lax (not (string-match-p "[~^]" name))) name))) + +(defun magit-name-remote-branch (rev &optional lax) + (and-let* ((name (magit-rev-name rev "refs/remotes/*"))) + (and (or lax (not (string-match-p "[~^]" name))) + (substring name 8)))) + +(defun magit-name-tag (rev &optional lax) + (and-let* ((name (magit-rev-name rev "refs/tags/*"))) + ;; The progn is necessary to work around debbugs#31840. This, and all + ;; the other instances, can be removed once we require at least Emacs 27. + (progn + (when (string-suffix-p "^0" name) + (setq name (substring name 0 -2))) + (and (or lax (not (string-match-p "[~^]" name))) + (substring name 5))))) + +(defun magit-ref-abbrev (refname) + "Return an unambiguous abbreviation of REFNAME." + (magit-rev-parse "--verify" "--abbrev-ref" refname)) + +(defun magit-ref-fullname (refname) + "Return fully qualified refname for REFNAME. +If REFNAME is ambiguous, return nil." + (magit-rev-parse "--verify" "--symbolic-full-name" refname)) + +(defun magit-ref-ambiguous-p (refname) + (save-match-data + (if (string-match "\\`\\([^^~]+\\)\\(.*\\)" refname) + (not (magit-ref-fullname (match-string 1 refname))) + (error "%S has an unrecognized format" refname)))) + +(defun magit-ref-maybe-qualify (refname &optional prefix) + "If REFNAME is ambiguous, try to disambiguate it by prepend PREFIX to it. +Return an unambiguous refname, either REFNAME or that prefixed +with PREFIX, nil otherwise. If REFNAME has an offset suffix +such as \"~1\", then that is preserved. If optional PREFIX is +nil, then use \"heads/\". " + (if (magit-ref-ambiguous-p refname) + (let ((refname (concat (or prefix "heads/") refname))) + (and (not (magit-ref-ambiguous-p refname)) refname)) + refname)) + +(defun magit-ref-exists-p (ref) + (magit-git-success "show-ref" "--verify" ref)) + +(defun magit-ref-equal (a b) + "Return t if the refnames A and B are `equal'. +A symbolic-ref pointing to some ref, is `equal' to that ref, +as are two symbolic-refs pointing to the same ref. Refnames +may be abbreviated." + (let ((a (magit-ref-fullname a)) + (b (magit-ref-fullname b))) + (and a b (equal a b)))) + +(defun magit-ref-eq (a b) + "Return t if the refnames A and B are `eq'. +A symbolic-ref is `eq' to itself, but not to the ref it points +to, or to some other symbolic-ref that points to the same ref." + (let ((symbolic-a (magit-symbolic-ref-p a)) + (symbolic-b (magit-symbolic-ref-p b))) + (or (and symbolic-a + symbolic-b + (equal a b)) + (and (not symbolic-a) + (not symbolic-b) + (magit-ref-equal a b))))) + +(defun magit-headish () + "Return the `HEAD' or if that doesn't exist the hash of the empty tree." + (if (magit-no-commit-p) + (magit-git-string "mktree") + "HEAD")) + +(defun magit-branch-at-point () + (magit-section-case + (branch (oref it value)) + (commit (or (magit--painted-branch-at-point) + (magit-name-branch (oref it value)))))) + +(defun magit--painted-branch-at-point (&optional type) + (or (and (not (eq type 'remote)) + (memq (get-text-property (magit-point) 'font-lock-face) + (list 'magit-branch-local + 'magit-branch-current)) + (and-let* ((branch (magit-thing-at-point 'git-revision t))) + (cdr (magit-split-branch-name branch)))) + (and (not (eq type 'local)) + (memq (get-text-property (magit-point) 'font-lock-face) + (list 'magit-branch-remote + 'magit-branch-remote-head)) + (thing-at-point 'git-revision t)))) + +(defun magit-local-branch-at-point () + (magit-section-case + (branch (let ((branch (magit-ref-maybe-qualify (oref it value)))) + (when (member branch (magit-list-local-branch-names)) + branch))) + (commit (or (magit--painted-branch-at-point 'local) + (magit-name-local-branch (oref it value)))))) + +(defun magit-remote-branch-at-point () + (magit-section-case + (branch (let ((branch (oref it value))) + (when (member branch (magit-list-remote-branch-names)) + branch))) + (commit (or (magit--painted-branch-at-point 'remote) + (magit-name-remote-branch (oref it value)))))) + +(defun magit-commit-at-point () + (or (magit-section-value-if 'commit) + (magit-thing-at-point 'git-revision t) + (and-let* ((chunk (and (bound-and-true-p magit-blame-mode) + (fboundp 'magit-current-blame-chunk) + (magit-current-blame-chunk)))) + (oref chunk orig-rev)) + (and (derived-mode-p 'magit-stash-mode + 'magit-merge-preview-mode + 'magit-revision-mode) + magit-buffer-revision))) + +(defun magit-branch-or-commit-at-point () + (or (magit-section-case + (branch (magit-ref-maybe-qualify (oref it value))) + (commit (or (magit--painted-branch-at-point) + (let ((rev (oref it value))) + (or (magit-name-branch rev) rev)))) + (tag (magit-ref-maybe-qualify (oref it value) "tags/")) + (pullreq (or (and (fboundp 'forge--pullreq-branch) + (magit-branch-p + (forge--pullreq-branch (oref it value)))) + (magit-ref-p (format "refs/pullreqs/%s" + (oref (oref it value) number))))) + ((unpulled unpushed) + (magit-ref-abbrev + (replace-regexp-in-string "\\.\\.\\.?" "" (oref it value))))) + (magit-thing-at-point 'git-revision t) + (and-let* ((chunk (and (bound-and-true-p magit-blame-mode) + (fboundp 'magit-current-blame-chunk) + (magit-current-blame-chunk)))) + (oref chunk orig-rev)) + (and magit-buffer-file-name + magit-buffer-refname) + (and (derived-mode-p 'magit-stash-mode + 'magit-merge-preview-mode + 'magit-revision-mode) + magit-buffer-revision))) + +(defun magit-tag-at-point () + (magit-section-case + (tag (oref it value)) + (commit (magit-name-tag (oref it value))))) + +(defun magit-stash-at-point () + (magit-section-value-if 'stash)) + +(defun magit-remote-at-point () + (magit-section-case + (remote (oref it value)) + ([branch remote] (magit-section-parent-value it)))) + +(defun magit-module-at-point (&optional predicate) + (when (magit-section-match 'module) + (let ((module (oref (magit-current-section) value))) + (and (or (not predicate) + (funcall predicate module)) + module)))) + +(defun magit-get-current-branch () + "Return the refname of the currently checked out branch. +Return nil if no branch is currently checked out." + (magit-git-string "symbolic-ref" "--short" "HEAD")) + +(defvar magit-get-previous-branch-timeout 0.5 + "Maximum time to spend in `magit-get-previous-branch'. +Given as a number of seconds.") + +(defun magit-get-previous-branch () + "Return the refname of the previously checked out branch. +Return nil if no branch can be found in the `HEAD' reflog +which is different from the current branch and still exists. +The amount of time spent searching is limited by +`magit-get-previous-branch-timeout'." + (let ((t0 (float-time)) + (current (magit-get-current-branch)) + (i 1) prev) + (while (if (> (- (float-time) t0) magit-get-previous-branch-timeout) + (setq prev nil) ;; Timed out. + (and (setq prev (magit-rev-verify (format "@{-%d}" i))) + (or (not (setq prev (magit-rev-branch prev))) + (equal prev current)))) + (cl-incf i)) + prev)) + +(defun magit--set-default-branch (newname oldname) + (let ((remote (or (magit-primary-remote) + (user-error "Cannot determine primary remote"))) + (branches (mapcar (lambda (line) (split-string line "\t")) + (magit-git-lines + "for-each-ref" "refs/heads" + "--format=%(refname:short)\t%(upstream:short)")))) + (when-let ((old (assoc oldname branches))) + (unless (assoc newname branches) + (magit-call-git "branch" "-m" oldname newname) + (setcar old newname))) + (let ((new (if (magit-branch-p newname) + newname + (concat remote "/" newname)))) + (pcase-dolist (`(,branch ,upstream) branches) + (cond + ((equal upstream oldname) + (magit-set-upstream-branch branch new)) + ((equal upstream (concat remote "/" oldname)) + (magit-set-upstream-branch branch (concat remote "/" newname)))))))) + +(defun magit--get-default-branch (&optional update) + (let ((remote (magit-primary-remote))) + (when update + (if (not remote) + (user-error "Cannot determine primary remote") + (message "Determining default branch...") + (magit-git "fetch" "--prune") + (magit-git "remote" "set-head" "--auto" remote) + (message "Determining default branch...done"))) + (let ((branch (magit-git-string "symbolic-ref" "--short" + (format "refs/remotes/%s/HEAD" remote)))) + (when (and update (not branch)) + (error "Cannot determine new default branch")) + (list remote (and branch (cdr (magit-split-branch-name branch))))))) + +(defun magit-set-upstream-branch (branch upstream) + "Set UPSTREAM as the upstream of BRANCH. +If UPSTREAM is nil, then unset BRANCH's upstream. +Otherwise UPSTREAM has to be an existing branch." + (if upstream + (magit-call-git "branch" "--set-upstream-to" upstream branch) + (magit-call-git "branch" "--unset-upstream" branch))) + +(defun magit-get-upstream-ref (&optional branch) + "Return the upstream branch of BRANCH as a fully qualified ref. +It BRANCH is nil, then return the upstream of the current branch, +if any, nil otherwise. If the upstream is not configured, the +configured remote is an url, or the named branch does not exist, +then return nil. I.e., return an existing local or +remote-tracking branch ref." + (and-let* ((branch (or branch (magit-get-current-branch)))) + (magit-ref-fullname (concat branch "@{upstream}")))) + +(defun magit-get-upstream-branch (&optional branch) + "Return the name of the upstream branch of BRANCH. +It BRANCH is nil, then return the upstream of the current branch +if any, nil otherwise. If the upstream is not configured, the +configured remote is an url, or the named branch does not exist, +then return nil. I.e., return the name of an existing local or +remote-tracking branch. The returned string is colorized +according to the branch type." + (magit--with-refresh-cache + (list default-directory 'magit-get-upstream-branch branch) + (and-let* ((branch (or branch (magit-get-current-branch))) + (upstream (magit-ref-abbrev (concat branch "@{upstream}")))) + (magit--propertize-face + upstream (if (equal (magit-get "branch" branch "remote") ".") + 'magit-branch-local + 'magit-branch-remote))))) + +(defun magit-get-indirect-upstream-branch (branch &optional force) + (let ((remote (magit-get "branch" branch "remote"))) + (and remote (not (equal remote ".")) + ;; The user has opted in... + (or force + (--some (if (magit-git-success "check-ref-format" "--branch" it) + (equal it branch) + (string-match-p it branch)) + magit-branch-prefer-remote-upstream)) + ;; and local BRANCH tracks a remote branch... + (let ((upstream (magit-get-upstream-branch branch))) + ;; whose upstream... + (and upstream + ;; has the same name as BRANCH... + (equal (substring upstream (1+ (length remote))) branch) + ;; and can be fast-forwarded to BRANCH. + (magit-rev-ancestor-p upstream branch) + upstream))))) + +(defun magit-get-upstream-remote (&optional branch allow-unnamed) + (and-let* ((branch (or branch (magit-get-current-branch))) + (remote (magit-get "branch" branch "remote"))) + (and (not (equal remote ".")) + (cond ((member remote (magit-list-remotes)) + (magit--propertize-face remote 'magit-branch-remote)) + ((and allow-unnamed + (string-match-p "\\(\\`.\\{0,2\\}/\\|[:@]\\)" remote)) + (magit--propertize-face remote 'bold)))))) + +(defun magit-get-unnamed-upstream (&optional branch) + (and-let* ((branch (or branch (magit-get-current-branch))) + (remote (magit-get "branch" branch "remote")) + (merge (magit-get "branch" branch "merge"))) + (and (magit--unnamed-upstream-p remote merge) + (list (magit--propertize-face remote 'bold) + (magit--propertize-face merge 'magit-branch-remote))))) + +(defun magit--unnamed-upstream-p (remote merge) + (and remote (string-match-p "\\(\\`\\.\\{0,2\\}/\\|[:@]\\)" remote) + merge (string-prefix-p "refs/" merge))) + +(defun magit--valid-upstream-p (remote merge) + (and (or (equal remote ".") + (member remote (magit-list-remotes))) + (string-prefix-p "refs/" merge))) + +(defun magit-get-current-remote (&optional allow-unnamed) + (or (magit-get-upstream-remote nil allow-unnamed) + (and-let* ((remotes (magit-list-remotes)) + (remote (if (length= remotes 1) + (car remotes) + (magit-primary-remote)))) + (magit--propertize-face remote 'magit-branch-remote)))) + +(defun magit-get-push-remote (&optional branch) + (and-let* ((remote + (or (and (or branch (setq branch (magit-get-current-branch))) + (magit-get "branch" branch "pushRemote")) + (magit-get "remote.pushDefault")))) + (magit--propertize-face remote 'magit-branch-remote))) + +(defun magit-get-push-branch (&optional branch verify) + (magit--with-refresh-cache + (list default-directory 'magit-get-push-branch branch verify) + (and-let* ((branch (or branch (setq branch (magit-get-current-branch)))) + (remote (magit-get-push-remote branch)) + (target (concat remote "/" branch))) + (and (or (not verify) + (magit-rev-verify target)) + (magit--propertize-face target 'magit-branch-remote))))) + +(defun magit-get-@{push}-branch (&optional branch) + (let ((ref (magit-rev-parse "--symbolic-full-name" + (concat branch "@{push}")))) + (and ref + (string-prefix-p "refs/remotes/" ref) + (substring ref 13)))) + +(defun magit-get-remote (&optional branch) + (and (or branch (setq branch (magit-get-current-branch))) + (let ((remote (magit-get "branch" branch "remote"))) + (and (not (equal remote ".")) + remote)))) + +(defun magit-get-some-remote (&optional branch) + (or (magit-get-remote branch) + (and-let* ((main (magit-main-branch))) + (magit-get-remote main)) + (magit-primary-remote) + (car (magit-list-remotes)))) + +(defvar magit-primary-remote-names + '("upstream" "origin")) + +(defun magit-primary-remote () + "Return the primary remote. + +The primary remote is the remote that tracks the repository that +other repositories are forked from. It often is called \"origin\" +but because many people name their own fork \"origin\", using that +term would be ambiguous. Likewise we avoid the term \"upstream\" +because a branch's @{upstream} branch may be a local branch or a +branch from a remote other than the primary remote. + +If a remote exists whose name matches `magit.primaryRemote', then +that is considered the primary remote. If no remote by that name +exists, then remotes in `magit-primary-remote-names' are tried in +order and the first remote from that list that actually exists in +the current repository is considered its primary remote." + (let ((remotes (magit-list-remotes))) + (seq-find (lambda (name) + (member name remotes)) + (delete-dups + (delq nil + (cons (magit-get "magit.primaryRemote") + magit-primary-remote-names)))))) + +(defun magit-branch-merged-p (branch &optional target) + "Return non-nil if BRANCH is merged into its upstream and TARGET. + +TARGET defaults to the current branch. If `HEAD' is detached and +TARGET is nil, then always return nil. As a special case, if +TARGET is t, then return non-nil if BRANCH is merged into any one +of the other local branches. + +If, and only if, BRANCH has an upstream, then only return non-nil +if BRANCH is merged into both TARGET (as described above) as well +as into its upstream." + (and (if-let ((upstream (and (magit-branch-p branch) + (magit-get-upstream-branch branch)))) + (magit-rev-ancestor-p branch upstream) + t) + (if (eq target t) + (delete (magit-name-local-branch branch) + (magit-list-containing-branches branch)) + (and-let* ((target (or target (magit-get-current-branch)))) + (magit-rev-ancestor-p branch target))))) + +(defun magit-get-tracked (refname) + "Return the remote branch tracked by the remote-tracking branch REFNAME. +The returned value has the form (REMOTE . REF), where REMOTE is +the name of a remote and REF is the ref local to the remote." + (and-let* ((ref (magit-ref-fullname refname))) + (save-match-data + (seq-some (lambda (line) + (and (string-match "\ +\\`remote\\.\\([^.]+\\)\\.fetch=\\+?\\([^:]+\\):\\(.+\\)" line) + (let ((rmt (match-string 1 line)) + (src (match-string 2 line)) + (dst (match-string 3 line))) + (and (string-match (format "\\`%s\\'" + (string-replace + "*" "\\(.+\\)" dst)) + ref) + (cons rmt (string-replace + "*" (match-string 1 ref) src)))))) + (magit-git-lines "config" "--local" "--list"))))) + +(defun magit-split-branch-name (branch) + (cond ((member branch (magit-list-local-branch-names)) + (cons "." branch)) + ((string-match "/" branch) + (or (seq-some (lambda (remote) + (and (string-match + (format "\\`\\(%s\\)/\\(.+\\)\\'" remote) + branch) + (cons (match-string 1 branch) + (match-string 2 branch)))) + (magit-list-remotes)) + (error "Invalid branch name %s" branch))))) + +(defun magit-get-current-tag (&optional rev with-distance) + "Return the closest tag reachable from REV. + +If optional REV is nil, then default to `HEAD'. +If optional WITH-DISTANCE is non-nil then return (TAG COMMITS), +if it is `dirty' return (TAG COMMIT DIRTY). COMMITS is the number +of commits in `HEAD' but not in TAG and DIRTY is t if there are +uncommitted changes, nil otherwise." + (and-let* ((str (magit-git-str "describe" "--long" "--tags" + (and (eq with-distance 'dirty) "--dirty") + rev))) + (save-match-data + (string-match + "\\(.+\\)-\\(?:0[0-9]*\\|\\([0-9]+\\)\\)-g[0-9a-z]+\\(-dirty\\)?$" str) + (if with-distance + `(,(match-string 1 str) + ,(string-to-number (or (match-string 2 str) "0")) + ,@(and (match-string 3 str) (list t))) + (match-string 1 str))))) + +(defun magit-get-next-tag (&optional rev with-distance) + "Return the closest tag from which REV is reachable. + +If optional REV is nil, then default to `HEAD'. +If no such tag can be found or if the distance is 0 (in which +case it is the current tag, not the next), return nil instead. +If optional WITH-DISTANCE is non-nil, then return (TAG COMMITS) +where COMMITS is the number of commits in TAG but not in REV." + (and-let* ((str (magit-git-str "describe" "--contains" (or rev "HEAD")))) + (save-match-data + (when (string-match "^[^^~]+" str) + (setq str (match-string 0 str)) + (unless (equal str (magit-get-current-tag rev)) + (if with-distance + (list str (car (magit-rev-diff-count str rev))) + str)))))) + +(defun magit-list-refs (&optional namespaces format sortby) + "Return list of references, excluding symbolic references. + +When NAMESPACES is non-nil, list refs from these namespaces +rather than those from `magit-list-refs-namespaces'. + +FORMAT is passed to the `--format' flag of `git for-each-ref' +and defaults to \"%(refname)\". + +SORTBY is a key or list of keys to pass to the `--sort' flag of +`git for-each-ref'. When nil, use `magit-list-refs-sortby'" + (unless format + (setq format "%(refname)")) + (seq-keep (lambda (line) + (pcase-let* ((`(,symrefp ,value) + (split-string line "")) + (symrefp (not (equal symrefp "")))) + (and (not symrefp) value))) + (magit-git-lines "for-each-ref" + (concat "--format=%(symref)" format) + (--map (concat "--sort=" it) + (pcase (or sortby magit-list-refs-sortby) + ((and val (pred stringp)) (list val)) + ((and val (pred listp)) val))) + (or namespaces magit-list-refs-namespaces)))) + +(defun magit-list-branches () + (magit-list-refs (list "refs/heads" "refs/remotes"))) + +(defun magit-list-local-branches () + (magit-list-refs "refs/heads")) + +(defun magit-list-remote-branches (&optional remote) + (magit-list-refs (concat "refs/remotes/" remote))) + +(defun magit-list-related-branches (relation &optional commit &rest args) + (--remove (string-match-p "\\(\\`(HEAD\\|HEAD -> \\)" it) + (--map (substring it 2) + (magit-git-lines "branch" args relation commit)))) + +(defun magit-list-containing-branches (&optional commit &rest args) + (magit-list-related-branches "--contains" commit args)) + +(defun magit-list-publishing-branches (&optional commit) + (--filter (magit-rev-ancestor-p (or commit "HEAD") it) + magit-published-branches)) + +(defun magit-list-merged-branches (&optional commit &rest args) + (magit-list-related-branches "--merged" commit args)) + +(defun magit-list-unmerged-branches (&optional commit &rest args) + (magit-list-related-branches "--no-merged" commit args)) + +(defun magit-list-unmerged-to-upstream-branches () + (--filter (and-let* ((upstream (magit-get-upstream-branch it))) + (member it (magit-list-unmerged-branches upstream))) + (magit-list-local-branch-names))) + +(defun magit-list-branches-pointing-at (commit) + (let ((re (format "\\`%s refs/\\(heads\\|remotes\\)/\\(.*\\)\\'" + (magit-rev-verify commit)))) + (--keep (and (string-match re it) + (let ((name (match-string 2 it))) + (and (not (string-suffix-p "HEAD" name)) + name))) + (magit-git-lines "show-ref")))) + +(defun magit-list-refnames (&optional namespaces include-special) + (nconc (magit-list-refs namespaces "%(refname:short)") + (and include-special + (magit-list-special-refnames)))) + +(defvar magit-special-refnames + '("HEAD" "ORIG_HEAD" "FETCH_HEAD" "MERGE_HEAD" "CHERRY_PICK_HEAD")) + +(defun magit-list-special-refnames () + (let ((gitdir (magit-gitdir))) + (cl-mapcan (lambda (name) + (and (file-exists-p (expand-file-name name gitdir)) + (list name))) + magit-special-refnames))) + +(defun magit-list-branch-names () + (magit-list-refnames (list "refs/heads" "refs/remotes"))) + +(defun magit-list-local-branch-names () + (magit-list-refnames "refs/heads")) + +(defun magit-list-remote-branch-names (&optional remote relative) + (if (and remote relative) + (let ((regexp (format "^refs/remotes/%s/\\(.+\\)" remote))) + (--mapcat (when (string-match regexp it) + (list (match-string 1 it))) + (magit-list-remote-branches remote))) + (magit-list-refnames (concat "refs/remotes/" remote)))) + +(defun magit-format-refs (format &rest args) + (let ((lines (magit-git-lines + "for-each-ref" (concat "--format=" format) + (or args (list "refs/heads" "refs/remotes" "refs/tags"))))) + (if (string-search "\f" format) + (--map (split-string it "\f") lines) + lines))) + +(defun magit-list-remotes () + (magit-git-lines "remote")) + +(defun magit-list-tags () + (magit-git-lines "tag")) + +(defun magit-list-stashes (&optional format) + (magit-git-lines "stash" "list" (concat "--format=" (or format "%gd")))) + +(defun magit-list-active-notes-refs () + "Return notes refs according to `core.notesRef' and `notes.displayRef'." + (magit-git-lines "for-each-ref" "--format=%(refname)" + (or (magit-get "core.notesRef") "refs/notes/commits") + (magit-get-all "notes.displayRef"))) + +(defun magit-list-notes-refnames () + (--map (substring it 6) (magit-list-refnames "refs/notes"))) + +(defun magit-remote-list-tags (remote) + (--keep (and (not (string-suffix-p "^{}" it)) + (substring it 51)) + (magit-git-lines "ls-remote" "--tags" remote))) + +(defun magit-remote-list-branches (remote) + (--keep (and (not (string-suffix-p "^{}" it)) + (substring it 52)) + (magit-git-lines "ls-remote" "--heads" remote))) + +(defun magit-remote-list-refs (remote) + (--keep (and (not (string-suffix-p "^{}" it)) + (substring it 41)) + (magit-git-lines "ls-remote" remote))) + +(defun magit-remote-head (remote) + (and-let* ((line (cl-find-if + (lambda (line) + (string-match + "\\`ref: refs/heads/\\([^\s\t]+\\)[\s\t]HEAD\\'" line)) + (magit-git-lines "ls-remote" "--symref" remote "HEAD")))) + (match-string 1 line))) + +(defun magit-list-modified-modules () + (--keep (and (string-match "\\`\\+\\([^ ]+\\) \\(.+\\) (.+)\\'" it) + (match-string 2 it)) + (magit-git-lines "submodule" "status"))) + +(defun magit-list-module-paths () + (magit-with-toplevel + (--mapcat (and (string-match "^160000 [0-9a-z]\\{40,\\} 0\t\\(.+\\)$" it) + (list (match-string 1 it))) + (magit-git-items "ls-files" "-z" "--stage")))) + +(defun magit-list-module-names () + (mapcar #'magit-get-submodule-name (magit-list-module-paths))) + +(defun magit-get-submodule-name (path) + "Return the name of the submodule at PATH. +PATH has to be relative to the super-repository." + (if (magit-git-version>= "2.38.0") + ;; "git submodule--helper name" was removed, + ;; but might still come back in another form. + (substring + (car (split-string + (car (or (magit-git-items + "config" "-z" + "-f" (expand-file-name ".gitmodules" (magit-toplevel)) + "--get-regexp" "^submodule\\..*\\.path$" + (concat "^" (regexp-quote (directory-file-name path)) "$")) + (error "No such submodule `%s'" path))) + "\n")) + 10 -5) + (magit-git-string "submodule--helper" "name" path))) + +(defun magit-list-worktrees () + "Return list of the worktrees of this repository. + +The returned list has the form (PATH COMMIT BRANCH BARE DETACHED +LOCKED PRUNABLE). The last four elements are booleans, with the +exception of LOCKED and PRUNABLE, which may also be strings. +See git-worktree(1) manpage for the meaning of the various parts. + +This function corrects a situation where \"git worktree list\" +would claim a worktree is bare, even though the working tree is +specified using `core.worktree'." + (let ((remote (file-remote-p default-directory)) + worktrees worktree) + (dolist (line (let ((magit-git-global-arguments + ;; KLUDGE At least in Git v2.8.3 this argument + ;; would trigger a segfault. + (remove "--no-pager" magit-git-global-arguments))) + (if (magit-git-version>= "2.36") + (magit-git-items "worktree" "list" "--porcelain" "-z") + (magit-git-lines "worktree" "list" "--porcelain")))) + (cond ((string-prefix-p "worktree" line) + (let ((path (substring line 9))) + (when remote + (setq path (concat remote path))) + ;; If the git directory is separate from the main + ;; worktree, then "git worktree" returns the git + ;; directory instead of the worktree, which isn't + ;; what it is supposed to do and not what we want. + ;; However, if the worktree has been removed, then + ;; we want to return it anyway; instead of nil. + (setq path (or (magit-toplevel path) path)) + (setq worktree (list path nil nil nil nil nil nil)) + (push worktree worktrees))) + ((string-prefix-p "HEAD" line) + (setf (nth 1 worktree) (substring line 5))) + ((string-prefix-p "branch" line) + (setf (nth 2 worktree) (substring line 18))) + ((string-equal line "bare") + (let* ((default-directory (car worktree)) + (wt (and (not (magit-get-boolean "core.bare")) + (magit-get "core.worktree")))) + (if (and wt (file-exists-p (expand-file-name wt))) + (progn (setf (nth 0 worktree) (expand-file-name wt)) + (setf (nth 2 worktree) (magit-rev-parse "HEAD")) + (setf (nth 3 worktree) (magit-get-current-branch))) + (setf (nth 3 worktree) t)))) + ((string-equal line "detached") + (setf (nth 4 worktree) t)) + ((string-prefix-p line "locked") + (setf (nth 5 worktree) + (if (> (length line) 6) (substring line 7) t))) + ((string-prefix-p line "prunable") + (setf (nth 6 worktree) + (if (> (length line) 8) (substring line 9) t))))) + (nreverse worktrees))) + +(defun magit-symbolic-ref-p (name) + (magit-git-success "symbolic-ref" "--quiet" name)) + +(defun magit-ref-p (rev) + (or (car (member rev (magit-list-refs "refs/"))) + (car (member rev (magit-list-refnames "refs/"))))) + +(defun magit-branch-p (rev) + (or (car (member rev (magit-list-branches))) + (car (member rev (magit-list-branch-names))))) + +(defun magit-local-branch-p (rev) + (or (car (member rev (magit-list-local-branches))) + (car (member rev (magit-list-local-branch-names))))) + +(defun magit-remote-branch-p (rev) + (or (car (member rev (magit-list-remote-branches))) + (car (member rev (magit-list-remote-branch-names))))) + +(defun magit-branch-set-face (branch) + (magit--propertize-face branch (if (magit-local-branch-p branch) + 'magit-branch-local + 'magit-branch-remote))) + +(defun magit-tag-p (rev) + (car (member rev (magit-list-tags)))) + +(defun magit-remote-p (string) + (car (member string (magit-list-remotes)))) + +(defvar magit-main-branch-names + '("main" "master" "trunk" "development") + "Branch names reserved for use by the primary branch. +Use function `magit-main-branch' to get the name actually used in +the current repository.") + +(defvar magit-long-lived-branches + (append magit-main-branch-names (list "maint" "next")) + "Branch names reserved for use by long lived branches.") + +(defun magit-main-branch () + "Return the main branch. + +If a branch exists whose name matches `init.defaultBranch', then +that is considered the main branch. If no branch by that name +exists, then the branch names in `magit-main-branch-names' are +tried in order. The first branch from that list that actually +exists in the current repository is considered its main branch." + (let ((branches (magit-list-local-branch-names))) + (seq-find (lambda (name) + (member name branches)) + (delete-dups + (delq nil + (cons (magit-get "init.defaultBranch") + magit-main-branch-names)))))) + +(defun magit-rev-diff-count (a b &optional first-parent) + "Return the commits in A but not B and vice versa. +Return a list of two integers: (A>B B>A). + +If `first-parent' is set, traverse only first parents." + (mapcar #'string-to-number + (split-string (magit-git-string "rev-list" + "--count" "--left-right" + (and first-parent "--first-parent") + (concat a "..." b)) + "\t"))) + +(defun magit-abbrev-length () + (let ((abbrev (magit-get "core.abbrev"))) + (if (and abbrev (not (equal abbrev "auto"))) + (string-to-number abbrev) + ;; Guess the length git will be using based on an example + ;; abbreviation. Actually HEAD's abbreviation might be an + ;; outlier, so use the shorter of the abbreviations for two + ;; commits. See #3034. + (if-let ((head (magit-rev-parse "--short" "HEAD")) + (head-len (length head))) + (min head-len + (if-let ((rev (magit-rev-parse "--short" "HEAD~"))) + (length rev) + head-len)) + ;; We're on an unborn branch, but perhaps the repository has + ;; other commits. See #4123. + (if-let ((commits (magit-git-lines "rev-list" "-n2" "--all" + "--abbrev-commit"))) + (apply #'min (mapcar #'length commits)) + ;; A commit does not exist. Fall back to the default of 7. + 7))))) + +(defun magit-abbrev-arg (&optional arg) + (format "--%s=%d" (or arg "abbrev") (magit-abbrev-length))) + +(defun magit-rev-abbrev (rev) + (magit-rev-parse (magit-abbrev-arg "short") rev)) + +(defun magit-commit-children (commit &optional args) + (mapcar #'car + (--filter (member commit (cdr it)) + (--map (split-string it " ") + (magit-git-lines + "log" "--format=%H %P" + (or args (list "--branches" "--tags" "--remotes")) + "--not" commit))))) + +(defun magit-commit-parents (commit) + (and-let* ((str (magit-git-string "rev-list" "-1" "--parents" commit))) + (cdr (split-string str)))) + +(defun magit-patch-id (rev) + (magit--with-connection-local-variables + (magit--with-temp-process-buffer + (magit-process-file + shell-file-name nil '(t nil) nil shell-command-switch + (let ((exec (shell-quote-argument (magit-git-executable)))) + (format "%s diff-tree -u %s | %s patch-id" exec rev exec))) + (car (split-string (buffer-string)))))) + +(defun magit-rev-format (format &optional rev args) + ;; Prefer `git log --no-walk' to `git show --no-patch' because it + ;; performs better in some scenarios. + (let ((str (magit-git-string "log" "--no-walk" + (concat "--format=" format) args + (if rev (magit--rev-dereference rev) "HEAD") + "--"))) + (and (not (string-equal str "")) + str))) + +(defun magit-rev-insert-format (format &optional rev args) + ;; Prefer `git log --no-walk' to `git show --no-patch' because it + ;; performs better in some scenarios. + (magit-git-insert "log" "--no-walk" + (concat "--format=" format) args + (if rev (magit--rev-dereference rev) "HEAD") + "--")) + +(defun magit-format-rev-summary (rev) + (and-let* ((str (magit-rev-format "%h %s" rev))) + (progn + (magit--put-face 0 (string-match " " str) 'magit-hash str) + str))) + +(defvar magit-ref-namespaces + '(("\\`HEAD\\'" . magit-head) + ("\\`refs/tags/\\(.+\\)" . magit-tag) + ("\\`refs/heads/\\(.+\\)" . magit-branch-local) + ("\\`refs/remotes/\\(.+\\)" . magit-branch-remote) + ("\\`refs/bisect/\\(bad\\)" . magit-bisect-bad) + ("\\`refs/bisect/\\(skip.*\\)" . magit-bisect-skip) + ("\\`refs/bisect/\\(good.*\\)" . magit-bisect-good) + ("\\`refs/stash$" . magit-refname-stash) + ("\\`refs/wip/\\(.+\\)" . magit-refname-wip) + ("\\`refs/pullreqs/\\(.+\\)" . magit-refname-pullreq) + ("\\`\\(bad\\):" . magit-bisect-bad) + ("\\`\\(skip\\):" . magit-bisect-skip) + ("\\`\\(good\\):" . magit-bisect-good) + ("\\`\\(.+\\)" . magit-refname)) + "How refs are formatted for display. + +Each entry controls how a certain type of ref is displayed, and +has the form (REGEXP . FACE). REGEXP is a regular expression +used to match full refs. The first entry whose REGEXP matches +the reference is used. + +In log and revision buffers the first regexp submatch becomes the +\"label\" that represents the ref and is propertized with FONT. +In refs buffers the displayed text is controlled by other means +and this option only controls what face is used.") + +(defun magit-format-ref-labels (string) + (save-match-data + (let ((regexp "\\(, \\|tag: \\|HEAD -> \\)") + names) + (if (and (derived-mode-p 'magit-log-mode) + (member "--simplify-by-decoration" magit-buffer-log-args)) + (let ((branches (magit-list-local-branch-names)) + (re (format "^%s/.+" (regexp-opt (magit-list-remotes))))) + (setq names + (--map (cond ((string-equal it "HEAD") it) + ((string-prefix-p "refs/" it) it) + ((member it branches) (concat "refs/heads/" it)) + ((string-match re it) (concat "refs/remotes/" it)) + (t (concat "refs/" it))) + (split-string + (string-replace "tag: " "refs/tags/" string) + regexp t)))) + (setq names (split-string string regexp t))) + (let (state head upstream tags branches remotes other combined) + (dolist (ref names) + (let* ((face (cdr (--first (string-match (car it) ref) + magit-ref-namespaces))) + (name (magit--propertize-face + (or (match-string 1 ref) ref) face))) + (cl-case face + ((magit-bisect-bad magit-bisect-skip magit-bisect-good) + (setq state name)) + (magit-head + (setq head (magit--propertize-face "@" 'magit-head))) + (magit-tag (push name tags)) + (magit-branch-local (push name branches)) + (magit-branch-remote (push name remotes)) + (t (push name other))))) + (setq remotes + (seq-keep + (lambda (name) + (if (string-match "\\`\\([^/]*\\)/\\(.*\\)\\'" name) + (let ((r (match-string 1 name)) + (b (match-string 2 name))) + (and (not (equal b "HEAD")) + (if (equal (concat "refs/remotes/" name) + (magit-git-string + "symbolic-ref" + (format "refs/remotes/%s/HEAD" r))) + (magit--propertize-face + name 'magit-branch-remote-head) + name))) + name)) + remotes)) + (let* ((current (magit-get-current-branch)) + (target (magit-get-upstream-branch current))) + (dolist (name branches) + (let ((push (car (member (magit-get-push-branch name) remotes)))) + (when push + (setq remotes (delete push remotes)) + (string-match "^[^/]*/" push) + (setq push (substring push 0 (match-end 0)))) + (cond + ((equal name current) + (setq head + (concat push + (magit--propertize-face + name 'magit-branch-current)))) + ((equal name target) + (setq upstream + (concat push + (magit--propertize-face + name '(magit-branch-upstream + magit-branch-local))))) + (t + (push (concat push name) combined))))) + (when (and target (not upstream)) + (if (member target remotes) + (progn + (magit--add-face-text-property + 0 (length target) 'magit-branch-upstream nil target) + (setq upstream target) + (setq remotes (delete target remotes))) + (when-let ((target (car (member target combined)))) + (magit--add-face-text-property + 0 (length target) 'magit-branch-upstream nil target) + (setq upstream target) + (setq combined (delete target combined)))))) + (string-join (flatten-tree `(,state + ,head + ,upstream + ,@(nreverse tags) + ,@(nreverse combined) + ,@(nreverse remotes) + ,@other)) + " "))))) + +(defun magit-object-type (object) + (magit-git-string "cat-file" "-t" object)) + +(defmacro magit-with-blob (commit file &rest body) + (declare (indent 2) + (debug (form form body))) + `(magit--with-temp-process-buffer + (let ((buffer-file-name ,file)) + (save-excursion + (magit-git-insert "cat-file" "-p" + (concat ,commit ":" buffer-file-name))) + (decode-coding-inserted-region + (point-min) (point-max) buffer-file-name t nil nil t) + ,@body))) + +(defmacro magit-with-temp-index (tree arg &rest body) + (declare (indent 2) (debug (form form body))) + (let ((file (cl-gensym "file"))) + `(let ((magit--refresh-cache nil) + (,file (magit-convert-filename-for-git + (make-temp-name + (expand-file-name "index.magit." (magit-gitdir)))))) + (unwind-protect + (magit-with-toplevel + (when-let ((tree ,tree)) + (unless (magit-git-success "read-tree" ,arg tree + (concat "--index-output=" ,file)) + (error "Cannot read tree %s" tree))) + (with-environment-variables (("GIT_INDEX_FILE" ,file)) + ,@body)) + (ignore-errors + (delete-file (concat (file-remote-p default-directory) ,file))))))) + +(defun magit-commit-tree (message &optional tree &rest parents) + (magit-git-string "commit-tree" "--no-gpg-sign" "-m" message + (--mapcat (list "-p" it) (delq nil parents)) + (or tree + (magit-git-string "write-tree") + (error "Cannot write tree")))) + +(defun magit-commit-worktree (message &optional arg &rest other-parents) + (magit-with-temp-index "HEAD" arg + (and (magit-update-files (magit-unstaged-files)) + (apply #'magit-commit-tree message nil "HEAD" other-parents)))) + +(defun magit-update-files (files) + (magit-git-success "update-index" "--add" "--remove" "--" files)) + +(defun magit-update-ref (ref message rev &optional stashish) + (let ((magit--refresh-cache nil)) + (or (if (magit-git-version>= "2.6.0") + (zerop (magit-call-git "update-ref" "--create-reflog" + "-m" message ref rev + (or (magit-rev-verify ref) ""))) + ;; `--create-reflog' didn't exist before v2.6.0 + (let ((oldrev (magit-rev-verify ref)) + (logfile (expand-file-name (concat "logs/" ref) + (magit-gitdir)))) + (unless (file-exists-p logfile) + (when oldrev + (magit-git-success "update-ref" "-d" ref oldrev)) + (make-directory (file-name-directory logfile) t) + (with-temp-file logfile) + (when (and oldrev (not stashish)) + (magit-git-success "update-ref" "-m" "enable reflog" + ref oldrev "")))) + (magit-git-success "update-ref" "-m" message ref rev + (or (magit-rev-verify ref) ""))) + (error "Cannot update %s with %s" ref rev)))) + +(defconst magit-range-re + (concat "\\`\\([^ \t]*[^.]\\)?" ; revA + "\\(\\.\\.\\.?\\)" ; range marker + "\\([^.][^ \t]*\\)?\\'")) ; revB + +(defun magit-split-range (range) + (pcase-let ((`(,beg ,end ,sep) (magit--split-range-raw range))) + (and sep + (let ((beg (or beg "HEAD")) + (end (or end "HEAD"))) + (if (string-equal (match-string 2 range) "...") + (and-let* ((base (magit-git-string "merge-base" beg end))) + (cons base end)) + (cons beg end)))))) + +(defun magit--split-range-raw (range) + (and (string-match magit-range-re range) + (let ((beg (match-string 1 range)) + (end (match-string 3 range))) + (and (or beg end) + (list beg end (match-string 2 range)))))) + +(defun magit-hash-range (range) + (if (string-match magit-range-re range) + (let ((beg (match-string 1 range)) + (end (match-string 3 range))) + (and (or beg end) + (let ((beg-hash (and beg (magit-rev-hash (match-string 1 range)))) + (end-hash (and end (magit-rev-hash (match-string 3 range))))) + (and (or (not beg) beg-hash) + (or (not end) end-hash) + (concat beg-hash (match-string 2 range) end-hash))))) + (magit-rev-hash range))) + +(defvar magit-revision-faces + '(magit-hash + magit-tag + magit-branch-remote + magit-branch-remote-head + magit-branch-local + magit-branch-current + magit-branch-upstream + magit-branch-warning + magit-head + magit-refname + magit-refname-stash + magit-refname-wip + magit-refname-pullreq)) + +(put 'git-revision 'thing-at-point #'magit-thingatpt--git-revision) +(defun magit-thingatpt--git-revision (&optional disallow) + ;; Support hashes and references. + (and-let* ((bounds + (let ((c (concat "\s\n\t~^:?*[\\" disallow))) + (cl-letf + (((get 'git-revision 'beginning-op) + (lambda () + (if (re-search-backward (format "[%s]" c) nil t) + (forward-char) + (goto-char (point-min))))) + ((get 'git-revision 'end-op) + (lambda () + (re-search-forward (format "\\=[^%s]*" c) nil t)))) + (bounds-of-thing-at-point 'git-revision)))) + (string (buffer-substring-no-properties (car bounds) (cdr bounds))) + ;; References are allowed to contain most parentheses and + ;; most punctuation, but if those characters appear at the + ;; edges of a possible reference in arbitrary text, then + ;; they are much more likely to be intended as just that: + ;; punctuation and delimiters. + (string (thread-first string + (string-trim-left "[(</]") + (string-trim-right "[])>/.,;!]")))) + (let (disallow) + (when (or (string-match-p "\\.\\." string) + (string-match-p "/\\." string)) + (setq disallow (concat disallow "."))) + (when (string-match-p "@{" string) + (setq disallow (concat disallow "@{"))) + (if disallow + ;; These additional restrictions overcompensate, + ;; but that only matters in rare cases. + (magit-thingatpt--git-revision disallow) + (and (not (equal string "@")) + (or (and (>= (length string) 7) + (string-match-p "[a-z]" string) + (magit-commit-p string)) + (and (magit-ref-p string) + (let ((face (get-text-property (point) 'face))) + (or (not face) + (member face magit-revision-faces))))) + string))))) + +(put 'git-revision-range 'thing-at-point #'magit-thingatpt--git-revision-range) +(defun magit-thingatpt--git-revision-range () + ;; Support hashes but no references. + (and-let* ((bounds + (cl-letf (((get 'git-revision 'beginning-op) + (lambda () + (if (re-search-backward "[^a-z0-9.]" nil t) + (forward-char) + (goto-char (point-min))))) + ((get 'git-revision 'end-op) + (lambda () + (and (re-search-forward "[^a-z0-9.]" nil t) + (backward-char))))) + (bounds-of-thing-at-point 'git-revision))) + (range (buffer-substring-no-properties (car bounds) (cdr bounds)))) + ;; Validate but return as-is. + (and (magit-hash-range range) range))) + +;;; Completion + +(defvar magit-revision-history nil) + +(defun magit--minibuf-default-add-commit () + (let ((fn minibuffer-default-add-function)) + (setq-local + minibuffer-default-add-function + (lambda () + (let ((rest (and (functionp fn) (funcall fn)))) + (if-let ((commit (with-selected-window (minibuffer-selected-window) + (or (magit-thing-at-point 'git-revision-range t) + (magit-commit-at-point))))) + (let ((rest (cons commit (delete commit rest))) + (def minibuffer-default)) + (if (listp def) + (append def rest) + (cons def (delete def rest)))) + rest)))))) + +(defun magit-read-branch (prompt &optional secondary-default) + (magit-completing-read prompt (magit-list-branch-names) + nil t nil 'magit-revision-history + (or (magit-branch-at-point) + secondary-default + (magit-get-current-branch)))) + +(defun magit-read-branch-or-commit (prompt &optional secondary-default exclude) + (let ((current (magit-get-current-branch)) + (branch-at-point (magit-branch-at-point)) + (commit-at-point (magit-commit-at-point)) + (choices (delete exclude (magit-list-refnames nil t)))) + (when (equal current exclude) + (setq current nil)) + (when (equal branch-at-point exclude) + (setq branch-at-point nil)) + (when (and commit-at-point (not branch-at-point)) + (setq choices (cons commit-at-point choices))) + (minibuffer-with-setup-hook #'magit--minibuf-default-add-commit + (or (magit-completing-read + prompt choices nil nil nil 'magit-revision-history + (or branch-at-point commit-at-point secondary-default current)) + (user-error "Nothing selected"))))) + +(defun magit-read-range-or-commit (prompt &optional secondary-default) + (magit-read-range + prompt + (or (and-let* ((revs (magit-region-values '(commit branch) t))) + (progn + (deactivate-mark) + (concat (car (last revs)) ".." (car revs)))) + (magit-branch-or-commit-at-point) + secondary-default + (magit-get-current-branch)))) + +(defun magit-read-range (prompt &optional default) + (minibuffer-with-setup-hook + (lambda () + (magit--minibuf-default-add-commit) + (setq-local crm-separator "\\.\\.\\.?")) + (magit-completing-read-multiple + (concat prompt ": ") + (magit-list-refnames) + nil nil nil 'magit-revision-history default nil t))) + +(defun magit-read-remote-branch + (prompt &optional remote default local-branch require-match) + (let ((choice (magit-completing-read + prompt + (cl-union (and local-branch + (if remote + (list local-branch) + (--map (concat it "/" local-branch) + (magit-list-remotes)))) + (magit-list-remote-branch-names remote t) + :test #'equal) + nil require-match nil 'magit-revision-history default))) + (if (or remote (string-match "\\`\\([^/]+\\)/\\(.+\\)" choice)) + choice + (user-error "`%s' doesn't have the form REMOTE/BRANCH" choice)))) + +(defun magit-read-refspec (prompt remote) + (magit-completing-read prompt + (prog2 (message "Determining available refs...") + (magit-remote-list-refs remote) + (message "Determining available refs...done")))) + +(defun magit-read-local-branch (prompt &optional secondary-default) + (magit-completing-read prompt (magit-list-local-branch-names) + nil t nil 'magit-revision-history + (or (magit-local-branch-at-point) + secondary-default + (magit-get-current-branch)))) + +(defun magit-read-local-branch-or-commit (prompt) + (let ((choices (nconc (magit-list-local-branch-names) + (magit-list-special-refnames))) + (commit (magit-commit-at-point))) + (when commit + (push commit choices)) + (minibuffer-with-setup-hook #'magit--minibuf-default-add-commit + (or (magit-completing-read prompt choices + nil nil nil 'magit-revision-history + (or (magit-local-branch-at-point) commit)) + (user-error "Nothing selected"))))) + +(defun magit-read-local-branch-or-ref (prompt &optional secondary-default) + (magit-completing-read prompt (nconc (magit-list-local-branch-names) + (magit-list-refs "refs/")) + nil t nil 'magit-revision-history + (or (magit-local-branch-at-point) + secondary-default + (magit-get-current-branch)))) + +(defun magit-read-other-branch + (prompt &optional exclude secondary-default no-require-match) + (let* ((current (magit-get-current-branch)) + (atpoint (magit-branch-at-point)) + (exclude (or exclude current)) + (default (or (and (not (equal atpoint exclude)) atpoint) + (and (not (equal current exclude)) current) + secondary-default + (magit-get-previous-branch)))) + (magit-completing-read prompt (delete exclude (magit-list-branch-names)) + nil (not no-require-match) + nil 'magit-revision-history default))) + +(defun magit-read-other-branch-or-commit + (prompt &optional exclude secondary-default) + (let* ((current (magit-get-current-branch)) + (atpoint (magit-branch-or-commit-at-point)) + (exclude (or exclude current)) + (default (or (and (not (equal atpoint exclude)) + (not (and (not current) + (magit-rev-equal atpoint "HEAD"))) + atpoint) + (and (not (equal current exclude)) current) + secondary-default + (magit-get-previous-branch)))) + (minibuffer-with-setup-hook #'magit--minibuf-default-add-commit + (or (magit-completing-read prompt (delete exclude (magit-list-refnames)) + nil nil nil 'magit-revision-history default) + (user-error "Nothing selected"))))) + +(defun magit-read-other-local-branch + (prompt &optional exclude secondary-default no-require-match) + (let* ((current (magit-get-current-branch)) + (atpoint (magit-local-branch-at-point)) + (exclude (or exclude current)) + (default (or (and (not (equal atpoint exclude)) atpoint) + (and (not (equal current exclude)) current) + secondary-default + (magit-get-previous-branch)))) + (magit-completing-read prompt + (delete exclude (magit-list-local-branch-names)) + nil (not no-require-match) + nil 'magit-revision-history default))) + +(defun magit-read-branch-prefer-other (prompt) + (let* ((current (magit-get-current-branch)) + (commit (magit-commit-at-point)) + (atrev (and commit (magit-list-branches-pointing-at commit))) + (atpoint (magit--painted-branch-at-point))) + (magit-completing-read prompt (magit-list-branch-names) + nil t nil 'magit-revision-history + (or (magit-section-value-if 'branch) + atpoint + (and (not (cdr atrev)) (car atrev)) + (--first (not (equal it current)) atrev) + (magit-get-previous-branch) + (car atrev))))) + +(defun magit-read-upstream-branch (&optional branch prompt) + "Read the upstream for BRANCH using PROMPT. +If optional BRANCH is nil, then read the upstream for the +current branch, or raise an error if no branch is checked +out. Only existing branches can be selected." + (unless branch + (setq branch (or (magit-get-current-branch) + (error "Need a branch to set its upstream")))) + (let ((branches (delete branch (magit-list-branch-names)))) + (magit-completing-read + (or prompt (format "Change upstream of %s to" branch)) + branches nil t nil 'magit-revision-history + (or (let ((r (car (member (magit-remote-branch-at-point) branches))) + (l (car (member (magit-local-branch-at-point) branches)))) + (if magit-prefer-remote-upstream (or r l) (or l r))) + (and-let* ((main (magit-main-branch))) + (let ((r (car (member (concat "origin/" main) branches))) + (l (car (member main branches)))) + (if magit-prefer-remote-upstream (or r l) (or l r)))) + (car (member (magit-get-previous-branch) branches)))))) + +(defun magit-read-starting-point (prompt &optional branch default) + (or (magit-completing-read + (concat prompt + (and branch + (if (bound-and-true-p ivy-mode) + ;; Ivy-mode strips faces from prompt. + (format " `%s'" branch) + (concat " " (magit--propertize-face + branch 'magit-branch-local)))) + " starting at") + (nconc (list "HEAD") + (magit-list-refnames) + (directory-files (magit-gitdir) nil "_HEAD\\'")) + nil nil nil 'magit-revision-history + (or default (magit--default-starting-point))) + (user-error "Nothing selected"))) + +(defun magit--default-starting-point () + (or (let ((r (magit-remote-branch-at-point)) + (l (magit-local-branch-at-point))) + (if magit-prefer-remote-upstream (or r l) (or l r))) + (magit-commit-at-point) + (magit-stash-at-point) + (magit-get-current-branch))) + +(defun magit-read-tag (prompt &optional require-match) + (magit-completing-read prompt (magit-list-tags) nil + require-match nil 'magit-revision-history + (magit-tag-at-point))) + +(defun magit-read-stash (prompt) + (let* ((atpoint (magit-stash-at-point)) + (default (and atpoint + (concat atpoint (magit-rev-format " %s" atpoint)))) + (choices (mapcar (lambda (c) + (pcase-let ((`(,rev ,msg) (split-string c "\0"))) + (concat (propertize rev 'face 'magit-hash) + " " msg))) + (magit-list-stashes "%gd%x00%s"))) + (choice (magit-completing-read prompt choices + nil t nil nil + default + (car choices)))) + (and choice + (string-match "^\\([^ ]+\\) \\(.+\\)" choice) + (substring-no-properties (match-string 1 choice))))) + +(defun magit-read-remote (prompt &optional default use-only) + (let ((remotes (magit-list-remotes))) + (if (and use-only (length= remotes 1)) + (car remotes) + (magit-completing-read prompt remotes + nil t nil nil + (or default + (magit-remote-at-point) + (magit-get-remote)))))) + +(defun magit-read-remote-or-url (prompt &optional default) + (magit-completing-read prompt + (nconc (magit-list-remotes) + (list "https://" "git://" "git@")) + nil nil nil nil + (or default + (magit-remote-at-point) + (magit-get-remote)))) + +(defun magit-read-module-path (prompt &optional predicate) + (magit-completing-read prompt (magit-list-module-paths) + predicate t nil nil + (magit-module-at-point predicate))) + +(defun magit-module-confirm (verb &optional predicate) + ;; Some predicates use the inefficient `magit-toplevel' + ;; and some repositories have thousands of submodules. + (let ((magit--refresh-cache (list (cons 0 0))) + (modules nil)) + (if current-prefix-arg + (progn + (setq modules (magit-list-module-paths)) + (when predicate + (setq modules (seq-filter predicate modules))) + (unless modules + (if predicate + (user-error "No modules satisfying %s available" predicate) + (user-error "No modules available")))) + (setq modules (magit-region-values 'module)) + (when modules + (when predicate + (setq modules (seq-filter predicate modules))) + (unless modules + (user-error "No modules satisfying %s selected" predicate)))) + (if (or (length> modules 1) current-prefix-arg) + (magit-confirm t nil (format "%s %%d modules" verb) nil modules) + (list (magit-read-module-path (format "%s module" verb) predicate))))) + +;;; _ +(provide 'magit-git) +;;; magit-git.el ends here diff --git a/emacs/elpa/magit-20241004.917/magit-gitignore.el b/emacs/elpa/magit-20241004.917/magit-gitignore.el @@ -0,0 +1,195 @@ +;;; magit-gitignore.el --- Intentionally untracked files -*- lexical-binding:t -*- + +;; Copyright (C) 2008-2024 The Magit Project Contributors + +;; Author: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> +;; Maintainer: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> + +;; SPDX-License-Identifier: GPL-3.0-or-later + +;; Magit is free software: you can redistribute it and/or modify it +;; under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. +;; +;; Magit is distributed in the hope that it will be useful, but WITHOUT +;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +;; or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public +;; License for more details. +;; +;; You should have received a copy of the GNU General Public License +;; along with Magit. If not, see <https://www.gnu.org/licenses/>. + +;;; Commentary: + +;; This library implements gitignore commands. + +;;; Code: + +(require 'magit) + +;;; Transient + +;;;###autoload (autoload 'magit-gitignore "magit-gitignore" nil t) +(transient-define-prefix magit-gitignore () + "Instruct Git to ignore a file or pattern." + :man-page "gitignore" + ["Gitignore" + ("t" "shared at toplevel (.gitignore)" + magit-gitignore-in-topdir) + ("s" "shared in subdirectory (path/to/.gitignore)" + magit-gitignore-in-subdir) + ("p" "privately (.git/info/exclude)" + magit-gitignore-in-gitdir) + ("g" magit-gitignore-on-system + :if (lambda () (magit-get "core.excludesfile")) + :description (lambda () + (format "privately for all repositories (%s)" + (magit-get "core.excludesfile"))))] + ["Skip worktree" + (7 "w" "do skip worktree" magit-skip-worktree) + (7 "W" "do not skip worktree" magit-no-skip-worktree)] + ["Assume unchanged" + (7 "u" "do assume unchanged" magit-assume-unchanged) + (7 "U" "do not assume unchanged" magit-no-assume-unchanged)]) + +;;; Gitignore Commands + +;;;###autoload +(defun magit-gitignore-in-topdir (rule) + "Add the Git ignore RULE to the top-level \".gitignore\" file. +Since this file is tracked, it is shared with other clones of the +repository. Also stage the file." + (interactive (list (magit-gitignore-read-pattern))) + (magit-with-toplevel + (magit--gitignore rule ".gitignore") + (magit-run-git "add" ".gitignore"))) + +;;;###autoload +(defun magit-gitignore-in-subdir (rule directory) + "Add the Git ignore RULE to a \".gitignore\" file in DIRECTORY. +Prompt the user for a directory and add the rule to the +\".gitignore\" file in that directory. Since such files are +tracked, they are shared with other clones of the repository. +Also stage the file." + (interactive (list (magit-gitignore-read-pattern) + (read-directory-name "Limit rule to files in: "))) + (magit-with-toplevel + (let ((file (expand-file-name ".gitignore" directory))) + (magit--gitignore rule file) + (magit-run-git "add" (magit-convert-filename-for-git file))))) + +;;;###autoload +(defun magit-gitignore-in-gitdir (rule) + "Add the Git ignore RULE to \"$GIT_DIR/info/exclude\". +Rules in that file only affects this clone of the repository." + (interactive (list (magit-gitignore-read-pattern))) + (magit--gitignore rule (expand-file-name "info/exclude" (magit-gitdir))) + (magit-refresh)) + +;;;###autoload +(defun magit-gitignore-on-system (rule) + "Add the Git ignore RULE to the file specified by `core.excludesFile'. +Rules that are defined in that file affect all local repositories." + (interactive (list (magit-gitignore-read-pattern))) + (magit--gitignore rule + (or (magit-get "core.excludesFile") + (error "Variable `core.excludesFile' isn't set"))) + (magit-refresh)) + +(defun magit--gitignore (rule file) + (when-let ((directory (file-name-directory file))) + (make-directory directory t)) + (with-temp-buffer + (when (file-exists-p file) + (insert-file-contents file)) + (goto-char (point-max)) + (unless (bolp) + (insert "\n")) + (insert (replace-regexp-in-string "\\(\\\\*\\)" "\\1\\1" rule)) + (insert "\n") + (write-region nil nil file))) + +(defun magit-gitignore-read-pattern () + (let* ((default (magit-current-file)) + (base (car magit-buffer-diff-files)) + (base (and base (file-directory-p base) base)) + (choices + (delete-dups + (--mapcat + (cons (concat "/" it) + (and-let* ((ext (file-name-extension it))) + (list (concat "/" (file-name-directory it) "*." ext) + (concat "*." ext)))) + (sort (nconc + (magit-untracked-files nil base) + ;; The untracked section of the status buffer lists + ;; directories containing only untracked files. + ;; Add those as candidates. + (seq-filter #'directory-name-p + (magit-list-files + "--other" "--exclude-standard" "--directory" + "--no-empty-directory" "--" base))) + #'string-lessp))))) + (when default + (setq default (concat "/" default)) + (unless (member default choices) + (setq default (concat "*." (file-name-extension default))) + (unless (member default choices) + (setq default nil)))) + (magit-completing-read "File or pattern to ignore" + choices nil nil nil nil default))) + +;;; Skip Worktree Commands + +;;;###autoload +(defun magit-skip-worktree (file) + "Call \"git update-index --skip-worktree -- FILE\"." + (interactive + (list (magit-read-file-choice "Skip worktree for" + (magit-with-toplevel + (cl-set-difference + (magit-list-files) + (magit-skip-worktree-files) + :test #'equal))))) + (magit-with-toplevel + (magit-run-git "update-index" "--skip-worktree" "--" file))) + +;;;###autoload +(defun magit-no-skip-worktree (file) + "Call \"git update-index --no-skip-worktree -- FILE\"." + (interactive + (list (magit-read-file-choice "Do not skip worktree for" + (magit-with-toplevel + (magit-skip-worktree-files))))) + (magit-with-toplevel + (magit-run-git "update-index" "--no-skip-worktree" "--" file))) + +;;; Assume Unchanged Commands + +;;;###autoload +(defun magit-assume-unchanged (file) + "Call \"git update-index --assume-unchanged -- FILE\"." + (interactive + (list (magit-read-file-choice "Assume file to be unchanged" + (magit-with-toplevel + (cl-set-difference + (magit-list-files) + (magit-assume-unchanged-files) + :test #'equal))))) + (magit-with-toplevel + (magit-run-git "update-index" "--assume-unchanged" "--" file))) + +;;;###autoload +(defun magit-no-assume-unchanged (file) + "Call \"git update-index --no-assume-unchanged -- FILE\"." + (interactive + (list (magit-read-file-choice "Do not assume file to be unchanged" + (magit-with-toplevel + (magit-assume-unchanged-files))))) + (magit-with-toplevel + (magit-run-git "update-index" "--no-assume-unchanged" "--" file))) + +;;; _ +(provide 'magit-gitignore) +;;; magit-gitignore.el ends here diff --git a/emacs/elpa/magit-20241004.917/magit-log.el b/emacs/elpa/magit-20241004.917/magit-log.el @@ -0,0 +1,2031 @@ +;;; magit-log.el --- Inspect Git history -*- lexical-binding:t; coding:utf-8 -*- + +;; Copyright (C) 2008-2024 The Magit Project Contributors + +;; Author: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> +;; Maintainer: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> + +;; SPDX-License-Identifier: GPL-3.0-or-later + +;; Magit is free software: you can redistribute it and/or modify it +;; under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. +;; +;; Magit is distributed in the hope that it will be useful, but WITHOUT +;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +;; or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public +;; License for more details. +;; +;; You should have received a copy of the GNU General Public License +;; along with Magit. If not, see <https://www.gnu.org/licenses/>. + +;;; Commentary: + +;; This library implements support for looking at Git logs, including +;; special logs like cherry-logs, as well as for selecting a commit +;; from a log. + +;;; Code: + +(require 'magit-core) +(require 'magit-diff) + +(declare-function magit-blob-visit "magit-files" (blob-or-file)) +(declare-function magit-cherry-apply "magit-sequence" (commit &optional args)) +(declare-function magit-insert-head-branch-header "magit-status" + (&optional branch)) +(declare-function magit-insert-upstream-branch-header "magit-status" + (&optional branch pull keyword)) +(declare-function magit-read-file-from-rev "magit-files" + (rev prompt &optional default include-dirs)) +(declare-function magit-rebase--get-state-lines "magit-sequence" + (file)) +(declare-function magit-show-commit "magit-diff" + (arg1 &optional arg2 arg3 arg4)) +(declare-function magit-reflog-format-subject "magit-reflog" (subject)) +(defvar magit-refs-focus-column-width) +(defvar magit-refs-margin) +(defvar magit-refs-show-commit-count) +(defvar magit-buffer-margin) +(defvar magit-status-margin) +(defvar magit-status-sections-hook) + +(require 'ansi-color) +(require 'crm) +(require 'which-func) + +;;; Options +;;;; Log Mode + +(defgroup magit-log nil + "Inspect and manipulate Git history." + :link '(info-link "(magit)Logging") + :group 'magit-commands + :group 'magit-modes) + +(defcustom magit-log-mode-hook nil + "Hook run after entering Magit-Log mode." + :group 'magit-log + :type 'hook) + +(defcustom magit-log-remove-graph-args '("--follow" "--grep" "-G" "-S" "-L") + "The log arguments that cause the `--graph' argument to be dropped. + +The default value lists the arguments that are incompatible with +`--graph' and therefore must be dropped when that is used. You +can add additional arguments that are available in `magit-log', +but I recommend that you don't do that. Nowadays I would define +this as a constant, but I am preserving it as an option, in case +someone actually customized it." + :package-version '(magit . "2.3.0") + :group 'magit-log + :type '(repeat (string :tag "Argument")) + :options '("--follow" "--grep" "-G" "-S" "-L")) + +(defcustom magit-log-revision-headers-format "\ +%+b%+N +Author: %aN <%aE> +Committer: %cN <%cE>" + "Additional format string used with the `++header' argument." + :package-version '(magit . "3.2.0") + :group 'magit-log + :type 'string) + +(defcustom magit-log-auto-more nil + "Insert more log entries automatically when moving past the last entry. +Only considered when moving past the last entry with +`magit-goto-*-section' commands." + :group 'magit-log + :type 'boolean) + +(defcustom magit-log-margin '(t age magit-log-margin-width t 18) + "Format of the margin in `magit-log-mode' buffers. + +The value has the form (INIT STYLE WIDTH AUTHOR AUTHOR-WIDTH). + +If INIT is non-nil, then the margin is shown initially. +STYLE controls how to format the author or committer date. + It can be one of `age' (to show the age of the commit), + `age-abbreviated' (to abbreviate the time unit to a character), + or a string (suitable for `format-time-string') to show the + actual date. Option `magit-log-margin-show-committer-date' + controls which date is being displayed. +WIDTH controls the width of the margin. This exists for forward + compatibility and currently the value should not be changed. +AUTHOR controls whether the name of the author is also shown by + default. +AUTHOR-WIDTH has to be an integer. When the name of the author + is shown, then this specifies how much space is used to do so." + :package-version '(magit . "2.9.0") + :group 'magit-log + :group 'magit-margin + :type magit-log-margin--custom-type + :initialize #'magit-custom-initialize-reset + :set (apply-partially #'magit-margin-set-variable 'magit-log-mode)) + +(defcustom magit-log-margin-show-committer-date nil + "Whether to show the committer date in the margin. + +This option only controls whether the committer date is displayed +instead of the author date. Whether some date is displayed in +the margin and whether the margin is displayed at all is +controlled by other options." + :package-version '(magit . "3.0.0") + :group 'magit-log + :group 'magit-margin + :type 'boolean) + +(defcustom magit-log-show-refname-after-summary nil + "Whether to show refnames after commit summaries. +This is useful if you use really long branch names." + :package-version '(magit . "2.2.0") + :group 'magit-log + :type 'boolean) + +(defcustom magit-log-highlight-keywords t + "Whether to highlight bracketed keywords in commit summaries." + :package-version '(magit . "2.12.0") + :group 'magit-log + :type 'boolean) + +(defcustom magit-log-header-line-function #'magit-log-header-line-sentence + "Function used to generate text shown in header line of log buffers." + :package-version '(magit . "2.12.0") + :group 'magit-log + :type '(choice (function-item magit-log-header-line-arguments) + (function-item magit-log-header-line-sentence) + function)) + +(defcustom magit-log-trace-definition-function #'magit-which-function + "Function used to determine the function at point. +This is used by the command `magit-log-trace-definition'. +You should prefer `magit-which-function' over `which-function' +because the latter may make use of Imenu's outdated cache." + :package-version '(magit . "3.0.0") + :group 'magit-log + :type '(choice (function-item magit-which-function) + (function-item which-function) + (function-item add-log-current-defun) + function)) + +(defcustom magit-log-color-graph-limit 256 + "Number of commits over which log graphs are not colored. +When showing more commits than specified, then the `--color' +argument is silently dropped. This is necessary because the +`ansi-color' library, which is used to turn control sequences +into faces, is just too slow." + :package-version '(magit . "4.0.0") + :group 'magit-log + :type 'number) + +(defcustom magit-log-show-signatures-limit 256 + "Number of commits over which signatures are not verified. +When showing more commits than specified by this option, then the +`--show-signature' argument, if specified, is silently dropped. +This is necessary because checking the signature of a large +number of commits is just too slow." + :package-version '(magit . "4.0.0") + :group 'magit-log + :type 'number) + +(defface magit-log-graph + '((((class color) (background light)) :foreground "grey30") + (((class color) (background dark)) :foreground "grey80")) + "Face for the graph part of the log output." + :group 'magit-faces) + +(defface magit-log-author + '((((class color) (background light)) + :foreground "firebrick" + :slant normal + :weight normal) + (((class color) (background dark)) + :foreground "tomato" + :slant normal + :weight normal)) + "Face for the author part of the log output." + :group 'magit-faces) + +(defface magit-log-date + '((((class color) (background light)) + :foreground "grey30" + :slant normal + :weight normal) + (((class color) (background dark)) + :foreground "grey80" + :slant normal + :weight normal)) + "Face for the date part of the log output." + :group 'magit-faces) + +(defface magit-header-line-log-select + '((t :inherit bold)) + "Face for the `header-line' in `magit-log-select-mode'." + :group 'magit-faces) + +;;;; File Log + +(defcustom magit-log-buffer-file-locked t + "Whether `magit-log-buffer-file-quick' uses a dedicated buffer." + :package-version '(magit . "2.7.0") + :group 'magit-commands + :group 'magit-log + :type 'boolean) + +;;;; Select Mode + +(defcustom magit-log-select-show-usage 'both + "Whether to show usage information when selecting a commit from a log. +The message can be shown in the `echo-area' or the `header-line', or in +`both' places. If the value isn't one of these symbols, then it should +be nil, in which case no usage information is shown." + :package-version '(magit . "2.1.0") + :group 'magit-log + :type '(choice (const :tag "in echo-area" echo-area) + (const :tag "in header-line" header-line) + (const :tag "in both places" both) + (const :tag "nowhere"))) + +(defcustom magit-log-select-margin + (list (nth 0 magit-log-margin) + (nth 1 magit-log-margin) + 'magit-log-margin-width t + (nth 4 magit-log-margin)) + "Format of the margin in `magit-log-select-mode' buffers. + +The value has the form (INIT STYLE WIDTH AUTHOR AUTHOR-WIDTH). + +If INIT is non-nil, then the margin is shown initially. +STYLE controls how to format the author or committer date. + It can be one of `age' (to show the age of the commit), + `age-abbreviated' (to abbreviate the time unit to a character), + or a string (suitable for `format-time-string') to show the + actual date. Option `magit-log-margin-show-committer-date' + controls which date is being displayed. +WIDTH controls the width of the margin. This exists for forward + compatibility and currently the value should not be changed. +AUTHOR controls whether the name of the author is also shown by + default. +AUTHOR-WIDTH has to be an integer. When the name of the author + is shown, then this specifies how much space is used to do so." + :package-version '(magit . "2.9.0") + :group 'magit-log + :group 'magit-margin + :type magit-log-margin--custom-type + :initialize #'magit-custom-initialize-reset + :set-after '(magit-log-margin) + :set (apply-partially #'magit-margin-set-variable 'magit-log-select-mode)) + +;;;; Cherry Mode + +(defcustom magit-cherry-sections-hook + '(magit-insert-cherry-headers + magit-insert-cherry-commits) + "Hook run to insert sections into the cherry buffer." + :package-version '(magit . "2.1.0") + :group 'magit-log + :type 'hook) + +(defcustom magit-cherry-margin + (list (nth 0 magit-log-margin) + (nth 1 magit-log-margin) + 'magit-log-margin-width t + (nth 4 magit-log-margin)) + "Format of the margin in `magit-cherry-mode' buffers. + +The value has the form (INIT STYLE WIDTH AUTHOR AUTHOR-WIDTH). + +If INIT is non-nil, then the margin is shown initially. +STYLE controls how to format the author or committer date. + It can be one of `age' (to show the age of the commit), + `age-abbreviated' (to abbreviate the time unit to a character), + or a string (suitable for `format-time-string') to show the + actual date. Option `magit-log-margin-show-committer-date' + controls which date is being displayed. +WIDTH controls the width of the margin. This exists for forward + compatibility and currently the value should not be changed. +AUTHOR controls whether the name of the author is also shown by + default. +AUTHOR-WIDTH has to be an integer. When the name of the author + is shown, then this specifies how much space is used to do so." + :package-version '(magit . "2.9.0") + :group 'magit-log + :group 'magit-margin + :type magit-log-margin--custom-type + :initialize #'magit-custom-initialize-reset + :set-after '(magit-log-margin) + :set (apply-partially #'magit-margin-set-variable 'magit-cherry-mode)) + +;;;; Log Sections + +(defcustom magit-log-section-commit-count 10 + "How many recent commits to show in certain log sections. +How many recent commits `magit-insert-recent-commits' and +`magit-insert-unpulled-from-upstream-or-recent' (provided +the upstream isn't ahead of the current branch) show." + :package-version '(magit . "2.1.0") + :group 'magit-status + :type 'number) + +(defcustom magit-log-merged-commit-count 20 + "How many surrounding commits to show for `magit-log-merged'. +`magit-log-merged' will shows approximately half of this number +commits before and half after." + :package-version '(magit . "3.3.0") + :group 'magit-log + :type 'integer) + +;;; Arguments +;;;; Prefix Classes + +(defclass magit-log-prefix (transient-prefix) + ((history-key :initform 'magit-log) + (major-mode :initform 'magit-log-mode))) + +(defclass magit-log-refresh-prefix (magit-log-prefix) + ((history-key :initform 'magit-log) + (major-mode :initform nil))) + +;;;; Prefix Methods + +(cl-defmethod transient-init-value ((obj magit-log-prefix)) + (pcase-let ((`(,args ,files) + (magit-log--get-value 'magit-log-mode + magit-prefix-use-buffer-arguments))) + (unless (eq transient-current-command 'magit-dispatch) + (when-let ((file (magit-file-relative-name))) + (setq files (list file)))) + (oset obj value (if files `(("--" ,@files) ,args) args)))) + +(cl-defmethod transient-init-value ((obj magit-log-refresh-prefix)) + (oset obj value (if magit-buffer-log-files + `(("--" ,@magit-buffer-log-files) + ,magit-buffer-log-args) + magit-buffer-log-args))) + +(cl-defmethod transient-set-value ((obj magit-log-prefix)) + (magit-log--set-value obj)) + +(cl-defmethod transient-save-value ((obj magit-log-prefix)) + (magit-log--set-value obj 'save)) + +;;;; Argument Access + +(defun magit-log-arguments (&optional mode) + "Return the current log arguments." + (if (memq transient-current-command '(magit-log magit-log-refresh)) + (magit--transient-args-and-files) + (magit-log--get-value (or mode 'magit-log-mode)))) + +(defun magit-log--get-value (mode &optional use-buffer-args) + (unless use-buffer-args + (setq use-buffer-args magit-direct-use-buffer-arguments)) + (let (args files) + (cond + ((and (memq use-buffer-args '(always selected current)) + (eq major-mode mode)) + (setq args magit-buffer-log-args) + (setq files magit-buffer-log-files)) + ((and (memq use-buffer-args '(always selected)) + (when-let ((buffer (magit-get-mode-buffer + mode nil + (eq use-buffer-args 'selected)))) + (setq args (buffer-local-value 'magit-buffer-log-args buffer)) + (setq files (buffer-local-value 'magit-buffer-log-files buffer)) + t))) + ((plist-member (symbol-plist mode) 'magit-log-current-arguments) + (setq args (get mode 'magit-log-current-arguments))) + ((when-let ((elt (assq (intern (format "magit-log:%s" mode)) + transient-values))) + (setq args (cdr elt)) + t)) + (t + (setq args (get mode 'magit-log-default-arguments)))) + (list args files))) + +(defun magit-log--set-value (obj &optional save) + (pcase-let* ((obj (oref obj prototype)) + (mode (or (oref obj major-mode) major-mode)) + (key (intern (format "magit-log:%s" mode))) + (`(,args ,files) (magit--transient-args-and-files))) + (put mode 'magit-log-current-arguments args) + (when save + (setf (alist-get key transient-values) args) + (transient-save-values)) + (transient--history-push obj) + (setq magit-buffer-log-args args) + (unless (derived-mode-p 'magit-log-select-mode) + (setq magit-buffer-log-files files)) + (magit-refresh))) + +;;; Commands +;;;; Prefix Commands + +;;;###autoload (autoload 'magit-log "magit-log" nil t) +(transient-define-prefix magit-log () + "Show a commit or reference log." + :man-page "git-log" + :class 'magit-log-prefix + ;; The grouping in git-log(1) appears to be guided by implementation + ;; details, so our logical grouping only follows it to an extend. + ;; Arguments that are "misplaced" here: + ;; 1. From "Commit Formatting". + ;; 2. From "Common Diff Options". + ;; 3. From unnamed first group. + ;; 4. Implemented by Magit. + ["Commit limiting" + (magit-log:-n) + (magit:--author) + (7 magit-log:--since) + (7 magit-log:--until) + (magit-log:--grep) + (7 "-i" "Search case-insensitive" ("-i" "--regexp-ignore-case")) + (7 "-I" "Invert search pattern" "--invert-grep") + (magit-log:-G) ;2 + (magit-log:-S) ;2 + (magit-log:-L) ;2 + (7 "=m" "Omit merges" "--no-merges") + (7 "=p" "First parent" "--first-parent")] + ["History simplification" + ( "-D" "Simplify by decoration" "--simplify-by-decoration") + (magit:--) + ( "-f" "Follow renames when showing single-file log" "--follow") ;3 + (6 "/s" "Only commits changing given paths" "--sparse") + (7 "/d" "Only selected commits plus meaningful history" "--dense") + (7 "/a" "Only commits existing directly on ancestry path" "--ancestry-path") + (6 "/f" "Do not prune history" "--full-history") + (7 "/m" "Prune some history" "--simplify-merges")] + ["Commit ordering" + (magit-log:--*-order) + ("-r" "Reverse order" "--reverse")] + ["Formatting" + ("-g" "Show graph" "--graph") ;1 + ("-c" "Show graph in color" "--color") ;2 + ("-d" "Show refnames" "--decorate") ;3 + ("=S" "Show signatures" "--show-signature") ;1 + ("-h" "Show header" "++header") ;4 + ("-p" "Show diffs" ("-p" "--patch")) ;2 + ("-s" "Show diffstats" "--stat")] ;2 + [["Log" + ("l" "current" magit-log-current) + ("h" "HEAD" magit-log-head) + ("u" "related" magit-log-related) + ("o" "other" magit-log-other)] + ["" + ("L" "local branches" magit-log-branches) + ("b" "all branches" magit-log-all-branches) + ("a" "all references" magit-log-all) + (7 "B" "matching branches" magit-log-matching-branches) + (7 "T" "matching tags" magit-log-matching-tags) + (7 "m" "merged" magit-log-merged)] + ["Reflog" + ("r" "current" magit-reflog-current) + ("H" "HEAD" magit-reflog-head) + ("O" "other" magit-reflog-other)] + [:if (lambda () + (and (fboundp 'magit--any-wip-mode-enabled-p) + (magit--any-wip-mode-enabled-p))) + :description "Wiplog" + ("i" "index" magit-wip-log-index) + ("w" "worktree" magit-wip-log-worktree)] + ["Other" + (5 "s" "shortlog" magit-shortlog)]]) + +;;;###autoload (autoload 'magit-log-refresh "magit-log" nil t) +(transient-define-prefix magit-log-refresh () + "Change the arguments used for the log(s) in the current buffer." + :man-page "git-log" + :class 'magit-log-refresh-prefix + [:if-mode magit-log-mode + :class transient-subgroups + ["Commit limiting" + (magit-log:-n) + (magit:--author) + (magit-log:--grep) + (7 "-i" "Search case-insensitive" ("-i" "--regexp-ignore-case")) + (7 "-I" "Invert search pattern" "--invert-grep") + (magit-log:-G) + (magit-log:-S) + (magit-log:-L)] + ["History simplification" + ( "-D" "Simplify by decoration" "--simplify-by-decoration") + (magit:--) + ( "-f" "Follow renames when showing single-file log" "--follow") ;3 + (6 "/s" "Only commits changing given paths" "--sparse") + (7 "/d" "Only selected commits plus meaningful history" "--dense") + (7 "/a" "Only commits existing directly on ancestry path" "--ancestry-path") + (6 "/f" "Do not prune history" "--full-history") + (7 "/m" "Prune some history" "--simplify-merges")] + ["Commit ordering" + (magit-log:--*-order) + ("-r" "Reverse order" "--reverse")] + ["Formatting" + ("-g" "Show graph" "--graph") + ("-c" "Show graph in color" "--color") + ("-d" "Show refnames" "--decorate") + ("=S" "Show signatures" "--show-signature") + ("-h" "Show header" "++header") + ("-p" "Show diffs" ("-p" "--patch")) + ("-s" "Show diffstats" "--stat")]] + [:if-not-mode magit-log-mode + :description "Arguments" + (magit-log:-n) + (magit-log:--*-order) + ("-g" "Show graph" "--graph") + ("-c" "Show graph in color" "--color") + ("-d" "Show refnames" "--decorate")] + [["Refresh" + ("g" "buffer" magit-log-refresh) + ("s" "buffer and set defaults" transient-set-and-exit) + ("w" "buffer and save defaults" transient-save-and-exit)] + ["Margin" + (magit-toggle-margin) + (magit-cycle-margin-style) + (magit-toggle-margin-details) + (magit-toggle-log-margin-style)] + [:if-mode magit-log-mode + :description "Toggle" + ("b" "buffer lock" magit-toggle-buffer-lock)]] + (interactive) + (cond + ((not (eq transient-current-command 'magit-log-refresh)) + (pcase major-mode + ('magit-reflog-mode + (user-error "Cannot change log arguments in reflog buffers")) + ('magit-cherry-mode + (user-error "Cannot change log arguments in cherry buffers"))) + (transient-setup 'magit-log-refresh)) + (t + (pcase-let ((`(,args ,files) (magit-log-arguments))) + (setq magit-buffer-log-args args) + (unless (derived-mode-p 'magit-log-select-mode) + (setq magit-buffer-log-files files))) + (magit-refresh)))) + +;;;; Infix Commands + +(transient-define-argument magit-log:-n () + :description "Limit number of commits" + :class 'transient-option + ;; For historic reasons (and because it easy to guess what "-n" + ;; stands for) this is the only argument where we do not use the + ;; long argument ("--max-count"). + :shortarg "-n" + :argument "-n" + :reader #'transient-read-number-N+) + +(transient-define-argument magit:--author () + :description "Limit to author" + :class 'transient-option + :key "-A" + :argument "--author=" + :reader #'magit-transient-read-person) + +(transient-define-argument magit-log:--since () + :description "Limit to commits since" + :class 'transient-option + :key "=s" + :argument "--since=" + :reader #'transient-read-date) + +(transient-define-argument magit-log:--until () + :description "Limit to commits until" + :class 'transient-option + :key "=u" + :argument "--until=" + :reader #'transient-read-date) + +(transient-define-argument magit-log:--*-order () + :description "Order commits by" + :class 'transient-switches + :key "-o" + :argument-format "--%s-order" + :argument-regexp "\\(--\\(topo\\|author-date\\|date\\)-order\\)" + :choices '("topo" "author-date" "date")) + +(transient-define-argument magit-log:--grep () + :description "Search messages" + :class 'transient-option + :key "-F" + :argument "--grep=") + +(transient-define-argument magit-log:-G () + :description "Search changes" + :class 'transient-option + :argument "-G") + +(transient-define-argument magit-log:-S () + :description "Search occurrences" + :class 'transient-option + :argument "-S") + +(transient-define-argument magit-log:-L () + :description "Trace line evolution" + :class 'transient-option + :argument "-L" + :reader #'magit-read-file-trace) + +(defun magit-read-file-trace (&rest _ignored) + (let ((file (magit-read-file-from-rev "HEAD" "File")) + (trace (magit-read-string "Trace"))) + (concat trace ":" file))) + +;;;; Setup Commands + +(defvar-keymap magit-log-read-revs-map + :parent crm-local-completion-map + "SPC" #'self-insert-command) + +(defun magit-log-read-revs (&optional use-current) + (or (and use-current (and-let* ((buf (magit-get-current-branch))) (list buf))) + (let ((crm-separator "\\(\\.\\.\\.?\\|[, ]\\)") + (crm-local-completion-map magit-log-read-revs-map)) + (split-string (magit-completing-read-multiple + "Log rev,s: " + (magit-list-refnames nil t) + nil nil nil 'magit-revision-history + (or (magit-branch-or-commit-at-point) + (and (not use-current) + (magit-get-previous-branch))) + nil t) + "[, ]" t)))) + +(defun magit-log-read-pattern (option) + "Read a string from the user to pass as parameter to OPTION." + (magit-read-string (format "Type a pattern to pass to %s" option))) + +;;;###autoload +(defun magit-log-current (revs &optional args files) + "Show log for the current branch. +When `HEAD' is detached or with a prefix argument show log for +one or more revs read from the minibuffer." + (interactive (cons (magit-log-read-revs t) + (magit-log-arguments))) + (magit-log-setup-buffer revs args files)) + +;;;###autoload +(defun magit-log-head (&optional args files) + "Show log for `HEAD'." + (interactive (magit-log-arguments)) + (magit-log-setup-buffer (list "HEAD") args files)) + +;;;###autoload +(defun magit-log-related (revs &optional args files) + "Show log for the current branch, its upstream and its push target. +When the upstream is a local branch, then also show its own +upstream. When `HEAD' is detached, then show log for that, the +previously checked out branch and its upstream and push-target." + (interactive + (cons (let ((current (magit-get-current-branch)) + head rebase target upstream upup) + (unless current + (setq rebase (magit-rebase--get-state-lines "head-name")) + (cond (rebase + (setq rebase (magit-ref-abbrev rebase)) + (setq current rebase) + (setq head "HEAD")) + ((setq current (magit-get-previous-branch))))) + (cond (current + (setq current + (magit--propertize-face current 'magit-branch-local)) + (setq target (magit-get-push-branch current t)) + (setq upstream (magit-get-upstream-branch current)) + (when upstream + (setq upup (and (magit-local-branch-p upstream) + (magit-get-upstream-branch upstream))))) + ((setq head "HEAD"))) + (delq nil (list current head target upstream upup))) + (magit-log-arguments))) + (magit-log-setup-buffer revs args files)) + +;;;###autoload +(defun magit-log-other (revs &optional args files) + "Show log for one or more revs read from the minibuffer. +The user can input any revision or revisions separated by a +space, or even ranges, but only branches and tags, and a +representation of the commit at point, are available as +completion candidates." + (interactive (cons (magit-log-read-revs) + (magit-log-arguments))) + (magit-log-setup-buffer revs args files)) + +;;;###autoload +(defun magit-log-branches (&optional args files) + "Show log for all local branches and `HEAD'." + (interactive (magit-log-arguments)) + (magit-log-setup-buffer (if (magit-get-current-branch) + (list "--branches") + (list "HEAD" "--branches")) + args files)) + +;;;###autoload +(defun magit-log-matching-branches (pattern &optional args files) + "Show log for all branches matching PATTERN and `HEAD'." + (interactive (cons (magit-log-read-pattern "--branches") (magit-log-arguments))) + (magit-log-setup-buffer + (list "HEAD" (format "--branches=%s" pattern)) + args files)) + +;;;###autoload +(defun magit-log-matching-tags (pattern &optional args files) + "Show log for all tags matching PATTERN and `HEAD'." + (interactive (cons (magit-log-read-pattern "--tags") (magit-log-arguments))) + (magit-log-setup-buffer + (list "HEAD" (format "--tags=%s" pattern)) + args files)) + +;;;###autoload +(defun magit-log-all-branches (&optional args files) + "Show log for all local and remote branches and `HEAD'." + (interactive (magit-log-arguments)) + (magit-log-setup-buffer (if (magit-get-current-branch) + (list "--branches" "--remotes") + (list "HEAD" "--branches" "--remotes")) + args files)) + +;;;###autoload +(defun magit-log-all (&optional args files) + "Show log for all references and `HEAD'." + (interactive (magit-log-arguments)) + (magit-log-setup-buffer (if (magit-get-current-branch) + (list "--all") + (list "HEAD" "--all")) + args files)) + +;;;###autoload +(defun magit-log-buffer-file (&optional follow beg end) + "Show log for the blob or file visited in the current buffer. +With a prefix argument or when `--follow' is an active log +argument, then follow renames. When the region is active, +restrict the log to the lines that the region touches." + (interactive + (cons current-prefix-arg + (and (region-active-p) + (magit-file-relative-name) + (not (derived-mode-p 'dired-mode)) + (save-restriction + (widen) + (list (line-number-at-pos (region-beginning)) + (line-number-at-pos + (let ((end (region-end))) + (if (char-after end) + end + ;; Ensure that we don't get the line number + ;; of a trailing newline. + (1- end))))))))) + (require 'magit) + (if-let ((file (magit-file-relative-name))) + (magit-log-setup-buffer + (list (or magit-buffer-refname + (magit-get-current-branch) + "HEAD")) + (let ((args (car (magit-log-arguments)))) + (when (and follow (not (member "--follow" args))) + (push "--follow" args)) + (when (and beg end) + (setq args (cons (format "-L%s,%s:%s" beg end file) + (cl-delete "-L" args :test + #'string-prefix-p))) + (setq file nil)) + args) + (and file (list file)) + magit-log-buffer-file-locked) + (user-error "Buffer isn't visiting a file"))) + +;;;###autoload +(defun magit-log-trace-definition (file fn rev) + "Show log for the definition at point." + (interactive (list (or (magit-file-relative-name) + (user-error "Buffer isn't visiting a file")) + (or (funcall magit-log-trace-definition-function) + (user-error "No function at point found")) + (or magit-buffer-refname + (magit-get-current-branch) + "HEAD"))) + (require 'magit) + (magit-log-setup-buffer + (list rev) + (cons (format "-L:%s%s:%s" + (string-replace ":" "\\:" (regexp-quote fn)) + (if (derived-mode-p 'lisp-mode 'emacs-lisp-mode) + ;; Git doesn't treat "-" the same way as + ;; "_", leading to false-positives such as + ;; "foo-suffix" being considered a match + ;; for "foo". Wing it. + "\\( \\|$\\)" + ;; We could use "\\b" here, but since Git + ;; already does something equivalent, that + ;; isn't necessary. + "") + file) + (cl-delete "-L" (car (magit-log-arguments)) + :test #'string-prefix-p)) + nil magit-log-buffer-file-locked)) + +(defun magit-diff-trace-definition () + "Show log for the definition at point in a diff." + (interactive) + (pcase-let ((`(,buf ,pos) (magit-diff-visit-file--noselect))) + (magit--with-temp-position buf pos + (call-interactively #'magit-log-trace-definition)))) + +;;;###autoload +(defun magit-log-merged (commit branch &optional args files) + "Show log for the merge of COMMIT into BRANCH. + +More precisely, find merge commit M that brought COMMIT into +BRANCH, and show the log of the range \"M^1..M\". If COMMIT is +directly on BRANCH, then show approximately +`magit-log-merged-commit-count' surrounding commits instead. + +This command requires git-when-merged, which is available from +https://github.com/mhagger/git-when-merged." + (interactive + (append (let ((commit (magit-read-branch-or-commit "Log merge of commit"))) + (list commit + (magit-read-other-branch "Merged into" commit))) + (magit-log-arguments))) + (unless (magit-git-executable-find "git-when-merged") + (user-error "This command requires git-when-merged (%s)" + "https://github.com/mhagger/git-when-merged")) + (let (exit m) + (with-temp-buffer + (save-excursion + (setq exit (magit-process-git t "when-merged" "-c" + (magit-abbrev-arg) + commit branch))) + (setq m (buffer-substring-no-properties (point) (line-end-position)))) + (if (zerop exit) + (magit-log-setup-buffer (list (format "%s^1..%s" m m)) + args files nil commit) + ;; Output: "<ref><lots of spaces><message>". + ;; This is not the same as `string-trim'. + (setq m (string-trim-left (substring m (string-match " " m)))) + (if (equal m "Commit is directly on this branch.") + (let* ((from (format "%s~%d" commit + (/ magit-log-merged-commit-count 2))) + (to (- (car (magit-rev-diff-count branch commit t)) + (/ magit-log-merged-commit-count 2))) + (to (if (<= to 0) + branch + (format "%s~%s" branch to)))) + (unless (magit-rev-verify-commit from) + (setq from (magit-git-string "rev-list" "--max-parents=0" + commit))) + (magit-log-setup-buffer (list (concat from ".." to)) + (cons "--first-parent" args) + files nil commit)) + (user-error "Could not find when %s was merged into %s: %s" + commit branch m))))) + +;;;; Limit Commands + +(defun magit-log-toggle-commit-limit () + "Toggle the number of commits the current log buffer is limited to. +If the number of commits is currently limited, then remove that +limit. Otherwise set it to 256." + (interactive) + (magit-log-set-commit-limit (lambda (&rest _) nil))) + +(defun magit-log-double-commit-limit () + "Double the number of commits the current log buffer is limited to." + (interactive) + (magit-log-set-commit-limit '*)) + +(defun magit-log-half-commit-limit () + "Half the number of commits the current log buffer is limited to." + (interactive) + (magit-log-set-commit-limit '/)) + +(defun magit-log-set-commit-limit (fn) + (let* ((val magit-buffer-log-args) + (arg (--first (string-match "^-n\\([0-9]+\\)?$" it) val)) + (num (and arg (string-to-number (match-string 1 arg)))) + (num (if num (funcall fn num 2) 256))) + (setq val (remove arg val)) + (setq magit-buffer-log-args + (if (and num (> num 0)) + (cons (format "-n%d" num) val) + val))) + (magit-refresh)) + +(defun magit-log-get-commit-limit (&optional args) + (and-let* ((str (--first (string-match "^-n\\([0-9]+\\)?$" it) + (or args magit-buffer-log-args)))) + (string-to-number (match-string 1 str)))) + +;;;; Mode Commands + +(defun magit-log-bury-buffer (&optional arg) + "Bury the current buffer or the revision buffer in the same frame. +Like `magit-mode-bury-buffer' (which see) but with a negative +prefix argument instead bury the revision buffer, provided it +is displayed in the current frame." + (interactive "p") + (if (< arg 0) + (let* ((buf (magit-get-mode-buffer 'magit-revision-mode)) + (win (and buf (get-buffer-window buf (selected-frame))))) + (if win + (with-selected-window win + (with-current-buffer buf + (magit-mode-bury-buffer (> (abs arg) 1)))) + (user-error "No revision buffer in this frame"))) + (magit-mode-bury-buffer (> arg 1)))) + +;;;###autoload +(defun magit-log-move-to-parent (&optional n) + "Move to the Nth parent of the current commit." + (interactive "p") + (when (derived-mode-p 'magit-log-mode) + (when (magit-section-match 'commit) + (let* ((section (magit-current-section)) + (parent-rev (format "%s^%s" (oref section value) (or n 1)))) + (if-let ((parent-hash (magit-rev-parse "--short" parent-rev))) + (if-let ((parent (--first (equal (oref it value) + parent-hash) + (magit-section-siblings section 'next)))) + (magit-section-goto parent) + (user-error + (substitute-command-keys + (concat "Parent " parent-hash " not found. Try typing " + "\\[magit-log-double-commit-limit] first")))) + (user-error "Parent %s does not exist" parent-rev)))))) + +(defun magit-log-move-to-revision (rev) + "Read a revision and move to it in current log buffer. + +If the chosen reference or revision isn't being displayed in +the current log buffer, then inform the user about that and do +nothing else. + +If invoked outside any log buffer, then display the log buffer +of the current repository first; creating it if necessary." + (interactive + (list (or (magit-completing-read + "In log, jump to" + (magit-list-refnames nil t) + nil nil nil 'magit-revision-history + (or (and-let* ((rev (magit-commit-at-point))) + (magit-rev-fixup-target rev)) + (magit-get-current-branch))) + (user-error "Nothing selected")))) + (with-current-buffer + (cond ((derived-mode-p 'magit-log-mode) + (current-buffer)) + ((and-let* ((buf (magit-get-mode-buffer 'magit-log-mode))) + (pop-to-buffer-same-window buf))) + (t + (apply #'magit-log-all-branches (magit-log-arguments)))) + (unless (magit-log-goto-commit-section (magit-rev-abbrev rev)) + (user-error "%s isn't visible in the current log buffer" rev)))) + +;;;; Shortlog Commands + +;;;###autoload (autoload 'magit-shortlog "magit-log" nil t) +(transient-define-prefix magit-shortlog () + "Show a history summary." + :man-page "git-shortlog" + :value '("--numbered" "--summary") + ["Arguments" + ("-n" "Sort by number of commits" ("-n" "--numbered")) + ("-s" "Show commit count summary only" ("-s" "--summary")) + ("-e" "Show email addresses" ("-e" "--email")) + ("-g" "Group commits by" "--group=" + :choices ("author" "committer" "trailer:")) + (7 "-f" "Format string" "--format=") + (7 "-w" "Linewrap" "-w" :class transient-option)] + ["Shortlog" + ("s" "since" magit-shortlog-since) + ("r" "range" magit-shortlog-range)]) + +(defun magit-git-shortlog (rev args) + (let ((dir default-directory)) + (with-current-buffer (get-buffer-create "*magit-shortlog*") + (setq default-directory dir) + (setq buffer-read-only t) + (let ((inhibit-read-only t)) + (erase-buffer) + (save-excursion + (magit-git-insert "shortlog" args rev)) + (switch-to-buffer-other-window (current-buffer)))))) + +;;;###autoload +(defun magit-shortlog-since (rev args) + "Show a history summary for commits since REV." + (interactive + (list (magit-read-branch-or-commit "Shortlog since" (magit-get-current-tag)) + (transient-args 'magit-shortlog))) + (magit-git-shortlog (concat rev "..") args)) + +;;;###autoload +(defun magit-shortlog-range (rev-or-range args) + "Show a history summary for commit or range REV-OR-RANGE." + (interactive + (list (magit-read-range-or-commit "Shortlog for revision or range") + (transient-args 'magit-shortlog))) + (magit-git-shortlog rev-or-range args)) + +;;; Log Mode + +(defvar magit-log-disable-graph-hack-args + '("-G" "--grep" "--author") + "Arguments which disable the graph speedup hack.") + +(defvar-keymap magit-log-mode-map + :doc "Keymap for `magit-log-mode'." + :parent magit-mode-map + "C-c C-b" #'magit-go-backward + "C-c C-f" #'magit-go-forward + "C-c C-n" #'magit-log-move-to-parent + "j" #'magit-log-move-to-revision + "=" #'magit-log-toggle-commit-limit + "+" #'magit-log-double-commit-limit + "-" #'magit-log-half-commit-limit + "q" #'magit-log-bury-buffer) + +(define-derived-mode magit-log-mode magit-mode "Magit Log" + "Mode for looking at Git log. + +This mode is documented in info node `(magit)Log Buffer'. + +\\<magit-mode-map>\ +Type \\[magit-refresh] to refresh the current buffer. +Type \\[magit-visit-thing] or \\[magit-diff-show-or-scroll-up] \ +to visit the commit at point. + +Type \\[magit-branch] to see available branch commands. +Type \\[magit-merge] to merge the branch or commit at point. +Type \\[magit-cherry-pick] to apply the commit at point. +Type \\[magit-reset] to reset `HEAD' to the commit at point. + +\\{magit-log-mode-map}" + :interactive nil + :group 'magit-log + (magit-hack-dir-local-variables) + (setq magit--imenu-item-types 'commit)) + +(put 'magit-log-mode 'magit-log-default-arguments + '("--graph" "-n256" "--decorate")) + +(defun magit-log-setup-buffer (revs args files &optional locked focus) + (require 'magit) + (with-current-buffer + (magit-setup-buffer #'magit-log-mode locked + (magit-buffer-revisions revs) + (magit-buffer-log-args args) + (magit-buffer-log-files files)) + (when (if focus + (magit-log-goto-commit-section focus) + (magit-log-goto-same-commit)) + (magit-section-update-highlight)) + (current-buffer))) + +(defun magit-log-refresh-buffer () + (let ((revs magit-buffer-revisions) + (args magit-buffer-log-args) + (files magit-buffer-log-files) + (limit (magit-log-get-commit-limit))) + (magit-set-header-line-format + (funcall magit-log-header-line-function revs args files)) + (unless (length= files 1) + (setq args (remove "--follow" args))) + (when (and (car magit-log-remove-graph-args) + (--any-p (string-match-p + (concat "^" (regexp-opt magit-log-remove-graph-args)) it) + args)) + (setq args (remove "--graph" args))) + (setq args (magit-log--maybe-drop-color-graph args limit)) + (when-let* ((limit limit) + (limit (* 2 limit)) ; increase odds for complete graph + (count (and (length= revs 1) + (> limit 1024) ; otherwise it's fast enough + (setq revs (car revs)) + (not (string-search ".." revs)) + (not (member revs '("--all" "--branches"))) + (not (seq-some + (lambda (arg) + (--any-p (string-prefix-p it arg) + magit-log-disable-graph-hack-args)) + args)) + (magit-git-string "rev-list" "--count" + "--first-parent" args revs)))) + (setq revs (if (< (string-to-number count) limit) + revs + (format "%s~%s..%s" revs limit revs)))) + (let ((delay (cl-find-if (lambda (arg) + (member arg '("++header" "--patch" "--stat"))) + args))) + (setq magit-section-inhibit-markers (if delay 'delay t)) + (setq magit-section-insert-in-reverse (not delay))) + (magit-insert-section (logbuf) + (magit--insert-log t revs args files)))) + +(defvar-local magit-log--color-graph nil) + +(defun magit-log--maybe-drop-color-graph (args limit) + (if (member "--color" args) + (if (cond ((not (member "--graph" args))) + ((not magit-log-color-graph-limit) nil) + ((not limit) + (message "Dropping --color because -n isn't set (see %s)" + 'magit-log-color-graph-limit)) + ((> limit magit-log-color-graph-limit) + (message "Dropping --color because -n is larger than %s" + 'magit-log-color-graph-limit))) + (progn (setq args (remove "--color" args)) + (setq magit-log--color-graph nil)) + (setq magit-log--color-graph t)) + (setq magit-log--color-graph nil)) + args) + +(cl-defmethod magit-buffer-value (&context (major-mode magit-log-mode)) + (append magit-buffer-revisions + (if (and magit-buffer-revisions magit-buffer-log-files) + (cons "--" magit-buffer-log-files) + magit-buffer-log-files))) + +(defun magit-log-header-line-arguments (revs args files) + "Return string describing some of the used arguments." + (mapconcat (lambda (arg) + (if (string-search " " arg) + (prin1 arg) + arg)) + `("git" "log" ,@args ,@revs "--" ,@files) + " ")) + +(defun magit-log-header-line-sentence (revs args files) + "Return string containing all arguments." + (concat "Commits in " + (string-join revs " ") + (and (member "--reverse" args) + " in reverse") + (and files (concat " touching " + (string-join files " "))) + (--some (and (string-prefix-p "-L" it) + (concat " " it)) + args))) + +(defun magit-insert-log (revs &optional args files) + (declare (obsolete magit--insert-log "Magit 4.0.0")) + (magit--insert-log nil revs args files)) + +(defun magit--insert-log (keep-error revs &optional args files) + "Insert a log section. +Do not add this to a hook variable." + (declare (indent defun)) + (setq magit-section-preserve-visibility t) ; TODO do it here? + (let ((magit-git-global-arguments + (remove "--literal-pathspecs" magit-git-global-arguments))) + (magit--git-wash (apply-partially #'magit-log-wash-log 'log) keep-error + "log" + (format "--format=%s%%h%%x0c%s%%x0c%s%%x0c%%aN%%x0c%s%%x0c%%s%s" + (if (and (member "--left-right" args) + (not (member "--graph" args))) + "%m " + "") + (if (member "--decorate" args) "%D" "") + (if (not (member "--show-signature" args)) + "" + (setq args (remove "--show-signature" args)) + (let ((limit (magit-log-get-commit-limit args))) + (cond + ((not limit) + (message + "Dropping --show-signature because -n isn't set (see %s)" + 'magit-log-show-signatures-limit) + "") + ((> limit magit-log-show-signatures-limit) + (message + "Dropping --show-signature because -n is larger than %s" + 'magit-log-show-signatures-limit) + "") + ("%G?")))) + (if magit-log-margin-show-committer-date "%ct" "%at") + (if (member "++header" args) + (if (member "--graph" (setq args (remove "++header" args))) + (concat "\n" magit-log-revision-headers-format "\n") + (concat "\n" magit-log-revision-headers-format "\n")) + "")) + (progn + (when-let ((order (--first (string-match "^\\+\\+order=\\(.+\\)$" it) + args))) + (setq args (cons (format "--%s-order" (match-string 1 order)) + (remove order args)))) + (when (member "--decorate" args) + (setq args (cons "--decorate=full" (remove "--decorate" args)))) + (when (member "--reverse" args) + (setq args (remove "--graph" args))) + (setq args (magit-diff--maybe-add-stat-arguments args)) + args) + "--use-mailmap" "--no-prefix" revs "--" files))) + +(cl-defmethod magit-menu-common-value ((_section magit-commit-section)) + (or (magit-diff--region-range) + (oref (magit-current-section) value))) + +(defvar-keymap magit-commit-section-map + :doc "Keymap for `commit' sections." + "<remap> <magit-visit-thing>" #'magit-show-commit + "<3>" (magit-menu-item "Apply %x" #'magit-cherry-apply) + "<2>" (magit-menu-item "Show commit %x" #'magit-show-commit + '(:visible (not (region-active-p)))) + "<1>" (magit-menu-item "Diff %x" #'magit-diff-range + '(:visible (region-active-p)))) + +(defvar-keymap magit-module-commit-section-map + :doc "Keymap for `module-commit' sections." + :parent magit-commit-section-map) + +(defconst magit-log-heading-re + ;; Note: A form feed instead of a null byte is used as the delimiter + ;; because using the latter interferes with the graph prefix when + ;; ++header is used. + (concat "^" + "\\(?4:[-_/|\\*o<>. ]*\\)" ; graph + "\\(?1:[0-9a-fA-F]+\\)?" ; hash + "\\(?3:[^\n]+\\)?" ; refs + "\\(?7:[BGUXYREN]\\)?" ; gpg + "\\(?5:[^\n]*\\)" ; author + ;; Note: Date is optional because, prior to Git v2.19.0, + ;; `git rebase -i --root` corrupts the root's author date. + "\\(?6:[^\n]*\\)" ; date + "\\(?2:.*\\)$")) ; msg + +(defconst magit-log-cherry-re + (concat "^" + "\\(?8:[-+]\\) " ; cherry + "\\(?1:[0-9a-fA-F]+\\) " ; hash + "\\(?2:.*\\)$")) ; msg + +(defconst magit-log-module-re + (concat "^" + "\\(?:\\(?11:[<>]\\) \\)?" ; side + "\\(?1:[0-9a-fA-F]+\\) " ; hash + "\\(?2:.*\\)$")) ; msg + +(defconst magit-log-bisect-vis-re + (concat "^" + "\\(?4:[-_/|\\*o<>. ]*\\)" ; graph + "\\(?1:[0-9a-fA-F]+\\)?\0" ; hash + "\\(?3:[^\0\n]+\\)?\0" ; refs + "\\(?2:.*\\)$")) ; msg + +(defconst magit-log-bisect-log-re + (concat "^# " + "\\(?3:[^: \n]+:\\) " ; "refs" + "\\[\\(?1:[^]\n]+\\)\\] " ; hash + "\\(?2:.*\\)$")) ; msg + +(defconst magit-log-reflog-re + (concat "^" + "\\(?1:[^\0\n]+\\)\0" ; hash + "\\(?5:[^\0\n]*\\)\0" ; author + "\\(?:\\(?:[^@\n]+@{\\(?6:[^}\n]+\\)}\0" ; date + ;;; refsub + "\\(?10:merge \\|autosave \\|restart \\|rewritten \\|[^:\n]+: \\)?" + "\\(?2:.*\\)\\)\\|\0\\)$")) ; msg + +(defconst magit-reflog-subject-re + (concat "\\(?1:[^ ]+\\) ?" ; command + "\\(?2:\\(?: ?-[^ ]+\\)+\\)?" ; option + "\\(?: ?(\\(?3:[^)]+\\))\\)?")) ; type + +(defconst magit-log-stash-re + (concat "^" + "\\(?1:[^\0\n]+\\)\0" ; "hash" + "\\(?5:[^\0\n]*\\)\0" ; author + "\\(?6:[^\0\n]+\\)\0" ; date + "\\(?2:.*\\)$")) ; msg + +(defvar magit-log-count nil) + +(defvar magit-log-format-message-function #'magit-log-propertize-keywords) + +(defun magit-log-wash-log (style args) + (setq args (flatten-tree args)) + (when (if (derived-mode-p 'magit-log-mode) + magit-log--color-graph + (and (member "--graph" args) + (member "--color" args))) + (let ((ansi-color-apply-face-function + (lambda (beg end face) + (put-text-property beg end 'font-lock-face + (or face 'magit-log-graph))))) + (ansi-color-apply-on-region (point-min) (point-max)))) + (when (eq style 'cherry) + (reverse-region (point-min) (point-max))) + (let ((magit-log-count 0)) + (when (looking-at "^\\.\\.\\.") + (magit-delete-line)) + (magit-wash-sequence (apply-partially #'magit-log-wash-rev style + (magit-abbrev-length))) + (if (derived-mode-p 'magit-log-mode 'magit-reflog-mode) + (when (eq magit-log-count (magit-log-get-commit-limit)) + (magit-insert-section (longer) + (insert-text-button + (substitute-command-keys + (format "Type \\<%s>\\[%s] to show more history" + 'magit-log-mode-map + 'magit-log-double-commit-limit)) + 'action (lambda (_button) + (magit-log-double-commit-limit)) + 'follow-link t + 'mouse-face 'magit-section-highlight))) + (insert ?\n)))) + +(cl-defun magit-log-wash-rev (style abbrev) + (when (derived-mode-p 'magit-log-mode 'magit-reflog-mode) + (cl-incf magit-log-count)) + (looking-at (pcase style + ('log magit-log-heading-re) + ('cherry magit-log-cherry-re) + ('module magit-log-module-re) + ('reflog magit-log-reflog-re) + ('stash magit-log-stash-re) + ('bisect-vis magit-log-bisect-vis-re) + ('bisect-log magit-log-bisect-log-re))) + (magit-bind-match-strings + (hash msg refs graph author date gpg cherry _ refsub side) nil + (setq msg (substring-no-properties msg)) + (when refs + (setq refs (substring-no-properties refs))) + (let ((align (or (eq style 'cherry) + (not (member "--stat" magit-buffer-log-args)))) + (non-graph-re (if (eq style 'bisect-vis) + magit-log-bisect-vis-re + magit-log-heading-re))) + (magit-delete-line) + ;; If the reflog entries have been pruned, the output of `git + ;; reflog show' includes a partial line that refers to the hash + ;; of the youngest expired reflog entry. + (when (and (eq style 'reflog) (not date)) + (cl-return-from magit-log-wash-rev t)) + (magit-insert-section + ((eval (pcase style + ('stash 'stash) + ('module 'module-commit) + (_ 'commit))) + hash) + (setq hash (propertize (if (eq style 'bisect-log) + (magit-rev-parse "--short" hash) + hash) + 'font-lock-face + (pcase (and gpg (aref gpg 0)) + (?G 'magit-signature-good) + (?B 'magit-signature-bad) + (?U 'magit-signature-untrusted) + (?X 'magit-signature-expired) + (?Y 'magit-signature-expired-key) + (?R 'magit-signature-revoked) + (?E 'magit-signature-error) + (?N 'magit-hash) + (_ 'magit-hash)))) + (when cherry + (when (and (derived-mode-p 'magit-refs-mode) + magit-refs-show-commit-count) + (insert (make-string (1- magit-refs-focus-column-width) ?\s))) + (insert (propertize cherry 'font-lock-face + (if (string= cherry "-") + 'magit-cherry-equivalent + 'magit-cherry-unmatched))) + (insert ?\s)) + (when side + (insert (propertize side 'font-lock-face + (if (string= side "<") + 'magit-cherry-equivalent + 'magit-cherry-unmatched))) + (insert ?\s)) + (when align + (insert hash ?\s)) + (when graph + (insert graph)) + (unless align + (insert hash ?\s)) + (when (and refs (not magit-log-show-refname-after-summary)) + (insert (magit-format-ref-labels refs) ?\s)) + (when (eq style 'reflog) + (insert (format "%-2s " (1- magit-log-count))) + (when refsub + (insert (magit-reflog-format-subject + (substring refsub 0 + (if (string-search ":" refsub) -2 -1)))))) + (insert (funcall magit-log-format-message-function hash msg)) + (when (and refs magit-log-show-refname-after-summary) + (insert ?\s) + (insert (magit-format-ref-labels refs))) + (insert ?\n) + (when (memq style '(log reflog stash)) + (goto-char (line-beginning-position)) + (when (and refsub + (string-match "\\`\\([^ ]\\) \\+\\(..\\)\\(..\\)" date)) + (setq date (+ (string-to-number (match-string 1 date)) + (* (string-to-number (match-string 2 date)) 60 60) + (* (string-to-number (match-string 3 date)) 60)))) + (save-excursion + (backward-char) + (magit-log-format-margin hash author date))) + (when (and (eq style 'cherry) + (magit-buffer-margin-p)) + (save-excursion + (backward-char) + (apply #'magit-log-format-margin hash + (split-string (magit-rev-format "%aN%x00%ct" hash) "\0")))) + (when (and graph + (not (eobp)) + (not (looking-at non-graph-re))) + (when (looking-at "") + (magit-insert-heading) + (delete-char 1) + (magit-insert-section (commit-header) + (forward-line) + (magit-insert-heading) + (re-search-forward "") + (delete-char -1) + (forward-char) + (insert ?\n)) + (delete-char 1)) + (if (looking-at "^\\(---\\|\n\s\\|\ndiff\\)") + (let ((limit (save-excursion + (and (re-search-forward non-graph-re nil t) + (match-beginning 0))))) + (unless (oref magit-insert-section--current content) + (magit-insert-heading)) + (delete-char (if (looking-at "\n") 1 4)) + (magit-diff-wash-diffs (list "--stat") limit)) + (when align + (setq align (make-string (1+ abbrev) ? ))) + (when (and (not (eobp)) (not (looking-at non-graph-re))) + (when align + (setq align (make-string (1+ abbrev) ? ))) + (while (and (not (eobp)) (not (looking-at non-graph-re))) + (when align + (save-excursion (insert align))) + (magit-make-margin-overlay) + (forward-line)) + ;; When `--format' is used and its value isn't one of the + ;; predefined formats, then `git-log' does not insert a + ;; separator line. + (save-excursion + (forward-line -1) + (looking-at "[-_/|\\*o<>. ]*")) + (setq graph (match-string 0)) + (unless (string-match-p "[/\\.]" graph) + (insert graph ?\n)))))))) + t) + +(defun magit-log-propertize-keywords (_rev msg) + (let ((boundary 0)) + (when (string-match "^\\(?:squash\\|fixup\\)! " msg boundary) + (setq boundary (match-end 0)) + (magit--put-face (match-beginning 0) (1- boundary) + 'magit-keyword-squash msg)) + (when magit-log-highlight-keywords + (while (string-match "\\[[^][]*]" msg boundary) + (setq boundary (match-end 0)) + (magit--put-face (match-beginning 0) boundary + 'magit-keyword msg)))) + msg) + +(defun magit-log-maybe-show-more-commits (section) + "When point is at the end of a log buffer, insert more commits. + +Log buffers end with a button \"Type + to show more history\". +When the use of a section movement command puts point on that +button, then automatically show more commits, without the user +having to press \"+\". + +This function is called by `magit-section-movement-hook' and +exists mostly for backward compatibility reasons." + (when (and (eq (oref section type) 'longer) + magit-log-auto-more) + (magit-log-double-commit-limit) + (forward-line -1) + (magit-section-forward))) + +(add-hook 'magit-section-movement-hook #'magit-log-maybe-show-more-commits) + +(defvar magit--update-revision-buffer nil) + +(defun magit-log-maybe-update-revision-buffer (&optional _) + "When moving in a log or cherry buffer, update the revision buffer. +If there is no revision buffer in the same frame, then do nothing." + (when (derived-mode-p 'magit-log-mode 'magit-cherry-mode 'magit-reflog-mode) + (magit--maybe-update-revision-buffer))) + +(add-hook 'magit-section-movement-hook #'magit-log-maybe-update-revision-buffer) + +(defun magit--maybe-update-revision-buffer () + (when-let* ((commit (magit-section-value-if 'commit)) + (buffer (magit-get-mode-buffer 'magit-revision-mode nil t))) + (if magit--update-revision-buffer + (setq magit--update-revision-buffer (list commit buffer)) + (setq magit--update-revision-buffer (list commit buffer)) + (run-with-idle-timer + magit-update-other-window-delay nil + (let ((args (let ((magit-direct-use-buffer-arguments 'selected)) + (magit-show-commit--arguments)))) + (lambda () + (pcase-let ((`(,rev ,buf) magit--update-revision-buffer)) + (setq magit--update-revision-buffer nil) + (when (buffer-live-p buf) + (let ((magit-display-buffer-noselect t)) + (apply #'magit-show-commit rev args)))) + (setq magit--update-revision-buffer nil))))))) + +(defvar magit--update-blob-buffer nil) + +(defun magit-log-maybe-update-blob-buffer (&optional _) + "When moving in a log or cherry buffer, update the blob buffer. +If there is no blob buffer in the same frame, then do nothing." + (when (derived-mode-p 'magit-log-mode 'magit-cherry-mode 'magit-reflog-mode) + (magit--maybe-update-blob-buffer))) + +(defun magit--maybe-update-blob-buffer () + (when-let* ((commit (magit-section-value-if 'commit)) + (buffer (--first (with-current-buffer it + (eq revert-buffer-function + 'magit-revert-rev-file-buffer)) + (mapcar #'window-buffer (window-list))))) + (if magit--update-blob-buffer + (setq magit--update-blob-buffer (list commit buffer)) + (setq magit--update-blob-buffer (list commit buffer)) + (run-with-idle-timer + magit-update-other-window-delay nil + (lambda () + (pcase-let ((`(,rev ,buf) magit--update-blob-buffer)) + (setq magit--update-blob-buffer nil) + (when (buffer-live-p buf) + (with-selected-window (get-buffer-window buf) + (with-current-buffer buf + (save-excursion + (magit-blob-visit (list (magit-rev-parse rev) + (magit-file-relative-name + magit-buffer-file-name))))))))))))) + +(defun magit-log-goto-commit-section (rev) + (let ((abbrev (magit-rev-format "%h" rev))) + (when-let ((section (--first (equal (oref it value) abbrev) + (oref magit-root-section children)))) + (goto-char (oref section start))))) + +(defun magit-log-goto-same-commit () + (when (and magit-previous-section + (magit-section-match '(commit branch) + magit-previous-section)) + (magit-log-goto-commit-section (oref magit-previous-section value)))) + +;;; Log Margin + +(defvar-local magit-log-margin-show-shortstat nil) + +(transient-define-suffix magit-toggle-log-margin-style () + "Toggle between the regular and the shortstat margin style. +The shortstat style is experimental and rather slow." + :description "Toggle shortstat" + :key "x" + :transient t + (interactive) + (setq magit-log-margin-show-shortstat + (not magit-log-margin-show-shortstat)) + (magit-set-buffer-margin nil t)) + +(defun magit-log-format-margin (rev author date) + (when (magit-margin-option) + (if magit-log-margin-show-shortstat + (magit-log-format-shortstat-margin rev) + (magit-log-format-author-margin author date)))) + +(defun magit-log-format-author-margin (author date &optional previous-line) + (pcase-let ((`(,_ ,style ,width ,details ,details-width) + (or magit-buffer-margin + (symbol-value (magit-margin-option)) + (error "No margin format specified for %s" major-mode)))) + (magit-make-margin-overlay + (concat (and details + (concat (magit--propertize-face + (truncate-string-to-width + (or author "") + details-width + nil ?\s + (magit--ellipsis 'margin)) + 'magit-log-author) + " ")) + (magit--propertize-face + (if (stringp style) + (format-time-string + style + (seconds-to-time (string-to-number date))) + (pcase-let* ((abbr (eq style 'age-abbreviated)) + (`(,cnt ,unit) (magit--age date abbr))) + (format (format (if abbr "%%2d%%-%dc" "%%2d %%-%ds") + (- width (if details (1+ details-width) 0))) + cnt unit))) + 'magit-log-date)) + previous-line))) + +(defun magit-log-format-shortstat-margin (rev) + (magit-make-margin-overlay + (if-let ((line (and rev (magit-git-string + "show" "--format=" "--shortstat" rev)))) + (if (string-match "\ +\\([0-9]+\\) files? changed, \ +\\(?:\\([0-9]+\\) insertions?(\\+)\\)?\ +\\(?:\\(?:, \\)?\\([0-9]+\\) deletions?(-)\\)?\\'" line) + (magit-bind-match-strings (files add del) line + (format + "%5s %5s%4s" + (if add + (magit--propertize-face (format "%s+" add) + 'magit-diffstat-added) + "") + (if del + (magit--propertize-face (format "%s-" del) + 'magit-diffstat-removed) + "") + files)) + "") + ""))) + +(defun magit-log-margin-width (style details details-width) + (if magit-log-margin-show-shortstat + 16 + (+ (if details (1+ details-width) 0) + (if (stringp style) + (length (format-time-string style)) + (+ 2 ; two digits + 1 ; trailing space + (if (eq style 'age-abbreviated) + 1 ; single character + (+ 1 ; gap after digits + (apply #'max (--map (max (length (nth 1 it)) + (length (nth 2 it))) + magit--age-spec))))))))) + +;;; Select Mode + +(defvar-keymap magit-log-select-mode-map + :doc "Keymap for `magit-log-select-mode'." + :parent magit-log-mode-map + "C-c C-b" #'undefined + "C-c C-f" #'undefined + "." #'magit-log-select-pick + "e" #'magit-log-select-pick + "C-c C-c" #'magit-log-select-pick + "q" #'magit-log-select-quit + "C-c C-k" #'magit-log-select-quit) +(put 'magit-log-select-pick :advertised-binding [?\C-c ?\C-c]) +(put 'magit-log-select-quit :advertised-binding [?\C-c ?\C-k]) + +(define-derived-mode magit-log-select-mode magit-log-mode "Magit Select" + "Mode for selecting a commit from history. + +This mode is documented in info node `(magit)Select from Log'. + +\\<magit-mode-map>\ +Type \\[magit-refresh] to refresh the current buffer. +Type \\[magit-visit-thing] or \\[magit-diff-show-or-scroll-up] \ +to visit the commit at point. + +\\<magit-log-select-mode-map>\ +Type \\[magit-log-select-pick] to select the commit at point. +Type \\[magit-log-select-quit] to abort without selecting a commit." + :group 'magit-log + (magit-hack-dir-local-variables)) + +(put 'magit-log-select-mode 'magit-log-default-arguments + '("--graph" "-n256" "--decorate")) + +(defun magit-log-select-setup-buffer (revs args) + (magit-setup-buffer #'magit-log-select-mode nil + (magit-buffer-revisions revs) + (magit-buffer-log-args args))) + +(defun magit-log-select-refresh-buffer () + (setq magit-section-inhibit-markers t) + (setq magit-section-insert-in-reverse t) + (magit-insert-section (logbuf) + (magit--insert-log t magit-buffer-revisions + (magit-log--maybe-drop-color-graph + magit-buffer-log-args + (magit-log-get-commit-limit))))) + +(cl-defmethod magit-buffer-value (&context (major-mode magit-log-select-mode)) + magit-buffer-revisions) + +(defvar-local magit-log-select-pick-function nil) +(defvar-local magit-log-select-quit-function nil) + +(defun magit-log-select (pick &optional msg quit branch args initial) + (declare (indent defun)) + (unless initial + (setq initial (magit-commit-at-point))) + (magit-log-select-setup-buffer + (or branch (magit-get-current-branch) "HEAD") + (append args + (car (magit-log--get-value 'magit-log-select-mode + magit-direct-use-buffer-arguments)))) + (if initial + (magit-log-goto-commit-section initial) + (while-let ((rev (magit-section-value-if 'commit)) + ((string-match-p "\\`\\(fixup\\|squash\\)!" + (magit-rev-format "%s" rev))) + (section (magit-current-section)) + (next (car (magit-section-siblings section 'next)))) + (magit-section-goto next))) + (setq magit-log-select-pick-function pick) + (setq magit-log-select-quit-function quit) + (when magit-log-select-show-usage + (let ((pick (propertize (substitute-command-keys + "\\[magit-log-select-pick]") + 'font-lock-face + 'magit-header-line-key)) + (quit (propertize (substitute-command-keys + "\\[magit-log-select-quit]") + 'font-lock-face + 'magit-header-line-key))) + (setq msg (format-spec + (if msg + (if (string-suffix-p "," msg) + (concat msg " or %q to abort") + msg) + "Type %p to select commit at point, or %q to abort") + `((?p . ,pick) + (?q . ,quit))))) + (magit--add-face-text-property + 0 (length msg) 'magit-header-line-log-select t msg) + (when (memq magit-log-select-show-usage '(both header-line)) + (magit-set-header-line-format msg)) + (when (memq magit-log-select-show-usage '(both echo-area)) + (message "%s" (substring-no-properties msg))))) + +(defun magit-log-select-pick () + "Select the commit at point and act on it. +Call `magit-log-select-pick-function' with the selected +commit as argument." + (interactive) + (let ((fun magit-log-select-pick-function) + (rev (magit-commit-at-point))) + (magit-mode-bury-buffer 'kill) + (funcall fun rev))) + +(defun magit-log-select-quit () + "Abort selecting a commit, don't act on any commit. +Call `magit-log-select-quit-function' if set." + (interactive) + (let ((fun magit-log-select-quit-function)) + (magit-mode-bury-buffer 'kill) + (when fun (funcall fun)))) + +;;; Cherry Mode + +(defvar-keymap magit-cherry-mode-map + :doc "Keymap for `magit-cherry-mode'." + :parent magit-mode-map + "q" #'magit-log-bury-buffer + "L" #'magit-margin-settings) + +(define-derived-mode magit-cherry-mode magit-mode "Magit Cherry" + "Mode for looking at commits not merged upstream. + +\\<magit-mode-map>\ +Type \\[magit-refresh] to refresh the current buffer. +Type \\[magit-visit-thing] or \\[magit-diff-show-or-scroll-up] \ +to visit the commit at point. + +Type \\[magit-cherry-pick] to apply the commit at point. + +\\{magit-cherry-mode-map}" + :interactive nil + :group 'magit-log + (magit-hack-dir-local-variables) + (setq magit--imenu-group-types 'cherries)) + +(defun magit-cherry-setup-buffer (head upstream) + (magit-setup-buffer #'magit-cherry-mode nil + (magit-buffer-refname head) + (magit-buffer-upstream upstream) + (magit-buffer-range (concat upstream ".." head)))) + +(defun magit-cherry-refresh-buffer () + (setq magit-section-insert-in-reverse t) + (magit-insert-section (cherry) + (magit-run-section-hook 'magit-cherry-sections-hook))) + +(cl-defmethod magit-buffer-value (&context (major-mode magit-cherry-mode)) + magit-buffer-range) + +;;;###autoload +(defun magit-cherry (head upstream) + "Show commits in a branch that are not merged in the upstream branch." + (interactive + (let ((head (magit-read-branch "Cherry head"))) + (list head (magit-read-other-branch "Cherry upstream" head + (magit-get-upstream-branch head))))) + (require 'magit) + (magit-cherry-setup-buffer head upstream)) + +(defun magit-insert-cherry-headers () + "Insert headers appropriate for `magit-cherry-mode' buffers." + (let ((branch (propertize magit-buffer-refname + 'font-lock-face 'magit-branch-local)) + (upstream (propertize magit-buffer-upstream 'font-lock-face + (if (magit-local-branch-p magit-buffer-upstream) + 'magit-branch-local + 'magit-branch-remote)))) + (magit-insert-head-branch-header branch) + (magit-insert-upstream-branch-header branch upstream "Upstream: ") + (insert ?\n))) + +(defun magit-insert-cherry-commits () + "Insert commit sections into a `magit-cherry-mode' buffer." + (magit-insert-section (cherries) + (magit-insert-heading t "Cherry commits") + (magit-git-wash (apply-partially #'magit-log-wash-log 'cherry) + "cherry" "-v" "--abbrev" + magit-buffer-upstream + magit-buffer-refname))) + +;;; Log Sections +;;;; Standard Log Sections + +(defvar-keymap magit-log-section-map + :doc "Keymap for log sections. +The classes `magit-{unpulled,unpushed,unmerged}-section' derive +from the abstract `magit-log-section' class. Accordingly this +keymap is the parent of their keymaps." + "<remap> <magit-visit-thing>" #'magit-diff-dwim + "<1>" (magit-menu-item "Visit diff" #'magit-diff-dwim)) + +(cl-defmethod magit-section-ident-value ((section magit-unpulled-section)) + "\"..@{push}\" cannot be used as the value because that is +ambiguous if `push.default' does not allow a 1:1 mapping, and +many commands would fail because of that. But here that does +not matter and we need an unique value so we use that string +in the pushremote case." + (let ((value (oref section value))) + (if (equal value "..@{upstream}") value "..@{push}"))) + +(magit-define-section-jumper magit-jump-to-unpulled-from-upstream + "Unpulled from @{upstream}" unpulled "..@{upstream}" + magit-insert-unpulled-from-upstream) + +(defun magit-insert-unpulled-from-upstream () + "Insert commits that haven't been pulled from the upstream yet." + (when-let ((upstream (magit-get-upstream-branch))) + (magit-insert-section (unpulled "..@{upstream}" t) + (magit-insert-heading + (format (propertize "Unpulled from %s." + 'font-lock-face 'magit-section-heading) + upstream)) + (magit--insert-log nil "..@{upstream}" magit-buffer-log-args) + (magit-log-insert-child-count)))) + +(magit-define-section-jumper magit-jump-to-unpulled-from-pushremote + "Unpulled from <push-remote>" unpulled "..@{push}" + magit-insert-unpulled-from-pushremote) + +(defun magit-insert-unpulled-from-pushremote () + "Insert commits that haven't been pulled from the push-remote yet." + (when-let* ((target (magit-get-push-branch)) + (range (concat ".." target))) + (when (magit--insert-pushremote-log-p) + (magit-insert-section (unpulled range t) + (magit-insert-heading + (format (propertize "Unpulled from %s." + 'font-lock-face 'magit-section-heading) + (propertize target 'font-lock-face 'magit-branch-remote))) + (magit--insert-log nil range magit-buffer-log-args) + (magit-log-insert-child-count))))) + +(cl-defmethod magit-section-ident-value ((section magit-unpushed-section)) + "\"..@{push}\" cannot be used as the value because that is +ambiguous if `push.default' does not allow a 1:1 mapping, and +many commands would fail because of that. But here that does +not matter and we need an unique value so we use that string +in the pushremote case." + (let ((value (oref section value))) + (if (equal value "@{upstream}..") value "@{push}.."))) + +(magit-define-section-jumper magit-jump-to-unpushed-to-upstream + "Unpushed to @{upstream}" unpushed "@{upstream}.." nil + :if (lambda () + (or (memq 'magit-insert-unpushed-to-upstream-or-recent + magit-status-sections-hook) + (memq 'magit-insert-unpushed-to-upstream + magit-status-sections-hook))) + :description (lambda () + (let ((upstream (magit-get-upstream-branch))) + (if (or (not upstream) + (magit-rev-ancestor-p "HEAD" upstream)) + "Recent commits" + "Unmerged into upstream")))) + +(defun magit-insert-unpushed-to-upstream-or-recent () + "Insert section showing unpushed or other recent commits. +If an upstream is configured for the current branch and it is +behind of the current branch, then show the commits that have +not yet been pushed into the upstream branch. If no upstream is +configured or if the upstream is not behind of the current branch, +then show the last `magit-log-section-commit-count' commits." + (let ((upstream (magit-get-upstream-branch))) + (if (or (not upstream) + (magit-rev-ancestor-p "HEAD" upstream)) + (magit-insert-recent-commits 'unpushed "@{upstream}..") + (magit-insert-unpushed-to-upstream)))) + +(defun magit-insert-unpushed-to-upstream () + "Insert commits that haven't been pushed to the upstream yet." + (when (magit-git-success "rev-parse" "@{upstream}") + (magit-insert-section (unpushed "@{upstream}..") + (magit-insert-heading + (format (propertize "Unmerged into %s." + 'font-lock-face 'magit-section-heading) + (magit-get-upstream-branch))) + (magit--insert-log nil "@{upstream}.." magit-buffer-log-args) + (magit-log-insert-child-count)))) + +(defun magit-insert-recent-commits (&optional type value) + "Insert section showing recent commits. +Show the last `magit-log-section-commit-count' commits." + (let* ((start (format "HEAD~%s" magit-log-section-commit-count)) + (range (and (magit-rev-verify start) + (concat start "..HEAD")))) + (magit-insert-section ((eval (or type 'recent)) + (or value range) + t) + (magit-insert-heading "Recent commits") + (magit--insert-log nil + (and (member "--graph" magit-buffer-log-args) range) + (cons (format "-n%d" magit-log-section-commit-count) + (--remove (string-prefix-p "-n" it) + magit-buffer-log-args)))))) + +(magit-define-section-jumper magit-jump-to-unpushed-to-pushremote + "Unpushed to <push-remote>" unpushed "@{push}.." + magit-insert-unpushed-to-pushremote) + +(defun magit-insert-unpushed-to-pushremote () + "Insert commits that haven't been pushed to the push-remote yet." + (when-let* ((target (magit-get-push-branch)) + (range (concat target ".."))) + (when (magit--insert-pushremote-log-p) + (magit-insert-section (unpushed range t) + (magit-insert-heading + (format (propertize "Unpushed to %s." + 'font-lock-face 'magit-section-heading) + (propertize target 'font-lock-face 'magit-branch-remote))) + (magit--insert-log nil range magit-buffer-log-args) + (magit-log-insert-child-count))))) + +(defun magit--insert-pushremote-log-p () + (magit--with-refresh-cache + (cons default-directory 'magit--insert-pushremote-log-p) + (not (and (equal (magit-get-push-branch) + (magit-get-upstream-branch)) + (or (memq 'magit-insert-unpulled-from-upstream + magit-status-sections-hook) + (memq 'magit-insert-unpulled-from-upstream-or-recent + magit-status-sections-hook)))))) + +(defun magit-log-insert-child-count () + (when magit-section-show-child-count + (let ((count (length (oref magit-insert-section--current children)))) + (when (> count 0) + (when (eq count (magit-log-get-commit-limit)) + (setq count (format "%s+" count))) + (save-excursion + (goto-char (- (oref magit-insert-section--current content) 2)) + (insert (format " (%s)" count)) + (delete-char 1)))))) + +;;;; Auxiliary Log Sections + +(defun magit-insert-unpulled-cherries () + "Insert section showing unpulled commits. +Like `magit-insert-unpulled-from-upstream' but prefix each commit +which has not been applied yet (i.e., a commit with a patch-id +not shared with any local commit) with \"+\", and all others with +\"-\"." + (when (magit-git-success "rev-parse" "@{upstream}") + (magit-insert-section (unpulled "..@{upstream}") + (magit-insert-heading t "Unpulled commits") + (magit-git-wash (apply-partially #'magit-log-wash-log 'cherry) + "cherry" "-v" (magit-abbrev-arg) + (magit-get-current-branch) "@{upstream}")))) + +(defun magit-insert-unpushed-cherries () + "Insert section showing unpushed commits. +Like `magit-insert-unpushed-to-upstream' but prefix each commit +which has not been applied to upstream yet (i.e., a commit with +a patch-id not shared with any upstream commit) with \"+\", and +all others with \"-\"." + (when (magit-git-success "rev-parse" "@{upstream}") + (magit-insert-section (unpushed "@{upstream}..") + (magit-insert-heading t "Unpushed commits") + (magit-git-wash (apply-partially #'magit-log-wash-log 'cherry) + "cherry" "-v" (magit-abbrev-arg) "@{upstream}")))) + +;;; _ +(provide 'magit-log) +;;; magit-log.el ends here diff --git a/emacs/elpa/magit-20241004.917/magit-margin.el b/emacs/elpa/magit-20241004.917/magit-margin.el @@ -0,0 +1,251 @@ +;;; magit-margin.el --- Margins in Magit buffers -*- lexical-binding:t -*- + +;; Copyright (C) 2008-2024 The Magit Project Contributors + +;; Author: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> +;; Maintainer: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> + +;; SPDX-License-Identifier: GPL-3.0-or-later + +;; Magit is free software: you can redistribute it and/or modify it +;; under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. +;; +;; Magit is distributed in the hope that it will be useful, but WITHOUT +;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +;; or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public +;; License for more details. +;; +;; You should have received a copy of the GNU General Public License +;; along with Magit. If not, see <https://www.gnu.org/licenses/>. + +;;; Commentary: + +;; This library implements support for showing additional information +;; in the margins of Magit buffers. Currently this is only used for +;; commits, for which the committer date or age, and optionally the +;; author name are shown. + +;;; Code: + +(require 'magit-base) +(require 'magit-transient) +(require 'magit-mode) + +;;; Options + +(defgroup magit-margin nil + "Information Magit displays in the margin. + +You can change the STYLE and AUTHOR-WIDTH of all `magit-*-margin' +options to the same values by customizing `magit-log-margin' +*before* `magit' is loaded. If you do that, then the respective +values for the other options will default to what you have set +for that variable. Likewise if you set `magit-log-margin's INIT +to nil, then that is used in the default of all other options. But +setting it to t, i.e., re-enforcing the default for that option, +does not carry to other options." + :link '(info-link "(magit)Log Margin") + :group 'magit-log) + +(defvar-local magit-buffer-margin nil) +(put 'magit-buffer-margin 'permanent-local t) + +(defvar-local magit-set-buffer-margin-refresh nil) + +(defvar magit--age-spec) + +;;; Commands + +(transient-define-prefix magit-margin-settings () + "Change what information is displayed in the margin." + :info-manual "(magit) Log Margin" + ["Margin" + (magit-toggle-margin) + (magit-cycle-margin-style) + (magit-toggle-margin-details) + (magit-refs-set-show-commit-count)]) + +(transient-define-suffix magit-toggle-margin () + "Show or hide the Magit margin." + :description "Toggle visibility" + :key "L" + :transient t + (interactive) + (unless (magit-margin-option) + (user-error "Magit margin isn't supported in this buffer")) + (setcar magit-buffer-margin (not (magit-buffer-margin-p))) + (magit-set-buffer-margin)) + +(defvar magit-margin-default-time-format nil + "See https://github.com/magit/magit/pull/4605.") + +(transient-define-suffix magit-cycle-margin-style () + "Cycle style used for the Magit margin." + :description "Cycle style" + :key "l" + :transient t + (interactive) + (unless (magit-margin-option) + (user-error "Magit margin isn't supported in this buffer")) + ;; This is only suitable for commit margins (there are not others). + (setf (cadr magit-buffer-margin) + (pcase (cadr magit-buffer-margin) + ('age 'age-abbreviated) + ('age-abbreviated + (let ((default (or magit-margin-default-time-format + (cadr (symbol-value (magit-margin-option)))))) + (if (stringp default) default "%Y-%m-%d %H:%M "))) + (_ 'age))) + (magit-set-buffer-margin nil t)) + +(transient-define-suffix magit-toggle-margin-details () + "Show or hide details in the Magit margin." + :description "Toggle details" + :key "d" + :transient t + (interactive) + (unless (magit-margin-option) + (user-error "Magit margin isn't supported in this buffer")) + (setf (nth 3 magit-buffer-margin) + (not (nth 3 magit-buffer-margin))) + (magit-set-buffer-margin nil t)) + +;;; Core + +(defun magit-buffer-margin-p () + (car magit-buffer-margin)) + +(defun magit-margin-option () + (pcase major-mode + ('magit-cherry-mode 'magit-cherry-margin) + ('magit-log-mode 'magit-log-margin) + ('magit-log-select-mode 'magit-log-select-margin) + ('magit-reflog-mode 'magit-reflog-margin) + ('magit-refs-mode 'magit-refs-margin) + ('magit-stashes-mode 'magit-stashes-margin) + ('magit-status-mode 'magit-status-margin) + ('forge-notifications-mode 'magit-status-margin) + ('forge-topics-mode 'magit-status-margin))) + +(defun magit-set-buffer-margin (&optional reset refresh) + (when-let ((option (magit-margin-option))) + (let* ((default (symbol-value option)) + (default-width (nth 2 default))) + (when (or reset (not magit-buffer-margin)) + (setq magit-buffer-margin (copy-sequence default))) + (pcase-let ((`(,enable ,style ,_width ,details ,details-width) + magit-buffer-margin)) + (when (functionp default-width) + (setf (nth 2 magit-buffer-margin) + (funcall default-width style details details-width))) + (dolist (window (get-buffer-window-list nil nil 0)) + (with-selected-window window + (magit-set-window-margin window) + (if enable + (add-hook 'window-configuration-change-hook + #'magit-set-window-margin nil t) + (remove-hook 'window-configuration-change-hook + #'magit-set-window-margin t)))) + (when (and enable (or refresh magit-set-buffer-margin-refresh)) + (magit-refresh-buffer)))))) + +(defun magit-set-window-margin (&optional window) + (when (or window (setq window (get-buffer-window))) + (with-selected-window window + (set-window-margins + nil (car (window-margins)) + (and (magit-buffer-margin-p) + (nth 2 magit-buffer-margin)))))) + +(defun magit-make-margin-overlay (&optional string previous-line) + (if previous-line + (save-excursion + (forward-line -1) + (magit-make-margin-overlay string)) + ;; Don't put the overlay on the complete line to work around #1880. + (let ((o (make-overlay (1+ (line-beginning-position)) + (line-end-position) + nil t))) + (overlay-put o 'evaporate t) + (overlay-put o 'before-string + (propertize "o" 'display + (list (list 'margin 'right-margin) + (or string " "))))))) + +(defvar magit-margin-overlay-conditions + '( unpulled unpushed recent stashes local cherries + [remote branchbuf] + [tags branchbuf] + topics issues pullreqs)) + +(defun magit-maybe-make-margin-overlay () + (when (magit-section-match magit-margin-overlay-conditions + magit-insert-section--current) + (magit-make-margin-overlay nil t))) + +;;; Custom Support + +(defun magit-margin-set-variable (mode symbol value) + (set-default symbol value) + (message "Updating margins in %s buffers..." mode) + (dolist (buffer (buffer-list)) + (with-current-buffer buffer + (when (eq major-mode mode) + (magit-set-buffer-margin t) + (magit-refresh)))) + (message "Updating margins in %s buffers...done" mode)) + +(defconst magit-log-margin--custom-type + '(list (boolean :tag "Show margin initially") + (choice :tag "Show committer" + (string :tag "date using time-format" "%Y-%m-%d %H:%M ") + (const :tag "date's age" age) + (const :tag "date's age (abbreviated)" age-abbreviated)) + (const :tag "Calculate width using magit-log-margin-width" + magit-log-margin-width) + (boolean :tag "Show author name by default") + (integer :tag "Show author name using width"))) + +;;; Time Utilities + +(defvar magit--age-spec + `((?Y "year" "years" ,(round (* 60 60 24 365.2425))) + (?M "month" "months" ,(round (* 60 60 24 30.436875))) + (?w "week" "weeks" ,(* 60 60 24 7)) + (?d "day" "days" ,(* 60 60 24)) + (?h "hour" "hours" ,(* 60 60)) + (?m "minute" "minutes" 60) + (?s "second" "seconds" 1)) + "Time units used when formatting relative commit ages. + +The value is a list of time units, beginning with the longest. +Each element has the form (CHAR UNIT UNITS SECONDS). UNIT is the +time unit, UNITS is the plural of that unit. CHAR is a character +abbreviation. And SECONDS is the number of seconds in one UNIT. + +This is defined as a variable to make it possible to use time +units for a language other than English. It is not defined +as an option, because most other parts of Magit are always in +English.") + +(defun magit--age (date &optional abbreviate) + (cl-labels ((fn (age spec) + (pcase-let ((`(,char ,unit ,units ,weight) (car spec))) + (let ((cnt (round (/ age weight 1.0)))) + (if (or (not (cdr spec)) + (>= (/ age weight) 1)) + (list cnt (cond (abbreviate char) + ((= cnt 1) unit) + (t units))) + (fn age (cdr spec))))))) + (fn (abs (- (float-time) + (if (stringp date) + (string-to-number date) + date))) + magit--age-spec))) + +;;; _ +(provide 'magit-margin) +;;; magit-margin.el ends here diff --git a/emacs/elpa/magit-20241004.917/magit-merge.el b/emacs/elpa/magit-20241004.917/magit-merge.el @@ -0,0 +1,315 @@ +;;; magit-merge.el --- Merge functionality -*- lexical-binding:t -*- + +;; Copyright (C) 2008-2024 The Magit Project Contributors + +;; Author: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> +;; Maintainer: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> + +;; SPDX-License-Identifier: GPL-3.0-or-later + +;; Magit is free software: you can redistribute it and/or modify it +;; under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. +;; +;; Magit is distributed in the hope that it will be useful, but WITHOUT +;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +;; or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public +;; License for more details. +;; +;; You should have received a copy of the GNU General Public License +;; along with Magit. If not, see <https://www.gnu.org/licenses/>. + +;;; Commentary: + +;; This library implements merge commands. + +;;; Code: + +(require 'magit) +(require 'magit-diff) + +(declare-function magit-git-push "magit-push" (branch target args)) + +;;; Commands + +;;;###autoload (autoload 'magit-merge "magit" nil t) +(transient-define-prefix magit-merge () + "Merge branches." + :man-page "git-merge" + :incompatible '(("--ff-only" "--no-ff")) + ["Arguments" + :if-not magit-merge-in-progress-p + ("-f" "Fast-forward only" "--ff-only") + ("-n" "No fast-forward" "--no-ff") + (magit-merge:--strategy) + (5 magit-merge:--strategy-option) + (5 "-b" "Ignore changes in amount of whitespace" "-Xignore-space-change") + (5 "-w" "Ignore whitespace when comparing lines" "-Xignore-all-space") + (5 magit-diff:--diff-algorithm :argument "-Xdiff-algorithm=") + (5 magit:--gpg-sign)] + ["Actions" + :if-not magit-merge-in-progress-p + [("m" "Merge" magit-merge-plain) + ("e" "Merge and edit message" magit-merge-editmsg) + ("n" "Merge but don't commit" magit-merge-nocommit) + ("a" "Absorb" magit-merge-absorb)] + [("p" "Preview merge" magit-merge-preview) + "" + ("s" "Squash merge" magit-merge-squash) + ("i" "Dissolve" magit-merge-into)]] + ["Actions" + :if magit-merge-in-progress-p + ("m" "Commit merge" magit-commit-create) + ("a" "Abort merge" magit-merge-abort)]) + +(defun magit-merge-arguments () + (transient-args 'magit-merge)) + +(transient-define-argument magit-merge:--strategy () + :description "Strategy" + :class 'transient-option + ;; key for merge and rebase: "-s" + ;; key for cherry-pick and revert: "=s" + ;; shortarg for merge and rebase: "-s" + ;; shortarg for cherry-pick and revert: none + :key "-s" + :argument "--strategy=" + :choices '("resolve" "recursive" "octopus" "ours" "subtree")) + +(transient-define-argument magit-merge:--strategy-option () + :description "Strategy Option" + :class 'transient-option + :key "-X" + :argument "--strategy-option=" + :choices '("ours" "theirs" "patience")) + +;;;###autoload +(defun magit-merge-plain (rev &optional args nocommit) + "Merge commit REV into the current branch; using default message. + +Unless there are conflicts or a prefix argument is used create a +merge commit using a generic commit message and without letting +the user inspect the result. With a prefix argument pretend the +merge failed to give the user the opportunity to inspect the +merge. + +\(git merge --no-edit|--no-commit [ARGS] REV)" + (interactive (list (magit-read-other-branch-or-commit "Merge") + (magit-merge-arguments) + current-prefix-arg)) + (magit-merge-assert) + (magit-run-git-async "merge" (if nocommit "--no-commit" "--no-edit") args rev)) + +;;;###autoload +(defun magit-merge-editmsg (rev &optional args) + "Merge commit REV into the current branch; and edit message. +Perform the merge and prepare a commit message but let the user +edit it. +\n(git merge --edit --no-ff [ARGS] REV)" + (interactive (list (magit-read-other-branch-or-commit "Merge") + (magit-merge-arguments))) + (magit-merge-assert) + (cl-pushnew "--no-ff" args :test #'equal) + (apply #'magit-run-git-with-editor "merge" "--edit" + (append (delete "--ff-only" args) + (list rev)))) + +;;;###autoload +(defun magit-merge-nocommit (rev &optional args) + "Merge commit REV into the current branch; pretending it failed. +Pretend the merge failed to give the user the opportunity to +inspect the merge and change the commit message. +\n(git merge --no-commit --no-ff [ARGS] REV)" + (interactive (list (magit-read-other-branch-or-commit "Merge") + (magit-merge-arguments))) + (magit-merge-assert) + (cl-pushnew "--no-ff" args :test #'equal) + (magit-run-git-async "merge" "--no-commit" args rev)) + +;;;###autoload +(defun magit-merge-into (branch &optional args) + "Merge the current branch into BRANCH and remove the former. + +Before merging, force push the source branch to its push-remote, +provided the respective remote branch already exists, ensuring +that the respective pull-request (if any) won't get stuck on some +obsolete version of the commits that are being merged. Finally +if `forge-branch-pullreq' was used to create the merged branch, +then also remove the respective remote branch." + (interactive + (list (magit-read-other-local-branch + (format "Merge `%s' into" + (or (magit-get-current-branch) + (magit-rev-parse "HEAD"))) + nil + (and-let* ((upstream (magit-get-upstream-branch)) + (upstream (cdr (magit-split-branch-name upstream)))) + (and (magit-branch-p upstream) upstream))) + (magit-merge-arguments))) + (let ((current (magit-get-current-branch)) + (head (magit-rev-parse "HEAD"))) + (when (zerop (magit-call-git "checkout" branch)) + (if current + (magit--merge-absorb current args) + (magit-run-git-with-editor "merge" args head))))) + +;;;###autoload +(defun magit-merge-absorb (branch &optional args) + "Merge BRANCH into the current branch and remove the former. + +Before merging, force push the source branch to its push-remote, +provided the respective remote branch already exists, ensuring +that the respective pull-request (if any) won't get stuck on some +obsolete version of the commits that are being merged. Finally +if `forge-branch-pullreq' was used to create the merged branch, +then also remove the respective remote branch." + (interactive (list (magit-read-other-local-branch "Absorb branch") + (magit-merge-arguments))) + (magit--merge-absorb branch args)) + +(defun magit--merge-absorb (branch args) + (when (equal branch (magit-main-branch)) + (unless (yes-or-no-p + (format "Do you really want to merge `%s' into another branch? " + branch)) + (user-error "Abort"))) + (if-let ((target (magit-get-push-branch branch t))) + (progn + (magit-git-push branch target (list "--force-with-lease")) + (set-process-sentinel + magit-this-process + (lambda (process event) + (when (memq (process-status process) '(exit signal)) + (if (not (zerop (process-exit-status process))) + (magit-process-sentinel process event) + (process-put process 'inhibit-refresh t) + (magit-process-sentinel process event) + (magit--merge-absorb-1 branch args)))))) + (magit--merge-absorb-1 branch args))) + +(defun magit--merge-absorb-1 (branch args) + (if-let ((pr (magit-get "branch" branch "pullRequest"))) + (magit-run-git-async + "merge" args "-m" + (format "Merge branch '%s'%s [#%s]" + branch + (let ((current (magit-get-current-branch))) + (if (equal current (magit-main-branch)) + "" + (format " into %s" current))) + pr) + branch) + (magit-run-git-async "merge" args "--no-edit" branch)) + (set-process-sentinel + magit-this-process + (lambda (process event) + (when (memq (process-status process) '(exit signal)) + (if (> (process-exit-status process) 0) + (magit-process-sentinel process event) + (process-put process 'inhibit-refresh t) + (magit-process-sentinel process event) + (magit-branch-maybe-delete-pr-remote branch) + (magit-branch-unset-pushRemote branch) + (magit-run-git "branch" "-D" branch)))))) + +;;;###autoload +(defun magit-merge-squash (rev) + "Squash commit REV into the current branch; don't create a commit. +\n(git merge --squash REV)" + (interactive (list (magit-read-other-branch-or-commit "Squash"))) + (magit-merge-assert) + (magit-run-git-async "merge" "--squash" rev)) + +;;;###autoload +(defun magit-merge-preview (rev) + "Preview result of merging REV into the current branch." + (interactive (list (magit-read-other-branch-or-commit "Preview merge"))) + (magit-merge-preview-setup-buffer rev)) + +;;;###autoload +(defun magit-merge-abort () + "Abort the current merge operation. +\n(git merge --abort)" + (interactive) + (unless (file-exists-p (expand-file-name "MERGE_HEAD" (magit-gitdir))) + (user-error "No merge in progress")) + (magit-confirm 'abort-merge) + (magit-run-git-async "merge" "--abort")) + +(defun magit-checkout-stage (file arg) + "During a conflict checkout and stage side, or restore conflict." + (interactive + (let ((file (magit-completing-read "Checkout file" + (magit-tracked-files) nil nil nil + 'magit-read-file-hist + (magit-current-file)))) + (cond ((member file (magit-unmerged-files)) + (list file (magit-checkout-read-stage file))) + ((yes-or-no-p (format "Restore conflicts in %s? " file)) + (list file "--merge")) + (t + (user-error "Quit"))))) + (pcase (cons arg (cddr (car (magit-file-status file)))) + ((or `("--ours" ?D ,_) + '("--ours" ?U ?A) + `("--theirs" ,_ ?D) + '("--theirs" ?A ?U)) + (magit-run-git "rm" "--" file)) + (_ (if (equal arg "--merge") + ;; This fails if the file was deleted on one + ;; side. And we cannot do anything about it. + (magit-run-git "checkout" "--merge" "--" file) + (magit-call-git "checkout" arg "--" file) + (magit-run-git "add" "-u" "--" file))))) + +;;; Utilities + +(defun magit-merge-in-progress-p () + (file-exists-p (expand-file-name "MERGE_HEAD" (magit-gitdir)))) + +(defun magit--merge-range (&optional head) + (unless head + (setq head (magit-get-shortname + (car (magit-file-lines + (expand-file-name "MERGE_HEAD" (magit-gitdir))))))) + (and head + (concat (magit-git-string "merge-base" "--octopus" "HEAD" head) + ".." head))) + +(defun magit-merge-assert () + (or (not (magit-anything-modified-p t)) + (magit-confirm 'merge-dirty + "Merging with dirty worktree is risky. Continue"))) + +(defun magit-checkout-read-stage (file) + (magit-read-char-case (format "For %s checkout: " file) t + (?o "[o]ur stage" "--ours") + (?t "[t]heir stage" "--theirs") + (?c (if magit-verbose-messages "restore [c]onflict" "[c]onflict") + "--merge"))) + +;;; Sections + +(defun magit-insert-merge-log () + "Insert section for the on-going merge. +Display the heads that are being merged. +If no merge is in progress, do nothing." + (when (magit-merge-in-progress-p) + (let* ((heads (mapcar #'magit-get-shortname + (magit-file-lines + (expand-file-name "MERGE_HEAD" (magit-gitdir))))) + (range (magit--merge-range (car heads)))) + (magit-insert-section (unmerged range) + (magit-insert-heading + (format "Merging %s:" (string-join heads ", "))) + (magit--insert-log nil + range + (let ((args magit-buffer-log-args)) + (unless (member "--decorate=full" magit-buffer-log-args) + (push "--decorate=full" args)) + args)))))) + +;;; _ +(provide 'magit-merge) +;;; magit-merge.el ends here diff --git a/emacs/elpa/magit-20241004.917/magit-mode.el b/emacs/elpa/magit-20241004.917/magit-mode.el @@ -0,0 +1,1480 @@ +;;; magit-mode.el --- Create and refresh Magit buffers -*- lexical-binding:t -*- + +;; Copyright (C) 2008-2024 The Magit Project Contributors + +;; Author: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> +;; Maintainer: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> + +;; SPDX-License-Identifier: GPL-3.0-or-later + +;; Magit is free software: you can redistribute it and/or modify it +;; under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. +;; +;; Magit is distributed in the hope that it will be useful, but WITHOUT +;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +;; or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public +;; License for more details. +;; +;; You should have received a copy of the GNU General Public License +;; along with Magit. If not, see <https://www.gnu.org/licenses/>. + +;;; Commentary: + +;; This library implements the abstract major-mode `magit-mode' from +;; which almost all other Magit major-modes derive. The code in here +;; is mostly concerned with creating and refreshing Magit buffers. + +;;; Code: + +(require 'magit-base) +(require 'magit-git) + +(require 'benchmark) +(require 'browse-url) +(require 'format-spec) +(require 'help-mode) + +(require 'transient) + +(defvar bookmark-make-record-function) +(defvar magit--wip-inhibit-autosave) +(defvar magit-wip-after-save-local-mode) +(declare-function magit-wip-get-ref "magit-wip" ()) +(declare-function magit-wip-commit-worktree "magit-wip" (ref files msg)) + +;;; Options + +(defcustom magit-mode-hook + '(magit-load-config-extensions) + "Hook run when entering a mode derived from Magit mode." + :package-version '(magit . "3.0.0") + :group 'magit-modes + :type 'hook + :options '(magit-load-config-extensions + bug-reference-mode)) + +(defcustom magit-setup-buffer-hook + '(magit-maybe-save-repository-buffers + magit-set-buffer-margin) + "Hook run by `magit-setup-buffer'. + +This is run right after displaying the buffer and right before +generating or updating its content. `magit-mode-hook' and other, +more specific, `magit-mode-*-hook's on the other hand are run +right before displaying the buffer. Usually one of these hooks +should be used instead of this one." + :package-version '(magit . "2.3.0") + :group 'magit-modes + :type 'hook + :options '(magit-maybe-save-repository-buffers + magit-set-buffer-margin)) + +(defcustom magit-pre-refresh-hook '(magit-maybe-save-repository-buffers) + "Hook run before refreshing in `magit-refresh'. + +This hook, or `magit-post-refresh-hook', should be used +for functions that are not tied to a particular buffer. + +To run a function with a particular buffer current, use +`magit-refresh-buffer-hook' and use `derived-mode-p' +inside your function." + :package-version '(magit . "2.4.0") + :group 'magit-refresh + :type 'hook + :options '(magit-maybe-save-repository-buffers)) + +(defcustom magit-post-refresh-hook + '(magit-auto-revert-buffers + magit-run-post-commit-hook + magit-run-post-stage-hook + magit-run-post-unstage-hook) + "Hook run after refreshing in `magit-refresh'. + +This hook, or `magit-pre-refresh-hook', should be used +for functions that are not tied to a particular buffer. + +To run a function with a particular buffer current, use +`magit-refresh-buffer-hook' and use `derived-mode-p' +inside your function." + :package-version '(magit . "2.4.0") + :group 'magit-refresh + :type 'hook + :options '(magit-auto-revert-buffers + magit-run-post-commit-hook + magit-run-post-stage-hook + magit-run-post-unstage-hook)) + +(defcustom magit-display-buffer-function #'magit-display-buffer-traditional + "The function used to display a Magit buffer. + +All Magit buffers (buffers whose major-modes derive from +`magit-mode') are displayed using `magit-display-buffer', +which in turn uses the function specified here." + :package-version '(magit . "2.3.0") + :group 'magit-buffers + :type '(radio (function-item magit-display-buffer-traditional) + (function-item magit-display-buffer-same-window-except-diff-v1) + (function-item magit-display-buffer-fullframe-status-v1) + (function-item magit-display-buffer-fullframe-status-topleft-v1) + (function-item magit-display-buffer-fullcolumn-most-v1) + (function-item display-buffer) + (function :tag "Function"))) + +(defcustom magit-pre-display-buffer-hook '(magit-save-window-configuration) + "Hook run by `magit-display-buffer' before displaying the buffer." + :package-version '(magit . "2.3.0") + :group 'magit-buffers + :type 'hook + :get #'magit-hook-custom-get + :options '(magit-save-window-configuration)) + +(defcustom magit-post-display-buffer-hook '(magit-maybe-set-dedicated) + "Hook run by `magit-display-buffer' after displaying the buffer." + :package-version '(magit . "2.3.0") + :group 'magit-buffers + :type 'hook + :get #'magit-hook-custom-get + :options '(magit-maybe-set-dedicated)) + +(defcustom magit-generate-buffer-name-function + #'magit-generate-buffer-name-default-function + "The function used to generate the name for a Magit buffer." + :package-version '(magit . "2.3.0") + :group 'magit-buffers + :type '(radio (function-item magit-generate-buffer-name-default-function) + (function :tag "Function"))) + +(defcustom magit-buffer-name-format "%x%M%v: %t%x" + "The format string used to name Magit buffers. + +The following %-sequences are supported: + +`%m' The name of the major-mode, but with the `-mode' suffix + removed. + +`%M' Like \"%m\" but abbreviate `magit-status-mode' as `magit'. + +`%v' The value the buffer is locked to, in parentheses, or an + empty string if the buffer is not locked to a value. + +`%V' Like \"%v\", but the string is prefixed with a space, unless + it is an empty string. + +`%t' The top-level directory of the working tree of the + repository, or if `magit-uniquify-buffer-names' is non-nil + an abbreviation of that. + +`%x' If `magit-uniquify-buffer-names' is nil \"*\", otherwise the + empty string. Due to limitations of the `uniquify' package, + buffer names must end with the path. + +The value should always contain \"%m\" or \"%M\", \"%v\" or \"%V\", and +\"%t\". If `magit-uniquify-buffer-names' is non-nil, then the +value must end with \"%t\" or \"%t%x\". See issue #2841. + +This is used by `magit-generate-buffer-name-default-function'. +If another `magit-generate-buffer-name-function' is used, then +it may not respect this option, or on the contrary it may +support additional %-sequences." + :package-version '(magit . "2.12.0") + :group 'magit-buffers + :type 'string) + +(defcustom magit-uniquify-buffer-names t + "Whether to uniquify the names of Magit buffers." + :package-version '(magit . "2.3.0") + :group 'magit-buffers + :type 'boolean) + +(defcustom magit-bury-buffer-function #'magit-mode-quit-window + "The function used to bury or kill the current Magit buffer." + :package-version '(magit . "3.2.0") + :group 'magit-buffers + :type '(radio (function-item quit-window) + (function-item magit-mode-quit-window) + (function-item magit-restore-window-configuration) + (function :tag "Function"))) + +(defcustom magit-prefix-use-buffer-arguments 'selected + "Whether certain prefix commands reuse arguments active in relevant buffer. + +This affects the transient prefix commands `magit-diff', +`magit-log' and `magit-show-refs'. + +Valid values are: + +`always': Always use the set of arguments that is currently + active in the respective buffer, provided that buffer exists + of course. +`selected': Use the set of arguments from the respective + buffer, but only if it is displayed in a window of the current + frame. This is the default. +`current': Use the set of arguments from the respective buffer, + but only if it is the current buffer. +`never': Never use the set of arguments from the respective + buffer. + +For more information see info node `(magit)Transient Arguments +and Buffer Variables'." + :package-version '(magit . "3.0.0") + :group 'magit-buffers + :group 'magit-commands + :group 'magit-diff + :group 'magit-log + :type '(choice + (const :tag "always use args from buffer" always) + (const :tag "use args from buffer if displayed in frame" selected) + (const :tag "use args from buffer if it is current" current) + (const :tag "never use args from buffer" never))) + +(defcustom magit-direct-use-buffer-arguments 'selected + "Whether certain commands reuse arguments active in relevant buffer. + +This affects certain commands such as `magit-show-commit' that +are suffixes of the diff or log transient prefix commands, but +only if they are invoked directly, i.e., *not* as a suffix. + +Valid values are: + +`always': Always use the set of arguments that is currently + active in the respective buffer, provided that buffer exists + of course. +`selected': Use the set of arguments from the respective + buffer, but only if it is displayed in a window of the current + frame. This is the default. +`current': Use the set of arguments from the respective buffer, + but only if it is the current buffer. +`never': Never use the set of arguments from the respective + buffer. + +For more information see info node `(magit)Transient Arguments +and Buffer Variables'." + :package-version '(magit . "3.0.0") + :group 'magit-buffers + :group 'magit-commands + :group 'magit-diff + :group 'magit-log + :type '(choice + (const :tag "always use args from buffer" always) + (const :tag "use args from buffer if displayed in frame" selected) + (const :tag "use args from buffer if it is current" current) + (const :tag "never use args from buffer" never))) + +(defcustom magit-region-highlight-hook '(magit-diff-update-hunk-region) + "Functions used to highlight the region. + +Each function is run with the current section as only argument +until one of them returns non-nil. If all functions return nil, +then fall back to regular region highlighting." + :package-version '(magit . "2.1.0") + :group 'magit-refresh + :type 'hook + :options '(magit-diff-update-hunk-region)) + +(defcustom magit-create-buffer-hook nil + "Normal hook run while creating a new `magit-mode' buffer. +Runs before the buffer is populated with sections. Also see +`magit-post-create-buffer-hook'." + :package-version '(magit . "2.90.0") + :group 'magit-refresh + :type 'hook) + +(defcustom magit-post-create-buffer-hook nil + "Normal hook run after creating a new `magit-mode' buffer. +Runs after the buffer is populated with sections for the first +time. Also see `magit-create-buffer-hook' (which runs earlier) +and `magit-refresh-buffer-hook' (which runs on every refresh)." + :package-version '(magit . "4.0.0") + :group 'magit-refresh + :type 'hook) + +(defcustom magit-refresh-buffer-hook nil + "Normal hook for `magit-refresh-buffer' to run after refreshing." + :package-version '(magit . "2.1.0") + :group 'magit-refresh + :type 'hook) + +(defcustom magit-refresh-status-buffer t + "Whether the status buffer is refreshed after running git. + +When this is non-nil, then the status buffer is automatically +refreshed after running git for side-effects, in addition to the +current Magit buffer, which is always refreshed automatically. + +Only set this to nil after exhausting all other options to +improve performance." + :package-version '(magit . "2.4.0") + :group 'magit-refresh + :group 'magit-status + :type 'boolean) + +(defcustom magit-refresh-verbose nil + "Whether to revert Magit buffers verbosely." + :package-version '(magit . "2.1.0") + :group 'magit-refresh + :type 'boolean) + +(defcustom magit-save-repository-buffers t + "Whether to save file-visiting buffers when appropriate. + +If non-nil, then all modified file-visiting buffers belonging +to the current repository may be saved before running Magit +commands and before creating or refreshing Magit buffers. +If `dontask', then this is done without user intervention, for +any other non-nil value the user has to confirm each save. + +The default is t to avoid surprises, but `dontask' is the +recommended value." + :group 'magit-essentials + :group 'magit-buffers + :type '(choice (const :tag "Never" nil) + (const :tag "Ask" t) + (const :tag "Save without asking" dontask))) + +;;; Key Bindings + +(defvar-keymap magit-mode-map + :doc "Parent keymap for all keymaps of modes derived from `magit-mode'." + :parent magit-section-mode-map + ;; Don't function-quote but make sure all commands are autoloaded. + "C-<return>" 'magit-visit-thing + "RET" 'magit-visit-thing + "M-TAB" 'magit-dired-jump + "M-<tab>" 'magit-section-cycle-diffs + "SPC" 'magit-diff-show-or-scroll-up + "S-SPC" 'magit-diff-show-or-scroll-down + "DEL" 'magit-diff-show-or-scroll-down + "+" 'magit-diff-more-context + "-" 'magit-diff-less-context + "0" 'magit-diff-default-context + "a" 'magit-cherry-apply + "A" 'magit-cherry-pick + "b" 'magit-branch + "B" 'magit-bisect + "c" 'magit-commit + "C" 'magit-clone + "d" 'magit-diff + "D" 'magit-diff-refresh + "e" 'magit-ediff-dwim + "E" 'magit-ediff + "f" 'magit-fetch + "F" 'magit-pull + "g" 'magit-refresh + "G" 'magit-refresh-all + "h" 'magit-dispatch + "?" 'magit-dispatch + "H" 'magit-describe-section + "i" 'magit-gitignore + "I" 'magit-init + "j" 'magit-status-quick + "J" 'magit-display-repository-buffer + "k" 'magit-delete-thing + "K" 'magit-file-untrack + "l" 'magit-log + "L" 'magit-log-refresh + "m" 'magit-merge + "M" 'magit-remote + ;; "n" magit-section-forward in magit-section-mode-map + ;; "N" forge-dispatch, added by forge package + "o" 'magit-submodule + "O" 'magit-subtree + ;; "p" magit-section-backward in magit-section-mode-map + "P" 'magit-push + "q" 'magit-mode-bury-buffer + "Q" 'magit-git-command + ":" 'magit-git-command + "r" 'magit-rebase + "R" 'magit-file-rename + "s" 'magit-stage-file + "S" 'magit-stage-modified + "t" 'magit-tag + "T" 'magit-notes + "u" 'magit-unstage-file + "U" 'magit-unstage-all + "v" 'magit-revert-no-commit + "V" 'magit-revert + "w" 'magit-am + "W" 'magit-patch + "x" 'magit-reset-quickly + "X" 'magit-reset + "y" 'magit-show-refs + "Y" 'magit-cherry + "z" 'magit-stash + "Z" 'magit-worktree + "%" 'magit-worktree + "$" 'magit-process-buffer + "!" 'magit-run + ">" 'magit-sparse-checkout + "C-c C-c" 'magit-dispatch + "C-c C-e" 'magit-edit-thing + "C-c C-o" 'magit-browse-thing + "C-c C-w" 'magit-copy-thing + "C-w" 'magit-copy-section-value + "M-w" 'magit-copy-buffer-revision + "<remap> <back-to-indentation>" 'magit-back-to-indentation + "<remap> <previous-line>" 'magit-previous-line + "<remap> <next-line>" 'magit-next-line + "<remap> <evil-previous-line>" 'evil-previous-visual-line + "<remap> <evil-next-line>" 'evil-next-visual-line) + +(defun magit-delete-thing () + "This is a placeholder command, which signals an error if called. +Where applicable, other keymaps remap this command to another, +which actually deletes the thing at point." + (interactive) + (user-error "There is no thing at point that could be deleted")) +;; Starting with Emacs 28.1 we could use (declare (completion ignore)). +(put 'magit-delete-thing 'completion-predicate #'ignore) + +(defun magit-visit-thing () + "This is a placeholder command, which may signal an error if called. +Where applicable, other keymaps remap this command to another, +which actually visits the thing at point." + (interactive) + (if (eq transient-current-command 'magit-dispatch) + (call-interactively (key-binding (this-command-keys))) + (if-let ((url (browse-url-url-at-point))) + (browse-url url) + (user-error "There is no thing at point that could be visited")))) +(put 'magit-visit-thing 'completion-predicate #'ignore) + +(defun magit-edit-thing () + "This is a placeholder command, which may signal an error if called. +Where applicable, other keymaps remap this command to another, +which actually lets you edit the thing at point, likely in another +buffer." + (interactive) + (if (eq transient-current-command 'magit-dispatch) + (call-interactively (key-binding (this-command-keys))) + (user-error "There is no thing at point that could be edited"))) +(put 'magit-edit-thing 'completion-predicate #'ignore) + +(defun magit-browse-thing () + "This is a placeholder command, which may signal an error if called. +Where applicable, other keymaps remap this command to another, +which actually visits thing at point using `browse-url'." + (interactive) + (if-let ((url (browse-url-url-at-point))) + (browse-url url) + (user-error "There is no thing at point that could be browsed"))) +(put 'magit-browse-thing 'completion-predicate #'ignore) + +(defun magit-copy-thing () + "This is a placeholder command, which signals an error if called. +Where applicable, other keymaps remap this command to another, +which actually copies some representation of the thing at point +to the kill ring." + (interactive) + (user-error "There is no thing at point that we know how to copy")) +(put 'magit-copy-thing 'completion-predicate #'ignore) + +;;;###autoload +(defun magit-info () + "Visit the Magit manual." + (interactive) + (info "magit")) + +(defvar bug-reference-map) +(with-eval-after-load 'bug-reference + (keymap-set bug-reference-map "<remap> <magit-visit-thing>" + 'bug-reference-push-button)) + +(easy-menu-define magit-mode-menu magit-mode-map + "Magit menu" + ;; Similar to `magit-dispatch' but exclude: + ;; - commands that are available from context menus: + ;; apply, reverse, discard, stage, unstage, + ;; cherry-pick, revert, reset, + ;; describe-section + ;; - commands that are available from submenus: + ;; git-command, ediff-dwim + ;; - and: refresh-all, status-jump, status-quick. + '("Magit" + "---" "Inspect" + [" Bisect..." magit-bisect t] + [" Cherries..." magit-cherry t] + [" Diff..." magit-diff t] + [" Ediff..." magit-ediff t] + [" Log..." magit-log t] + [" References..." magit-show-refs t] + "---" "Manipulate" + [" Commit..." magit-commit t] + [" Stash..." magit-stash t] + [" Tag..." magit-tag t] + "---" + [" Branch..." magit-branch t] + [" Remote..." magit-remote t] + "---" + [" Merge..." magit-merge t] + [" Rebase..." magit-rebase t] + "---" "Transfer" + [" Fetch..." magit-fetch t] + [" Pull..." magit-pull t] + [" Push..." magit-push t] + "---" "Setup" + [" Clone..." magit-clone t] + [" Ignore..." magit-gitignore t] + [" Init..." magit-init t] + "---" + ("Advanced" + ["Run..." magit-run t] + "---" + ["Apply patches..." magit-am t] + ["Format patches..." magit-patch t] + "---" + ["Note..." magit-notes t] + "---" + ["Submodule..." magit-submodule t] + ["Subtree..." magit-subtree t] + ["Worktree..." magit-worktree t]) + "---" + ["Show command dispatcher..." magit-dispatch t] + ["Show manual" magit-info t] + ["Show another buffer" magit-display-repository-buffer t] + "---" + ("Change buffer arguments" + ["Diff arguments" magit-diff-refresh t] + ["Log arguments" magit-log-refresh t]) + ["Refresh buffer" magit-refresh t] + ["Bury buffer" magit-mode-bury-buffer t])) + +;;; Mode + +(defun magit-load-config-extensions () + "Load Magit extensions that are defined at the Git config layer." + (dolist (ext (magit-get-all "magit.extension")) + (let ((sym (intern (format "magit-%s-mode" ext)))) + (when (fboundp sym) + (funcall sym 1))))) + +(define-derived-mode magit-mode magit-section-mode "Magit" + "Parent major mode from which Magit major modes inherit. + +Magit is documented in info node `(magit)'." + :interactive nil + :group 'magit + (magit-hack-dir-local-variables) + (face-remap-add-relative 'header-line 'magit-header-line) + (setq mode-line-process (magit-repository-local-get 'mode-line-process)) + (setq-local revert-buffer-function #'magit-refresh-buffer) + (setq-local bookmark-make-record-function #'magit--make-bookmark) + (setq-local imenu-create-index-function #'magit--imenu-create-index) + (setq-local imenu-default-goto-function #'magit--imenu-goto-function) + (setq-local isearch-filter-predicate #'magit-section--open-temporarily)) + +(defun magit-hack-dir-local-variables () + "Like `hack-dir-local-variables-non-file-buffer' but ignore some variables." + (let ((ignored-local-variables + `(show-trailing-whitespace + ,@ignored-local-variables))) + (hack-dir-local-variables-non-file-buffer))) + +;;; Local Variables + +(defvar-local magit-buffer-arguments nil) +(defvar-local magit-buffer-diff-type nil) +(defvar-local magit-buffer-diff-args nil) +(defvar-local magit-buffer-diff-files nil) +(defvar-local magit-buffer-diff-files-suspended nil) +(defvar-local magit-buffer-file-name nil) +(defvar-local magit-buffer-files nil) +(defvar-local magit-buffer-log-args nil) +(defvar-local magit-buffer-log-files nil) +(defvar-local magit-buffer-range nil) +(defvar-local magit-buffer-range-hashed nil) +(defvar-local magit-buffer-refname nil) +(defvar-local magit-buffer-revision nil) +(defvar-local magit-buffer-revision-hash nil) +(defvar-local magit-buffer-revisions nil) +(defvar-local magit-buffer-typearg nil) +(defvar-local magit-buffer-upstream nil) + +;; These variables are also used in file-visiting buffers. +;; Because the user may change the major-mode, they have +;; to be permanent buffer-local. +(put 'magit-buffer-file-name 'permanent-local t) +(put 'magit-buffer-refname 'permanent-local t) +(put 'magit-buffer-revision 'permanent-local t) +(put 'magit-buffer-revision-hash 'permanent-local t) + +;; `magit-status' re-enables mode function but its refresher +;; function does not reinstate this. +(put 'magit-buffer-diff-files-suspended 'permanent-local t) + +(cl-defgeneric magit-buffer-value () + "Return the value of the current buffer. +The \"value\" identifies what is being displayed in the buffer. +The buffer's major-mode should derive from `magit-section-mode'." + nil) + +(defvar-local magit-previous-section nil) +(put 'magit-previous-section 'permanent-local t) + +;;; Setup Buffer + +(defmacro magit-setup-buffer (mode &optional locked &rest bindings) + (declare (indent 2)) + `(magit-setup-buffer-internal + ,mode ,locked + ,(cons 'list (mapcar (pcase-lambda (`(,var ,form)) + `(list ',var ,form)) + bindings)))) + +(defun magit-setup-buffer-internal ( mode locked bindings + &optional buffer-or-name directory) + (let* ((value (and locked + (with-temp-buffer + (pcase-dolist (`(,var ,val) bindings) + (set (make-local-variable var) val)) + (let ((major-mode mode)) + (magit-buffer-value))))) + (buffer (if buffer-or-name + (get-buffer-create buffer-or-name) + (magit-get-mode-buffer mode value))) + (section (and buffer (magit-current-section))) + (created (not buffer))) + (unless buffer + (setq buffer (magit-generate-new-buffer mode value))) + (with-current-buffer buffer + (setq magit-previous-section section) + (when directory + (setq default-directory directory)) + (funcall mode) + (magit-xref-setup #'magit-setup-buffer-internal bindings) + (pcase-dolist (`(,var ,val) bindings) + (set (make-local-variable var) val)) + (when created + (run-hooks 'magit-create-buffer-hook))) + (magit-display-buffer buffer) + (with-current-buffer buffer + (run-hooks 'magit-setup-buffer-hook) + (magit-refresh-buffer) + (when created + (run-hooks 'magit-post-create-buffer-hook))) + buffer)) + +;;; Display Buffer + +(defvar magit-display-buffer-noselect nil + "If non-nil, then `magit-display-buffer' doesn't call `select-window'.") + +(defun magit-display-buffer (buffer &optional display-function) + "Display BUFFER in some window and maybe select it. + +If optional DISPLAY-FUNCTION is non-nil, then use that to display +the buffer. Otherwise use `magit-display-buffer-function', which +is the normal case. + +Then, unless `magit-display-buffer-noselect' is non-nil, select +the window which was used to display the buffer. + +Also run the hooks `magit-pre-display-buffer-hook' +and `magit-post-display-buffer-hook'." + (with-current-buffer buffer + (run-hooks 'magit-pre-display-buffer-hook)) + (let ((window (funcall (or display-function magit-display-buffer-function) + buffer))) + (unless magit-display-buffer-noselect + (let* ((old-frame (selected-frame)) + (new-frame (window-frame window))) + (select-window window) + (unless (eq old-frame new-frame) + (select-frame-set-input-focus new-frame))))) + (with-current-buffer buffer + (run-hooks 'magit-post-display-buffer-hook))) + +(defun magit-display-buffer-traditional (buffer) + "Display BUFFER the way this has traditionally been done." + (display-buffer + buffer (if (and (derived-mode-p 'magit-mode) + (not (memq (with-current-buffer buffer major-mode) + '(magit-process-mode + magit-revision-mode + magit-diff-mode + magit-stash-mode + magit-status-mode)))) + '(display-buffer-same-window) + nil))) ; display in another window + +(defun magit-display-buffer-same-window-except-diff-v1 (buffer) + "Display BUFFER in the selected window except for some modes. +If a buffer's `major-mode' derives from `magit-diff-mode' or +`magit-process-mode', display it in another window. Display all +other buffers in the selected window." + (display-buffer + buffer (if (with-current-buffer buffer + (derived-mode-p 'magit-diff-mode 'magit-process-mode)) + '(nil (inhibit-same-window . t)) + '(display-buffer-same-window)))) + +(defun magit--display-buffer-fullframe (buffer alist) + (when-let ((window (or (display-buffer-reuse-window buffer alist) + (display-buffer-same-window buffer alist) + (display-buffer-pop-up-window buffer alist) + (display-buffer-use-some-window buffer alist)))) + (delete-other-windows window) + window)) + +(defun magit-display-buffer-fullframe-status-v1 (buffer) + "Display BUFFER, filling entire frame if BUFFER is a status buffer. +Otherwise, behave like `magit-display-buffer-traditional'." + (if (eq (with-current-buffer buffer major-mode) + 'magit-status-mode) + (display-buffer buffer '(magit--display-buffer-fullframe)) + (magit-display-buffer-traditional buffer))) + +(defun magit--display-buffer-topleft (buffer alist) + (or (display-buffer-reuse-window buffer alist) + (when-let ((window2 (display-buffer-pop-up-window buffer alist))) + (let ((window1 (get-buffer-window)) + (buffer1 (current-buffer)) + (buffer2 (window-buffer window2)) + (w2-quit-restore (window-parameter window2 'quit-restore))) + (set-window-buffer window1 buffer2) + (set-window-buffer window2 buffer1) + (select-window window2) + ;; Swap some window state that `magit-mode-quit-window' and + ;; `quit-restore-window' inspect. + (set-window-prev-buffers window2 (cdr (window-prev-buffers window1))) + (set-window-prev-buffers window1 nil) + (set-window-parameter window2 'magit-dedicated + (window-parameter window1 'magit-dedicated)) + (set-window-parameter window1 'magit-dedicated t) + (set-window-parameter window1 'quit-restore + (list 'window 'window + (nth 2 w2-quit-restore) + (nth 3 w2-quit-restore))) + (set-window-parameter window2 'quit-restore nil) + window1)))) + +(defun magit-display-buffer-fullframe-status-topleft-v1 (buffer) + "Display BUFFER, filling entire frame if BUFFER is a status buffer. +When BUFFER derives from `magit-diff-mode' or +`magit-process-mode', try to display BUFFER to the top or left of +the current buffer rather than to the bottom or right, as +`magit-display-buffer-fullframe-status-v1' would. Whether the +split is made vertically or horizontally is determined by +`split-window-preferred-function'." + (display-buffer + buffer + (cond ((eq (with-current-buffer buffer major-mode) + 'magit-status-mode) + '(magit--display-buffer-fullframe)) + ((with-current-buffer buffer + (derived-mode-p 'magit-diff-mode 'magit-process-mode)) + '(magit--display-buffer-topleft)) + (t + '(display-buffer-same-window))))) + +(defun magit--display-buffer-fullcolumn (buffer alist) + (when-let ((window (or (display-buffer-reuse-window buffer alist) + (display-buffer-same-window buffer alist) + (display-buffer-below-selected buffer alist)))) + (delete-other-windows-vertically window) + window)) + +(defun magit-display-buffer-fullcolumn-most-v1 (buffer) + "Display BUFFER using the full column except in some cases. +For most cases where BUFFER's `major-mode' derives from +`magit-mode', display it in the selected window and grow that +window to the full height of the frame, deleting other windows in +that column as necessary. However, display BUFFER in another +window if 1) BUFFER's mode derives from `magit-process-mode', or +2) BUFFER's mode derives from `magit-diff-mode', provided that +the mode of the current buffer derives from `magit-log-mode' or +`magit-cherry-mode'." + (display-buffer + buffer + (cond ((and (or (bound-and-true-p git-commit-mode) + (derived-mode-p 'magit-log-mode + 'magit-cherry-mode + 'magit-reflog-mode)) + (with-current-buffer buffer + (derived-mode-p 'magit-diff-mode))) + nil) + ((with-current-buffer buffer + (derived-mode-p 'magit-process-mode)) + nil) + (t + '(magit--display-buffer-fullcolumn))))) + +(defun magit-maybe-set-dedicated () + "Mark the selected window as dedicated if appropriate. + +If a new window was created to display the buffer, then remember +that fact. That information is used by `magit-mode-quit-window', +to determine whether the window should be deleted when its last +Magit buffer is buried." + (let ((window (get-buffer-window (current-buffer)))) + (when (and (window-live-p window) + (not (window-prev-buffers window))) + (set-window-parameter window 'magit-dedicated t)))) + +;;; Get Buffer + +(defvar-local magit--default-directory nil + "Value of `default-directory' when buffer is generated. +This exists to prevent a let-bound `default-directory' from +tricking `magit-get-mode-buffer' or `magit-mode-get-buffers' +into thinking a buffer belongs to a repo that it doesn't.") +(put 'magit--default-directory 'permanent-local t) + +(defun magit-mode-get-buffers () + (let ((topdir (magit-toplevel))) + (--filter (with-current-buffer it + (and (derived-mode-p 'magit-mode) + (equal magit--default-directory topdir))) + (buffer-list)))) + +(defvar-local magit-buffer-locked-p nil) +(put 'magit-buffer-locked-p 'permanent-local t) + +(defun magit-get-mode-buffer (mode &optional value frame) + "Return buffer belonging to the current repository whose major-mode is MODE. + +If no such buffer exists then return nil. Multiple buffers with +the same major-mode may exist for a repository but only one can +exist that hasn't been locked to its value. Return that buffer +\(or nil if there is no such buffer) unless VALUE is non-nil, in +which case return the buffer that has been locked to that value. + +If FRAME is nil or omitted, then consider all buffers. Otherwise + only consider buffers that are displayed in some live window + on some frame. +If `all', then consider all buffers on all frames. +If `visible', then only consider buffers on all visible frames. +If `selected' or t, then only consider buffers on the selected + frame. +If a frame, then only consider buffers on that frame." + (let ((topdir (magit--toplevel-safe))) + (cl-flet* ((b (buffer) + (with-current-buffer buffer + (and (eq major-mode mode) + (equal magit--default-directory topdir) + (if value + (and magit-buffer-locked-p + (equal (magit-buffer-value) value)) + (not magit-buffer-locked-p)) + buffer))) + (w (window) + (b (window-buffer window))) + (f (frame) + (seq-some #'w (window-list frame 'no-minibuf)))) + (pcase-exhaustive frame + ('nil (seq-some #'b (buffer-list))) + ('all (seq-some #'f (frame-list))) + ('visible (seq-some #'f (visible-frame-list))) + ((or 'selected 't) (seq-some #'w (window-list (selected-frame)))) + ((guard (framep frame)) (seq-some #'w (window-list frame))))))) + +(defun magit-generate-new-buffer (mode &optional value directory) + (let* ((default-directory (or directory (magit--toplevel-safe))) + (name (funcall magit-generate-buffer-name-function mode value)) + (buffer (generate-new-buffer name))) + (with-current-buffer buffer + (setq magit--default-directory default-directory) + (setq magit-buffer-locked-p (and value t)) + (magit-restore-section-visibility-cache mode)) + (when magit-uniquify-buffer-names + (add-to-list 'uniquify-list-buffers-directory-modes mode) + (with-current-buffer buffer + (setq list-buffers-directory (abbreviate-file-name default-directory))) + (let ((uniquify-buffer-name-style + (if (memq uniquify-buffer-name-style '(nil forward)) + 'post-forward-angle-brackets + uniquify-buffer-name-style))) + (uniquify-rationalize-file-buffer-names + name (file-name-directory (directory-file-name default-directory)) + buffer))) + buffer)) + +(defun magit-generate-buffer-name-default-function (mode &optional value) + "Generate buffer name for a MODE buffer in the current repository. +The returned name is based on `magit-buffer-name-format' and +takes `magit-uniquify-buffer-names' and VALUE, if non-nil, into +account." + (let ((m (substring (symbol-name mode) 0 -5)) + (v (and value (format "%s" (ensure-list value)))) + (n (if magit-uniquify-buffer-names + (file-name-nondirectory + (directory-file-name default-directory)) + (abbreviate-file-name default-directory)))) + (format-spec + magit-buffer-name-format + `((?m . ,m) + (?M . ,(if (eq mode 'magit-status-mode) "magit" m)) + (?v . ,(or v "")) + (?V . ,(if v (concat " " v) "")) + (?t . ,n) + (?x . ,(if magit-uniquify-buffer-names "" "*")))))) + +;;; Buffer Lock + +(defun magit-toggle-buffer-lock () + "Lock the current buffer to its value or unlock it. + +Locking a buffer to its value prevents it from being reused to +display another value. The name of a locked buffer contains its +value, which allows telling it apart from other locked buffers +and the unlocked buffer. + +Not all Magit buffers can be locked to their values, for example +it wouldn't make sense to lock a status buffer. + +There can only be a single unlocked buffer using a certain +major-mode per repository. So when a buffer is being unlocked +and another unlocked buffer already exists for that mode and +repository, then the former buffer is instead deleted and the +latter is displayed in its place." + (interactive) + (if magit-buffer-locked-p + (if-let ((unlocked (magit-get-mode-buffer major-mode))) + (let ((locked (current-buffer))) + (switch-to-buffer unlocked nil t) + (kill-buffer locked)) + (setq magit-buffer-locked-p nil) + (rename-buffer (funcall magit-generate-buffer-name-function + major-mode))) + (if-let ((value (magit-buffer-value))) + (if-let ((locked (magit-get-mode-buffer major-mode value))) + (let ((unlocked (current-buffer))) + (switch-to-buffer locked nil t) + (kill-buffer unlocked)) + (setq magit-buffer-locked-p t) + (rename-buffer (funcall magit-generate-buffer-name-function + major-mode value))) + (user-error "Buffer has no value it could be locked to")))) + +;;; Bury Buffer + +(defun magit-mode-bury-buffer (&optional kill-buffer) + "Bury or kill the current buffer. + +Use `magit-bury-buffer-function' to bury the buffer when called +without a prefix argument or to kill it when called with a single +prefix argument. + +With two prefix arguments, always kill the current and all other +Magit buffers, associated with this repository." + (interactive "P") + (if (>= (prefix-numeric-value kill-buffer) 16) + (mapc #'kill-buffer (magit-mode-get-buffers)) + (funcall magit-bury-buffer-function kill-buffer))) + +(defun magit-mode-quit-window (kill-buffer) + "Quit the selected window and bury its buffer. + +This behaves similar to `quit-window', but when the window +was originally created to display a Magit buffer and the +current buffer is the last remaining Magit buffer that was +ever displayed in the selected window, then delete that +window." + (if (or (one-window-p) + (--first (let ((buffer (car it))) + (and (not (eq buffer (current-buffer))) + (buffer-live-p buffer) + (or (not (window-parameter nil 'magit-dedicated)) + (with-current-buffer buffer + (derived-mode-p 'magit-mode + 'magit-process-mode))))) + (window-prev-buffers))) + (quit-window kill-buffer) + (let ((window (selected-window))) + (quit-window kill-buffer) + (when (window-live-p window) + (delete-window window))))) + +;;; Refresh Buffers + +(defvar magit-inhibit-refresh nil) + +(defun magit-refresh () + "Refresh some buffers belonging to the current repository. + +Refresh the current buffer if its major mode derives from +`magit-mode', and refresh the corresponding status buffer. + +Run hooks `magit-pre-refresh-hook' and `magit-post-refresh-hook'." + (interactive) + (unless magit-inhibit-refresh + (unwind-protect + (let ((start (current-time)) + (magit--refresh-cache (or magit--refresh-cache + (list (cons 0 0))))) + (when magit-refresh-verbose + (message "Refreshing magit...")) + (magit-run-hook-with-benchmark 'magit-pre-refresh-hook) + (cond ((derived-mode-p 'magit-mode) + (magit-refresh-buffer)) + ((derived-mode-p 'tabulated-list-mode) + (revert-buffer))) + (when-let ((buffer (and magit-refresh-status-buffer + (not (derived-mode-p 'magit-status-mode)) + (magit-get-mode-buffer 'magit-status-mode)))) + (with-current-buffer buffer + (magit-refresh-buffer))) + (magit-run-hook-with-benchmark 'magit-post-refresh-hook) + (when magit-refresh-verbose + (let* ((c (caar magit--refresh-cache)) + (a (+ c (cdar magit--refresh-cache)))) + (message "Refreshing magit...done (%.3fs, cached %s/%s (%.0f%%))" + (float-time (time-since start)) + c a (* (/ c (* a 1.0)) 100))))) + (run-hooks 'magit-unwind-refresh-hook)))) + +(defun magit-refresh-all () + "Refresh all buffers belonging to the current repository. + +Refresh all Magit buffers belonging to the current repository, +and revert buffers that visit files located inside the current +repository. + +Run hooks `magit-pre-refresh-hook' and `magit-post-refresh-hook'." + (interactive) + (magit-run-hook-with-benchmark 'magit-pre-refresh-hook) + (dolist (buffer (magit-mode-get-buffers)) + (with-current-buffer buffer (magit-refresh-buffer))) + (magit-run-hook-with-benchmark 'magit-post-refresh-hook)) + +(defvar-local magit-refresh-start-time nil) + +(defun magit-refresh-buffer (&rest _ignore) + "Refresh the current Magit buffer." + (interactive) + (setq magit-refresh-start-time (current-time)) + (let ((refresh (intern (format "%s-refresh-buffer" + (substring (symbol-name major-mode) 0 -5)))) + (magit--refresh-cache (or magit--refresh-cache (list (cons 0 0))))) + (when (functionp refresh) + (when magit-refresh-verbose + (message "Refreshing buffer `%s'..." (buffer-name))) + (let* ((buffer (current-buffer)) + (windows (cl-mapcan + (lambda (window) + (with-selected-window window + (with-current-buffer buffer + (and-let* ((section (magit-section-at))) + `(( ,window + ,section + ,@(magit-section-get-relative-position + section))))))) + ;; If it qualifies, then the selected window + ;; comes first, but we want to handle it last + ;; so that its `magit-section-movement-hook' + ;; run can override the effects of other runs. + (or (nreverse (get-buffer-window-list buffer nil t)) + (list (selected-window)))))) + (deactivate-mark) + (setq magit-section-pre-command-section nil) + (setq magit-section-highlight-overlays nil) + (setq magit-section-highlighted-sections nil) + (setq magit-section-unhighlight-sections nil) + (let ((inhibit-read-only t)) + (erase-buffer) + (save-excursion + (funcall refresh))) + (pcase-dolist (`(,window . ,args) windows) + (if (eq buffer (window-buffer window)) + (with-selected-window window + (apply #'magit-section-goto-successor args)) + (with-current-buffer buffer + (let ((magit-section-movement-hook nil)) + (apply #'magit-section-goto-successor args))))) + (run-hooks 'magit-refresh-buffer-hook) + (magit-section-update-highlight) + (set-buffer-modified-p nil)) + (when magit-refresh-verbose + (message "Refreshing buffer `%s'...done (%.3fs)" (buffer-name) + (float-time (time-since magit-refresh-start-time))))))) + +(defun magit-profile-refresh-buffer () + "Profile refreshing the current Magit buffer." + (interactive) + (require (quote elp)) + (when (fboundp 'elp-reset-all) + (elp-reset-all) + (elp-instrument-package "magit-") + (elp-instrument-package "forge-") + (magit-refresh-buffer) + (elp-results) + (elp-reset-all))) + +;;; Save File-Visiting Buffers + +(defvar magit--disable-save-buffers nil) + +(defun magit-pre-command-hook () + (setq magit--disable-save-buffers nil)) +(add-hook 'pre-command-hook #'magit-pre-command-hook) + +(defvar magit-after-save-refresh-buffers nil) + +(defun magit-after-save-refresh-buffers () + (dolist (buffer magit-after-save-refresh-buffers) + (when (buffer-live-p buffer) + (with-current-buffer buffer + (magit-refresh-buffer)))) + (setq magit-after-save-refresh-buffers nil) + (remove-hook 'post-command-hook #'magit-after-save-refresh-buffers)) + +(defun magit-after-save-refresh-status () + "Refresh the status buffer of the current repository. + +This function is intended to be added to `after-save-hook'. + +If the status buffer does not exist or the file being visited in +the current buffer isn't inside the working tree of a repository, +then do nothing. + +Note that refreshing a Magit buffer is done by re-creating its +contents from scratch, which can be slow in large repositories. +If you are not satisfied with Magit's performance, then you +should obviously not add this function to that hook." + (when (and (not magit--disable-save-buffers) + (magit-inside-worktree-p t)) + (when-let ((buffer (ignore-errors + (magit-get-mode-buffer 'magit-status-mode)))) + (add-to-list 'magit-after-save-refresh-buffers buffer) + (add-hook 'post-command-hook #'magit-after-save-refresh-buffers)))) + +(defun magit-maybe-save-repository-buffers () + "Maybe save file-visiting buffers belonging to the current repository. +Do so if `magit-save-repository-buffers' is non-nil. You should +not remove this from any hooks, instead set that variable to nil +if you so desire." + (when (and magit-save-repository-buffers + (not magit--disable-save-buffers)) + (setq magit--disable-save-buffers t) + (let ((msg (current-message))) + (magit-save-repository-buffers + (eq magit-save-repository-buffers 'dontask)) + (when (and msg + (current-message) + (not (equal msg (current-message)))) + (message "%s" msg))))) + +(add-hook 'magit-pre-refresh-hook #'magit-maybe-save-repository-buffers) +(add-hook 'magit-pre-call-git-hook #'magit-maybe-save-repository-buffers) +(add-hook 'magit-pre-start-git-hook #'magit-maybe-save-repository-buffers) + +(defvar-local magit-inhibit-refresh-save nil) + +(defun magit-save-repository-buffers (&optional arg) + "Save file-visiting buffers belonging to the current repository. +After any buffer where `buffer-save-without-query' is non-nil +is saved without asking, the user is asked about each modified +buffer which visits a file in the current repository. Optional +argument (the prefix) non-nil means save all with no questions." + (interactive "P") + (when-let ((topdir (magit-rev-parse-safe "--show-toplevel"))) + (let ((remote (file-remote-p default-directory)) + (save-some-buffers-action-alist + `((?Y (lambda (buffer) + (with-current-buffer buffer + (setq buffer-save-without-query t) + (save-buffer))) + "to save the current buffer and remember choice") + (?N (lambda (buffer) + (with-current-buffer buffer + (setq magit-inhibit-refresh-save t))) + "to skip the current buffer and remember choice") + ,@save-some-buffers-action-alist)) + (topdirs nil) + (unwiped nil) + (magit--wip-inhibit-autosave t)) + (unwind-protect + (save-some-buffers + arg + (lambda () + ;; If the current file is modified and resides inside + ;; a repository, and a let-binding is in effect, which + ;; places us in another repository, then this binding + ;; is needed to prevent that file from being saved. + (and-let* ((default-directory + (and buffer-file-name + (file-name-directory buffer-file-name)))) + (and + ;; Check whether the repository still exists. + (file-exists-p default-directory) + ;; Check whether refreshing is disabled. + (not magit-inhibit-refresh-save) + ;; Check whether the visited file is either on the + ;; same remote as the repository, or both are on + ;; the local system. + (equal (file-remote-p buffer-file-name) remote) + ;; Delayed checks that are more expensive for remote + ;; repositories, due to the required network access. + ;; + ;; Check whether the file is inside the repository. + (equal (or (cdr (assoc default-directory topdirs)) + (let ((top (magit-rev-parse-safe "--show-toplevel"))) + (push (cons default-directory top) topdirs) + top)) + topdir) + ;; Check whether the file is actually writable. + (file-writable-p buffer-file-name) + (prog1 t + ;; Schedule for wip commit, if appropriate. + (when magit-wip-after-save-local-mode + (push (expand-file-name buffer-file-name) unwiped))))))) + (when unwiped + (let ((default-directory topdir)) + (magit-wip-commit-worktree + (magit-wip-get-ref) + unwiped + (if (cdr unwiped) + (format "autosave %s files after save" (length unwiped)) + (format "autosave %s after save" + (file-relative-name (car unwiped))))))))))) + +;;; Restore Window Configuration + +(defvar magit-inhibit-save-previous-winconf nil) + +(defvar-local magit-previous-window-configuration nil) +(put 'magit-previous-window-configuration 'permanent-local t) + +(defun magit-save-window-configuration () + "Save the current window configuration. + +Later, when the buffer is buried, it may be restored by +`magit-restore-window-configuration'." + (if magit-inhibit-save-previous-winconf + (when (eq magit-inhibit-save-previous-winconf 'unset) + (setq magit-previous-window-configuration nil)) + (unless (get-buffer-window (current-buffer) (selected-frame)) + (setq magit-previous-window-configuration + (current-window-configuration))))) + +(defun magit-restore-window-configuration (&optional kill-buffer) + "Bury or kill the current buffer and restore previous window configuration." + (let ((winconf magit-previous-window-configuration) + (buffer (current-buffer)) + (frame (selected-frame))) + (quit-window kill-buffer (selected-window)) + (when (and winconf (equal frame (window-configuration-frame winconf))) + (set-window-configuration winconf) + (when (buffer-live-p buffer) + (with-current-buffer buffer + (setq magit-previous-window-configuration nil))) + (set-buffer (with-selected-window (selected-window) + (current-buffer)))))) + +;;; Buffer History + +(defun magit-go-backward () + "Move backward in current buffer's history." + (interactive) + (if help-xref-stack + (help-xref-go-back (current-buffer)) + (user-error "No previous entry in buffer's history"))) + +(defun magit-go-forward () + "Move forward in current buffer's history." + (interactive) + (if help-xref-forward-stack + (help-xref-go-forward (current-buffer)) + (user-error "No next entry in buffer's history"))) + +(defun magit-insert-xref-buttons () + "Insert xref buttons." + (when (and (not magit-buffer-locked-p) + (or help-xref-stack help-xref-forward-stack)) + (when help-xref-stack + (magit-xref-insert-button help-back-label 'magit-xref-backward)) + (when help-xref-forward-stack + (when help-xref-stack + (insert " ")) + (magit-xref-insert-button help-forward-label 'magit-xref-forward)))) + +(defun magit-xref-insert-button (label type) + (magit-insert-section (button label) + (insert-text-button label 'type type + 'help-args (list (current-buffer))))) + +(define-button-type 'magit-xref-backward + :supertype 'help-back + 'mouse-face 'magit-section-highlight + 'help-echo (purecopy "mouse-2, RET: go back to previous history entry")) + +(define-button-type 'magit-xref-forward + :supertype 'help-forward + 'mouse-face 'magit-section-highlight + 'help-echo (purecopy "mouse-2, RET: go back to next history entry")) + +(defvar magit-xref-modes + '(magit-log-mode + magit-reflog-mode + magit-diff-mode + magit-revision-mode) + "List of modes for which to insert navigation buttons.") + +(defun magit-xref-setup (fn args) + (when (memq major-mode magit-xref-modes) + (when help-xref-stack-item + (push (cons (point) help-xref-stack-item) help-xref-stack) + (setq help-xref-forward-stack nil)) + (when-let ((tail (nthcdr 30 help-xref-stack))) + (setcdr tail nil)) + (setq help-xref-stack-item + (list 'magit-xref-restore fn default-directory args)))) + +(defun magit-xref-restore (fn dir args) + (setq default-directory dir) + (funcall fn major-mode nil args) + (magit-refresh-buffer)) + +;;; Repository-Local Cache + +(defvar magit-repository-local-cache nil + "Alist mapping `magit-toplevel' paths to alists of key/value pairs.") + +(defun magit-repository-local-repository () + "Return the key for the current repository." + (or (bound-and-true-p magit--default-directory) + (magit-toplevel))) + +(defun magit-repository-local-set (key value &optional repository) + "Set the repository-local VALUE for KEY. + +Unless specified, REPOSITORY is the current buffer's repository. + +If REPOSITORY is nil (meaning there is no current repository), +then the value is not cached, and we return nil." + (let* ((repokey (or repository (magit-repository-local-repository))) + (cache (assoc repokey magit-repository-local-cache))) + ;; Don't cache values for a nil REPOSITORY, as the 'set' and 'get' + ;; calls for some KEY may happen in unrelated contexts. + (when repokey + (if cache + (let ((keyvalue (assoc key (cdr cache)))) + (if keyvalue + ;; Update pre-existing value for key. + (setcdr keyvalue value) + ;; No such key in repository-local cache. + (push (cons key value) (cdr cache)))) + ;; No cache for this repository. + (push (cons repokey (list (cons key value))) + magit-repository-local-cache))))) + +(defun magit-repository-local-exists-p (key &optional repository) + "Non-nil when a repository-local value exists for KEY. + +Return a (KEY . VALUE) cons cell. + +The KEY is matched using `equal'. + +Unless specified, REPOSITORY is the current buffer's repository." + (and-let* ((cache (assoc (or repository + (magit-repository-local-repository)) + magit-repository-local-cache))) + (assoc key (cdr cache)))) + +(defun magit-repository-local-get (key &optional default repository) + "Return the repository-local value for KEY. + +Return DEFAULT if no value for KEY exists. + +The KEY is matched using `equal'. + +Unless specified, REPOSITORY is the current buffer's repository." + (if-let ((keyvalue (magit-repository-local-exists-p key repository))) + (cdr keyvalue) + default)) + +(defun magit-repository-local-delete (key &optional repository) + "Delete the repository-local value for KEY. + +Unless specified, REPOSITORY is the current buffer's repository. +If REPOSITORY is `all', then delete the value for KEY for all +repositories." + (if (eq repository 'all) + (dolist (cache magit-repository-local-cache) + (setf cache (compat-call assoc-delete-all key cache))) + (when-let ((cache (assoc (or repository + (magit-repository-local-repository)) + magit-repository-local-cache))) + (setf cache (compat-call assoc-delete-all key cache))))) + +(defmacro magit--with-repository-local-cache (key &rest body) + (declare (indent 1) (debug (form body))) + (let ((k (cl-gensym))) + `(let ((,k ,key)) + (if-let ((kv (magit-repository-local-exists-p ,k))) + (cdr kv) + (let ((v ,(macroexp-progn body))) + (magit-repository-local-set ,k v) + v))))) + +(defun magit-preserve-section-visibility-cache () + (when (derived-mode-p 'magit-status-mode 'magit-refs-mode) + (magit-repository-local-set + (cons major-mode 'magit-section-visibility-cache) + magit-section-visibility-cache))) + +(defun magit-restore-section-visibility-cache (mode) + (setq magit-section-visibility-cache + (magit-repository-local-get + (cons mode 'magit-section-visibility-cache)))) + +(defun magit-zap-caches (&optional all) + "Zap caches for the current repository. + +Remove the repository's entry from `magit-repository-local-cache', +remove the host's entry from `magit--host-git-version-cache', and +set `magit-section-visibility-cache' to nil for all Magit buffers +of the repository. + +With a prefix argument or if optional ALL is non-nil, discard the +mentioned caches completely." + (interactive) + (cond (all + (setq magit-repository-local-cache nil) + (setq magit--host-git-version-cache nil) + (dolist (buffer (buffer-list)) + (with-current-buffer buffer + (when (derived-mode-p 'magit-mode) + (setq magit-section-visibility-cache nil))))) + (t + (magit-with-toplevel + (setq magit-repository-local-cache + (cl-delete default-directory + magit-repository-local-cache + :key #'car :test #'equal)) + (setq magit--host-git-version-cache + (cl-delete (file-remote-p default-directory) + magit--host-git-version-cache + :key #'car :test #'equal))) + (dolist (buffer (magit-mode-get-buffers)) + (with-current-buffer buffer + (setq magit-section-visibility-cache nil)))))) + +;;; Utilities + +(defun magit-toggle-verbose-refresh () + "Toggle whether Magit refreshes buffers verbosely. +Enabling this helps figuring out which sections are bottlenecks. +The additional output can be found in the *Messages* buffer." + (interactive) + (setq magit-refresh-verbose (not magit-refresh-verbose)) + (message "%s verbose refreshing" + (if magit-refresh-verbose "Enabled" "Disabled"))) + +(defun magit-run-hook-with-benchmark (hook) + (cond + ((not hook)) + (magit-refresh-verbose + (message "Running %s..." hook) + (message "Running %s...done (%.3fs)" hook + (benchmark-elapse + (run-hook-wrapped + hook + (lambda (fn) + (message " %-50s %f" fn (benchmark-elapse (funcall fn)))))))) + ((run-hooks hook)))) + +;;; _ +(provide 'magit-mode) +;;; magit-mode.el ends here diff --git a/emacs/elpa/magit-20241004.917/magit-notes.el b/emacs/elpa/magit-20241004.917/magit-notes.el @@ -0,0 +1,201 @@ +;;; magit-notes.el --- Notes support -*- lexical-binding:t -*- + +;; Copyright (C) 2008-2024 The Magit Project Contributors + +;; Author: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> +;; Maintainer: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> + +;; SPDX-License-Identifier: GPL-3.0-or-later + +;; Magit is free software: you can redistribute it and/or modify it +;; under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. +;; +;; Magit is distributed in the hope that it will be useful, but WITHOUT +;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +;; or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public +;; License for more details. +;; +;; You should have received a copy of the GNU General Public License +;; along with Magit. If not, see <https://www.gnu.org/licenses/>. + +;;; Commentary: + +;; This library implements support for `git-notes'. + +;;; Code: + +(require 'magit) + +;;; Commands + +;;;###autoload (autoload 'magit-notes "magit" nil t) +(transient-define-prefix magit-notes () + "Edit notes attached to commits." + :man-page "git-notes" + ["Configure local settings" + ("c" magit-core.notesRef) + ("d" magit-notes.displayRef)] + ["Configure global settings" + ("C" magit-global-core.notesRef) + ("D" magit-global-notes.displayRef)] + ["Arguments for prune" + :if-not magit-notes-merging-p + ("-n" "Dry run" ("-n" "--dry-run"))] + ["Arguments for edit and remove" + :if-not magit-notes-merging-p + (magit-notes:--ref)] + ["Arguments for merge" + :if-not magit-notes-merging-p + (magit-notes:--strategy)] + ["Actions" + :if-not magit-notes-merging-p + ("T" "Edit" magit-notes-edit) + ("r" "Remove" magit-notes-remove) + ("m" "Merge" magit-notes-merge) + ("p" "Prune" magit-notes-prune)] + ["Actions" + :if magit-notes-merging-p + ("c" "Commit merge" magit-notes-merge-commit) + ("a" "Abort merge" magit-notes-merge-abort)]) + +(defun magit-notes-merging-p () + (let ((dir (expand-file-name "NOTES_MERGE_WORKTREE" (magit-gitdir)))) + (and (file-directory-p dir) + (directory-files dir nil "\\`[^.]")))) + +(transient-define-infix magit-core.notesRef () + :class 'magit--git-variable + :variable "core.notesRef" + :reader #'magit-notes-read-ref + :prompt "Set local core.notesRef") + +(transient-define-infix magit-notes.displayRef () + :class 'magit--git-variable + :variable "notes.displayRef" + :multi-value t + :reader #'magit-notes-read-refs + :prompt "Set local notes.displayRef") + +(transient-define-infix magit-global-core.notesRef () + :class 'magit--git-variable + :variable "core.notesRef" + :global t + :reader #'magit-notes-read-ref + :prompt "Set global core.notesRef") + +(transient-define-infix magit-global-notes.displayRef () + :class 'magit--git-variable + :variable "notes.displayRef" + :global t + :multi-value t + :reader #'magit-notes-read-refs + :prompt "Set global notes.displayRef") + +(transient-define-argument magit-notes:--ref () + :description "Manipulate ref" + :class 'transient-option + :key "-r" + :argument "--ref=" + :reader #'magit-notes-read-ref) + +(transient-define-argument magit-notes:--strategy () + :description "Merge strategy" + :class 'transient-option + :shortarg "-s" + :argument "--strategy=" + :choices '("manual" "ours" "theirs" "union" "cat_sort_uniq")) + +(defun magit-notes-edit (commit &optional ref) + "Edit the note attached to COMMIT. +REF is the notes ref used to store the notes. + +Interactively or when optional REF is nil use the value of Git +variable `core.notesRef' or \"refs/notes/commits\" if that is +undefined." + (interactive (magit-notes-read-args "Edit notes")) + (magit-run-git-with-editor "notes" (and ref (concat "--ref=" ref)) + "edit" commit)) + +(defun magit-notes-remove (commit &optional ref) + "Remove the note attached to COMMIT. +REF is the notes ref from which the note is removed. + +Interactively or when optional REF is nil use the value of Git +variable `core.notesRef' or \"refs/notes/commits\" if that is +undefined." + (interactive (magit-notes-read-args "Remove notes")) + (magit-run-git-with-editor "notes" (and ref (concat "--ref=" ref)) + "remove" commit)) + +(defun magit-notes-merge (ref) + "Merge the notes ref REF into the current notes ref. + +The current notes ref is the value of Git variable +`core.notesRef' or \"refs/notes/commits\" if that is undefined. + +When there are conflicts, then they have to be resolved in the +temporary worktree \".git/NOTES_MERGE_WORKTREE\". When +done use `magit-notes-merge-commit' to finish. To abort +use `magit-notes-merge-abort'." + (interactive (list (magit-read-string-ns "Merge reference"))) + (magit-run-git-with-editor "notes" "merge" ref)) + +(defun magit-notes-merge-commit () + "Commit the current notes ref merge. +Also see `magit-notes-merge'." + (interactive) + (magit-run-git-with-editor "notes" "merge" "--commit")) + +(defun magit-notes-merge-abort () + "Abort the current notes ref merge. +Also see `magit-notes-merge'." + (interactive) + (magit-run-git-with-editor "notes" "merge" "--abort")) + +(defun magit-notes-prune (&optional dry-run) + "Remove notes about unreachable commits." + (interactive (list (and (member "--dry-run" (transient-args 'magit-notes)) t))) + (when dry-run + (magit-process-buffer)) + (magit-run-git-with-editor "notes" "prune" (and dry-run "--dry-run"))) + +;;; Readers + +(defun magit-notes-read-ref (prompt _initial-input history) + (and-let* ((ref (magit-completing-read + prompt (magit-list-notes-refnames) nil nil + (and-let* ((def (magit-get "core.notesRef"))) + (if (string-prefix-p "refs/notes/" def) + (substring def 11) + def)) + history))) + (if (string-prefix-p "refs/" ref) + ref + (concat "refs/notes/" ref)))) + +(defun magit-notes-read-refs (prompt &optional _initial-input _history) + (mapcar (lambda (ref) + (if (string-prefix-p "refs/" ref) + ref + (concat "refs/notes/" ref))) + (completing-read-multiple + (concat prompt ": ") + (magit-list-notes-refnames) nil nil + (mapconcat (lambda (ref) + (if (string-prefix-p "refs/notes/" ref) + (substring ref 11) + ref)) + (magit-get-all "notes.displayRef") + ",")))) + +(defun magit-notes-read-args (prompt) + (list (magit-read-branch-or-commit prompt (magit-stash-at-point)) + (and-let* ((str (--first (string-match "^--ref=\\(.+\\)" it) + (transient-args 'magit-notes)))) + (match-string 1 str)))) + +;;; _ +(provide 'magit-notes) +;;; magit-notes.el ends here diff --git a/emacs/elpa/magit-20241004.917/magit-patch.el b/emacs/elpa/magit-20241004.917/magit-patch.el @@ -0,0 +1,328 @@ +;;; magit-patch.el --- Creating and applying patches -*- lexical-binding:t -*- + +;; Copyright (C) 2008-2024 The Magit Project Contributors + +;; Author: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> +;; Maintainer: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> + +;; SPDX-License-Identifier: GPL-3.0-or-later + +;; Magit is free software: you can redistribute it and/or modify it +;; under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. +;; +;; Magit is distributed in the hope that it will be useful, but WITHOUT +;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +;; or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public +;; License for more details. +;; +;; You should have received a copy of the GNU General Public License +;; along with Magit. If not, see <https://www.gnu.org/licenses/>. + +;;; Commentary: + +;; This library implements patch commands. + +;;; Code: + +(require 'magit) + +;;; Options + +(defcustom magit-patch-save-arguments '(exclude "--stat") + "Control arguments used by the command `magit-patch-save'. + +`magit-patch-save' (which see) saves a diff for the changes +shown in the current buffer in a patch file. It may use the +same arguments as used in the buffer or a subset thereof, or +a constant list of arguments, depending on this option and +the prefix argument." + :package-version '(magit . "2.12.0") + :group 'magit-diff + :type '(choice (const :tag "use buffer arguments" buffer) + (cons :tag "use buffer arguments except" + (const :format "" exclude) + (repeat :format "%v%i\n" + (string :tag "Argument"))) + (repeat :tag "use constant arguments" + (string :tag "Argument")))) + +;;; Commands + +;;;###autoload (autoload 'magit-patch "magit-patch" nil t) +(transient-define-prefix magit-patch () + "Create or apply patches." + ["Actions" + [("c" "Create patches" magit-patch-create) + ("w" "Apply patches" magit-am)] + [("a" "Apply plain patch" magit-patch-apply) + ("s" "Save diff as patch" magit-patch-save)] + [("r" "Request pull" magit-request-pull)]]) + +;;;###autoload (autoload 'magit-patch-create "magit-patch" nil t) +(transient-define-prefix magit-patch-create (range args files) + "Create patches for the commits in RANGE. +When a single commit is given for RANGE, create a patch for the +changes introduced by that commit (unlike 'git format-patch' +which creates patches for all commits that are reachable from +`HEAD' but not from the specified commit)." + :man-page "git-format-patch" + :incompatible '(("--subject-prefix=" "--rfc")) + ["Mail arguments" + (6 magit-format-patch:--in-reply-to) + (6 magit-format-patch:--thread) + (6 magit-format-patch:--from) + (6 magit-format-patch:--to) + (6 magit-format-patch:--cc)] + ["Patch arguments" + (magit-format-patch:--base) + (magit-format-patch:--reroll-count) + (5 magit-format-patch:--interdiff) + (magit-format-patch:--range-diff) + (magit-format-patch:--subject-prefix) + ("C-m r " "RFC subject prefix" "--rfc") + ("C-m l " "Add cover letter" "--cover-letter") + (5 magit-format-patch:--cover-from-description) + (5 magit-format-patch:--notes) + (magit-format-patch:--output-directory)] + ["Diff arguments" + (magit-diff:-U) + (magit-diff:-M) + (magit-diff:-C) + (magit-diff:--diff-algorithm) + (magit:--) + (7 "-b" "Ignore whitespace changes" ("-b" "--ignore-space-change")) + (7 "-w" "Ignore all whitespace" ("-w" "--ignore-all-space"))] + ["Actions" + ("c" "Create patches" magit-patch-create)] + (interactive + (if (not (eq transient-current-command 'magit-patch-create)) + (list nil nil nil) + (cons (if-let ((revs (magit-region-values 'commit t))) + (concat (car (last revs)) "^.." (car revs)) + (let ((range (magit-read-range-or-commit + "Create patches for range or commit"))) + (if (string-search ".." range) + range + (format "%s~..%s" range range)))) + (let ((args (transient-args 'magit-patch-create))) + (list (seq-filter #'stringp args) + (cdr (assoc "--" args))))))) + (if (not range) + (transient-setup 'magit-patch-create) + (magit-run-git "format-patch" range args "--" files) + (when (member "--cover-letter" args) + (save-match-data + (find-file + (expand-file-name + (concat (and-let* ((v (transient-arg-value "--reroll-count=" args))) + (format "v%s-" v)) + "0000-cover-letter.patch") + (let ((topdir (magit-toplevel))) + (if-let ((dir (transient-arg-value "--output-directory=" args))) + (expand-file-name dir topdir) + topdir)))))))) + +(transient-define-argument magit-format-patch:--in-reply-to () + :description "In reply to" + :class 'transient-option + :key "C-m C-r" + :argument "--in-reply-to=") + +(transient-define-argument magit-format-patch:--thread () + :description "Thread style" + :class 'transient-option + :key "C-m s " + :argument "--thread=" + :reader #'magit-format-patch-select-thread-style) + +(defun magit-format-patch-select-thread-style (&rest _ignore) + (magit-read-char-case "Thread style " t + (?d "[d]eep" "deep") + (?s "[s]hallow" "shallow"))) + +(transient-define-argument magit-format-patch:--base () + :description "Insert base commit" + :class 'transient-option + :key "C-m b " + :argument "--base=" + :reader #'magit-format-patch-select-base) + +(defun magit-format-patch-select-base (prompt initial-input history) + (or (magit-completing-read prompt (cons "auto" (magit-list-refnames)) + nil nil initial-input history "auto") + (user-error "Nothing selected"))) + +(transient-define-argument magit-format-patch:--reroll-count () + :description "Reroll count" + :class 'transient-option + :key "C-m v " + :shortarg "-v" + :argument "--reroll-count=" + :reader #'transient-read-number-N+) + +(transient-define-argument magit-format-patch:--interdiff () + :description "Insert interdiff" + :class 'transient-option + :key "C-m d i" + :argument "--interdiff=" + :reader #'magit-transient-read-revision) + +(transient-define-argument magit-format-patch:--range-diff () + :description "Insert range-diff" + :class 'transient-option + :key "C-m d r" + :argument "--range-diff=" + :reader #'magit-format-patch-select-range-diff) + +(defun magit-format-patch-select-range-diff (prompt _initial-input _history) + (magit-read-range-or-commit prompt)) + +(transient-define-argument magit-format-patch:--subject-prefix () + :description "Subject Prefix" + :class 'transient-option + :key "C-m p " + :argument "--subject-prefix=") + +(transient-define-argument magit-format-patch:--cover-from-description () + :description "Use branch description" + :class 'transient-option + :key "C-m D " + :argument "--cover-from-description=" + :reader #'magit-format-patch-select-description-mode) + +(defun magit-format-patch-select-description-mode (&rest _ignore) + (magit-read-char-case "Use description as " t + (?m "[m]essage" "message") + (?s "[s]ubject" "subject") + (?a "[a]uto" "auto") + (?n "[n]othing" "none"))) + +(transient-define-argument magit-format-patch:--notes () + :description "Insert commentary from notes" + :class 'transient-option + :key "C-m n " + :argument "--notes=" + :reader #'magit-notes-read-ref) + +(transient-define-argument magit-format-patch:--from () + :description "From" + :class 'transient-option + :key "C-m C-f" + :argument "--from=" + :reader #'magit-transient-read-person) + +(transient-define-argument magit-format-patch:--to () + :description "To" + :class 'transient-option + :key "C-m C-t" + :argument "--to=" + :reader #'magit-transient-read-person) + +(transient-define-argument magit-format-patch:--cc () + :description "CC" + :class 'transient-option + :key "C-m C-c" + :argument "--cc=" + :reader #'magit-transient-read-person) + +(transient-define-argument magit-format-patch:--output-directory () + :description "Output directory" + :class 'transient-option + :key "C-m o " + :shortarg "-o" + :argument "--output-directory=" + :reader #'transient-read-existing-directory) + +;;;###autoload (autoload 'magit-patch-apply "magit-patch" nil t) +(transient-define-prefix magit-patch-apply (file &rest args) + "Apply the patch file FILE." + :man-page "git-apply" + ["Arguments" + ("-i" "Also apply to index" "--index") + ("-c" "Only apply to index" "--cached") + ("-3" "Fall back on 3way merge" ("-3" "--3way"))] + ["Actions" + ("a" "Apply patch" magit-patch-apply)] + (interactive + (if (not (eq transient-current-command 'magit-patch-apply)) + (list nil) + (list (expand-file-name + (read-file-name "Apply patch: " + default-directory nil nil + (and-let* ((file (magit-file-at-point))) + (file-relative-name file)))) + (transient-args 'magit-patch-apply)))) + (if (not file) + (transient-setup 'magit-patch-apply) + (magit-run-git "apply" args "--" (magit-convert-filename-for-git file)))) + +;;;###autoload +(defun magit-patch-save (file &optional arg) + "Write current diff into patch FILE. + +What arguments are used to create the patch depends on the value +of `magit-patch-save-arguments' and whether a prefix argument is +used. + +If the value is the symbol `buffer', then use the same arguments +as the buffer. With a prefix argument use no arguments. + +If the value is a list beginning with the symbol `exclude', then +use the same arguments as the buffer except for those matched by +entries in the cdr of the list. The comparison is done using +`string-prefix-p'. With a prefix argument use the same arguments +as the buffer. + +If the value is a list of strings (including the empty list), +then use those arguments. With a prefix argument use the same +arguments as the buffer. + +Of course the arguments that are required to actually show the +same differences as those shown in the buffer are always used." + (interactive (list (read-file-name "Write patch file: " default-directory) + current-prefix-arg)) + (unless (derived-mode-p 'magit-diff-mode) + (user-error "Only diff buffers can be saved as patches")) + (let ((rev magit-buffer-range) + (typearg magit-buffer-typearg) + (args magit-buffer-diff-args) + (files magit-buffer-diff-files)) + (cond ((eq magit-patch-save-arguments 'buffer) + (when arg + (setq args nil))) + ((eq (car-safe magit-patch-save-arguments) 'exclude) + (unless arg + (setq args + (cl-set-difference args (cdr magit-patch-save-arguments) + :test #'equal)))) + ((not arg) + (setq args magit-patch-save-arguments))) + (with-temp-file file + (magit-git-insert "diff" rev "-p" typearg args "--" files))) + (magit-refresh)) + +;;;###autoload +(defun magit-request-pull (url start end) + "Request upstream to pull from your public repository. + +URL is the url of your publicly accessible repository. +START is a commit that already is in the upstream repository. +END is the last commit, usually a branch name, which upstream +is asked to pull. START has to be reachable from that commit." + (interactive + (list (magit-get "remote" (magit-read-remote "Remote") "url") + (magit-read-branch-or-commit "Start" (magit-get-upstream-branch)) + (magit-read-branch-or-commit "End"))) + (let ((dir default-directory)) + ;; mu4e changes default-directory + (compose-mail) + (setq default-directory dir)) + (message-goto-body) + (magit-git-insert "request-pull" start url end) + (set-buffer-modified-p nil)) + +;;; _ +(provide 'magit-patch) +;;; magit-patch.el ends here diff --git a/emacs/elpa/magit-20241004.917/magit-pkg.el b/emacs/elpa/magit-20241004.917/magit-pkg.el @@ -0,0 +1,18 @@ +;; -*- no-byte-compile: t; lexical-binding: nil -*- +(define-package "magit" "20241004.917" + "A Git porcelain inside Emacs." + '((emacs "26.1") + (compat "30.0.0.0") + (dash "2.19.1") + (magit-section "4.1.1") + (seq "2.24") + (transient "0.7.6") + (with-editor "3.4.2")) + :url "https://github.com/magit/magit" + :commit "2b6516e04431c339a41887b27ce6a1193df6e9c3" + :revdesc "2b6516e04431" + :keywords '("git" "tools" "vc") + :authors '(("Marius Vollmer" . "marius.vollmer@gmail.com") + ("Jonas Bernoulli" . "emacs.magit@jonas.bernoulli.dev")) + :maintainers '(("Jonas Bernoulli" . "emacs.magit@jonas.bernoulli.dev") + ("Kyle Meyer" . "kyle@kyleam.com"))) diff --git a/emacs/elpa/magit-20241004.917/magit-process.el b/emacs/elpa/magit-20241004.917/magit-process.el @@ -0,0 +1,1281 @@ +;;; magit-process.el --- Process functionality -*- lexical-binding:t -*- + +;; Copyright (C) 2008-2024 The Magit Project Contributors + +;; Author: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> +;; Maintainer: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> + +;; SPDX-License-Identifier: GPL-3.0-or-later + +;; Magit is free software: you can redistribute it and/or modify it +;; under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. +;; +;; Magit is distributed in the hope that it will be useful, but WITHOUT +;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +;; or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public +;; License for more details. +;; +;; You should have received a copy of the GNU General Public License +;; along with Magit. If not, see <https://www.gnu.org/licenses/>. + +;;; Commentary: + +;; This library implements the tools used to run Git for side-effects. + +;; Note that the functions used to run Git and then consume its +;; output, are defined in `magit-git.el'. There's a bit of overlap +;; though. + +;;; Code: + +(require 'magit-base) +(require 'magit-git) +(require 'magit-mode) + +(require 'ansi-color) +(require 'auth-source) +(require 'with-editor) + +(defvar y-or-n-p-map) + +;;; Options + +(defcustom magit-process-connection-type (not (eq system-type 'cygwin)) + "Connection type used for the Git process. + +If nil, use pipes: this is usually more efficient, and works on Cygwin. +If t, use ptys: this enables Magit to prompt for passphrases when needed." + :group 'magit-process + :type '(choice (const :tag "pipe" nil) + (const :tag "pty" t))) + +(defcustom magit-need-cygwin-noglob + (and (eq system-type 'windows-nt) + (with-temp-buffer + (let ((process-environment + (append magit-git-environment process-environment))) + (condition-case e + (process-file magit-git-executable + nil (current-buffer) nil + "-c" "alias.echo=!echo" "echo" "x{0}") + (file-error + (lwarn 'magit-process :warning + "Could not run Git: %S" e)))) + (equal "x0\n" (buffer-string)))) + "Whether to use a workaround for Cygwin's globbing behavior. + +If non-nil, add environment variables to `process-environment' to +prevent the git.exe distributed by Cygwin and MSYS2 from +attempting to perform glob expansion when called from a native +Windows build of Emacs. See #2246." + :package-version '(magit . "2.3.0") + :group 'magit-process + :type '(choice (const :tag "Yes" t) + (const :tag "No" nil))) + +(defcustom magit-process-popup-time -1 + "Popup the process buffer if a command takes longer than this many seconds." + :group 'magit-process + :type '(choice (const :tag "Never" -1) + (const :tag "Immediately" 0) + (integer :tag "After this many seconds"))) + +(defcustom magit-process-log-max 32 + "Maximum number of sections to keep in a process log buffer. +When adding a new section would go beyond the limit set here, +then the older half of the sections are remove. Sections that +belong to processes that are still running are never removed. +When this is nil, no sections are ever removed." + :package-version '(magit . "2.1.0") + :group 'magit-process + :type '(choice (const :tag "Never remove old sections" nil) integer)) + +(defvar magit-process-extreme-logging nil + "Whether `magit-process-file' logs to the *Messages* buffer. + +Only intended for temporary use when you try to figure out how +Magit uses Git behind the scene. Output that normally goes to +the magit-process buffer continues to go there. Not all output +goes to either of these two buffers. + +Also see `magit-git-debug'.") + +(defcustom magit-process-error-tooltip-max-lines 20 + "The number of lines for `magit-process-error-lines' to return. + +These are displayed in a tooltip for `mode-line-process' errors. + +If `magit-process-error-tooltip-max-lines' is nil, the tooltip +displays the text of `magit-process-error-summary' instead." + :package-version '(magit . "2.12.0") + :group 'magit-process + :type '(choice (const :tag "Use summary line" nil) + integer)) + +(defcustom magit-credential-cache-daemon-socket + (--some (pcase-let ((`(,prog . ,args) (split-string it))) + (if (and prog + (string-match-p + "\\`\\(?:\\(?:/.*/\\)?git-credential-\\)?cache\\'" prog)) + (or (cl-loop for (opt val) on args + if (string= opt "--socket") + return val) + (expand-file-name "~/.git-credential-cache/socket")))) + ;; Note: `magit-process-file' is not yet defined when + ;; evaluating this form, so we use `process-lines'. + (ignore-errors + (let ((process-environment + (append magit-git-environment process-environment))) + (process-lines magit-git-executable + "config" "--get-all" "credential.helper")))) + "If non-nil, start a credential cache daemon using this socket. + +When using Git's cache credential helper in the normal way, Emacs +sends a SIGHUP to the credential daemon after the git subprocess +has exited, causing the daemon to also quit. This can be avoided +by starting the `git-credential-cache--daemon' process directly +from Emacs. + +The function `magit-maybe-start-credential-cache-daemon' takes +care of starting the daemon if necessary, using the value of this +option as the socket. If this option is nil, then it does not +start any daemon. Likewise if another daemon is already running, +then it starts no new daemon. This function has to be a member +of the hook variable `magit-credential-hook' for this to work. +If an error occurs while starting the daemon, most likely because +the necessary executable is missing, then the function removes +itself from the hook, to avoid further futile attempts." + :package-version '(magit . "2.3.0") + :group 'magit-process + :type '(choice (file :tag "Socket") + (const :tag "Don't start a cache daemon" nil))) + +(defcustom magit-process-yes-or-no-prompt-regexp + (concat " [([]" + "\\([Yy]\\(?:es\\)?\\)" + "[/|]" + "\\([Nn]o?\\)" + ;; OpenSSH v8 prints this. See #3969. + "\\(?:/\\[fingerprint\\]\\)?" + "[])] ?[?:]? ?$") + "Regexp matching Yes-or-No prompts of Git and its subprocesses." + :package-version '(magit . "2.1.0") + :group 'magit-process + :type 'regexp) + +(defcustom magit-process-password-prompt-regexps + '("^\\(Enter \\)?[Pp]assphrase\\( for \\(RSA \\)?key '.*'\\)?: ?$" + ;; Match-group 99 is used to identify the "user@host" part. + "^\\(Enter \\|([^) ]+) \\)?\ +[Pp]assword\\( for '?\\(https?://\\)?\\(?99:[^']*\\)'?\\)?: ?$" + "Please enter the passphrase for the ssh key" + "Please enter the passphrase to unlock the OpenPGP secret key" + "^.*'s password: ?$" + "^Token: $" ; For git-credential-manager-core (#4318). + "^Yubikey for .*: ?$" + "^Enter PIN for .*: ?$") + "List of regexps matching password prompts of Git and its subprocesses. +Also see `magit-process-find-password-functions'." + :package-version '(magit . "3.0.0") + :group 'magit-process + :type '(repeat (regexp))) + +(defcustom magit-process-find-password-functions nil + "List of functions to try in sequence to get a password. + +These functions may be called when git asks for a password, which +is detected using `magit-process-password-prompt-regexps'. They +are called if and only if matching the prompt resulted in the +value of the 99th submatch to be non-nil. Therefore users can +control for which prompts these functions should be called by +putting the host name in the 99th submatch, or not. + +If the functions are called, then they are called in the order +given, with the host name as only argument, until one of them +returns non-nil. If they are not called or none of them returns +non-nil, then the password is read from the user instead." + :package-version '(magit . "2.3.0") + :group 'magit-process + :type 'hook + :options '(magit-process-password-auth-source)) + +(defcustom magit-process-username-prompt-regexps + '("^Username for '.*': ?$") + "List of regexps matching username prompts of Git and its subprocesses." + :package-version '(magit . "2.1.0") + :group 'magit-process + :type '(repeat (regexp))) + +(defcustom magit-process-prompt-functions nil + "List of functions used to forward arbitrary questions to the user. + +Magit has dedicated support for forwarding username and password +prompts and Yes-or-No questions asked by Git and its subprocesses +to the user. This can be customized using other options in the +`magit-process' customization group. + +If you encounter a new question that isn't handled by default, +then those options should be used instead of this hook. + +However subprocesses may also ask questions that differ too much +from what the code related to the above options assume, and this +hook allows users to deal with such questions explicitly. + +Each function is called with the process and the output string +as arguments until one of the functions returns non-nil. The +function is responsible for asking the user the appropriate +question using, e.g., `read-char-choice' and then forwarding the +answer to the process using `process-send-string'. + +While functions such as `magit-process-yes-or-no-prompt' may not +be sufficient to handle some prompt, it may still be of benefit +to look at the implementations to gain some insights on how to +implement such functions." + :package-version '(magit . "3.0.0") + :group 'magit-process + :type 'hook) + +(defcustom magit-process-ensure-unix-line-ending t + "Whether Magit should ensure a unix coding system when talking to Git." + :package-version '(magit . "2.6.0") + :group 'magit-process + :type 'boolean) + +(defcustom magit-process-display-mode-line-error t + "Whether Magit should retain and highlight process errors in the mode line." + :package-version '(magit . "2.12.0") + :group 'magit-process + :type 'boolean) + +(defcustom magit-process-timestamp-format nil + "Format of timestamp for each process in the process buffer. +If non-nil, pass this to `format-time-string' when creating a +process section in the process buffer, and insert the returned +string in the heading of its section." + :package-version '(magit . "4.0.0") + :group 'magit-process + :type '(choice (const :tag "none" nil) string)) + +(defvar tramp-pipe-stty-settings) +(defvar magit-tramp-pipe-stty-settings "" + "Override `tramp-pipe-stty-settings' in `magit-start-process'. + +The default for that Tramp variable is \"-icanon min 1 time 0\", +which causes staging of individual hunks to hang. Using \"\" +prevents that, but apparently has other issues, which is why it +isn't the default. + +This variable defaults to \"\" and is used to override the Tramp +variable in `magit-start-process'. This only has an effect when +using Tramp 2.6.2 or greater. This can also be set to `pty', in +which case a pty is used instead of a pipe. That also prevents +the hanging, but doesn't work for files with DOS line endings +\(see #20). + +For connections that have `tramp-direct-async-process' enabled, +staging hunks hangs, unless this variable is set to `pty' (see +#5220). + +To fall back to the value of `tramp-pipe-stty-settings', set this +variable to nil. + +Also see https://github.com/magit/magit/issues/4720 +and https://debbugs.gnu.org/cgi/bugreport.cgi?bug=62093.") + +(defface magit-process-ok + '((t :inherit magit-section-heading :foreground "green")) + "Face for zero exit-status." + :group 'magit-faces) + +(defface magit-process-ng + '((t :inherit magit-section-heading :foreground "red")) + "Face for non-zero exit-status." + :group 'magit-faces) + +(defface magit-mode-line-process + '((t :inherit mode-line-emphasis)) + "Face for `mode-line-process' status when Git is running for side-effects." + :group 'magit-faces) + +(defface magit-mode-line-process-error + '((t :inherit error)) + "Face for `mode-line-process' error status. + +Used when `magit-process-display-mode-line-error' is non-nil." + :group 'magit-faces) + +;;; Process Mode + +(defvar-keymap magit-process-mode-map + :doc "Keymap for `magit-process-mode'." + :parent magit-mode-map + "<remap> <magit-delete-thing>" #'magit-process-kill) + +(define-derived-mode magit-process-mode magit-mode "Magit Process" + "Mode for looking at Git process output." + :interactive nil + :group 'magit-process + (magit-hack-dir-local-variables) + (setq magit--imenu-item-types 'process)) + +(defun magit-process-buffer (&optional nodisplay) + "Display the current repository's process buffer. + +If that buffer doesn't exist yet, then create it. +Non-interactively return the buffer and unless +optional NODISPLAY is non-nil also display it." + (interactive) + (let ((topdir (magit-toplevel))) + (unless topdir + (magit--with-safe-default-directory nil + (setq topdir default-directory) + (let (prev) + (while (not (equal topdir prev)) + (setq prev topdir) + (setq topdir (file-name-directory (directory-file-name topdir))))))) + (let ((buffer (or (--first (with-current-buffer it + (and (eq major-mode 'magit-process-mode) + (equal default-directory topdir))) + (buffer-list)) + (magit-generate-new-buffer 'magit-process-mode + nil topdir)))) + (with-current-buffer buffer + (if magit-root-section + (when magit-process-log-max + (magit-process-truncate-log)) + (magit-process-mode) + (let ((inhibit-read-only t) + (magit-insert-section--parent nil) + (magit-insert-section--oldroot nil)) + (make-local-variable 'text-property-default-nonsticky) + (magit-insert-section (processbuf) + (insert "\n"))))) + (unless nodisplay + (magit-display-buffer buffer)) + buffer))) + +(defun magit-process-kill () + "Kill the process at point." + (interactive) + (when-let ((process (magit-section-value-if 'process))) + (unless (eq (process-status process) 'run) + (user-error "Process isn't running")) + (magit-confirm 'kill-process) + (kill-process process))) + +;;; Synchronous Processes + +(defvar magit-process-raise-error nil) + +(defun magit-git (&rest args) + "Call Git synchronously in a separate process, for side-effects. + +Option `magit-git-executable' specifies the Git executable. +The arguments ARGS specify arguments to Git, they are flattened +before use. + +Process output goes into a new section in the buffer returned by +`magit-process-buffer'. If Git exits with a non-zero status, +then raise an error." + (let ((magit-process-raise-error t)) + (magit-call-git args))) + +(defun magit-run-git (&rest args) + "Call Git synchronously in a separate process, and refresh. + +Function `magit-git-executable' specifies the Git executable and +option `magit-git-global-arguments' specifies constant arguments. +The arguments ARGS specify arguments to Git, they are flattened +before use. + +After Git returns, the current buffer (if it is a Magit buffer) +as well as the current repository's status buffer are refreshed. + +Process output goes into a new section in the buffer returned by +`magit-process-buffer'." + (let ((magit--refresh-cache (list (cons 0 0)))) + (prog1 (magit-call-git args) + (when (member (car args) '("init" "clone")) + ;; Creating a new repository invalidates the cache. + (setq magit--refresh-cache nil)) + (magit-refresh)))) + +(defvar magit-pre-call-git-hook nil) + +(defun magit-call-git (&rest args) + "Call Git synchronously in a separate process. + +Function `magit-git-executable' specifies the Git executable and +option `magit-git-global-arguments' specifies constant arguments. +The arguments ARGS specify arguments to Git, they are flattened +before use. + +Process output goes into a new section in the buffer returned by +`magit-process-buffer'." + (run-hooks 'magit-pre-call-git-hook) + (let ((default-process-coding-system (magit--process-coding-system))) + (apply #'magit-call-process + (magit-git-executable) + (magit-process-git-arguments args)))) + +(defun magit-call-process (program &rest args) + "Call PROGRAM synchronously in a separate process. +Process output goes into a new section in the buffer returned by +`magit-process-buffer'." + (pcase-let ((`(,process-buf . ,section) + (magit-process-setup program args))) + (magit-process-finish + (let ((inhibit-read-only t)) + (apply #'magit-process-file program nil process-buf nil args)) + process-buf (current-buffer) default-directory section))) + +(defun magit-process-git (destination &rest args) + "Call Git synchronously in a separate process, returning its exit code. +DESTINATION specifies how to handle the output, like for +`call-process', except that file handlers are supported. +Enable Cygwin's \"noglob\" option during the call and +ensure unix eol conversion." + (apply #'magit-process-file + (magit-git-executable) + nil destination nil + (magit-process-git-arguments args))) + +(defun magit-process-file (process &optional infile buffer display &rest args) + "Process files synchronously in a separate process. +Identical to `process-file' but temporarily enable Cygwin's +\"noglob\" option during the call and ensure unix eol +conversion." + (when magit-process-extreme-logging + (let ((inhibit-message t)) + (message "$ %s" (magit-process--format-arguments process args)))) + (let ((process-environment (magit-process-environment)) + (default-process-coding-system (magit--process-coding-system))) + (apply #'process-file process infile buffer display args))) + +(defun magit-process-environment () + ;; The various w32 hacks are only applicable when running on the local + ;; machine. A local binding of process-environment different from the + ;; top-level value affects the environment used by Tramp. + (let ((local (not (file-remote-p default-directory)))) + (append magit-git-environment + (and local + (cdr (assoc magit-git-executable magit-git-w32-path-hack))) + (and local magit-need-cygwin-noglob + (mapcar (lambda (var) + (concat var "=" (if-let ((val (getenv var))) + (concat val " noglob") + "noglob"))) + '("CYGWIN" "MSYS"))) + process-environment))) + +(defvar magit-this-process nil) + +(defun magit-run-git-with-input (&rest args) + "Call Git in a separate process. +ARGS is flattened and then used as arguments to Git. + +The current buffer's content is used as the process's standard +input. The buffer is assumed to be temporary and thus OK to +modify. + +Function `magit-git-executable' specifies the Git executable and +option `magit-git-global-arguments' specifies constant arguments. +The remaining arguments ARGS specify arguments to Git, they are +flattened before use." + (when (eq system-type 'windows-nt) + ;; On w32, git expects UTF-8 encoded input, ignore any user + ;; configuration telling us otherwise (see #3250). + (encode-coding-region (point-min) (point-max) 'utf-8-unix)) + (if (file-remote-p default-directory) + ;; We lack `process-file-region', so fall back to asynch + + ;; waiting in remote case. + (progn + (magit-start-git (current-buffer) args) + (while (and magit-this-process + (eq (process-status magit-this-process) 'run)) + (sleep-for 0.005))) + (run-hooks 'magit-pre-call-git-hook) + (pcase-let* ((process-environment (magit-process-environment)) + (default-process-coding-system (magit--process-coding-system)) + (flat-args (magit-process-git-arguments args)) + (`(,process-buf . ,section) + (magit-process-setup (magit-git-executable) flat-args)) + (inhibit-read-only t)) + (magit-process-finish + (apply #'call-process-region (point-min) (point-max) + (magit-git-executable) nil process-buf nil flat-args) + process-buf nil default-directory section)))) + +;;; Asynchronous Processes + +(defun magit-run-git-async (&rest args) + "Start Git, prepare for refresh, and return the process object. +ARGS is flattened and then used as arguments to Git. + +Display the command line arguments in the echo area. + +After Git returns some buffers are refreshed: the buffer that was +current when this function was called (if it is a Magit buffer +and still alive), as well as the respective Magit status buffer. + +See `magit-start-process' for more information." + (message "Running %s %s" (magit-git-executable) + (let ((m (string-join (flatten-tree args) " "))) + (remove-list-of-text-properties 0 (length m) '(face) m) + m)) + (magit-start-git nil args)) + +(defun magit-run-git-with-editor (&rest args) + "Export GIT_EDITOR and start Git. +Also prepare for refresh and return the process object. +ARGS is flattened and then used as arguments to Git. + +Display the command line arguments in the echo area. + +After Git returns some buffers are refreshed: the buffer that was +current when this function was called (if it is a Magit buffer +and still alive), as well as the respective Magit status buffer. + +See `magit-start-process' and `with-editor' for more information." + (magit--record-separated-gitdir) + (magit-with-editor (magit-run-git-async args))) + +(defun magit-run-git-sequencer (&rest args) + "Export GIT_EDITOR and start Git. +Also prepare for refresh and return the process object. +ARGS is flattened and then used as arguments to Git. + +Display the command line arguments in the echo area. + +After Git returns some buffers are refreshed: the buffer that was +current when this function was called (if it is a Magit buffer +and still alive), as well as the respective Magit status buffer. +If the sequence stops at a commit, make the section representing +that commit the current section by moving `point' there. + +See `magit-start-process' and `with-editor' for more information." + (apply #'magit-run-git-with-editor args) + (set-process-sentinel magit-this-process #'magit-sequencer-process-sentinel) + magit-this-process) + +(defvar magit-pre-start-git-hook nil) + +(defun magit-start-git (input &rest args) + "Start Git, prepare for refresh, and return the process object. + +If INPUT is non-nil, it has to be a buffer or the name of an +existing buffer. The buffer content becomes the processes +standard input. + +Function `magit-git-executable' specifies the Git executable and +option `magit-git-global-arguments' specifies constant arguments. +The remaining arguments ARGS specify arguments to Git, they are +flattened before use. + +After Git returns some buffers are refreshed: the buffer that was +current when this function was called (if it is a Magit buffer +and still alive), as well as the respective Magit status buffer. + +See `magit-start-process' for more information." + (run-hooks 'magit-pre-start-git-hook) + (let ((default-process-coding-system (magit--process-coding-system))) + (apply #'magit-start-process (magit-git-executable) input + (magit-process-git-arguments args)))) + +(defun magit-start-process (program &optional input &rest args) + "Start PROGRAM, prepare for refresh, and return the process object. + +If optional argument INPUT is non-nil, it has to be a buffer or +the name of an existing buffer. The buffer content becomes the +processes standard input. + +The process is started using `start-file-process' and then setup +to use the sentinel `magit-process-sentinel' and the filter +`magit-process-filter'. Information required by these functions +is stored in the process object. When this function returns the +process has not started to run yet so it is possible to override +the sentinel and filter. + +After the process returns, `magit-process-sentinel' refreshes the +buffer that was current when `magit-start-process' was called (if +it is a Magit buffer and still alive), as well as the respective +Magit status buffer." + (pcase-let* + ((`(,process-buf . ,section) + (magit-process-setup program args)) + (process + (let ((process-connection-type ;t=pty nil=pipe + (or + ;; With Tramp, maybe force use a pty. #4720 + (and (file-remote-p default-directory) + (eq magit-tramp-pipe-stty-settings 'pty)) + ;; Without input, don't use a pty, because it would + ;; set icrnl, which would modify the input. #20 + (and (not input) magit-process-connection-type))) + (tramp-pipe-stty-settings + (or (and (not (eq magit-tramp-pipe-stty-settings 'pty)) + ;; Defaults to "", to allow staging hunks over + ;; Tramp again. #4720 + magit-tramp-pipe-stty-settings) + tramp-pipe-stty-settings)) + (process-environment (magit-process-environment)) + (default-process-coding-system (magit--process-coding-system))) + (apply #'start-file-process + (file-name-nondirectory program) + process-buf program args)))) + (with-editor-set-process-filter process #'magit-process-filter) + (set-process-sentinel process #'magit-process-sentinel) + (set-process-buffer process process-buf) + (when (eq system-type 'windows-nt) + ;; On w32, git expects UTF-8 encoded input, ignore any user + ;; configuration telling us otherwise. + (set-process-coding-system process nil 'utf-8-unix)) + (process-put process 'section section) + (process-put process 'command-buf (current-buffer)) + (process-put process 'default-dir default-directory) + (when magit-inhibit-refresh + (process-put process 'inhibit-refresh t)) + (oset section process process) + (with-current-buffer process-buf + (set-marker (process-mark process) (point))) + (when input + (with-current-buffer input + (process-send-region process (point-min) (point-max)) + ;; `process-send-eof' appears to be broken over + ;; Tramp from Windows. See #3624 and bug#43226. + (if (and (eq system-type 'windows-nt) + (file-remote-p (process-get process 'default-dir) nil t)) + (process-send-string process "") + (process-send-eof process)))) + (setq magit-this-process process) + (oset section value process) + (magit-process-display-buffer process) + process)) + +(defun magit-parse-git-async (&rest args) + (setq args (magit-process-git-arguments args)) + (let ((command-buf (current-buffer)) + (stdout-buf (generate-new-buffer " *git-stdout*")) + (stderr-buf (generate-new-buffer " *git-stderr*")) + (toplevel (magit-toplevel))) + (with-current-buffer stdout-buf + (setq default-directory toplevel) + (let ((process + (let ((process-environment (magit-process-environment))) + (make-process :name "git" + :buffer stdout-buf + :stderr stderr-buf + :command (cons (magit-git-executable) args) + :coding (magit--process-coding-system) + :file-handler t)))) + (process-put process 'command-buf command-buf) + (process-put process 'stderr-buf stderr-buf) + (process-put process 'parsed (point)) + (setq magit-this-process process) + process)))) + +;;; Process Internals + +(defclass magit-process-section (magit-section) + ((process :initform nil))) + +(setf (alist-get 'process magit--section-type-alist) 'magit-process-section) + +(defun magit-process-setup (program args) + (magit-process-set-mode-line program args) + (let ((pwd default-directory) + (buf (magit-process-buffer t))) + (cons buf (with-current-buffer buf + (prog1 (magit-process-insert-section pwd program args nil nil) + (backward-char 1)))))) + +(defun magit-process-insert-section (pwd program args &optional errcode errlog) + (let ((inhibit-read-only t) + (magit-insert-section--parent magit-root-section) + (magit-insert-section--oldroot nil)) + (goto-char (1- (point-max))) + (magit-insert-section (process) + (insert (if errcode + (format "%3s " (propertize (number-to-string errcode) + 'font-lock-face 'magit-process-ng)) + "run ")) + (when magit-process-timestamp-format + (insert (format-time-string magit-process-timestamp-format) " ")) + (unless (equal (expand-file-name pwd) + (expand-file-name default-directory)) + (insert (file-relative-name pwd default-directory) ?\s)) + (insert (magit-process--format-arguments program args)) + (magit-insert-heading) + (when errlog + (if (bufferp errlog) + (insert (with-current-buffer errlog + (buffer-substring-no-properties (point-min) (point-max)))) + (insert-file-contents errlog) + (goto-char (1- (point-max))))) + (insert "\n")))) + +(defun magit-process--format-arguments (program args) + (cond + ((and args (equal program (magit-git-executable))) + (let ((global (length magit-git-global-arguments))) + (concat + (propertize (file-name-nondirectory program) + 'font-lock-face 'magit-section-heading) + " " + (propertize (magit--ellipsis) + 'font-lock-face 'magit-section-heading + 'help-echo (string-join (seq-take args global) " ")) + " " + (propertize (mapconcat #'shell-quote-argument (seq-drop args global) " ") + 'font-lock-face 'magit-section-heading)))) + ((and args (equal program shell-file-name)) + (propertize (cadr args) + 'font-lock-face 'magit-section-heading)) + (t + (concat (propertize (file-name-nondirectory program) + 'font-lock-face 'magit-section-heading) + " " + (propertize (mapconcat #'shell-quote-argument args " ") + 'font-lock-face 'magit-section-heading))))) + +(defun magit-process-truncate-log () + (let* ((head nil) + (tail (oref magit-root-section children)) + (count (length tail))) + (when (> (1+ count) magit-process-log-max) + (while (and (cdr tail) + (> count (/ magit-process-log-max 2))) + (let* ((inhibit-read-only t) + (section (car tail)) + (process (oref section process))) + (cond ((not process)) + ((memq (process-status process) '(exit signal)) + (delete-region (oref section start) + (1+ (oref section end))) + (cl-decf count)) + (t + (push section head)))) + (pop tail)) + (oset magit-root-section children + (nconc (reverse head) tail))))) + +(defun magit-process-sentinel (process event) + "Default sentinel used by `magit-start-process'." + (when (memq (process-status process) '(exit signal)) + (setq event (substring event 0 -1)) + (when (string-match "^finished" event) + (message (concat (capitalize (process-name process)) " finished"))) + (magit-process-finish process) + (when (eq process magit-this-process) + (setq magit-this-process nil)) + (unless (process-get process 'inhibit-refresh) + (let ((command-buf (process-get process 'command-buf))) + (if (buffer-live-p command-buf) + (with-current-buffer command-buf + (magit-refresh)) + (with-temp-buffer + (setq default-directory (process-get process 'default-dir)) + (magit-refresh))))))) + +(defun magit-sequencer-process-sentinel (process event) + "Special sentinel used by `magit-run-git-sequencer'." + (when (memq (process-status process) '(exit signal)) + (magit-process-sentinel process event) + (when-let* ((process-buf (process-buffer process)) + ((buffer-live-p process-buf)) + (status-buf (with-current-buffer process-buf + (magit-get-mode-buffer 'magit-status-mode)))) + (with-current-buffer status-buf + (when-let ((section + (magit-get-section + `((commit . ,(magit-rev-parse "HEAD")) + (,(pcase (car (seq-drop + (process-command process) + (1+ (length magit-git-global-arguments)))) + ((or "rebase" "am") 'rebase-sequence) + ((or "cherry-pick" "revert") 'sequence))) + (status))))) + (goto-char (oref section start)) + (magit-section-update-highlight)))))) + +(defun magit-process-filter (proc string) + "Default filter used by `magit-start-process'." + (with-current-buffer (process-buffer proc) + (let ((inhibit-read-only t)) + (goto-char (process-mark proc)) + ;; Find last ^M in string. If one was found, ignore + ;; everything before it and delete the current line. + (when-let ((ret-pos (cl-position ?\r string :from-end t))) + (cl-callf substring string (1+ ret-pos)) + (delete-region (line-beginning-position) (point))) + (setq string (magit-process-remove-bogus-errors string)) + (insert (propertize string 'magit-section + (process-get proc 'section))) + (set-marker (process-mark proc) (point)) + ;; Make sure prompts are matched after removing ^M. + (magit-process-yes-or-no-prompt proc string) + (magit-process-username-prompt proc string) + (magit-process-password-prompt proc string) + (run-hook-with-args-until-success 'magit-process-prompt-functions + proc string)))) + +(defun magit-process-make-keymap (process parent) + "Remap `abort-minibuffers' to a command that also kills PROCESS. +PARENT is used as the parent of the returned keymap." + (let ((cmd (lambda () + (interactive) + (ignore-errors (kill-process process)) + (if (fboundp 'abort-minibuffers) + (abort-minibuffers) + (abort-recursive-edit))))) + (define-keymap :parent parent + "C-g" cmd + "<remap> <abort-minibuffers>" cmd + "<remap> <abort-recursive-edit>" cmd))) + +(defmacro magit-process-kill-on-abort (process &rest body) + (declare (indent 1) + (debug (form body)) + (obsolete magit-process-make-keymap "Magit 4.0.0")) + `(let ((minibuffer-local-map + (magit-process-make-keymap ,process minibuffer-local-map))) + ,@body)) + +(defun magit-process-remove-bogus-errors (str) + (save-match-data + (when (string-match "^\\(\\*ERROR\\*: \\)Canceled by user" str) + (setq str (replace-match "" nil nil str 1))) + (when (string-match "^error: There was a problem with the editor.*\n" str) + (setq str (replace-match "" nil nil str))) + (when (string-match + "^Please supply the message using either -m or -F option\\.\n" str) + (setq str (replace-match "" nil nil str)))) + str) + +(defun magit-process-yes-or-no-prompt (process string) + "Forward Yes-or-No prompts to the user." + (when-let ((beg (string-match magit-process-yes-or-no-prompt-regexp string))) + (process-send-string + process + (if (save-match-data + (let ((max-mini-window-height 30) + (minibuffer-local-map + (magit-process-make-keymap process minibuffer-local-map)) + ;; In case yes-or-no-p is fset to that, but does + ;; not cover use-dialog-box-p and y-or-n-p-read-key. + (y-or-n-p-map + (magit-process-make-keymap process y-or-n-p-map))) + (yes-or-no-p (substring string 0 beg)))) + (concat (downcase (match-string 1 string)) "\n") + (concat (downcase (match-string 2 string)) "\n"))))) + +(defun magit-process-password-auth-source (key) + "Use `auth-source-search' to get a password. +If found, return the password. Otherwise, return nil. + +To use this function add it to the appropriate hook + (add-hook \\='magit-process-find-password-functions + \\='magit-process-password-auth-source) + +KEY typically derives from a prompt such as: + Password for \\='https://yourname@github.com\\=' +in which case it would be the string + yourname@github.com +which matches the ~/.authinfo.gpg entry + machine github.com login yourname password 12345 +or iff that is undefined, for backward compatibility + machine yourname@github.com password 12345 + +On github.com you should not use your password but a +personal access token, see [1]. For information about +the peculiarities of other forges, please consult the +respective documentation. + +After manually editing ~/.authinfo.gpg you must reset +the cache using + M-x auth-source-forget-all-cached RET + +The above will save you from having to repeatedly type +your token or password, but you might still repeatedly +be asked for your username. To prevent that, change an +URL like + https://github.com/foo/bar.git +to + https://yourname@github.com/foo/bar.git + +Instead of changing all such URLs manually, they can +be translated on the fly by doing this once + git config --global \ + url.https://yourname@github.com.insteadOf \ + https://github.com + +[1]: https://docs.github.com/en/github/authenticating-to-github/creating-a-personal-access-token." + (require 'auth-source) + (and (fboundp 'auth-source-search) + (string-match "\\`\\(.+\\)@\\([^@]+\\)\\'" key) + (let* ((user (match-string 1 key)) + (host (match-string 2 key)) + (secret + (plist-get + (car (or (auth-source-search :max 1 :host host :user user) + (auth-source-search :max 1 :host key))) + :secret))) + (if (functionp secret) + (funcall secret) + secret)))) + +(defun magit-process-git-credential-manager-core (process string) + "Authenticate using `git-credential-manager-core'. + +To use this function add it to the appropriate hook + (add-hook \\='magit-process-prompt-functions + \\='magit-process-git-credential-manager-core)" + (and (string-match "^option (enter for default): $" string) + (progn + (magit-process-buffer) + (let ((option (format "%c\n" + (read-char-choice "Option: " '(?\r ?\j ?1 ?2))))) + (insert-before-markers-and-inherit option) + (process-send-string process option))))) + +(defun magit-process-password-prompt (process string) + "Find a password based on prompt STRING and send it to git. +Use `magit-process-password-prompt-regexps' to find a known +prompt. If and only if one is found, then call functions in +`magit-process-find-password-functions' until one of them returns +the password. If all functions return nil, then read the password +from the user." + (when-let ((prompt (magit-process-match-prompt + magit-process-password-prompt-regexps string))) + (process-send-string + process + (concat (or (and-let* ((key (match-string 99 string))) + (run-hook-with-args-until-success + 'magit-process-find-password-functions key)) + (let ((read-passwd-map + (magit-process-make-keymap process read-passwd-map))) + (read-passwd prompt))) + "\n")))) + +(defun magit-process-username-prompt (process string) + "Forward username prompts to the user." + (when-let ((prompt (magit-process-match-prompt + magit-process-username-prompt-regexps string))) + (process-send-string + process + (let ((minibuffer-local-map + (magit-process-make-keymap process minibuffer-local-map))) + (concat (read-string prompt nil nil (user-login-name)) "\n"))))) + +(defun magit-process-match-prompt (prompts string) + "Match STRING against PROMPTS and set match data. +Return the matched string suffixed with \": \", if needed." + (when (--any-p (string-match it string) prompts) + (let ((prompt (match-string 0 string))) + (cond ((string-suffix-p ": " prompt) prompt) + ((string-suffix-p ":" prompt) (concat prompt " ")) + (t (concat prompt ": ")))))) + +(defun magit--process-coding-system () + (let ((fro (or magit-git-output-coding-system + (car default-process-coding-system))) + (to (cdr default-process-coding-system))) + (if magit-process-ensure-unix-line-ending + (cons (coding-system-change-eol-conversion fro 'unix) + (coding-system-change-eol-conversion to 'unix)) + (cons fro to)))) + +(defvar magit-credential-hook nil + "Hook run before Git needs credentials.") + +(defvar magit-credential-cache-daemon-process nil) + +(defun magit-maybe-start-credential-cache-daemon () + "Maybe start a `git-credential-cache--daemon' process. + +If such a process is already running or if the value of option +`magit-credential-cache-daemon-socket' is nil, then do nothing. +Otherwise start the process passing the value of that options +as argument." + (unless (or (not magit-credential-cache-daemon-socket) + (process-live-p magit-credential-cache-daemon-process) + (memq magit-credential-cache-daemon-process + (list-system-processes))) + (setq magit-credential-cache-daemon-process + (or (--first (let* ((attr (process-attributes it)) + (comm (cdr (assq 'comm attr))) + (user (cdr (assq 'user attr)))) + (and (string= comm "git-credential-cache--daemon") + (string= user user-login-name))) + (list-system-processes)) + (condition-case nil + (start-process "git-credential-cache--daemon" + " *git-credential-cache--daemon*" + (magit-git-executable) + "credential-cache--daemon" + magit-credential-cache-daemon-socket) + ;; Some Git implementations (e.g., Windows) won't have + ;; this program; if we fail the first time, stop trying. + ((debug error) + (remove-hook 'magit-credential-hook + #'magit-maybe-start-credential-cache-daemon))))))) + +(add-hook 'magit-credential-hook #'magit-maybe-start-credential-cache-daemon) + +(defvar-keymap magit-mode-line-process-map + :doc "Keymap for `mode-line-process'." + "<mode-line> <mouse-1>" 'magit-process-buffer) + +(defun magit-process-set-mode-line (program args) + "Display the git command (sans arguments) in the mode line." + (when (equal program (magit-git-executable)) + (setq args (nthcdr (length magit-git-global-arguments) args))) + (let ((str (concat " " (propertize + (concat (file-name-nondirectory program) + (and args (concat " " (car args)))) + 'mouse-face 'highlight + 'keymap magit-mode-line-process-map + 'help-echo "mouse-1: Show process buffer" + 'font-lock-face 'magit-mode-line-process)))) + (magit-repository-local-set 'mode-line-process str) + (dolist (buf (magit-mode-get-buffers)) + (with-current-buffer buf + (setq mode-line-process str))) + (force-mode-line-update t))) + +(defun magit-process-set-mode-line-error-status (&optional error str) + "Apply an error face to the string set by `magit-process-set-mode-line'. + +If ERROR is supplied, include it in the `mode-line-process' tooltip. + +If STR is supplied, it replaces the `mode-line-process' text." + (setq str (or str (magit-repository-local-get 'mode-line-process))) + (when str + (setq error (format "%smouse-1: Show process buffer" + (if (stringp error) + (concat error "\n\n") + ""))) + (setq str (concat " " (propertize + (substring-no-properties str 1) + 'mouse-face 'highlight + 'keymap magit-mode-line-process-map + 'help-echo error + 'font-lock-face 'magit-mode-line-process-error))) + (magit-repository-local-set 'mode-line-process str) + (dolist (buf (magit-mode-get-buffers)) + (with-current-buffer buf + (setq mode-line-process str))) + (force-mode-line-update t) + ;; We remove any error status from the mode line when a magit + ;; buffer is refreshed (see `magit-refresh-buffer'), but we must + ;; ensure that we ignore any refreshes during the remainder of the + ;; current command -- otherwise a newly-set error status would be + ;; removed before it was seen. We set a flag which prevents the + ;; status from being removed prior to the next command, so that + ;; the error status is guaranteed to remain visible until then. + (let ((repokey (magit-repository-local-repository))) + ;; The following closure captures the repokey value, and is + ;; added to `pre-command-hook'. + (cl-labels ((enable-magit-process-unset-mode-line () + ;; Remove ourself from the hook variable, so + ;; that we only run once. + (remove-hook 'pre-command-hook + #'enable-magit-process-unset-mode-line) + ;; Clear the inhibit flag for the repository in + ;; which we set it. + (magit-repository-local-set + 'inhibit-magit-process-unset-mode-line nil repokey))) + ;; Set the inhibit flag until the next command is invoked. + (magit-repository-local-set + 'inhibit-magit-process-unset-mode-line t repokey) + (add-hook 'pre-command-hook + #'enable-magit-process-unset-mode-line))))) + +(defun magit-process-unset-mode-line-error-status () + "Remove any current error status from the mode line." + (let ((status (or mode-line-process + (magit-repository-local-get 'mode-line-process)))) + (when (and status + (eq (get-text-property 1 'font-lock-face status) + 'magit-mode-line-process-error)) + (magit-process-unset-mode-line)))) + +(add-hook 'magit-refresh-buffer-hook + #'magit-process-unset-mode-line-error-status) + +(defun magit-process-unset-mode-line (&optional directory) + "Remove the git command from the mode line." + (let ((default-directory (or directory default-directory))) + (unless (magit-repository-local-get 'inhibit-magit-process-unset-mode-line) + (magit-repository-local-set 'mode-line-process nil) + (dolist (buf (magit-mode-get-buffers)) + (with-current-buffer buf (setq mode-line-process nil))) + (force-mode-line-update t)))) + +(defvar magit-process-error-message-regexps + (list "^\\*ERROR\\*: Canceled by user$" + "^\\(?:error\\|fatal\\|git\\): \\(.*\\)$" + "^\\(Cannot rebase:.*\\)$")) + +(define-error 'magit-git-error "Git error") + +(defun magit-process-error-summary (process-buf section) + "A one-line error summary from the given SECTION." + (or (and (buffer-live-p process-buf) + (with-current-buffer process-buf + (and (oref section content) + (save-excursion + (goto-char (oref section end)) + (run-hook-wrapped + 'magit-process-error-message-regexps + (lambda (re) + (save-excursion + (and (re-search-backward + re (oref section start) t) + (or (match-string-no-properties 1) + (and (not magit-process-raise-error) + 'suppressed)))))))))) + "Git failed")) + +(defun magit-process-error-tooltip (process-buf section) + "Returns the text from SECTION of the PROCESS-BUF buffer. + +Limited by `magit-process-error-tooltip-max-lines'." + (and (integerp magit-process-error-tooltip-max-lines) + (> magit-process-error-tooltip-max-lines 0) + (buffer-live-p process-buf) + (with-current-buffer process-buf + (save-excursion + (goto-char (or (oref section content) + (oref section start))) + (buffer-substring-no-properties + (point) + (save-excursion + (forward-line magit-process-error-tooltip-max-lines) + (goto-char + (if (> (point) (oref section end)) + (oref section end) + (point))) + ;; Remove any trailing whitespace. + (when (re-search-backward "[^[:space:]\n]" + (oref section start) t) + (forward-char 1)) + (point))))))) + +(defvar-local magit-this-error nil) + +(defvar magit-process-finish-apply-ansi-colors nil) + +(defun magit-process-finish (arg &optional process-buf command-buf + default-dir section) + (unless (integerp arg) + (setq process-buf (process-buffer arg)) + (setq command-buf (process-get arg 'command-buf)) + (setq default-dir (process-get arg 'default-dir)) + (setq section (process-get arg 'section)) + (setq arg (process-exit-status arg))) + (when (fboundp 'dired-uncache) + (dired-uncache default-dir)) + (when (buffer-live-p process-buf) + (with-current-buffer process-buf + (let ((inhibit-read-only t) + (marker (oref section start))) + (goto-char marker) + (save-excursion + (delete-char 3) + (set-marker-insertion-type marker nil) + (insert (propertize (format "%3s" arg) + 'magit-section section + 'font-lock-face (if (= arg 0) + 'magit-process-ok + 'magit-process-ng))) + (set-marker-insertion-type marker t)) + (when magit-process-finish-apply-ansi-colors + (ansi-color-apply-on-region (oref section content) + (oref section end))) + (if (= (oref section end) + (+ (line-end-position) 2)) + (save-excursion + (goto-char (1+ (line-end-position))) + (delete-char -1) + (oset section content nil)) + (when (and (= arg 0) + (not (--any-p (eq (window-buffer it) process-buf) + (window-list)))) + (magit-section-hide section)))))) + (if (= arg 0) + ;; Unset the `mode-line-process' value upon success. + (magit-process-unset-mode-line default-dir) + ;; Otherwise process the error. + (let ((msg (magit-process-error-summary process-buf section))) + ;; Change `mode-line-process' to an error face upon failure. + (if magit-process-display-mode-line-error + (magit-process-set-mode-line-error-status + (or (magit-process-error-tooltip process-buf section) + msg)) + (magit-process-unset-mode-line default-dir)) + ;; Either signal the error, or else display the error summary in + ;; the status buffer and with a message in the echo area. + (cond + (magit-process-raise-error + (signal 'magit-git-error (list (format "%s (in %s)" msg default-dir)))) + ((not (eq msg 'suppressed)) + (when (buffer-live-p process-buf) + (with-current-buffer process-buf + (when-let ((status-buf (magit-get-mode-buffer 'magit-status-mode))) + (with-current-buffer status-buf + (setq magit-this-error msg))))) + (message "%s ... [%s buffer %s for details]" msg + (if-let ((key (and (buffer-live-p command-buf) + (with-current-buffer command-buf + (car (where-is-internal + 'magit-process-buffer)))))) + (format "Hit %s to see" (key-description key)) + "See") + (buffer-name process-buf)))))) + arg) + +(defun magit-process-display-buffer (process) + (when (process-live-p process) + (let ((buf (process-buffer process))) + (cond ((not (buffer-live-p buf))) + ((= magit-process-popup-time 0) + (if (minibufferp) + (switch-to-buffer-other-window buf) + (pop-to-buffer buf))) + ((> magit-process-popup-time 0) + (run-with-timer magit-process-popup-time nil + (lambda (p) + (when (eq (process-status p) 'run) + (let ((buf (process-buffer p))) + (when (buffer-live-p buf) + (if (minibufferp) + (switch-to-buffer-other-window buf) + (pop-to-buffer buf)))))) + process)))))) + +(defun magit--log-action (summary line list) + (let (heading lines) + (if (cdr list) + (progn (setq heading (funcall summary list)) + (setq lines (mapcar line list))) + (setq heading (funcall line (car list)))) + (with-current-buffer (magit-process-buffer t) + (goto-char (1- (point-max))) + (let ((inhibit-read-only t)) + (magit-insert-section (message) + (magit-insert-heading (concat " * " heading)) + (when lines + (dolist (line lines) + (insert line "\n")) + (insert "\n")))) + (let ((inhibit-message t)) + (when heading + (setq lines (cons heading lines))) + (message (string-join lines "\n")))))) + +;;; _ +(provide 'magit-process) +;;; magit-process.el ends here diff --git a/emacs/elpa/magit-20241004.917/magit-pull.el b/emacs/elpa/magit-20241004.917/magit-pull.el @@ -0,0 +1,166 @@ +;;; magit-pull.el --- Update local objects and refs -*- lexical-binding:t -*- + +;; Copyright (C) 2008-2024 The Magit Project Contributors + +;; Author: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> +;; Maintainer: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> + +;; SPDX-License-Identifier: GPL-3.0-or-later + +;; Magit is free software: you can redistribute it and/or modify it +;; under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. +;; +;; Magit is distributed in the hope that it will be useful, but WITHOUT +;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +;; or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public +;; License for more details. +;; +;; You should have received a copy of the GNU General Public License +;; along with Magit. If not, see <https://www.gnu.org/licenses/>. + +;;; Commentary: + +;; This library implements pull commands. + +;;; Code: + +(require 'magit) + +;;; Options + +(defcustom magit-pull-or-fetch nil + "Whether `magit-pull' also offers some fetch suffixes." + :package-version '(magit . "3.0.0") + :group 'magit-commands + :type 'boolean) + +;;; Commands + +;;;###autoload (autoload 'magit-pull "magit-pull" nil t) +(transient-define-prefix magit-pull () + "Pull from another repository." + :man-page "git-pull" + :incompatible '(("--ff-only" "--rebase")) + [:description + (lambda () (if magit-pull-or-fetch "Pull arguments" "Arguments")) + ("-f" "Fast-forward only" "--ff-only") + ("-r" "Rebase local commits" ("-r" "--rebase")) + ("-A" "Autostash" "--autostash" :level 7) + ("-F" "Force" ("-f" "--force"))] + [:description + (lambda () + (if-let ((branch (magit-get-current-branch))) + (concat + (propertize "Pull into " 'face 'transient-heading) + (propertize branch 'face 'magit-branch-local) + (propertize " from" 'face 'transient-heading)) + (propertize "Pull from" 'face 'transient-heading))) + ("p" magit-pull-from-pushremote) + ("u" magit-pull-from-upstream) + ("e" "elsewhere" magit-pull-branch)] + ["Fetch from" + :if-non-nil magit-pull-or-fetch + ("f" "remotes" magit-fetch-all-no-prune) + ("F" "remotes and prune" magit-fetch-all-prune)] + ["Fetch" + :if-non-nil magit-pull-or-fetch + ("o" "another branch" magit-fetch-branch) + ("s" "explicit refspec" magit-fetch-refspec) + ("m" "submodules" magit-fetch-modules)] + ["Configure" + ("r" magit-branch.<branch>.rebase :if magit-get-current-branch) + ("C" "variables..." magit-branch-configure)] + (interactive) + (transient-setup 'magit-pull nil nil :scope (magit-get-current-branch))) + +(defun magit-pull-arguments () + (transient-args 'magit-pull)) + +;;;###autoload (autoload 'magit-pull-from-pushremote "magit-pull" nil t) +(transient-define-suffix magit-pull-from-pushremote (args) + "Pull from the push-remote of the current branch. + +With a prefix argument or when the push-remote is either not +configured or unusable, then let the user first configure the +push-remote." + :if #'magit-get-current-branch + :description #'magit-pull--pushbranch-description + (interactive (list (magit-pull-arguments))) + (pcase-let ((`(,branch ,remote) + (magit--select-push-remote "pull from there"))) + (run-hooks 'magit-credential-hook) + (magit-run-git-with-editor "pull" args remote branch))) + +(defun magit-pull--pushbranch-description () + ;; Also used by `magit-rebase-onto-pushremote'. + (let* ((branch (magit-get-current-branch)) + (target (magit-get-push-branch branch t)) + (remote (magit-get-push-remote branch)) + (v (magit--push-remote-variable branch t))) + (cond + (target) + ((member remote (magit-list-remotes)) + (format "%s, replacing non-existent" v)) + (remote + (format "%s, replacing invalid" v)) + (t + (format "%s, setting that" v))))) + +;;;###autoload (autoload 'magit-pull-from-upstream "magit-pull" nil t) +(transient-define-suffix magit-pull-from-upstream (args) + "Pull from the upstream of the current branch. + +With a prefix argument or when the upstream is either not +configured or unusable, then let the user first configure +the upstream." + :if #'magit-get-current-branch + :description #'magit-pull--upstream-description + (interactive (list (magit-pull-arguments))) + (let* ((branch (or (magit-get-current-branch) + (user-error "No branch is checked out"))) + (remote (magit-get "branch" branch "remote")) + (merge (magit-get "branch" branch "merge"))) + (when (or current-prefix-arg + (not (or (magit-get-upstream-branch branch) + (magit--unnamed-upstream-p remote merge)))) + (magit-set-upstream-branch + branch (magit-read-upstream-branch + branch (format "Set upstream of %s and pull from there" branch))) + (setq remote (magit-get "branch" branch "remote")) + (setq merge (magit-get "branch" branch "merge"))) + (run-hooks 'magit-credential-hook) + (magit-run-git-with-editor "pull" args remote merge))) + +(defun magit-pull--upstream-description () + (and-let* ((branch (magit-get-current-branch))) + (or (magit-get-upstream-branch branch) + (let ((remote (magit-get "branch" branch "remote")) + (merge (magit-get "branch" branch "merge")) + (u (magit--propertize-face "@{upstream}" 'bold))) + (cond + ((magit--unnamed-upstream-p remote merge) + (format "%s of %s" + (magit--propertize-face merge 'magit-branch-remote) + (magit--propertize-face remote 'bold))) + ((magit--valid-upstream-p remote merge) + (concat u ", replacing non-existent")) + ((or remote merge) + (concat u ", replacing invalid")) + (t + (concat u ", setting that"))))))) + +;;;###autoload +(defun magit-pull-branch (source args) + "Pull from a branch read in the minibuffer." + (interactive (list (magit-read-remote-branch "Pull" nil nil nil t) + (magit-pull-arguments))) + (run-hooks 'magit-credential-hook) + (pcase-let ((`(,remote . ,branch) + (magit-get-tracked source))) + (magit-run-git-with-editor "pull" args remote branch))) + +;;; _ +(provide 'magit-pull) +;;; magit-pull.el ends here diff --git a/emacs/elpa/magit-20241004.917/magit-push.el b/emacs/elpa/magit-20241004.917/magit-push.el @@ -0,0 +1,373 @@ +;;; magit-push.el --- Update remote objects and refs -*- lexical-binding:t -*- + +;; Copyright (C) 2008-2024 The Magit Project Contributors + +;; Author: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> +;; Maintainer: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> + +;; SPDX-License-Identifier: GPL-3.0-or-later + +;; Magit is free software: you can redistribute it and/or modify it +;; under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. +;; +;; Magit is distributed in the hope that it will be useful, but WITHOUT +;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +;; or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public +;; License for more details. +;; +;; You should have received a copy of the GNU General Public License +;; along with Magit. If not, see <https://www.gnu.org/licenses/>. + +;;; Commentary: + +;; This library implements push commands. + +;;; Code: + +(require 'magit) + +;;; Commands + +;;;###autoload (autoload 'magit-push "magit-push" nil t) +(transient-define-prefix magit-push () + "Push to another repository." + :man-page "git-push" + ["Arguments" + ("-f" "Force with lease" (nil "--force-with-lease")) + ("-F" "Force" ("-f" "--force")) + ("-h" "Disable hooks" "--no-verify") + ("-n" "Dry run" ("-n" "--dry-run")) + (5 "-u" "Set upstream" "--set-upstream") + (7 "-t" "Follow tags" "--follow-tags")] + [:if magit-get-current-branch + :description (lambda () + (format (propertize "Push %s to" 'face 'transient-heading) + (propertize (magit-get-current-branch) + 'face 'magit-branch-local))) + ("p" magit-push-current-to-pushremote) + ("u" magit-push-current-to-upstream) + ("e" "elsewhere" magit-push-current)] + ["Push" + [("o" "another branch" magit-push-other) + ("r" "explicit refspecs" magit-push-refspecs) + ("m" "matching branches" magit-push-matching)] + [("T" "a tag" magit-push-tag) + ("t" "all tags" magit-push-tags) + (6 "n" "a note ref" magit-push-notes-ref)]] + ["Configure" + ("C" "Set variables..." magit-branch-configure)]) + +(defun magit-push-arguments () + (transient-args 'magit-push)) + +(defun magit-git-push (branch target args) + (run-hooks 'magit-credential-hook) + ;; If the remote branch already exists, then we do not have to + ;; qualify the target, which we prefer to avoid doing because + ;; using the default namespace is wrong in obscure cases. + (pcase-let ((namespace (if (magit-get-tracked target) "" "refs/heads/")) + (`(,remote . ,target) + (magit-split-branch-name target))) + (magit-run-git-async "push" "-v" args remote + (format "%s:%s%s" branch namespace target)))) + +;;;###autoload (autoload 'magit-push-current-to-pushremote "magit-push" nil t) +(transient-define-suffix magit-push-current-to-pushremote (args) + "Push the current branch to its push-remote. + +When the push-remote is not configured, then read the push-remote +from the user, set it, and then push to it. With a prefix +argument the push-remote can be changed before pushed to it." + :if #'magit-get-current-branch + :description #'magit-push--pushbranch-description + (interactive (list (magit-push-arguments))) + (pcase-let ((`(,branch ,remote ,changed) + (magit--select-push-remote "push there"))) + (when changed + (magit-confirm 'set-and-push + (list "Really use \"%s\" as push-remote and push \"%s\" there" + remote branch))) + (run-hooks 'magit-credential-hook) + (magit-run-git-async "push" "-v" args remote + (format "refs/heads/%s:refs/heads/%s" + branch branch)))) ; see #3847 and #3872 + +(defun magit-push--pushbranch-description () + (let* ((branch (magit-get-current-branch)) + (target (magit-get-push-branch branch t)) + (remote (magit-get-push-remote branch)) + (v (magit--push-remote-variable branch t))) + (cond + (target) + ((member remote (magit-list-remotes)) + (format "%s, creating it" + (magit--propertize-face (concat remote "/" branch) + 'magit-branch-remote))) + (remote + (format "%s, replacing invalid" v)) + (t + (format "%s, setting that" v))))) + +;;;###autoload (autoload 'magit-push-current-to-upstream "magit-push" nil t) +(transient-define-suffix magit-push-current-to-upstream (args) + "Push the current branch to its upstream branch. + +With a prefix argument or when the upstream is either not +configured or unusable, then let the user first configure +the upstream." + :if #'magit-get-current-branch + :description #'magit-push--upstream-description + (interactive (list (magit-push-arguments))) + (let* ((branch (or (magit-get-current-branch) + (user-error "No branch is checked out"))) + (remote (magit-get "branch" branch "remote")) + (merge (magit-get "branch" branch "merge"))) + (when (or current-prefix-arg + (not (or (magit-get-upstream-branch branch) + (magit--unnamed-upstream-p remote merge) + (magit--valid-upstream-p remote merge)))) + (let* ((branches (cl-union (--map (concat it "/" branch) + (magit-list-remotes)) + (magit-list-remote-branch-names) + :test #'equal)) + (upstream (magit-completing-read + (format "Set upstream of %s and push there" branch) + branches nil nil nil 'magit-revision-history + (or (car (member (magit-remote-branch-at-point) branches)) + (car (member "origin/master" branches))))) + (upstream* (or (magit-get-tracked upstream) + (magit-split-branch-name upstream)))) + (setq remote (car upstream*)) + (setq merge (cdr upstream*)) + (unless (string-prefix-p "refs/" merge) + ;; User selected a non-existent remote-tracking branch. + ;; It is very likely, but not certain, that this is the + ;; correct thing to do. It is even more likely that it + ;; is what the user wants to happen. + (setq merge (concat "refs/heads/" merge))) + (magit-confirm 'set-and-push + (list "Really use \"%s\" as upstream and push \"%s\" there" + upstream branch))) + (cl-pushnew "--set-upstream" args :test #'equal)) + (run-hooks 'magit-credential-hook) + (magit-run-git-async "push" "-v" args remote (concat branch ":" merge)))) + +(defun magit-push--upstream-description () + (and-let* ((branch (magit-get-current-branch))) + (or (magit-get-upstream-branch branch) + (let ((remote (magit-get "branch" branch "remote")) + (merge (magit-get "branch" branch "merge")) + (u (magit--propertize-face "@{upstream}" 'bold))) + (cond + ((magit--unnamed-upstream-p remote merge) + (format "%s as %s" + (magit--propertize-face remote 'bold) + (magit--propertize-face merge 'magit-branch-remote))) + ((magit--valid-upstream-p remote merge) + (format "%s creating %s" + (magit--propertize-face remote 'magit-branch-remote) + (magit--propertize-face merge 'magit-branch-remote))) + ((or remote merge) + (concat u ", creating it and replacing invalid")) + (t + (concat u ", creating it"))))))) + +;;;###autoload +(defun magit-push-current (target args) + "Push the current branch to a branch read in the minibuffer." + (interactive + (if-let ((current (magit-get-current-branch))) + (list (magit-read-remote-branch (format "Push %s to" current) + nil nil current 'confirm) + (magit-push-arguments)) + (user-error "No branch is checked out"))) + (magit-git-push (magit-get-current-branch) target args)) + +;;;###autoload +(defun magit-push-other (source target args) + "Push an arbitrary branch or commit somewhere. +Both the source and the target are read in the minibuffer." + (interactive + (let ((source (magit-read-local-branch-or-commit "Push"))) + (list source + (magit-read-remote-branch + (format "Push %s to" source) nil + (if (magit-local-branch-p source) + (or (magit-get-push-branch source) + (magit-get-upstream-branch source)) + (and (magit-rev-ancestor-p source "HEAD") + (or (magit-get-push-branch) + (magit-get-upstream-branch)))) + source 'confirm) + (magit-push-arguments)))) + (magit-git-push source target args)) + +(defvar magit-push-refspecs-history nil) + +;;;###autoload +(defun magit-push-refspecs (remote refspecs args) + "Push one or multiple REFSPECS to a REMOTE. +Both the REMOTE and the REFSPECS are read in the minibuffer. To +use multiple REFSPECS, separate them with commas. Completion is +only available for the part before the colon, or when no colon +is used." + (interactive + (list (magit-read-remote "Push to remote") + (magit-completing-read-multiple + "Push refspec,s: " + (cons "HEAD" (magit-list-local-branch-names)) + nil nil nil 'magit-push-refspecs-history) + (magit-push-arguments))) + (run-hooks 'magit-credential-hook) + (magit-run-git-async "push" "-v" args remote refspecs)) + +;;;###autoload +(defun magit-push-matching (remote &optional args) + "Push all matching branches to another repository. +If multiple remotes exist, then read one from the user. +If just one exists, use that without requiring confirmation." + (interactive (list (magit-read-remote "Push matching branches to" nil t) + (magit-push-arguments))) + (run-hooks 'magit-credential-hook) + (magit-run-git-async "push" "-v" args remote ":")) + +;;;###autoload +(defun magit-push-tags (remote &optional args) + "Push all tags to another repository. +If only one remote exists, then push to that. Otherwise prompt +for a remote, offering the remote configured for the current +branch as default." + (interactive (list (magit-read-remote "Push tags to remote" nil t) + (magit-push-arguments))) + (run-hooks 'magit-credential-hook) + (magit-run-git-async "push" remote "--tags" args)) + +;;;###autoload +(defun magit-push-tag (tag remote &optional args) + "Push a tag to another repository." + (interactive + (let ((tag (magit-read-tag "Push tag"))) + (list tag (magit-read-remote (format "Push %s to remote" tag) nil t) + (magit-push-arguments)))) + (run-hooks 'magit-credential-hook) + (magit-run-git-async "push" remote tag args)) + +;;;###autoload +(defun magit-push-notes-ref (ref remote &optional args) + "Push a notes ref to another repository." + (interactive + (let ((note (magit-notes-read-ref "Push notes" nil nil))) + (list note + (magit-read-remote (format "Push %s to remote" note) nil t) + (magit-push-arguments)))) + (run-hooks 'magit-credential-hook) + (magit-run-git-async "push" remote ref args)) + +;;;###autoload (autoload 'magit-push-implicitly "magit-push" nil t) +(transient-define-suffix magit-push-implicitly (args) + "Push somewhere without using an explicit refspec. + +This command simply runs \"git push -v [ARGS]\". ARGS are the +arguments specified in the popup buffer. No explicit refspec +arguments are used. Instead the behavior depends on at least +these Git variables: `push.default', `remote.pushDefault', +`branch.<branch>.pushRemote', `branch.<branch>.remote', +`branch.<branch>.merge', and `remote.<remote>.push'. + +If you add this suffix to a transient prefix without explicitly +specifying the description, then an attempt is made to predict +what this command will do. To add it use something like: + + (transient-insert-suffix \\='magit-push \"o\" + \\='(\"i\" magit-push-implicitly))" + :description #'magit-push-implicitly--desc + (interactive (list (magit-push-arguments))) + (run-hooks 'magit-credential-hook) + (magit-run-git-async "push" "-v" args)) + +(defun magit-push-implicitly--desc () + ;; This implements the logic for git push as documented. + ;; First, we resolve a remote to use based on various remote and + ;; pushRemote options. + ;; Then, we resolve the refspec to use for the remote based on push + ;; and pushDefault options. + ;; Note that the remote and refspec to push are handled separately, + ;; so it doesn't make sense to talk about "pushing to upstream". + ;; Depending on the options, you could end up pushing to the + ;; "upstream" remote but not the "upstream" branch, and vice versa. + (let* ((branch (magit-get-current-branch)) + (remote (or (magit-get-push-remote branch) + ;; Note: Avoid `magit-get-remote' because it + ;; filters out the local repo case ("."). + (magit-get "branch" branch "remote") + (let ((remotes (magit-list-remotes))) + (cond + ((and (magit-git-version>= "2.27") + (= (length remotes) 1)) + (car remotes)) + ((member "origin" remotes) "origin")))))) + (if (null remote) + "nothing (no remote)" + (let ((refspec (magit-get "remote" remote "push"))) + (if refspec + (format "to %s with refspecs %s" + (magit--propertize-face remote 'bold) + (magit--propertize-face refspec 'bold)) + (pcase (or (magit-get "push.default") "simple") + ("nothing" "nothing (due to push.default)") + ((or "current" "simple") + (format "%s to %s" + (magit--propertize-face branch 'magit-branch-current) + (magit--propertize-face (format "%s/%s" remote branch) + 'magit-branch-remote))) + ((or "upstream" "tracking") + (let ((ref (magit-get "branch" branch "merge"))) + (if ref + (format "%s to %s" + (magit--propertize-face branch 'magit-branch-current) + (cond + ((string-prefix-p "refs/heads/" ref) + (magit--propertize-face + (format "%s/%s" remote + (substring ref (length "refs/heads/"))) + 'magit-branch-remote)) + ((not (string-match "/" ref)) + (magit--propertize-face (format "%s/%s" remote ref) + 'magit-branch-remote)) + ((format "%s as %s" + (magit--propertize-face remote 'bold) + (magit--propertize-face ref 'bold))))) + "nothing (no upstream)"))) + ("matching" (format "all matching to %s" + (magit--propertize-face remote 'bold))))))))) + +;;;###autoload (autoload 'magit-push-to-remote "magit-push" nil t) +(transient-define-suffix magit-push-to-remote (remote args) + "Push to REMOTE without using an explicit refspec. +The REMOTE is read in the minibuffer. + +This command simply runs \"git push -v [ARGS] REMOTE\". ARGS +are the arguments specified in the popup buffer. No refspec +arguments are used. Instead the behavior depends on at least +these Git variables: `push.default', `remote.pushDefault', +`branch.<branch>.pushRemote', `branch.<branch>.remote', +`branch.<branch>.merge', and `remote.<remote>.push'. + +You can add this command as a suffix using something like: + + (transient-insert-suffix \\='magit-push \"o\" + \\='(\"x\" magit-push-to-remote))" + :description #'magit-push-to-remote--desc + (interactive (list (magit-read-remote "Push to remote") + (magit-push-arguments))) + (run-hooks 'magit-credential-hook) + (magit-run-git-async "push" "-v" args remote)) + +(defun magit-push-to-remote--desc () + (format "using %s" (magit--propertize-face "git push <remote>" 'bold))) + +;;; _ +(provide 'magit-push) +;;; magit-push.el ends here diff --git a/emacs/elpa/magit-20241004.917/magit-reflog.el b/emacs/elpa/magit-20241004.917/magit-reflog.el @@ -0,0 +1,208 @@ +;;; magit-reflog.el --- Inspect ref history -*- lexical-binding:t -*- + +;; Copyright (C) 2008-2024 The Magit Project Contributors + +;; Author: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> +;; Maintainer: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> + +;; SPDX-License-Identifier: GPL-3.0-or-later + +;; Magit is free software: you can redistribute it and/or modify it +;; under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. +;; +;; Magit is distributed in the hope that it will be useful, but WITHOUT +;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +;; or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public +;; License for more details. +;; +;; You should have received a copy of the GNU General Public License +;; along with Magit. If not, see <https://www.gnu.org/licenses/>. + +;;; Commentary: + +;; This library implements support for looking at Git reflogs. + +;;; Code: + +(require 'magit-core) +(require 'magit-log) + +;;; Options + +(defcustom magit-reflog-limit 256 + "Maximal number of entries initially shown in reflog buffers. +The limit in the current buffer can be changed using \"+\" +and \"-\"." + :package-version '(magit . "3.0.0") + :group 'magit-commands + :type 'number) + +(defcustom magit-reflog-margin + (list (nth 0 magit-log-margin) + (nth 1 magit-log-margin) + 'magit-log-margin-width nil + (nth 4 magit-log-margin)) + "Format of the margin in `magit-reflog-mode' buffers. + +The value has the form (INIT STYLE WIDTH AUTHOR AUTHOR-WIDTH). + +If INIT is non-nil, then the margin is shown initially. +STYLE controls how to format the author or committer date. + It can be one of `age' (to show the age of the commit), + `age-abbreviated' (to abbreviate the time unit to a character), + or a string (suitable for `format-time-string') to show the + actual date. Option `magit-log-margin-show-committer-date' + controls which date is being displayed. +WIDTH controls the width of the margin. This exists for forward + compatibility and currently the value should not be changed. +AUTHOR controls whether the name of the author is also shown by + default. +AUTHOR-WIDTH has to be an integer. When the name of the author + is shown, then this specifies how much space is used to do so." + :package-version '(magit . "2.9.0") + :group 'magit-log + :group 'magit-margin + :type magit-log-margin--custom-type + :initialize #'magit-custom-initialize-reset + :set-after '(magit-log-margin) + :set (apply-partially #'magit-margin-set-variable 'magit-reflog-mode)) + +;;; Faces + +(defface magit-reflog-commit '((t :foreground "green")) + "Face for commit commands in reflogs." + :group 'magit-faces) + +(defface magit-reflog-amend '((t :foreground "magenta")) + "Face for amend commands in reflogs." + :group 'magit-faces) + +(defface magit-reflog-merge '((t :foreground "green")) + "Face for merge, checkout and branch commands in reflogs." + :group 'magit-faces) + +(defface magit-reflog-checkout '((t :foreground "blue")) + "Face for checkout commands in reflogs." + :group 'magit-faces) + +(defface magit-reflog-reset '((t :foreground "red")) + "Face for reset commands in reflogs." + :group 'magit-faces) + +(defface magit-reflog-rebase '((t :foreground "magenta")) + "Face for rebase commands in reflogs." + :group 'magit-faces) + +(defface magit-reflog-cherry-pick '((t :foreground "green")) + "Face for cherry-pick commands in reflogs." + :group 'magit-faces) + +(defface magit-reflog-remote '((t :foreground "cyan")) + "Face for pull and clone commands in reflogs." + :group 'magit-faces) + +(defface magit-reflog-other '((t :foreground "cyan")) + "Face for other commands in reflogs." + :group 'magit-faces) + +;;; Commands + +;;;###autoload +(defun magit-reflog-current () + "Display the reflog of the current branch. +If `HEAD' is detached, then show the reflog for that instead." + (interactive) + (magit-reflog-setup-buffer (or (magit-get-current-branch) "HEAD"))) + +;;;###autoload +(defun magit-reflog-other (ref) + "Display the reflog of a branch or another ref." + (interactive (list (magit-read-local-branch-or-ref "Show reflog for"))) + (magit-reflog-setup-buffer ref)) + +;;;###autoload +(defun magit-reflog-head () + "Display the `HEAD' reflog." + (interactive) + (magit-reflog-setup-buffer "HEAD")) + +;;; Mode + +(defvar-keymap magit-reflog-mode-map + :doc "Keymap for `magit-reflog-mode'." + :parent magit-log-mode-map + "C-c C-n" #'undefined + "L" #'magit-margin-settings) + +(define-derived-mode magit-reflog-mode magit-mode "Magit Reflog" + "Mode for looking at Git reflog. + +This mode is documented in info node `(magit)Reflog'. + +\\<magit-mode-map>\ +Type \\[magit-refresh] to refresh the current buffer. +Type \\[magit-visit-thing] or \\[magit-diff-show-or-scroll-up] \ +to visit the commit at point. + +Type \\[magit-cherry-pick] to apply the commit at point. +Type \\[magit-reset] to reset `HEAD' to the commit at point. + +\\{magit-reflog-mode-map}" + :interactive nil + :group 'magit-log + (magit-hack-dir-local-variables) + (setq magit--imenu-item-types 'commit)) + +(defun magit-reflog-setup-buffer (ref) + (require 'magit) + (magit-setup-buffer #'magit-reflog-mode nil + (magit-buffer-refname ref) + (magit-buffer-log-args (list (format "-n%s" magit-reflog-limit))))) + +(defun magit-reflog-refresh-buffer () + (magit-set-header-line-format (concat "Reflog for " magit-buffer-refname)) + (magit-insert-section (reflogbuf) + (magit-git-wash (apply-partially #'magit-log-wash-log 'reflog) + "reflog" "show" "--format=%h%x00%aN%x00%gd%x00%gs" "--date=raw" + magit-buffer-log-args magit-buffer-refname "--"))) + +(cl-defmethod magit-buffer-value (&context (major-mode magit-reflog-mode)) + magit-buffer-refname) + +(defvar magit-reflog-labels + '(("commit" . magit-reflog-commit) + ("amend" . magit-reflog-amend) + ("merge" . magit-reflog-merge) + ("checkout" . magit-reflog-checkout) + ("branch" . magit-reflog-checkout) + ("reset" . magit-reflog-reset) + ("rebase" . magit-reflog-rebase) + ("rewritten" . magit-reflog-rebase) + ("cherry-pick" . magit-reflog-cherry-pick) + ("initial" . magit-reflog-commit) + ("pull" . magit-reflog-remote) + ("clone" . magit-reflog-remote) + ("autosave" . magit-reflog-commit) + ("restart" . magit-reflog-reset))) + +(defun magit-reflog-format-subject (subject) + (let* ((match (string-match magit-reflog-subject-re subject)) + (command (and match (match-string 1 subject))) + (option (and match (match-string 2 subject))) + (type (and match (match-string 3 subject))) + (label (if (string= command "commit") + (or type command) + command)) + (text (if (string= command "commit") + label + (string-join (delq nil (list command option type)) " ")))) + (format "%-16s " + (magit--propertize-face + text (or (cdr (assoc label magit-reflog-labels)) + 'magit-reflog-other))))) + +;;; _ +(provide 'magit-reflog) +;;; magit-reflog.el ends here diff --git a/emacs/elpa/magit-20241004.917/magit-refs.el b/emacs/elpa/magit-20241004.917/magit-refs.el @@ -0,0 +1,790 @@ +;;; magit-refs.el --- Listing references -*- lexical-binding:t -*- + +;; Copyright (C) 2008-2024 The Magit Project Contributors + +;; Author: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> +;; Maintainer: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> + +;; SPDX-License-Identifier: GPL-3.0-or-later + +;; Magit is free software: you can redistribute it and/or modify it +;; under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. +;; +;; Magit is distributed in the hope that it will be useful, but WITHOUT +;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +;; or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public +;; License for more details. +;; +;; You should have received a copy of the GNU General Public License +;; along with Magit. If not, see <https://www.gnu.org/licenses/>. + +;;; Commentary: + +;; This library implements support for listing references in a buffer. + +;;; Code: + +(require 'magit) + +;;; Options + +(defgroup magit-refs nil + "Inspect and manipulate Git branches and tags." + :link '(info-link "(magit)References Buffer") + :group 'magit-modes) + +(defcustom magit-refs-mode-hook nil + "Hook run after entering Magit-Refs mode." + :package-version '(magit . "2.1.0") + :group 'magit-refs + :type 'hook) + +(defcustom magit-refs-sections-hook + '(magit-insert-error-header + magit-insert-branch-description + magit-insert-local-branches + magit-insert-remote-branches + magit-insert-tags) + "Hook run to insert sections into a references buffer." + :package-version '(magit . "2.1.0") + :group 'magit-refs + :type 'hook) + +(defcustom magit-refs-show-commit-count nil + "Whether to show commit counts in Magit-Refs mode buffers. + +all Show counts for branches and tags. +branch Show counts for branches only. +nil Never show counts. + +To change the value in an existing buffer use the command +`magit-refs-set-show-commit-count'." + :package-version '(magit . "2.1.0") + :group 'magit-refs + :safe (lambda (val) (memq val '(all branch nil))) + :type '(choice (const :tag "For branches and tags" all) + (const :tag "For branches only" branch) + (const :tag "Never" nil))) +(put 'magit-refs-show-commit-count 'safe-local-variable 'symbolp) +(put 'magit-refs-show-commit-count 'permanent-local t) + +(defcustom magit-refs-pad-commit-counts nil + "Whether to pad all counts on all sides in `magit-refs-mode' buffers. + +If this is nil, then some commit counts are displayed right next +to one of the branches that appear next to the count, without any +space in between. This might look bad if the branch name faces +look too similar to `magit-dimmed'. + +If this is non-nil, then spaces are placed on both sides of all +commit counts." + :package-version '(magit . "2.12.0") + :group 'magit-refs + :type 'boolean) + +(defvar magit-refs-show-push-remote nil + "Whether to show the push-remotes of local branches. +Also show the commits that the local branch is ahead and behind +the push-target. Unfortunately there is a bug in Git that makes +this useless (the commits ahead and behind the upstream are +shown), so this isn't enabled yet.") + +(defcustom magit-refs-show-remote-prefix nil + "Whether to show the remote prefix in lists of remote branches. + +This is redundant because the name of the remote is already shown +in the heading preceding the list of its branches." + :package-version '(magit . "2.12.0") + :group 'magit-refs + :type 'boolean) + +(defcustom magit-refs-margin + (list nil + (nth 1 magit-log-margin) + 'magit-log-margin-width nil + (nth 4 magit-log-margin)) + "Format of the margin in `magit-refs-mode' buffers. + +The value has the form (INIT STYLE WIDTH AUTHOR AUTHOR-WIDTH). + +If INIT is non-nil, then the margin is shown initially. +STYLE controls how to format the author or committer date. + It can be one of `age' (to show the age of the commit), + `age-abbreviated' (to abbreviate the time unit to a character), + or a string (suitable for `format-time-string') to show the + actual date. Option `magit-log-margin-show-committer-date' + controls which date is being displayed. +WIDTH controls the width of the margin. This exists for forward + compatibility and currently the value should not be changed. +AUTHOR controls whether the name of the author is also shown by + default. +AUTHOR-WIDTH has to be an integer. When the name of the author + is shown, then this specifies how much space is used to do so." + :package-version '(magit . "2.9.0") + :group 'magit-refs + :group 'magit-margin + :safe (lambda (val) (memq val '(all branch nil))) + :type magit-log-margin--custom-type + :initialize #'magit-custom-initialize-reset + :set-after '(magit-log-margin) + :set (apply-partially #'magit-margin-set-variable 'magit-refs-mode)) + +(defcustom magit-refs-margin-for-tags nil + "Whether to show information about tags in the margin. + +This is disabled by default because it is slow if there are many +tags." + :package-version '(magit . "2.9.0") + :group 'magit-refs + :group 'magit-margin + :type 'boolean) + +(defcustom magit-refs-primary-column-width (cons 16 32) + "Width of the focus column in `magit-refs-mode' buffers. + +The primary column is the column that contains the name of the +branch that the current row is about. + +If this is an integer, then the column is that many columns wide. +Otherwise it has to be a cons-cell of two integers. The first +specifies the minimal width, the second the maximal width. In that +case the actual width is determined using the length of the names +of the shown local branches. (Remote branches and tags are not +taken into account when calculating to optimal width.)" + :package-version '(magit . "2.12.0") + :group 'magit-refs + :type '(choice (integer :tag "Constant wide") + (cons :tag "Wide constrains" + (integer :tag "Minimum") + (integer :tag "Maximum")))) + +(defcustom magit-refs-focus-column-width 5 + "Width of the focus column in `magit-refs-mode' buffers. + +The focus column is the first column, which marks one +branch (usually the current branch) as the focused branch using +\"*\" or \"@\". For each other reference, this column optionally +shows how many commits it is ahead of the focused branch and \"<\", or +if it isn't ahead then the commits it is behind and \">\", or if it +isn't behind either, then a \"=\". + +This column may also display only \"*\" or \"@\" for the focused +branch, in which case this option is ignored. Use \"L v\" to +change the verbosity of this column." + :package-version '(magit . "2.12.0") + :group 'magit-refs + :type 'integer) + +(defcustom magit-refs-filter-alist nil + "Alist controlling which refs are omitted from `magit-refs-mode' buffers. + +The purpose of this option is to forgo displaying certain refs +based on their name. If you want to not display any refs of a +certain type, then you should remove the appropriate function +from `magit-refs-sections-hook' instead. + +All keys are tried in order until one matches. Then its value +is used and subsequent elements are ignored. If the value is +non-nil, then the reference is displayed, otherwise it is not. +If no element matches, then the reference is displayed. + +A key can either be a regular expression that the refname has to +match, or a function that takes the refname as only argument and +returns a boolean. A remote branch such as \"origin/master\" is +displayed as just \"master\", however for this comparison the +former is used." + :package-version '(magit . "2.12.0") + :group 'magit-refs + :type '(alist :key-type (choice :tag "Key" regexp function) + :value-type (boolean :tag "Value" + :on "show (non-nil)" + :off "omit (nil)"))) + +(defcustom magit-visit-ref-behavior nil + "Control how `magit-visit-ref' behaves in `magit-refs-mode' buffers. + +By default `magit-visit-ref' behaves like `magit-show-commit', +in all buffers, including `magit-refs-mode' buffers. When the +type of the section at point is `commit' then \"RET\" is bound to +`magit-show-commit', and when the type is either `branch' or +`tag' then it is bound to `magit-visit-ref'. + +\"RET\" is one of Magit's most essential keys and at least by +default it should behave consistently across all of Magit, +especially because users quickly learn that it does something +very harmless; it shows more information about the thing at point +in another buffer. + +However \"RET\" used to behave differently in `magit-refs-mode' +buffers, doing surprising things, some of which cannot really be +described as \"visit this thing\". If you have grown accustomed +to such inconsistent, but to you useful, behavior, then you can +restore that by adding one or more of the below symbols to the +value of this option. But keep in mind that by doing so you +don't only introduce inconsistencies, you also lose some +functionality and might have to resort to `M-x magit-show-commit' +to get it back. + +`magit-visit-ref' looks for these symbols in the order in which +they are described here. If the presence of a symbol applies to +the current situation, then the symbols that follow do not affect +the outcome. + +`focus-on-ref' + + With a prefix argument update the buffer to show commit counts + and lists of cherry commits relative to the reference at point + instead of relative to the current buffer or `HEAD'. + + Instead of adding this symbol, consider pressing \"C-u y o RET\". + +`create-branch' + + If point is on a remote branch, then create a new local branch + with the same name, use the remote branch as its upstream, and + then check out the local branch. + + Instead of adding this symbol, consider pressing \"b c RET RET\", + like you would do in other buffers. + +`checkout-any' + + Check out the reference at point. If that reference is a tag + or a remote branch, then this results in a detached `HEAD'. + + Instead of adding this symbol, consider pressing \"b b RET\", + like you would do in other buffers. + +`checkout-branch' + + Check out the local branch at point. + + Instead of adding this symbol, consider pressing \"b b RET\", + like you would do in other buffers." + :package-version '(magit . "2.9.0") + :group 'magit-refs + :group 'magit-commands + :options '(focus-on-ref create-branch checkout-any checkout-branch) + :type '(list :convert-widget custom-hook-convert-widget)) + +;;; Mode + +(defvar-keymap magit-refs-mode-map + :doc "Keymap for `magit-refs-mode'." + :parent magit-mode-map + "C-y" #'magit-refs-set-show-commit-count + "L" #'magit-margin-settings) + +(define-derived-mode magit-refs-mode magit-mode "Magit Refs" + "Mode which lists and compares references. + +This mode is documented in info node `(magit)References Buffer'. + +\\<magit-mode-map>\ +Type \\[magit-refresh] to refresh the current buffer. +Type \\[magit-section-toggle] to expand or hide the section at point. +Type \\[magit-visit-thing] or \\[magit-diff-show-or-scroll-up] \ +to visit the commit or branch at point. + +Type \\[magit-branch] to see available branch commands. +Type \\[magit-merge] to merge the branch or commit at point. +Type \\[magit-cherry-pick] to apply the commit at point. +Type \\[magit-reset] to reset `HEAD' to the commit at point. + +\\{magit-refs-mode-map}" + :interactive nil + :group 'magit-refs + (magit-hack-dir-local-variables) + (setq magit--imenu-group-types '(local remote tags))) + +(defun magit-refs-setup-buffer (ref args) + (magit-setup-buffer #'magit-refs-mode nil + (magit-buffer-upstream ref) + (magit-buffer-arguments args))) + +(defun magit-refs-refresh-buffer () + (setq magit-set-buffer-margin-refresh (not (magit-buffer-margin-p))) + (unless (magit-rev-verify magit-buffer-upstream) + (setq magit-refs-show-commit-count nil)) + (magit-set-header-line-format + (format "%s %s" magit-buffer-upstream + (string-join magit-buffer-arguments " "))) + (magit-insert-section (branchbuf) + (magit-run-section-hook 'magit-refs-sections-hook)) + (add-hook 'kill-buffer-hook #'magit-preserve-section-visibility-cache)) + +(cl-defmethod magit-buffer-value (&context (major-mode magit-refs-mode)) + (cons magit-buffer-upstream magit-buffer-arguments)) + +;;; Commands + +;;;###autoload (autoload 'magit-show-refs "magit-refs" nil t) +(transient-define-prefix magit-show-refs (&optional transient) + "List and compare references in a dedicated buffer." + :man-page "git-branch" + :value (lambda () + (magit-show-refs-arguments magit-prefix-use-buffer-arguments)) + ["Arguments" + (magit-for-each-ref:--contains) + ("-M" "Merged" "--merged=" magit-transient-read-revision) + ("-m" "Merged to HEAD" "--merged") + ("-N" "Not merged" "--no-merged=" magit-transient-read-revision) + ("-n" "Not merged to HEAD" "--no-merged") + (magit-for-each-ref:--sort)] + ["Actions" + ("y" "Show refs, comparing them with HEAD" magit-show-refs-head) + ("c" "Show refs, comparing them with current branch" magit-show-refs-current) + ("o" "Show refs, comparing them with other branch" magit-show-refs-other) + ("r" "Show refs, changing commit count display" + magit-refs-set-show-commit-count)] + (interactive (list (or (derived-mode-p 'magit-refs-mode) + current-prefix-arg))) + (if transient + (transient-setup 'magit-show-refs) + (magit-refs-setup-buffer "HEAD" (magit-show-refs-arguments)))) + +(defun magit-show-refs-arguments (&optional use-buffer-args) + (unless use-buffer-args + (setq use-buffer-args magit-direct-use-buffer-arguments)) + (let (args) + (cond + ((eq transient-current-command 'magit-show-refs) + (setq args (transient-args 'magit-show-refs))) + ((eq major-mode 'magit-refs-mode) + (setq args magit-buffer-arguments)) + ((and (memq use-buffer-args '(always selected)) + (and-let* ((buffer (magit-get-mode-buffer + 'magit-refs-mode nil + (eq use-buffer-args 'selected)))) + (progn + (setq args (buffer-local-value 'magit-buffer-arguments buffer)) + t)))) + (t + (setq args (alist-get 'magit-show-refs transient-values)))) + args)) + +(transient-define-argument magit-for-each-ref:--contains () + :description "Contains" + :class 'transient-option + :key "-c" + :argument "--contains=" + :reader #'magit-transient-read-revision) + +(transient-define-argument magit-for-each-ref:--sort () + :description "Sort" + :class 'transient-option + :key "-s" + :argument "--sort=" + :reader #'magit-read-ref-sort) + +(defun magit-read-ref-sort (prompt initial-input _history) + (magit-completing-read prompt + '("-committerdate" "-authordate" + "committerdate" "authordate") + nil nil initial-input)) + +;;;###autoload +(defun magit-show-refs-head (&optional args) + "List and compare references in a dedicated buffer. +Compared with `HEAD'." + (interactive (list (magit-show-refs-arguments))) + (magit-refs-setup-buffer "HEAD" args)) + +;;;###autoload +(defun magit-show-refs-current (&optional args) + "List and compare references in a dedicated buffer. +Compare with the current branch or `HEAD' if it is detached." + (interactive (list (magit-show-refs-arguments))) + (magit-refs-setup-buffer (magit-get-current-branch) args)) + +;;;###autoload +(defun magit-show-refs-other (&optional ref args) + "List and compare references in a dedicated buffer. +Compared with a branch read from the user." + (interactive (list (magit-read-other-branch "Compare with") + (magit-show-refs-arguments))) + (magit-refs-setup-buffer ref args)) + +(transient-define-suffix magit-refs-set-show-commit-count () + "Change for which refs the commit count is shown." + :description "Change verbosity" + :key "v" + :transient nil + :if-derived 'magit-refs-mode + (interactive) + (setq-local magit-refs-show-commit-count + (magit-read-char-case "Show commit counts for " nil + (?a "[a]ll refs" 'all) + (?b "[b]ranches only" t) + (?n "[n]othing" nil))) + (magit-refresh)) + +(defun magit-visit-ref () + "Visit the reference or revision at point in another buffer. +If there is no revision at point or with a prefix argument prompt +for a revision. + +This command behaves just like `magit-show-commit', except if +point is on a reference in a `magit-refs-mode' buffer (a buffer +listing branches and tags), in which case the behavior may be +different, but only if you have customized the option +`magit-visit-ref-behavior' (which see). When invoked from a +menu this command always behaves like `magit-show-commit'." + (interactive) + (if (and (derived-mode-p 'magit-refs-mode) + (magit-section-match '(branch tag)) + (not (magit-menu-position))) + (let ((ref (oref (magit-current-section) value))) + (cond (current-prefix-arg + (cond ((memq 'focus-on-ref magit-visit-ref-behavior) + (magit-refs-setup-buffer ref (magit-show-refs-arguments))) + (magit-visit-ref-behavior + ;; Don't prompt for commit to visit. + (let ((current-prefix-arg nil)) + (call-interactively #'magit-show-commit))))) + ((and (memq 'create-branch magit-visit-ref-behavior) + (magit-section-match [branch remote])) + (let ((branch (cdr (magit-split-branch-name ref)))) + (if (magit-branch-p branch) + (if (magit-rev-eq branch ref) + (magit-call-git "checkout" branch) + (setq branch (propertize branch 'face 'magit-branch-local)) + (setq ref (propertize ref 'face 'magit-branch-remote)) + (pcase (prog1 (read-char-choice (format (propertize "\ +Branch %s already exists. + [c]heckout %s as-is + [r]reset %s to %s and checkout %s + [a]bort " 'face 'minibuffer-prompt) branch branch branch ref branch) + '(?c ?r ?a)) + (message "")) ; otherwise prompt sticks + (?c (magit-call-git "checkout" branch)) + (?r (magit-call-git "checkout" "-B" branch ref)) + (?a (user-error "Abort")))) + (magit-call-git "checkout" "-b" branch ref)) + (setq magit-buffer-upstream branch) + (magit-refresh))) + ((or (memq 'checkout-any magit-visit-ref-behavior) + (and (memq 'checkout-branch magit-visit-ref-behavior) + (magit-section-match [branch local]))) + (magit-call-git "checkout" ref) + (setq magit-buffer-upstream ref) + (magit-refresh)) + (t + (call-interactively #'magit-show-commit)))) + (call-interactively #'magit-show-commit))) + +;;; Sections + +(defvar-keymap magit-remote-section-map + :doc "Keymap for `remote' sections." + "<remap> <magit-file-rename>" #'magit-remote-rename + "<remap> <magit-delete-thing>" #'magit-remote-remove + "<2>" (magit-menu-item "Rename %s" #'magit-remote-rename) + "<1>" (magit-menu-item "Remove %m" #'magit-remote-remove)) + +(defvar-keymap magit-branch-section-map + :doc "Keymap for `branch' sections." + "<remap> <magit-file-rename>" #'magit-branch-rename + "<remap> <magit-delete-thing>" #'magit-branch-delete + "<remap> <magit-visit-thing>" #'magit-visit-ref + "<3>" (magit-menu-item "Rename %s" #'magit-branch-rename) + "<2>" (magit-menu-item "Delete %m" #'magit-branch-delete) + "<1>" (magit-menu-item "Visit commit" #'magit-visit-ref)) + +(defvar-keymap magit-tag-section-map + :doc "Keymap for `tag' sections." + "<remap> <magit-delete-thing>" #'magit-tag-delete + "<remap> <magit-visit-thing>" #'magit-visit-ref + "<2>" (magit-menu-item "Delete %m" #'magit-tag-delete) + "<1>" (magit-menu-item "Visit %s" #'magit-visit-ref)) + +(defun magit--painted-branch-as-menu-section (section) + (and-let* ((branch (and (magit-section-match 'commit) + (magit--painted-branch-at-point)))) + (let ((dummy (magit-section :type 'branch :value branch))) + (oset dummy keymap magit-branch-section-map) + (dolist (slot '(start content hidden parent children)) + (when (slot-boundp section slot) + (setf (eieio-oref dummy slot) + (eieio-oref section slot)))) + dummy))) + +(add-hook 'magit-menu-alternative-section-hook + #'magit--painted-branch-as-menu-section) + +(defun magit-insert-branch-description () + "Insert header containing the description of the current branch. +Insert a header line with the name and description of the +current branch. The description is taken from the Git variable +`branch.<NAME>.description'; if that is undefined then no header +line is inserted at all." + (when-let* ((branch (magit-get-current-branch)) + (desc (magit-get "branch" branch "description")) + (desc (split-string desc "\n"))) + (when (equal (car (last desc)) "") + (setq desc (butlast desc))) + (magit-insert-section (branchdesc branch t) + (magit-insert-heading branch ": " (car desc)) + (when (cdr desc) + (insert (string-join (cdr desc) "\n")) + (insert "\n\n"))))) + +(defun magit-insert-tags () + "Insert sections showing all tags." + (when-let ((tags (magit-git-lines "tag" "--list" "-n" magit-buffer-arguments))) + (let ((_head (magit-rev-parse "HEAD"))) + (magit-insert-section (tags) + (magit-insert-heading (length tags) "Tags") + (dolist (tag tags) + (string-match "^\\([^ \t]+\\)[ \t]+\\([^ \t\n].*\\)?" tag) + (let ((tag (match-string 1 tag)) + (msg (match-string 2 tag))) + (when (magit-refs--insert-refname-p tag) + (magit-insert-section (tag tag t) + (magit-insert-heading + (magit-refs--format-focus-column tag 'tag) + (propertize tag 'font-lock-face 'magit-tag) + (make-string + (max 1 (- (if (consp magit-refs-primary-column-width) + (car magit-refs-primary-column-width) + magit-refs-primary-column-width) + (length tag))) + ?\s) + (and msg (magit-log-propertize-keywords nil msg))) + (when (and magit-refs-margin-for-tags (magit-buffer-margin-p)) + (magit-refs--format-margin tag)) + (magit-refs--insert-cherry-commits tag))))) + (insert ?\n) + (magit-make-margin-overlay nil t))))) + +(defun magit-insert-remote-branches () + "Insert sections showing all remote-tracking branches." + (dolist (remote (magit-list-remotes)) + (magit-insert-section (remote remote) + (magit-insert-heading + (let ((pull (magit-get "remote" remote "url")) + (push (magit-get "remote" remote "pushurl"))) + (format (propertize "Remote %s (%s):" + 'font-lock-face 'magit-section-heading) + (propertize remote 'font-lock-face 'magit-branch-remote) + (concat pull (and pull push ", ") push)))) + (let (head) + (dolist (line (magit-git-lines "for-each-ref" "--format=\ +%(symref:short)%00%(refname:short)%00%(refname)%00%(subject)" + (concat "refs/remotes/" remote) + magit-buffer-arguments)) + (pcase-let ((`(,head-branch ,branch ,ref ,msg) + (cl-substitute nil "" + (split-string line "\0") + :test #'equal))) + (cond + (head-branch + ;; Note: Use `ref' instead of `branch' for the check + ;; below because 'refname:short' shortens the remote + ;; HEAD to '<remote>' instead of '<remote>/HEAD' as of + ;; Git v2.40.0. + (cl-assert + (equal ref (concat "refs/remotes/" remote "/HEAD"))) + (setq head head-branch)) + ((not (equal ref (concat "refs/remotes/" remote "/HEAD"))) + ;; ^ Skip mis-configured remotes where HEAD is not a + ;; symref. See #5092. + (when (magit-refs--insert-refname-p branch) + (magit-insert-section (branch branch t) + (let ((headp (equal branch head)) + (abbrev (if magit-refs-show-remote-prefix + branch + (substring branch (1+ (length remote)))))) + (magit-insert-heading + (magit-refs--format-focus-column branch) + (magit-refs--propertize-branch + abbrev ref (and headp 'magit-branch-remote-head)) + (make-string + (max 1 (- (if (consp magit-refs-primary-column-width) + (car magit-refs-primary-column-width) + magit-refs-primary-column-width) + (length abbrev))) + ?\s) + (and msg (magit-log-propertize-keywords nil msg)))) + (when (magit-buffer-margin-p) + (magit-refs--format-margin branch)) + (magit-refs--insert-cherry-commits branch)))))))) + (insert ?\n) + (magit-make-margin-overlay nil t)))) + +(defun magit-insert-local-branches () + "Insert sections showing all local branches." + (magit-insert-section (local nil) + (magit-insert-heading t "Branches") + (dolist (line (magit-refs--format-local-branches)) + (pcase-let ((`(,branch . ,strings) line)) + (magit-insert-section + ((eval (if branch 'branch 'commit)) + (or branch (magit-rev-parse "HEAD")) + t) + (apply #'magit-insert-heading strings) + (when (magit-buffer-margin-p) + (magit-refs--format-margin branch)) + (magit-refs--insert-cherry-commits branch)))) + (insert ?\n) + (magit-make-margin-overlay nil t))) + +(defun magit-refs--format-local-branches () + (let ((lines (seq-keep #'magit-refs--format-local-branch + (magit-git-lines + "for-each-ref" + (concat "--format=\ +%(HEAD)%00%(refname:short)%00%(refname)%00\ +%(upstream:short)%00%(upstream)%00%(upstream:track)%00" + (if magit-refs-show-push-remote "\ +%(push:remotename)%00%(push)%00%(push:track)%00%(subject)" + "%00%00%00%(subject)")) + "refs/heads" + magit-buffer-arguments)))) + (unless (magit-get-current-branch) + (push (magit-refs--format-local-branch + (concat "*\0\0\0\0\0\0\0\0" (magit-rev-format "%s"))) + lines)) + (setq-local magit-refs-primary-column-width + (let ((def (default-value 'magit-refs-primary-column-width))) + (if (atom def) + def + (pcase-let ((`(,min . ,max) def)) + (min max (apply #'max min (mapcar #'car lines))))))) + (mapcar (pcase-lambda (`(,_ ,branch ,focus ,branch-desc ,u:ahead ,p:ahead + ,u:behind ,upstream ,p:behind ,push ,msg)) + (list branch focus branch-desc u:ahead p:ahead + (make-string (max 1 (- magit-refs-primary-column-width + (length (concat branch-desc + u:ahead + p:ahead + u:behind)))) + ?\s) + u:behind upstream p:behind push + msg)) + lines))) + +(defun magit-refs--format-local-branch (line) + (pcase-let ((`(,head ,branch ,ref ,upstream ,u:ref ,u:track + ,push ,p:ref ,p:track ,msg) + (cl-substitute nil "" (split-string line "\0") :test #'equal))) + (when (or (not branch) + (magit-refs--insert-refname-p branch)) + (let* ((headp (equal head "*")) + (pushp (and push + magit-refs-show-push-remote + (magit-rev-verify p:ref) + (not (equal p:ref u:ref)))) + (branch-desc + (if branch + (magit-refs--propertize-branch + branch ref (and headp 'magit-branch-current)) + (magit--propertize-face "(detached)" 'magit-branch-warning))) + (u:ahead (and u:track + (string-match "ahead \\([0-9]+\\)" u:track) + (magit--propertize-face + (concat (and magit-refs-pad-commit-counts " ") + (match-string 1 u:track) + ">") + 'magit-dimmed))) + (u:behind (and u:track + (string-match "behind \\([0-9]+\\)" u:track) + (magit--propertize-face + (concat "<" + (match-string 1 u:track) + (and magit-refs-pad-commit-counts " ")) + 'magit-dimmed))) + (p:ahead (and pushp p:track + (string-match "ahead \\([0-9]+\\)" p:track) + (magit--propertize-face + (concat (match-string 1 p:track) + ">" + (and magit-refs-pad-commit-counts " ")) + 'magit-branch-remote))) + (p:behind (and pushp p:track + (string-match "behind \\([0-9]+\\)" p:track) + (magit--propertize-face + (concat "<" + (match-string 1 p:track) + (and magit-refs-pad-commit-counts " ")) + 'magit-dimmed)))) + (list (1+ (length (concat branch-desc u:ahead p:ahead u:behind))) + branch + (magit-refs--format-focus-column branch headp) + branch-desc u:ahead p:ahead u:behind + (and upstream + (concat (if (equal u:track "[gone]") + (magit--propertize-face upstream 'error) + (magit-refs--propertize-branch upstream u:ref)) + " ")) + (and pushp + (concat p:behind + (magit--propertize-face + push 'magit-branch-remote) + " ")) + (and msg (magit-log-propertize-keywords nil msg))))))) + +(defun magit-refs--format-focus-column (ref &optional type) + (let ((focus magit-buffer-upstream) + (width (if magit-refs-show-commit-count + magit-refs-focus-column-width + 1))) + (format + (format "%%%ss " width) + (cond ((or (equal ref focus) + (and (eq type t) + (equal focus "HEAD"))) + (magit--propertize-face (concat (if (equal focus "HEAD") "@" "*") + (make-string (1- width) ?\s)) + 'magit-section-heading)) + ((if (eq type 'tag) + (eq magit-refs-show-commit-count 'all) + magit-refs-show-commit-count) + (pcase-let ((`(,behind ,ahead) + (magit-rev-diff-count magit-buffer-upstream ref))) + (magit--propertize-face + (cond ((> ahead 0) (concat "<" (number-to-string ahead))) + ((> behind 0) (concat (number-to-string behind) ">")) + (t "=")) + 'magit-dimmed))) + (t ""))))) + +(defun magit-refs--propertize-branch (branch ref &optional head-face) + (let ((face (cdr (cl-find-if (pcase-lambda (`(,re . ,_)) + (string-match-p re ref)) + magit-ref-namespaces)))) + (magit--propertize-face + branch (if head-face (list face head-face) face)))) + +(defun magit-refs--insert-refname-p (refname) + (if-let ((entry (seq-find (pcase-lambda (`(,key . ,_)) + (if (functionp key) + (funcall key refname) + (string-match-p key refname))) + magit-refs-filter-alist))) + (cdr entry) + t)) + +(defun magit-refs--insert-cherry-commits (ref) + (magit-insert-section-body + (let ((start (point)) + (magit-insert-section--current nil)) + (magit-git-wash (apply-partially #'magit-log-wash-log 'cherry) + "cherry" "-v" (magit-abbrev-arg) magit-buffer-upstream ref) + (if (= (point) start) + (message "No cherries for %s" ref) + (magit-make-margin-overlay nil t))))) + +(defun magit-refs--format-margin (commit) + (save-excursion + (goto-char (line-beginning-position 0)) + (let ((line (magit-rev-format "%ct%cN" commit))) + (magit-log-format-margin commit + (substring line 10) + (substring line 0 10))))) + +;;; _ +(provide 'magit-refs) +;;; magit-refs.el ends here diff --git a/emacs/elpa/magit-20241004.917/magit-remote.el b/emacs/elpa/magit-20241004.917/magit-remote.el @@ -0,0 +1,401 @@ +;;; magit-remote.el --- Transfer Git commits -*- lexical-binding:t -*- + +;; Copyright (C) 2008-2024 The Magit Project Contributors + +;; Author: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> +;; Maintainer: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> + +;; SPDX-License-Identifier: GPL-3.0-or-later + +;; Magit is free software: you can redistribute it and/or modify it +;; under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. +;; +;; Magit is distributed in the hope that it will be useful, but WITHOUT +;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +;; or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public +;; License for more details. +;; +;; You should have received a copy of the GNU General Public License +;; along with Magit. If not, see <https://www.gnu.org/licenses/>. + +;;; Commentary: + +;; This library implements remote commands. + +;;; Code: + +(require 'magit) + +;;; Options + +(defcustom magit-remote-add-set-remote.pushDefault 'ask-if-unset + "Whether to set the value of `remote.pushDefault' after adding a remote. + +If `ask', then always ask. If `ask-if-unset', then ask, but only +if the variable isn't set already. If nil, then don't ever set. +If the value is a string, then set without asking, provided that +the name of the added remote is equal to that string and the +variable isn't already set." + :package-version '(magit . "2.4.0") + :group 'magit-commands + :type '(choice (const :tag "ask if unset" ask-if-unset) + (const :tag "always ask" ask) + (string :tag "set if named") + (const :tag "don't set"))) + +(defcustom magit-remote-direct-configure t + "Whether the command `magit-remote' shows Git variables. +When set to nil, no variables are displayed by this transient +command, instead the sub-transient `magit-remote-configure' +has to be used to view and change remote related variables." + :package-version '(magit . "2.12.0") + :group 'magit-commands + :type 'boolean) + +(defcustom magit-prefer-push-default nil + "Whether to prefer `remote.pushDefault' over per-branch variables." + :package-version '(magit . "3.0.0") + :group 'magit-commands + :type 'boolean) + +;;; Commands + +;;;###autoload (autoload 'magit-remote "magit-remote" nil t) +(transient-define-prefix magit-remote (remote) + "Add, configure or remove a remote." + :man-page "git-remote" + :value '("-f") + ["Variables" + :if (lambda () + (and magit-remote-direct-configure + (oref (transient-prefix-object) scope))) + ("u" magit-remote.<remote>.url) + ("U" magit-remote.<remote>.fetch) + ("s" magit-remote.<remote>.pushurl) + ("S" magit-remote.<remote>.push) + ("O" magit-remote.<remote>.tagopt)] + ["Arguments for add" + ("-f" "Fetch after add" "-f")] + ["Actions" + [("a" "Add" magit-remote-add) + ("r" "Rename" magit-remote-rename) + ("k" "Remove" magit-remote-remove)] + [("C" "Configure..." magit-remote-configure) + ("p" "Prune stale branches" magit-remote-prune) + ("P" "Prune stale refspecs" magit-remote-prune-refspecs) + ("b" magit-update-default-branch) + (7 "z" "Unshallow remote" magit-remote-unshallow)]] + (interactive (list (magit-get-current-remote))) + (transient-setup 'magit-remote nil nil :scope remote)) + +(defun magit-read-url (prompt &optional initial-input) + (let ((url (magit-read-string-ns prompt initial-input))) + (if (string-prefix-p "~" url) + (expand-file-name url) + url))) + +;;;###autoload +(defun magit-remote-add (remote url &optional args) + "Add a remote named REMOTE and fetch it." + (interactive + (let ((origin (magit-get "remote.origin.url")) + (remote (magit-read-string-ns "Remote name"))) + (list remote + (magit-read-url + "Remote url" + (and origin + (string-match "\\([^:/]+\\)/[^/]+\\(\\.git\\)?\\'" origin) + (replace-match remote t t origin 1))) + (transient-args 'magit-remote)))) + (if (pcase (list magit-remote-add-set-remote.pushDefault + (magit-get "remote.pushDefault")) + (`(,(pred stringp) ,_) t) + ((or `(ask ,_) '(ask-if-unset nil)) + (y-or-n-p (format "Set `remote.pushDefault' to \"%s\"? " remote)))) + (progn (magit-call-git "remote" "add" args remote url) + (setf (magit-get "remote.pushDefault") remote) + (magit-refresh)) + (magit-run-git-async "remote" "add" args remote url))) + +;;;###autoload +(defun magit-remote-rename (old new) + "Rename the remote named OLD to NEW." + (interactive + (let ((remote (magit-read-remote "Rename remote"))) + (list remote (magit-read-string-ns (format "Rename %s to" remote))))) + (unless (string= old new) + (magit-call-git "remote" "rename" old new) + (magit-remote--cleanup-push-variables old new) + (magit-refresh))) + +;;;###autoload +(defun magit-remote-remove (remote) + "Delete the remote named REMOTE." + (interactive (list (magit-read-remote "Delete remote"))) + (magit-call-git "remote" "rm" remote) + (magit-remote--cleanup-push-variables remote) + (magit-refresh)) + +(defun magit-remote--cleanup-push-variables (remote &optional new-name) + (magit-with-toplevel + (when (equal (magit-get "remote.pushDefault") remote) + (magit-set new-name "remote.pushDefault")) + (dolist (var (magit-git-lines "config" "--name-only" + "--get-regexp" "^branch\\.[^.]*\\.pushRemote" + (format "^%s$" remote))) + (magit-call-git "config" (and (not new-name) "--unset") var new-name)))) + +(defconst magit--refspec-re "\\`\\(\\+\\)?\\([^:]+\\):\\(.*\\)\\'") + +;;;###autoload +(defun magit-remote-prune (remote) + "Remove stale remote-tracking branches for REMOTE." + (interactive (list (magit-read-remote "Prune stale branches of remote"))) + (magit-run-git-async "remote" "prune" remote)) + +;;;###autoload +(defun magit-remote-prune-refspecs (remote) + "Remove stale refspecs for REMOTE. + +A refspec is stale if there no longer exists at least one branch +on the remote that would be fetched due to that refspec. A stale +refspec is problematic because its existence causes Git to refuse +to fetch according to the remaining non-stale refspecs. + +If only stale refspecs remain, then offer to either delete the +remote or to replace the stale refspecs with the default refspec. + +Also remove the remote-tracking branches that were created due to +the now stale refspecs. Other stale branches are not removed." + (interactive (list (magit-read-remote "Prune refspecs of remote"))) + (let* ((tracking-refs (magit-list-remote-branches remote)) + (remote-refs (magit-remote-list-refs remote)) + (variable (format "remote.%s.fetch" remote)) + (refspecs (magit-get-all variable)) + stale) + (dolist (refspec refspecs) + (when (string-match magit--refspec-re refspec) + (let ((theirs (match-string 2 refspec)) + (ours (match-string 3 refspec))) + (unless (if (string-match "\\*" theirs) + (let ((re (replace-match ".*" t t theirs))) + (--some (string-match-p re it) remote-refs)) + (member theirs remote-refs)) + (push (cons refspec + (if (string-match "\\*" ours) + (let ((re (replace-match ".*" t t ours))) + (--filter (string-match-p re it) tracking-refs)) + (list (car (member ours tracking-refs))))) + stale))))) + (if (not stale) + (message "No stale refspecs for remote %S" remote) + (if (= (length stale) + (length refspecs)) + (magit-read-char-case + (format "All of %s's refspecs are stale. " remote) nil + (?s "replace with [d]efault refspec" + (magit-set-all + (list (format "+refs/heads/*:refs/remotes/%s/*" remote)) + variable)) + (?r "[r]emove remote" + (magit-call-git "remote" "rm" remote)) + (?a "or [a]abort" + (user-error "Abort"))) + (if (if (length= stale 1) + (pcase-let ((`(,refspec . ,refs) (car stale))) + (magit-confirm 'prune-stale-refspecs + (list "Prune stale refspec %s and branch %%s" refspec) + (list "Prune stale refspec %s and %%d branches" refspec) + nil refs)) + (magit-confirm 'prune-stale-refspecs nil + (format "Prune %%d stale refspecs and %d branches" + (length (cl-mapcan (lambda (s) (copy-sequence (cdr s))) + stale))) + nil + (mapcar (pcase-lambda (`(,refspec . ,refs)) + (concat refspec "\n" + (mapconcat (lambda (b) (concat " " b)) + refs "\n"))) + stale))) + (pcase-dolist (`(,refspec . ,refs) stale) + (magit-call-git "config" "--unset" variable + (regexp-quote refspec)) + (magit--log-action + (lambda (refs) + (format "Deleting %d branches" (length refs))) + (lambda (ref) + (format "Deleting branch %s (was %s)" ref + (magit-rev-parse "--short" ref))) + refs) + (dolist (ref refs) + (magit-call-git "update-ref" "-d" ref))) + (user-error "Abort"))) + (magit-refresh)))) + +;;;###autoload +(defun magit-remote-set-head (remote &optional branch) + "Set the local representation of REMOTE's default branch. +Query REMOTE and set the symbolic-ref refs/remotes/<remote>/HEAD +accordingly. With a prefix argument query for the branch to be +used, which allows you to select an incorrect value if you fancy +doing that." + (interactive + (let ((remote (magit-read-remote "Set HEAD for remote"))) + (list remote + (and current-prefix-arg + (magit-read-remote-branch (format "Set %s/HEAD to" remote) + remote nil nil t))))) + (magit-run-git "remote" "set-head" remote (or branch "--auto"))) + +;;;###autoload +(defun magit-remote-unset-head (remote) + "Unset the local representation of REMOTE's default branch. +Delete the symbolic-ref \"refs/remotes/<remote>/HEAD\"." + (interactive (list (magit-read-remote "Unset HEAD for remote"))) + (magit-run-git "remote" "set-head" remote "--delete")) + +;;;###autoload (autoload 'magit-update-default-branch "magit-remote" nil t) +(transient-define-suffix magit-update-default-branch () + "Update name of the default branch after upstream changed it." + :description "Update default branch" + :inapt-if-not #'magit-get-some-remote + (interactive) + (pcase-let ((`(,_remote ,oldname) (magit--get-default-branch)) + (`( ,remote ,newname) (magit--get-default-branch t))) + (cond + ((equal oldname newname) + (setq oldname + (read-string + (format + "Name of default branch is still `%s', %s\n%s `%s': " oldname + "but the upstreams of some local branches might need updating." + "Name of upstream branches to replace with" newname))) + (magit--set-default-branch newname oldname) + (magit-refresh)) + (t + (unless oldname + (setq oldname + (magit-read-other-local-branch + (format "Name of old default branch to be renamed to `%s'" + newname) + newname "master"))) + (cond + ((y-or-n-p (format "Default branch changed from `%s' to `%s' on %s.%s" + oldname newname remote " Do the same locally? ")) + (magit--set-default-branch newname oldname) + (magit-refresh)) + ((user-error "Abort"))))))) + +;;;###autoload +(defun magit-remote-unshallow (remote) + "Convert a shallow remote into a full one. +If only a single refspec is set and it does not contain a +wildcard, then also offer to replace it with the standard +refspec." + (interactive (list (or (magit-get-current-remote) + (magit-read-remote "Delete remote")))) + (let ((refspecs (magit-get-all "remote" remote "fetch")) + (standard (format "+refs/heads/*:refs/remotes/%s/*" remote))) + (when (and (length= refspecs 1) + (not (string-search "*" (car refspecs))) + (yes-or-no-p (format "Also replace refspec %s with %s? " + (car refspecs) + standard))) + (magit-set standard "remote" remote "fetch")) + (magit-git-fetch "--unshallow" remote))) + +;;; Configure + +;;;###autoload (autoload 'magit-remote-configure "magit-remote" nil t) +(transient-define-prefix magit-remote-configure (remote) + "Configure a remote." + :man-page "git-remote" + [:description + (lambda () + (concat (propertize "Configure " 'face 'transient-heading) + (propertize (oref (transient-prefix-object) scope) + 'face 'magit-branch-remote))) + ("u" magit-remote.<remote>.url) + ("U" magit-remote.<remote>.fetch) + ("s" magit-remote.<remote>.pushurl) + ("S" magit-remote.<remote>.push) + ("O" magit-remote.<remote>.tagopt)] + (interactive + (list (or (and (not current-prefix-arg) + (not (and magit-remote-direct-configure + (eq transient-current-command 'magit-remote))) + (magit-get-current-remote)) + (magit--read-remote-scope)))) + (transient-setup 'magit-remote-configure nil nil :scope remote)) + +(defun magit--read-remote-scope (&optional obj) + (magit-read-remote + (if obj + (format "Set %s for remote" + (format (oref obj variable) "<name>")) + "Configure remote"))) + +(transient-define-infix magit-remote.<remote>.url () + :class 'magit--git-variable:urls + :scope #'magit--read-remote-scope + :variable "remote.%s.url" + :multi-value t + :history-key 'magit-remote.<remote>.*url) + +(transient-define-infix magit-remote.<remote>.fetch () + :class 'magit--git-variable + :scope #'magit--read-remote-scope + :variable "remote.%s.fetch" + :multi-value t) + +(transient-define-infix magit-remote.<remote>.pushurl () + :class 'magit--git-variable:urls + :scope #'magit--read-remote-scope + :variable "remote.%s.pushurl" + :multi-value t + :history-key 'magit-remote.<remote>.*url + :seturl-arg "--push") + +(transient-define-infix magit-remote.<remote>.push () + :class 'magit--git-variable + :scope #'magit--read-remote-scope + :variable "remote.%s.push") + +(transient-define-infix magit-remote.<remote>.tagopt () + :class 'magit--git-variable:choices + :scope #'magit--read-remote-scope + :variable "remote.%s.tagOpt" + :choices '("--no-tags" "--tags")) + +;;; Transfer Utilities + +(defun magit--push-remote-variable (&optional branch short) + (unless branch + (setq branch (magit-get-current-branch))) + (magit--propertize-face + (if (or (not branch) magit-prefer-push-default) + (if short "pushDefault" "remote.pushDefault") + (if short "pushRemote" (format "branch.%s.pushRemote" branch))) + 'bold)) + +(defun magit--select-push-remote (prompt-suffix) + (let* ((branch (or (magit-get-current-branch) + (user-error "No branch is checked out"))) + (remote (magit-get-push-remote branch)) + (changed nil)) + (when (or current-prefix-arg + (not remote) + (not (member remote (magit-list-remotes)))) + (setq changed t) + (setq remote + (magit-read-remote (format "Set %s and %s" + (magit--push-remote-variable) + prompt-suffix))) + (setf (magit-get (magit--push-remote-variable branch)) remote)) + (list branch remote changed))) + +;;; _ +(provide 'magit-remote) +;;; magit-remote.el ends here diff --git a/emacs/elpa/magit-20241004.917/magit-repos.el b/emacs/elpa/magit-20241004.917/magit-repos.el @@ -0,0 +1,546 @@ +;;; magit-repos.el --- Listing repositories -*- lexical-binding:t -*- + +;; Copyright (C) 2008-2024 The Magit Project Contributors + +;; Author: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> +;; Maintainer: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> + +;; SPDX-License-Identifier: GPL-3.0-or-later + +;; Magit is free software: you can redistribute it and/or modify it +;; under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. +;; +;; Magit is distributed in the hope that it will be useful, but WITHOUT +;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +;; or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public +;; License for more details. +;; +;; You should have received a copy of the GNU General Public License +;; along with Magit. If not, see <https://www.gnu.org/licenses/>. + +;;; Commentary: + +;; This library implements support for listing repositories. This +;; includes getting a Lisp list of known repositories as well as a +;; mode for listing repositories in a buffer. + +;;; Code: + +(require 'magit-core) + +(declare-function magit-status-setup-buffer "magit-status" (&optional directory)) + +(defvar x-stretch-cursor) + +;;; Options + +(defcustom magit-repository-directories nil + "List of directories that are or contain Git repositories. + +Each element has the form (DIRECTORY . DEPTH). DIRECTORY has +to be a directory or a directory file-name, a string. DEPTH, +an integer, specifies the maximum depth to look for Git +repositories. If it is 0, then only add DIRECTORY itself. + +This option controls which repositories are being listed by +`magit-list-repositories'. It also affects `magit-status' +\(which see) in potentially surprising ways." + :package-version '(magit . "3.0.0") + :group 'magit-essentials + :type '(repeat (cons directory (integer :tag "Depth")))) + +(defgroup magit-repolist nil + "List repositories in a buffer." + :link '(info-link "(magit)Repository List") + :group 'magit-modes) + +(defcustom magit-repolist-mode-hook '(hl-line-mode) + "Hook run after entering Magit-Repolist mode." + :package-version '(magit . "2.9.0") + :group 'magit-repolist + :type 'hook + :get #'magit-hook-custom-get + :options '(hl-line-mode)) + +(defcustom magit-repolist-columns + '(("Name" 25 magit-repolist-column-ident + ()) + ("Version" 25 magit-repolist-column-version + ((:sort magit-repolist-version<))) + ("B<U" 3 magit-repolist-column-unpulled-from-upstream + (;; (:help-echo "Upstream changes not in branch") + (:right-align t) + (:sort <))) + ("B>U" 3 magit-repolist-column-unpushed-to-upstream + (;; (:help-echo "Local changes not in upstream") + (:right-align t) + (:sort <))) + ("Path" 99 magit-repolist-column-path + ())) + "List of columns displayed by `magit-list-repositories'. + +Each element has the form (HEADER WIDTH FORMAT PROPS). + +HEADER is the string displayed in the header. WIDTH is the width +of the column. FORMAT is a function that is called with one +argument, the repository identification (usually its basename), +and with `default-directory' bound to the toplevel of its working +tree. It has to return a string to be inserted or nil. PROPS is +an alist that supports the keys `:right-align', `:pad-right' and +`:sort'. + +The `:sort' function has a weird interface described in the +docstring of `tabulated-list--get-sort'. Alternatively `<' and +`magit-repolist-version<' can be used as those functions are +automatically replaced with functions that satisfy the interface. +Set `:sort' to nil to inhibit sorting; if unspecified, then the +column is sortable using the default sorter. + +You may wish to display a range of numeric columns using just one +character per column and without any padding between columns, in +which case you should use an appropriate HEADER, set WIDTH to 1, +and set `:pad-right' to 0. \"+\" is substituted for numbers higher +than 9." + :package-version '(magit . "2.12.0") + :group 'magit-repolist + :type '(repeat (list :tag "Column" + (string :tag "Header Label") + (integer :tag "Column Width") + (function :tag "Inserter Function") + (repeat :tag "Properties" + (list (choice :tag "Property" + (const :right-align) + (const :pad-right) + (const :sort) + (symbol)) + (sexp :tag "Value")))))) + +(defcustom magit-repolist-column-flag-alist + '((magit-untracked-files . "N") + (magit-unstaged-files . "U") + (magit-staged-files . "S")) + "Association list of predicates and flags for `magit-repolist-column-flag'. + +Each element is of the form (FUNCTION . FLAG). Each FUNCTION is +called with no arguments, with `default-directory' bound to the +top level of a repository working tree, until one of them returns +a non-nil value. FLAG corresponding to that function is returned +as the value of `magit-repolist-column-flag'." + :package-version '(magit . "3.0.0") + :group 'magit-repolist + :type '(alist :key-type (function :tag "Predicate Function") + :value-type (string :tag "Flag"))) + +(defcustom magit-repolist-sort-key '("Path" . nil) + "Initial sort key for buffer created by `magit-list-repositories'. +If nil, no additional sorting is performed. Otherwise, this +should be a cons cell (NAME . FLIP). NAME is a string matching +one of the column names in `magit-repolist-columns'. FLIP, if +non-nil, means to invert the resulting sort." + :package-version '(magit . "3.2.0") + :group 'magit-repolist + :type '(choice (const nil) + (cons (string :tag "Column name") + (boolean :tag "Flip order")))) + +;;; List Repositories +;;;; List Commands +;;;###autoload +(defun magit-list-repositories () + "Display a list of repositories. + +Use the option `magit-repository-directories' to control which +repositories are displayed." + (interactive) + (magit-repolist-setup (default-value 'magit-repolist-columns))) + +;;;; Mode Commands + +(defun magit-repolist-status (&optional _button) + "Show the status for the repository at point." + (interactive) + (if-let ((id (tabulated-list-get-id))) + (magit-status-setup-buffer (expand-file-name id)) + (user-error "There is no repository at point"))) + +(defun magit-repolist-mark () + "Mark a repository and move to the next line." + (interactive) + (magit-repolist--ensure-padding) + (tabulated-list-put-tag "*" t)) + +(defun magit-repolist-unmark () + "Unmark a repository and move to the next line." + (interactive) + (tabulated-list-put-tag " " t)) + +(defun magit-repolist-fetch (repos) + "Fetch all marked or listed repositories." + (interactive (list (magit-repolist--get-repos ?*))) + (run-hooks 'magit-credential-hook) + (magit-repolist--mapc (apply-partially #'magit-run-git "remote" "update") + repos "Fetching in %s...")) + +(defun magit-repolist-find-file-other-frame (repos file) + "Find a file in all marked or listed repositories." + (interactive (list (magit-repolist--get-repos ?*) + (read-string "Find file in repositories: "))) + (magit-repolist--mapc (apply-partially #'find-file-other-frame file) repos)) + +(defun magit-repolist--ensure-padding () + "Set `tabulated-list-padding' to 2, unless that is already non-zero." + (when (zerop tabulated-list-padding) + (setq tabulated-list-padding 2) + (tabulated-list-init-header) + (tabulated-list-print t))) + +(defun magit-repolist--get-repos (&optional char) + "Return marked repositories or `all' if none are marked. +If optional CHAR is non-nil, then only return repositories +marked with that character. If no repositories are marked +then ask whether to act on all repositories instead." + (or (magit-repolist--marked-repos char) + (if (magit-confirm 'repolist-all + "Nothing selected. Act on ALL displayed repositories") + 'all + (user-error "Abort")))) + +(defun magit-repolist--marked-repos (&optional char) + "Return marked repositories. +If optional CHAR is non-nil, then only return repositories +marked with that character." + (let (c list) + (save-excursion + (goto-char (point-min)) + (while (not (eobp)) + (setq c (char-after)) + (unless (eq c ?\s) + (if char + (when (eq c char) + (push (tabulated-list-get-id) list)) + (push (cons c (tabulated-list-get-id)) list))) + (forward-line))) + list)) + +(defun magit-repolist--mapc (fn repos &optional msg) + "Apply FN to each directory in REPOS for side effects only. +If REPOS is the symbol `all', then call FN for all displayed +repositories. When FN is called, `default-directory' is bound to +the top-level directory of the current repository. If optional +MSG is non-nil then that is displayed around each call to FN. +If it contains \"%s\" then the directory is substituted for that." + (when (eq repos 'all) + (setq repos nil) + (save-excursion + (goto-char (point-min)) + (while (not (eobp)) + (push (tabulated-list-get-id) repos) + (forward-line))) + (setq repos (nreverse repos))) + (let ((base default-directory) + (len (length repos)) + (i 0)) + (mapc (lambda (repo) + (let ((default-directory + (file-name-as-directory (expand-file-name repo base)))) + (if msg + (let ((msg (concat (format "(%s/%s) " (cl-incf i) len) + (format msg default-directory)))) + (message msg) + (funcall fn) + (message (concat msg "done"))) + (funcall fn)))) + repos))) + +;;;; Mode + +(defvar-keymap magit-repolist-mode-map + :doc "Local keymap for Magit-Repolist mode buffers." + :parent tabulated-list-mode-map + "C-m" #'magit-repolist-status + "m" #'magit-repolist-mark + "u" #'magit-repolist-unmark + "f" #'magit-repolist-fetch + "5" #'magit-repolist-find-file-other-frame) + +(define-derived-mode magit-repolist-mode tabulated-list-mode "Repos" + "Major mode for browsing a list of Git repositories." + :interactive nil + :group 'magit-repolist + (setq-local x-stretch-cursor nil) + (setq tabulated-list-padding 0) + (add-hook 'tabulated-list-revert-hook #'magit-repolist-refresh nil t) + (setq imenu-prev-index-position-function + #'magit-repolist--imenu-prev-index-position) + (setq imenu-extract-index-name-function #'tabulated-list-get-id)) + +(defun magit-repolist-setup (columns) + (unless magit-repository-directories + (user-error "You need to customize `magit-repository-directories' %s" + "before you can list repositories")) + (with-current-buffer (get-buffer-create "*Magit Repositories*") + (magit-repolist-mode) + (setq-local magit-repolist-columns columns) + (magit-repolist-setup-1) + (magit-repolist-refresh) + (switch-to-buffer (current-buffer)))) + +(defun magit-repolist-setup-1 () + (unless tabulated-list-sort-key + (setq tabulated-list-sort-key + (pcase-let ((`(,column . ,flip) magit-repolist-sort-key)) + (cons (or (car (assoc column magit-repolist-columns)) + (caar magit-repolist-columns)) + flip)))) + (setq tabulated-list-format + (vconcat (seq-map-indexed + (lambda (column idx) + (pcase-let* ((`(,title ,width ,_fn ,props) column) + (sort-set (assoc :sort props)) + (sort-fn (cadr sort-set))) + (nconc (list title width + (cond ((eq sort-fn '<) + (magit-repolist-make-sorter + sort-fn #'string-to-number idx)) + ((eq sort-fn 'magit-repolist-version<) + (magit-repolist-make-sorter + sort-fn #'identity idx)) + (sort-fn sort-fn) + (sort-set nil) + (t t))) + (flatten-tree props)))) + magit-repolist-columns)))) + +(defun magit-repolist-refresh () + (setq tabulated-list-entries + (mapcar (pcase-lambda (`(,id . ,path)) + (let ((default-directory path)) + (list path + (vconcat + (mapcar (pcase-lambda (`(,title ,width ,fn ,props)) + (or (funcall fn `((:id ,id) + (:title ,title) + (:width ,width) + ,@props)) + "")) + magit-repolist-columns))))) + (magit-list-repos-uniquify + (--map (cons (file-name-nondirectory (directory-file-name it)) + it) + (magit-list-repos))))) + (message "Listing repositories...") + (tabulated-list-init-header) + (tabulated-list-print t) + (message "Listing repositories...done")) + +(defun magit-repolist--imenu-prev-index-position () + (and (not (bobp)) + (forward-line -1))) + +;;;; Columns + +(defun magit-repolist-make-sorter (sort-predicate convert-cell column-idx) + "Return a function suitable as a sorter for tabulated lists. +See `tabulated-list--get-sorter'. Given a more reasonable API +this would not be necessary and one could just use SORT-PREDICATE +directly. CONVERT-CELL can be used to turn the cell value, which +is always a string back into, e.g., a number. COLUMN-IDX has to +be the index of the column that uses the returned sorter function." + (lambda (a b) + (funcall sort-predicate + (funcall convert-cell (aref (cadr a) column-idx)) + (funcall convert-cell (aref (cadr b) column-idx))))) + +(defun magit-repolist-column-ident (spec) + "Insert the identification of the repository. +Usually this is just its basename." + (cadr (assq :id spec))) + +(defun magit-repolist-column-path (_) + "Insert the absolute path of the repository." + (abbreviate-file-name default-directory)) + +(defvar magit-repolist-column-version-regexp "\ +\\(?1:-\\(?2:[0-9]*\\)\ +\\(?3:-g[a-z0-9]*\\)\\)?\ +\\(?:-\\(?4:dirty\\)\\)\ +?\\'") + +(defvar magit-repolist-column-version-resume-regexp + "\\`Resume development\\'") + +(defun magit-repolist-column-version (_) + "Insert a description of the repository's `HEAD' revision." + (and-let* ((v (or (magit-git-string "describe" "--tags" "--dirty") + ;; If there are no tags, use the date in MELPA format. + (magit-rev-format "%cd-g%h" nil + "--date=format:%Y%m%d.%H%M")))) + (save-match-data + (when (string-match magit-repolist-column-version-regexp v) + (magit--put-face (match-beginning 0) (match-end 0) 'shadow v) + (when (match-end 2) + (magit--put-face (match-beginning 2) (match-end 2) 'bold v)) + (when (match-end 4) + (magit--put-face (or (match-beginning 3) (match-beginning 4)) + (match-end 4) 'error v)) + (when (and (equal (match-string 2 v) "1") + (string-match-p magit-repolist-column-version-resume-regexp + (magit-rev-format "%s"))) + (setq v (replace-match (propertize "+" 'face 'shadow) t t v 1)))) + (if (and v (string-match "\\`[0-9]" v)) + (concat " " v) + (when (and v (string-match "\\`[^0-9]+" v)) + (magit--put-face 0 (match-end 0) 'shadow v)) + v)))) + +(defun magit-repolist-version< (a b) + (save-match-data + (let ((re "[0-9]+\\(\\.[0-9]*\\)*")) + (setq a (and (string-match re a) (match-string 0 a))) + (setq b (and (string-match re b) (match-string 0 b))) + (cond ((and a b) (version< a b)) + (b nil) + (t t))))) + +(defun magit-repolist-column-branch (_) + "Insert the current branch." + (let ((branch (magit-get-current-branch))) + (if (member branch magit-main-branch-names) + (magit--propertize-face branch 'shadow) + branch))) + +(defun magit-repolist-column-upstream (_) + "Insert the upstream branch of the current branch." + (magit-get-upstream-branch)) + +(defun magit-repolist-column-flag (_) + "Insert a flag as specified by `magit-repolist-column-flag-alist'. + +By default this indicates whether there are uncommitted changes. +- N if there is at least one untracked file. +- U if there is at least one unstaged file. +- S if there is at least one staged file. +Only one letter is shown, the first that applies." + (seq-some (pcase-lambda (`(,fun . ,flag)) + (and (funcall fun) flag)) + magit-repolist-column-flag-alist)) + +(defun magit-repolist-column-flags (_) + "Insert all flags as specified by `magit-repolist-column-flag-alist'. +This is an alternative to function `magit-repolist-column-flag', +which only lists the first one found." + (mapconcat (pcase-lambda (`(,fun . ,flag)) + (if (funcall fun) flag " ")) + magit-repolist-column-flag-alist + "")) + +(defun magit-repolist-column-unpulled-from-upstream (spec) + "Insert number of upstream commits not in the current branch." + (and-let* ((br (magit-get-upstream-branch))) + (magit-repolist-insert-count (cadr (magit-rev-diff-count "HEAD" br)) spec))) + +(defun magit-repolist-column-unpulled-from-pushremote (spec) + "Insert number of commits in the push branch but not the current branch." + (and-let* ((br (magit-get-push-branch nil t))) + (magit-repolist-insert-count (cadr (magit-rev-diff-count "HEAD" br)) spec))) + +(defun magit-repolist-column-unpushed-to-upstream (spec) + "Insert number of commits in the current branch but not its upstream." + (and-let* ((br (magit-get-upstream-branch))) + (magit-repolist-insert-count (car (magit-rev-diff-count "HEAD" br)) spec))) + +(defun magit-repolist-column-unpushed-to-pushremote (spec) + "Insert number of commits in the current branch but not its push branch." + (and-let* ((br (magit-get-push-branch nil t))) + (magit-repolist-insert-count (car (magit-rev-diff-count "HEAD" br)) spec))) + +(defun magit-repolist-column-branches (spec) + "Insert number of branches." + (magit-repolist-insert-count (length (magit-list-local-branches)) + `((:normal-count 1) ,@spec))) + +(defun magit-repolist-column-stashes (spec) + "Insert number of stashes." + (magit-repolist-insert-count (length (magit-list-stashes)) spec)) + +(defun magit-repolist-insert-count (n spec) + (magit--propertize-face + (if (and (> n 9) (= (cadr (assq :width spec)) 1)) + "+" + (number-to-string n)) + (if (> n (or (cadr (assq :normal-count spec)) 0)) 'bold 'shadow))) + +;;; Read Repository + +(defun magit-read-repository (&optional read-directory-name) + "Read a Git repository in the minibuffer, with completion. + +The completion choices are the basenames of top-levels of +repositories found in the directories specified by option +`magit-repository-directories'. In case of name conflicts +the basenames are prefixed with the name of the respective +parent directories. The returned value is the actual path +to the selected repository. + +If READ-DIRECTORY-NAME is non-nil or no repositories can be +found based on the value of `magit-repository-directories', +then read an arbitrary directory using `read-directory-name' +instead." + (if-let ((repos (and (not read-directory-name) + magit-repository-directories + (magit-repos-alist)))) + (let ((reply (magit-completing-read "Git repository" repos))) + (file-name-as-directory + (or (cdr (assoc reply repos)) + (if (file-directory-p reply) + (expand-file-name reply) + (user-error "Not a repository or a directory: %s" reply))))) + (file-name-as-directory + (read-directory-name "Git repository: " + (or (magit-toplevel) default-directory))))) + +(defun magit-list-repos () + (cl-mapcan (pcase-lambda (`(,dir . ,depth)) + (magit-list-repos-1 dir depth)) + magit-repository-directories)) + +(defun magit-list-repos-1 (directory depth) + (cond ((file-readable-p (expand-file-name ".git" directory)) + (list (file-name-as-directory directory))) + ((and (> depth 0) (file-accessible-directory-p directory)) + (--mapcat (and (file-directory-p it) + (magit-list-repos-1 it (1- depth))) + (directory-files directory t + directory-files-no-dot-files-regexp t))))) + +(defun magit-list-repos-uniquify (alist) + (let (result (dict (make-hash-table :test #'equal))) + (dolist (a (delete-dups alist)) + (puthash (car a) (cons (cdr a) (gethash (car a) dict)) dict)) + (maphash + (lambda (key value) + (if (length= value 1) + (push (cons key (car value)) result) + (setq result + (append result + (magit-list-repos-uniquify + (--map (cons (concat + key "\\" + (file-name-nondirectory + (directory-file-name + (substring it 0 (- (1+ (length key))))))) + it) + value)))))) + dict) + result)) + +(defun magit-repos-alist () + (magit-list-repos-uniquify + (--map (cons (file-name-nondirectory (directory-file-name it)) it) + (magit-list-repos)))) + +;;; _ +(provide 'magit-repos) +;;; magit-repos.el ends here diff --git a/emacs/elpa/magit-20241004.917/magit-reset.el b/emacs/elpa/magit-20241004.917/magit-reset.el @@ -0,0 +1,137 @@ +;;; magit-reset.el --- Reset functionality -*- lexical-binding:t -*- + +;; Copyright (C) 2008-2024 The Magit Project Contributors + +;; Author: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> +;; Maintainer: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> + +;; SPDX-License-Identifier: GPL-3.0-or-later + +;; Magit is free software: you can redistribute it and/or modify it +;; under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. +;; +;; Magit is distributed in the hope that it will be useful, but WITHOUT +;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +;; or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public +;; License for more details. +;; +;; You should have received a copy of the GNU General Public License +;; along with Magit. If not, see <https://www.gnu.org/licenses/>. + +;;; Commentary: + +;; This library implements reset commands. + +;;; Code: + +(require 'magit) + +;;; Commands + +;;;###autoload (autoload 'magit-reset "magit" nil t) +(transient-define-prefix magit-reset () + "Reset the `HEAD', index and/or worktree to a previous state." + :man-page "git-reset" + [["Reset" + ("b" "branch" magit-branch-reset) + ("f" "file" magit-file-checkout)] + ["Reset this" + ("m" "mixed (HEAD and index)" magit-reset-mixed) + ("s" "soft (HEAD only)" magit-reset-soft) + ("h" "hard (HEAD, index and worktree)" magit-reset-hard) + ("k" "keep (HEAD and index, keeping uncommitted)" magit-reset-keep) + ("i" "index (only)" magit-reset-index) + ("w" "worktree (only)" magit-reset-worktree)]]) + +;;;###autoload +(defun magit-reset-mixed (commit) + "Reset the `HEAD' and index to COMMIT, but not the working tree. +\n(git reset --mixed COMMIT)" + (interactive (list (magit-reset-read-branch-or-commit "Reset %s to"))) + (magit-reset-internal "--mixed" commit)) + +;;;###autoload +(defun magit-reset-soft (commit) + "Reset the `HEAD' to COMMIT, but not the index and working tree. +\n(git reset --soft REVISION)" + (interactive (list (magit-reset-read-branch-or-commit "Soft reset %s to"))) + (magit-reset-internal "--soft" commit)) + +;;;###autoload +(defun magit-reset-hard (commit) + "Reset the `HEAD', index, and working tree to COMMIT. +\n(git reset --hard REVISION)" + (interactive (list (magit-reset-read-branch-or-commit + (concat (magit--propertize-face "Hard" 'bold) + " reset %s to")))) + (magit-reset-internal "--hard" commit)) + +;;;###autoload +(defun magit-reset-keep (commit) + "Reset the `HEAD' and index to COMMIT, while keeping uncommitted changes. +\n(git reset --keep REVISION)" + (interactive (list (magit-reset-read-branch-or-commit "Reset %s to"))) + (magit-reset-internal "--keep" commit)) + +;;;###autoload +(defun magit-reset-index (commit) + "Reset the index to COMMIT. +Keep the `HEAD' and working tree as-is, so if COMMIT refers to the +head this effectively unstages all changes. +\n(git reset COMMIT .)" + (interactive (list (magit-read-branch-or-commit "Reset index to"))) + (magit-reset-internal nil commit ".")) + +;;;###autoload +(defun magit-reset-worktree (commit) + "Reset the worktree to COMMIT. +Keep the `HEAD' and index as-is." + (interactive (list (magit-read-branch-or-commit "Reset worktree to"))) + (magit-wip-commit-before-change nil " before reset") + (magit-with-temp-index commit nil + (magit-call-git "checkout-index" "--all" "--force")) + (magit-wip-commit-after-apply nil " after reset") + (magit-refresh)) + +;;;###autoload +(defun magit-reset-quickly (commit &optional hard) + "Reset the `HEAD' and index to COMMIT, and possibly the working tree. +With a prefix argument reset the working tree otherwise don't. +\n(git reset --mixed|--hard COMMIT)" + (interactive (list (magit-reset-read-branch-or-commit + (if current-prefix-arg + (concat (magit--propertize-face "Hard" 'bold) + " reset %s to") + "Reset %s to")) + current-prefix-arg)) + (magit-reset-internal (if hard "--hard" "--mixed") commit)) + +(defun magit-reset-read-branch-or-commit (prompt) + "Prompt for and return a ref to reset HEAD to. + +PROMPT is a format string, where either the current branch name +or \"detached head\" will be substituted for %s." + (magit-read-branch-or-commit + (format prompt (or (magit-get-current-branch) "detached head")))) + +(defun magit-reset-internal (arg commit &optional path) + (when (and (not (member arg '("--hard" nil))) + (equal (magit-rev-parse commit) + (magit-rev-parse "HEAD~"))) + (with-temp-buffer + (magit-git-insert "show" "-s" "--format=%B" "HEAD") + (when git-commit-major-mode + (funcall git-commit-major-mode)) + (git-commit-setup-font-lock) + (git-commit-save-message))) + (let ((cmd (if (and (equal commit "HEAD") (not arg)) "unstage" "reset"))) + (magit-wip-commit-before-change nil (concat " before " cmd)) + (magit-run-git "reset" arg commit "--" path) + (when (equal cmd "unstage") + (magit-wip-commit-after-apply nil " after unstage")))) + +;;; _ +(provide 'magit-reset) +;;; magit-reset.el ends here diff --git a/emacs/elpa/magit-20241004.917/magit-sequence.el b/emacs/elpa/magit-20241004.917/magit-sequence.el @@ -0,0 +1,1124 @@ +;;; magit-sequence.el --- History manipulation in Magit -*- lexical-binding:t -*- + +;; Copyright (C) 2008-2024 The Magit Project Contributors + +;; Author: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> +;; Maintainer: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> + +;; SPDX-License-Identifier: GPL-3.0-or-later + +;; Magit is free software: you can redistribute it and/or modify it +;; under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. +;; +;; Magit is distributed in the hope that it will be useful, but WITHOUT +;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +;; or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public +;; License for more details. +;; +;; You should have received a copy of the GNU General Public License +;; along with Magit. If not, see <https://www.gnu.org/licenses/>. + +;;; Commentary: + +;; Support for Git commands that replay commits and help the user make +;; changes along the way. Supports `cherry-pick', `revert', `rebase', +;; `rebase--interactive' and `am'. + +;;; Code: + +(require 'magit) + +;; For `magit-rebase--todo'. +(declare-function git-rebase-current-line "git-rebase" ()) +(eval-when-compile + (cl-pushnew 'action-type eieio--known-slot-names) + (cl-pushnew 'action eieio--known-slot-names) + (cl-pushnew 'action-options eieio--known-slot-names) + (cl-pushnew 'target eieio--known-slot-names)) + +;;; Options +;;;; Faces + +(defface magit-sequence-pick + '((t :inherit default)) + "Face used in sequence sections." + :group 'magit-faces) + +(defface magit-sequence-stop + '((((class color) (background light)) :foreground "DarkOliveGreen4") + (((class color) (background dark)) :foreground "DarkSeaGreen2")) + "Face used in sequence sections." + :group 'magit-faces) + +(defface magit-sequence-part + '((((class color) (background light)) :foreground "Goldenrod4") + (((class color) (background dark)) :foreground "LightGoldenrod2")) + "Face used in sequence sections." + :group 'magit-faces) + +(defface magit-sequence-head + '((((class color) (background light)) :foreground "SkyBlue4") + (((class color) (background dark)) :foreground "LightSkyBlue1")) + "Face used in sequence sections." + :group 'magit-faces) + +(defface magit-sequence-drop + '((((class color) (background light)) :foreground "IndianRed") + (((class color) (background dark)) :foreground "IndianRed")) + "Face used in sequence sections." + :group 'magit-faces) + +(defface magit-sequence-done + '((t :inherit magit-hash)) + "Face used in sequence sections." + :group 'magit-faces) + +(defface magit-sequence-onto + '((t :inherit magit-sequence-done)) + "Face used in sequence sections." + :group 'magit-faces) + +(defface magit-sequence-exec + '((t :inherit magit-hash)) + "Face used in sequence sections." + :group 'magit-faces) + +;;; Common + +;;;###autoload +(defun magit-sequencer-continue () + "Resume the current cherry-pick or revert sequence." + (interactive) + (cond + ((not (magit-sequencer-in-progress-p)) + (user-error "No cherry-pick or revert in progress")) + ((magit-anything-unmerged-p) + (user-error "Cannot continue due to unresolved conflicts")) + ((magit-run-git-sequencer + (if (magit-revert-in-progress-p) "revert" "cherry-pick") "--continue")))) + +;;;###autoload +(defun magit-sequencer-skip () + "Skip the stopped at commit during a cherry-pick or revert sequence." + (interactive) + (unless (magit-sequencer-in-progress-p) + (user-error "No cherry-pick or revert in progress")) + (magit-call-git "reset" "--hard") + (magit-sequencer-continue)) + +;;;###autoload +(defun magit-sequencer-abort () + "Abort the current cherry-pick or revert sequence. +This discards all changes made since the sequence started." + (interactive) + (cond + ((not (magit-sequencer-in-progress-p)) + (user-error "No cherry-pick or revert in progress")) + ((magit-revert-in-progress-p) + (magit-confirm 'abort-revert "Really abort revert") + (magit-run-git-sequencer "revert" "--abort")) + ((magit-confirm 'abort-cherry-pick "Really abort cherry-pick") + (magit-run-git-sequencer "cherry-pick" "--abort")))) + +(defun magit-sequencer-in-progress-p () + (or (magit-cherry-pick-in-progress-p) + (magit-revert-in-progress-p))) + +;;; Cherry-Pick + +(defvar magit-perl-executable "perl" + "The Perl executable.") + +;;;###autoload (autoload 'magit-cherry-pick "magit-sequence" nil t) +(transient-define-prefix magit-cherry-pick () + "Apply or transplant commits." + :man-page "git-cherry-pick" + :value '("--ff") + :incompatible '(("--ff" "-x")) + ["Arguments" + :if-not magit-sequencer-in-progress-p + (magit-cherry-pick:--mainline) + ("=s" magit-merge:--strategy) + ("-F" "Attempt fast-forward" "--ff") + ("-x" "Reference cherry in commit message" "-x") + ("-e" "Edit commit messages" ("-e" "--edit")) + ("-s" "Add Signed-off-by lines" ("-s" "--signoff")) + (5 magit:--gpg-sign)] + [:if-not magit-sequencer-in-progress-p + ["Apply here" + ("A" "Pick" magit-cherry-copy) + ("a" "Apply" magit-cherry-apply) + ("h" "Harvest" magit-cherry-harvest) + ("m" "Squash" magit-merge-squash)] + ["Apply elsewhere" + ("d" "Donate" magit-cherry-donate) + ("n" "Spinout" magit-cherry-spinout) + ("s" "Spinoff" magit-cherry-spinoff)]] + ["Actions" + :if magit-sequencer-in-progress-p + ("A" "Continue" magit-sequencer-continue) + ("s" "Skip" magit-sequencer-skip) + ("a" "Abort" magit-sequencer-abort)]) + +(transient-define-argument magit-cherry-pick:--mainline () + :description "Replay merge relative to parent" + :class 'transient-option + :shortarg "-m" + :argument "--mainline=" + :reader #'transient-read-number-N+) + +(defun magit-cherry-pick-read-args (prompt) + (list (or (nreverse (magit-region-values 'commit)) + (magit-read-other-branch-or-commit prompt)) + (transient-args 'magit-cherry-pick))) + +(defun magit--cherry-move-read-args (verb away fn &optional allow-detached) + (declare (indent defun)) + (let ((commits (or (nreverse (magit-region-values 'commit)) + (list (funcall (if away + #'magit-read-branch-or-commit + #'magit-read-other-branch-or-commit) + (format "%s cherry" (capitalize verb)))))) + (current (or (magit-get-current-branch) + (and allow-detached (magit-rev-parse "HEAD"))))) + (unless current + (user-error "Cannot %s cherries while HEAD is detached" verb)) + (let ((reachable (magit-rev-ancestor-p (car commits) current)) + (msg "Cannot %s cherries that %s reachable from HEAD")) + (pcase (list away reachable) + ('(nil t) (user-error msg verb "are")) + ('(t nil) (user-error msg verb "are not")))) + `(,commits + ,@(funcall fn commits) + ,(transient-args 'magit-cherry-pick)))) + +(defun magit--cherry-spinoff-read-args (verb) + (magit--cherry-move-read-args verb t + (lambda (commits) + (magit-branch-read-args + (format "Create branch from %s cherries" (length commits)) + (magit-get-upstream-branch))))) + +;;;###autoload +(defun magit-cherry-copy (commits &optional args) + "Copy COMMITS from another branch onto the current branch. +Prompt for a commit, defaulting to the commit at point. If +the region selects multiple commits, then pick all of them, +without prompting." + (interactive (magit-cherry-pick-read-args "Cherry-pick")) + (magit--cherry-pick commits args)) + +;;;###autoload +(defun magit-cherry-apply (commits &optional args) + "Apply the changes in COMMITS but do not commit them. +Prompt for a commit, defaulting to the commit at point. If +the region selects multiple commits, then apply all of them, +without prompting." + (interactive (magit-cherry-pick-read-args "Apply changes from commit")) + (magit--cherry-pick commits (cons "--no-commit" (remove "--ff" args)))) + +;;;###autoload +(defun magit-cherry-harvest (commits branch &optional args) + "Move COMMITS from another BRANCH onto the current branch. +Remove the COMMITS from BRANCH and stay on the current branch. +If a conflict occurs, then you have to fix that and finish the +process manually." + (interactive + (magit--cherry-move-read-args "harvest" nil + (lambda (commits) + (list (let ((branches (magit-list-containing-branches (car commits)))) + (pcase (length branches) + (0 nil) + (1 (car branches)) + (_ (magit-completing-read + (let ((len (length commits))) + (if (= len 1) + "Remove 1 cherry from branch" + (format "Remove %s cherries from branch" len))) + branches nil t)))))))) + (magit--cherry-move commits branch (magit-get-current-branch) args nil t)) + +;;;###autoload +(defun magit-cherry-donate (commits branch &optional args) + "Move COMMITS from the current branch onto another existing BRANCH. +Remove COMMITS from the current branch and stay on that branch. +If a conflict occurs, then you have to fix that and finish the +process manually. `HEAD' is allowed to be detached initially." + (interactive + (magit--cherry-move-read-args "donate" t + (lambda (commits) + (list (magit-read-other-branch + (let ((len (length commits))) + (if (= len 1) + "Move 1 cherry to branch" + (format "Move %s cherries to branch" len)))))) + 'allow-detached)) + (magit--cherry-move commits + (or (magit-get-current-branch) + (magit-rev-parse "HEAD")) + branch args)) + +;;;###autoload +(defun magit-cherry-spinout (commits branch start-point &optional args) + "Move COMMITS from the current branch onto a new BRANCH. +Remove COMMITS from the current branch and stay on that branch. +If a conflict occurs, then you have to fix that and finish the +process manually." + (interactive (magit--cherry-spinoff-read-args "spinout")) + (magit--cherry-move commits (magit-get-current-branch) branch args + start-point)) + +;;;###autoload +(defun magit-cherry-spinoff (commits branch start-point &optional args) + "Move COMMITS from the current branch onto a new BRANCH. +Remove COMMITS from the current branch and checkout BRANCH. +If a conflict occurs, then you have to fix that and finish +the process manually." + (interactive (magit--cherry-spinoff-read-args "spinoff")) + (magit--cherry-move commits (magit-get-current-branch) branch args + start-point t)) + +(defun magit--cherry-move (commits src dst args + &optional start-point checkout-dst) + (let ((current (magit-get-current-branch))) + (unless (magit-branch-p dst) + (let ((magit-process-raise-error t)) + (magit-call-git "branch" dst start-point)) + (when-let ((upstream (magit-get-indirect-upstream-branch start-point))) + (magit-call-git "branch" "--set-upstream-to" upstream dst))) + (unless (equal dst current) + (let ((magit-process-raise-error t)) + (magit-call-git "checkout" dst))) + (if (not src) ; harvest only + (magit--cherry-pick commits args) + (let ((tip (car (last commits))) + (keep (concat (car commits) "^"))) + (magit--cherry-pick commits args) + (set-process-sentinel + magit-this-process + (lambda (process event) + (when (memq (process-status process) '(exit signal)) + (if (> (process-exit-status process) 0) + (magit-process-sentinel process event) + (process-put process 'inhibit-refresh t) + (magit-process-sentinel process event) + (cond + ((magit-rev-equal tip src) + (magit-call-git "update-ref" + "-m" (format "reset: moving to %s" keep) + (magit-ref-fullname src) + keep tip) + (if (not checkout-dst) + (magit-run-git "checkout" src) + (magit-refresh))) + (t + (magit-git "checkout" src) + (with-environment-variables + (("GIT_SEQUENCE_EDITOR" + (format "%s -i -ne '/^pick (%s)/ or print'" + magit-perl-executable + (mapconcat #'magit-rev-abbrev commits "|")))) + (magit-run-git-sequencer "rebase" "-i" keep)) + (when checkout-dst + (set-process-sentinel + magit-this-process + (lambda (process event) + (when (memq (process-status process) '(exit signal)) + (if (> (process-exit-status process) 0) + (magit-process-sentinel process event) + (process-put process 'inhibit-refresh t) + (magit-process-sentinel process event) + (magit-run-git "checkout" dst)))))))))))))))) + +(defun magit--cherry-pick (commits args &optional revert) + (let ((command (if revert "revert" "cherry-pick"))) + (when (stringp commits) + (setq commits (if (string-search ".." commits) + (split-string commits "\\.\\.") + (list commits)))) + (magit-run-git-sequencer + (if revert "revert" "cherry-pick") + (let ((merges (seq-filter #'magit-merge-commit-p commits))) + (cond + ((not merges) + (--remove (string-prefix-p "--mainline=" it) args)) + ((cl-set-difference commits merges :test #'equal) + (user-error "Cannot %s merge and non-merge commits at once" + command)) + ((--first (string-prefix-p "--mainline=" it) args) + args) + (t + (cons (format "--mainline=%s" + (read-number "Replay merges relative to parent: ")) + args)))) + commits))) + +(defun magit-cherry-pick-in-progress-p () + ;; .git/sequencer/todo does not exist when there is only one commit left. + (let ((dir (magit-gitdir))) + (or (file-exists-p (expand-file-name "CHERRY_PICK_HEAD" dir)) + ;; And CHERRY_PICK_HEAD does not exist when a conflict happens + ;; while picking a series of commits with --no-commit. + (and-let* ((line (magit-file-line + (expand-file-name "sequencer/todo" dir)))) + (string-prefix-p "pick" line))))) + +;;; Revert + +;;;###autoload (autoload 'magit-revert "magit-sequence" nil t) +(transient-define-prefix magit-revert () + "Revert existing commits, with or without creating new commits." + :man-page "git-revert" + :value '("--edit") + ["Arguments" + :if-not magit-sequencer-in-progress-p + (magit-cherry-pick:--mainline) + ("-e" "Edit commit message" ("-e" "--edit")) + ("-E" "Don't edit commit message" "--no-edit") + ("=s" magit-merge:--strategy) + ("-s" "Add Signed-off-by lines" ("-s" "--signoff")) + (5 magit:--gpg-sign)] + ["Actions" + :if-not magit-sequencer-in-progress-p + ("V" "Revert commit(s)" magit-revert-and-commit) + ("v" "Revert changes" magit-revert-no-commit)] + ["Actions" + :if magit-sequencer-in-progress-p + ("V" "Continue" magit-sequencer-continue) + ("s" "Skip" magit-sequencer-skip) + ("a" "Abort" magit-sequencer-abort)]) + +(defun magit-revert-read-args (prompt) + (list (or (magit-region-values 'commit) + (magit-read-branch-or-commit prompt)) + (transient-args 'magit-revert))) + +;;;###autoload +(defun magit-revert-and-commit (commit &optional args) + "Revert COMMIT by creating a new commit. +Prompt for a commit, defaulting to the commit at point. If +the region selects multiple commits, then revert all of them, +without prompting." + (interactive (magit-revert-read-args "Revert commit")) + (magit--cherry-pick commit args t)) + +;;;###autoload +(defun magit-revert-no-commit (commit &optional args) + "Revert COMMIT by applying it in reverse to the worktree. +Prompt for a commit, defaulting to the commit at point. If +the region selects multiple commits, then revert all of them, +without prompting." + (interactive (magit-revert-read-args "Revert changes")) + (magit--cherry-pick commit (cons "--no-commit" args) t)) + +(defun magit-revert-in-progress-p () + ;; .git/sequencer/todo does not exist when there is only one commit left. + (let ((dir (magit-gitdir))) + (or (file-exists-p (expand-file-name "REVERT_HEAD" dir)) + ;; And REVERT_HEAD does not exist when a conflict happens + ;; while reverting a series of commits with --no-commit. + (and-let* ((line (magit-file-line + (expand-file-name "sequencer/todo" dir)))) + (string-prefix-p "revert" line))))) + +;;; Patch + +;;;###autoload (autoload 'magit-am "magit-sequence" nil t) +(transient-define-prefix magit-am () + "Apply patches received by email." + :man-page "git-am" + :value '("--3way") + ["Arguments" + :if-not magit-am-in-progress-p + ("-3" "Fall back on 3way merge" ("-3" "--3way")) + (magit-apply:-p) + ("-c" "Remove text before scissors line" ("-c" "--scissors")) + ("-k" "Inhibit removal of email cruft" ("-k" "--keep")) + ("-b" "Limit removal of email cruft" "--keep-non-patch") + ("-d" "Use author date as committer date" "--committer-date-is-author-date") + ("-t" "Use current time as author date" "--ignore-date") + ("-s" "Add Signed-off-by lines" ("-s" "--signoff")) + (5 magit:--gpg-sign)] + ["Apply" + :if-not magit-am-in-progress-p + ("m" "maildir" magit-am-apply-maildir) + ("w" "patches" magit-am-apply-patches) + ("a" "plain patch" magit-patch-apply)] + ["Actions" + :if magit-am-in-progress-p + ("w" "Continue" magit-am-continue) + ("s" "Skip" magit-am-skip) + ("a" "Abort" magit-am-abort)]) + +(defun magit-am-arguments () + (transient-args 'magit-am)) + +(transient-define-argument magit-apply:-p () + :description "Remove leading slashes from paths" + :class 'transient-option + :argument "-p" + :allow-empty t + :reader #'transient-read-number-N+) + +;;;###autoload +(defun magit-am-apply-patches (&optional files args) + "Apply the patches FILES." + (interactive (list (or (magit-region-values 'file) + (list (let ((default (magit-file-at-point))) + (read-file-name + (if default + (format "Apply patch (%s): " default) + "Apply patch: ") + nil default)))) + (magit-am-arguments))) + (magit-run-git-sequencer "am" args "--" + (--map (magit-convert-filename-for-git + (expand-file-name it)) + files))) + +;;;###autoload +(defun magit-am-apply-maildir (&optional maildir args) + "Apply the patches from MAILDIR." + (interactive (list (read-file-name "Apply mbox or Maildir: ") + (magit-am-arguments))) + (magit-run-git-sequencer "am" args (magit-convert-filename-for-git + (expand-file-name maildir)))) + +;;;###autoload +(defun magit-am-continue () + "Resume the current patch applying sequence." + (interactive) + (cond + ((not (magit-am-in-progress-p)) + (user-error "Not applying any patches")) + ((magit-anything-unstaged-p t) + (user-error "Cannot continue due to unstaged changes")) + ((magit-run-git-sequencer "am" "--continue")))) + +;;;###autoload +(defun magit-am-skip () + "Skip the stopped at patch during a patch applying sequence." + (interactive) + (unless (magit-am-in-progress-p) + (user-error "Not applying any patches")) + (magit-run-git-sequencer "am" "--skip")) + +;;;###autoload +(defun magit-am-abort () + "Abort the current patch applying sequence. +This discards all changes made since the sequence started." + (interactive) + (unless (magit-am-in-progress-p) + (user-error "Not applying any patches")) + (magit-run-git "am" "--abort")) + +(defun magit-am-in-progress-p () + (file-exists-p (expand-file-name "rebase-apply/applying" (magit-gitdir)))) + +;;; Rebase + +;;;###autoload (autoload 'magit-rebase "magit-sequence" nil t) +(transient-define-prefix magit-rebase () + "Transplant commits and/or modify existing commits." + :man-page "git-rebase" + :value '("--autostash") + ["Arguments" + :if-not magit-rebase-in-progress-p + ("-k" "Keep empty commits" "--keep-empty") + ("-p" "Preserve merges" ("-p" "--preserve-merges") + :if (lambda () (magit-git-version< "2.33.0"))) + ("-r" "Rebase merges" ("-r" "--rebase-merges=") + magit-rebase-merges-select-mode + :if (lambda () (magit-git-version>= "2.18.0"))) + ("-u" "Update branches" "--update-refs" + :if (lambda () (magit-git-version>= "2.38.0"))) + (7 magit-merge:--strategy) + (7 magit-merge:--strategy-option) + (7 "=X" magit-diff:--diff-algorithm :argument "-Xdiff-algorithm=") + (7 "-f" "Force rebase" ("-f" "--force-rebase")) + ("-d" "Use author date as committer date" "--committer-date-is-author-date") + ("-t" "Use current time as author date" "--ignore-date") + ("-a" "Autosquash" "--autosquash") + ("-A" "Autostash" "--autostash") + ("-i" "Interactive" ("-i" "--interactive")) + ("-h" "Disable hooks" "--no-verify") + (7 magit-rebase:--exec) + (5 magit:--gpg-sign)] + [:if-not magit-rebase-in-progress-p + :description (lambda () + (format (propertize "Rebase %s onto" 'face 'transient-heading) + (propertize (or (magit-get-current-branch) "HEAD") + 'face 'magit-branch-local))) + ("p" magit-rebase-onto-pushremote) + ("u" magit-rebase-onto-upstream) + ("e" "elsewhere" magit-rebase-branch)] + ["Rebase" + :if-not magit-rebase-in-progress-p + [("i" "interactively" magit-rebase-interactive) + ("s" "a subset" magit-rebase-subset)] + [("m" "to modify a commit" magit-rebase-edit-commit) + ("w" "to reword a commit" magit-rebase-reword-commit) + ("k" "to remove a commit" magit-rebase-remove-commit) + ("f" "to autosquash" magit-rebase-autosquash) + (6 "t" "to change dates" magit-reshelve-since)]] + ["Actions" + :if magit-rebase-in-progress-p + ("r" "Continue" magit-rebase-continue) + ("s" "Skip" magit-rebase-skip) + ("e" "Edit" magit-rebase-edit) + ("a" "Abort" magit-rebase-abort)]) + +(transient-define-argument magit-rebase:--exec () + :description "Run command after commits" + :class 'transient-option + :shortarg "-x" + :argument "--exec=" + :reader #'read-shell-command) + +(defun magit-rebase-merges-select-mode (&rest _ignore) + (magit-read-char-case nil t + (?n "[n]o-rebase-cousins" "no-rebase-cousins") + (?r "[r]ebase-cousins" "rebase-cousins"))) + +(defun magit-rebase-arguments () + (transient-args 'magit-rebase)) + +(defun magit-git-rebase (target args) + (magit-run-git-sequencer "rebase" args target)) + +;;;###autoload (autoload 'magit-rebase-onto-pushremote "magit-sequence" nil t) +(transient-define-suffix magit-rebase-onto-pushremote (args) + "Rebase the current branch onto its push-remote branch. + +With a prefix argument or when the push-remote is either not +configured or unusable, then let the user first configure the +push-remote." + :if #'magit-get-current-branch + :description #'magit-pull--pushbranch-description + (interactive (list (magit-rebase-arguments))) + (pcase-let ((`(,branch ,remote) + (magit--select-push-remote "rebase onto that"))) + (magit-git-rebase (concat remote "/" branch) args))) + +;;;###autoload (autoload 'magit-rebase-onto-upstream "magit-sequence" nil t) +(transient-define-suffix magit-rebase-onto-upstream (args) + "Rebase the current branch onto its upstream branch. + +With a prefix argument or when the upstream is either not +configured or unusable, then let the user first configure +the upstream." + :if #'magit-get-current-branch + :description #'magit-rebase--upstream-description + (interactive (list (magit-rebase-arguments))) + (let* ((branch (or (magit-get-current-branch) + (user-error "No branch is checked out"))) + (upstream (magit-get-upstream-branch branch))) + (when (or current-prefix-arg (not upstream)) + (setq upstream + (magit-read-upstream-branch + branch (format "Set upstream of %s and rebase onto that" branch))) + (magit-set-upstream-branch branch upstream)) + (magit-git-rebase upstream args))) + +(defun magit-rebase--upstream-description () + (and-let* ((branch (magit-get-current-branch))) + (or (magit-get-upstream-branch branch) + (let ((remote (magit-get "branch" branch "remote")) + (merge (magit-get "branch" branch "merge")) + (u (magit--propertize-face "@{upstream}" 'bold))) + (cond + ((magit--unnamed-upstream-p remote merge) + (concat u ", replacing unnamed")) + ((magit--valid-upstream-p remote merge) + (concat u ", replacing non-existent")) + ((or remote merge) + (concat u ", replacing invalid")) + (t + (concat u ", setting that"))))))) + +;;;###autoload +(defun magit-rebase-branch (target args) + "Rebase the current branch onto a branch read in the minibuffer. +All commits that are reachable from `HEAD' but not from the +selected branch TARGET are being rebased." + (interactive (list (magit-read-other-branch-or-commit "Rebase onto") + (magit-rebase-arguments))) + (message "Rebasing...") + (magit-git-rebase target args) + (message "Rebasing...done")) + +;;;###autoload +(defun magit-rebase-subset (newbase start args) + "Rebase a subset of the current branch's history onto a new base. +Rebase commits from START to `HEAD' onto NEWBASE. +START has to be selected from a list of recent commits." + (interactive (list (magit-read-other-branch-or-commit + "Rebase subset onto" nil + (magit-get-upstream-branch)) + nil + (magit-rebase-arguments))) + (if start + (progn (message "Rebasing...") + (magit-run-git-sequencer "rebase" "--onto" newbase start args) + (message "Rebasing...done")) + (magit-log-select + `(lambda (commit) + (magit-rebase-subset ,newbase (concat commit "^") (list ,@args))) + (concat "Type %p on a commit to rebase it " + "and commits above it onto " newbase ",")))) + +(defvar magit-rebase-interactive-include-selected t) + +(defun magit-rebase-interactive-1 + (commit args message &optional editor delay-edit-confirm noassert confirm) + (declare (indent 2)) + (when commit + (if (eq commit :merge-base) + (setq commit + (and-let* ((upstream (magit-get-upstream-branch))) + (magit-git-string "merge-base" upstream "HEAD"))) + (unless (magit-rev-ancestor-p commit "HEAD") + (user-error "%s isn't an ancestor of HEAD" commit)) + (if (magit-commit-parents commit) + (when (or (not (eq this-command 'magit-rebase-interactive)) + magit-rebase-interactive-include-selected) + (setq commit (concat commit "^"))) + (setq args (cons "--root" args))))) + (when (and commit (not noassert)) + (setq commit (magit-rebase-interactive-assert + commit delay-edit-confirm + (--some (string-prefix-p "--rebase-merges" it) args)))) + (if (and commit (not confirm)) + (let ((process-environment process-environment)) + (when editor + (push (concat "GIT_SEQUENCE_EDITOR=" + (if (functionp editor) + (funcall editor commit) + editor)) + process-environment)) + (magit-run-git-sequencer "rebase" "-i" args + (and (not (member "--root" args)) commit))) + (magit-log-select + `(lambda (commit) + ;; In some cases (currently just magit-rebase-remove-commit), "-c + ;; commentChar=#" is added to the global arguments for git. Ensure + ;; that the same happens when we chose the commit via + ;; magit-log-select, below. + (let ((magit-git-global-arguments (list ,@magit-git-global-arguments))) + (magit-rebase-interactive-1 commit (list ,@args) + ,message ,editor ,delay-edit-confirm ,noassert))) + message))) + +(defvar magit--rebase-published-symbol nil) +(defvar magit--rebase-public-edit-confirmed nil) + +(defun magit-rebase-interactive-assert + (since &optional delay-edit-confirm rebase-merges) + (let* ((commit (magit-rebase--target-commit since)) + (branches (magit-list-publishing-branches commit))) + (setq magit--rebase-public-edit-confirmed + (delete (magit-toplevel) magit--rebase-public-edit-confirmed)) + (when (and branches + (or (not delay-edit-confirm) + ;; The user might have stopped at a published commit + ;; merely to add new commits *after* it. Try not to + ;; ask users whether they really want to edit public + ;; commits, when they don't actually intend to do so. + (not (--all-p (magit-rev-equal it commit) branches)))) + (let ((m1 "Some of these commits have already been published to ") + (m2 ".\nDo you really want to modify them")) + (magit-confirm (or magit--rebase-published-symbol 'rebase-published) + (concat m1 "%s" m2) + (concat m1 "%d public branches" m2) + nil branches)) + (push (magit-toplevel) magit--rebase-public-edit-confirmed))) + (if (and (magit-git-lines "rev-list" "--merges" (concat since "..HEAD")) + (not rebase-merges)) + (magit-read-char-case "Proceed despite merge in rebase range? " nil + (?c "[c]ontinue" since) + (?s "[s]elect other" nil) + (?a "[a]bort" (user-error "Quit"))) + since)) + +(defun magit-rebase--target-commit (since) + (if (string-suffix-p "^" since) + ;; If SINCE is "REV^", then the user selected + ;; "REV", which is the first commit that will + ;; be replaced. (from^..to] <=> [from..to] + (substring since 0 -1) + ;; The "--root" argument is being used. + since)) + +;;;###autoload +(defun magit-rebase-interactive (commit args) + "Start an interactive rebase sequence." + (interactive (list (magit-commit-at-point) + (magit-rebase-arguments))) + (magit-rebase-interactive-1 commit args + "Type %p on a commit to rebase it and all commits above it," + nil t)) + +;;;###autoload +(defun magit-rebase-autosquash (args) + "Combine squash and fixup commits with their intended targets." + (interactive (list (magit-rebase-arguments))) + (magit-rebase-interactive-1 :merge-base + (nconc (list "--autosquash" "--keep-empty") args) + "Type %p on a commit to squash into it and then rebase as necessary," + "true" nil t)) + +;;;###autoload +(defun magit-rebase-edit-commit (commit args) + "Edit a single older commit using rebase." + (interactive (list (magit-commit-at-point) + (magit-rebase-arguments))) + (magit-rebase-interactive-1 commit args + "Type %p on a commit to edit it," + (apply-partially #'magit-rebase--perl-editor 'edit) + t)) + +;;;###autoload +(defun magit-rebase-reword-commit (commit args) + "Reword a single older commit using rebase." + (interactive (list (magit-commit-at-point) + (magit-rebase-arguments))) + (magit-rebase-interactive-1 commit args + "Type %p on a commit to reword its message," + (apply-partially #'magit-rebase--perl-editor 'reword))) + +;;;###autoload +(defun magit-rebase-remove-commit (commit args) + "Remove a single older commit using rebase." + (interactive (list (magit-commit-at-point) + (magit-rebase-arguments))) + ;; magit-rebase--perl-editor assumes that the comment character is "#". + (let ((magit-git-global-arguments + (nconc (list "-c" "core.commentChar=#") + magit-git-global-arguments))) + (magit-rebase-interactive-1 commit args + "Type %p on a commit to remove it," + (apply-partially #'magit-rebase--perl-editor 'remove) + nil nil t))) + +(defun magit-rebase--perl-editor (action since) + (let ((commit (magit-rev-abbrev (magit-rebase--target-commit since)))) + (format "%s -i -p -e '++$x if not $x and s/^pick %s/%s %s/'" + magit-perl-executable + commit + (cl-case action + (edit "edit") + (remove "noop\n# pick") + (reword "reword") + (t (error "unknown action: %s" action))) + commit))) + +;;;###autoload +(defun magit-rebase-continue (&optional noedit) + "Restart the current rebasing operation. +In some cases this pops up a commit message buffer for you do +edit. With a prefix argument the old message is reused as-is." + (interactive "P") + (if (magit-rebase-in-progress-p) + (if (magit-anything-unstaged-p t) + (user-error "Cannot continue rebase with unstaged changes") + (let ((dir (magit-gitdir))) + (when (and (magit-anything-staged-p) + (file-exists-p (expand-file-name "rebase-merge" dir)) + (not (member (magit-toplevel) + magit--rebase-public-edit-confirmed))) + (magit-commit-amend-assert + (magit-file-line + (expand-file-name "rebase-merge/orig-head" dir))))) + (if noedit + (with-environment-variables (("GIT_EDITOR" "true")) + (magit-run-git-async (magit--rebase-resume-command) "--continue") + (set-process-sentinel magit-this-process + #'magit-sequencer-process-sentinel) + magit-this-process) + (magit-run-git-sequencer (magit--rebase-resume-command) "--continue"))) + (user-error "No rebase in progress"))) + +;;;###autoload +(defun magit-rebase-skip () + "Skip the current commit and restart the current rebase operation." + (interactive) + (unless (magit-rebase-in-progress-p) + (user-error "No rebase in progress")) + (magit-run-git-sequencer (magit--rebase-resume-command) "--skip")) + +;;;###autoload +(defun magit-rebase-edit () + "Edit the todo list of the current rebase operation." + (interactive) + (unless (magit-rebase-in-progress-p) + (user-error "No rebase in progress")) + (magit-run-git-sequencer "rebase" "--edit-todo")) + +;;;###autoload +(defun magit-rebase-abort () + "Abort the current rebase operation, restoring the original branch." + (interactive) + (unless (magit-rebase-in-progress-p) + (user-error "No rebase in progress")) + (magit-confirm 'abort-rebase "Abort this rebase") + (magit-run-git (magit--rebase-resume-command) "--abort")) + +(defun magit-rebase-in-progress-p () + "Return t if a rebase is in progress." + (let ((dir (magit-gitdir))) + (or (file-exists-p (expand-file-name "rebase-merge" dir)) + (file-exists-p (expand-file-name "rebase-apply/onto" dir))))) + +(defun magit--rebase-resume-command () + (if (file-exists-p (expand-file-name "rebase-recursive" (magit-gitdir))) + "rbr" + "rebase")) + +(defun magit-rebase--get-state-lines (file) + (and (magit-rebase-in-progress-p) + (let ((dir (magit-gitdir))) + (magit-file-line + (expand-file-name + (concat (if (file-directory-p (expand-file-name "rebase-merge" dir)) + "rebase-merge/" + "rebase-apply/") + file) + dir))))) + +;;; Sections + +(defun magit-insert-sequencer-sequence () + "Insert section for the on-going cherry-pick or revert sequence. +If no such sequence is in progress, do nothing." + (let ((picking (magit-cherry-pick-in-progress-p))) + (when (or picking (magit-revert-in-progress-p)) + (let ((dir (magit-gitdir))) + (magit-insert-section (sequence) + (magit-insert-heading (if picking "Cherry Picking" "Reverting")) + (when-let ((lines (cdr (magit-file-lines + (expand-file-name "sequencer/todo" dir))))) + (dolist (line (nreverse lines)) + (when (string-match + "^\\(pick\\|revert\\) \\([^ ]+\\) \\(.*\\)$" line) + (magit-bind-match-strings (cmd hash msg) line + (magit-insert-section (commit hash) + (insert (propertize cmd 'font-lock-face 'magit-sequence-pick) + " " (propertize hash 'font-lock-face 'magit-hash) + " " msg "\n")))))) + (magit-sequence-insert-sequence + (magit-file-line + (expand-file-name (if picking "CHERRY_PICK_HEAD" "REVERT_HEAD") + dir)) + (magit-file-line (expand-file-name "sequencer/head" dir))) + (insert "\n")))))) + +(defun magit-insert-am-sequence () + "Insert section for the on-going patch applying sequence. +If no such sequence is in progress, do nothing." + (when (magit-am-in-progress-p) + (magit-insert-section (rebase-sequence) + (magit-insert-heading "Applying patches") + (let* ((patches (nreverse (magit-rebase-patches))) + (dir (expand-file-name "rebase-apply" (magit-gitdir))) + (i (string-to-number + (magit-file-line (expand-file-name "last" dir)))) + (cur (string-to-number + (magit-file-line (expand-file-name "next" dir)))) + patch commit) + (while (and patches (>= i cur)) + (setq patch (pop patches)) + (setq commit (magit-commit-p + (cadr (split-string (magit-file-line patch))))) + (cond ((and commit (= i cur)) + (magit-sequence-insert-commit + "stop" commit 'magit-sequence-stop)) + ((= i cur) + (magit-sequence-insert-am-patch + "stop" patch 'magit-sequence-stop)) + (commit + (magit-sequence-insert-commit + "pick" commit 'magit-sequence-pick)) + (t + (magit-sequence-insert-am-patch + "pick" patch 'magit-sequence-pick))) + (cl-decf i))) + (magit-sequence-insert-sequence nil "ORIG_HEAD") + (insert ?\n)))) + +(defun magit-sequence-insert-am-patch (type patch face) + (magit-insert-section (file patch) + (let ((title + (with-temp-buffer + (insert-file-contents patch nil nil 4096) + (unless (re-search-forward "^Subject: " nil t) + (goto-char (point-min))) + (buffer-substring (point) (line-end-position))))) + (insert (propertize type 'font-lock-face face) + ?\s (propertize (file-name-nondirectory patch) + 'font-lock-face 'magit-hash) + ?\s title + ?\n)))) + +(defun magit-insert-rebase-sequence () + "Insert section for the on-going rebase sequence. +If no such sequence is in progress, do nothing." + (when (magit-rebase-in-progress-p) + (let* ((gitdir (magit-gitdir)) + (interactive + (file-directory-p (expand-file-name "rebase-merge" gitdir))) + (dir (if interactive "rebase-merge/" "rebase-apply/")) + (name (thread-first (concat dir "head-name") + (expand-file-name gitdir) + magit-file-line)) + (onto (thread-first (concat dir "onto") + (expand-file-name gitdir) + magit-file-line)) + (onto (or (magit-rev-name onto name) + (magit-rev-name onto "refs/heads/*") onto)) + (name (or (magit-rev-name name "refs/heads/*") name))) + (magit-insert-section (rebase-sequence) + (magit-insert-heading (format "Rebasing %s onto %s" name onto)) + (if interactive + (magit-rebase-insert-merge-sequence onto) + (magit-rebase-insert-apply-sequence onto)) + (insert ?\n))))) + +(defun magit-rebase--todo () + "Return `git-rebase-action' instances for remaining rebase actions. +These are ordered in that the same way they'll be sorted in the +status buffer (i.e., the reverse of how they will be applied)." + (let ((comment-start (or (magit-get "core.commentChar") "#")) + lines) + (with-temp-buffer + (insert-file-contents + (expand-file-name "rebase-merge/git-rebase-todo" (magit-gitdir))) + (while (not (eobp)) + (let ((ln (git-rebase-current-line))) + (when (oref ln action-type) + (push ln lines))) + (forward-line))) + lines)) + +(defun magit-rebase-insert-merge-sequence (onto) + (dolist (line (magit-rebase--todo)) + (with-slots (action-type action action-options target) line + (pcase action-type + ('commit + (magit-sequence-insert-commit action target 'magit-sequence-pick)) + ((or (or `exec `label) + (and `merge (guard (not action-options)))) + (insert (propertize action 'font-lock-face 'magit-sequence-onto) "\s" + (propertize target 'font-lock-face 'git-rebase-label) "\n")) + ('merge + (if-let ((hash (and (string-match "-[cC] \\([^ ]+\\)" action-options) + (match-string 1 action-options)))) + (magit-insert-section (commit hash) + (magit-insert-heading + (propertize "merge" 'font-lock-face 'magit-sequence-pick) + "\s" + (magit-format-rev-summary hash) "\n")) + (error "failed to parse merge message hash")))))) + (let ((dir (magit-gitdir))) + (magit-sequence-insert-sequence + (magit-file-line (expand-file-name "rebase-merge/stopped-sha" dir)) + onto + (and-let* ((lines (magit-file-lines + (expand-file-name "rebase-merge/done" dir)))) + (cadr (split-string (car (last lines)))))))) + +(defun magit-rebase-insert-apply-sequence (onto) + (let* ((dir (magit-gitdir)) + (rewritten + (--map (car (split-string it)) + (magit-file-lines + (expand-file-name "rebase-apply/rewritten" dir)))) + (stop (magit-file-line + (expand-file-name "rebase-apply/original-commit" dir)))) + (dolist (patch (nreverse (cdr (magit-rebase-patches)))) + (let ((hash (cadr (split-string (magit-file-line patch))))) + (unless (or (member hash rewritten) + (equal hash stop)) + (magit-sequence-insert-commit "pick" hash 'magit-sequence-pick)))) + (magit-sequence-insert-sequence + (magit-file-line (expand-file-name "rebase-apply/original-commit" dir)) + onto))) + +(defun magit-rebase-patches () + (directory-files (expand-file-name "rebase-apply" (magit-gitdir)) + t "\\`[0-9]\\{4\\}\\'")) + +(defun magit-sequence-insert-sequence (stop onto &optional orig) + (let ((head (magit-rev-parse "HEAD")) done) + (setq onto (if onto (magit-rev-parse onto) head)) + (setq done (magit-git-lines "log" "--format=%H" (concat onto "..HEAD"))) + (when (and stop (not (member (magit-rev-parse stop) done))) + (let ((id (magit-patch-id stop))) + (if-let ((matched (--first (equal (magit-patch-id it) id) done))) + (setq stop matched) + (cond + ((--first (magit-rev-equal it stop) done) + ;; The commit's testament has been executed. + (magit-sequence-insert-commit "void" stop 'magit-sequence-drop)) + ;; The faith of the commit is still undecided... + ((magit-anything-unmerged-p) + ;; ...and time travel isn't for the faint of heart. + (magit-sequence-insert-commit "join" stop 'magit-sequence-part)) + ((magit-anything-modified-p t) + ;; ...and the dust hasn't settled yet... + (magit-sequence-insert-commit + (let* ((magit--refresh-cache nil) + (staged (magit-commit-tree "oO" nil "HEAD")) + (unstaged (magit-commit-worktree "oO" "--reset"))) + (cond + ;; ...but we could end up at the same tree just by committing. + ((or (magit-rev-equal staged stop) + (magit-rev-equal unstaged stop)) + "goal") + ;; ...but the changes are still there, untainted. + ((or (equal (magit-patch-id staged) id) + (equal (magit-patch-id unstaged) id)) + "same") + ;; ...and some changes are gone and/or others were added. + (t "work"))) + stop 'magit-sequence-part)) + ;; The commit is definitely gone... + ((--first (magit-rev-equal it stop) done) + ;; ...but all of its changes are still in effect. + (magit-sequence-insert-commit "poof" stop 'magit-sequence-drop)) + (t + ;; ...and some changes are gone and/or other changes were added. + (magit-sequence-insert-commit "gone" stop 'magit-sequence-drop))) + (setq stop nil)))) + (dolist (rev done) + (apply #'magit-sequence-insert-commit + (cond ((equal rev stop) + ;; ...but its reincarnation lives on. + ;; Or it didn't die in the first place. + (list (if (and (equal rev head) + (equal (magit-patch-id rev) + (magit-patch-id orig))) + "stop" ; We haven't done anything yet. + "like") ; There are new commits. + rev (if (equal rev head) + 'magit-sequence-head + 'magit-sequence-stop))) + ((equal rev head) + (list "done" rev 'magit-sequence-head)) + (t + (list "done" rev 'magit-sequence-done))))) + (magit-sequence-insert-commit "onto" onto + (if (equal onto head) + 'magit-sequence-head + 'magit-sequence-onto)))) + +(defun magit-sequence-insert-commit (type hash face) + (magit-insert-section (commit hash) + (magit-insert-heading + (propertize type 'font-lock-face face) "\s" + (magit-format-rev-summary hash) "\n"))) + +;;; _ +(provide 'magit-sequence) +;;; magit-sequence.el ends here diff --git a/emacs/elpa/magit-20241004.917/magit-sparse-checkout.el b/emacs/elpa/magit-20241004.917/magit-sparse-checkout.el @@ -0,0 +1,170 @@ +;;; magit-sparse-checkout.el --- Sparse checkout support for Magit -*- lexical-binding:t -*- + +;; Copyright (C) 2008-2024 The Magit Project Contributors + +;; Author: Kyle Meyer <kyle@kyleam.com> +;; Maintainer: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> + +;; SPDX-License-Identifier: GPL-3.0-or-later + +;; Magit is free software: you can redistribute it and/or modify it +;; under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. +;; +;; Magit is distributed in the hope that it will be useful, but WITHOUT +;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +;; or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public +;; License for more details. +;; +;; You should have received a copy of the GNU General Public License +;; along with Magit. If not, see <https://www.gnu.org/licenses/>. + +;;; Commentary: + +;; This library provides an interface to the `git sparse-checkout' +;; command. It's been possible to define sparse checkouts since Git +;; v1.7.0 by adding patterns to $GIT_DIR/info/sparse-checkout and +;; calling `git read-tree -mu HEAD' to update the index and working +;; tree. However, Git v2.25 introduced the `git sparse-checkout' +;; command along with "cone mode", which restricts the possible +;; patterns to directories to provide better performance. +;; +;; The goal of this library is to support the `git sparse-checkout' +;; command operating in cone mode. + +;;; Code: + +(require 'magit) + +;;; Utilities + +(defun magit-sparse-checkout-enabled-p () + "Return non-nil if working tree is a sparse checkout." + (magit-get-boolean "core.sparsecheckout")) + +(defun magit-sparse-checkout--assert-version () + ;; Older versions of Git have the ability to define sparse checkout + ;; patterns in .git/info/sparse-checkout, but the sparse-checkout + ;; command isn't available until 2.25.0. + (when (magit-git-version< "2.25.0") + (user-error "`git sparse-checkout' not available until Git v2.25"))) + +(defun magit-sparse-checkout--auto-enable () + (if (magit-sparse-checkout-enabled-p) + (unless (magit-get-boolean "core.sparsecheckoutcone") + (user-error + "Magit's sparse checkout functionality requires cone mode")) + ;; Note: Don't use `magit-sparse-checkout-enable' because it's + ;; asynchronous. + (magit-run-git "sparse-checkout" "init" "--cone"))) + +(defun magit-sparse-checkout-directories () + "Return directories that are recursively included in the sparse checkout. +See the `git sparse-checkout' manpage for details about +\"recursive\" versus \"parent\" directories in cone mode." + (and (magit-get-boolean "core.sparsecheckoutcone") + (mapcar #'file-name-as-directory + (magit-git-lines "sparse-checkout" "list")))) + +;;; Commands + +;;;###autoload (autoload 'magit-sparse-checkout "magit-sparse-checkout" nil t) +(transient-define-prefix magit-sparse-checkout () + "Create and manage sparse checkouts." + :man-page "git-sparse-checkout" + ["Arguments for enabling" + :if-not magit-sparse-checkout-enabled-p + ("-i" "Use sparse index" "--sparse-index")] + ["Actions" + [:if-not magit-sparse-checkout-enabled-p + ("e" "Enable sparse checkout" magit-sparse-checkout-enable)] + [:if magit-sparse-checkout-enabled-p + ("d" "Disable sparse checkout" magit-sparse-checkout-disable) + ("r" "Reapply rules" magit-sparse-checkout-reapply)] + [("s" "Set directories" magit-sparse-checkout-set) + ("a" "Add directories" magit-sparse-checkout-add)]]) + +;;;###autoload +(defun magit-sparse-checkout-enable (&optional args) + "Convert the working tree to a sparse checkout." + (interactive (list (transient-args 'magit-sparse-checkout))) + (magit-sparse-checkout--assert-version) + (magit-run-git-async "sparse-checkout" "init" "--cone" args)) + +;;;###autoload +(defun magit-sparse-checkout-set (directories) + "Restrict working tree to DIRECTORIES. +To extend rather than override the currently configured +directories, call `magit-sparse-checkout-add' instead." + (interactive + (list (magit-completing-read-multiple + "Include these directories: " + ;; Note: Given that the appeal of sparse checkouts is + ;; dealing with very large trees, listing all subdirectories + ;; may need to be reconsidered. + (magit-revision-directories "HEAD")))) + (magit-sparse-checkout--assert-version) + (magit-sparse-checkout--auto-enable) + (magit-run-git-async "sparse-checkout" "set" directories)) + +;;;###autoload +(defun magit-sparse-checkout-add (directories) + "Add DIRECTORIES to the working tree. +To override rather than extend the currently configured +directories, call `magit-sparse-checkout-set' instead." + (interactive + (list (magit-completing-read-multiple + "Add these directories: " + ;; Same performance note as in `magit-sparse-checkout-set', + ;; but even more so given the additional processing. + (seq-remove + (let ((re (concat + "\\`" + (regexp-opt (magit-sparse-checkout-directories))))) + (lambda (d) (string-match-p re d))) + (magit-revision-directories "HEAD"))))) + (magit-sparse-checkout--assert-version) + (magit-sparse-checkout--auto-enable) + (magit-run-git-async "sparse-checkout" "add" directories)) + +;;;###autoload +(defun magit-sparse-checkout-reapply () + "Reapply the sparse checkout rules to the working tree. +Some operations such as merging or rebasing may need to check out +files that aren't included in the sparse checkout. Call this +command to reset to the sparse checkout state." + (interactive) + (magit-sparse-checkout--assert-version) + (magit-run-git-async "sparse-checkout" "reapply")) + +;;;###autoload +(defun magit-sparse-checkout-disable () + "Convert sparse checkout to full checkout. +Note that disabling the sparse checkout does not clear the +configured directories. Call `magit-sparse-checkout-enable' to +restore the previous sparse checkout." + (interactive) + (magit-sparse-checkout--assert-version) + (magit-run-git-async "sparse-checkout" "disable")) + +;;; Miscellaneous + +(defun magit-sparse-checkout-insert-header () + "Insert header line with sparse checkout information. +This header is not inserted by default. To enable it, add it to +`magit-status-headers-hook'." + (when (magit-sparse-checkout-enabled-p) + (insert (propertize (format "%-10s" "Sparse! ") + 'font-lock-face 'magit-section-heading)) + (insert + (let ((dirs (magit-sparse-checkout-directories))) + (pcase (length dirs) + (0 "top-level directory") + (1 (car dirs)) + (n (format "%d directories" n))))) + (insert ?\n))) + +;;; _ +(provide 'magit-sparse-checkout) +;;; magit-sparse-checkout.el ends here diff --git a/emacs/elpa/magit-20241004.917/magit-stash.el b/emacs/elpa/magit-20241004.917/magit-stash.el @@ -0,0 +1,646 @@ +;;; magit-stash.el --- Stash support for Magit -*- lexical-binding:t -*- + +;; Copyright (C) 2008-2024 The Magit Project Contributors + +;; Author: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> +;; Maintainer: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> + +;; SPDX-License-Identifier: GPL-3.0-or-later + +;; Magit is free software: you can redistribute it and/or modify it +;; under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. +;; +;; Magit is distributed in the hope that it will be useful, but WITHOUT +;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +;; or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public +;; License for more details. +;; +;; You should have received a copy of the GNU General Public License +;; along with Magit. If not, see <https://www.gnu.org/licenses/>. + +;;; Commentary: + +;; Support for Git stashes. + +;;; Code: + +(require 'magit) +(require 'magit-reflog) +(require 'magit-sequence) + +;;; Options + +(defgroup magit-stash nil + "List stashes and show stash diffs." + :group 'magit-modes) + +;;;; Diff options + +(defcustom magit-stash-sections-hook + '(magit-insert-stash-notes + magit-insert-stash-worktree + magit-insert-stash-index + magit-insert-stash-untracked) + "Hook run to insert sections into stash diff buffers." + :package-version '(magit . "2.1.0") + :group 'magit-stash + :type 'hook) + +;;;; Log options + +(defcustom magit-stashes-margin + (list (nth 0 magit-log-margin) + (nth 1 magit-log-margin) + 'magit-log-margin-width nil + (nth 4 magit-log-margin)) + "Format of the margin in `magit-stashes-mode' buffers. + +The value has the form (INIT STYLE WIDTH AUTHOR AUTHOR-WIDTH). + +If INIT is non-nil, then the margin is shown initially. +STYLE controls how to format the author or committer date. + It can be one of `age' (to show the age of the commit), + `age-abbreviated' (to abbreviate the time unit to a character), + or a string (suitable for `format-time-string') to show the + actual date. Option `magit-log-margin-show-committer-date' + controls which date is being displayed. +WIDTH controls the width of the margin. This exists for forward + compatibility and currently the value should not be changed. +AUTHOR controls whether the name of the author is also shown by + default. +AUTHOR-WIDTH has to be an integer. When the name of the author + is shown, then this specifies how much space is used to do so." + :package-version '(magit . "2.9.0") + :group 'magit-stash + :group 'magit-margin + :type magit-log-margin--custom-type + :initialize #'magit-custom-initialize-reset + :set-after '(magit-log-margin) + :set (apply-partially #'magit-margin-set-variable 'magit-stashes-mode)) + +;;;; Variables + +(defvar magit-stash-read-message-function #'magit-stash-read-message + "Function used to read the message when creating a stash.") + +;;; Commands + +;;;###autoload (autoload 'magit-stash "magit-stash" nil t) +(transient-define-prefix magit-stash () + "Stash uncommitted changes." + :man-page "git-stash" + ["Arguments" + ("-u" "Also save untracked files" ("-u" "--include-untracked")) + ("-a" "Also save untracked and ignored files" ("-a" "--all"))] + [["Stash" + ("z" "both" magit-stash-both) + ("i" "index" magit-stash-index) + ("w" "worktree" magit-stash-worktree) + ("x" "keeping index" magit-stash-keep-index) + ("P" "push" magit-stash-push :level 5)] + ["Snapshot" + ("Z" "both" magit-snapshot-both) + ("I" "index" magit-snapshot-index) + ("W" "worktree" magit-snapshot-worktree) + ("r" "to wip ref" magit-wip-commit)] + ["Use" + ("a" "Apply" magit-stash-apply) + ("p" "Pop" magit-stash-pop) + ("k" "Drop" magit-stash-drop)] + ["Inspect" + ("l" "List" magit-stash-list) + ("v" "Show" magit-stash-show)] + ["Transform" + ("b" "Branch" magit-stash-branch) + ("B" "Branch here" magit-stash-branch-here) + ("f" "Format patch" magit-stash-format-patch)]]) + +(defun magit-stash-arguments () + (transient-args 'magit-stash)) + +;;;###autoload +(defun magit-stash-both (message &optional include-untracked) + "Create a stash of the index and working tree. +Untracked files are included according to infix arguments. +One prefix argument is equivalent to `--include-untracked' +while two prefix arguments are equivalent to `--all'." + (interactive + (progn (when (and (magit-merge-in-progress-p) + (not (magit-y-or-n-p "\ +Stashing and resetting during a merge conflict. \ +Applying the resulting stash won't restore the merge state. \ +Proceed anyway? "))) + (user-error "Abort")) + (magit-stash-read-args))) + (magit-stash-save message t t include-untracked t)) + +;;;###autoload +(defun magit-stash-index (message) + "Create a stash of the index only. +Unstaged and untracked changes are not stashed. The stashed +changes are applied in reverse to both the index and the +worktree. This command can fail when the worktree is not clean. +Applying the resulting stash has the inverse effect." + (interactive (list (magit-stash-read-message))) + (magit-stash-save message t nil nil t 'worktree)) + +;;;###autoload +(defun magit-stash-worktree (message &optional include-untracked) + "Create a stash of unstaged changes in the working tree. +Untracked files are included according to infix arguments. +One prefix argument is equivalent to `--include-untracked' +while two prefix arguments are equivalent to `--all'." + (interactive (magit-stash-read-args)) + (magit-stash-save message nil t include-untracked t 'index)) + +;;;###autoload +(defun magit-stash-keep-index (message &optional include-untracked) + "Create a stash of the index and working tree, keeping index intact. +Untracked files are included according to infix arguments. +One prefix argument is equivalent to `--include-untracked' +while two prefix arguments are equivalent to `--all'." + (interactive (magit-stash-read-args)) + (magit-stash-save message t t include-untracked t 'index)) + +(defun magit-stash-read-args () + (list (funcall magit-stash-read-message-function) + (magit-stash-read-untracked))) + +(defun magit-stash-read-message () + "Read a message from the minibuffer, to be used for a stash. + +The message that Git would have picked, is available as the +default (used when the user enters the empty string) and as +the next history element (which can be accessed with \ +\\<minibuffer-local-map>\\[next-history-element])." + (read-string (format "Stash message (default: On%s:%s): " + (magit--ellipsis) (magit--ellipsis)) + nil nil + (format "On %s: %s" + (or (magit-get-current-branch) "(no branch)") + (magit-rev-format "%h %s")))) + +(defun magit-stash-read-message-traditional () + "Read a message from the minibuffer, to be used for a stash. + +If the user confirms the initial-input unmodified, then the +abbreviated commit hash and commit summary are appended. +The resulting message is what Git would have used." + (let* ((default (format "On %s: " + (or (magit-get-current-branch) "(no branch)"))) + (input (magit-read-string "Stash message" default))) + (if (equal input default) + (concat default (magit-rev-format "%h %s")) + input))) + +(defun magit-stash-read-untracked () + (let ((prefix (prefix-numeric-value current-prefix-arg)) + (args (magit-stash-arguments))) + (cond ((or (= prefix 16) (member "--all" args)) 'all) + ((or (= prefix 4) (member "--include-untracked" args)) t)))) + +;;;###autoload +(defun magit-snapshot-both (&optional include-untracked) + "Create a snapshot of the index and working tree. +Untracked files are included according to infix arguments. +One prefix argument is equivalent to `--include-untracked' +while two prefix arguments are equivalent to `--all'." + (interactive (magit-snapshot-read-args)) + (magit-snapshot-save t t include-untracked t)) + +;;;###autoload +(defun magit-snapshot-index () + "Create a snapshot of the index only. +Unstaged and untracked changes are not stashed." + (interactive) + (magit-snapshot-save t nil nil t)) + +;;;###autoload +(defun magit-snapshot-worktree (&optional include-untracked) + "Create a snapshot of unstaged changes in the working tree. +Untracked files are included according to infix arguments. +One prefix argument is equivalent to `--include-untracked' +while two prefix arguments are equivalent to `--all'." + (interactive (magit-snapshot-read-args)) + (magit-snapshot-save nil t include-untracked t)) + +(defun magit-snapshot-read-args () + (list (magit-stash-read-untracked))) + +(defun magit-snapshot-save (index worktree untracked &optional refresh) + (magit-stash-save (concat "WIP on " (magit-stash-summary)) + index worktree untracked refresh t)) + +;;;###autoload (autoload 'magit-stash-push "magit-stash" nil t) +(transient-define-prefix magit-stash-push (&optional transient args) + "Create stash using \"git stash push\". + +This differs from Magit's other stashing commands, which don't +use \"git stash\" and are generally more flexible but don't allow +specifying a list of files to be stashed." + :man-page "git-stash" + ["Arguments" + (magit:-- :reader (lambda (prompt initial-input history) + (magit-read-files prompt initial-input history + #'magit-modified-files))) + ("-u" "Also save untracked files" ("-u" "--include-untracked")) + ("-a" "Also save untracked and ignored files" ("-a" "--all")) + ("-k" "Keep index" ("-k" "--keep-index")) + ("-K" "Don't keep index" "--no-keep-index")] + ["Actions" + ("P" "push" magit-stash-push)] + (interactive (if (eq transient-current-command 'magit-stash-push) + (list nil (transient-args 'magit-stash-push)) + (list t))) + (if transient + (transient-setup 'magit-stash-push) + (magit-run-git "stash" "push" args))) + +;;;###autoload +(defun magit-stash-apply (stash) + "Apply a stash to the working tree. + +First try \"git stash apply --index\", which tries to preserve +the index stored in the stash, if any. This may fail because +applying the stash could result in conflicts and those have to +be stored in the index, making it impossible to also store the +stash's index there as well. + +If the above failed, then try \"git stash apply\". This fails +\(with or without \"--index\") if there are any uncommitted +changes to files that are also modified in the stash. + +If both of the above failed, then apply using \"git apply\". +If there are no conflicting files, use \"--3way\". If there are +conflicting files, then using \"--3way\" requires that those +files are staged first, which may be undesirable, so prompt +the user whether to use \"--3way\" or \"--reject\"." + (interactive (list (magit-read-stash "Apply stash"))) + (magit-stash--apply "apply" stash)) + +;;;###autoload +(defun magit-stash-pop (stash) + "Apply a stash to the working tree, on success remove it from stash list. + +First try \"git stash pop --index\", which tries to preserve +the index stored in the stash, if any. This may fail because +applying the stash could result in conflicts and those have to +be stored in the index, making it impossible to also store the +stash's index there as well. + +If the above failed, then try \"git stash apply\". This fails +\(with or without \"--index\") if there are any uncommitted +changes to files that are also modified in the stash. + +If both of the above failed, then apply using \"git apply\". +If there are no conflicting files, use \"--3way\". If there are +conflicting files, then using \"--3way\" requires that those +files are staged first, which may be undesirable, so prompt +the user whether to use \"--3way\" or \"--reject\"." + (interactive (list (magit-read-stash "Pop stash"))) + (magit-stash--apply "pop" stash)) + +(defun magit-stash--apply (action stash) + (or (= (magit-call-git "stash" action "--index" stash) 0) + ;; The stash's index could not be applied, so always keep the stash. + (= (magit-call-git "stash" "apply" stash) 0) + (let* ((range (format "%s^..%s" stash stash)) + (stashed (magit-git-items "diff" "-z" "--name-only" range "--")) + (conflicts (cl-sort (cl-union (magit-unstaged-files t stashed) + (magit-untracked-files t stashed) + :test #'equal) + #'string<)) + (arg (cond + ((not conflicts) "--3way") + ((magit-confirm-files + 'stash-apply-3way conflicts + "Apply stash using `--3way', which requires first staging" + "(else use `--reject')" + t) + (magit-stage-1 nil conflicts) + "--3way") + ("--reject")))) + (with-temp-buffer + (magit-git-insert "diff" range) + (magit-run-git-with-input "apply" arg "-")))) + (magit-refresh)) + +;;;###autoload +(defun magit-stash-drop (stash) + "Remove a stash from the stash list. +When the region is active offer to drop all contained stashes." + (interactive + (list (if-let ((values (magit-region-values 'stash))) + (magit-confirm 'drop-stashes nil "Drop %d stashes" nil values) + (magit-read-stash "Drop stash")))) + (dolist (stash (if (listp stash) + (nreverse (prog1 stash (setq stash (car stash)))) + (list stash))) + (message "Deleted refs/%s (was %s)" stash + (magit-rev-parse "--short" stash)) + (magit-call-git "rev-parse" stash) + (magit-call-git "stash" "drop" stash)) + (magit-refresh)) + +;;;###autoload +(defun magit-stash-clear (ref) + "Remove all stashes saved in REF's reflog by deleting REF." + (interactive (let ((ref (or (magit-section-value-if 'stashes) "refs/stash"))) + (magit-confirm t (list "Drop all stashes in %s" ref)) + (list ref))) + (magit-run-git "update-ref" "-d" ref)) + +;;;###autoload +(defun magit-stash-branch (stash branch) + "Create and checkout a new BRANCH from an existing STASH. +The new branch starts at the commit that was current when the +stash was created. If the stash applies cleanly, then drop it." + (interactive (list (magit-read-stash "Branch stash") + (magit-read-string-ns "Branch name"))) + (magit-run-git "stash" "branch" branch stash)) + +;;;###autoload +(defun magit-stash-branch-here (stash branch) + "Create and checkout a new BRANCH from an existing STASH. +Use the current branch or `HEAD' as the starting-point of BRANCH. +Then apply STASH, dropping it if it applies cleanly." + (interactive (list (magit-read-stash "Branch stash") + (magit-read-string-ns "Branch name"))) + (let ((start-point (or (magit-get-current-branch) "HEAD"))) + (magit-call-git "checkout" "-b" branch start-point) + (magit-branch-maybe-adjust-upstream branch start-point)) + (magit-stash-apply stash)) + +;;;###autoload +(defun magit-stash-format-patch (stash) + "Create a patch from STASH" + (interactive (list (magit-read-stash "Create patch from stash"))) + (with-temp-file (magit-rev-format "0001-%f.patch" stash) + (magit-git-insert "stash" "show" "-p" stash)) + (magit-refresh)) + +;;; Plumbing + +(defun magit-stash-save (message index worktree untracked + &optional refresh keep noerror ref) + (if (or (and index (magit-staged-files t)) + (and worktree (magit-unstaged-files t)) + (and untracked (magit-untracked-files (eq untracked 'all)))) + (magit-with-toplevel + (magit-stash-store message (or ref "refs/stash") + (magit-stash-create message index worktree untracked)) + (if (eq keep 'worktree) + (with-temp-buffer + (magit-git-insert "diff" "--cached" "--no-ext-diff") + (magit-run-git-with-input + "apply" "--reverse" "--cached" "--ignore-space-change" "-") + (magit-run-git-with-input + "apply" "--reverse" "--ignore-space-change" "-")) + (unless (eq keep t) + (if (eq keep 'index) + (magit-call-git "checkout" "--" ".") + (magit-call-git "reset" "--hard" "HEAD" "--")) + (when untracked + (magit-call-git "clean" "--force" "-d" + (and (eq untracked 'all) "-x"))))) + (when refresh + (magit-refresh))) + (unless noerror + (user-error "No %s changes to save" (cond ((not index) "unstaged") + ((not worktree) "staged") + (t "local")))))) + +(defun magit-stash-store (message ref commit) + (magit-update-ref ref message commit t)) + +(defun magit-stash-create (message index worktree untracked) + (unless (magit-rev-parse "--verify" "HEAD") + (error "You do not have the initial commit yet")) + (let ((magit-git-global-arguments (nconc (list "-c" "commit.gpgsign=false") + magit-git-global-arguments)) + (default-directory (magit-toplevel)) + (summary (magit-stash-summary)) + (head "HEAD")) + (when (and worktree (not index)) + (setq head (or (magit-commit-tree "pre-stash index" nil "HEAD") + (error "Cannot save the current index state")))) + (or (setq index (magit-commit-tree (concat "index on " summary) nil head)) + (error "Cannot save the current index state")) + (and untracked + (setq untracked (magit-untracked-files (eq untracked 'all))) + (setq untracked (magit-with-temp-index nil nil + (or (and (magit-update-files untracked) + (magit-commit-tree + (concat "untracked files on " summary))) + (error "Cannot save the untracked files"))))) + (magit-with-temp-index index "-m" + (when worktree + (or (magit-update-files (magit-git-items "diff" "-z" "--name-only" head)) + (error "Cannot save the current worktree state"))) + (or (magit-commit-tree message nil head index untracked) + (error "Cannot save the current worktree state"))))) + +(defun magit-stash-summary () + (concat (or (magit-get-current-branch) "(no branch)") + ": " (magit-rev-format "%h %s"))) + +;;; Sections + +(defvar-keymap magit-stashes-section-map + :doc "Keymap for `stashes' section." + "<remap> <magit-delete-thing>" #'magit-stash-clear + "<remap> <magit-visit-thing>" #'magit-stash-list + "<2>" (magit-menu-item "Clear %t" #'magit-stash-clear) + "<1>" (magit-menu-item "List %t" #'magit-stash-list)) + +(defvar-keymap magit-stash-section-map + :doc "Keymap for `stash' sections." + "<remap> <magit-cherry-pick>" #'magit-stash-pop + "<remap> <magit-cherry-apply>" #'magit-stash-apply + "<remap> <magit-delete-thing>" #'magit-stash-drop + "<remap> <magit-visit-thing>" #'magit-stash-show + "<4>" (magit-menu-item "Pop %M" #'magit-stash-pop) + "<3>" (magit-menu-item "Apply %M" #'magit-stash-apply) + "<2>" (magit-menu-item "Delete %M" #'magit-stash-drop) + "<1>" (magit-menu-item "Visit %v" #'magit-stash-show)) + +(magit-define-section-jumper magit-jump-to-stashes + "Stashes" stashes "refs/stash" magit-insert-stashes) + +(cl-defun magit-insert-stashes (&optional (ref "refs/stash") + (heading "Stashes:")) + "Insert `stashes' section showing reflog for \"refs/stash\". +If optional REF is non-nil, show reflog for that instead. +If optional HEADING is non-nil, use that as section heading +instead of \"Stashes:\"." + (let ((verified (magit-rev-verify ref)) + (autostash (magit-rebase--get-state-lines "autostash"))) + (when (or autostash verified) + (magit-insert-section (stashes ref) + (magit-insert-heading heading) + (when autostash + (pcase-let ((`(,author ,date ,msg) + (split-string + (car (magit-git-lines + "show" "-q" "--format=%aN%x00%at%x00%s" + autostash)) + "\0"))) + (magit-insert-section (stash autostash) + (insert (propertize "AUTOSTASH" 'font-lock-face 'magit-hash)) + (insert " " msg "\n") + (save-excursion + (backward-char) + (magit-log-format-margin autostash author date))))) + (if verified + (magit-git-wash (apply-partially #'magit-log-wash-log 'stash) + "reflog" "--format=%gd%x00%aN%x00%at%x00%gs" ref) + (insert ?\n) + (save-excursion + (backward-char) + (magit-make-margin-overlay))))))) + +;;; List Stashes + +;;;###autoload +(defun magit-stash-list () + "List all stashes in a buffer." + (interactive) + (magit-stashes-setup-buffer)) + +(define-derived-mode magit-stashes-mode magit-reflog-mode "Magit Stashes" + "Mode for looking at lists of stashes." + :interactive nil + :group 'magit-log + (magit-hack-dir-local-variables)) + +(defun magit-stashes-setup-buffer () + (magit-setup-buffer #'magit-stashes-mode nil + (magit-buffer-refname "refs/stash"))) + +(defun magit-stashes-refresh-buffer () + (magit-insert-section (stashesbuf) + (magit-insert-heading t + (if (equal magit-buffer-refname "refs/stash") + "Stashes" + (format "Stashes [%s]" magit-buffer-refname))) + (magit-git-wash (apply-partially #'magit-log-wash-log 'stash) + "reflog" "--format=%gd%x00%aN%x00%at%x00%gs" magit-buffer-refname))) + +(cl-defmethod magit-buffer-value (&context (major-mode magit-stashes-mode)) + magit-buffer-refname) + +(defvar magit--update-stash-buffer nil) + +(defun magit-stashes-maybe-update-stash-buffer (&optional _) + "When moving in the stashes buffer, update the stash buffer. +If there is no stash buffer in the same frame, then do nothing." + (when (derived-mode-p 'magit-stashes-mode) + (magit--maybe-update-stash-buffer))) + +(defun magit--maybe-update-stash-buffer () + (when-let* ((stash (magit-section-value-if 'stash)) + (buffer (magit-get-mode-buffer 'magit-stash-mode nil t))) + (if magit--update-stash-buffer + (setq magit--update-stash-buffer (list stash buffer)) + (setq magit--update-stash-buffer (list stash buffer)) + (run-with-idle-timer + magit-update-other-window-delay nil + (let ((args (with-current-buffer buffer + (let ((magit-direct-use-buffer-arguments 'selected)) + (magit-show-commit--arguments))))) + (lambda () + (pcase-let ((`(,stash ,buf) magit--update-stash-buffer)) + (setq magit--update-stash-buffer nil) + (when (buffer-live-p buf) + (let ((magit-display-buffer-noselect t)) + (apply #'magit-stash-show stash args)))) + (setq magit--update-stash-buffer nil))))))) + +;;; Show Stash + +;;;###autoload +(defun magit-stash-show (stash &optional args files) + "Show all diffs of a stash in a buffer." + (interactive (cons (or (and (not current-prefix-arg) + (magit-stash-at-point)) + (magit-read-stash "Show stash")) + (pcase-let ((`(,args ,files) + (magit-diff-arguments 'magit-stash-mode))) + (list (delete "--stat" args) files)))) + (magit-stash-setup-buffer stash args files)) + +(define-derived-mode magit-stash-mode magit-diff-mode "Magit Stash" + "Mode for looking at individual stashes." + :interactive nil + :group 'magit-diff + (magit-hack-dir-local-variables) + (setq magit--imenu-group-types '(commit))) + +(defun magit-stash-setup-buffer (stash args files) + (magit-setup-buffer #'magit-stash-mode nil + (magit-buffer-revision stash) + (magit-buffer-range (format "%s^..%s" stash stash)) + (magit-buffer-diff-args args) + (magit-buffer-diff-files files))) + +(defun magit-stash-refresh-buffer () + (magit-set-header-line-format + (concat (capitalize magit-buffer-revision) " " + (propertize (magit-rev-format "%s" magit-buffer-revision) + 'font-lock-face + (list :weight 'normal :foreground + (face-attribute 'default :foreground))))) + (setq magit-buffer-revision-hash (magit-rev-parse magit-buffer-revision)) + (magit-insert-section (stash) + (magit-run-section-hook 'magit-stash-sections-hook))) + +(cl-defmethod magit-buffer-value (&context (major-mode magit-stash-mode)) + magit-buffer-revision) + +(defun magit-stash-insert-section (commit range message &optional files) + (magit-insert-section (commit commit) + (magit-insert-heading message) + (magit--insert-diff nil + "diff" range "-p" "--no-prefix" magit-buffer-diff-args + "--" (or files magit-buffer-diff-files)))) + +(defun magit-insert-stash-notes () + "Insert section showing notes for a stash. +This shows the notes for stash@{N} but not for the other commits +that make up the stash." + (magit-insert-section (note) + (magit-insert-heading t "Notes") + (magit-git-insert "notes" "show" magit-buffer-revision) + (magit-cancel-section 'if-empty) + (insert "\n"))) + +(defun magit-insert-stash-index () + "Insert section showing staged changes of the stash." + (magit-stash-insert-section + (format "%s^2" magit-buffer-revision) + (format "%s^..%s^2" magit-buffer-revision magit-buffer-revision) + "Staged")) + +(defun magit-insert-stash-worktree () + "Insert section showing unstaged changes of the stash." + (magit-stash-insert-section + magit-buffer-revision + (format "%s^2..%s" magit-buffer-revision magit-buffer-revision) + "Unstaged")) + +(defun magit-insert-stash-untracked () + "Insert section showing the untracked files commit of the stash." + (let ((stash magit-buffer-revision) + (rev (concat magit-buffer-revision "^3"))) + (when (magit-rev-verify rev) + (magit-stash-insert-section (format "%s^3" stash) + (format "%s^..%s^3" stash stash) + "Untracked files" + (magit-git-items "ls-tree" "-z" "--name-only" + "-r" "--full-tree" rev))))) + +;;; _ +(provide 'magit-stash) +;;; magit-stash.el ends here diff --git a/emacs/elpa/magit-20241004.917/magit-status.el b/emacs/elpa/magit-20241004.917/magit-status.el @@ -0,0 +1,802 @@ +;;; magit-status.el --- The grand overview -*- lexical-binding:t -*- + +;; Copyright (C) 2008-2024 The Magit Project Contributors + +;; Author: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> +;; Maintainer: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> + +;; SPDX-License-Identifier: GPL-3.0-or-later + +;; Magit is free software: you can redistribute it and/or modify it +;; under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. +;; +;; Magit is distributed in the hope that it will be useful, but WITHOUT +;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +;; or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public +;; License for more details. +;; +;; You should have received a copy of the GNU General Public License +;; along with Magit. If not, see <https://www.gnu.org/licenses/>. + +;;; Commentary: + +;; This library implements the status buffer. + +;;; Code: + +(require 'magit) + +;;; Options + +(defgroup magit-status nil + "Inspect and manipulate Git repositories." + :link '(info-link "(magit)Status Buffer") + :group 'magit-modes) + +(defcustom magit-status-mode-hook nil + "Hook run after entering Magit-Status mode." + :group 'magit-status + :type 'hook) + +(defcustom magit-status-headers-hook + '(magit-insert-error-header + magit-insert-diff-filter-header + magit-insert-head-branch-header + magit-insert-upstream-branch-header + magit-insert-push-branch-header + magit-insert-tags-header) + "Hook run to insert headers into the status buffer. + +This hook is run by `magit-insert-status-headers', which in turn +has to be a member of `magit-status-sections-hook' to be used at +all." + :package-version '(magit . "2.1.0") + :group 'magit-status + :type 'hook + :options '(magit-insert-error-header + magit-insert-diff-filter-header + magit-insert-repo-header + magit-insert-remote-header + magit-insert-head-branch-header + magit-insert-upstream-branch-header + magit-insert-push-branch-header + magit-insert-tags-header)) + +(defcustom magit-status-sections-hook + '(magit-insert-status-headers + magit-insert-merge-log + magit-insert-rebase-sequence + magit-insert-am-sequence + magit-insert-sequencer-sequence + magit-insert-bisect-output + magit-insert-bisect-rest + magit-insert-bisect-log + magit-insert-untracked-files + magit-insert-unstaged-changes + magit-insert-staged-changes + magit-insert-stashes + magit-insert-unpushed-to-pushremote + magit-insert-unpushed-to-upstream-or-recent + magit-insert-unpulled-from-pushremote + magit-insert-unpulled-from-upstream) + "Hook run to insert sections into a status buffer." + :package-version '(magit . "2.12.0") + :group 'magit-status + :type 'hook) + +(defcustom magit-status-initial-section '(1) + "The section point is placed on when a status buffer is created. + +When such a buffer is merely being refreshed or being shown again +after it was merely buried, then this option has no effect. + +If this is nil, then point remains on the very first section as +usual. Otherwise it has to be a list of integers and section +identity lists. The members of that list are tried in order +until a matching section is found. + +An integer means to jump to the nth section, 1 for example +jumps over the headings. To get a section's \"identity list\" +use \\[universal-argument] \\[magit-describe-section-briefly]. + +If, for example, you want to jump to the commits that haven't +been pulled from the upstream, or else the second section, then +use: (((unpulled . \"..@{upstream}\") (status)) 1). + +See option `magit-section-initial-visibility-alist' for how to +control the initial visibility of the jumped to section." + :package-version '(magit . "2.90.0") + :group 'magit-status + :type '(choice (const :tag "as usual" nil) + (repeat (choice (number :tag "nth top-level section") + (sexp :tag "section identity"))))) + +(defcustom magit-status-goto-file-position nil + "Whether to go to position corresponding to file position. + +If this is non-nil and the current buffer is visiting a file, +then `magit-status' tries to go to the position in the status +buffer that corresponds to the position in the file-visiting +buffer. This jumps into either the diff of unstaged changes +or the diff of staged changes. + +If the previously current buffer does not visit a file, or if +the file has neither unstaged nor staged changes then this has +no effect. + +The command `magit-status-here' tries to go to that position, +regardless of the value of this option." + :package-version '(magit . "3.0.0") + :group 'magit-status + :type 'boolean) + +(defcustom magit-status-show-hashes-in-headers nil + "Whether headers in the status buffer show hashes. +The functions which respect this option are +`magit-insert-head-branch-header', +`magit-insert-upstream-branch-header', and +`magit-insert-push-branch-header'." + :package-version '(magit . "2.4.0") + :group 'magit-status + :type 'boolean) + +(defcustom magit-status-margin + (list nil + (nth 1 magit-log-margin) + 'magit-log-margin-width nil + (nth 4 magit-log-margin)) + "Format of the margin in `magit-status-mode' buffers. + +The value has the form (INIT STYLE WIDTH AUTHOR AUTHOR-WIDTH). + +If INIT is non-nil, then the margin is shown initially. +STYLE controls how to format the author or committer date. + It can be one of `age' (to show the age of the commit), + `age-abbreviated' (to abbreviate the time unit to a character), + or a string (suitable for `format-time-string') to show the + actual date. Option `magit-log-margin-show-committer-date' + controls which date is being displayed. +WIDTH controls the width of the margin. This exists for forward + compatibility and currently the value should not be changed. +AUTHOR controls whether the name of the author is also shown by + default. +AUTHOR-WIDTH has to be an integer. When the name of the author + is shown, then this specifies how much space is used to do so." + :package-version '(magit . "2.9.0") + :group 'magit-status + :group 'magit-margin + :type magit-log-margin--custom-type + :initialize #'magit-custom-initialize-reset + :set-after '(magit-log-margin) + :set (apply-partially #'magit-margin-set-variable 'magit-status-mode)) + +(defcustom magit-status-use-buffer-arguments 'selected + "Whether `magit-status' reuses arguments when the buffer already exists. + +This option has no effect when merely refreshing the status +buffer using `magit-refresh'. + +Valid values are: + +`always': Always use the set of arguments that is currently + active in the status buffer, provided that buffer exists + of course. +`selected': Use the set of arguments from the status + buffer, but only if it is displayed in a window of the + current frame. This is the default. +`current': Use the set of arguments from the status buffer, + but only if it is the current buffer. +`never': Never use the set of arguments from the status + buffer." + :package-version '(magit . "3.0.0") + :group 'magit-buffers + :group 'magit-commands + :type '(choice + (const :tag "always use args from buffer" always) + (const :tag "use args from buffer if displayed in frame" selected) + (const :tag "use args from buffer if it is current" current) + (const :tag "never use args from buffer" never))) + +;;; Commands + +;;;###autoload +(defun magit-init (directory) + "Initialize a Git repository, then show its status. + +If the directory is below an existing repository, then the user +has to confirm that a new one should be created inside. If the +directory is the root of the existing repository, then the user +has to confirm that it should be reinitialized. + +Non-interactively DIRECTORY is (re-)initialized unconditionally." + (interactive + (let ((directory (file-name-as-directory + (expand-file-name + (read-directory-name "Create repository in: "))))) + (when-let ((toplevel (magit-toplevel directory))) + (setq toplevel (expand-file-name toplevel)) + (unless (y-or-n-p (if (file-equal-p toplevel directory) + (format "Reinitialize existing repository %s? " + directory) + (format "%s is a repository. Create another in %s? " + toplevel directory))) + (user-error "Abort"))) + (list directory))) + ;; `git init' does not understand the meaning of "~"! + (magit-call-git "init" (magit-convert-filename-for-git + (expand-file-name directory))) + (magit-status-setup-buffer directory)) + +;;;###autoload +(defun magit-status (&optional directory cache) + "Show the status of the current Git repository in a buffer. + +If the current directory isn't located within a Git repository, +then prompt for an existing repository or an arbitrary directory, +depending on option `magit-repository-directories', and show the +status of the selected repository instead. + +* If that option specifies any existing repositories, then offer + those for completion and show the status buffer for the + selected one. + +* Otherwise read an arbitrary directory using regular file-name + completion. If the selected directory is the top-level of an + existing working tree, then show the status buffer for that. + +* Otherwise offer to initialize the selected directory as a new + repository. After creating the repository show its status + buffer. + +These fallback behaviors can also be forced using one or more +prefix arguments: + +* With two prefix arguments (or more precisely a numeric prefix + value of 16 or greater) read an arbitrary directory and act on + it as described above. The same could be accomplished using + the command `magit-init'. + +* With a single prefix argument read an existing repository, or + if none can be found based on `magit-repository-directories', + then fall back to the same behavior as with two prefix + arguments." + (interactive + (let ((magit--refresh-cache (list (cons 0 0)))) + (list (and (or current-prefix-arg (not (magit-toplevel))) + (progn (magit--assert-usable-git) + (magit-read-repository + (>= (prefix-numeric-value current-prefix-arg) 16)))) + magit--refresh-cache))) + (let ((magit--refresh-cache (or cache (list (cons 0 0))))) + (if directory + (let ((toplevel (magit-toplevel directory))) + (setq directory (file-name-as-directory + (expand-file-name directory))) + (if (and toplevel (file-equal-p directory toplevel)) + (magit-status-setup-buffer directory) + (when (y-or-n-p + (if toplevel + (format "%s is a repository. Create another in %s? " + toplevel directory) + (format "Create repository in %s? " directory))) + ;; Creating a new repository invalidates cached values. + (setq magit--refresh-cache nil) + (magit-init directory)))) + (magit-status-setup-buffer default-directory)))) + +(put 'magit-status 'interactive-only 'magit-status-setup-buffer) + +;;;###autoload +(defalias 'magit #'magit-status + "Begin using Magit. + +This alias for `magit-status' exists for better discoverability. + +Instead of invoking this alias for `magit-status' using +\"M-x magit RET\", you should bind a key to `magit-status' +and read the info node `(magit)Getting Started', which +also contains other useful hints.") + +;;;###autoload +(defun magit-status-here () + "Like `magit-status' but with non-nil `magit-status-goto-file-position'." + (interactive) + (let ((magit-status-goto-file-position t)) + (call-interactively #'magit-status))) + +(put 'magit-status-here 'interactive-only 'magit-status-setup-buffer) + +;;;###autoload +(defun magit-status-quick () + "Show the status of the current Git repository, maybe without refreshing. + +If the status buffer of the current Git repository exists but +isn't being displayed in the selected frame, then display it +without refreshing it. + +If the status buffer is being displayed in the selected frame, +then also refresh it. + +Prefix arguments have the same meaning as for `magit-status', +and additionally cause the buffer to be refresh. + +To use this function instead of `magit-status', add this to your +init file: (global-set-key (kbd \"C-x g\") \\='magit-status-quick)." + (interactive) + (if-let ((buffer + (and (not current-prefix-arg) + (not (magit-get-mode-buffer 'magit-status-mode nil 'selected)) + (magit-get-mode-buffer 'magit-status-mode)))) + (magit-display-buffer buffer) + (call-interactively #'magit-status))) + +;;; Mode + +(defvar-keymap magit-status-mode-map + :doc "Keymap for `magit-status-mode'." + :parent magit-mode-map + "j" #'magit-status-jump + "<remap> <dired-jump>" #'magit-dired-jump) + +(transient-define-prefix magit-status-jump () + "In a Magit-Status buffer, jump to a section." + [["Jump to" + ("z " magit-jump-to-stashes) + ("t " magit-jump-to-tracked) + ("n " magit-jump-to-untracked) + ("i " magit-jump-to-ignored) + ("u " magit-jump-to-unstaged) + ("s " magit-jump-to-staged)] + ["" + ("fu" magit-jump-to-unpulled-from-upstream) + ("fp" magit-jump-to-unpulled-from-pushremote) + ("pu" magit-jump-to-unpushed-to-upstream) + ("pp" magit-jump-to-unpushed-to-pushremote) + ("a " magit-jump-to-assume-unchanged) + ("w " magit-jump-to-skip-worktree)] + ["Jump using" + ("j" "Imenu" imenu)]]) + +(define-derived-mode magit-status-mode magit-mode "Magit" + "Mode for looking at Git status. + +This mode is documented in info node `(magit)Status Buffer'. + +\\<magit-mode-map>\ +Type \\[magit-refresh] to refresh the current buffer. +Type \\[magit-section-toggle] to expand or hide the section at point. +Type \\[magit-visit-thing] to visit the change or commit at point. + +Type \\[magit-dispatch] to invoke major commands. + +Staging and applying changes is documented in info node +`(magit)Staging and Unstaging' and info node `(magit)Applying'. + +\\<magit-hunk-section-map>Type \ +\\[magit-apply] to apply the change at point, \ +\\[magit-stage] to stage, +\\[magit-unstage] to unstage, \ +\\[magit-discard] to discard, or \ +\\[magit-reverse] to reverse it. + +\\<magit-status-mode-map>\ +Type \\[magit-commit] to create a commit. + +\\{magit-status-mode-map}" + :interactive nil + :group 'magit-status + (magit-hack-dir-local-variables) + (when magit-status-initial-section + (add-hook 'magit-post-create-buffer-hook + #'magit-status-goto-initial-section nil t)) + (setq magit--imenu-group-types '(not branch commit))) + +(put 'magit-status-mode 'magit-diff-default-arguments + '("--no-ext-diff")) +(put 'magit-status-mode 'magit-log-default-arguments + '("-n256" "--decorate")) + +;;;###autoload +(defun magit-status-setup-buffer (&optional directory) + (unless directory + (setq directory default-directory)) + (when (file-remote-p directory) + (magit-git-version-assert)) + (let* ((default-directory directory) + (d (magit-diff--get-value 'magit-status-mode + magit-status-use-buffer-arguments)) + (l (magit-log--get-value 'magit-status-mode + magit-status-use-buffer-arguments)) + (file (and magit-status-goto-file-position + (magit-file-relative-name))) + (line (and file (save-restriction (widen) (line-number-at-pos)))) + (col (and file (save-restriction (widen) (current-column)))) + (buf (magit-setup-buffer #'magit-status-mode nil + (magit-buffer-diff-args (nth 0 d)) + (magit-buffer-diff-files (nth 1 d)) + (magit-buffer-log-args (nth 0 l)) + (magit-buffer-log-files (nth 1 l))))) + (when file + (with-current-buffer buf + (let ((staged (magit-get-section '((staged) (status))))) + (if (and staged + (cadr (magit-diff--locate-hunk file line staged))) + (magit-diff--goto-position file line col staged) + (let ((unstaged (magit-get-section '((unstaged) (status))))) + (unless (and unstaged + (magit-diff--goto-position file line col unstaged)) + (when staged + (magit-diff--goto-position file line col staged)))))))) + buf)) + +(defun magit-status-refresh-buffer () + (magit-git-exit-code "update-index" "--refresh") + (magit-insert-section (status) + (magit-run-section-hook 'magit-status-sections-hook))) + +(defun magit-status-goto-initial-section () + "Jump to the section specified by `magit-status-initial-section'." + (when-let ((section + (--some (if (integerp it) + (nth (1- it) + (magit-section-siblings (magit-current-section) + 'next)) + (magit-get-section it)) + magit-status-initial-section))) + (goto-char (oref section start)) + (when-let ((vis (cdr (assq 'magit-status-initial-section + magit-section-initial-visibility-alist)))) + (if (eq vis 'hide) + (magit-section-hide section) + (magit-section-show section))))) + +(defun magit-status-maybe-update-revision-buffer (&optional _) + "When moving in the status buffer, update the revision buffer. +If there is no revision buffer in the same frame, then do nothing." + (when (derived-mode-p 'magit-status-mode) + (magit--maybe-update-revision-buffer))) + +(defun magit-status-maybe-update-stash-buffer (&optional _) + "When moving in the status buffer, update the stash buffer. +If there is no stash buffer in the same frame, then do nothing." + (when (derived-mode-p 'magit-status-mode) + (magit--maybe-update-stash-buffer))) + +(defun magit-status-maybe-update-blob-buffer (&optional _) + "When moving in the status buffer, update the blob buffer. +If there is no blob buffer in the same frame, then do nothing." + (when (derived-mode-p 'magit-status-mode) + (magit--maybe-update-blob-buffer))) + +;;; Sections +;;;; Special Headers + +(defun magit-insert-status-headers () + "Insert header sections appropriate for `magit-status-mode' buffers. +The sections are inserted by running the functions on the hook +`magit-status-headers-hook'." + (if (magit-rev-verify "HEAD") + (magit-insert-headers 'magit-status-headers-hook) + (insert "In the beginning there was darkness\n\n"))) + +(defvar-keymap magit-error-section-map + :doc "Keymap for `error' sections." + "<remap> <magit-visit-thing>" #'magit-process-buffer + "<1>" (magit-menu-item "Visit process output" #'magit-process-buffer)) + +(defun magit-insert-error-header () + "Insert the message about the Git error that just occurred. + +This function is only aware of the last error that occur when Git +was run for side-effects. If, for example, an error occurs while +generating a diff, then that error won't be inserted. Refreshing +the status buffer causes this section to disappear again." + (when magit-this-error + (magit-insert-section (error 'git) + (insert (propertize (format "%-10s" "GitError! ") + 'font-lock-face 'magit-section-heading)) + (insert (propertize magit-this-error 'font-lock-face 'error)) + (when-let ((key (car (where-is-internal 'magit-process-buffer)))) + (insert (format " [Type `%s' for details]" (key-description key)))) + (insert ?\n)) + (setq magit-this-error nil))) + +(defun magit-insert-diff-filter-header () + "Insert a header line showing the effective diff filters." + (let ((ignore-modules (magit-ignore-submodules-p))) + (when (or ignore-modules + magit-buffer-diff-files) + (insert (propertize (format "%-10s" "Filter! ") + 'font-lock-face 'magit-section-heading)) + (when ignore-modules + (insert ignore-modules) + (when magit-buffer-diff-files + (insert " -- "))) + (when magit-buffer-diff-files + (insert (string-join magit-buffer-diff-files " "))) + (insert ?\n)))) + +;;;; Reference Headers + +(defun magit-insert-head-branch-header (&optional branch) + "Insert a header line about the current branch. +If `HEAD' is detached, then insert information about that commit +instead. The optional BRANCH argument is for internal use only." + (let ((branch (or branch (magit-get-current-branch))) + (output (magit-rev-format "%h %s" (or branch "HEAD")))) + (string-match "^\\([^ ]+\\) \\(.*\\)" output) + (magit-bind-match-strings (commit summary) output + (when (equal summary "") + (setq summary "(no commit message)")) + (if branch + (magit-insert-section (branch branch) + (insert (format "%-10s" "Head: ")) + (when magit-status-show-hashes-in-headers + (insert (propertize commit 'font-lock-face 'magit-hash) ?\s)) + (insert (propertize branch 'font-lock-face 'magit-branch-local)) + (insert ?\s) + (insert (funcall magit-log-format-message-function branch summary)) + (insert ?\n)) + (magit-insert-section (commit commit) + (insert (format "%-10s" "Head: ")) + (insert (propertize commit 'font-lock-face 'magit-hash)) + (insert ?\s) + (insert (funcall magit-log-format-message-function nil summary)) + (insert ?\n)))))) + +(defun magit-insert-upstream-branch-header (&optional branch upstream keyword) + "Insert a header line about the upstream of the current branch. +If no branch is checked out, then insert nothing. The optional +arguments are for internal use only." + (when-let ((branch (or branch (magit-get-current-branch)))) + (let ((remote (magit-get "branch" branch "remote")) + (merge (magit-get "branch" branch "merge")) + (rebase (magit-get "branch" branch "rebase"))) + (when (or remote merge) + (unless upstream + (setq upstream (magit-get-upstream-branch branch))) + (magit-insert-section (branch upstream) + (pcase rebase + ("true") + ("false" (setq rebase nil)) + (_ (setq rebase (magit-get-boolean "pull.rebase")))) + (insert (format "%-10s" (or keyword (if rebase "Rebase: " "Merge: ")))) + (insert + (if upstream + (concat (and magit-status-show-hashes-in-headers + (concat (propertize (magit-rev-format "%h" upstream) + 'font-lock-face 'magit-hash) + " ")) + upstream " " + (funcall magit-log-format-message-function upstream + (funcall magit-log-format-message-function nil + (or (magit-rev-format "%s" upstream) + "(no commit message)")))) + (cond + ((magit--unnamed-upstream-p remote merge) + (concat (propertize merge 'font-lock-face 'magit-branch-remote) + " from " + (propertize remote 'font-lock-face 'bold))) + ((magit--valid-upstream-p remote merge) + (if (equal remote ".") + (concat + (propertize merge 'font-lock-face 'magit-branch-local) " " + (propertize "does not exist" + 'font-lock-face 'magit-branch-warning)) + (format + "%s %s %s" + (propertize merge 'font-lock-face 'magit-branch-remote) + (propertize "does not exist on" + 'font-lock-face 'magit-branch-warning) + (propertize remote 'font-lock-face 'magit-branch-remote)))) + (t + (propertize "invalid upstream configuration" + 'font-lock-face 'magit-branch-warning))))) + (insert ?\n)))))) + +(defun magit-insert-push-branch-header () + "Insert a header line about the branch the current branch is pushed to." + (when-let* ((branch (magit-get-current-branch)) + (target (magit-get-push-branch branch))) + (magit-insert-section (branch target) + (insert (format "%-10s" "Push: ")) + (insert + (if (magit-rev-verify target) + (concat (and magit-status-show-hashes-in-headers + (concat (propertize (magit-rev-format "%h" target) + 'font-lock-face 'magit-hash) + " ")) + target " " + (funcall magit-log-format-message-function target + (funcall magit-log-format-message-function nil + (or (magit-rev-format "%s" target) + "(no commit message)")))) + (let ((remote (magit-get-push-remote branch))) + (if (magit-remote-p remote) + (concat target " " + (propertize "does not exist" + 'font-lock-face 'magit-branch-warning)) + (concat remote " " + (propertize "remote does not exist" + 'font-lock-face 'magit-branch-warning)))))) + (insert ?\n)))) + +(defun magit-insert-tags-header () + "Insert a header line about the current and/or next tag." + (let* ((this-tag (magit-get-current-tag nil t)) + (next-tag (magit-get-next-tag nil t)) + (this-cnt (cadr this-tag)) + (next-cnt (cadr next-tag)) + (this-tag (car this-tag)) + (next-tag (car next-tag)) + (both-tags (and this-tag next-tag t))) + (when (or this-tag next-tag) + (magit-insert-section (tag (or this-tag next-tag)) + (insert (format "%-10s" (if both-tags "Tags: " "Tag: "))) + (cl-flet ((insert-count (tag count face) + (insert (concat (propertize tag 'font-lock-face 'magit-tag) + (and (> count 0) + (format " (%s)" + (propertize + (format "%s" count) + 'font-lock-face face))))))) + (when this-tag (insert-count this-tag this-cnt 'magit-branch-local)) + (when both-tags (insert ", ")) + (when next-tag (insert-count next-tag next-cnt 'magit-tag))) + (insert ?\n))))) + +;;;; Auxiliary Headers + +(defun magit-insert-user-header () + "Insert a header line about the current user." + (let ((name (magit-get "user.name")) + (email (magit-get "user.email"))) + (when (and name email) + (magit-insert-section (user name) + (insert (format "%-10s" "User: ")) + (insert (propertize name 'font-lock-face 'magit-log-author)) + (insert " <" email ">\n"))))) + +(defun magit-insert-repo-header () + "Insert a header line showing the path to the repository top-level." + (let ((topdir (magit-toplevel))) + (magit-insert-section (repo topdir) + (insert (format "%-10s%s\n" "Repo: " (abbreviate-file-name topdir)))))) + +(defun magit-insert-remote-header () + "Insert a header line about the remote of the current branch. + +If no remote is configured for the current branch, then fall back +showing the \"origin\" remote, or if that does not exist the first +remote in alphabetic order." + (when-let* ((name (magit-get-some-remote)) + ;; Under certain configurations it's possible for + ;; url to be nil, when name is not, see #2858. + (url (magit-get "remote" name "url"))) + (magit-insert-section (remote name) + (insert (format "%-10s" "Remote: ")) + (insert (propertize name 'font-lock-face 'magit-branch-remote) ?\s) + (insert url ?\n)))) + +;;;; File Sections + +(defvar-keymap magit-untracked-section-map + :doc "Keymap for the `untracked' section." + "<remap> <magit-delete-thing>" #'magit-discard + "<remap> <magit-stage-file>" #'magit-stage + "<2>" (magit-menu-item "Discard files" #'magit-discard) + "<1>" (magit-menu-item "Stage files" #'magit-stage)) + +(magit-define-section-jumper magit-jump-to-untracked + "Untracked files" untracked nil magit-insert-untracked-files) + +(magit-define-section-jumper magit-jump-to-tracked + "Tracked files" tracked nil magit-insert-tracked-files) + +(magit-define-section-jumper magit-jump-to-ignored + "Ignored files" ignored nil magit-insert-ignored-files) + +(magit-define-section-jumper magit-jump-to-skip-worktree + "Skip-worktree files" skip-worktree nil magit-insert-skip-worktree-files) + +(magit-define-section-jumper magit-jump-to-assume-unchanged + "Assume-unchanged files" assume-unchanged nil + magit-insert-assume-unchanged-files) + +(defun magit-insert-untracked-files () + "Maybe insert a list or tree of untracked files. + +Do so depending on the value of `status.showUntrackedFiles'. +Note that even if the value is `all', Magit still initially +only shows directories. But the directory sections can then +be expanded using \"TAB\". + +If the first element of `magit-buffer-diff-files' is a +directory, then limit the list to files below that. The value +value of that variable can be set using \"D -- DIRECTORY RET g\"." + (let ((show (or (magit-get "status.showUntrackedFiles") "normal"))) + (unless (equal show "no") + (let* ((all (equal show "all")) + (base (car magit-buffer-diff-files)) + (base (and base (file-directory-p base) base))) + (magit-insert-files 'untracked + (lambda () (magit-untracked-files nil base (not all))) + (not all)))))) + +(defun magit-insert-tracked-files () + "Insert a tree of tracked files. + +If the first element of `magit-buffer-diff-files' is a +directory, then limit the list to files below that. The value +value of that variable can be set using \"D -- DIRECTORY RET g\"." + (magit-insert-files 'tracked #'magit-list-files)) + +(defun magit-insert-ignored-files () + "Insert a tree of ignored files. + +If the first element of `magit-buffer-diff-files' is a +directory, then limit the list to files below that. The value +of that variable can be set using \"D -- DIRECTORY RET g\"." + (magit-insert-files 'ignored #'magit-ignored-files)) + +(defun magit-insert-skip-worktree-files () + "Insert a tree of skip-worktree files. + +If the first element of `magit-buffer-diff-files' is a +directory, then limit the list to files below that. The value +of that variable can be set using \"D -- DIRECTORY RET g\"." + (magit-insert-files 'skip-worktree #'magit-skip-worktree-files)) + +(defun magit-insert-assume-unchanged-files () + "Insert a tree of files that are assumed to be unchanged. + +If the first element of `magit-buffer-diff-files' is a +directory, then limit the list to files below that. The value +of that variable can be set using \"D -- DIRECTORY RET g\"." + (magit-insert-files 'assume-unchanged #'magit-assume-unchanged-files)) + +(defvar magit-file-section-indent nil + "Indentation used for simple `file' sections. +If non-nil, this must be a string or character, and is used as +indentation of `file' sections inserted by `magit-insert-*-files'. +`file' sections that are part of diffs are not affected. This is mainly +intended as a workaround for https://github.com/magit/magit/issues/5176, +in which case ?\N{ZERO WIDTH SPACE} is a good value.") + +(defun magit-insert-files (type fn &optional nogroup) + (when-let ((files (funcall fn))) + (let* ((base (car magit-buffer-diff-files)) + (base (and base (file-directory-p base) base)) + (title (symbol-name type))) + (magit-insert-section ((eval type) nil t) + (magit-insert-heading (length files) + (format "%c%s files" + (capitalize (aref title 0)) + (substring title 1))) + (magit-insert-files-1 files base nogroup) + (insert ?\n))))) + +(defun magit-insert-files-1 (files directory &optional nogroup) + (while (and files (or nogroup + (not directory) + (string-prefix-p directory (car files)))) + (let ((dir (file-name-directory (car files)))) + (if (or nogroup (equal dir directory)) + (let ((file (pop files))) + (magit-insert-section (file file) + (when magit-file-section-indent + (insert magit-file-section-indent)) + (insert (propertize file 'font-lock-face 'magit-filename) ?\n))) + (magit-insert-section (file dir t) + (when magit-file-section-indent + (insert magit-file-section-indent)) + (insert (propertize dir 'file 'magit-filename) ?\n) + (magit-insert-heading) + (setq files (magit-insert-files-1 files dir)))))) + files) + +;;; _ +(provide 'magit-status) +;;; magit-status.el ends here diff --git a/emacs/elpa/magit-20241004.917/magit-submodule.el b/emacs/elpa/magit-20241004.917/magit-submodule.el @@ -0,0 +1,724 @@ +;;; magit-submodule.el --- Submodule support for Magit -*- lexical-binding:t -*- + +;; Copyright (C) 2008-2024 The Magit Project Contributors + +;; Author: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> +;; Maintainer: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> + +;; SPDX-License-Identifier: GPL-3.0-or-later + +;; Magit is free software: you can redistribute it and/or modify it +;; under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. +;; +;; Magit is distributed in the hope that it will be useful, but WITHOUT +;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +;; or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public +;; License for more details. +;; +;; You should have received a copy of the GNU General Public License +;; along with Magit. If not, see <https://www.gnu.org/licenses/>. + +;;; Code: + +(require 'magit) + +(defvar x-stretch-cursor) + +;;; Options + +(defcustom magit-module-sections-hook + '(magit-insert-modules-overview + magit-insert-modules-unpulled-from-upstream + magit-insert-modules-unpulled-from-pushremote + magit-insert-modules-unpushed-to-upstream + magit-insert-modules-unpushed-to-pushremote) + "Hook run by `magit-insert-modules'. + +That function isn't part of `magit-status-sections-hook's default +value, so you have to add it yourself for this hook to have any +effect." + :package-version '(magit . "2.11.0") + :group 'magit-status + :type 'hook) + +(defcustom magit-module-sections-nested t + "Whether `magit-insert-modules' wraps inserted sections. + +If this is non-nil, then only a single top-level section +is inserted. If it is nil, then all sections listed in +`magit-module-sections-hook' become top-level sections." + :package-version '(magit . "2.11.0") + :group 'magit-status + :type 'boolean) + +(defcustom magit-submodule-list-mode-hook '(hl-line-mode) + "Hook run after entering Magit-Submodule-List mode." + :package-version '(magit . "2.9.0") + :group 'magit-repolist + :type 'hook + :get 'magit-hook-custom-get + :options '(hl-line-mode)) + +(defcustom magit-submodule-list-columns + '(("Path" 25 magit-modulelist-column-path + ()) + ("Version" 25 magit-repolist-column-version + ((:sort magit-repolist-version<))) + ("Branch" 20 magit-repolist-column-branch + ()) + ("B<P" 3 magit-repolist-column-unpulled-from-pushremote + ((:right-align t) + (:sort <))) + ("B<U" 3 magit-repolist-column-unpulled-from-upstream + ((:right-align t) + (:sort <))) + ("B>P" 3 magit-repolist-column-unpushed-to-pushremote + ((:right-align t) + (:sort <))) + ("B>U" 3 magit-repolist-column-unpushed-to-upstream + ((:right-align t) + (:sort <))) + ("S" 3 magit-repolist-column-stashes + ((:right-align t) + (:sort <))) + ("B" 3 magit-repolist-column-branches + ((:right-align t) + (:sort <)))) + "List of columns displayed by `magit-list-submodules'. + +Each element has the form (HEADER WIDTH FORMAT PROPS). + +HEADER is the string displayed in the header. WIDTH is the width +of the column. FORMAT is a function that is called with one +argument, the repository identification (usually its basename), +and with `default-directory' bound to the toplevel of its working +tree. It has to return a string to be inserted or nil. PROPS is +an alist that supports the keys `:right-align', `:pad-right' and +`:sort'. + +The `:sort' function has a weird interface described in the +docstring of `tabulated-list--get-sort'. Alternatively `<' and +`magit-repolist-version<' can be used as those functions are +automatically replaced with functions that satisfy the interface. +Set `:sort' to nil to inhibit sorting; if unspecified, then the +column is sortable using the default sorter. + +You may wish to display a range of numeric columns using just one +character per column and without any padding between columns, in +which case you should use an appropriate HEADER, set WIDTH to 1, +and set `:pad-right' to 0. \"+\" is substituted for numbers higher +than 9." + :package-version '(magit . "2.8.0") + :group 'magit-repolist + :type `(repeat (list :tag "Column" + (string :tag "Header Label") + (integer :tag "Column Width") + (function :tag "Inserter Function") + (repeat :tag "Properties" + (list (choice :tag "Property" + (const :right-align) + (const :pad-right) + (const :sort) + (symbol)) + (sexp :tag "Value")))))) + +(defcustom magit-submodule-list-sort-key '("Path" . nil) + "Initial sort key for buffer created by `magit-list-submodules'. +If nil, no additional sorting is performed. Otherwise, this +should be a cons cell (NAME . FLIP). NAME is a string matching +one of the column names in `magit-submodule-list-columns'. FLIP, +if non-nil, means to invert the resulting sort." + :package-version '(magit . "3.2.0") + :group 'magit-repolist + :type '(choice (const nil) + (cons (string :tag "Column name") + (boolean :tag "Flip order")))) + +(defvar magit-submodule-list-format-path-functions nil) + +(defcustom magit-submodule-remove-trash-gitdirs nil + "Whether `magit-submodule-remove' offers to trash module gitdirs. + +If this is nil, then that command does not offer to do so unless +a prefix argument is used. When this is t, then it does offer to +do so even without a prefix argument. + +In both cases the action still has to be confirmed unless that is +disabled using the option `magit-no-confirm'. Doing the latter +and also setting this variable to t will lead to tears." + :package-version '(magit . "2.90.0") + :group 'magit-commands + :type 'boolean) + +;;; Popup + +;;;###autoload (autoload 'magit-submodule "magit-submodule" nil t) +(transient-define-prefix magit-submodule () + "Act on a submodule." + :man-page "git-submodule" + ["Arguments" + ("-f" "Force" ("-f" "--force")) + ("-r" "Recursive" "--recursive") + ("-N" "Do not fetch" ("-N" "--no-fetch")) + ("-C" "Checkout tip" "--checkout") + ("-R" "Rebase onto tip" "--rebase") + ("-M" "Merge tip" "--merge") + ("-U" "Use upstream tip" "--remote")] + ["One module actions" + ("a" magit-submodule-add) + ("r" magit-submodule-register) + ("p" magit-submodule-populate) + ("u" magit-submodule-update) + ("s" magit-submodule-synchronize) + ("d" magit-submodule-unpopulate) + ("k" "Remove" magit-submodule-remove)] + ["Populated modules actions" + ("l" "List modules" magit-list-submodules) + ("f" "Fetch modules" magit-fetch-modules)]) + +(defun magit-submodule-arguments (&rest filters) + (--filter (and (member it filters) it) + (transient-args 'magit-submodule))) + +(defclass magit--git-submodule-suffix (transient-suffix) + ()) + +(cl-defmethod transient-format-description ((obj magit--git-submodule-suffix)) + (let ((value (delq nil (mapcar #'transient-infix-value transient--suffixes)))) + (replace-regexp-in-string + "\\[--[^]]+\\]" + (lambda (match) + (format (propertize "[%s]" 'face 'transient-inactive-argument) + (mapconcat (lambda (arg) + (propertize arg 'face + (if (member arg value) + 'transient-argument + 'transient-inactive-argument))) + (save-match-data + (split-string (substring match 1 -1) "|")) + (propertize "|" 'face 'transient-inactive-argument)))) + (cl-call-next-method obj)))) + +;;;###autoload (autoload 'magit-submodule-add "magit-submodule" nil t) +(transient-define-suffix magit-submodule-add (url &optional path name args) + "Add the repository at URL as a module. + +Optional PATH is the path to the module relative to the root of +the superproject. If it is nil, then the path is determined +based on the URL. Optional NAME is the name of the module. If +it is nil, then PATH also becomes the name." + :class 'magit--git-submodule-suffix + :description "Add git submodule add [--force]" + (interactive + (magit-with-toplevel + (let* ((url (magit-read-string-ns "Add submodule (remote url)")) + (path (let ((read-file-name-function + (if (or (eq read-file-name-function 'ido-read-file-name) + (advice-function-member-p + 'ido-read-file-name + read-file-name-function)) + ;; The Ido variant doesn't work properly here. + #'read-file-name-default + read-file-name-function))) + (directory-file-name + (file-relative-name + (read-directory-name + "Add submodules at path: " nil nil nil + (and (string-match "\\([^./]+\\)\\(\\.git\\)?$" url) + (match-string 1 url)))))))) + (list url + (directory-file-name path) + (magit-submodule-read-name-for-path path) + (magit-submodule-arguments "--force"))))) + (magit-submodule-add-1 url path name args)) + +(defun magit-submodule-add-1 (url &optional path name args) + (magit-with-toplevel + (magit-submodule--maybe-reuse-gitdir name path) + (magit-run-git-async "submodule" "add" + (and name (list "--name" name)) + args "--" url path) + (set-process-sentinel + magit-this-process + (lambda (process event) + (when (memq (process-status process) '(exit signal)) + (if (> (process-exit-status process) 0) + (magit-process-sentinel process event) + (process-put process 'inhibit-refresh t) + (magit-process-sentinel process event) + (when (magit-git-version>= "2.12.0") + (magit-call-git "submodule" "absorbgitdirs" path)) + (magit-refresh))))))) + +;;;###autoload +(defun magit-submodule-read-name-for-path (path &optional prefer-short) + (let* ((path (directory-file-name (file-relative-name path))) + (name (file-name-nondirectory path))) + (push (if prefer-short path name) minibuffer-history) + (magit-read-string-ns + "Submodule name" nil (cons 'minibuffer-history 2) + (or (--keep (pcase-let ((`(,var ,val) (split-string it "="))) + (and (equal val path) + (cadr (split-string var "\\.")))) + (magit-git-lines "config" "--list" "-f" ".gitmodules")) + (if prefer-short name path))))) + +;;;###autoload (autoload 'magit-submodule-register "magit-submodule" nil t) +(transient-define-suffix magit-submodule-register (modules) + "Register MODULES. + +With a prefix argument act on all suitable modules. Otherwise, +if the region selects modules, then act on those. Otherwise, if +there is a module at point, then act on that. Otherwise read a +single module from the user." + ;; This command and the underlying "git submodule init" do NOT + ;; "initialize" modules. They merely "register" modules in the + ;; super-projects $GIT_DIR/config file, the purpose of which is to + ;; allow users to change such values before actually initializing + ;; the modules. + :description "Register git submodule init" + (interactive + (list (magit-module-confirm "Register" 'magit-module-no-worktree-p))) + (magit-with-toplevel + (magit-run-git-async "submodule" "init" "--" modules))) + +;;;###autoload (autoload 'magit-submodule-populate "magit-submodule" nil t) +(transient-define-suffix magit-submodule-populate (modules) + "Create MODULES working directories, checking out the recorded commits. + +With a prefix argument act on all suitable modules. Otherwise, +if the region selects modules, then act on those. Otherwise, if +there is a module at point, then act on that. Otherwise read a +single module from the user." + ;; This is the command that actually "initializes" modules. + ;; A module is initialized when it has a working directory, + ;; a gitlink, and a .gitmodules entry. + :description "Populate git submodule update --init" + (interactive + (list (magit-module-confirm "Populate" 'magit-module-no-worktree-p))) + (magit-with-toplevel + (magit-run-git-async "submodule" "update" "--init" "--" modules))) + +;;;###autoload (autoload 'magit-submodule-update "magit-submodule" nil t) +(transient-define-suffix magit-submodule-update (modules args) + "Update MODULES by checking out the recorded commits. + +With a prefix argument act on all suitable modules. Otherwise, +if the region selects modules, then act on those. Otherwise, if +there is a module at point, then act on that. Otherwise read a +single module from the user." + ;; Unlike `git-submodule's `update' command ours can only update + ;; "initialized" modules by checking out other commits but not + ;; "initialize" modules by creating the working directories. + ;; To do the latter we provide the "setup" command. + :class 'magit--git-submodule-suffix + :description "Update git submodule update [--force] [--no-fetch] + [--remote] [--recursive] [--checkout|--rebase|--merge]" + (interactive + (list (magit-module-confirm "Update" 'magit-module-worktree-p) + (magit-submodule-arguments + "--force" "--remote" "--recursive" "--checkout" "--rebase" "--merge" + "--no-fetch"))) + (magit-with-toplevel + (magit-run-git-async "submodule" "update" args "--" modules))) + +;;;###autoload (autoload 'magit-submodule-synchronize "magit-submodule" nil t) +(transient-define-suffix magit-submodule-synchronize (modules args) + "Synchronize url configuration of MODULES. + +With a prefix argument act on all suitable modules. Otherwise, +if the region selects modules, then act on those. Otherwise, if +there is a module at point, then act on that. Otherwise read a +single module from the user." + :class 'magit--git-submodule-suffix + :description "Synchronize git submodule sync [--recursive]" + (interactive + (list (magit-module-confirm "Synchronize" 'magit-module-worktree-p) + (magit-submodule-arguments "--recursive"))) + (magit-with-toplevel + (magit-run-git-async "submodule" "sync" args "--" modules))) + +;;;###autoload (autoload 'magit-submodule-unpopulate "magit-submodule" nil t) +(transient-define-suffix magit-submodule-unpopulate (modules args) + "Remove working directories of MODULES. + +With a prefix argument act on all suitable modules. Otherwise, +if the region selects modules, then act on those. Otherwise, if +there is a module at point, then act on that. Otherwise read a +single module from the user." + ;; Even when a submodule is "uninitialized" (it has no worktree) + ;; the super-project's $GIT_DIR/config may never-the-less set the + ;; module's url. This may happen if you `deinit' and then `init' + ;; to register (NOT initialize). Because the purpose of `deinit' + ;; is to remove the working directory AND to remove the url, this + ;; command does not limit itself to modules that have no working + ;; directory. + :class 'magit--git-submodule-suffix + :description "Unpopulate git submodule deinit [--force]" + (interactive + (list (magit-module-confirm "Unpopulate") + (magit-submodule-arguments "--force"))) + (magit-with-toplevel + (magit-run-git-async "submodule" "deinit" args "--" modules))) + +;;;###autoload +(defun magit-submodule-remove (modules args trash-gitdirs) + "Unregister MODULES and remove their working directories. + +For safety reasons, do not remove the gitdirs and if a module has +uncommitted changes, then do not remove it at all. If a module's +gitdir is located inside the working directory, then move it into +the gitdir of the superproject first. + +With the \"--force\" argument offer to remove dirty working +directories and with a prefix argument offer to delete gitdirs. +Both actions are very dangerous and have to be confirmed. There +are additional safety precautions in place, so you might be able +to recover from making a mistake here, but don't count on it." + (interactive + (list (if-let ((modules (magit-region-values 'magit-module-section t))) + (magit-confirm 'remove-modules nil "Remove %d modules" nil modules) + (list (magit-read-module-path "Remove module"))) + (magit-submodule-arguments "--force") + current-prefix-arg)) + (when (magit-git-version< "2.12.0") + (error "This command requires Git v2.12.0")) + (when magit-submodule-remove-trash-gitdirs + (setq trash-gitdirs t)) + (magit-with-toplevel + (when-let + ((modified + (seq-filter (lambda (module) + (let ((default-directory (file-name-as-directory + (expand-file-name module)))) + (and (cddr (directory-files default-directory)) + (magit-anything-modified-p)))) + modules))) + (if (member "--force" args) + (if (magit-confirm 'remove-dirty-modules + "Remove dirty module %s" + "Remove %d dirty modules" + t modified) + (dolist (module modified) + (let ((default-directory (file-name-as-directory + (expand-file-name module)))) + (magit-git "stash" "push" + "-m" "backup before removal of this module"))) + (setq modules (cl-set-difference modules modified :test #'equal))) + (if (cdr modified) + (message "Omitting %s modules with uncommitted changes: %s" + (length modified) + (string-join modified ", ")) + (message "Omitting module %s, it has uncommitted changes" + (car modified))) + (setq modules (cl-set-difference modules modified :test #'equal)))) + (when modules + (let ((alist + (and trash-gitdirs + (--map (split-string it "\0") + (magit-git-lines "submodule" "foreach" "-q" + "printf \"$sm_path\\0$name\n\""))))) + (magit-git "submodule" "absorbgitdirs" "--" modules) + (magit-git "submodule" "deinit" args "--" modules) + (magit-git "rm" args "--" modules) + (when (and trash-gitdirs + (magit-confirm 'trash-module-gitdirs + "Trash gitdir of module %s" + "Trash gitdirs of %d modules" + t modules)) + (dolist (module modules) + (if-let ((name (cadr (assoc module alist)))) + ;; Disregard if `magit-delete-by-moving-to-trash' + ;; is nil. Not doing so would be too dangerous. + (delete-directory (convert-standard-filename + (expand-file-name + (concat "modules/" name) + (magit-gitdir))) + t t) + (error "BUG: Weird module name and/or path for %s" module))))) + (magit-refresh)))) + +;;; Sections + +;;;###autoload +(defun magit-insert-modules () + "Insert submodule sections. +Hook `magit-module-sections-hook' controls which module sections +are inserted, and option `magit-module-sections-nested' controls +whether they are wrapped in an additional section." + (when-let ((modules (magit-list-module-paths))) + (if magit-module-sections-nested + (magit-insert-section (modules nil t) + (magit-insert-heading + (format "%s (%s)" + (propertize "Modules" + 'font-lock-face 'magit-section-heading) + (length modules))) + (magit-insert-section-body + (magit--insert-modules))) + (magit--insert-modules)))) + +(defun magit--insert-modules (&optional _section) + (magit-run-section-hook 'magit-module-sections-hook)) + +;;;###autoload +(defun magit-insert-modules-overview () + "Insert sections for all modules. +For each section insert the path and the output of `git describe --tags', +or, failing that, the abbreviated HEAD commit hash." + (when-let ((modules (magit-list-module-paths))) + (magit-insert-section (modules nil t) + (magit-insert-heading + (format "%s (%s)" + (propertize "Modules overview" + 'font-lock-face 'magit-section-heading) + (length modules))) + (magit-insert-section-body + (magit--insert-modules-overview))))) + +(defvar magit-modules-overview-align-numbers t) + +(defun magit--insert-modules-overview (&optional _section) + (magit-with-toplevel + (let* ((modules (magit-list-module-paths)) + (path-format (format "%%-%ds " + (min (apply #'max (mapcar #'length modules)) + (/ (window-width) 2)))) + (branch-format (format "%%-%ds " (min 25 (/ (window-width) 3))))) + (dolist (module modules) + (let ((default-directory + (expand-file-name (file-name-as-directory module)))) + (magit-insert-section (module module t) + (insert (propertize (format path-format module) + 'font-lock-face 'magit-diff-file-heading)) + (if (not (file-exists-p ".git")) + (insert "(unpopulated)") + (insert + (format + branch-format + (if-let ((branch (magit-get-current-branch))) + (propertize branch 'font-lock-face 'magit-branch-local) + (propertize "(detached)" 'font-lock-face 'warning)))) + (if-let ((desc (magit-git-string "describe" "--tags"))) + (progn (when (and magit-modules-overview-align-numbers + (string-match-p "\\`[0-9]" desc)) + (insert ?\s)) + (insert (propertize desc 'font-lock-face 'magit-tag))) + (when-let ((abbrev (magit-rev-format "%h"))) + (insert (propertize abbrev 'font-lock-face 'magit-hash))))) + (insert ?\n)))))) + (insert ?\n)) + +(defvar-keymap magit-modules-section-map + :doc "Keymap for `modules' sections." + "<remap> <magit-visit-thing>" #'magit-list-submodules + "<1>" (magit-menu-item "List %t" #'magit-list-submodules)) + +(defvar-keymap magit-module-section-map + :doc "Keymap for `module' sections." + "C-j" #'magit-submodule-visit + "C-<return>" #'magit-submodule-visit + "<remap> <magit-unstage-file>" #'magit-unstage + "<remap> <magit-stage-file>" #'magit-stage + "<remap> <magit-visit-thing>" #'magit-submodule-visit + "<5>" (magit-menu-item "Module commands..." #'magit-submodule) + "<4>" '(menu-item "--") + "<3>" (magit-menu-item "Unstage %T" #'magit-unstage + '(:visible (eq (magit-diff-type) 'staged))) + "<2>" (magit-menu-item "Stage %T" #'magit-stage + '(:visible (eq (magit-diff-type) 'unstaged))) + "<1>" (magit-menu-item "Visit %s" #'magit-submodule-visit)) + +(defun magit-submodule-visit (module &optional other-window) + "Visit MODULE by calling `magit-status' on it. +Offer to initialize MODULE if it's not checked out yet. +With a prefix argument, visit in another window." + (interactive (list (or (magit-section-value-if 'module) + (magit-read-module-path "Visit module")) + current-prefix-arg)) + (magit-with-toplevel + (let ((path (expand-file-name module))) + (cond + ((file-exists-p (expand-file-name ".git" module)) + (magit-diff-visit-directory path other-window)) + ((y-or-n-p (format "Initialize submodule '%s' first?" module)) + (magit-run-git-async "submodule" "update" "--init" "--" module) + (set-process-sentinel + magit-this-process + (lambda (process event) + (let ((magit-process-raise-error t)) + (magit-process-sentinel process event)) + (when (and (eq (process-status process) 'exit) + (= (process-exit-status process) 0)) + (magit-diff-visit-directory path other-window))))) + ((file-exists-p path) + (dired-jump other-window (concat path "/."))))))) + +;;;###autoload +(defun magit-insert-modules-unpulled-from-upstream () + "Insert sections for modules that haven't been pulled from the upstream. +These sections can be expanded to show the respective commits." + (magit--insert-modules-logs "Modules unpulled from @{upstream}" + 'modules-unpulled-from-upstream + "HEAD..@{upstream}")) + +;;;###autoload +(defun magit-insert-modules-unpulled-from-pushremote () + "Insert sections for modules that haven't been pulled from the push-remote. +These sections can be expanded to show the respective commits." + (magit--insert-modules-logs "Modules unpulled from @{push}" + 'modules-unpulled-from-pushremote + "HEAD..@{push}")) + +;;;###autoload +(defun magit-insert-modules-unpushed-to-upstream () + "Insert sections for modules that haven't been pushed to the upstream. +These sections can be expanded to show the respective commits." + (magit--insert-modules-logs "Modules unmerged into @{upstream}" + 'modules-unpushed-to-upstream + "@{upstream}..HEAD")) + +;;;###autoload +(defun magit-insert-modules-unpushed-to-pushremote () + "Insert sections for modules that haven't been pushed to the push-remote. +These sections can be expanded to show the respective commits." + (magit--insert-modules-logs "Modules unpushed to @{push}" + 'modules-unpushed-to-pushremote + "@{push}..HEAD")) + +(defun magit--insert-modules-logs (heading type range) + "For internal use, don't add to a hook." + (unless (magit-ignore-submodules-p) + (when-let ((modules (magit-list-module-paths))) + (magit-insert-section ((eval type) nil t) + (string-match "\\`\\(.+\\) \\([^ ]+\\)\\'" heading) + (magit-insert-heading + (propertize (match-string 1 heading) + 'font-lock-face 'magit-section-heading) + " " + (propertize (match-string 2 heading) + 'font-lock-face 'magit-branch-remote) + ":") + (dolist (module modules) + (when-let* ((default-directory (expand-file-name module)) + ((file-exists-p (expand-file-name ".git"))) + (lines (magit-git-lines "-c" "push.default=current" + "log" "--oneline" range)) + (count (length lines)) + ((> count 0))) + (magit-insert-section + ( module module t + :range range) + (magit-insert-heading count + (propertize module 'font-lock-face 'magit-diff-file-heading)) + (dolist (line lines) + (string-match magit-log-module-re line) + (let ((rev (match-string 1 line)) + (msg (match-string 2 line))) + (magit-insert-section (module-commit rev t) + (insert (propertize rev 'font-lock-face 'magit-hash) " " + (funcall magit-log-format-message-function rev msg) + "\n"))))))) + (magit-cancel-section 'if-empty) + (insert ?\n))))) + +;;; List + +;;;###autoload +(defun magit-list-submodules () + "Display a list of the current repository's populated submodules." + (interactive) + (magit-submodule-list-setup magit-submodule-list-columns)) + +(defvar-keymap magit-submodule-list-mode-map + :doc "Local keymap for Magit-Submodule-List mode buffers." + :parent magit-repolist-mode-map) + +(define-derived-mode magit-submodule-list-mode tabulated-list-mode "Modules" + "Major mode for browsing a list of Git submodules." + :interactive nil + :group 'magit-repolist + (setq-local x-stretch-cursor nil) + (setq tabulated-list-padding 0) + (add-hook 'tabulated-list-revert-hook #'magit-submodule-list-refresh nil t) + (setq imenu-prev-index-position-function + #'magit-repolist--imenu-prev-index-position) + (setq imenu-extract-index-name-function #'tabulated-list-get-id)) + +(defvar-local magit-submodule-list-predicate nil) + +(defun magit-submodule-list-setup (columns &optional predicate) + (magit-display-buffer + (or (magit-get-mode-buffer 'magit-submodule-list-mode) + (magit-generate-new-buffer 'magit-submodule-list-mode))) + (magit-submodule-list-mode) + (setq-local magit-repolist-columns columns) + (setq-local magit-repolist-sort-key magit-submodule-list-sort-key) + (setq-local magit-submodule-list-predicate predicate) + (magit-repolist-setup-1) + (magit-submodule-list-refresh)) + +(defun magit-submodule-list-refresh () + (setq tabulated-list-entries + (seq-keep + (lambda (module) + (let ((default-directory + (expand-file-name (file-name-as-directory module)))) + (and (file-exists-p ".git") + (or (not magit-submodule-list-predicate) + (funcall magit-submodule-list-predicate module)) + (list module + (vconcat + (mapcar (pcase-lambda (`(,title ,width ,fn ,props)) + (or (funcall fn `((:path ,module) + (:title ,title) + (:width ,width) + ,@props)) + "")) + magit-repolist-columns)))))) + (magit-list-module-paths))) + (message "Listing submodules...") + (tabulated-list-init-header) + (tabulated-list-print t) + (message "Listing submodules...done")) + +(defun magit-modulelist-column-path (spec) + "Insert the relative path of the submodule." + (let ((path (cadr (assq :path spec)))) + (or (run-hook-with-args-until-success + 'magit-submodule-list-format-path-functions path) + path))) + +;;; Utilities + +(defun magit-submodule--maybe-reuse-gitdir (name path) + (let ((gitdir (convert-standard-filename + (expand-file-name (concat "modules/" name) + (magit-gitdir))))) + (when (and (file-exists-p gitdir) + (not (file-exists-p path))) + (pcase (read-char-choice + (concat + gitdir " already exists.\n" + "Type [u] to use the existing gitdir and create the working tree\n" + " [r] to rename the existing gitdir and clone again\n" + " [t] to trash the existing gitdir and clone again\n" + " [C-g] to abort ") + '(?u ?r ?t)) + (?u (magit-submodule--restore-worktree (expand-file-name path) gitdir)) + (?r (rename-file gitdir (concat gitdir "-" + (format-time-string "%F-%T")))) + (?t (delete-directory gitdir t t)))))) + +(defun magit-submodule--restore-worktree (worktree gitdir) + (make-directory worktree t) + (with-temp-file (expand-file-name ".git" worktree) + (insert "gitdir: " (file-relative-name gitdir worktree) "\n")) + (let ((default-directory worktree)) + (magit-call-git "reset" "--hard" "HEAD" "--"))) + +;;; _ +(provide 'magit-submodule) +;;; magit-submodule.el ends here diff --git a/emacs/elpa/magit-20241004.917/magit-subtree.el b/emacs/elpa/magit-20241004.917/magit-subtree.el @@ -0,0 +1,181 @@ +;;; magit-subtree.el --- Subtree support for Magit -*- lexical-binding:t -*- + +;; Copyright (C) 2008-2024 The Magit Project Contributors + +;; Author: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> +;; Maintainer: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> + +;; SPDX-License-Identifier: GPL-3.0-or-later + +;; Magit is free software: you can redistribute it and/or modify it +;; under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. +;; +;; Magit is distributed in the hope that it will be useful, but WITHOUT +;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +;; or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public +;; License for more details. +;; +;; You should have received a copy of the GNU General Public License +;; along with Magit. If not, see <https://www.gnu.org/licenses/>. + +;;; Code: + +(require 'magit) + +;;; Commands + +;;;###autoload (autoload 'magit-subtree "magit-subtree" nil t) +(transient-define-prefix magit-subtree () + "Import or export subtrees." + :man-page "git-subtree" + ["Actions" + ("i" "Import" magit-subtree-import) + ("e" "Export" magit-subtree-export)]) + +;;;###autoload (autoload 'magit-subtree-import "magit-subtree" nil t) +(transient-define-prefix magit-subtree-import () + "Import subtrees." + :man-page "git-subtree" + ["Arguments" + (magit-subtree:--prefix) + (magit-subtree:--message) + ("-s" "Squash" "--squash")] + ["Actions" + [("a" "Add" magit-subtree-add) + ("c" "Add commit" magit-subtree-add-commit)] + [("m" "Merge" magit-subtree-merge) + ("f" "Pull" magit-subtree-pull)]]) + +;;;###autoload (autoload 'magit-subtree-export "magit-subtree" nil t) +(transient-define-prefix magit-subtree-export () + "Export subtrees." + :man-page "git-subtree" + ["Arguments" + (magit-subtree:--prefix) + (magit-subtree:--annotate) + (magit-subtree:--branch) + (magit-subtree:--onto) + ("-i" "Ignore joins" "--ignore-joins") + ("-j" "Rejoin" "--rejoin")] + ["Actions" + ("p" "Push" magit-subtree-push) + ("s" "Split" magit-subtree-split)]) + +(transient-define-argument magit-subtree:--prefix () + :description "Prefix" + :class 'transient-option + :shortarg "-P" + :argument "--prefix=" + :reader #'magit-subtree-read-prefix) + +(defun magit-subtree-read-prefix (prompt &optional default _history) + (let* ((insert-default-directory nil) + (topdir (magit-toplevel)) + (prefix (read-directory-name (concat prompt ": ") topdir default))) + (if (file-name-absolute-p prefix) + ;; At least `ido-mode's variant is not compatible. + (if (string-prefix-p topdir prefix) + (file-relative-name prefix topdir) + (user-error "%s isn't inside the repository at %s" prefix topdir)) + prefix))) + +(transient-define-argument magit-subtree:--message () + :description "Message" + :class 'transient-option + :shortarg "-m" + :argument "--message=") + +(transient-define-argument magit-subtree:--annotate () + :description "Annotate" + :class 'transient-option + :key "-a" + :argument "--annotate=") + +(transient-define-argument magit-subtree:--branch () + :description "Branch" + :class 'transient-option + :shortarg "-b" + :argument "--branch=") + +(transient-define-argument magit-subtree:--onto () + :description "Onto" + :class 'transient-option + :key "-o" + :argument "--onto=" + :reader #'magit-transient-read-revision) + +(defun magit-subtree-prefix (transient prompt) + (if-let ((arg (--first (string-prefix-p "--prefix=" it) + (transient-args transient)))) + (substring arg 9) + (magit-subtree-read-prefix prompt))) + +(defun magit-subtree-arguments (transient) + (--remove (string-prefix-p "--prefix=" it) + (transient-args transient))) + +(defun magit-git-subtree (subcmd prefix &rest args) + (magit-run-git-async "subtree" subcmd (concat "--prefix=" prefix) args)) + +;;;###autoload +(defun magit-subtree-add (prefix repository ref args) + "Add REF from REPOSITORY as a new subtree at PREFIX." + (interactive + (cons (magit-subtree-prefix 'magit-subtree-import "Add subtree") + (let ((remote (magit-read-remote-or-url "From repository"))) + (list remote + (magit-read-refspec "Ref" remote) + (magit-subtree-arguments 'magit-subtree-import))))) + (magit-git-subtree "add" prefix args repository ref)) + +;;;###autoload +(defun magit-subtree-add-commit (prefix commit args) + "Add COMMIT as a new subtree at PREFIX." + (interactive + (list (magit-subtree-prefix 'magit-subtree-import "Add subtree") + (magit-read-string-ns "Commit") + (magit-subtree-arguments 'magit-subtree-import))) + (magit-git-subtree "add" prefix args commit)) + +;;;###autoload +(defun magit-subtree-merge (prefix commit args) + "Merge COMMIT into the PREFIX subtree." + (interactive + (list (magit-subtree-prefix 'magit-subtree-import "Merge into subtree") + (magit-read-string-ns "Commit") + (magit-subtree-arguments 'magit-subtree-import))) + (magit-git-subtree "merge" prefix args commit)) + +;;;###autoload +(defun magit-subtree-pull (prefix repository ref args) + "Pull REF from REPOSITORY into the PREFIX subtree." + (interactive + (cons (magit-subtree-prefix 'magit-subtree-import "Pull into subtree") + (let ((remote (magit-read-remote-or-url "From repository"))) + (list remote + (magit-read-refspec "Ref" remote) + (magit-subtree-arguments 'magit-subtree-import))))) + (magit-git-subtree "pull" prefix args repository ref)) + +;;;###autoload +(defun magit-subtree-push (prefix repository ref args) + "Extract the history of the subtree PREFIX and push it to REF on REPOSITORY." + (interactive (list (magit-subtree-prefix 'magit-subtree-export "Push subtree") + (magit-read-remote-or-url "To repository") + (magit-read-string-ns "To reference") + (magit-subtree-arguments 'magit-subtree-export))) + (magit-git-subtree "push" prefix args repository ref)) + +;;;###autoload +(defun magit-subtree-split (prefix commit args) + "Extract the history of the subtree PREFIX." + (interactive (list (magit-subtree-prefix 'magit-subtree-export "Split subtree") + (magit-read-string-ns "Commit") + (magit-subtree-arguments 'magit-subtree-export))) + (magit-git-subtree "split" prefix args commit)) + +;;; _ +(provide 'magit-subtree) +;;; magit-subtree.el ends here diff --git a/emacs/elpa/magit-20241004.917/magit-tag.el b/emacs/elpa/magit-20241004.917/magit-tag.el @@ -0,0 +1,248 @@ +;;; magit-tag.el --- Tag functionality -*- lexical-binding:t -*- + +;; Copyright (C) 2008-2024 The Magit Project Contributors + +;; Author: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> +;; Maintainer: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> + +;; SPDX-License-Identifier: GPL-3.0-or-later + +;; Magit is free software: you can redistribute it and/or modify it +;; under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. +;; +;; Magit is distributed in the hope that it will be useful, but WITHOUT +;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +;; or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public +;; License for more details. +;; +;; You should have received a copy of the GNU General Public License +;; along with Magit. If not, see <https://www.gnu.org/licenses/>. + +;;; Commentary: + +;; This library implements tag commands. + +;;; Code: + +(require 'magit) + +;; For `magit-tag-delete'. +(defvar helm-comp-read-use-marked) + +;;; Commands + +;;;###autoload (autoload 'magit-tag "magit" nil t) +(transient-define-prefix magit-tag () + "Create or delete a tag." + :man-page "git-tag" + ["Arguments" + ("-f" "Force" ("-f" "--force")) + ("-e" "Edit message" ("-e" "--edit")) + ("-a" "Annotate" ("-a" "--annotate")) + ("-s" "Sign" ("-s" "--sign")) + (magit-tag:--local-user)] + [["Create" + ("t" "tag" magit-tag-create) + ("r" "release" magit-tag-release)] + ["Do" + ("k" "delete" magit-tag-delete) + ("p" "prune" magit-tag-prune)]]) + +(defun magit-tag-arguments () + (transient-args 'magit-tag)) + +(transient-define-argument magit-tag:--local-user () + :description "Sign as" + :class 'transient-option + :shortarg "-u" + :argument "--local-user=" + :reader #'magit-read-gpg-signing-key + :history-key 'magit:--gpg-sign) + +;;;###autoload +(defun magit-tag-create (name rev &optional args) + "Create a new tag with the given NAME at REV. +With a prefix argument annotate the tag. +\n(git tag [--annotate] NAME REV)" + (interactive (list (magit-read-tag "Tag name") + (magit-read-branch-or-commit "Place tag on") + (let ((args (magit-tag-arguments))) + (when current-prefix-arg + (cl-pushnew "--annotate" args :test #'equal)) + args))) + (magit-run-git-with-editor "tag" args name rev)) + +;;;###autoload +(defun magit-tag-delete (tags) + "Delete one or more tags. +If the region marks multiple tags (and nothing else), then offer +to delete those, otherwise prompt for a single tag to be deleted, +defaulting to the tag at point. +\n(git tag -d TAGS)" + (interactive (list (if-let ((tags (magit-region-values 'tag))) + (magit-confirm t nil "Delete %d tags" nil tags) + (let ((helm-comp-read-use-marked t)) + (magit-read-tag "Delete tag" t))))) + (magit-run-git "tag" "-d" tags)) + +;;;###autoload +(defun magit-tag-prune (tags remote-tags remote) + "Offer to delete tags missing locally from REMOTE, and vice versa." + (interactive + (let* ((remote (magit-read-remote "Prune tags using remote")) + (tags (magit-list-tags)) + (rtags (prog2 (message "Determining remote tags...") + (magit-remote-list-tags remote) + (message "Determining remote tags...done"))) + (ltags (cl-set-difference tags rtags :test #'equal)) + (rtags (cl-set-difference rtags tags :test #'equal))) + (unless (or ltags rtags) + (message "Same tags exist locally and remotely")) + (unless (magit-confirm t + "Delete %s locally" + "Delete %d tags locally" + 'noabort ltags) + (setq ltags nil)) + (unless (magit-confirm t + "Delete %s from remote" + "Delete %d tags from remote" + 'noabort rtags) + (setq rtags nil)) + (list ltags rtags remote))) + (when tags + (magit-call-git "tag" "-d" tags)) + (when remote-tags + (magit-run-git-async "push" remote (--map (concat ":" it) remote-tags)))) + +(defvar magit-tag-version-regexp-alist + '(("^[-._+ ]?snapshot\\.?$" . -4) + ("^[-._+]$" . -4) + ("^[-._+ ]?\\(cvs\\|git\\|bzr\\|svn\\|hg\\|darcs\\)\\.?$" . -4) + ("^[-._+ ]?unknown\\.?$" . -4) + ("^[-._+ ]?alpha\\.?$" . -3) + ("^[-._+ ]?beta\\.?$" . -2) + ("^[-._+ ]?\\(pre\\|rc\\)\\.?$" . -1)) + "Overrides `version-regexp-alist' for `magit-tag-release'. +See also `magit-release-tag-regexp'.") + +(defvar magit-release-tag-regexp "\\`\ +\\(?1:\\(?:v\\(?:ersion\\)?\\|r\\(?:elease\\)?\\)[-_]?\\)?\ +\\(?2:[0-9]+\\(?:\\.[0-9]+\\)*\ +\\(?:-[a-zA-Z0-9-]+\\(?:\\.[a-zA-Z0-9-]+\\)*\\)?\\)\\'" + "Regexp used by `magit-tag-release' to parse release tags. + +The first submatch must match the prefix, if any. The second +submatch must match the version string. + +If this matches versions that are not dot separated numbers, +then `magit-tag-version-regexp-alist' has to contain entries +for the separators allowed here.") + +(defvar magit-release-commit-regexp "\\`Release version \\(.+\\)\\'" + "Regexp used by `magit-tag-release' to parse release commit messages. +The first submatch must match the version string.") + +;;;###autoload +(defun magit-tag-release (tag msg &optional args) + "Create a release tag for `HEAD'. + +Assume that release tags match `magit-release-tag-regexp'. + +If `HEAD's message matches `magit-release-commit-regexp', then +base the tag on the version string specified by that. Otherwise +prompt for the name of the new tag using the highest existing +tag as initial input and leaving it to the user to increment the +desired part of the version string. + +When creating an annotated tag, prepare a message based on the message +of the highest existing tag, provided that contains the corresponding +version string, and substituting the new version string for that. If +that is not the case, propose a message using a reasonable format." + (interactive + (save-match-data + (pcase-let* + ((args (magit-tag-arguments)) + (`(,pver ,ptag ,pmsg) (car (magit--list-releases))) + (msg (magit-rev-format "%s")) + (ver (and (string-match magit-release-commit-regexp msg) + (match-string 1 msg))) + (_ (and (not ver) + (require (quote sisyphus) nil t) + (string-match magit-release-commit-regexp + (magit-rev-format "%s" ptag)) + (user-error "Use `sisyphus-create-release' first"))) + (tag (cond + ((not ptag) + ;; Force the user to review the message used for the + ;; initial release tag, in case they do not like the + ;; default format. + (cl-pushnew "--edit" args :test #'equal) + (read-string "Create first release tag: " + (if (and ver (string-match-p "\\`[0-9]" ver)) + (concat "v" ver) + ver))) + (ver + (concat (and (string-match magit-release-tag-regexp ptag) + (match-string 1 ptag)) + ver)) + (t + (read-string + (format "Create release tag (previous was %s): " ptag) + ptag)))) + (ver (and (string-match magit-release-tag-regexp tag) + (match-string 2 tag)))) + (list tag + (and (seq-some (apply-partially + #'string-match-p + "\\`--\\(annotate\\|local-user\\|sign\\)") + args) + (cond ((and pver (string-match (regexp-quote pver) pmsg)) + (replace-match ver t t pmsg)) + ((and ptag (string-match (regexp-quote ptag) pmsg)) + (replace-match tag t t pmsg)) + ((format "%s %s" + (capitalize + (file-name-nondirectory + (directory-file-name (magit-toplevel)))) + ver)))) + args)))) + (magit-run-git-with-editor "tag" args (and msg (list "-m" msg)) tag) + (set-process-sentinel + magit-this-process + (lambda (process event) + (when (memq (process-status process) '(exit signal)) + (magit-process-sentinel process event) + (magit-refs-setup-buffer "HEAD" (magit-show-refs-arguments)))))) + +(defun magit--list-releases () + "Return a list of releases. +The list is ordered, beginning with the highest release. +Each release element has the form (VERSION TAG MESSAGE). +`magit-release-tag-regexp' is used to determine whether +a tag qualifies as a release tag." + (save-match-data + (mapcar + #'cdr + (nreverse + (cl-sort (cl-mapcan + (lambda (line) + (and (string-match " +" line) + (let ((tag (substring line 0 (match-beginning 0))) + (msg (substring line (match-end 0)))) + (and (string-match magit-release-tag-regexp tag) + (let ((ver (match-string 2 tag)) + (version-regexp-alist + magit-tag-version-regexp-alist)) + (list (list (version-to-list ver) + ver tag msg))))))) + ;; Cannot rely on "--sort=-version:refname" because + ;; that gets confused if the version prefix has changed. + (magit-git-lines "tag" "-n")) + ;; The inverse of this function does not exist. + #'version-list-< :key #'car))))) + +;;; _ +(provide 'magit-tag) +;;; magit-tag.el ends here diff --git a/emacs/elpa/magit-20241004.917/magit-transient.el b/emacs/elpa/magit-20241004.917/magit-transient.el @@ -0,0 +1,233 @@ +;;; magit-transient.el --- Support for transients -*- lexical-binding:t -*- + +;; Copyright (C) 2008-2024 The Magit Project Contributors + +;; Author: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> +;; Maintainer: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> + +;; SPDX-License-Identifier: GPL-3.0-or-later + +;; Magit is free software: you can redistribute it and/or modify it +;; under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. +;; +;; Magit is distributed in the hope that it will be useful, but WITHOUT +;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +;; or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public +;; License for more details. +;; +;; You should have received a copy of the GNU General Public License +;; along with Magit. If not, see <https://www.gnu.org/licenses/>. + +;;; Commentary: + +;; This library implements Magit-specific prefix and suffix classes, +;; and their methods. + +;;; Code: + +(require 'magit-git) +(require 'magit-mode) +(require 'magit-process) + +(require 'transient) + +;;; Classes + +(defclass magit--git-variable (transient-variable) + ((scope :initarg :scope) + (global :initarg :global :initform nil) + (default :initarg :default :initform nil))) + +(defclass magit--git-variable:choices (magit--git-variable) + ((choices :initarg :choices) + (fallback :initarg :fallback :initform nil))) + +(defclass magit--git-variable:boolean (magit--git-variable:choices) + ((choices :initarg :choices :initform '("true" "false")))) + +(defclass magit--git-variable:urls (magit--git-variable) + ((seturl-arg :initarg :seturl-arg :initform nil))) + +;;; Methods +;;;; Init + +(cl-defmethod transient-init-scope ((obj magit--git-variable)) + (oset obj scope + (cond (transient--prefix + (oref transient--prefix scope)) + ((slot-boundp obj 'scope) + (funcall (oref obj scope) obj))))) + +(cl-defmethod transient-init-value ((obj magit--git-variable)) + (let ((variable (format (oref obj variable) + (oref obj scope))) + (arg (if (oref obj global) "--global" "--local"))) + (oset obj variable variable) + (oset obj value + (cond ((oref obj multi-value) + (magit-get-all arg variable)) + (t + (magit-get arg variable)))))) + +(cl-defmethod transient-init-value ((obj magit--git-variable:boolean)) + (let ((variable (format (oref obj variable) + (oref obj scope))) + (arg (if (oref obj global) "--global" "--local"))) + (oset obj variable variable) + (oset obj value (if (magit-get-boolean arg variable) "true" "false")))) + +;;;; Read + +(cl-defmethod transient-infix-read :around ((obj magit--git-variable:urls)) + (transient--with-emergency-exit + (transient--with-suspended-override + (mapcar (lambda (url) + (if (string-prefix-p "~" url) + (expand-file-name url) + url)) + (cl-call-next-method obj))))) + +(cl-defmethod transient-infix-read ((obj magit--git-variable:choices)) + (let ((choices (oref obj choices))) + (when (functionp choices) + (setq choices (funcall choices))) + (if-let ((value (oref obj value))) + (cadr (member value choices)) + (car choices)))) + +;;;; Readers + +(defun magit-transient-read-person (prompt initial-input history) + (magit-completing-read + prompt + (mapcar (lambda (line) + (save-excursion + (and (string-match "\\`[\s\t]+[0-9]+\t" line) + (list (substring line (match-end 0)))))) + (magit-git-lines "shortlog" "-n" "-s" "-e" "HEAD")) + nil nil initial-input history)) + +(defun magit-transient-read-revision (prompt initial-input history) + (or (magit-completing-read prompt (cons "HEAD" (magit-list-refnames)) + nil nil initial-input history + (or (magit-branch-or-commit-at-point) + (magit-get-current-branch))) + (user-error "Nothing selected"))) + +;;;; Set + +(cl-defmethod transient-infix-set ((obj magit--git-variable) value) + (let ((variable (oref obj variable)) + (arg (if (oref obj global) "--global" "--local"))) + (oset obj value value) + (if (oref obj multi-value) + (magit-set-all value arg variable) + (magit-set value arg variable)) + (magit-refresh) + (unless (or value transient--prefix) + (message "Unset %s" variable)))) + +(cl-defmethod transient-infix-set ((obj magit--git-variable:urls) values) + (let ((previous (oref obj value)) + (seturl (oref obj seturl-arg)) + (remote (oref transient--prefix scope))) + (oset obj value values) + (dolist (v (cl-set-difference values previous :test #'equal)) + (magit-call-git "remote" "set-url" seturl "--add" remote v)) + (dolist (v (cl-set-difference previous values :test #'equal)) + (magit-call-git "remote" "set-url" seturl "--delete" remote + (concat "^" (regexp-quote v) "$"))) + (magit-refresh))) + +;;;; Draw + +(cl-defmethod transient-format-description ((obj magit--git-variable)) + (or (oref obj description) + (oref obj variable))) + +(cl-defmethod transient-format-value ((obj magit--git-variable)) + (if-let ((value (oref obj value))) + (if (oref obj multi-value) + (if (cdr value) + (mapconcat (lambda (v) + (concat "\n " + (propertize v 'face 'transient-value))) + value "") + (propertize (car value) 'face 'transient-value)) + (propertize (car (split-string value "\n")) + 'face 'transient-value)) + (if-let* ((default (oref obj default)) + (default (if (functionp default) (funcall default) default))) + (concat (propertize "default:" 'face 'transient-inactive-value) + (propertize default 'face 'transient-value)) + (propertize "unset" 'face 'transient-inactive-value)))) + +(cl-defmethod transient-format-value ((obj magit--git-variable:choices)) + (let* ((variable (oref obj variable)) + (choices (oref obj choices)) + (globalp (oref obj global)) + (value nil) + (global (magit-git-string "config" "--global" variable)) + (defaultp (oref obj default)) + (default (if (functionp defaultp) (funcall defaultp obj) defaultp)) + (fallback (oref obj fallback)) + (fallback (and fallback + (and-let* ((val (magit-get fallback))) + (concat fallback ":" val))))) + (if (not globalp) + (setq value (magit-git-string "config" "--local" variable)) + (setq value global) + (setq global nil)) + (when (functionp choices) + (setq choices (funcall choices))) + (concat + (propertize "[" 'face 'transient-inactive-value) + (mapconcat (lambda (choice) + (propertize choice 'face (if (equal choice value) + (if (member choice choices) + 'transient-value + 'font-lock-warning-face) + 'transient-inactive-value))) + (if (and value (not (member value choices))) + (cons value choices) + choices) + (propertize "|" 'face 'transient-inactive-value)) + (and (or global fallback default) + (concat + (propertize "|" 'face 'transient-inactive-value) + (cond (global + (propertize (concat "global:" global) + 'face (cond (value + 'transient-inactive-value) + ((member global choices) + 'transient-value) + (t + 'font-lock-warning-face)))) + (fallback + (propertize fallback + 'face (if value + 'transient-inactive-value + 'transient-value))) + (default + (propertize (if (functionp defaultp) + (concat "dwim:" default) + (concat "default:" default)) + 'face (if value + 'transient-inactive-value + 'transient-value)))))) + (propertize "]" 'face 'transient-inactive-value)))) + +;;; Utilities + +(defun magit--transient-args-and-files () + "Return (args files) for use by log and diff functions. +The value derives from that returned by `transient-get-value'." + (let ((args (transient-get-value))) + (list (seq-filter #'atom args) + (cdr (assoc "--" args))))) + +;;; _ +(provide 'magit-transient) +;;; magit-transient.el ends here diff --git a/emacs/elpa/magit-20241004.917/magit-wip.el b/emacs/elpa/magit-20241004.917/magit-wip.el @@ -0,0 +1,476 @@ +;;; magit-wip.el --- Commit snapshots to work-in-progress refs -*- lexical-binding:t -*- + +;; Copyright (C) 2008-2024 The Magit Project Contributors + +;; Author: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> +;; Maintainer: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> + +;; SPDX-License-Identifier: GPL-3.0-or-later + +;; Magit is free software: you can redistribute it and/or modify it +;; under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. +;; +;; Magit is distributed in the hope that it will be useful, but WITHOUT +;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +;; or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public +;; License for more details. +;; +;; You should have received a copy of the GNU General Public License +;; along with Magit. If not, see <https://www.gnu.org/licenses/>. + +;;; Commentary: + +;; This library defines tree global modes which automatically commit +;; snapshots to branch-specific work-in-progress refs before and after +;; making changes, and two commands which can be used to do so on +;; demand. + +;;; Code: + +(require 'magit-core) +(require 'magit-log) + +;;; Options + +(defgroup magit-wip nil + "Automatically commit to work-in-progress refs." + :link '(info-link "(magit)Wip Modes") + :group 'magit-modes + :group 'magit-essentials) + +(defgroup magit-wip-legacy nil + "It is better to not use these modes individually." + :link '(info-link "(magit)Legacy Wip Modes") + :group 'magit-wip) + +(defcustom magit-wip-mode-lighter " Wip" + "Lighter for Magit-Wip mode." + :package-version '(magit . "2.90.0") + :group 'magit-wip + :type 'string) + +(defcustom magit-wip-after-save-local-mode-lighter "" + "Lighter for Magit-Wip-After-Save-Local mode." + :package-version '(magit . "2.1.0") + :group 'magit-wip-legacy + :type 'string) + +(defcustom magit-wip-after-apply-mode-lighter "" + "Lighter for Magit-Wip-After-Apply mode." + :package-version '(magit . "2.1.0") + :group 'magit-wip-legacy + :type 'string) + +(defcustom magit-wip-before-change-mode-lighter "" + "Lighter for Magit-Wip-Before-Change mode." + :package-version '(magit . "2.1.0") + :group 'magit-wip-legacy + :type 'string) + +(defcustom magit-wip-initial-backup-mode-lighter "" + "Lighter for Magit-Wip-Initial Backup mode." + :package-version '(magit . "2.1.0") + :group 'magit-wip-legacy + :type 'string) + +(defcustom magit-wip-merge-branch nil + "Whether to merge the current branch into its wip ref. + +If non-nil and the current branch has new commits, then it is +merged into the wip ref before creating a new wip commit. This +makes it easier to inspect wip history and the wip commits are +never garbage collected. + +If nil and the current branch has new commits, then the wip ref +is reset to the tip of the branch before creating a new wip +commit. With this setting wip commits are eventually garbage +collected. This is currently the default." + :package-version '(magit . "2.90.0") + :group 'magit-wip + :type 'boolean) + +(defcustom magit-wip-namespace "refs/wip/" + "Namespace used for work-in-progress refs. +The wip refs are named \"<namespace/>index/<branchref>\" +and \"<namespace/>wtree/<branchref>\". When snapshots +are created while the `HEAD' is detached then \"HEAD\" +is used as `branch-ref'." + :package-version '(magit . "2.1.0") + :group 'magit-wip + :type 'string) + +;;; Modes + +(defvar magit--wip-activation-cache nil) +(defvar magit--wip-inhibit-autosave nil) + +;;;###autoload +(define-minor-mode magit-wip-mode + "Save uncommitted changes to work-in-progress refs. + +Whenever appropriate (i.e., when dataloss would be a possibility +otherwise) this mode causes uncommitted changes to be committed +to dedicated work-in-progress refs. + +For historic reasons this mode is implemented on top of four +other `magit-wip-*' modes, which can also be used individually, +if you want finer control over when the wip refs are updated; +but that is discouraged." + :package-version '(magit . "2.90.0") + :lighter magit-wip-mode-lighter + :global t + (let ((arg (if magit-wip-mode 1 -1))) + (let ((magit--wip-activation-cache (list t))) + (magit-wip-after-save-mode arg)) + (magit-wip-after-apply-mode arg) + (magit-wip-before-change-mode arg) + (magit-wip-initial-backup-mode arg))) + +(define-minor-mode magit-wip-after-save-local-mode + "After saving, also commit to a worktree work-in-progress ref. + +After saving the current file-visiting buffer this mode also +commits the changes to the worktree work-in-progress ref for +the current branch. + +This mode should be enabled globally by turning on the globalized +variant `magit-wip-after-save-mode'." + :package-version '(magit . "2.1.0") + :lighter magit-wip-after-save-local-mode-lighter + (if magit-wip-after-save-local-mode + (if (and buffer-file-name (magit-inside-worktree-p t)) + (add-hook 'after-save-hook #'magit-wip-commit-buffer-file t t) + (setq magit-wip-after-save-local-mode nil) + (user-error "Need a worktree and a file")) + (remove-hook 'after-save-hook #'magit-wip-commit-buffer-file t))) + +(defun magit-wip-after-save-local-mode-turn-on () + (when (and buffer-file-name + (if magit--wip-activation-cache + (if-let ((elt (assoc default-directory + magit--wip-activation-cache))) + (and-let* ((top (cadr elt))) + (member (file-relative-name buffer-file-name top) + (cddr elt))) + (if-let ((top (magit-toplevel))) + (let (files) + (if-let ((elt (assoc top magit--wip-activation-cache))) + (setq files (cddr elt)) + (progn + (setq files (let ((default-directory top)) + (magit-tracked-files))) + (push `(,top ,top ,@files) + magit--wip-activation-cache) + (unless (eq default-directory top) + (push `(,default-directory ,top ,@files) + magit--wip-activation-cache)))) + (member (file-relative-name buffer-file-name) files)) + (push (list default-directory nil) + magit--wip-activation-cache) + nil)) + (and (magit-inside-worktree-p t) + (magit-file-tracked-p buffer-file-name)))) + (magit-wip-after-save-local-mode))) + +;;;###autoload +(define-globalized-minor-mode magit-wip-after-save-mode + magit-wip-after-save-local-mode magit-wip-after-save-local-mode-turn-on + :package-version '(magit . "2.1.0") + :group 'magit-wip) + +(defun magit-wip-commit-buffer-file (&optional msg) + "Commit visited file to a worktree work-in-progress ref. + +Also see `magit-wip-after-save-mode' which calls this function +automatically whenever a buffer visiting a tracked file is saved." + (interactive (list "wip-save %s after save")) + (unless magit--wip-inhibit-autosave + (when-let ((ref (magit-wip-get-ref))) + (magit-with-toplevel + (let ((file (file-relative-name buffer-file-name))) + (magit-wip-commit-worktree + ref (list file) + (format (or msg "autosave %s after save") file))))))) + +;;;###autoload +(define-minor-mode magit-wip-after-apply-mode + "Commit to work-in-progress refs. + +After applying a change using any \"apply variant\" +command (apply, stage, unstage, discard, and reverse) commit the +affected files to the current wip refs. For each branch there +may be two wip refs; one contains snapshots of the files as found +in the worktree and the other contains snapshots of the entries +in the index." + :package-version '(magit . "2.1.0") + :group 'magit-wip + :lighter magit-wip-after-apply-mode-lighter + :global t) + +(defun magit-wip-commit-after-apply (&optional files msg) + (when magit-wip-after-apply-mode + (magit-wip-commit files msg))) + +;;;###autoload +(define-minor-mode magit-wip-before-change-mode + "Commit to work-in-progress refs before certain destructive changes. + +Before invoking a revert command or an \"apply variant\" +command (apply, stage, unstage, discard, and reverse) commit the +affected tracked files to the current wip refs. For each branch +there may be two wip refs; one contains snapshots of the files +as found in the worktree and the other contains snapshots of the +entries in the index. + +Only changes to files which could potentially be affected by the +command which is about to be called are committed." + :package-version '(magit . "2.1.0") + :group 'magit-wip + :lighter magit-wip-before-change-mode-lighter + :global t) + +(defun magit-wip-commit-before-change (&optional files msg) + (when magit-wip-before-change-mode + (magit-with-toplevel + (magit-wip-commit files msg)))) + +(define-minor-mode magit-wip-initial-backup-mode + "Before saving a buffer for the first time, commit to a wip ref." + :package-version '(magit . "2.90.0") + :group 'magit-wip + :lighter magit-wip-initial-backup-mode-lighter + :global t + (if magit-wip-initial-backup-mode + (add-hook 'before-save-hook #'magit-wip-commit-initial-backup) + (remove-hook 'before-save-hook #'magit-wip-commit-initial-backup))) + +(defun magit--any-wip-mode-enabled-p () + "Return non-nil if any global wip mode is enabled." + (or magit-wip-mode + magit-wip-after-save-mode + magit-wip-after-apply-mode + magit-wip-before-change-mode + magit-wip-initial-backup-mode)) + +(defvar-local magit-wip-buffer-backed-up nil) +(put 'magit-wip-buffer-backed-up 'permanent-local t) + +;;;###autoload +(defun magit-wip-commit-initial-backup () + "Before saving, commit current file to a worktree wip ref. + +The user has to add this function to `before-save-hook'. + +Commit the current state of the visited file before saving the +current buffer to that file. This backs up the same version of +the file as `backup-buffer' would, but stores the backup in the +worktree wip ref, which is also used by the various Magit Wip +modes, instead of in a backup file as `backup-buffer' would. + +This function ignores the variables that affect `backup-buffer' +and can be used along-side that function, which is recommended +because this function only backs up files that are tracked in +a Git repository." + (when (and (not magit-wip-buffer-backed-up) + buffer-file-name + (magit-inside-worktree-p t) + (magit-file-tracked-p buffer-file-name)) + (let ((magit-save-repository-buffers nil)) + (magit-wip-commit-buffer-file "autosave %s before save")) + (setq magit-wip-buffer-backed-up t))) + +;;; Core + +(defun magit-wip-commit (&optional files msg) + "Commit all tracked files to the work-in-progress refs. + +Interactively, commit all changes to all tracked files using +a generic commit message. With a prefix-argument the commit +message is read in the minibuffer. + +Non-interactively, only commit changes to FILES using MSG as +commit message." + (interactive (list nil (if current-prefix-arg + (magit-read-string "Wip commit message") + "wip-save tracked files"))) + (when-let ((ref (magit-wip-get-ref))) + (magit-wip-commit-index ref files msg) + (magit-wip-commit-worktree ref files msg))) + +(defun magit-wip-commit-index (ref files msg) + (let* ((wipref (magit--wip-index-ref ref)) + (parent (magit-wip-get-parent ref wipref)) + (tree (magit-git-string "write-tree"))) + (magit-wip-update-wipref ref wipref tree parent files msg "index"))) + +(defun magit-wip-commit-worktree (ref files msg) + (when (or (not files) + ;; `update-index' will either ignore (before Git v2.32.0) + ;; or fail when passed directories (relevant for the + ;; untracked files code paths). + (setq files (seq-remove #'file-directory-p files))) + (let* ((wipref (magit--wip-wtree-ref ref)) + (parent (magit-wip-get-parent ref wipref)) + (tree (magit-with-temp-index parent (list "--reset" "-i") + (if files + ;; Note: `update-index' is used instead of `add' + ;; because `add' will fail if a file is already + ;; deleted in the temporary index. + (magit-call-git + "update-index" "--add" "--remove" + (and (magit-git-version>= "2.25.0") + "--ignore-skip-worktree-entries") + "--" files) + (magit-with-toplevel + (magit-call-git "add" "-u" "."))) + (magit-git-string "write-tree")))) + (magit-wip-update-wipref ref wipref tree parent files msg "worktree")))) + +(defun magit-wip-update-wipref (ref wipref tree parent files msg start-msg) + (cond + ((and (not (equal parent wipref)) + (or (not magit-wip-merge-branch) + (not (magit-rev-verify wipref)))) + (setq start-msg (concat "start autosaving " start-msg)) + (magit-update-ref wipref start-msg + (magit-git-string "commit-tree" "--no-gpg-sign" + "-p" parent "-m" start-msg + (concat parent "^{tree}"))) + (setq parent wipref)) + ((and magit-wip-merge-branch + (or (not (magit-rev-ancestor-p ref wipref)) + (not (magit-rev-ancestor-p + (concat (magit-git-string "log" "--format=%H" + "-1" "--merges" wipref) + "^2") + ref)))) + (setq start-msg (format "merge %s into %s" ref start-msg)) + (magit-update-ref wipref start-msg + (magit-git-string "commit-tree" "--no-gpg-sign" + "-p" wipref "-p" ref + "-m" start-msg + (concat ref "^{tree}"))) + (setq parent wipref))) + (when (magit-git-failure "diff-tree" "--quiet" parent tree "--" files) + (unless (and msg (not (= (aref msg 0) ?\s))) + (let ((len (length files))) + (setq msg (concat + (cond ((= len 0) "autosave tracked files") + ((> len 1) (format "autosave %s files" len)) + ((concat "autosave " + (file-relative-name (car files) + (magit-toplevel))))) + msg)))) + (magit-update-ref wipref msg + (magit-git-string "commit-tree" "--no-gpg-sign" + "-p" parent "-m" msg tree)))) + +(defun magit-wip-get-ref () + (let ((ref (or (magit-git-string "symbolic-ref" "HEAD") "HEAD"))) + (and (magit-rev-verify ref) + ref))) + +(defun magit-wip-get-parent (ref wipref) + (if (and (magit-rev-verify wipref) + (equal (magit-git-string "merge-base" wipref ref) + (magit-rev-verify ref))) + wipref + ref)) + +(defun magit--wip-index-ref (&optional ref) + (magit--wip-ref "index/" ref)) + +(defun magit--wip-wtree-ref (&optional ref) + (magit--wip-ref "wtree/" ref)) + +(defun magit--wip-ref (namespace &optional ref) + (concat magit-wip-namespace namespace + (or (and ref (string-prefix-p "refs/" ref) ref) + (and-let* ((branch (and (not (equal ref "HEAD")) + (or ref (magit-get-current-branch))))) + (concat "refs/heads/" branch)) + "HEAD"))) + +(defun magit-wip-maybe-add-commit-hook () + (when (and magit-wip-merge-branch + (magit-wip-any-enabled-p)) + (add-hook 'git-commit-post-finish-hook #'magit-wip-commit nil t))) + +(defun magit-wip-any-enabled-p () + (or magit-wip-mode + magit-wip-after-save-local-mode + magit-wip-after-save-mode + magit-wip-after-apply-mode + magit-wip-before-change-mode + magit-wip-initial-backup-mode)) + +;;; Log + +(defun magit-wip-log-index (args files) + "Show log for the index wip ref of the current branch." + (interactive (magit-log-arguments)) + (magit-log-setup-buffer (list (magit--wip-index-ref)) args files)) + +(defun magit-wip-log-worktree (args files) + "Show log for the worktree wip ref of the current branch." + (interactive (magit-log-arguments)) + (magit-log-setup-buffer (list (magit--wip-wtree-ref)) args files)) + +(defun magit-wip-log-current (branch args files count) + "Show log for the current branch and its wip refs. +With a negative prefix argument only show the worktree wip ref. +The absolute numeric value of the prefix argument controls how +many \"branches\" of each wip ref are shown." + (interactive + (nconc (list (or (magit-get-current-branch) "HEAD")) + (magit-log-arguments) + (list (prefix-numeric-value current-prefix-arg)))) + (magit-wip-log branch args files count)) + +(defun magit-wip-log (branch args files count) + "Show log for a branch and its wip refs. +With a negative prefix argument only show the worktree wip ref. +The absolute numeric value of the prefix argument controls how +many \"branches\" of each wip ref are shown." + (interactive + (nconc (list (magit-completing-read + "Log branch and its wip refs" + (nconc (magit-list-local-branch-names) + (list "HEAD")) + nil t nil 'magit-revision-history + (or (magit-branch-at-point) + (magit-get-current-branch) + "HEAD"))) + (magit-log-arguments) + (list (prefix-numeric-value current-prefix-arg)))) + (magit-log-setup-buffer (nconc (list branch) + (magit-wip-log-get-tips + (magit--wip-wtree-ref branch) + (abs count)) + (and (>= count 0) + (magit-wip-log-get-tips + (magit--wip-index-ref branch) + (abs count)))) + args files)) + +(defun magit-wip-log-get-tips (wipref count) + (and-let* ((reflog (magit-git-lines "reflog" wipref))) + (let (tips) + (while (and reflog (> count 1)) + ;; "start autosaving ..." is the current message, but it used + ;; to be "restart autosaving ...", and those messages may + ;; still be around (e.g., if gc.reflogExpire is set to "never"). + (setq reflog (cl-member "^[^ ]+ [^:]+: \\(?:re\\)?start autosaving" + reflog :test #'string-match-p)) + (when (and (cadr reflog) + (string-match "^[^ ]+ \\([^:]+\\)" (cadr reflog))) + (push (match-string 1 (cadr reflog)) tips)) + (setq reflog (cddr reflog)) + (cl-decf count)) + (cons wipref (nreverse tips))))) + +;;; _ +(provide 'magit-wip) +;;; magit-wip.el ends here diff --git a/emacs/elpa/magit-20241004.917/magit-worktree.el b/emacs/elpa/magit-20241004.917/magit-worktree.el @@ -0,0 +1,207 @@ +;;; magit-worktree.el --- Worktree support -*- lexical-binding:t -*- + +;; Copyright (C) 2008-2024 The Magit Project Contributors + +;; Author: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> +;; Maintainer: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> + +;; SPDX-License-Identifier: GPL-3.0-or-later + +;; Magit is free software: you can redistribute it and/or modify it +;; under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. +;; +;; Magit is distributed in the hope that it will be useful, but WITHOUT +;; ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +;; or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public +;; License for more details. +;; +;; You should have received a copy of the GNU General Public License +;; along with Magit. If not, see <https://www.gnu.org/licenses/>. + +;;; Commentary: + +;; This library implements support for `git-worktree'. + +;;; Code: + +(require 'magit) + +;;; Options + +(defcustom magit-worktree-read-directory-name-function #'read-directory-name + "Function used to read a directory for worktree commands. +This is called with one argument, the prompt, and can be used +to, e.g., use a base directory other than `default-directory'. +Used by `magit-worktree-checkout' and `magit-worktree-branch'." + :package-version '(magit . "3.0.0") + :group 'magit-commands + :type 'function) + +;;; Commands + +;;;###autoload (autoload 'magit-worktree "magit-worktree" nil t) +(transient-define-prefix magit-worktree () + "Act on a worktree." + :man-page "git-worktree" + [["Create new" + ("b" "worktree" magit-worktree-checkout) + ("c" "branch and worktree" magit-worktree-branch)] + ["Commands" + ("m" "Move worktree" magit-worktree-move) + ("k" "Delete worktree" magit-worktree-delete) + ("g" "Visit worktree" magit-worktree-status)]]) + +;;;###autoload +(defun magit-worktree-checkout (path branch) + "Checkout BRANCH in a new worktree at PATH." + (interactive + (let ((branch (magit-read-branch-or-commit "Checkout"))) + (list (funcall magit-worktree-read-directory-name-function + (format "Checkout %s in new worktree: " branch)) + branch))) + (when (zerop (magit-run-git "worktree" "add" + (magit--expand-worktree path) branch)) + (magit-diff-visit-directory path))) + +;;;###autoload +(defun magit-worktree-branch (path branch start-point) + "Create a new BRANCH and check it out in a new worktree at PATH." + (interactive + `(,(funcall magit-worktree-read-directory-name-function + "Create worktree: ") + ,@(magit-branch-read-args "Create and checkout branch"))) + (when (zerop (magit-run-git "worktree" "add" "-b" branch + (magit--expand-worktree path) start-point)) + (magit-diff-visit-directory path))) + +;;;###autoload +(defun magit-worktree-move (worktree path) + "Move WORKTREE to PATH." + (interactive + (list (magit-completing-read "Move worktree" + (cdr (magit-list-worktrees)) + nil t nil nil + (magit-section-value-if 'worktree)) + (funcall magit-worktree-read-directory-name-function + "Move worktree to: "))) + (if (file-directory-p (expand-file-name ".git" worktree)) + (user-error "You may not move the main working tree") + (let ((preexisting-directory (file-directory-p path))) + (when (and (zerop (magit-call-git "worktree" "move" worktree + (magit--expand-worktree path))) + (not (file-exists-p default-directory)) + (derived-mode-p 'magit-status-mode)) + (kill-buffer) + (magit-diff-visit-directory + (if preexisting-directory + (concat (file-name-as-directory path) + (file-name-nondirectory worktree)) + path))) + (magit-refresh)))) + +(defun magit-worktree-delete (worktree) + "Delete a worktree, defaulting to the worktree at point. +The primary worktree cannot be deleted." + (interactive + (list (magit-completing-read "Delete worktree" + (cdr (magit-list-worktrees)) + nil t nil nil + (magit-section-value-if 'worktree)))) + (if (file-directory-p (expand-file-name ".git" worktree)) + (user-error "Deleting %s would delete the shared .git directory" worktree) + (let ((primary (file-name-as-directory (caar (magit-list-worktrees))))) + (magit-confirm-files (if magit-delete-by-moving-to-trash 'trash 'delete) + (list "worktree")) + (when (file-exists-p worktree) + (let ((delete-by-moving-to-trash magit-delete-by-moving-to-trash)) + (delete-directory worktree t magit-delete-by-moving-to-trash))) + (if (file-exists-p default-directory) + (magit-run-git "worktree" "prune") + (let ((default-directory primary)) + (magit-run-git "worktree" "prune")) + (when (derived-mode-p 'magit-status-mode) + (kill-buffer) + (magit-status-setup-buffer primary)))))) + +(defun magit-worktree-status (worktree) + "Show the status for the worktree at point. +If there is no worktree at point, then read one in the +minibuffer. If the worktree at point is the one whose +status is already being displayed in the current buffer, +then show it in Dired instead." + (interactive + (list (or (magit-section-value-if 'worktree) + (magit-completing-read + "Show status for worktree" + (cl-delete (directory-file-name (magit-toplevel)) + (magit-list-worktrees) + :test #'equal :key #'car))))) + (magit-diff-visit-directory worktree)) + +(defun magit--expand-worktree (path) + (magit-convert-filename-for-git (expand-file-name path))) + +;;; Sections + +(defvar-keymap magit-worktree-section-map + :doc "Keymap for `worktree' sections." + "<remap> <magit-delete-thing>" #'magit-worktree-delete + "<remap> <magit-visit-thing>" #'magit-worktree-status + "<4>" (magit-menu-item "Worktree commands..." #'magit-worktree) + "<3>" '(menu-item "--") + "<2>" (magit-menu-item "Delete %m" #'magit-worktree-delete) + "<1>" (magit-menu-item "Visit %s" #'magit-worktree-status)) + +(defun magit-insert-worktrees () + "Insert sections for all worktrees. +If there is only one worktree, then insert nothing." + (let ((worktrees (magit-list-worktrees))) + (when (length> worktrees 1) + (magit-insert-section (worktrees) + (magit-insert-heading t "Worktrees") + (let* ((cols + (mapcar + (lambda (config) + (pcase-let ((`(,_ ,commit ,branch ,bare) config)) + (cons (cond + (branch + (propertize + branch 'font-lock-face + (if (equal branch (magit-get-current-branch)) + 'magit-branch-current + 'magit-branch-local))) + (commit + (propertize (magit-rev-abbrev commit) + 'font-lock-face 'magit-hash)) + (bare "(bare)")) + config))) + worktrees)) + (align (1+ (apply #'max (--map (string-width (car it)) cols))))) + (pcase-dolist (`(,head . ,config) cols) + (magit--insert-worktree + config + (concat head (make-string (- align (length head)) ?\s))))) + (insert ?\n))))) + +(defun magit--insert-worktree (config head) + "Insert worktree section for CONFIG. +See `magit-list-worktrees' for the format of CONFIG. HEAD is +a prettified reference or revision representing the worktree, +with padding for alignment." + ;; #4926 Before changing the signature, inform @vermiculus. + (let ((path (car config))) + (magit-insert-section (worktree path) + (insert head) + (insert (let ((relative (file-relative-name path)) + (absolute (abbreviate-file-name path))) + (if (or (> (string-width relative) (string-width absolute)) + (equal relative "./")) + absolute + relative))) + (insert ?\n)))) + +;;; _ +(provide 'magit-worktree) +;;; magit-worktree.el ends here diff --git a/emacs/elpa/magit-20241004.917/magit.el b/emacs/elpa/magit-20241004.917/magit.el @@ -0,0 +1,789 @@ +;;; magit.el --- A Git porcelain inside Emacs -*- lexical-binding:t; coding:utf-8 -*- + +;; Copyright (C) 2008-2024 The Magit Project Contributors + +;; Author: Marius Vollmer <marius.vollmer@gmail.com> +;; Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> +;; Maintainer: Jonas Bernoulli <emacs.magit@jonas.bernoulli.dev> +;; Kyle Meyer <kyle@kyleam.com> +;; Former-Maintainers: +;; Nicolas Dudebout <nicolas.dudebout@gatech.edu> +;; Noam Postavsky <npostavs@users.sourceforge.net> +;; Peter J. Weisberg <pj@irregularexpressions.net> +;; Phil Jackson <phil@shellarchive.co.uk> +;; Rémi Vanicat <vanicat@debian.org> +;; Yann Hodique <yann.hodique@gmail.com> + +;; Homepage: https://github.com/magit/magit +;; Keywords: git tools vc + +;; Package-Version: 20241004.917 +;; Package-Revision: 2b6516e04431 +;; Package-Requires: ( +;; (emacs "26.1") +;; (compat "30.0.0.0") +;; (dash "2.19.1") +;; (magit-section "4.1.1") +;; (seq "2.24") +;; (transient "0.7.6") +;; (with-editor "3.4.2")) + +;; SPDX-License-Identifier: GPL-3.0-or-later + +;; Magit is free software: you can redistribute it and/or modify +;; it under the terms of the GNU General Public License as published +;; by the Free Software Foundation, either version 3 of the License, +;; or (at your option) any later version. +;; +;; Magit is distributed in the hope that it will be useful, +;; but WITHOUT ANY WARRANTY; without even the implied warranty of +;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +;; GNU General Public License for more details. +;; +;; You should have received a copy of the GNU General Public License +;; along with Magit. If not, see <https://www.gnu.org/licenses/>. + +;; You should have received a copy of the AUTHORS.md file, which +;; lists all contributors. If not, see https://magit.vc/authors. + +;;; Commentary: + +;; Magit is a text-based Git user interface that puts an unmatched focus +;; on streamlining workflows. Commands are invoked using short mnemonic +;; key sequences that take the cursor’s position in the highly actionable +;; interface into account to provide context-sensitive behavior. + +;; With Magit you can do nearly everything that you can do when using Git +;; on the command-line, but at greater speed and while taking advantage +;; of advanced features that previously seemed too daunting to use on a +;; daily basis. Many users will find that by using Magit they can become +;; more effective Git user. + +;;; Code: + +(require 'magit-core) +(require 'magit-diff) +(require 'magit-log) +(require 'magit-wip) +(require 'magit-apply) +(require 'magit-repos) +(require 'git-commit) + +(require 'format-spec) +(require 'package nil t) ; used in `magit-version' +(require 'with-editor) + +;; For `magit:--gpg-sign' +(declare-function epg-list-keys "epg" (context &optional name mode)) +(declare-function epg-decode-dn "epg" (alist)) +(defvar epa-protocol) + +;;; Options + +(defcustom magit-openpgp-default-signing-key nil + "Fingerprint of your default Openpgp key used for signing. +If the specified primary key has signing capacity then it is used +as the value of the `--gpg-sign' argument without prompting, even +when other such keys exist. To be able to select another key you +must then use a prefix argument." + :package-version '(magit . "4.0.0") + :group 'magit-commands + :type 'string) + +;;; Faces + +(defface magit-header-line + '((t :inherit magit-section-heading)) + "Face for the `header-line' in some Magit modes. +Note that some modes, such as `magit-log-select-mode', have their +own faces for the `header-line', or for parts of the +`header-line'." + :group 'magit-faces) + +(defface magit-header-line-key + '((t :inherit font-lock-builtin-face)) + "Face for keys in the `header-line'." + :group 'magit-faces) + +(defface magit-dimmed + '((((class color) (background light)) :foreground "grey50") + (((class color) (background dark)) :foreground "grey50")) + "Face for text that shouldn't stand out." + :group 'magit-faces) + +(defface magit-hash + '((((class color) (background light)) :foreground "grey60") + (((class color) (background dark)) :foreground "grey40")) + "Face for the commit object name in the log output." + :group 'magit-faces) + +(defface magit-tag + '((((class color) (background light)) :foreground "Goldenrod4") + (((class color) (background dark)) :foreground "LightGoldenrod2")) + "Face for tag labels shown in log buffer." + :group 'magit-faces) + +(defface magit-branch-remote + '((((class color) (background light)) :foreground "DarkOliveGreen4") + (((class color) (background dark)) :foreground "DarkSeaGreen2")) + "Face for remote branch head labels shown in log buffer." + :group 'magit-faces) + +(defface magit-branch-remote-head + '((((supports (:box t))) :inherit magit-branch-remote :box t) + (t :inherit magit-branch-remote :inverse-video t)) + "Face for current branch." + :group 'magit-faces) + +(defface magit-branch-local + '((((class color) (background light)) :foreground "SkyBlue4") + (((class color) (background dark)) :foreground "LightSkyBlue1")) + "Face for local branches." + :group 'magit-faces) + +(defface magit-branch-current + '((((supports (:box t))) :inherit magit-branch-local :box t) + (t :inherit magit-branch-local :inverse-video t)) + "Face for current branch." + :group 'magit-faces) + +(defface magit-branch-upstream + '((t :slant italic)) + "Face for upstream branch. +This face is only used in logs and it gets combined + with `magit-branch-local', `magit-branch-remote' +and/or `magit-branch-remote-head'." + :group 'magit-faces) + +(defface magit-branch-warning + '((t :inherit warning)) + "Face for warning about (missing) branch." + :group 'magit-faces) + +(defface magit-head + '((((class color) (background light)) :inherit magit-branch-local) + (((class color) (background dark)) :inherit magit-branch-local)) + "Face for the symbolic ref `HEAD'." + :group 'magit-faces) + +(defface magit-refname + '((((class color) (background light)) :foreground "grey30") + (((class color) (background dark)) :foreground "grey80")) + "Face for refnames without a dedicated face." + :group 'magit-faces) + +(defface magit-refname-stash + '((t :inherit magit-refname)) + "Face for stash refnames." + :group 'magit-faces) + +(defface magit-refname-wip + '((t :inherit magit-refname)) + "Face for wip refnames." + :group 'magit-faces) + +(defface magit-refname-pullreq + '((t :inherit magit-refname)) + "Face for pullreq refnames." + :group 'magit-faces) + +(defface magit-keyword + '((t :inherit font-lock-string-face)) + "Face for parts of commit messages inside brackets." + :group 'magit-faces) + +(defface magit-keyword-squash + '((t :inherit font-lock-warning-face)) + "Face for squash! and fixup! keywords in commit messages." + :group 'magit-faces) + +(defface magit-signature-good + '((t :foreground "green")) + "Face for good signatures." + :group 'magit-faces) + +(defface magit-signature-bad + '((t :foreground "red" :weight bold)) + "Face for bad signatures." + :group 'magit-faces) + +(defface magit-signature-untrusted + '((t :foreground "medium aquamarine")) + "Face for good untrusted signatures." + :group 'magit-faces) + +(defface magit-signature-expired + '((t :foreground "orange")) + "Face for signatures that have expired." + :group 'magit-faces) + +(defface magit-signature-expired-key + '((t :inherit magit-signature-expired)) + "Face for signatures made by an expired key." + :group 'magit-faces) + +(defface magit-signature-revoked + '((t :foreground "violet red")) + "Face for signatures made by a revoked key." + :group 'magit-faces) + +(defface magit-signature-error + '((t :foreground "light blue")) + "Face for signatures that cannot be checked (e.g., missing key)." + :group 'magit-faces) + +(defface magit-cherry-unmatched + '((t :foreground "cyan")) + "Face for unmatched cherry commits." + :group 'magit-faces) + +(defface magit-cherry-equivalent + '((t :foreground "magenta")) + "Face for equivalent cherry commits." + :group 'magit-faces) + +(defface magit-filename + '((t :weight normal)) + "Face for filenames." + :group 'magit-faces) + +;;; Global Bindings + +;;;###autoload +(defcustom magit-define-global-key-bindings 'default + "Which set of key bindings to add to the global keymap, if any. + +This option controls which set of Magit key bindings, if any, may +be added to the global keymap, even before Magit is first used in +the current Emacs session. + +If the value is nil, no bindings are added. + +If `default', maybe add: + + C-x g `magit-status' + C-x M-g `magit-dispatch' + C-c M-g `magit-file-dispatch' + +If `recommended', maybe add: + + C-x g `magit-status' + C-c g `magit-dispatch' + C-c f `magit-file-dispatch' + + These bindings are strongly recommended, but we cannot use + them by default, because the \"C-c <LETTER>\" namespace is + strictly reserved for bindings added by the user. + +The bindings in the chosen set may be added when +`after-init-hook' is run. Each binding is added if, and only +if, at that time no other key is bound to the same command, +and no other command is bound to the same key. In other words +we try to avoid adding bindings that are unnecessary, as well +as bindings that conflict with other bindings. + +Adding these bindings is delayed until `after-init-hook' is +run to allow users to set the variable anywhere in their init +file (without having to make sure to do so before `magit' is +loaded or autoloaded) and to increase the likelihood that all +the potentially conflicting user bindings have already been +added. + +To set this variable use either `setq' or the Custom interface. +Do not use the function `customize-set-variable' because doing +that would cause Magit to be loaded immediately, when that form +is evaluated (this differs from `custom-set-variables', which +doesn't load the libraries that define the customized variables). + +Setting this variable has no effect if `after-init-hook' has +already been run." + :package-version '(magit . "4.0.0") + :group 'magit-essentials + :type '(choice (const :tag "Add no binding" nil) + (const :tag "Use default bindings" default) + (const :tag "Use recommended bindings" recommended))) + +;;;###autoload +(progn + (defun magit-maybe-define-global-key-bindings (&optional force) + "See variable `magit-define-global-key-bindings'." + (when magit-define-global-key-bindings + (let ((map (current-global-map))) + (pcase-dolist (`(,key . ,def) + (cond ((eq magit-define-global-key-bindings 'recommended) + '(("C-x g" . magit-status) + ("C-c g" . magit-dispatch) + ("C-c f" . magit-file-dispatch))) + ('(("C-x g" . magit-status) + ("C-x M-g" . magit-dispatch) + ("C-c M-g" . magit-file-dispatch))))) + ;; This is autoloaded and thus is used before `compat' is + ;; loaded, so we cannot use `keymap-lookup' and `keymap-set'. + (when (or force + (not (or (lookup-key map (kbd key)) + (where-is-internal def (make-sparse-keymap) t)))) + (define-key map (kbd key) def)))))) + (if after-init-time + (magit-maybe-define-global-key-bindings) + (add-hook 'after-init-hook #'magit-maybe-define-global-key-bindings t))) + +;;; Dispatch Popup + +;;;###autoload (autoload 'magit-dispatch "magit" nil t) +(transient-define-prefix magit-dispatch () + "Invoke a Magit command from a list of available commands." + :info-manual "(magit)Top" + ["Transient and dwim commands" + ;; → bound in magit-mode-map or magit-section-mode-map + ;; ↓ bound below + [("A" "Apply" magit-cherry-pick) + ;; a ↓ + ("b" "Branch" magit-branch) + ("B" "Bisect" magit-bisect) + ("c" "Commit" magit-commit) + ("C" "Clone" magit-clone) + ("d" "Diff" magit-diff) + ("D" "Diff (change)" magit-diff-refresh) + ("e" "Ediff (dwim)" magit-ediff-dwim) + ("E" "Ediff" magit-ediff) + ("f" "Fetch" magit-fetch) + ("F" "Pull" magit-pull) + ;; g ↓ + ;; G → magit-refresh-all + ("h" "Help" magit-info) + ("H" "Section info" magit-describe-section :if-derived magit-mode)] + [("i" "Ignore" magit-gitignore) + ("I" "Init" magit-init) + ("j" "Jump to section"magit-status-jump :if-mode magit-status-mode) + ("j" "Display status" magit-status-quick :if-not-mode magit-status-mode) + ("J" "Display buffer" magit-display-repository-buffer) + ;; k ↓ + ;; K → magit-file-untrack + ("l" "Log" magit-log) + ("L" "Log (change)" magit-log-refresh) + ("m" "Merge" magit-merge) + ("M" "Remote" magit-remote) + ;; n → magit-section-forward + ;; N reserved → forge-dispatch + ("o" "Submodule" magit-submodule) + ("O" "Subtree" magit-subtree) + ;; p → magit-section-backward + ("P" "Push" magit-push) + ;; q → magit-mode-bury-buffer + ("Q" "Command" magit-git-command)] + [("r" "Rebase" magit-rebase) + ;; R → magit-file-rename + ;; s ↓ + ;; S ↓ + ("t" "Tag" magit-tag) + ("T" "Note" magit-notes) + ;; u ↓ + ;; U ↓ + ;; v ↓ + ("V" "Revert" magit-revert) + ("w" "Apply patches" magit-am) + ("W" "Format patches" magit-patch) + ;; x → magit-reset-quickly + ("X" "Reset" magit-reset) + ("y" "Show Refs" magit-show-refs) + ("Y" "Cherries" magit-cherry) + ("z" "Stash" magit-stash) + ("Z" "Worktree" magit-worktree) + ("!" "Run" magit-run)]] + ["Applying changes" + :if-derived magit-mode + [("a" "Apply" magit-apply) + ("v" "Reverse" magit-reverse) + ("k" "Discard" magit-discard)] + [("s" "Stage" magit-stage) + ("u" "Unstage" magit-unstage)] + [("S" "Stage all" magit-stage-modified) + ("U" "Unstage all" magit-unstage-all)]] + ["Essential commands" + :if-derived magit-mode + [("g" " Refresh current buffer" magit-refresh) + ("q" " Bury current buffer" magit-mode-bury-buffer) + ("<tab>" " Toggle section at point" magit-section-toggle) + ("<return>" "Visit thing at point" magit-visit-thing)] + [("C-x m" "Show all key bindings" describe-mode) + ("C-x i" "Show Info manual" magit-info)]]) + +;;; Git Popup + +(defcustom magit-shell-command-verbose-prompt t + "Whether to show the working directory when reading a command. +This affects `magit-git-command', `magit-git-command-topdir', +`magit-shell-command', and `magit-shell-command-topdir'." + :package-version '(magit . "2.11.0") + :group 'magit-commands + :type 'boolean) + +(defvar magit-git-command-history nil) + +;;;###autoload (autoload 'magit-run "magit" nil t) +(transient-define-prefix magit-run () + "Run git or another command, or launch a graphical utility." + [["Run git subcommand" + ("!" "in repository root" magit-git-command-topdir) + ("p" "in working directory" magit-git-command)] + ["Run shell command" + ("s" "in repository root" magit-shell-command-topdir) + ("S" "in working directory" magit-shell-command)] + ["Launch" + ("k" "gitk" magit-run-gitk) + ("a" "gitk --all" magit-run-gitk-all) + ("b" "gitk --branches" magit-run-gitk-branches) + ("g" "git gui" magit-run-git-gui) + ("m" "git mergetool --gui" magit-git-mergetool)]]) + +;;;###autoload +(defun magit-git-command (command) + "Execute COMMAND asynchronously; display output. + +Interactively, prompt for COMMAND in the minibuffer. \"git \" is +used as initial input, but can be deleted to run another command. + +With a prefix argument COMMAND is run in the top-level directory +of the current working tree, otherwise in `default-directory'." + (interactive (list (magit-read-shell-command nil "git "))) + (magit--shell-command command)) + +;;;###autoload +(defun magit-git-command-topdir (command) + "Execute COMMAND asynchronously; display output. + +Interactively, prompt for COMMAND in the minibuffer. \"git \" is +used as initial input, but can be deleted to run another command. + +COMMAND is run in the top-level directory of the current +working tree." + (interactive (list (magit-read-shell-command t "git "))) + (magit--shell-command command (magit-toplevel))) + +;;;###autoload +(defun magit-shell-command (command) + "Execute COMMAND asynchronously; display output. + +Interactively, prompt for COMMAND in the minibuffer. With a +prefix argument COMMAND is run in the top-level directory of +the current working tree, otherwise in `default-directory'." + (interactive (list (magit-read-shell-command))) + (magit--shell-command command)) + +;;;###autoload +(defun magit-shell-command-topdir (command) + "Execute COMMAND asynchronously; display output. + +Interactively, prompt for COMMAND in the minibuffer. COMMAND +is run in the top-level directory of the current working tree." + (interactive (list (magit-read-shell-command t))) + (magit--shell-command command (magit-toplevel))) + +(defun magit--shell-command (command &optional directory) + (let ((default-directory (or directory default-directory))) + (with-environment-variables (("GIT_PAGER" "cat")) + (magit--with-connection-local-variables + (magit-with-editor + (magit-start-process shell-file-name nil + shell-command-switch command))))) + (magit-process-buffer)) + +(defun magit-read-shell-command (&optional toplevel initial-input) + (let ((default-directory + (if (or toplevel current-prefix-arg) + (or (magit-toplevel) + (magit--not-inside-repository-error)) + default-directory))) + (read-shell-command (if magit-shell-command-verbose-prompt + (format "Async shell command in %s: " + (abbreviate-file-name default-directory)) + "Async shell command: ") + initial-input 'magit-git-command-history))) + +;;; Shared Infix Arguments + +(transient-define-argument magit:--gpg-sign () + :description "Sign using gpg" + :class 'transient-option + :shortarg "-S" + :argument "--gpg-sign=" + :allow-empty t + :reader #'magit-read-gpg-signing-key) + +(defvar magit-gpg-secret-key-hist nil) + +(defun magit-read-gpg-secret-key + (prompt &optional initial-input history predicate default) + (require 'epa) + (let* ((keys (cl-mapcan + (lambda (cert) + (and (or (not predicate) + (funcall predicate cert)) + (let* ((key (car (epg-key-sub-key-list cert))) + (fpr (epg-sub-key-fingerprint key)) + (id (epg-sub-key-id key)) + (author + (and-let* ((id-obj + (car (epg-key-user-id-list cert)))) + (let ((id-str (epg-user-id-string id-obj))) + (if (stringp id-str) + id-str + (epg-decode-dn id-obj)))))) + (list + (propertize fpr 'display + (concat (substring fpr 0 (- (length id))) + (propertize id 'face 'highlight) + " " author)))))) + (epg-list-keys (epg-make-context epa-protocol) nil t))) + (choice (or (and (not current-prefix-arg) + (or (and (length= keys 1) (car keys)) + (and default (car (member default keys))))) + (completing-read prompt keys nil nil nil + history nil initial-input)))) + (set-text-properties 0 (length choice) nil choice) + choice)) + +(defun magit-read-gpg-signing-key (prompt &optional initial-input history) + (magit-read-gpg-secret-key + prompt initial-input history + (lambda (cert) + (cl-some (lambda (key) + (memq 'sign (epg-sub-key-capability key))) + (epg-key-sub-key-list cert))) + magit-openpgp-default-signing-key)) + +;;; Font-Lock Keywords + +(defconst magit-font-lock-keywords + (eval-when-compile + `((,(concat "(\\(magit-define-section-jumper\\)\\_>" + "[ \t'(]*" + "\\(\\(?:\\sw\\|\\s_\\)+\\)?") + (1 'font-lock-keyword-face) + (2 'font-lock-function-name-face nil t)) + (,(concat "(" (regexp-opt '("magit-insert-section" + "magit-section-case" + "magit-bind-match-strings" + "magit-with-temp-index" + "magit-with-blob" + "magit-with-toplevel") + t) + "\\_>") + . 1)))) + +(font-lock-add-keywords 'emacs-lisp-mode magit-font-lock-keywords) + +;;; Version + +(defvar magit-version #'undefined + "The version of Magit that you're using. +Use the function by the same name instead of this variable.") + +;;;###autoload +(defun magit-version (&optional print-dest interactive nowarn) + "Return the version of Magit currently in use. + +If optional argument PRINT-DEST is non-nil, also print the used +versions of Magit, Transient, Git and Emacs to the output stream +selected by that argument. Interactively use the echo area, or +with a prefix argument use the current buffer. Additionally put +the output in the kill ring. +\n(fn &optional PRINT-DEST)" + (interactive (list (if current-prefix-arg (current-buffer) t) t)) + (let ((magit-git-global-arguments nil) + (toplib (or load-file-name buffer-file-name)) + debug) + (unless (and toplib + (member (file-name-nondirectory toplib) + '("magit.el" "magit.el.gz"))) + (let ((load-suffixes (reverse load-suffixes))) ; prefer .el than .elc + (setq toplib (locate-library "magit")))) + (setq toplib (and toplib (magit--chase-links toplib))) + (push toplib debug) + (when toplib + (let* ((topdir (file-name-directory toplib)) + (gitdir (expand-file-name + ".git" (file-name-directory + (directory-file-name topdir)))) + (static (locate-library "magit-version.el" nil (list topdir))) + (static (and static (magit--chase-links static)))) + (or (progn + (push 'repo debug) + (when (and (file-exists-p gitdir) + ;; It is a repo, but is it the Magit repo? + (file-exists-p + (expand-file-name "../lisp/magit.el" gitdir))) + (push t debug) + ;; Inside the repo the version file should only exist + ;; while running make. + (when (and static (not noninteractive)) + (ignore-errors (delete-file static))) + (setq magit-version + (let ((default-directory topdir)) + (magit-git-string "describe" + "--tags" "--dirty" "--always"))))) + (progn + (push 'static debug) + (when (and static (file-exists-p static)) + (push t debug) + (load-file static) + magit-version)) + (when (featurep 'package) + (push 'elpa debug) + (ignore-errors + (when-let ((version (cadr (assq 'magit package-alist)))) + (push t debug) + (setq magit-version + (and (fboundp 'package-desc-version) + (package-version-join + (package-desc-version version))))))) + (progn + (push 'dirname debug) + (let ((dirname (file-name-nondirectory + (directory-file-name topdir)))) + (when (string-match "\\`magit-\\([0-9].*\\)" dirname) + (setq magit-version (match-string 1 dirname))))) + ;; If all else fails, just report the commit hash. It's + ;; better than nothing and we cannot do better in the case + ;; of e.g., a shallow clone. + (progn + (push 'hash debug) + ;; Same check as above to see if it's really the Magit repo. + (when (and (file-exists-p gitdir) + (file-exists-p + (expand-file-name "../lisp/magit.el" gitdir))) + (setq magit-version + (let ((default-directory topdir)) + (magit-git-string "rev-parse" "HEAD")))))))) + (if (stringp magit-version) + (when print-dest + (let ((str (format + "Magit %s%s, Transient %s,%s Git %s, Emacs %s, %s" + (or magit-version "(unknown)") + (or (and (ignore-errors + (magit--version>= magit-version "2008")) + (ignore-errors + (require 'lisp-mnt) + (and (fboundp 'lm-header) + (format + " [>= %s]" + (with-temp-buffer + (insert-file-contents + (locate-library "magit.el" t)) + (lm-header "Package-Version")))))) + "") + (or (ignore-errors + (require 'lisp-mnt) + (and (fboundp 'lm-header) + (with-temp-buffer + (insert-file-contents + (locate-library "transient.el" t)) + (lm-header "Package-Version")))) + "(unknown)") + (let ((lib (locate-library "forge.el" t))) + (or (and lib + (format + " Forge %s," + (or (ignore-errors + (require 'lisp-mnt) + (with-temp-buffer + (insert-file-contents lib) + (and (fboundp 'lm-header) + (lm-header "Package-Version")))) + "(unknown)"))) + "")) + (magit--safe-git-version) + emacs-version + system-type))) + (when interactive + (kill-new str)) + (princ str print-dest))) + (setq debug (reverse debug)) + (setq magit-version 'error) + (when magit-version + (push magit-version debug)) + (unless (or nowarn (equal (getenv "CI") "true")) + (message "Cannot determine Magit's version %S" debug))) + magit-version)) + +;;; Startup Asserts + +(defun magit-startup-asserts () + (when-let ((val (getenv "GIT_DIR"))) + (setenv "GIT_DIR") + (message + "Magit unset $GIT_DIR (was %S). See %s" val + ;; Note: Pass URL as argument rather than embedding in the format + ;; string to prevent the single quote from being rendered + ;; according to `text-quoting-style'. + "https://github.com/magit/magit/wiki/Don't-set-$GIT_DIR-and-alike")) + (when-let ((val (getenv "GIT_WORK_TREE"))) + (setenv "GIT_WORK_TREE") + (message + "Magit unset $GIT_WORK_TREE (was %S). See %s" val + ;; See comment above. + "https://github.com/magit/magit/wiki/Don't-set-$GIT_DIR-and-alike")) + ;; Git isn't required while building Magit. + (unless (bound-and-true-p byte-compile-current-file) + (magit-git-version-assert)) + (when (version< emacs-version magit--minimal-emacs) + (display-warning 'magit (format "\ +Magit requires Emacs >= %s, you are using %s. + +If this comes as a surprise to you, because you do actually have +a newer version installed, then that probably means that the +older version happens to appear earlier on the `$PATH'. If you +always start Emacs from a shell, then that can be fixed in the +shell's init file. If you start Emacs by clicking on an icon, +or using some sort of application launcher, then you probably +have to adjust the environment as seen by graphical interface. +For X11 something like ~/.xinitrc should work.\n" + magit--minimal-emacs emacs-version) + :error))) + +;;; Loading Libraries + +(provide 'magit) + +(cl-eval-when (load eval) + (require 'magit-status) + (require 'magit-refs) + (require 'magit-files) + (require 'magit-reset) + (require 'magit-branch) + (require 'magit-merge) + (require 'magit-tag) + (require 'magit-worktree) + (require 'magit-notes) + (require 'magit-sequence) + (require 'magit-commit) + (require 'magit-remote) + (require 'magit-clone) + (require 'magit-fetch) + (require 'magit-pull) + (require 'magit-push) + (require 'magit-bisect) + (require 'magit-stash) + (require 'magit-blame) + (require 'magit-submodule) + (unless (load "magit-autoloads" t t) + (require 'magit-patch) + (require 'magit-subtree) + (require 'magit-ediff) + (require 'magit-gitignore) + (require 'magit-sparse-checkout) + (require 'magit-extras) + (require 'git-rebase) + (require 'magit-bookmark))) + +(with-eval-after-load 'bookmark + (require 'magit-bookmark)) + +(unless (bound-and-true-p byte-compile-current-file) + (if after-init-time + (progn (magit-startup-asserts) + (magit-version nil nil t)) + (add-hook 'after-init-hook #'magit-startup-asserts t) + (add-hook 'after-init-hook #'magit-version t))) + +;;; magit.el ends here diff --git a/emacs/elpa/magit-20241004.917/magit.info b/emacs/elpa/magit-20241004.917/magit.info @@ -0,0 +1,11592 @@ +This is magit.info, produced by makeinfo version 6.8 from magit.texi. + + Copyright (C) 2015-2024 Jonas Bernoulli + <emacs.magit@jonas.bernoulli.dev> + + You can redistribute this document and/or modify it under the terms + of the GNU General Public License as published by the Free Software + Foundation, either version 3 of the License, or (at your option) + any later version. + + This document is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + +INFO-DIR-SECTION Emacs +START-INFO-DIR-ENTRY +* Magit: (magit). Using Git from Emacs with Magit. +END-INFO-DIR-ENTRY + + +File: magit.info, Node: Top, Next: Introduction, Up: (dir) + +Magit User Manual +***************** + +Magit is an interface to the version control system Git, implemented as +an Emacs package. Magit aspires to be a complete Git porcelain. While +we cannot (yet) claim that Magit wraps and improves upon each and every +Git command, it is complete enough to allow even experienced Git users +to perform almost all of their daily version control tasks directly from +within Emacs. While many fine Git clients exist, only Magit and Git +itself deserve to be called porcelains. + +This manual is for Magit version 4.1.1. + + Copyright (C) 2015-2024 Jonas Bernoulli + <emacs.magit@jonas.bernoulli.dev> + + You can redistribute this document and/or modify it under the terms + of the GNU General Public License as published by the Free Software + Foundation, either version 3 of the License, or (at your option) + any later version. + + This document is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + +* Menu: + +* Introduction:: +* Installation:: +* Getting Started:: +* Interface Concepts:: +* Inspecting:: +* Manipulating:: +* Transferring:: +* Miscellaneous:: +* Customizing:: +* Plumbing:: +* FAQ:: +* Debugging Tools:: +* Keystroke Index:: +* Function and Command Index:: +* Variable Index:: + +— The Detailed Node Listing — + +Installation + +* Installing from Melpa:: +* Installing from the Git Repository:: +* Post-Installation Tasks:: + +Interface Concepts + +* Modes and Buffers:: +* Sections:: +* Transient Commands:: +* Transient Arguments and Buffer Variables:: +* Completion, Confirmation and the Selection: Completion Confirmation and the Selection. +* Mouse Support:: +* Running Git:: + +Modes and Buffers + +* Switching Buffers:: +* Naming Buffers:: +* Quitting Windows:: +* Automatic Refreshing of Magit Buffers:: +* Automatic Saving of File-Visiting Buffers:: +* Automatic Reverting of File-Visiting Buffers:: + + +Sections + +* Section Movement:: +* Section Visibility:: +* Section Hooks:: +* Section Types and Values:: +* Section Options:: + + +Completion, Confirmation and the Selection + +* Action Confirmation:: +* Completion and Confirmation:: +* The Selection:: +* The hunk-internal region:: +* Support for Completion Frameworks:: +* Additional Completion Options:: + + +Running Git + +* Viewing Git Output:: +* Git Process Status:: +* Running Git Manually:: +* Git Executable:: +* Global Git Arguments:: + + +Inspecting + +* Status Buffer:: +* Repository List:: +* Logging:: +* Diffing:: +* Ediffing:: +* References Buffer:: +* Bisecting:: +* Visiting Files and Blobs:: +* Blaming:: + +Status Buffer + +* Status Sections:: +* Status Header Sections:: +* Status Module Sections:: +* Status Options:: + + +Logging + +* Refreshing Logs:: +* Log Buffer:: +* Log Margin:: +* Select from Log:: +* Reflog:: +* Cherries:: + + +Diffing + +* Refreshing Diffs:: +* Commands Available in Diffs:: +* Diff Options:: +* Revision Buffer:: + + +References Buffer + +* References Sections:: + + +Visiting Files and Blobs + +* General-Purpose Visit Commands:: +* Visiting Files and Blobs from a Diff:: + + +Manipulating + +* Creating Repository:: +* Cloning Repository:: +* Staging and Unstaging:: +* Applying:: +* Committing:: +* Branching:: +* Merging:: +* Resolving Conflicts:: +* Rebasing:: +* Cherry Picking:: +* Resetting:: +* Stashing:: + +Staging and Unstaging + +* Staging from File-Visiting Buffers:: + + +Committing + +* Initiating a Commit:: +* Editing Commit Messages:: + + +Branching + +* The Two Remotes:: +* Branch Commands:: +* Branch Git Variables:: +* Auxiliary Branch Commands:: + + +Rebasing + +* Editing Rebase Sequences:: +* Information About In-Progress Rebase:: + + +Cherry Picking + +* Reverting:: + + +Transferring + +* Remotes:: +* Fetching:: +* Pulling:: +* Pushing:: +* Plain Patches:: +* Maildir Patches:: + +Remotes + +* Remote Commands:: +* Remote Git Variables:: + + +Miscellaneous + +* Tagging:: +* Notes:: +* Submodules:: +* Subtree:: +* Worktree:: +* Sparse checkouts:: +* Bundle:: +* Common Commands:: +* Wip Modes:: +* Commands for Buffers Visiting Files:: +* Minor Mode for Buffers Visiting Blobs:: + +Submodules + +* Listing Submodules:: +* Submodule Transient:: + + +Wip Modes + +* Wip Graph:: +* Legacy Wip Modes:: + + +Customizing + +* Per-Repository Configuration:: +* Essential Settings:: + +Essential Settings + +* Safety:: +* Performance:: +* Global Bindings:: + + +Plumbing + +* Calling Git:: +* Section Plumbing:: +* Refreshing Buffers:: +* Conventions:: + +Calling Git + +* Getting a Value from Git:: +* Calling Git for Effect:: + + +Section Plumbing + +* Creating Sections:: +* Section Selection:: +* Matching Sections:: + + +Conventions + +* Theming Faces:: + + +FAQ + +* FAQ - How to ...?:: +* FAQ - Issues and Errors:: + +FAQ - How to ...? + +* How to pronounce Magit?:: +* How to show git's output?:: +* How to install the gitman info manual?:: +* How to show diffs for gpg-encrypted files?:: +* How does branching and pushing work?:: +* Should I disable VC?:: + + +FAQ - Issues and Errors + +* Magit is slow:: +* I changed several thousand files at once and now Magit is unusable:: +* I am having problems committing:: +* I am using MS Windows and cannot push with Magit:: +* I am using macOS and SOMETHING works in shell, but not in Magit: I am using macOS and SOMETHING works in shell but not in Magit. +* Expanding a file to show the diff causes it to disappear:: +* Point is wrong in the COMMIT_EDITMSG buffer:: +* The mode-line information isn't always up-to-date:: +* A branch and tag sharing the same name breaks SOMETHING:: +* My Git hooks work on the command-line but not inside Magit:: +* git-commit-mode isn't used when committing from the command-line:: +* Point ends up inside invisible text when jumping to a file-visiting buffer:: +* I am no longer able to save popup defaults:: + + + + +File: magit.info, Node: Introduction, Next: Installation, Prev: Top, Up: Top + +1 Introduction +************** + +Magit is an interface to the version control system Git, implemented as +an Emacs package. Magit aspires to be a complete Git porcelain. While +we cannot (yet) claim that Magit wraps and improves upon each and every +Git command, it is complete enough to allow even experienced Git users +to perform almost all of their daily version control tasks directly from +within Emacs. While many fine Git clients exist, only Magit and Git +itself deserve to be called porcelains. + + Staging and otherwise applying changes is one of the most important +features in a Git porcelain and here Magit outshines anything else, +including Git itself. Git’s own staging interface (‘git add --patch’) +is so cumbersome that many users only use it in exceptional cases. In +Magit staging a hunk or even just part of a hunk is as trivial as +staging all changes made to a file. + + The most visible part of Magit’s interface is the status buffer, +which displays information about the current repository. Its content is +created by running several Git commands and making their output +actionable. Among other things, it displays information about the +current branch, lists unpulled and unpushed changes and contains +sections displaying the staged and unstaged changes. That might sound +noisy, but, since sections are collapsible, it’s not. + + To stage or unstage a change one places the cursor on the change and +then types ‘s’ or ‘u’. The change can be a file or a hunk, or when the +region is active (i.e., when there is a selection) several files or +hunks, or even just part of a hunk. The change or changes that these +commands - and many others - would act on are highlighted. + + Magit also implements several other "apply variants" in addition to +staging and unstaging. One can discard or reverse a change, or apply it +to the working tree. Git’s own porcelain only supports this for staging +and unstaging and you would have to do something like ‘git diff ... | +??? | git apply ...’ to discard, revert, or apply a single hunk on the +command line. In fact that’s exactly what Magit does internally (which +is what lead to the term "apply variants"). + + Magit isn’t just for Git experts, but it does assume some prior +experience with Git as well as Emacs. That being said, many users have +reported that using Magit was what finally taught them what Git is +capable of and how to use it to its fullest. Other users wished they +had switched to Emacs sooner so that they would have gotten their hands +on Magit earlier. + + While one has to know the basic features of Emacs to be able to make +full use of Magit, acquiring just enough Emacs skills doesn’t take long +and is worth it, even for users who prefer other editors. Vim users are +advised to give Evil (https://github.com/emacs-evil/evil), the +"Extensible VI Layer for Emacs", and Spacemacs +(https://github.com/syl20bnr/spacemacs), an "Emacs starter-kit focused +on Evil" a try. + + Magit provides a consistent and efficient Git porcelain. After a +short learning period, you will be able to perform most of your daily +version control tasks faster than you would on the command line. You +will likely also start using features that seemed too daunting in the +past. + + Magit fully embraces Git. It exposes many advanced features using a +simple but flexible interface instead of only wrapping the trivial ones +like many GUI clients do. Of course Magit supports logging, cloning, +pushing, and other commands that usually don’t fail in spectacular ways; +but it also supports tasks that often cannot be completed in a single +step. Magit fully supports tasks such as merging, rebasing, +cherry-picking, reverting, and blaming by not only providing a command +to initiate these tasks but also by displaying context sensitive +information along the way and providing commands that are useful for +resolving conflicts and resuming the sequence after doing so. + + Magit wraps and in many cases improves upon at least the following +Git porcelain commands: ‘add’, ‘am’, ‘bisect’, ‘blame’, ‘branch’, +‘checkout’, ‘cherry’, ‘cherry-pick’, ‘clean’, ‘clone’, ‘commit’, +‘config’, ‘describe’, ‘diff’, ‘fetch’, ‘format-patch’, ‘init’, ‘log’, +‘merge’, ‘merge-tree’, ‘mv’, ‘notes’, ‘pull’, ‘rebase’, ‘reflog’, +‘remote’, ‘request-pull’, ‘reset’, ‘revert’, ‘rm’, ‘show’, ‘stash’, +‘submodule’, ‘subtree’, ‘tag’, and ‘worktree.’ Many more Magit porcelain +commands are implemented on top of Git plumbing commands. + + +File: magit.info, Node: Installation, Next: Getting Started, Prev: Introduction, Up: Top + +2 Installation +************** + +Magit can be installed using Emacs’ package manager or manually from its +development repository. + +* Menu: + +* Installing from Melpa:: +* Installing from the Git Repository:: +* Post-Installation Tasks:: + + +File: magit.info, Node: Installing from Melpa, Next: Installing from the Git Repository, Up: Installation + +2.1 Installing from Melpa +========================= + +Magit is available from Melpa and Melpa-Stable. If you haven’t used +Emacs’ package manager before, then it is high time you familiarize +yourself with it by reading the documentation in the Emacs manual, see +*note (emacs)Packages::. Then add one of the archives to +‘package-archives’: + + • To use Melpa: + + (require 'package) + (add-to-list 'package-archives + '("melpa" . "https://melpa.org/packages/") t) + + • To use Melpa-Stable: + + (require 'package) + (add-to-list 'package-archives + '("melpa-stable" . "https://stable.melpa.org/packages/") t) + + Once you have added your preferred archive, you need to update the +local package list using: + + M-x package-refresh-contents RET + + Once you have done that, you can install Magit and its dependencies +using: + + M-x package-install RET magit RET + + Now see *note Post-Installation Tasks::. + + +File: magit.info, Node: Installing from the Git Repository, Next: Post-Installation Tasks, Prev: Installing from Melpa, Up: Installation + +2.2 Installing from the Git Repository +====================================== + +Magit depends on the ‘compat’, ‘dash’, ‘transient’ and ‘with-editor’ +libraries which are available from Melpa and Melpa-Stable. Install them +using ‘M-x package-install RET <package> RET’. Of course you may also +install them manually from their repository. + + Then clone the Magit repository: + + $ git clone https://github.com/magit/magit.git ~/.emacs.d/site-lisp/magit + $ cd ~/.emacs.d/site-lisp/magit + + Then compile the libraries and generate the info manuals: + + $ make + + If you haven’t installed ‘compat’, ‘dash’, ‘transient’ and +‘with-editor’ from Melpa or at ‘/path/to/magit/../<package>’, then you +have to tell ‘make’ where to find them. To do so create the file +‘/path/to/magit/config.mk’ with the following content before running +‘make’: + + LOAD_PATH = -L ~/.emacs.d/site-lisp/magit/lisp + LOAD_PATH += -L ~/.emacs.d/site-lisp/dash + LOAD_PATH += -L ~/.emacs.d/site-lisp/transient/lisp + LOAD_PATH += -L ~/.emacs.d/site-lisp/with-editor/lisp + LOAD_PATH += -L ~/.emacs.d/site-lisp/compat + + Finally add this to your init file: + + (add-to-list 'load-path "~/.emacs.d/site-lisp/magit/lisp") + (require 'magit) + + (with-eval-after-load 'info + (info-initialize) + (add-to-list 'Info-directory-list + "~/.emacs.d/site-lisp/magit/Documentation/")) + + Of course if you installed the dependencies manually as well, then +you have to tell Emacs about them too, by prefixing the above with: + + (add-to-list 'load-path "~/.emacs.d/site-lisp/dash") + (add-to-list 'load-path "~/.emacs.d/site-lisp/transient/lisp") + (add-to-list 'load-path "~/.emacs.d/site-lisp/with-editor") + + Note that you have to add the ‘lisp’ subdirectory to the ‘load-path’, +not the top-level of the repository, and that elements of ‘load-path’ +should not end with a slash, while those of ‘Info-directory-list’ +should. + + Instead of requiring the feature ‘magit’, you could load just the +autoload definitions, by loading the file ‘magit-autoloads.el’. + + (load "/path/to/magit/lisp/magit-autoloads") + + Instead of running Magit directly from the repository by adding that +to the ‘load-path’, you might want to instead install it in some other +directory using ‘sudo make install’ and setting ‘load-path’ accordingly. + + To update Magit use: + + $ git pull + $ make + + At times it might be necessary to run ‘make clean all’ instead. + + To view all available targets use ‘make help’. + + Now see *note Post-Installation Tasks::. + + +File: magit.info, Node: Post-Installation Tasks, Prev: Installing from the Git Repository, Up: Installation + +2.3 Post-Installation Tasks +=========================== + +After installing Magit you should verify that you are indeed using the +Magit, Git, and Emacs releases you think you are using. It’s best to +restart Emacs before doing so, to make sure you are not using an +outdated value for ‘load-path’. + + M-x magit-version RET + + should display something like + + Magit 2.8.0, Git 2.10.2, Emacs 25.1.1, gnu/linux + + Then you might also want to read about options that many users likely +want to customize. See *note Essential Settings::. + + To be able to follow cross references to Git manpages found in this +manual, you might also have to manually install the ‘gitman’ info +manual, or advice ‘Info-follow-nearest-node’ to instead open the actual +manpage. See *note How to install the gitman info manual?::. + + If you are completely new to Magit then see *note Getting Started::. + + If you run into problems, then please see the *note FAQ::. Also see +the *note Debugging Tools::. + + And last but not least please consider making a donation, to ensure +that I can keep working on Magit. See <https://magit.vc/donations>. +for various donation options. + + +File: magit.info, Node: Getting Started, Next: Interface Concepts, Prev: Installation, Up: Top + +3 Getting Started +***************** + +This short tutorial describes the most essential features that many +Magitians use on a daily basis. It only scratches the surface but +should be enough to get you started. + + IMPORTANT: It is safest if you clone some repository just for this +tutorial. Alternatively you can use an existing local repository, but +if you do that, then you should commit all uncommitted changes before +proceeding. + + Type ‘C-x g’ to display information about the current Git repository +in a dedicated buffer, called the status buffer. + + Most Magit commands are commonly invoked from the status buffer. It +can be considered the primary interface for interacting with Git using +Magit. Many other Magit buffers may exist at a given time, but they are +often created from this buffer. + + Depending on what state your repository is in, this buffer may +contain sections titled "Staged changes", "Unstaged changes", "Unmerged +into origin/master", "Unpushed to origin/master", and many others. + + Since we are starting from a safe state, which you can easily return +to (by doing a ‘git reset --hard PRE-MAGIT-STATE’), there currently are +no staged or unstaged changes. Edit some files and save the changes. +Then go back to the status buffer, while at the same time refreshing it, +by typing ‘C-x g’. (When the status buffer, or any Magit buffer for +that matter, is the current buffer, then you can also use just ‘g’ to +refresh it). + + Move between sections using ‘p’ and ‘n’. Note that the bodies of +some sections are hidden. Type ‘TAB’ to expand or collapse the section +at point. You can also use ‘C-tab’ to cycle the visibility of the +current section and its children. Move to a file section inside the +section named "Unstaged changes" and type ‘s’ to stage the changes you +have made to that file. That file now appears under "Staged changes". + + Magit can stage and unstage individual hunks, not just complete +files. Move to the file you have just staged, expand it using ‘TAB’, +move to one of the hunks using ‘n’, and unstage just that by typing ‘u’. +Note how the staging (‘s’) and unstaging (‘u’) commands operate on the +change at point. Many other commands behave the same way. + + You can also un-/stage just part of a hunk. Inside the body of a +hunk section (move there using ‘C-n’), set the mark using ‘C-SPC’ and +move down until some added and/or removed lines fall inside the region +but not all of them. Again type ‘s’ to stage. + + It is also possible to un-/stage multiple files at once. Move to a +file section, type ‘C-SPC’, move to the next file using ‘n’, and then +‘s’ to stage both files. Note that both the mark and point have to be +on the headings of sibling sections for this to work. If the region +looks like it does in other buffers, then it doesn’t select Magit +sections that can be acted on as a unit. + + And then of course you want to commit your changes. Type ‘c’. This +shows the available commit commands and arguments in a buffer at the +bottom of the frame. Each command and argument is prefixed with the key +that invokes/sets it. Do not worry about this for now. We want to +create a "normal" commit, which is done by typing ‘c’ again. + + Now two new buffers appear. One is for writing the commit message, +the other shows a diff with the changes that you are about to commit. +Write a message and then type ‘C-c C-c’ to actually create the commit. + + You probably don’t want to push the commit you just created because +you just committed some random changes, but if that is not the case you +could push it by typing ‘P’ to show all the available push commands and +arguments and then ‘p’ to push to a branch with the same name as the +local branch onto the remote configured as the push-remote. (If the +push-remote is not configured yet, then you would first be prompted for +the remote to push to.) + + So far we have mentioned the commit and push menu commands. These +are probably among the menus you will be using the most, but many others +exist. To show a menu that lists all other menus (as well as the +various apply commands and some other essential commands), type ‘h’. +Try a few. (Such menus are also called "transient prefix commands" or +just "transients".) + + The key bindings in that menu correspond to the bindings in Magit +buffers, including but not limited to the status buffer. So you could +type ‘h d’ to bring up the diff menu, but once you remember that "d" +stands for "diff", you would usually do so by just typing ‘d’. + + This "prefix of prefixes" is useful even once you have memorized all +the bindings, as it can provide easy access to Magit commands from +non-Magit buffers. So, by default, it is globally bound to ‘C-x M-g’. + + A similar menu featuring (for the most part) commands that act on +just the file being visited in the current buffer, is globally bound to +‘C-c M-g’. That binding can also be used in buffers, which do not visit +a file, but then only a subset of the commands is available. + + The global key bindings mentioned in the previous two paragraphs are +quite inconvenient. We recommend using ‘C-c g’ and ‘C-c f’ instead, but +cannot use those key sequences by default because they are strictly +reserved for bindings added by the user. See *note Global Bindings::, +if you want to explicitly opt-in to the recommended key bindings. + + Magit also provides context menus and other mouse commands, see *note +Mouse Support::. + + It is not necessary that you do so now, but if you stick with Magit, +then it is highly recommended that you read the next section too. + + +File: magit.info, Node: Interface Concepts, Next: Inspecting, Prev: Getting Started, Up: Top + +4 Interface Concepts +******************** + +* Menu: + +* Modes and Buffers:: +* Sections:: +* Transient Commands:: +* Transient Arguments and Buffer Variables:: +* Completion, Confirmation and the Selection: Completion Confirmation and the Selection. +* Mouse Support:: +* Running Git:: + + +File: magit.info, Node: Modes and Buffers, Next: Sections, Up: Interface Concepts + +4.1 Modes and Buffers +===================== + +Magit provides several major-modes. For each of these modes there +usually exists only one buffer per repository. Separate modes and thus +buffers exist for commits, diffs, logs, and some other things. + + Besides these special purpose buffers, there also exists an overview +buffer, called the *status buffer*. It’s usually from this buffer that +the user invokes Git commands, or creates or visits other buffers. + + In this manual we often speak about "Magit buffers". By that we mean +buffers whose major-modes derive from ‘magit-mode’. + +‘M-x magit-toggle-buffer-lock’ + This command locks the current buffer to its value or if the buffer + is already locked, then it unlocks it. + + Locking a buffer to its value prevents it from being reused to + display another value. The name of a locked buffer contains its + value, which allows telling it apart from other locked buffers and + the unlocked buffer. + + Not all Magit buffers can be locked to their values; for example, + it wouldn’t make sense to lock a status buffer. + + There can only be a single unlocked buffer using a certain + major-mode per repository. So when a buffer is being unlocked and + another unlocked buffer already exists for that mode and + repository, then the former buffer is instead deleted and the + latter is displayed in its place. + +* Menu: + +* Switching Buffers:: +* Naming Buffers:: +* Quitting Windows:: +* Automatic Refreshing of Magit Buffers:: +* Automatic Saving of File-Visiting Buffers:: +* Automatic Reverting of File-Visiting Buffers:: + + +File: magit.info, Node: Switching Buffers, Next: Naming Buffers, Up: Modes and Buffers + +4.1.1 Switching Buffers +----------------------- + + -- Function: magit-display-buffer buffer &optional display-function + This function is a wrapper around ‘display-buffer’ and is used to + display any Magit buffer. It displays BUFFER in some window and, + unlike ‘display-buffer’, also selects that window, provided + ‘magit-display-buffer-noselect’ is ‘nil’. It also runs the hooks + mentioned below. + + If optional DISPLAY-FUNCTION is non-nil, then that is used to + display the buffer. Usually that is ‘nil’ and the function + specified by ‘magit-display-buffer-function’ is used. + + -- Variable: magit-display-buffer-noselect + When this is non-nil, then ‘magit-display-buffer’ only displays the + buffer but forgoes also selecting the window. This variable should + not be set globally, it is only intended to be let-bound, by code + that automatically updates "the other window". This is used for + example when the revision buffer is updated when you move inside + the log buffer. + + -- User Option: magit-display-buffer-function + The function specified here is called by ‘magit-display-buffer’ + with one argument, a buffer, to actually display that buffer. This + function should call ‘display-buffer’ with that buffer as first and + a list of display actions as second argument. + + Magit provides several functions, listed below, that are suitable + values for this option. If you want to use different rules, then a + good way of doing that is to start with a copy of one of these + functions and then adjust it to your needs. + + Instead of using a wrapper around ‘display-buffer’, that function + itself can be used here, in which case the display actions have to + be specified by adding them to ‘display-buffer-alist’ instead. + + To learn about display actions, see *note (elisp)Choosing Window::. + + -- Function: magit-display-buffer-traditional buffer + This function is the current default value of the option + ‘magit-display-buffer-function’. Before that option and this + function were added, the behavior was hard-coded in many places all + over the code base but now all the rules are contained in this one + function (except for the "noselect" special case mentioned above). + + -- Function: magit-display-buffer-same-window-except-diff-v1 + This function displays most buffers in the currently selected + window. If a buffer’s mode derives from ‘magit-diff-mode’ or + ‘magit-process-mode’, it is displayed in another window. + + -- Function: magit-display-buffer-fullframe-status-v1 + This function fills the entire frame when displaying a status + buffer. Otherwise, it behaves like + ‘magit-display-buffer-traditional’. + + -- Function: magit-display-buffer-fullframe-status-topleft-v1 + This function fills the entire frame when displaying a status + buffer. It behaves like ‘magit-display-buffer-fullframe-status-v1’ + except that it displays buffers that derive from ‘magit-diff-mode’ + or ‘magit-process-mode’ to the top or left of the current buffer + rather than to the bottom or right. As a result, Magit buffers + tend to pop up on the same side as they would if + ‘magit-display-buffer-traditional’ were in use. + + -- Function: magit-display-buffer-fullcolumn-most-v1 + This function displays most buffers so that they fill the entire + height of the frame. However, the buffer is displayed in another + window if (1) the buffer’s mode derives from ‘magit-process-mode’, + or (2) the buffer’s mode derives from ‘magit-diff-mode’, provided + that the mode of the current buffer derives from ‘magit-log-mode’ + or ‘magit-cherry-mode’. + + -- User Option: magit-pre-display-buffer-hook + This hook is run by ‘magit-display-buffer’ before displaying the + buffer. + + -- Function: magit-save-window-configuration + This function saves the current window configuration. Later when + the buffer is buried, it may be restored by + ‘magit-restore-window-configuration’. + + -- User Option: magit-post-display-buffer-hook + This hook is run by ‘magit-display-buffer’ after displaying the + buffer. + + -- Function: magit-maybe-set-dedicated + This function remembers if a new window had to be created to + display the buffer, or whether an existing window was reused. This + information is later used by ‘magit-mode-quit-window’, to determine + whether the window should be deleted when its last Magit buffer is + buried. + + +File: magit.info, Node: Naming Buffers, Next: Quitting Windows, Prev: Switching Buffers, Up: Modes and Buffers + +4.1.2 Naming Buffers +-------------------- + + -- User Option: magit-generate-buffer-name-function + The function used to generate the names of Magit buffers. + + Such a function should take the options + ‘magit-uniquify-buffer-names’ as well as ‘magit-buffer-name-format’ + into account. If it doesn’t, then should be clearly stated in the + doc-string. And if it supports %-sequences beyond those mentioned + in the doc-string of the option ‘magit-buffer-name-format’, then + its own doc-string should describe the additions. + + -- Function: magit-generate-buffer-name-default-function mode + This function returns a buffer name suitable for a buffer whose + major-mode is MODE and which shows information about the repository + in which ‘default-directory’ is located. + + This function uses ‘magit-buffer-name-format’ and supporting all of + the %-sequences mentioned the documentation of that option. It + also respects the option ‘magit-uniquify-buffer-names’. + + -- User Option: magit-buffer-name-format + The format string used to name Magit buffers. + + At least the following %-sequences are supported: + + • ‘%m’ + + The name of the major-mode, but with the ‘-mode’ suffix + removed. + + • ‘%M’ + + Like ‘%m’ but abbreviate ‘magit-status-mode’ as ‘magit’. + + • ‘%v’ + + The value the buffer is locked to, in parentheses, or an empty + string if the buffer is not locked to a value. + + • ‘%V’ + + Like ‘%v’, but the string is prefixed with a space, unless it + is an empty string. + + • ‘%t’ + + The top-level directory of the working tree of the repository, + or if ‘magit-uniquify-buffer-names’ is non-nil an abbreviation + of that. + + • ‘%x’ + + If ‘magit-uniquify-buffer-names’ is nil "*", otherwise the + empty string. Due to limitations of the ‘uniquify’ package, + buffer names must end with the path. + + The value should always contain ‘%m’ or ‘%M’, ‘%v’ or ‘%V’, and + ‘%t’. If ‘magit-uniquify-buffer-names’ is non-nil, then the value + must end with ‘%t’ or ‘%t%x’. See issue #2841. + + -- User Option: magit-uniquify-buffer-names + This option controls whether the names of Magit buffers are + uniquified. If the names are not being uniquified, then they + contain the full path of the top-level of the working tree of the + corresponding repository. If they are being uniquified, then they + end with the basename of the top-level, or if that would conflict + with the name used for other buffers, then the names of all these + buffers are adjusted until they no longer conflict. + + This is done using the ‘uniquify’ package; customize its options to + control how buffer names are uniquified. + + +File: magit.info, Node: Quitting Windows, Next: Automatic Refreshing of Magit Buffers, Prev: Naming Buffers, Up: Modes and Buffers + +4.1.3 Quitting Windows +---------------------- + +‘q’ (‘magit-mode-bury-buffer’) + This command buries or kills the current Magit buffer. The + function specified by option ‘magit-bury-buffer-function’ is used + to bury the buffer when called without a prefix argument or to kill + it when called with a single prefix argument. + + When called with two or more prefix arguments then it always kills + all Magit buffers, associated with the current project, including + the current buffer. + + -- User Option: magit-bury-buffer-function + The function used to actually bury or kill the current buffer. + + ‘magit-mode-bury-buffer’ calls this function with one argument. If + the argument is non-nil, then the function has to kill the current + buffer. Otherwise it has to bury it alive. The default value + currently is ‘magit-mode-quit-window’. + + -- Function: magit-restore-window-configuration kill-buffer + Bury or kill the current buffer using ‘quit-window’, which is + called with KILL-BUFFER as first and the selected window as second + argument. + + Then restore the window configuration that existed right before the + current buffer was displayed in the selected frame. Unfortunately + that also means that point gets adjusted in all the buffers, which + are being displayed in the selected frame. + + -- Function: magit-mode-quit-window kill-buffer + Bury or kill the current buffer using ‘quit-window’, which is + called with KILL-BUFFER as first and the selected window as second + argument. + + Then, if the window was originally created to display a Magit + buffer and the buried buffer was the last remaining Magit buffer + that was ever displayed in the window, then that is deleted. + + +File: magit.info, Node: Automatic Refreshing of Magit Buffers, Next: Automatic Saving of File-Visiting Buffers, Prev: Quitting Windows, Up: Modes and Buffers + +4.1.4 Automatic Refreshing of Magit Buffers +------------------------------------------- + +After running a command which may change the state of the current +repository, the current Magit buffer and the corresponding status buffer +are refreshed. The status buffer can be automatically refreshed +whenever a buffer is saved to a file inside the respective repository by +adding a hook, like so: + + (with-eval-after-load 'magit-mode + (add-hook 'after-save-hook 'magit-after-save-refresh-status t)) + + Automatically refreshing Magit buffers ensures that the displayed +information is up-to-date most of the time but can lead to a noticeable +delay in big repositories. Other Magit buffers are not refreshed to +keep the delay to a minimum and also because doing so can sometimes be +undesirable. + + Buffers can also be refreshed explicitly, which is useful in buffers +that weren’t current during the last refresh and after changes were made +to the repository outside of Magit. + +‘g’ (‘magit-refresh’) + This command refreshes the current buffer if its major mode derives + from ‘magit-mode’ as well as the corresponding status buffer. + + If the option ‘magit-revert-buffers’ calls for it, then it also + reverts all unmodified buffers that visit files being tracked in + the current repository. + +‘G’ (‘magit-refresh-all’) + This command refreshes all Magit buffers belonging to the current + repository and also reverts all unmodified buffers that visit files + being tracked in the current repository. + + The file-visiting buffers are always reverted, even if + ‘magit-revert-buffers’ is nil. + + -- User Option: magit-refresh-buffer-hook + This hook is run in each Magit buffer that was refreshed during the + current refresh - normally the current buffer and the status + buffer. + + -- User Option: magit-refresh-status-buffer + When this option is non-nil, then the status buffer is + automatically refreshed after running git for side-effects, in + addition to the current Magit buffer, which is always refreshed + automatically. + + Only set this to nil after exhausting all other options to improve + performance. + + -- Function: magit-after-save-refresh-status + This function is intended to be added to ‘after-save-hook’. After + doing that the corresponding status buffer is refreshed whenever a + buffer is saved to a file inside a repository. + + Note that refreshing a Magit buffer is done by re-creating its + contents from scratch, which can be slow in large repositories. If + you are not satisfied with Magit’s performance, then you should + obviously not add this function to that hook. + + +File: magit.info, Node: Automatic Saving of File-Visiting Buffers, Next: Automatic Reverting of File-Visiting Buffers, Prev: Automatic Refreshing of Magit Buffers, Up: Modes and Buffers + +4.1.5 Automatic Saving of File-Visiting Buffers +----------------------------------------------- + +File-visiting buffers are by default saved at certain points in time. +This doesn’t guarantee that Magit buffers are always up-to-date, but, +provided one only edits files by editing them in Emacs and uses only +Magit to interact with Git, one can be fairly confident. When in doubt +or after outside changes, type ‘g’ (‘magit-refresh’) to save and refresh +explicitly. + + -- User Option: magit-save-repository-buffers + This option controls whether file-visiting buffers are saved before + certain events. + + If this is non-nil then all modified file-visiting buffers + belonging to the current repository may be saved before running + commands, before creating new Magit buffers, and before explicitly + refreshing such buffers. If this is ‘dontask’ then this is done + without user intervention. If it is ‘t’ then the user has to + confirm each save. + + +File: magit.info, Node: Automatic Reverting of File-Visiting Buffers, Prev: Automatic Saving of File-Visiting Buffers, Up: Modes and Buffers + +4.1.6 Automatic Reverting of File-Visiting Buffers +-------------------------------------------------- + +By default Magit automatically reverts buffers that are visiting files +that are being tracked in a Git repository, after they have changed on +disk. When using Magit one often changes files on disk by running Git, +i.e., "outside Emacs", making this a rather important feature. + + For example, if you discard a change in the status buffer, then that +is done by running ‘git apply --reverse ...’, and Emacs considers the +file to have "changed on disk". If Magit did not automatically revert +the buffer, then you would have to type ‘M-x revert-buffer RET RET’ in +the visiting buffer before you could continue making changes. + + -- User Option: magit-auto-revert-mode + When this mode is enabled, then buffers that visit tracked files + are automatically reverted after the visited files change on disk. + + -- User Option: global-auto-revert-mode + When this mode is enabled, then any file-visiting buffer is + automatically reverted after the visited file changes on disk. + + If you like buffers that visit tracked files to be automatically + reverted, then you might also like any buffer to be reverted, not + just those visiting tracked files. If that is the case, then + enable this mode _instead of_ ‘magit-auto-revert-mode’. + + -- User Option: magit-auto-revert-immediately + This option controls whether Magit reverts buffers immediately. + + If this is non-nil and either ‘global-auto-revert-mode’ or + ‘magit-auto-revert-mode’ is enabled, then Magit immediately reverts + buffers by explicitly calling ‘auto-revert-buffers’ after running + Git for side-effects. + + If ‘auto-revert-use-notify’ is non-nil (and file notifications are + actually supported), then ‘magit-auto-revert-immediately’ does not + have to be non-nil, because the reverts happen immediately anyway. + + If ‘magit-auto-revert-immediately’ and ‘auto-revert-use-notify’ are + both ‘nil’, then reverts happen after ‘auto-revert-interval’ + seconds of user inactivity. That is not desirable. + + -- User Option: auto-revert-use-notify + This option controls whether file notification functions should be + used. Note that this variable unfortunately defaults to ‘t’ even + on systems on which file notifications cannot be used. + + -- User Option: magit-auto-revert-tracked-only + This option controls whether ‘magit-auto-revert-mode’ only reverts + tracked files or all files that are located inside Git + repositories, including untracked files and files located inside + Git’s control directory. + + -- User Option: auto-revert-mode + The global mode ‘magit-auto-revert-mode’ works by turning on this + local mode in the appropriate buffers (but + ‘global-auto-revert-mode’ is implemented differently). You can + also turn it on or off manually, which might be necessary if Magit + does not notice that a previously untracked file now is being + tracked or vice-versa. + + -- User Option: auto-revert-stop-on-user-input + This option controls whether the arrival of user input suspends the + automatic reverts for ‘auto-revert-interval’ seconds. + + -- User Option: auto-revert-interval + This option controls how many seconds Emacs waits for before + resuming suspended reverts. + + -- User Option: auto-revert-buffer-list-filter + This option specifies an additional filter used by + ‘auto-revert-buffers’ to determine whether a buffer should be + reverted or not. + + This option is provided by Magit, which also advises + ‘auto-revert-buffers’ to respect it. Magit users who do not turn + on the local mode ‘auto-revert-mode’ themselves, are best served by + setting the value to ‘magit-auto-revert-repository-buffer-p’. + + However the default is nil, so as not to disturb users who do use + the local mode directly. If you experience delays when running + Magit commands, then you should consider using one of the + predicates provided by Magit - especially if you also use Tramp. + + Users who do turn on ‘auto-revert-mode’ in buffers in which Magit + doesn’t do that for them, should likely not use any filter. Users + who turn on ‘global-auto-revert-mode’, do not have to worry about + this option, because it is disregarded if the global mode is + enabled. + + -- User Option: auto-revert-verbose + This option controls whether Emacs reports when a buffer has been + reverted. + + The options with the ‘auto-revert-’ prefix are located in the Custom +group named ‘auto-revert’. The other, Magit-specific, options are +located in the ‘magit’ group. + +* Menu: + +* Risk of Reverting Automatically:: + + +File: magit.info, Node: Risk of Reverting Automatically, Up: Automatic Reverting of File-Visiting Buffers + +Risk of Reverting Automatically +............................... + +For the vast majority of users, automatically reverting file-visiting +buffers after they have changed on disk is harmless. + + If a buffer is modified (i.e., it contains changes that haven’t been +saved yet), then Emacs will refuse to automatically revert it. If you +save a previously modified buffer, then that results in what is seen by +Git as an uncommitted change. Git will then refuse to carry out any +commands that would cause these changes to be lost. In other words, if +there is anything that could be lost, then either Git or Emacs will +refuse to discard the changes. + + However, if you use file-visiting buffers as a sort of ad hoc +"staging area", then the automatic reverts could potentially cause data +loss. So far I have heard from only one user who uses such a workflow. + + An example: You visit some file in a buffer, edit it, and save the +changes. Then, outside of Emacs (or at least not using Magit or by +saving the buffer) you change the file on disk again. At this point the +buffer is the only place where the intermediate version still exists. +You have saved the changes to disk, but that has since been overwritten. +Meanwhile Emacs considers the buffer to be unmodified (because you have +not made any changes to it since you last saved it to the visited file) +and therefore would not object to it being automatically reverted. At +this point an Auto-Revert mode would kick in. It would check whether +the buffer is modified and since that is not the case it would revert +it. The intermediate version would be lost. (Actually you could still +get it back using the ‘undo’ command.) + + If your workflow depends on Emacs preserving the intermediate version +in the buffer, then you have to disable all Auto-Revert modes. But +please consider that such a workflow would be dangerous even without +using an Auto-Revert mode, and should therefore be avoided. If Emacs +crashes or if you quit Emacs by mistake, then you would also lose the +buffer content. There would be no autosave file still containing the +intermediate version (because that was deleted when you saved the +buffer) and you would not be asked whether you want to save the buffer +(because it isn’t modified). + + +File: magit.info, Node: Sections, Next: Transient Commands, Prev: Modes and Buffers, Up: Interface Concepts + +4.2 Sections +============ + +Magit buffers are organized into nested sections, which can be collapsed +and expanded, similar to how sections are handled in Org mode. Each +section also has a type, and some sections also have a value. For each +section type there can also be a local keymap, shared by all sections of +that type. + + Taking advantage of the section value and type, many commands operate +on the current section, or when the region is active and selects +sections of the same type, all of the selected sections. Commands that +only make sense for a particular section type (as opposed to just +behaving differently depending on the type) are usually bound in section +type keymaps. + +* Menu: + +* Section Movement:: +* Section Visibility:: +* Section Hooks:: +* Section Types and Values:: +* Section Options:: + + +File: magit.info, Node: Section Movement, Next: Section Visibility, Up: Sections + +4.2.1 Section Movement +---------------------- + +To move within a section use the usual keys (‘C-p’, ‘C-n’, ‘C-b’, ‘C-f’ +etc), whose global bindings are not shadowed. To move to another +section use the following commands. + +‘p’ (‘magit-section-backward’) + When not at the beginning of a section, then move to the beginning + of the current section. At the beginning of a section, instead + move to the beginning of the previous visible section. + +‘n’ (‘magit-section-forward’) + Move to the beginning of the next visible section. + +‘M-p’ (‘magit-section-backward-siblings’) + Move to the beginning of the previous sibling section. If there is + no previous sibling section, then move to the parent section + instead. + +‘M-n’ (‘magit-section-forward-siblings’) + Move to the beginning of the next sibling section. If there is no + next sibling section, then move to the parent section instead. + +‘^’ (‘magit-section-up’) + Move to the beginning of the parent of the current section. + + The above commands all call the hook ‘magit-section-movement-hook’. +Any of the functions listed below can be used as members of this hook. + + You might want to remove some of the functions that Magit adds using +‘add-hook’. In doing so you have to make sure you do not attempt to +remove function that haven’t even been added yet, for example: + + (with-eval-after-load 'magit-diff + (remove-hook 'magit-section-movement-hook + 'magit-hunk-set-window-start)) + + -- Variable: magit-section-movement-hook + This hook is run by all of the above movement commands, after + arriving at the destination. + + -- Function: magit-hunk-set-window-start + This hook function ensures that the beginning of the current + section is visible, provided it is a ‘hunk’ section. Otherwise, it + does nothing. + + Loading ‘magit-diff’ adds this function to the hook. + + -- Function: magit-section-set-window-start + This hook function ensures that the beginning of the current + section is visible, regardless of the section’s type. If you add + this to ‘magit-section-movement-hook’, then you must remove the + hunk-only variant in turn. + + -- Function: magit-log-maybe-show-more-commits + This hook function only has an effect in log buffers, and ‘point’ + is on the "show more" section. If that is the case, then it + doubles the number of commits that are being shown. + + Loading ‘magit-log’ adds this function to the hook. + + -- Function: magit-log-maybe-update-revision-buffer + When moving inside a log buffer, then this function updates the + revision buffer, provided it is already being displayed in another + window of the same frame. + + Loading ‘magit-log’ adds this function to the hook. + + -- Function: magit-log-maybe-update-blob-buffer + When moving inside a log buffer and another window of the same + frame displays a blob buffer, then this function instead displays + the blob buffer for the commit at point in that window. + + -- Function: magit-status-maybe-update-revision-buffer + When moving inside a status buffer, then this function updates the + revision buffer, provided it is already being displayed in another + window of the same frame. + + -- Function: magit-status-maybe-update-stash-buffer + When moving inside a status buffer, then this function updates the + stash buffer, provided it is already being displayed in another + window of the same frame. + + -- Function: magit-status-maybe-update-blob-buffer + When moving inside a status buffer and another window of the same + frame displays a blob buffer, then this function instead displays + the blob buffer for the commit at point in that window. + + -- Function: magit-stashes-maybe-update-stash-buffer + When moving inside a buffer listing stashes, then this function + updates the stash buffer, provided it is already being displayed in + another window of the same frame. + + -- User Option: magit-update-other-window-delay + Delay before automatically updating the other window. + + When moving around in certain buffers, then certain other buffers, + which are being displayed in another window, may optionally be + updated to display information about the section at point. + + When holding down a key to move by more than just one section, then + that would update that buffer for each section on the way. To + prevent that, updating the revision buffer is delayed, and this + option controls for how long. For optimal experience you might + have to adjust this delay and/or the keyboard repeat rate and delay + of your graphical environment or operating system. + + +File: magit.info, Node: Section Visibility, Next: Section Hooks, Prev: Section Movement, Up: Sections + +4.2.2 Section Visibility +------------------------ + +Magit provides many commands for changing the visibility of sections, +but all you need to get started are the next two. + +‘<TAB>’ (‘magit-section-toggle’) + Toggle the visibility of the body of the current section. + +‘C-c <TAB>’ (‘magit-section-cycle’) +‘C-<tab>’ (‘magit-section-cycle’) + Cycle the visibility of current section and its children. + + If this command is invoked using ‘C-<tab>’ and that is globally + bound to ‘tab-next’, then this command pivots to behave like that + command, and you must instead use ‘C-c TAB’ to cycle section + visibility. + + If you would like to keep using ‘C-<tab>’ to cycle section + visibility but also want to use ‘tab-bar-mode’, then you have to + prevent that mode from using this key and instead bind another key + to ‘tab-next’. Because ‘tab-bar-mode’ does not use a mode map but + instead manipulates the global map, this involves advising + ‘tab-bar--define-keys’. + +‘M-<tab>’ (‘magit-section-cycle-diffs’) + Cycle the visibility of diff-related sections in the current + buffer. + +‘S-<tab>’ (‘magit-section-cycle-global’) + Cycle the visibility of all sections in the current buffer. + +‘1’ (‘magit-section-show-level-1’) +‘2’ (‘magit-section-show-level-2’) +‘3’ (‘magit-section-show-level-3’) +‘4’ (‘magit-section-show-level-4’) + Show sections surrounding the current section up to level N. + +‘M-1’ (‘magit-section-show-level-1-all’) +‘M-2’ (‘magit-section-show-level-2-all’) +‘M-3’ (‘magit-section-show-level-3-all’) +‘M-4’ (‘magit-section-show-level-4-all’) + Show all sections up to level N. + + Some functions, which are used to implement the above commands, are +also exposed as commands themselves. By default no keys are bound to +these commands, as they are generally perceived to be much less useful. +But your mileage may vary. + + -- Command: magit-section-show + Show the body of the current section. + + -- Command: magit-section-hide + Hide the body of the current section. + + -- Command: magit-section-show-headings + Recursively show headings of children of the current section. Only + show the headings. Previously shown text-only bodies are hidden. + + -- Command: magit-section-show-children + Recursively show the bodies of children of the current section. + With a prefix argument show children down to the level of the + current section, and hide deeper children. + + -- Command: magit-section-hide-children + Recursively hide the bodies of children of the current section. + + -- Command: magit-section-toggle-children + Toggle visibility of bodies of children of the current section. + + When a buffer is first created then some sections are shown expanded +while others are not. This is hard coded. When a buffer is refreshed +then the previous visibility is preserved. The initial visibility of +certain sections can also be overwritten using the hook +‘magit-section-set-visibility-hook’. + + -- User Option: magit-section-initial-visibility-alist + This options can be used to override the initial visibility of + sections. In the future it will also be used to define the + defaults, but currently a section’s default is still hardcoded. + + The value is an alist. Each element maps a section type or lineage + to the initial visibility state for such sections. The state has + to be one of ‘show’ or ‘hide’, or a function that returns one of + these symbols. A function is called with the section as the only + argument. + + Use the command ‘magit-describe-section-briefly’ to determine a + section’s lineage or type. The vector in the output is the section + lineage and the type is the first element of that vector. + Wildcards can be used, see ‘magit-section-match’. + + -- User Option: magit-section-cache-visibility + This option controls for which sections the previous visibility + state should be restored if a section disappears and later appears + again. The value is a boolean or a list of section types. If t, + then the visibility of all sections is cached. Otherwise this is + only done for sections whose type matches one of the listed types. + + This requires that the function ‘magit-section-cached-visibility’ + is a member of ‘magit-section-set-visibility-hook’. + + -- Variable: magit-section-set-visibility-hook + This hook is run when first creating a buffer and also when + refreshing an existing buffer, and is used to determine the + visibility of the section currently being inserted. + + Each function is called with one argument, the section being + inserted. It should return ‘hide’ or ‘show’, or to leave the + visibility undefined ‘nil’. If no function decides on the + visibility and the buffer is being refreshed, then the visibility + is preserved; or if the buffer is being created, then the hard + coded default is used. + + Usually this should only be used to set the initial visibility but + not during refreshes. If ‘magit-insert-section--oldroot’ is + non-nil, then the buffer is being refreshed and these functions + should immediately return ‘nil’. + + -- User Option: magit-section-visibility-indicator + This option controls whether and how to indicate that a section can + be expanded/collapsed. + + If nil, then no visibility indicators are shown. Otherwise the + value has to have one of these two forms: + + • ‘(EXPANDABLE-BITMAP . COLLAPSIBLE-BITMAP)’ + + Both values have to be variables whose values are fringe + bitmaps. In this case every section that can be expanded or + collapsed gets an indicator in the left fringe. + + To provide extra padding around the indicator, set + ‘left-fringe-width’ in ‘magit-mode-hook’, e.g.: + + (add-hook 'magit-mode-hook (lambda () + (setq left-fringe-width 20))) + + • ‘(STRING . BOOLEAN)’ + + In this case STRING (usually an ellipsis) is shown at the end + of the heading of every collapsed section. Expanded sections + get no indicator. The cdr controls whether the appearance of + these ellipsis take section highlighting into account. Doing + so might potentially have an impact on performance, while not + doing so is kinda ugly. + + +File: magit.info, Node: Section Hooks, Next: Section Types and Values, Prev: Section Visibility, Up: Sections + +4.2.3 Section Hooks +------------------- + +Which sections are inserted into certain buffers is controlled with +hooks. This includes the status and the refs buffers. For other +buffers, e.g., log and diff buffers, this is not possible. The command +‘magit-describe-section’ can be used to see which hook (if any) was +responsible for inserting the section at point. + + For buffers whose sections can be customized by the user, a hook +variable called ‘magit-TYPE-sections-hook’ exists. This hook should be +changed using ‘magit-add-section-hook’. Avoid using ‘add-hooks’ or the +Custom interface. + + The various available section hook variables are described later in +this manual along with the appropriate "section inserter functions". + + -- Function: magit-add-section-hook hook function &optional at append + local + Add the function FUNCTION to the value of section hook HOOK. + + Add FUNCTION at the beginning of the hook list unless optional + APPEND is non-nil, in which case FUNCTION is added at the end. If + FUNCTION already is a member then move it to the new location. + + If optional AT is non-nil and a member of the hook list, then add + FUNCTION next to that instead. Add before or after AT, or replace + AT with FUNCTION depending on APPEND. If APPEND is the symbol + ‘replace’, then replace AT with FUNCTION. For any other non-nil + value place FUNCTION right after AT. If nil, then place FUNCTION + right before AT. If FUNCTION already is a member of the list but + AT is not, then leave FUNCTION where ever it already is. + + If optional LOCAL is non-nil, then modify the hook’s buffer-local + value rather than its global value. This makes the hook local by + copying the default value. That copy is then modified. + + HOOK should be a symbol. If HOOK is void, it is first set to nil. + HOOK’s value must not be a single hook function. FUNCTION should + be a function that takes no arguments and inserts one or multiple + sections at point, moving point forward. FUNCTION may choose not + to insert its section(s), when doing so would not make sense. It + should not be abused for other side-effects. + + To remove a function from a section hook, use ‘remove-hook’. + + +File: magit.info, Node: Section Types and Values, Next: Section Options, Prev: Section Hooks, Up: Sections + +4.2.4 Section Types and Values +------------------------------ + +Each section has a type, for example ‘hunk’, ‘file’, and ‘commit’. +Instances of certain section types also have a value. The value of a +section of type ‘file’, for example, is a file name. + + Users usually do not have to worry about a section’s type and value, +but knowing them can be handy at times. + +‘H’ (‘magit-describe-section’) + This command shows information about the section at point in a + separate buffer. + + -- Command: magit-describe-section-briefly + This command shows information about the section at point in the + echo area, as ‘#<magit-section VALUE [TYPE PARENT-TYPE...] + BEGINNING-END>’. + + Many commands behave differently depending on the type of the section +at point and/or somehow consume the value of that section. But that is +only one of the reasons why the same key may do something different, +depending on what section is current. + + Additionally for each section type a keymap *might* be defined, named +‘magit-TYPE-section-map’. That keymap is used as text property keymap +of all text belonging to any section of the respective type. If such a +map does not exist for a certain type, then you can define it yourself, +and it will automatically be used. + + +File: magit.info, Node: Section Options, Prev: Section Types and Values, Up: Sections + +4.2.5 Section Options +--------------------- + +This section describes options that have an effect on more than just a +certain type of sections. As you can see there are not many of those. + + -- User Option: magit-section-show-child-count + Whether to append the number of children to section headings. This + only affects sections that could benefit from this information. + + +File: magit.info, Node: Transient Commands, Next: Transient Arguments and Buffer Variables, Prev: Sections, Up: Interface Concepts + +4.3 Transient Commands +====================== + +Many Magit commands are implemented as *transient* commands. First the +user invokes a *prefix* command, which causes its *infix* arguments and +*suffix* commands to be displayed in the echo area. The user then +optionally sets some infix arguments and finally invokes one of the +suffix commands. + + This is implemented in the library ‘transient’. Earlier Magit +releases used the package ‘magit-popup’ and even earlier versions +library ‘magit-key-mode’. + + Transient is documented in *note (transient)Top::. + +‘C-x M-g’ (‘magit-dispatch’) +‘C-c g’ (‘magit-dispatch’) + This transient prefix command binds most of Magit’s other prefix + commands as suffix commands and displays them in a temporary buffer + until one of them is invoked. Invoking such a sub-prefix causes + the suffixes of that command to be bound and displayed instead of + those of ‘magit-dispatch’. + + This command is also, or especially, useful outside Magit buffers, + so Magit by default binds it to ‘C-c M-g’ in the global keymap. + ‘C-c g’ would be a better binding, but we cannot use that by + default, because that key sequence is reserved for the user. See + *note Global Bindings:: to learn more default and recommended key + bindings. + + +File: magit.info, Node: Transient Arguments and Buffer Variables, Next: Completion Confirmation and the Selection, Prev: Transient Commands, Up: Interface Concepts + +4.4 Transient Arguments and Buffer Variables +============================================ + +The infix arguments of many of Magit’s transient prefix commands cease +to have an effect once the ‘git’ command that is called with those +arguments has returned. Commands that create a commit are a good +example for this. If the user changes the arguments, then that only +affects the next invocation of a suffix command. If the same transient +prefix command is later invoked again, then the arguments are initially +reset to the default value. This default value can be set for the +current Emacs session or saved permanently, see *note (transient)Saving +Values::. It is also possible to cycle through previously used sets of +arguments using ‘C-M-p’ and ‘C-M-n’, see *note (transient)Using +History::. + + However the infix arguments of many other transient commands continue +to have an effect even after the ‘git’ command that was called with +those arguments has returned. The most important commands like this are +those that display a diff or log in a dedicated buffer. Their arguments +obviously continue to have an effect for as long as the respective diff +or log is being displayed. Furthermore the used arguments are stored in +buffer-local variables for future reference. + + For commands in the second group it isn’t always desirable to reset +their arguments to the global value when the transient prefix command is +invoked again. + + As mentioned above, it is possible to cycle through previously used +sets of arguments while a transient popup is visible. That means that +we could always reset the infix arguments to the default because the set +of arguments that is active in the existing buffer is only a few ‘C-M-p’ +away. Magit can be configured to behave like that, but because I expect +that most users would not find that very convenient, it is not the +default. + + Also note that it is possible to change the diff and log arguments +used in the current buffer (including the status buffer, which contains +both diff and log sections) using the respective "refresh" transient +prefix commands on ‘D’ and ‘L’. (‘d’ and ‘l’ on the other hand are +intended to change *what* diff or log is being displayed. It is +possible to also change *how* the diff or log is being displayed at the +same time, but if you only want to do the latter, then you should use +the refresh variants.) Because these secondary diff and log transient +prefixes are about *changing* the arguments used in the current buffer, +they *always* start out with the set of arguments that are currently in +effect in that buffer. + + Some commands are usually invoked directly even though they can also +be invoked as the suffix of a transient prefix command. Most +prominently ‘magit-show-commit’ is usually invoked by typing ‘RET’ while +point is on a commit in a log, but it can also be invoked from the +‘magit-diff’ transient prefix. + + When such a command is invoked directly, then it is important to +reuse the arguments as specified by the respective buffer-local values, +instead of using the default arguments. Imagine you press ‘RET’ in a +log to display the commit at point in a different buffer and then use +‘D’ to change how the diff is displayed in that buffer. And then you +press ‘RET’ on another commit to show that instead and the diff +arguments are reset to the default. Not cool; so Magit does not do that +by default. + + -- User Option: magit-prefix-use-buffer-arguments + This option controls whether the infix arguments initially shown in + certain transient prefix commands are based on the arguments that + are currently in effect in the buffer that their suffixes update. + + The ‘magit-diff’ and ‘magit-log’ transient prefix commands are + affected by this option. + + -- User Option: magit-direct-use-buffer-arguments + This option controls whether certain commands, when invoked + directly (i.e., not as the suffix of a transient prefix command), + use the arguments that are currently active in the buffer that they + are about to update. The alternative is to use the default value + for these arguments, which might change the arguments that are used + in the buffer. + +Valid values for both of the above options are: + + • ‘always’: Always use the set of arguments that is currently active + in the respective buffer, provided that buffer exists of course. + • ‘selected’ or ‘t’: Use the set of arguments from the respective + buffer, but only if it is displayed in a window of the current + frame. This is the default for both variables. + • ‘current’: Use the set of arguments from the respective buffer, but + only if it is the current buffer. + • ‘never’: Never use the set of arguments from the respective buffer. + +I am afraid it gets more complicated still: + + • The global diff and log arguments are set for each supported mode + individually. The diff arguments for example have different values + in ‘magit-diff-mode’, ‘magit-revision-mode’, + ‘magit-merge-preview-mode’ and ‘magit-status-mode’ buffers. + Setting or saving the value for one mode does not change the value + for other modes. The history however is shared. + + • When ‘magit-show-commit’ is invoked directly from a log buffer, + then the file filter is picked up from that buffer, not from the + revision buffer or the mode’s global diff arguments. + + • Even though they are suffixes of the diff prefix + ‘magit-show-commit’ and ‘magit-stash-show’ do not use the diff + buffer used by the diff commands, instead they use the dedicated + revision and stash buffers. + + At the time you invoke the diff prefix it is unknown to Magit which + of the suffix commands you are going to invoke. While not certain, + more often than not users invoke one of the commands that use the + diff buffer, so the initial infix arguments are those used in that + buffer. However if you invoke one of these commands directly, then + Magit knows that it should use the arguments from the revision + resp. stash buffer. + + • The log prefix also features reflog commands, but these commands do + not use the log arguments. + + • If ‘magit-show-refs’ is invoked from a ‘magit-refs-mode’ buffer, + then it acts as a refresh prefix and therefore unconditionally uses + the buffer’s arguments as initial arguments. If it is invoked + elsewhere with a prefix argument, then it acts as regular prefix + and therefore respects ‘magit-prefix-use-buffer-arguments’. If it + is invoked elsewhere without a prefix argument, then it acts as a + direct command and therefore respects + ‘magit-direct-use-buffer-arguments’. + + +File: magit.info, Node: Completion Confirmation and the Selection, Next: Mouse Support, Prev: Transient Arguments and Buffer Variables, Up: Interface Concepts + +4.5 Completion, Confirmation and the Selection +============================================== + +* Menu: + +* Action Confirmation:: +* Completion and Confirmation:: +* The Selection:: +* The hunk-internal region:: +* Support for Completion Frameworks:: +* Additional Completion Options:: + + +File: magit.info, Node: Action Confirmation, Next: Completion and Confirmation, Up: Completion Confirmation and the Selection + +4.5.1 Action Confirmation +------------------------- + +By default many actions that could potentially lead to data loss have to +be confirmed. This includes many very common actions, so this can +quickly become annoying. Many of these actions can be undone and if you +have thought about how to undo certain mistakes, then it should be safe +to disable confirmation for the respective actions. + + The option ‘magit-no-confirm’ can be used to tell Magit to perform +certain actions without the user having to confirm them. Note that +while this option can only be used to disable confirmation for a +specific set of actions, the next section explains another way of +telling Magit to ask fewer questions. + + -- User Option: magit-no-confirm + The value of this option is a list of symbols, representing actions + that do not have to be confirmed by the user before being carried + out. + + By default many potentially dangerous commands ask the user for + confirmation. Each of the below symbols stands for an action + which, when invoked unintentionally or without being fully aware of + the consequences, could lead to tears. In many cases there are + several commands that perform variations of a certain action, so we + don’t use the command names but more generic symbols. + + • Applying changes: + + • ‘discard’ Discarding one or more changes (i.e., hunks or + the complete diff for a file) loses that change, + obviously. + + • ‘reverse’ Reverting one or more changes can usually be + undone by reverting the reversion. + + • ‘stage-all-changes’, ‘unstage-all-changes’ When there are + both staged and unstaged changes, then un-/staging + everything would destroy that distinction. Of course + that also applies when un-/staging a single change, but + then less is lost and one does that so often that having + to confirm every time would be unacceptable. + + • Files: + + • ‘delete’ When a file that isn’t yet tracked by Git is + deleted, then it is completely lost, not just the last + changes. Very dangerous. + + • ‘trash’ Instead of deleting a file it can also be move to + the system trash. Obviously much less dangerous than + deleting it. + + Also see option ‘magit-delete-by-moving-to-trash’. + + • ‘resurrect’ A deleted file can easily be resurrected by + "deleting" the deletion, which is done using the same + command that was used to delete the same file in the + first place. + + • ‘untrack’ Untracking a file can be undone by tracking it + again. + + • ‘rename’ Renaming a file can easily be undone. + + • Sequences: + + • ‘reset-bisect’ Aborting (known to Git as "resetting") a + bisect operation loses all information collected so far. + + • ‘abort-cherry-pick’ Aborting a cherry-pick throws away + all conflict resolutions which have already been carried + out by the user. + + • ‘abort-revert’ Aborting a revert throws away all conflict + resolutions which have already been carried out by the + user. + + • ‘abort-rebase’ Aborting a rebase throws away all already + modified commits, but it’s possible to restore those from + the reflog. + + • ‘abort-merge’ Aborting a merge throws away all conflict + resolutions which have already been carried out by the + user. + + • ‘merge-dirty’ Merging with a dirty worktree can make it + hard to go back to the state before the merge was + initiated. + + • References: + + • ‘delete-unmerged-branch’ Once a branch has been deleted, + it can only be restored using low-level recovery tools + provided by Git. And even then the reflog is gone. The + user always has to confirm the deletion of a branch by + accepting the default choice (or selecting another + branch), but when a branch has not been merged yet, also + make sure the user is aware of that. + + • ‘delete-pr-remote’ When deleting a branch that was + created from a pull-request and if no other branches + still exist on that remote, then ‘magit-branch-delete’ + offers to delete the remote as well. This should be safe + because it only happens if no other refs exist in the + remotes namespace, and you can recreate the remote if + necessary. + + • ‘drop-stashes’ Dropping a stash is dangerous because Git + stores stashes in the reflog. Once a stash is removed, + there is no going back without using low-level recovery + tools provided by Git. When a single stash is dropped, + then the user always has to confirm by accepting the + default (or selecting another). This action only + concerns the deletion of multiple stashes at once. + + • Publishing: + + • ‘set-and-push’ When pushing to the upstream or the + push-remote and that isn’t actually configured yet, then + the user can first set the target. If s/he confirms the + default too quickly, then s/he might end up pushing to + the wrong branch and if the remote repository is + configured to disallow fixing such mistakes, then that + can be quite embarrassing and annoying. + + • Edit published history: + + Without adding these symbols here, you will be warned before + editing commits that have already been pushed to one of the + branches listed in ‘magit-published-branches’. + + • ‘amend-published’ Affects most commands that amend to + "HEAD". + + • ‘rebase-published’ Affects commands that perform + interactive rebases. This includes commands from the + commit transient that modify a commit other than "HEAD", + namely the various fixup and squash variants. + + • ‘edit-published’ Affects the commands + ‘magit-edit-line-commit’ and + ‘magit-diff-edit-hunk-commit’. These two commands make + it quite easy to accidentally edit a published commit, so + you should think twice before configuring them not to ask + for confirmation. + + To disable confirmation completely, add all three symbols here + or set ‘magit-published-branches’ to ‘nil’. + + • Various: + + • ‘stash-apply-3way’ When a stash cannot be applied using + ‘git stash apply’, then Magit uses ‘git apply’ instead, + possibly using the ‘--3way’ argument, which isn’t always + perfectly safe. See also ‘magit-stash-apply’. + + • ‘kill-process’ There seldom is a reason to kill a + process. + + • Global settings: + + Instead of adding all of the above symbols to the value of + this option, you can also set it to the atom ‘t’, which has + the same effect as adding all of the above symbols. Doing + that most certainly is a bad idea, especially because other + symbols might be added in the future. So even if you don’t + want to be asked for confirmation for any of these actions, + you are still better of adding all of the respective symbols + individually. + + When ‘magit-wip-before-change-mode’ is enabled, then the + following actions can be undone fairly easily: ‘discard’, + ‘reverse’, ‘stage-all-changes’, and ‘unstage-all-changes’. If + and only if this mode is enabled, then ‘safe-with-wip’ has the + same effect as adding all of these symbols individually. + + +File: magit.info, Node: Completion and Confirmation, Next: The Selection, Prev: Action Confirmation, Up: Completion Confirmation and the Selection + +4.5.2 Completion and Confirmation +--------------------------------- + +Many Magit commands ask the user to select from a list of possible +things to act on, while offering the most likely choice as the default. +For many of these commands the default is the thing at point, provided +that it actually is a valid thing to act on. For many commands that act +on a branch, the current branch serves as the default if there is no +branch at point. + + These commands combine asking for confirmation and asking for a +target to act on into a single action. The user can confirm the default +target using ‘RET’ or abort using ‘C-g’. This is similar to a +‘y-or-n-p’ prompt, but the keys to confirm or abort differ. + + At the same time the user is also given the opportunity to select +another target, which is useful because for some commands and/or in some +situations you might want to select the action before selecting the +target by moving to it. + + However you might find that for some commands you always want to use +the default target, if any, or even that you want the command to act on +the default without requiring any confirmation at all. The option +‘magit-dwim-selection’ can be used to configure certain commands to that +effect. + + Note that when the region is active then many commands act on the +things that are selected using a mechanism based on the region, in many +cases after asking for confirmation. This region-based mechanism is +called the "selection" and is described in detail in the next section. +When a selection exists that is valid for the invoked command, then that +command never offers to act on something else, and whether it asks for +confirmation is not controlled by this option. + + Also note that Magit asks for confirmation of certain actions that +are not coupled with completion (or the selection). Such dialogs are +also not affected by this option and are described in the previous +section. + + -- User Option: magit-dwim-selection + This option can be used to tell certain commands to use the thing at +point instead of asking the user to select a candidate to act on, with +or without confirmation. + + The value has the form ‘((COMMAND nil|PROMPT DEFAULT)...)’. + + • COMMAND is the command that should not prompt for a choice. To + have an effect, the command has to use the function + ‘magit-completing-read’ or a utility function which in turn uses + that function. + + • If the command uses ‘magit-completing-read’ multiple times, then + PROMPT can be used to only affect one of these uses. PROMPT, if + non-nil, is a regular expression that is used to match against the + PROMPT argument passed to ‘magit-completing-read’. + + • DEFAULT specifies how to use the default. If it is ‘t’, then the + DEFAULT argument passed to ‘magit-completing-read’ is used without + confirmation. If it is ‘ask’, then the user is given a chance to + abort. DEFAULT can also be ‘nil’, in which case the entry has no + effect. + + +File: magit.info, Node: The Selection, Next: The hunk-internal region, Prev: Completion and Confirmation, Up: Completion Confirmation and the Selection + +4.5.3 The Selection +------------------- + +If the region is active, then many Magit commands act on the things that +are selected using a mechanism based on the region instead of one single +thing. When the region is not active, then these commands act on the +thing at point or read a single thing to act on. This is described in +the previous section — this section only covers how multiple things are +selected, how that is visualized, and how certain commands behave when +that is the case. + + Magit’s mechanism for selecting multiple things, or rather sections +that represent these things, is based on the Emacs region, but the area +that Magit considers to be selected is typically larger than the region +and additional restrictions apply. + + Magit makes a distinction between a region that qualifies as forming +a valid Magit selection and a region that does not. If the region does +not qualify, then it is displayed as it is in other Emacs buffers. If +the region does qualify as a Magit selection, then the selection is +always visualized, while the region itself is only visualized if it +begins and ends on the same line. + + For a region to qualify as a Magit selection, it must begin in the +heading of one section and end in the heading of a sibling section. +Note that if the end of the region is at the very beginning of section +heading (i.e., at the very beginning of a line) then that section is +considered to be *inside* the selection. + + This is not consistent with how the region is normally treated in +Emacs — if the region ends at the beginning of a line, then that line is +outside the region. Due to how Magit visualizes the selection, it +should be obvious that this difference exists. + + Not every command acts on every valid selection. Some commands do +not even consider the location of point, others may act on the section +at point but not support acting on the selection, and even commands that +do support the selection of course only do so if it selects things that +they can act on. + + This is the main reason why the selection must include the section at +point. Even if a selection exists, the invoked command may disregard +it, in which case it may act on the current section only. It is much +safer to only act on the current section but not the other selected +sections than it is to act on the current section *instead* of the +selected sections. The latter would be much more surprising and if the +current section always is part of the selection, then that cannot +happen. + + -- Variable: magit-keep-region-overlay + This variable controls whether the region is visualized as usual + even when a valid Magit selection or a hunk-internal region exists. + See the doc-string for more information. + + +File: magit.info, Node: The hunk-internal region, Next: Support for Completion Frameworks, Prev: The Selection, Up: Completion Confirmation and the Selection + +4.5.4 The hunk-internal region +------------------------------ + +Somewhat related to the Magit selection described in the previous +section is the hunk-internal region. + + Like the selection, the hunk-internal region is based on the Emacs +region but causes that region to not be visualized as it would in other +Emacs buffers, and includes the line on which the region ends even if it +ends at the very beginning of that line. + + Unlike the selection, which is based on a region that must begin in +the heading of one section and ends in the section of a sibling section, +the hunk-internal region must begin inside the *body* of a hunk section +and end in the body of the *same* section. + + The hunk-internal region is honored by "apply" commands, which can, +among other targets, act on a hunk. If the hunk-internal region is +active, then such commands act only on the marked part of the hunk +instead of on the complete hunk. + + +File: magit.info, Node: Support for Completion Frameworks, Next: Additional Completion Options, Prev: The hunk-internal region, Up: Completion Confirmation and the Selection + +4.5.5 Support for Completion Frameworks +--------------------------------------- + +The built-in option ‘completing-read-function’ specifies the low-level +function used by ‘completing-read’ to ask a user to select from a list +of choices. Its default value is ‘completing-read-default’. +Alternative completion frameworks typically activate themselves by +substituting their own implementation. + + Mostly for historic reasons Magit provides a similar option named +‘magit-completing-read-function’, which only controls the low-level +function used by ‘magit-completing-read’. This option also makes it +possible to use a different completing mechanism for Magit than for the +rest of Emacs, but doing that is not recommend. + + You most likely don’t have to customize the magit-specific option to +use an alternative completion framework. For example, if you enable +‘ivy-mode’, then Magit will respect that, and if you enable ‘helm-mode’, +then you are done too. + + However if you want to use Ido, then ‘ido-mode’ won’t do the trick. +You will also have to install the ‘ido-completing-read+’ package and use +‘magit-ido-completing-read’ as ‘magit-completing-read-function’. + + -- User Option: magit-completing-read-function + The value of this variable is the low-level function used to + perform completion by code that uses ‘magit-completing-read’ (as + opposed to the built-in ‘completing-read’). + + The default value, ‘magit-builtin-completing-read’, is suitable for + the standard completion mechanism, ‘ivy-mode’, and ‘helm-mode’ at + least. + + The built-in ‘completing-read’ and ‘completing-read-default’ are + *not* suitable to be used here. ‘magit-builtin-completing-read’ + performs some additional work, and any function used in its place + has to do the same. + + -- Function: magit-builtin-completing-read prompt choices &optional + predicate require-match initial-input hist def + This function performs completion using the built-in + ‘completing-read’ and does some additional magit-specific work. + + -- Function: magit-ido-completing-read prompt choices &optional + predicate require-match initial-input hist def + This function performs completion using ‘ido-completing-read+’ from + the package by the same name (which you have to explicitly install) + and does some additional magit-specific work. + + We have to use ‘ido-completing-read+’ instead of the + ‘ido-completing-read’ that comes with Ido itself, because the + latter, while intended as a drop-in replacement, cannot serve that + purpose because it violates too many of the implicit conventions. + + -- Function: magit-completing-read prompt choices &optional predicate + require-match initial-input hist def fallback + This is the function that Magit commands use when they need the + user to select a single thing to act on. The arguments have the + same meaning as for ‘completing-read’, except for FALLBACK, which + is unique to this function and is described below. + + Instead of asking the user to choose from a list of possible + candidates, this function may just return the default specified by + DEF, with or without requiring user confirmation. Whether that is + the case depends on PROMPT, ‘this-command’ and + ‘magit-dwim-selection’. See the documentation of the latter for + more information. + + If it does read a value in the minibuffer, then this function acts + similar to ‘completing-read’, except for the following: + + • COLLECTION must be a list of choices. A function is not + supported. + + • If REQUIRE-MATCH is ‘nil’ and the user exits without a choice, + then ‘nil’ is returned instead of an empty string. + + • If REQUIRE-MATCH is non-nil and the users exits without a + choice, an user-error is raised. + + • FALLBACK specifies a secondary default that is only used if + the primary default DEF is ‘nil’. The secondary default is + not subject to ‘magit-dwim-selection’ — if DEF is ‘nil’ but + FALLBACK is not, then this function always asks the user to + choose a candidate, just as if both defaults were ‘nil’. + + • ‘format-prompt’ is called on PROMPT and DEF (or FALLBACK if + DEF is ‘nil’). This appends ": " to the prompt and may also + add the default to the prompt, using the format specified by + ‘minibuffer-default-prompt-format’ and depending on + ‘magit-completing-read-default-prompt-predicate’. + + +File: magit.info, Node: Additional Completion Options, Prev: Support for Completion Frameworks, Up: Completion Confirmation and the Selection + +4.5.6 Additional Completion Options +----------------------------------- + + -- User Option: magit-list-refs-sortby + For many commands that read a ref or refs from the user, the value + of this option can be used to control the order of the refs. Valid + values include any key accepted by the ‘--sort’ flag of ‘git + for-each-ref’. By default, refs are sorted alphabetically by their + full name (e.g., "refs/heads/master"). + + +File: magit.info, Node: Mouse Support, Next: Running Git, Prev: Completion Confirmation and the Selection, Up: Interface Concepts + +4.6 Mouse Support +================= + +Double clicking on a section heading toggles the visibility of its body, +if any. Likewise clicking in the left fringe toggles the visibility of +the appropriate section. + + A context menu is provided but has to be enabled explicitly. In +Emacs 28 and greater, enable the global mode ‘context-menu-mode’. If +you use an older Emacs release, set +‘magit-section-show-context-menu-for-emacs<28’. + + +File: magit.info, Node: Running Git, Prev: Mouse Support, Up: Interface Concepts + +4.7 Running Git +=============== + +* Menu: + +* Viewing Git Output:: +* Git Process Status:: +* Running Git Manually:: +* Git Executable:: +* Global Git Arguments:: + + +File: magit.info, Node: Viewing Git Output, Next: Git Process Status, Up: Running Git + +4.7.1 Viewing Git Output +------------------------ + +Magit runs Git either for side-effects (e.g., when pushing) or to get +some value (e.g., the name of the current branch). + + When Git is run for side-effects, the process output is logged in a +per-repository log buffer, which can be consulted using the +‘magit-process’ command when things don’t go as expected. + + The output/errors for up to ‘magit-process-log-max’ Git commands are +retained. + +‘$’ (‘magit-process’) + This commands displays the process buffer for the current + repository. + + Inside that buffer, the usual key bindings for navigating and showing +sections are available. There is one additional command. + +‘k’ (‘magit-process-kill’) + This command kills the process represented by the section at point. + + -- Variable: magit-git-debug + This option controls whether additional reporting of git errors is + enabled. + + Magit basically calls git for one of these two reasons: for + side-effects or to do something with its standard output. + + When git is run for side-effects then its output, including error + messages, go into the process buffer which is shown when using ‘$’. + + When git’s output is consumed in some way, then it would be too + expensive to also insert it into this buffer, but when this option + is non-nil and git returns with a non-zero exit status, then at + least its standard error is inserted into this buffer. + + This is only intended for debugging purposes. Do not enable this + permanently, that would negatively affect performance. + + This is only intended for debugging purposes. Do not enable this + permanently, that would negatively affect performance. Also note + that just because git exits with a non-zero exit status and prints + an error message that usually doesn’t mean that it is an error as + far as Magit is concerned, which is another reason we usually hide + these error messages. Whether some error message is relevant in + the context of some unexpected behavior has to be judged on a case + by case basis. + + The command ‘magit-toggle-git-debug’ changes the value of this + variable. + + -- Variable: magit-process-extreme-logging + This option controls whether ‘magit-process-file’ logs to the + ‘*Messages*’ buffer. + + Only intended for temporary use when you try to figure out how + Magit uses Git behind the scene. Output that normally goes to the + magit-process buffer continues to go there. Not all output goes to + either of these two buffers. + + +File: magit.info, Node: Git Process Status, Next: Running Git Manually, Prev: Viewing Git Output, Up: Running Git + +4.7.2 Git Process Status +------------------------ + +When a Git process is running for side-effects, Magit displays an +indicator in the mode line, using the ‘magit-mode-line-process’ face. + + If the Git process exits successfully, the process indicator is +removed from the mode line immediately. + + In the case of a Git error, the process indicator is not removed, but +is instead highlighted with the ‘magit-mode-line-process-error’ face, +and the error details from the process buffer are provided as a tooltip +for mouse users. This error indicator persists in the mode line until +the next magit buffer refresh. + + If you do not wish process errors to be indicated in the mode line, +customize the ‘magit-process-display-mode-line-error’ user option. + + Process errors are additionally indicated at the top of the status +buffer. + + +File: magit.info, Node: Running Git Manually, Next: Git Executable, Prev: Git Process Status, Up: Running Git + +4.7.3 Running Git Manually +-------------------------- + +While Magit provides many Emacs commands to interact with Git, it does +not cover everything. In those cases your existing Git knowledge will +come in handy. Magit provides some commands for running arbitrary Git +commands by typing them into the minibuffer, instead of having to switch +to a shell. + +‘!’ (‘magit-run’) + This transient prefix command binds the following suffix commands + and displays them in a temporary buffer until a suffix is invoked. + +‘! !’ (‘magit-git-command-topdir’) + This command reads a command from the user and executes it in the + top-level directory of the current working tree. + + The string "git " is used as initial input when prompting the user + for the command. It can be removed to run another command. + +‘:’ (‘magit-git-command’) +‘! p’ + This command reads a command from the user and executes it in + ‘default-directory’. With a prefix argument the command is + executed in the top-level directory of the current working tree + instead. + + The string "git " is used as initial input when prompting the user + for the command. It can be removed to run another command. + +‘! s’ (‘magit-shell-command-topdir’) + This command reads a command from the user and executes it in the + top-level directory of the current working tree. + +‘! S’ (‘magit-shell-command’) + This command reads a command from the user and executes it in + ‘default-directory’. With a prefix argument the command is + executed in the top-level directory of the current working tree + instead. + + -- User Option: magit-shell-command-verbose-prompt + Whether the prompt, used by the above commands when reading a shell + command, shows the directory in which it will be run. + + These suffix commands start external gui tools. + +‘! k’ (‘magit-run-gitk’) + This command runs ‘gitk’ in the current repository. + +‘! a’ (‘magit-run-gitk-all’) + This command runs ‘gitk --all’ in the current repository. + +‘! b’ (‘magit-run-gitk-branches’) + This command runs ‘gitk --branches’ in the current repository. + +‘! g’ (‘magit-run-git-gui’) + This command runs ‘git gui’ in the current repository. + +‘! m’ (‘magit-git-mergetool’) + This command runs ‘git mergetool --gui’ in the current repository. + + With a prefix argument this acts as a transient prefix command, + allowing the user to select the mergetool and change some settings. + + +File: magit.info, Node: Git Executable, Next: Global Git Arguments, Prev: Running Git Manually, Up: Running Git + +4.7.4 Git Executable +-------------------- + +When Magit calls Git, then it may do so using the absolute path to the +‘git’ executable, or using just its name. + + When running ‘git’ locally and the ‘system-type’ is ‘windows-nt’ (any +Windows version) or ‘darwin’ (macOS) then ‘magit-git-executable’ is set +to an absolute path when Magit is loaded. + + On Windows it is necessary to use an absolute path because Git comes +with several wrapper scripts for the actual ‘git’ binary, which are also +placed on ‘$PATH’, and using one of these wrappers instead of the binary +would degrade performance horribly. For some macOS users using just the +name of the executable also performs horribly, so we avoid doing that on +that platform as well. On other platforms, using just the name seems to +work just fine. + + Using an absolute path when running ‘git’ on a remote machine over +Tramp, would be problematic to use an absolute path that is suitable on +the local machine, so a separate option is used to control the name or +path that is used on remote machines. + + -- User Option: magit-git-executable + The ‘git’ executable used by Magit on the local host. This should + be either the absolute path to the executable, or the string "git" + to let Emacs find the executable itself, using the standard + mechanism for doing such things. + + -- User Option: magit-remote-git-executable + The ‘git’ executable used by Magit on remote machines over Tramp. + Normally this should be just the string "git". Consider + customizing ‘tramp-remote-path’ instead of this option. + + If Emacs is unable to find the correct executable, then you can work +around that by explicitly setting the value of one of these two options. +Doing that should be considered a kludge; it is better to make sure that +the order in ‘exec-path’ or ‘tramp-remote-path’ is correct. + + Note that ‘exec-path’ is set based on the value of the ‘PATH’ +environment variable that is in effect when Emacs is started. If you +set ‘PATH’ in your shell’s init files, then that only has an effect on +Emacs if you start it from that shell (because the environment of a +process is only passed to its child processes, not to arbitrary other +processes). If that is not how you start Emacs, then the +‘exec-path-from-shell’ package can help; though honestly I consider that +a kludge too. + + The command ‘magit-debug-git-executable’ can be useful to find out +where Emacs is searching for ‘git’. + +‘M-x magit-debug-git-executable’ + This command displays a buffer with information about + ‘magit-git-executable’ and ‘magit-remote-git-executable’. + +‘M-x magit-version’ + This command shows the currently used versions of Magit, Git, and + Emacs in the echo area. Non-interactively this just returns the + Magit version. + + +File: magit.info, Node: Global Git Arguments, Prev: Git Executable, Up: Running Git + +4.7.5 Global Git Arguments +-------------------------- + + -- User Option: magit-git-global-arguments + The arguments set here are used every time the git executable is + run as a subprocess. They are placed right after the executable + itself and before the git command - as in ‘git HERE... COMMAND + REST’. For valid arguments see *note (gitman)git::. + + Be careful what you add here, especially if you are using Tramp to + connect to servers with ancient Git versions. Never remove + anything that is part of the default value, unless you really know + what you are doing. And think very hard before adding something; + it will be used every time Magit runs Git for any purpose. + + +File: magit.info, Node: Inspecting, Next: Manipulating, Prev: Interface Concepts, Up: Top + +5 Inspecting +************ + +The functionality provided by Magit can be roughly divided into three +groups: inspecting existing data, manipulating existing data or adding +new data, and transferring data. Of course that is a rather crude +distinction that often falls short, but it’s more useful than no +distinction at all. This section is concerned with inspecting data, the +next two with manipulating and transferring it. Then follows a section +about miscellaneous functionality, which cannot easily be fit into this +distinction. + + Of course other distinctions make sense too, e.g., Git’s distinction +between porcelain and plumbing commands, which for the most part is +equivalent to Emacs’ distinction between interactive commands and +non-interactive functions. All of the sections mentioned before are +mainly concerned with the porcelain – Magit’s plumbing layer is +described later. + +* Menu: + +* Status Buffer:: +* Repository List:: +* Logging:: +* Diffing:: +* Ediffing:: +* References Buffer:: +* Bisecting:: +* Visiting Files and Blobs:: +* Blaming:: + + +File: magit.info, Node: Status Buffer, Next: Repository List, Up: Inspecting + +5.1 Status Buffer +================= + +While other Magit buffers contain, e.g., one particular diff or one +particular log, the status buffer contains the diffs for staged and +unstaged changes, logs for unpushed and unpulled commits, lists of +stashes and untracked files, and information related to the current +branch. + + During certain incomplete operations – for example when a merge +resulted in a conflict – additional information is displayed that helps +proceeding with or aborting the operation. + + The command ‘magit-status’ displays the status buffer belonging to +the current repository in another window. This command is used so often +that it should be bound globally. We recommend using ‘C-x g’: + + (global-set-key (kbd "C-x g") 'magit-status) + +‘C-x g’ (‘magit-status’) + When invoked from within an existing Git repository, then this + command shows the status of that repository in a buffer. + + If the current directory isn’t located within a Git repository, + then this command prompts for an existing repository or an + arbitrary directory, depending on the option + ‘magit-repository-directories’, and the status for the selected + repository is shown instead. + + • If that option specifies any existing repositories, then the + user is asked to select one of them. + + • Otherwise the user is asked to select an arbitrary directory + using regular file-name completion. If the selected directory + is the top-level directory of an existing working tree, then + the status buffer for that is shown. + + • Otherwise the user is offered to initialize the selected + directory as a new repository. After creating the repository + its status buffer is shown. + + These fallback behaviors can also be forced using one or more + prefix arguments: + + • With two prefix arguments (or more precisely a numeric prefix + value of 16 or greater) an arbitrary directory is read, which + is then acted on as described above. The same could be + accomplished using the command ‘magit-init’. + + • With a single prefix argument an existing repository is read + from the user, or if no repository can be found based on the + value of ‘magit-repository-directories’, then the behavior is + the same as with two prefix arguments. + + -- User Option: magit-repository-directories + List of directories that are Git repositories or contain Git + repositories. + + Each element has the form ‘(DIRECTORY . DEPTH)’. DIRECTORY has to + be a directory or a directory file-name, a string. DEPTH, an + integer, specifies the maximum depth to look for Git repositories. + If it is 0, then only add DIRECTORY itself. + + This option controls which repositories are being listed by + ‘magit-list-repositories’. It also affects ‘magit-status’ (which + see) in potentially surprising ways (see above). + + -- Command: magit-status-quick + This command is an alternative to ‘magit-status’ that usually + avoids refreshing the status buffer. + + If the status buffer of the current Git repository exists but isn’t + being displayed in the selected frame, then it is displayed without + being refreshed. + + If the status buffer is being displayed in the selected frame, then + this command refreshes it. + + Prefix arguments have the same meaning as for ‘magit-status’, and + additionally cause the buffer to be refresh. + + To use this command add this to your init file: + + (global-set-key (kbd "C-x g") 'magit-status-quick). + + If you do that and then for once want to redisplay the buffer and + also immediately refresh it, then type ‘C-x g’ followed by ‘g’. + + A possible alternative command is + ‘magit-display-repository-buffer’. It supports displaying any + existing Magit buffer that belongs to the current repository; not + just the status buffer. + + -- Command: ido-enter-magit-status + From an Ido prompt used to open a file, instead drop into + ‘magit-status’. This is similar to ‘ido-magic-delete-char’, which, + despite its name, usually causes a Dired buffer to be created. + + To make this command available, use something like: + + (add-hook 'ido-setup-hook + (lambda () + (define-key ido-completion-map + (kbd \"C-x g\") 'ido-enter-magit-status))) + + Starting with Emacs 25.1 the Ido keymaps are defined just once + instead of every time Ido is invoked, so now you can modify it like + pretty much every other keymap: + + (define-key ido-common-completion-map + (kbd \"C-x g\") 'ido-enter-magit-status) + +* Menu: + +* Status Sections:: +* Status Header Sections:: +* Status Module Sections:: +* Status Options:: + + +File: magit.info, Node: Status Sections, Next: Status Header Sections, Up: Status Buffer + +5.1.1 Status Sections +--------------------- + +The contents of status buffers is controlled using the hook +‘magit-status-sections-hook’. See *note Section Hooks:: to learn about +such hooks and how to customize them. + + -- User Option: magit-status-sections-hook + Hook run to insert sections into a status buffer. + + The first function on that hook by default is +‘magit-insert-status-headers’; it is described in the next section. By +default the following functions are also members of that hook: + + -- Function: magit-insert-merge-log + Insert section for the on-going merge. Display the heads that are + being merged. If no merge is in progress, do nothing. + + -- Function: magit-insert-rebase-sequence + Insert section for the on-going rebase sequence. If no such + sequence is in progress, do nothing. + + -- Function: magit-insert-am-sequence + Insert section for the on-going patch applying sequence. If no + such sequence is in progress, do nothing. + + -- Function: magit-insert-sequencer-sequence + Insert section for the on-going cherry-pick or revert sequence. If + no such sequence is in progress, do nothing. + + -- Function: magit-insert-bisect-output + While bisecting, insert section with output from ‘git bisect’. + + -- Function: magit-insert-bisect-rest + While bisecting, insert section visualizing the bisect state. + + -- Function: magit-insert-bisect-log + While bisecting, insert section logging bisect progress. + + -- Function: magit-insert-untracked-files + Maybe insert a list or tree of untracked files. + + Do so depending on the value of ‘status.showUntrackedFiles’. Note + that even if the value is ‘all’, Magit still initially only shows + directories. But the directory sections can then be expanded using + ‘TAB’. + + -- Function: magit-insert-unstaged-changes + Insert section showing unstaged changes. + + -- Function: magit-insert-staged-changes + Insert section showing staged changes. + + -- Function: magit-insert-stashes &optional ref heading + Insert the ‘stashes’ section showing reflog for "refs/stash". If + optional REF is non-nil show reflog for that instead. If optional + HEADING is non-nil use that as section heading instead of + "Stashes:". + + -- Function: magit-insert-unpulled-from-upstream + Insert section showing commits that haven’t been pulled from the + upstream branch yet. + + -- Function: magit-insert-unpulled-from-pushremote + Insert section showing commits that haven’t been pulled from the + push-remote branch yet. + + -- Function: magit-insert-unpushed-to-upstream + Insert section showing commits that haven’t been pushed to the + upstream yet. + + -- Function: magit-insert-unpushed-to-pushremote + Insert section showing commits that haven’t been pushed to the + push-remote yet. + + The following functions can also be added to the above hook: + + -- Function: magit-insert-tracked-files + Insert a tree of tracked files. + + -- Function: magit-insert-ignored-files + Insert a tree of ignored files. Its possible to limit the logs in + the current buffer to a certain directory using ‘D = f <DIRECTORY> + RET g’. If you do that, then that that also affects this command. + + The log filter can be used to limit to multiple files. In that + case this function only respects the first of the files and only if + it is a directory. + + -- Function: magit-insert-skip-worktree-files + Insert a tree of skip-worktree files. If the first element of + ‘magit-buffer-diff-files’ is a directory, then limit the list to + files below that. The value of that variable can be set using ‘D + -- DIRECTORY RET g’. + + -- Function: magit-insert-assumed-unchanged-files + Insert a tree of files that are assumed to be unchanged. If the + first element of ‘magit-buffer-diff-files’ is a directory, then + limit the list to files below that. The value of that variable can + be set using ‘D -- DIRECTORY RET g’. + + -- Function: magit-insert-unpulled-or-recent-commits + Insert section showing unpulled or recent commits. If an upstream + is configured for the current branch and it is ahead of the current + branch, then show the missing commits. Otherwise, show the last + ‘magit-log-section-commit-count’ commits. + + -- Function: magit-insert-recent-commits + Insert section showing the last ‘magit-log-section-commit-count’ + commits. + + -- User Option: magit-log-section-commit-count + How many recent commits ‘magit-insert-recent-commits’ and + ‘magit-insert-unpulled-or-recent-commits’ (provided there are no + unpulled commits) show. + + -- Function: magit-insert-unpulled-cherries + Insert section showing unpulled commits. Like + ‘magit-insert-unpulled-commits’ but prefix each commit that has not + been applied yet (i.e., a commit with a patch-id not shared with + any local commit) with "+", and all others with "-". + + -- Function: magit-insert-unpushed-cherries + Insert section showing unpushed commits. Like + ‘magit-insert-unpushed-commits’ but prefix each commit which has + not been applied to upstream yet (i.e., a commit with a patch-id + not shared with any upstream commit) with "+" and all others with + "-". + + See *note References Buffer:: for some more section inserters, which +could be used here. + + +File: magit.info, Node: Status Header Sections, Next: Status Module Sections, Prev: Status Sections, Up: Status Buffer + +5.1.2 Status Header Sections +---------------------------- + +The contents of status buffers is controlled using the hook +‘magit-status-sections-hook’ (see *note Status Sections::). + + By default ‘magit-insert-status-headers’ is the first member of that +hook variable. + + -- Function: magit-insert-status-headers + Insert headers sections appropriate for ‘magit-status-mode’ + buffers. The sections are inserted by running the functions on the + hook ‘magit-status-headers-hook’. + + -- User Option: magit-status-headers-hook + Hook run to insert headers sections into the status buffer. + + This hook is run by ‘magit-insert-status-headers’, which in turn + has to be a member of ‘magit-status-sections-hook’ to be used at + all. + + By default the following functions are members of the above hook: + + -- Function: magit-insert-error-header + Insert a header line showing the message about the Git error that + just occurred. + + This function is only aware of the last error that occur when Git + was run for side-effects. If, for example, an error occurs while + generating a diff, then that error won’t be inserted. Refreshing + the status buffer causes this section to disappear again. + + -- Function: magit-insert-diff-filter-header + Insert a header line showing the effective diff filters. + + -- Function: magit-insert-head-branch-header + Insert a header line about the current branch or detached ‘HEAD’. + + -- Function: magit-insert-upstream-branch-header + Insert a header line about the branch that is usually pulled into + the current branch. + + -- Function: magit-insert-push-branch-header + Insert a header line about the branch that the current branch is + usually pushed to. + + -- Function: magit-insert-tags-header + Insert a header line about the current and/or next tag, along with + the number of commits between the tag and ‘HEAD’. + + The following functions can also be added to the above hook: + + -- Function: magit-insert-repo-header + Insert a header line showing the path to the repository top-level. + + -- Function: magit-insert-remote-header + Insert a header line about the remote of the current branch. + + If no remote is configured for the current branch, then fall back + showing the "origin" remote, or if that does not exist the first + remote in alphabetic order. + + -- Function: magit-insert-user-header + Insert a header line about the current user. + + +File: magit.info, Node: Status Module Sections, Next: Status Options, Prev: Status Header Sections, Up: Status Buffer + +5.1.3 Status Module Sections +---------------------------- + +The contents of status buffers is controlled using the hook +‘magit-status-sections-hook’ (see *note Status Sections::). + + By default ‘magit-insert-modules’ is _not_ a member of that hook +variable. + + -- Function: magit-insert-modules + Insert submodule sections. + + Hook ‘magit-module-sections-hook’ controls which module sections + are inserted, and option ‘magit-module-sections-nested’ controls + whether they are wrapped in an additional section. + + -- User Option: magit-module-sections-hook + Hook run by ‘magit-insert-modules’. + + -- User Option: magit-module-sections-nested + This option controls whether ‘magit-insert-modules’ wraps inserted + sections in an additional section. + + If this is non-nil, then only a single top-level section is + inserted. If it is nil, then all sections listed in + ‘magit-module-sections-hook’ become top-level sections. + + -- Function: magit-insert-modules-overview + Insert sections for all submodules. For each section insert the + path, the branch, and the output of ‘git describe --tags’, or, + failing that, the abbreviated HEAD commit hash. + + Press ‘RET’ on such a submodule section to show its own status + buffer. Press ‘RET’ on the "Modules" section to display a list of + submodules in a separate buffer. This shows additional information + not displayed in the super-repository’s status buffer. + + -- Function: magit-insert-modules-unpulled-from-upstream + Insert sections for modules that haven’t been pulled from the + upstream yet. These sections can be expanded to show the + respective commits. + + -- Function: magit-insert-modules-unpulled-from-pushremote + Insert sections for modules that haven’t been pulled from the + push-remote yet. These sections can be expanded to show the + respective commits. + + -- Function: magit-insert-modules-unpushed-to-upstream + Insert sections for modules that haven’t been pushed to the + upstream yet. These sections can be expanded to show the + respective commits. + + -- Function: magit-insert-modules-unpushed-to-pushremote + Insert sections for modules that haven’t been pushed to the + push-remote yet. These sections can be expanded to show the + respective commits. + + +File: magit.info, Node: Status Options, Prev: Status Module Sections, Up: Status Buffer + +5.1.4 Status Options +-------------------- + + -- User Option: magit-status-margin + This option specifies whether the margin is initially shown in + Magit-Status mode buffers and how it is formatted. + + The value has the form ‘(INIT STYLE WIDTH AUTHOR AUTHOR-WIDTH)’. + + • If INIT is non-nil, then the margin is shown initially. + • STYLE controls how to format the author or committer date. It + can be one of ‘age’ (to show the age of the commit), + ‘age-abbreviated’ (to abbreviate the time unit to a + character), or a string (suitable for ‘format-time-string’) to + show the actual date. Option + ‘magit-log-margin-show-committer-date’ controls which date is + being displayed. + • WIDTH controls the width of the margin. This exists for + forward compatibility and currently the value should not be + changed. + • AUTHOR controls whether the name of the author is also shown + by default. + • AUTHOR-WIDTH has to be an integer. When the name of the + author is shown, then this specifies how much space is used to + do so. + + Also see the proceeding section for more options concerning status +buffers. + + +File: magit.info, Node: Repository List, Next: Logging, Prev: Status Buffer, Up: Inspecting + +5.2 Repository List +=================== + + -- Command: magit-list-repositories + This command displays a list of repositories in a separate buffer. + + The option ‘magit-repository-directories’ controls which + repositories are displayed. + + -- User Option: magit-repolist-columns + This option controls what columns are displayed by the command + ‘magit-list-repositories’ and how they are displayed. + + Each element has the form ‘(HEADER WIDTH FORMAT PROPS)’. + + HEADER is the string displayed in the header. WIDTH is the width + of the column. FORMAT is a function that is called with one + argument, the repository identification (usually its basename), and + with ‘default-directory’ bound to the toplevel of its working tree. + It has to return a string to be inserted or nil. PROPS is an alist + that supports the keys ‘:right-align’, ‘:pad-right’ and ‘:sort’. + + The ‘:sort’ function has a weird interface described in the + docstring of ‘tabulated-list--get-sort’. Alternatively ‘<’ and + ‘magit-repolist-version<’ can be used as those functions are + automatically replaced with functions that satisfy the interface. + Set ‘:sort’ to ‘nil’ to inhibit sorting; if unspecified, then the + column is sortable using the default sorter. + + You may wish to display a range of numeric columns using just one + character per column and without any padding between columns, in + which case you should use an appropriate HEADER, set WIDTH to 1, + and set ‘:pad-right’ to 9. ‘+’ is substituted for numbers higher + than 9. + +The following functions can be added to the above option: + + -- Function: magit-repolist-column-ident + This function inserts the identification of the repository. + Usually this is just its basename. + + -- Function: magit-repolist-column-path + This function inserts the absolute path of the repository. + + -- Function: magit-repolist-column-version + This function inserts a description of the repository’s ‘HEAD’ + revision. + + -- Function: magit-repolist-column-branch + This function inserts the name of the current branch. + + -- Function: magit-repolist-column-upstream + This function inserts the name of the upstream branch of the + current branch. + + -- Function: magit-repolist-column-branches + This function inserts the number of branches. + + -- Function: magit-repolist-column-stashes + This function inserts the number of stashes. + + -- Function: magit-repolist-column-flag + This function inserts a flag as specified by + ‘magit-repolist-column-flag-alist’. + + By default this indicates whether there are uncommitted changes. + + • ‘N’ if there is at least one untracked file. + • ‘U’ if there is at least one unstaged file. + • ‘S’ if there is at least one staged file. + + Only the first one of these that applies is shown. + + -- Function: magit-repolist-column-flags + This functions insert all flags as specified by + ‘magit-repolist-column-flag-alist’. + + This is an alternative to function ‘magit-repolist-column-flag’, + which only lists the first one found. + + -- Function: magit-repolist-column-unpulled-from-upstream + This function inserts the number of upstream commits not in the + current branch. + + -- Function: magit-repolist-column-unpulled-from-pushremote + This function inserts the number of commits in the push branch but + not the current branch. + + -- Function: magit-repolist-column-unpushed-to-upstream + This function inserts the number of commits in the current branch + but not its upstream. + + -- Function: magit-repolist-column-unpushed-to-pushremote + This function inserts the number of commits in the current branch + but not its push branch. + +The following commands are available in repolist buffers: + +‘<RET>’ (‘magit-repolist-status’) + This command shows the status for the repository at point. + +‘m’ (‘magit-repolist-mark’) + This command marks the repository at point. + +‘u’ (‘magit-repolist-unmark’) + This command unmarks the repository at point. + +‘f’ (‘magit-repolist-fetch’) + This command fetches all marked repositories. If no repositories + are marked, then it offers to fetch all displayed repositories. + +‘5’ (‘magit-repolist-find-file-other-frame’) + This command reads a relative file-name (without completion) and + opens the respective file in each marked repository in a new frame. + If no repositories are marked, then it offers to do this for all + displayed repositories. + + +File: magit.info, Node: Logging, Next: Diffing, Prev: Repository List, Up: Inspecting + +5.3 Logging +=========== + +The status buffer contains logs for the unpushed and unpulled commits, +but that obviously isn’t enough. The transient prefix command +‘magit-log’, on ‘l’, features several suffix commands, which show a +specific log in a separate log buffer. + + Like other transient prefix commands, ‘magit-log’ also features +several infix arguments that can be changed before invoking one of the +suffix commands. However, in the case of the log transient, these +arguments may be taken from those currently in use in the current +repository’s log buffer, depending on the value of +‘magit-prefix-use-buffer-arguments’ (see *note Transient Arguments and +Buffer Variables::). + + For information about the various arguments, see *note +(gitman)git-log::. The switch ‘++order=VALUE’ is converted to one of +‘--author-date-order’, ‘--date-order’, or ‘--topo-order’ before being +passed to ‘git log’. + + The log transient also features several reflog commands. See *note +Reflog::. + +‘l’ (‘magit-log’) + This transient prefix command binds the following suffix commands + along with the appropriate infix arguments and displays them in a + temporary buffer until a suffix is invoked. + +‘l l’ (‘magit-log-current’) + Show log for the current branch. When ‘HEAD’ is detached or with a + prefix argument, show log for one or more revs read from the + minibuffer. + +‘l h’ (‘magit-log-head’) + Show log for ‘HEAD’. + +‘l u’ (‘magit-log-related’) + Show log for the current branch, its upstream and its push target. + When the upstream is a local branch, then also show its own + upstream. When ‘HEAD’ is detached, then show log for that, the + previously checked out branch and its upstream and push-target. + +‘l o’ (‘magit-log-other’) + Show log for one or more revs read from the minibuffer. The user + can input any revision or revisions separated by a space, or even + ranges, but only branches, tags, and a representation of the commit + at point are available as completion candidates. + +‘l L’ (‘magit-log-branches’) + Show log for all local branches and ‘HEAD’. + +‘l b’ (‘magit-log-all-branches’) + Show log for all local and remote branches and ‘HEAD’. + +‘l a’ (‘magit-log-all’) + Show log for all references and ‘HEAD’. + + Two additional commands that show the log for the file or blob that +is being visited in the current buffer exists, see *note Commands for +Buffers Visiting Files::. The command ‘magit-cherry’ also shows a log, +see *note Cherries::. + +* Menu: + +* Refreshing Logs:: +* Log Buffer:: +* Log Margin:: +* Select from Log:: +* Reflog:: +* Cherries:: + + +File: magit.info, Node: Refreshing Logs, Next: Log Buffer, Up: Logging + +5.3.1 Refreshing Logs +--------------------- + +The transient prefix command ‘magit-log-refresh’, on ‘L’, can be used to +change the log arguments used in the current buffer, without changing +which log is shown. This works in dedicated log buffers, but also in +the status buffer. + +‘L’ (‘magit-log-refresh’) + This transient prefix command binds the following suffix commands + along with the appropriate infix arguments and displays them in a + temporary buffer until a suffix is invoked. + +‘L g’ (‘magit-log-refresh’) + This suffix command sets the local log arguments for the current + buffer. + +‘L s’ (‘magit-log-set-default-arguments’) + This suffix command sets the default log arguments for buffers of + the same type as that of the current buffer. Other existing + buffers of the same type are not affected because their local + values have already been initialized. + +‘L w’ (‘magit-log-save-default-arguments’) + This suffix command sets the default log arguments for buffers of + the same type as that of the current buffer, and saves the value + for future sessions. Other existing buffers of the same type are + not affected because their local values have already been + initialized. + +‘L L’ (‘magit-toggle-margin’) + Show or hide the margin. + + +File: magit.info, Node: Log Buffer, Next: Log Margin, Prev: Refreshing Logs, Up: Logging + +5.3.2 Log Buffer +---------------- + +‘L’ (‘magit-log-refresh’) + This transient prefix command binds the following suffix commands + along with the appropriate infix arguments and displays them in a + temporary buffer until a suffix is invoked. + + See *note Refreshing Logs::. + +‘q’ (‘magit-log-bury-buffer’) + Bury the current buffer or the revision buffer in the same frame. + Like ‘magit-mode-bury-buffer’ (which see) but with a negative + prefix argument instead bury the revision buffer, provided it is + displayed in the current frame. + +‘C-c C-b’ (‘magit-go-backward’) + Move backward in current buffer’s history. + +‘C-c C-f’ (‘magit-go-forward’) + Move forward in current buffer’s history. + +‘C-c C-n’ (‘magit-log-move-to-parent’) + Move to a parent of the current commit. By default, this is the + first parent, but a numeric prefix can be used to specify another + parent. + +‘j’ (‘magit-log-move-to-revision’) + Read a revision and move to it in current log buffer. + + If the chosen reference or revision isn’t being displayed in the + current log buffer, then inform the user about that and do nothing + else. + + If invoked outside any log buffer, then display the log buffer of + the current repository first; creating it if necessary. + +‘<SPC>’ (‘magit-diff-show-or-scroll-up’) + Update the commit or diff buffer for the thing at point. + + Either show the commit or stash at point in the appropriate buffer, + or if that buffer is already being displayed in the current frame + and contains information about that commit or stash, then instead + scroll the buffer up. If there is no commit or stash at point, + then prompt for a commit. + +‘<DEL>’ (‘magit-diff-show-or-scroll-down’) + Update the commit or diff buffer for the thing at point. + + Either show the commit or stash at point in the appropriate buffer, + or if that buffer is already being displayed in the current frame + and contains information about that commit or stash, then instead + scroll the buffer down. If there is no commit or stash at point, + then prompt for a commit. + +‘=’ (‘magit-log-toggle-commit-limit’) + Toggle the number of commits the current log buffer is limited to. + If the number of commits is currently limited, then remove that + limit. Otherwise set it to 256. + +‘+’ (‘magit-log-double-commit-limit’) + Double the number of commits the current log buffer is limited to. + +‘-’ (‘magit-log-half-commit-limit’) + Half the number of commits the current log buffer is limited to. + + -- User Option: magit-log-auto-more + Insert more log entries automatically when moving past the last + entry. Only considered when moving past the last entry with + ‘magit-goto-*-section’ commands. + + -- User Option: magit-log-show-refname-after-summary + Whether to show the refnames after the commit summaries. This is + useful if you use really long branch names. + + -- User Option: magit-log-show-color-graph-limit + When showing more commits than specified by this option, then the + ‘--color’ argument, if specified, is silently dropped. This is + necessary because the ‘ansi-color’ library, which is used to turn + control sequences into faces, is just too slow. + + -- User Option: magit-log-show-signatures-limit + When showing more commits than specified by this option, then the + ‘--show-signature’ argument, if specified, is silently dropped. + This is necessary because checking the signature of a large number + of commits is just too slow. + + Magit displays references in logs a bit differently from how Git does +it. + + Local branches are blue and remote branches are green. Of course +that depends on the used theme, as do the colors used for other types of +references. The current branch has a box around it, as do remote +branches that are their respective remote’s ‘HEAD’ branch. + + If a local branch and its push-target point at the same commit, then +their names are combined to preserve space and to make that relationship +visible. For example: + + origin/feature + [green][blue-] + + instead of + + feature origin/feature + [blue-] [green-------] + + Also note that while the transient features the ‘--show-signature’ +argument, that won’t actually be used when enabled, because Magit +defaults to use just one line per commit. Instead the commit colorized +to indicate the validity of the signed commit object, using the faces +named ‘magit-signature-*’ (which see). + + For a description of ‘magit-log-margin’ see *note Log Margin::. + + +File: magit.info, Node: Log Margin, Next: Select from Log, Prev: Log Buffer, Up: Logging + +5.3.3 Log Margin +---------------- + +In buffers which show one or more logs, it is possible to show +additional information about each commit in the margin. The options +used to configure the margin are named ‘magit-INFIX-margin’, where INFIX +is the same as in the respective major-mode ‘magit-INFIX-mode’. In +regular log buffers that would be ‘magit-log-margin’. + + -- User Option: magit-log-margin + This option specifies whether the margin is initially shown in + Magit-Log mode buffers and how it is formatted. + + The value has the form ‘(INIT STYLE WIDTH AUTHOR AUTHOR-WIDTH)’. + + • If INIT is non-nil, then the margin is shown initially. + • STYLE controls how to format the author or committer date. It + can be one of ‘age’ (to show the age of the commit), + ‘age-abbreviated’ (to abbreviate the time unit to a + character), or a string (suitable for ‘format-time-string’) to + show the actual date. Option + ‘magit-log-margin-show-committer-date’ controls which date is + being displayed. + • WIDTH controls the width of the margin. This exists for + forward compatibility and currently the value should not be + changed. + • AUTHOR controls whether the name of the author is also shown + by default. + • AUTHOR-WIDTH has to be an integer. When the name of the + author is shown, then this specifies how much space is used to + do so. + + You can change the STYLE and AUTHOR-WIDTH of all ‘magit-INFIX-margin’ +options to the same values by customizing ‘magit-log-margin’ *before* +‘magit’ is loaded. If you do that, then the respective values for the +other options will default to what you have set for that variable. +Likewise if you set INIT in ‘magit-log-margin’ to ‘nil’, then that is +used in the default of all other options. But setting it to ‘t’, i.e. +re-enforcing the default for that option, does not carry to other +options. + + -- User Option: magit-log-margin-show-committer-date + This option specifies whether to show the committer date in the + margin. This option only controls whether the committer date is + displayed instead of the author date. Whether some date is + displayed in the margin and whether the margin is displayed at all + is controlled by other options. + +‘L’ (‘magit-margin-settings’) + This transient prefix command binds the following suffix commands, + each of which changes the appearance of the margin in some way. + + In some buffers that support the margin, ‘L’ is instead bound to +‘magit-log-refresh’, but that transient features the same commands, and +then some other unrelated commands. + +‘L L’ (‘magit-toggle-margin’) + This command shows or hides the margin. + +‘L l’ (‘magit-cycle-margin-style’) + This command cycles the style used for the margin. + +‘L d’ (‘magit-toggle-margin-details’) + This command shows or hides details in the margin. + + +File: magit.info, Node: Select from Log, Next: Reflog, Prev: Log Margin, Up: Logging + +5.3.4 Select from Log +--------------------- + +When the user has to select a recent commit that is reachable from +‘HEAD’, using regular completion would be inconvenient (because most +humans cannot remember hashes or "HEAD~5", at least not without double +checking). Instead a log buffer is used to select the commit, which has +the advantage that commits are presented in order and with the commit +message. + + Such selection logs are used when selecting the beginning of a rebase +and when selecting the commit to be squashed into. + + In addition to the key bindings available in all log buffers, the +following additional key bindings are available in selection log +buffers: + +‘C-c C-c’ (‘magit-log-select-pick’) + Select the commit at point and act on it. Call + ‘magit-log-select-pick-function’ with the selected commit as + argument. + +‘C-c C-k’ (‘magit-log-select-quit’) + Abort selecting a commit, don’t act on any commit. + + -- User Option: magit-log-select-margin + This option specifies whether the margin is initially shown in + Magit-Log-Select mode buffers and how it is formatted. + + The value has the form ‘(INIT STYLE WIDTH AUTHOR AUTHOR-WIDTH)’. + + • If INIT is non-nil, then the margin is shown initially. + • STYLE controls how to format the author or committer date. It + can be one of ‘age’ (to show the age of the commit), + ‘age-abbreviated’ (to abbreviate the time unit to a + character), or a string (suitable for ‘format-time-string’) to + show the actual date. Option + ‘magit-log-margin-show-committer-date’ controls which date is + being displayed. + • WIDTH controls the width of the margin. This exists for + forward compatibility and currently the value should not be + changed. + • AUTHOR controls whether the name of the author is also shown + by default. + • AUTHOR-WIDTH has to be an integer. When the name of the + author is shown, then this specifies how much space is used to + do so. + + +File: magit.info, Node: Reflog, Next: Cherries, Prev: Select from Log, Up: Logging + +5.3.5 Reflog +------------ + +Also see *note (gitman)git-reflog::. + + These reflog commands are available from the log transient. See +*note Logging::. + +‘l r’ (‘magit-reflog-current’) + Display the reflog of the current branch. + +‘l O’ (‘magit-reflog-other’) + Display the reflog of a branch or another ref. + +‘l H’ (‘magit-reflog-head’) + Display the ‘HEAD’ reflog. + + -- User Option: magit-reflog-margin + This option specifies whether the margin is initially shown in + Magit-Reflog mode buffers and how it is formatted. + + The value has the form ‘(INIT STYLE WIDTH AUTHOR AUTHOR-WIDTH)’. + + • If INIT is non-nil, then the margin is shown initially. + • STYLE controls how to format the author or committer date. It + can be one of ‘age’ (to show the age of the commit), + ‘age-abbreviated’ (to abbreviate the time unit to a + character), or a string (suitable for ‘format-time-string’) to + show the actual date. Option + ‘magit-log-margin-show-committer-date’ controls which date is + being displayed. + • WIDTH controls the width of the margin. This exists for + forward compatibility and currently the value should not be + changed. + • AUTHOR controls whether the name of the author is also shown + by default. + • AUTHOR-WIDTH has to be an integer. When the name of the + author is shown, then this specifies how much space is used to + do so. + + +File: magit.info, Node: Cherries, Prev: Reflog, Up: Logging + +5.3.6 Cherries +-------------- + +Cherries are commits that haven’t been applied upstream (yet), and are +usually visualized using a log. Each commit is prefixed with ‘-’ if it +has an equivalent in the upstream and ‘+’ if it does not, i.e., if it is +a cherry. + + The command ‘magit-cherry’ shows cherries for a single branch, but +the references buffer (see *note References Buffer::) can show cherries +for multiple "upstreams" at once. + + Also see *note (gitman)git-reflog::. + +‘Y’ (‘magit-cherry’) + Show commits that are in a certain branch but that have not been + merged in the upstream branch. + + -- User Option: magit-cherry-margin + This option specifies whether the margin is initially shown in + Magit-Cherry mode buffers and how it is formatted. + + The value has the form ‘(INIT STYLE WIDTH AUTHOR AUTHOR-WIDTH)’. + + • If INIT is non-nil, then the margin is shown initially. + • STYLE controls how to format the author or committer date. It + can be one of ‘age’ (to show the age of the commit), + ‘age-abbreviated’ (to abbreviate the time unit to a + character), or a string (suitable for ‘format-time-string’) to + show the actual date. Option + ‘magit-log-margin-show-committer-date’ controls which date is + being displayed. + • WIDTH controls the width of the margin. This exists for + forward compatibility and currently the value should not be + changed. + • AUTHOR controls whether the name of the author is also shown + by default. + • AUTHOR-WIDTH has to be an integer. When the name of the + author is shown, then this specifies how much space is used to + do so. + + +File: magit.info, Node: Diffing, Next: Ediffing, Prev: Logging, Up: Inspecting + +5.4 Diffing +=========== + +The status buffer contains diffs for the staged and unstaged commits, +but that obviously isn’t enough. The transient prefix command +‘magit-diff’, on ‘d’, features several suffix commands, which show a +specific diff in a separate diff buffer. + + Like other transient prefix commands, ‘magit-diff’ also features +several infix arguments that can be changed before invoking one of the +suffix commands. However, in the case of the diff transient, these +arguments may be taken from those currently in use in the current +repository’s diff buffer, depending on the value of +‘magit-prefix-use-buffer-arguments’ (see *note Transient Arguments and +Buffer Variables::). + + Also see *note (gitman)git-diff::. + +‘d’ (‘magit-diff’) + This transient prefix command binds the following suffix commands + along with the appropriate infix arguments and displays them in a + temporary buffer until a suffix is invoked. + +‘d d’ (‘magit-diff-dwim’) + Show changes for the thing at point. + +‘d r’ (‘magit-diff-range’) + Show differences between two commits. + + RANGE should be a range (A..B or A...B) but can also be a single + commit. If one side of the range is omitted, then it defaults to + ‘HEAD’. If just a commit is given, then changes in the working + tree relative to that commit are shown. + + If the region is active, use the revisions on the first and last + line of the region. With a prefix argument, instead of diffing the + revisions, choose a revision to view changes along, starting at the + common ancestor of both revisions (i.e., use a "..." range). + +‘d w’ (‘magit-diff-working-tree’) + Show changes between the current working tree and the ‘HEAD’ + commit. With a prefix argument show changes between the working + tree and a commit read from the minibuffer. + +‘d s’ (‘magit-diff-staged’) + Show changes between the index and the ‘HEAD’ commit. With a + prefix argument show changes between the index and a commit read + from the minibuffer. + +‘d u’ (‘magit-diff-unstaged’) + Show changes between the working tree and the index. + +‘d p’ (‘magit-diff-paths’) + Show changes between any two files on disk. + + All of the above suffix commands update the repository’s diff buffer. +The diff transient also features two commands which show differences in +another buffer: + +‘d c’ (‘magit-show-commit’) + Show the commit at point. If there is no commit at point or with a + prefix argument, prompt for a commit. + +‘d t’ (‘magit-stash-show’) + Show all diffs of a stash in a buffer. + + Two additional commands that show the diff for the file or blob that +is being visited in the current buffer exists, see *note Commands for +Buffers Visiting Files::. + +* Menu: + +* Refreshing Diffs:: +* Commands Available in Diffs:: +* Diff Options:: +* Revision Buffer:: + + +File: magit.info, Node: Refreshing Diffs, Next: Commands Available in Diffs, Up: Diffing + +5.4.1 Refreshing Diffs +---------------------- + +The transient prefix command ‘magit-diff-refresh’, on ‘D’, can be used +to change the diff arguments used in the current buffer, without +changing which diff is shown. This works in dedicated diff buffers, but +also in the status buffer. + + (There is one exception; diff arguments cannot be changed in buffers +created by ‘magit-merge-preview’ because the underlying Git command does +not support these arguments.) + +‘D’ (‘magit-diff-refresh’) + This transient prefix command binds the following suffix commands + along with the appropriate infix arguments and displays them in a + temporary buffer until a suffix is invoked. + +‘D g’ (‘magit-diff-refresh’) + This suffix command sets the local diff arguments for the current + buffer. + +‘D s’ (‘magit-diff-set-default-arguments’) + This suffix command sets the default diff arguments for buffers of + the same type as that of the current buffer. Other existing + buffers of the same type are not affected because their local + values have already been initialized. + +‘D w’ (‘magit-diff-save-default-arguments’) + This suffix command sets the default diff arguments for buffers of + the same type as that of the current buffer, and saves the value + for future sessions. Other existing buffers of the same type are + not affected because their local values have already been + initialized. + +‘D t’ (‘magit-diff-toggle-refine-hunk’) + This command toggles hunk refinement on or off. + +‘D r’ (‘magit-diff-switch-range-type’) + This command converts the diff range type from "revA..revB" to + "revB...revA", or vice versa. + +‘D f’ (‘magit-diff-flip-revs’) + This command swaps revisions in the diff range from "revA..revB" to + "revB..revA", or vice versa. + +‘D F’ (‘magit-diff-toggle-file-filter’) + This command toggles the file restriction of the diffs in the + current buffer, allowing you to quickly switch between viewing all + the changes in the commit and the restricted subset. As a special + case, when this command is called from a log buffer, it toggles the + file restriction in the repository’s revision buffer, which is + useful when you display a revision from a log buffer that is + restricted to a file or files. + + In addition to the above transient, which allows changing any of the +supported arguments, there also exist some commands that change only a +particular argument. + +‘-’ (‘magit-diff-less-context’) + This command decreases the context for diff hunks by COUNT lines. + +‘+’ (‘magit-diff-more-context’) + This command increases the context for diff hunks by COUNT lines. + +‘0’ (‘magit-diff-default-context’) + This command resets the context for diff hunks to the default + height. + + The following commands quickly change what diff is being displayed +without having to using one of the diff transient. + +‘C-c C-d’ (‘magit-diff-while-committing’) + While committing, this command shows the changes that are about to + be committed. While amending, invoking the command again toggles + between showing just the new changes or all the changes that will + be committed. + + This binding is available in the diff buffer as well as the commit + message buffer. + +‘C-c C-b’ (‘magit-go-backward’) + This command moves backward in current buffer’s history. + +‘C-c C-f’ (‘magit-go-forward’) + This command moves forward in current buffer’s history. + + +File: magit.info, Node: Commands Available in Diffs, Next: Diff Options, Prev: Refreshing Diffs, Up: Diffing + +5.4.2 Commands Available in Diffs +--------------------------------- + +Some commands are only available if point is inside a diff. + + ‘magit-diff-visit-file’ and related commands visit the appropriate +version of the file that the diff at point is about. Likewise +‘magit-diff-visit-worktree-file’ and related commands visit the worktree +version of the file that the diff at point is about. See *note Visiting +Files and Blobs from a Diff:: for more information and the key bindings. + +‘C-c C-t’ (‘magit-diff-trace-definition’) + This command shows a log for the definition at point. + + -- User Option: magit-log-trace-definition-function + The function specified by this option is used by + ‘magit-log-trace-definition’ to determine the function at point. + For major-modes that have special needs, you could set the local + value using the mode’s hook. + +‘C-c C-e’ (‘magit-diff-edit-hunk-commit’) + From a hunk, this command edits the respective commit and visits + the file. + + First it visits the file being modified by the hunk at the correct + location using ‘magit-diff-visit-file’. This actually visits a + blob. When point is on a diff header, not within an individual + hunk, then this visits the blob the first hunk is about. + + Then it invokes ‘magit-edit-line-commit’, which uses an interactive + rebase to make the commit editable, or if that is not possible + because the commit is not reachable from ‘HEAD’ by checking out + that commit directly. This also causes the actual worktree file to + be visited. + + Neither the blob nor the file buffer are killed when finishing the + rebase. If that is undesirable, then it might be better to use + ‘magit-rebase-edit-commit’ instead of this command. + +‘j’ (‘magit-jump-to-diffstat-or-diff’) + This command jumps to the diffstat or diff. When point is on a + file inside the diffstat section, then jump to the respective diff + section. Otherwise, jump to the diffstat section or a child + thereof. + + The next two commands are not specific to Magit-Diff mode (or and +Magit buffer for that matter), but it might be worth pointing out that +they are available here too. + +‘<SPC>’ (‘scroll-up’) + This command scrolls text upward. + +‘<DEL>’ (‘scroll-down’) + This command scrolls text downward. + + +File: magit.info, Node: Diff Options, Next: Revision Buffer, Prev: Commands Available in Diffs, Up: Diffing + +5.4.3 Diff Options +------------------ + + -- User Option: magit-diff-refine-hunk + Whether to show word-granularity differences within diff hunks. + + • ‘nil’ Never show fine differences. + • ‘t’ Show fine differences for the current diff hunk only. + • ‘all’ Show fine differences for all displayed diff hunks. + + -- User Option: magit-diff-refine-ignore-whitespace + Whether to ignore whitespace changes in word-granularity + differences. + + -- User Option: magit-diff-adjust-tab-width + Whether to adjust the width of tabs in diffs. + + Determining the correct width can be expensive if it requires + opening large and/or many files, so the widths are cached in the + variable ‘magit-diff--tab-width-cache’. Set that to nil to + invalidate the cache. + + • ‘nil’ Never adjust tab width. Use ‘tab-width’s value from the + Magit buffer itself instead. + + • ‘t’ If the corresponding file-visiting buffer exits, then use + ‘tab-width’’s value from that buffer. Doing this is cheap, so + this value is used even if a corresponding cache entry exists. + + • ‘always’ If there is no such buffer, then temporarily visit + the file to determine the value. + + • NUMBER Like ‘always’, but don’t visit files larger than NUMBER + bytes. + + -- User Option: magit-diff-paint-whitespace + Specify where to highlight whitespace errors. + + See ‘magit-diff-highlight-trailing’, + ‘magit-diff-highlight-indentation’. The symbol ‘t’ means in all + diffs, ‘status’ means only in the status buffer, and nil means + nowhere. + + • ‘nil’ Never highlight whitespace errors. + • ‘t’ Highlight whitespace errors everywhere. + • ‘uncommitted’ Only highlight whitespace errors in diffs + showing uncommitted changes. For backward compatibility + ‘status’ is treated as a synonym. + + -- User Option: magit-diff-paint-whitespace-lines + Specify in what kind of lines to highlight whitespace errors. + + • ‘t’ Highlight only in added lines. + • ‘both’ Highlight in added and removed lines. + • ‘all’ Highlight in added, removed and context lines. + + -- User Option: magit-diff-highlight-trailing + Whether to highlight whitespace at the end of a line in diffs. + Used only when ‘magit-diff-paint-whitespace’ is non-nil. + + -- User Option: magit-diff-highlight-indentation + This option controls whether to highlight the indentation in case + it used the "wrong" indentation style. Indentation is only + highlighted if ‘magit-diff-paint-whitespace’ is also non-nil. + + The value is an alist of the form ‘((REGEXP . INDENT)...)’. The + path to the current repository is matched against each element in + reverse order. Therefore if a REGEXP matches, then earlier + elements are not tried. + + If the used INDENT is ‘tabs’, highlight indentation with tabs. If + INDENT is an integer, highlight indentation with at least that many + spaces. Otherwise, highlight neither. + + -- User Option: magit-diff-hide-trailing-cr-characters + Whether to hide ^M characters at the end of a line in diffs. + + -- User Option: magit-diff-highlight-hunk-region-functions + This option specifies the functions used to highlight the + hunk-internal region. + + ‘magit-diff-highlight-hunk-region-dim-outside’ overlays the outside + of the hunk internal selection with a face that causes the added + and removed lines to have the same background color as context + lines. This function should not be removed from the value of this + option. + + ‘magit-diff-highlight-hunk-region-using-overlays’ and + ‘magit-diff-highlight-hunk-region-using-underline’ emphasize the + region by placing delimiting horizontal lines before and after it. + Both of these functions have glitches which cannot be fixed due to + limitations of Emacs’ display engine. For more information see + <https://github.com/magit/magit/issues/2758> ff. + + Instead of, or in addition to, using delimiting horizontal lines, + to emphasize the boundaries, you may wish to emphasize the text + itself, using ‘magit-diff-highlight-hunk-region-using-face’. + + In terminal frames it’s not possible to draw lines as the overlay + and underline variants normally do, so there they fall back to + calling the face function instead. + + -- User Option: magit-diff-unmarked-lines-keep-foreground + This option controls whether added and removed lines outside the + hunk-internal region only lose their distinct background color or + also the foreground color. Whether the outside of the region is + dimmed at all depends on + ‘magit-diff-highlight-hunk-region-functions’. + + -- User Option: magit-diff-extra-stat-arguments + This option specifies additional arguments to be used alongside + ‘--stat’. + + The value is a list of zero or more arguments or a function that + takes no argument and returns such a list. These arguments are + allowed here: ‘--stat-width’, ‘--stat-name-width’, + ‘--stat-graph-width’ and ‘--compact-summary’. Also see *note + (gitman)git-diff::. + + +File: magit.info, Node: Revision Buffer, Prev: Diff Options, Up: Diffing + +5.4.4 Revision Buffer +--------------------- + + -- User Option: magit-revision-insert-related-refs + Whether to show related branches in revision buffers. + + • ‘nil’ Don’t show any related branches. + • ‘t’ Show related local branches. + • ‘all’ Show related local and remote branches. + • ‘mixed’ Show all containing branches and local merged + branches. + + -- User Option: magit-revision-show-gravatars + Whether to show gravatar images in revision buffers. + + If ‘nil’, then don’t insert any gravatar images. If ‘t’, then + insert both images. If ‘author’ or ‘committer’, then insert only + the respective image. + + If you have customized the option ‘magit-revision-headers-format’ + and want to insert the images then you might also have to specify + where to do so. In that case the value has to be a cons-cell of + two regular expressions. The car specifies where to insert the + author’s image. The top half of the image is inserted right after + the matched text, the bottom half on the next line in the same + column. The cdr specifies where to insert the committer’s image, + accordingly. Either the car or the cdr may be nil." + + -- User Option: magit-revision-use-hash-sections + Whether to turn hashes inside the commit message into sections. + + If non-nil, then hashes inside the commit message are turned into + ‘commit’ sections. There is a trade off to be made between + performance and reliability: + + • ‘slow’ calls git for every word to be absolutely sure. + • ‘quick’ skips words less than seven characters long. + • ‘quicker’ additionally skips words that don’t contain a + number. + • ‘quickest’ uses all words that are at least seven characters + long and which contain at least one number as well as at least + one letter. + + If nil, then no hashes are turned into sections, but you can still + visit the commit at point using "RET". + + The diffs shown in the revision buffer may be automatically +restricted to a subset of the changed files. If the revision buffer is +displayed from a log buffer, the revision buffer will share the same +file restriction as that log buffer (also see the command +‘magit-diff-toggle-file-filter’). + + -- User Option: magit-revision-filter-files-on-follow + Whether showing a commit from a log buffer honors the log’s file + filter when the log arguments include ‘--follow’. + + When this option is nil, displaying a commit from a log ignores the + log’s file filter if the log arguments include ‘--follow’. Doing + so avoids showing an empty diff in revision buffers for commits + before a rename event. In such cases, the ‘--patch’ argument of + the log transient can be used to show the file-restricted diffs + inline. + + Set this option to non-nil to keep the log’s file restriction even + if ‘--follow’ is present in the log arguments. + + If the revision buffer is not displayed from a log buffer, the file +restriction is determined as usual (see *note Transient Arguments and +Buffer Variables::). + + +File: magit.info, Node: Ediffing, Next: References Buffer, Prev: Diffing, Up: Inspecting + +5.5 Ediffing +============ + +This section describes how to enter Ediff from Magit buffers. For +information on how to use Ediff itself, see *note (ediff)Top::. + +‘e’ (‘magit-ediff-dwim’) + Compare, stage, or resolve using Ediff. + + This command tries to guess what file, and what commit or range the + user wants to compare, stage, or resolve using Ediff. It might + only be able to guess either the file, or range/commit, in which + case the user is asked about the other. It might not always guess + right, in which case the appropriate ‘magit-ediff-*’ command has to + be used explicitly. If it cannot read the user’s mind at all, then + it asks the user for a command to run. + +‘E’ (‘magit-ediff’) + This transient prefix command binds the following suffix commands + and displays them in a temporary buffer until a suffix is invoked. + +‘E r’ (‘magit-ediff-compare’) + Compare two revisions of a file using Ediff. + + If the region is active, use the revisions on the first and last + line of the region. With a prefix argument, instead of diffing the + revisions, choose a revision to view changes along, starting at the + common ancestor of both revisions (i.e., use a "..." range). + +‘E m’ (‘magit-ediff-resolve-rest’) + This command allows you to resolve outstanding conflicts in the + file at point using Ediff. If there is no file at point or if it + doesn’t have any unmerged changes, then this command prompts for a + file. + + Provided that the value of ‘merge.conflictstyle’ is ‘diff3’, you + can view the file’s merge-base revision using ‘/’ in the Ediff + control buffer. + + The A, B and Ancestor buffers are constructed from the conflict + markers in the worktree file. Because you and/or Git may have + already resolved some conflicts, that means that these buffers may + not contain the actual versions from the respective blobs. + +‘E M’ (‘magit-ediff-resolve-all’) + This command allows you to resolve all conflicts in the file at + point using Ediff. If there is no file at point or if it doesn’t + have any unmerged changes, then this command prompts for a file. + + Provided that the value of ‘merge.conflictstyle’ is ‘diff3’, you + can view the file’s merge-base revision using ‘/’ in the Ediff + control buffer. + + First the file in the worktree is moved aside, appending the suffix + ‘.ORIG’, so that you could later go back to that version. Then it + is reconstructed from the two sides of the conflict and the + merge-base, if available. + + It would be nice if the worktree file were just used as-is, but + Ediff does not support that. This means that all conflicts, that + Git has already resolved, are restored. On the other hand Ediff + also tries to resolve conflicts, and in many cases Ediff and Git + should produce similar results. + + However if you have already resolved some conflicts manually, then + those changes are discarded (though you can recover them from the + backup file). In such cases ‘magit-ediff-resolve-rest’ might be + more suitable. + + The advantage that this command has over ‘magit-ediff-resolve-rest’ + is that the A, B and Ancestor buffers correspond to blobs from the + respective commits, allowing you to inspect a side in context and + to use Magit commands in these buffers to do so. Blame and log + commands are particularly useful here. + +‘E t’ (‘magit-git-mergetool’) + This command does not actually use Ediff. While it serves the same + purpose as ‘magit-ediff-resolve-rest’, it uses ‘git mergetool + --gui’ to resolve conflicts. + + With a prefix argument this acts as a transient prefix command, + allowing the user to select the mergetool and change some settings. + +‘E s’ (‘magit-ediff-stage’) + Stage and unstage changes to a file using Ediff, defaulting to the + file at point. + +‘E u’ (‘magit-ediff-show-unstaged’) + Show unstaged changes to a file using Ediff. + +‘E i’ (‘magit-ediff-show-staged’) + Show staged changes to a file using Ediff. + +‘E w’ (‘magit-ediff-show-working-tree’) + Show changes in a file between ‘HEAD’ and working tree using Ediff. + +‘E c’ (‘magit-ediff-show-commit’) + Show changes to a file introduced by a commit using Ediff. + +‘E z’ (‘magit-ediff-show-stash’) + Show changes to a file introduced by a stash using Ediff. + + -- User Option: magit-ediff-dwim-resolve-function + This option controls which function ‘magit-ediff-dwim’ uses to + resolve conflicts. One of ‘magit-ediff-resolve-rest’, + ‘magit-ediff-resolve-all’ or ‘magit-git-mergetool’; which are all + discussed above. + + -- User Option: magit-ediff-dwim-show-on-hunks + This option controls what command ‘magit-ediff-dwim’ calls when + point is on uncommitted hunks. When nil, always run + ‘magit-ediff-stage’. Otherwise, use ‘magit-ediff-show-staged’ and + ‘magit-ediff-show-unstaged’ to show staged and unstaged changes, + respectively. + + -- User Option: magit-ediff-show-stash-with-index + This option controls whether ‘magit-ediff-show-stash’ includes a + buffer containing the file’s state in the index at the time the + stash was created. This makes it possible to tell which changes in + the stash were staged. + + -- User Option: magit-ediff-quit-hook + This hook is run after quitting an Ediff session that was created + using a Magit command. The hook functions are run inside the Ediff + control buffer, and should not change the current buffer. + + This is similar to ‘ediff-quit-hook’ but takes the needs of Magit + into account. The regular ‘ediff-quit-hook’ is ignored by Ediff + sessions that were created using a Magit command. + + +File: magit.info, Node: References Buffer, Next: Bisecting, Prev: Ediffing, Up: Inspecting + +5.6 References Buffer +===================== + +‘y’ (‘magit-show-refs’) + This command lists branches and tags in a dedicated buffer. + + However if this command is invoked again from this buffer or if it + is invoked with a prefix argument, then it acts as a transient + prefix command, which binds the following suffix commands and some + infix arguments. + + All of the following suffix commands list exactly the same branches +and tags. The only difference the optional feature that can be enabled +by changing the value of ‘magit-refs-show-commit-count’ (see below). +These commands specify a different branch or commit against which all +the other references are compared. + +‘y y’ (‘magit-show-refs-head’) + This command lists branches and tags in a dedicated buffer. Each + reference is being compared with ‘HEAD’. + +‘y c’ (‘magit-show-refs-current’) + This command lists branches and tags in a dedicated buffer. Each + reference is being compared with the current branch or ‘HEAD’ if it + is detached. + +‘y o’ (‘magit-show-refs-other’) + This command lists branches and tags in a dedicated buffer. Each + reference is being compared with a branch read from the user. + +‘y r’ (‘magit-refs-set-show-commit-count’) + This command changes for which refs the commit count is shown. + + -- User Option: magit-refs-show-commit-count + Whether to show commit counts in Magit-Refs mode buffers. + + • ‘all’ Show counts for branches and tags. + • ‘branch’ Show counts for branches only. + • ‘nil’ Never show counts. + + The default is ‘nil’ because anything else can be very expensive. + + -- User Option: magit-refs-pad-commit-counts + Whether to pad all commit counts on all sides in Magit-Refs mode + buffers. + + If this is nil, then some commit counts are displayed right next to + one of the branches that appear next to the count, without any + space in between. This might look bad if the branch name faces + look too similar to ‘magit-dimmed’. + + If this is non-nil, then spaces are placed on both sides of all + commit counts. + + -- User Option: magit-refs-show-remote-prefix + Whether to show the remote prefix in lists of remote branches. + + Showing the prefix is redundant because the name of the remote is + already shown in the heading preceding the list of its branches. + + -- User Option: magit-refs-primary-column-width + Width of the primary column in ‘magit-refs-mode’ buffers. The + primary column is the column that contains the name of the branch + that the current row is about. + + If this is an integer, then the column is that many columns wide. + Otherwise it has to be a cons-cell of two integers. The first + specifies the minimal width, the second the maximal width. In that + case the actual width is determined using the length of the names + of the shown local branches. (Remote branches and tags are not + taken into account when calculating to optimal width.) + + -- User Option: magit-refs-focus-column-width + Width of the focus column in ‘magit-refs-mode’ buffers. + + The focus column is the first column, which marks one branch + (usually the current branch) as the focused branch using ‘*’ or + ‘@’. For each other reference, this column optionally shows how + many commits it is ahead of the focused branch and ‘<’, or if it + isn’t ahead then the commits it is behind and ‘>’, or if it isn’t + behind either, then a ‘=’. + + This column may also display only ‘*’ or ‘@’ for the focused + branch, in which case this option is ignored. Use ‘L v’ to change + the verbosity of this column. + + -- User Option: magit-refs-margin + This option specifies whether the margin is initially shown in + Magit-Refs mode buffers and how it is formatted. + + The value has the form ‘(INIT STYLE WIDTH AUTHOR AUTHOR-WIDTH)’. + + • If INIT is non-nil, then the margin is shown initially. + • STYLE controls how to format the author or committer date. It + can be one of ‘age’ (to show the age of the commit), + ‘age-abbreviated’ (to abbreviate the time unit to a + character), or a string (suitable for ‘format-time-string’) to + show the actual date. Option + ‘magit-log-margin-show-committer-date’ controls which date is + being displayed. + • WIDTH controls the width of the margin. This exists for + forward compatibility and currently the value should not be + changed. + • AUTHOR controls whether the name of the author is also shown + by default. + • AUTHOR-WIDTH has to be an integer. When the name of the + author is shown, then this specifies how much space is used to + do so. + + -- User Option: magit-refs-margin-for-tags + This option specifies whether to show information about tags in the + margin. This is disabled by default because it is slow if there + are many tags. + + The following variables control how individual refs are displayed. +If you change one of these variables (especially the "%c" part), then +you should also change the others to keep things aligned. The following +%-sequences are supported: + + • ‘%a’ Number of commits this ref has over the one we compare to. + • ‘%b’ Number of commits the ref we compare to has over this one. + • ‘%c’ Number of commits this ref has over the one we compare to. + For the ref which all other refs are compared this is instead "@", + if it is the current branch, or "#" otherwise. + • ‘%C’ For the ref which all other refs are compared this is "@", if + it is the current branch, or "#" otherwise. For all other refs " + ". + • ‘%h’ Hash of this ref’s tip. + • ‘%m’ Commit summary of the tip of this ref. + • ‘%n’ Name of this ref. + • ‘%u’ Upstream of this local branch. + • ‘%U’ Upstream of this local branch and additional local vs. + upstream information. + + -- User Option: magit-refs-filter-alist + The purpose of this option is to forgo displaying certain refs + based on their name. If you want to not display any refs of a + certain type, then you should remove the appropriate function from + ‘magit-refs-sections-hook’ instead. + + This alist controls which tags and branches are omitted from being + displayed in ‘magit-refs-mode’ buffers. If it is ‘nil’, then all + refs are displayed (subject to ‘magit-refs-sections-hook’). + + All keys are tried in order until one matches. Then its value is + used and subsequent elements are ignored. If the value is non-nil, + then the reference is displayed, otherwise it is not. If no + element matches, then the reference is displayed. + + A key can either be a regular expression that the refname has to + match, or a function that takes the refname as only argument and + returns a boolean. A remote branch such as "origin/master" is + displayed as just "master", however for this comparison the former + is used. + +‘<RET>’ (‘magit-visit-ref’) + This command visits the reference or revision at point in another + buffer. If there is no revision at point or with a prefix argument + then it prompts for a revision. + + This command behaves just like ‘magit-show-commit’ as described + above, except if point is on a reference in a ‘magit-refs-mode’ + buffer, in which case the behavior may be different, but only if + you have customized the option ‘magit-visit-ref-behavior’. + + -- User Option: magit-visit-ref-behavior + This option controls how ‘magit-visit-ref’ behaves in + ‘magit-refs-mode’ buffers. + + By default ‘magit-visit-ref’ behaves like ‘magit-show-commit’, in + all buffers, including ‘magit-refs-mode’ buffers. When the type of + the section at point is ‘commit’ then "RET" is bound to + ‘magit-show-commit’, and when the type is either ‘branch’ or ‘tag’ + then it is bound to ‘magit-visit-ref’. + + "RET" is one of Magit’s most essential keys and at least by default + it should behave consistently across all of Magit, especially + because users quickly learn that it does something very harmless; + it shows more information about the thing at point in another + buffer. + + However "RET" used to behave differently in ‘magit-refs-mode’ + buffers, doing surprising things, some of which cannot really be + described as "visit this thing". If you’ve grown accustomed this + behavior, you can restore it by adding one or more of the below + symbols to the value of this option. But keep in mind that by + doing so you don’t only introduce inconsistencies, you also lose + some functionality and might have to resort to ‘M-x + magit-show-commit’ to get it back. + + ‘magit-visit-ref’ looks for these symbols in the order in which + they are described here. If the presence of a symbol applies to + the current situation, then the symbols that follow do not affect + the outcome. + + • ‘focus-on-ref’ + + With a prefix argument update the buffer to show commit counts + and lists of cherry commits relative to the reference at point + instead of relative to the current buffer or ‘HEAD’. + + Instead of adding this symbol, consider pressing "C-u y o + RET". + + • ‘create-branch’ + + If point is on a remote branch, then create a new local branch + with the same name, use the remote branch as its upstream, and + then check out the local branch. + + Instead of adding this symbol, consider pressing "b c RET + RET", like you would do in other buffers. + + • ‘checkout-any’ + + Check out the reference at point. If that reference is a tag + or a remote branch, then this results in a detached ‘HEAD’. + + Instead of adding this symbol, consider pressing "b b RET", + like you would do in other buffers. + + • ‘checkout-branch’ + + Check out the local branch at point. + + Instead of adding this symbol, consider pressing "b b RET", + like you would do in other buffers. + +* Menu: + +* References Sections:: + + +File: magit.info, Node: References Sections, Up: References Buffer + +5.6.1 References Sections +------------------------- + +The contents of references buffers is controlled using the hook +‘magit-refs-sections-hook’. See *note Section Hooks:: to learn about +such hooks and how to customize them. All of the below functions are +members of the default value. Note that it makes much less sense to +customize this hook than it does for the respective hook used for the +status buffer. + + -- User Option: magit-refs-sections-hook + Hook run to insert sections into a references buffer. + + -- Function: magit-insert-local-branches + Insert sections showing all local branches. + + -- Function: magit-insert-remote-branches + Insert sections showing all remote-tracking branches. + + -- Function: magit-insert-tags + Insert sections showing all tags. + + +File: magit.info, Node: Bisecting, Next: Visiting Files and Blobs, Prev: References Buffer, Up: Inspecting + +5.7 Bisecting +============= + +Also see *note (gitman)git-bisect::. + +‘B’ (‘magit-bisect’) + This transient prefix command binds the following suffix commands + and displays them in a temporary buffer until a suffix is invoked. + + When bisecting is not in progress, then the transient features the +following suffix commands. + +‘B B’ (‘magit-bisect-start’) + Start a bisect session. + + Bisecting a bug means to find the commit that introduced it. This + command starts such a bisect session by asking for a known good + commit and a known bad commit. If you’re bisecting a change that + isn’t a regression, you can select alternate terms that are + conceptually more fitting than "bad" and "good", but the infix + arguments to do so are disabled by default. + +‘B s’ (‘magit-bisect-run’) + Bisect automatically by running commands after each step. + + When bisecting in progress, then the transient instead features the +following suffix commands. + +‘B b’ (‘magit-bisect-bad’) + Mark the current commit as bad. Use this after you have asserted + that the commit does contain the bug in question. + +‘B g’ (‘magit-bisect-good’) + Mark the current commit as good. Use this after you have asserted + that the commit does not contain the bug in question. + +‘B m’ (‘magit-bisect-mark’) + Mark the current commit with one of the bisect terms. This command + provides an alternative to ‘magit-bisect-bad’ and + ‘magit-bisect-good’ and is useful when using terms other than "bad" + and "good". This suffix is disabled by default. + +‘B k’ (‘magit-bisect-skip’) + Skip the current commit. Use this if for some reason the current + commit is not a good one to test. This command lets Git choose a + different one. + +‘B r’ (‘magit-bisect-reset’) + After bisecting, cleanup bisection state and return to original + ‘HEAD’. + + By default the status buffer shows information about the ongoing +bisect session. + + -- User Option: magit-bisect-show-graph + This option controls whether a graph is displayed for the log of + commits that still have to be bisected. + + +File: magit.info, Node: Visiting Files and Blobs, Next: Blaming, Prev: Bisecting, Up: Inspecting + +5.8 Visiting Files and Blobs +============================ + +Magit provides several commands that visit a file or blob (the version +of a file that is stored in a certain commit). Actually it provides +several *groups* of such commands and the several *variants* within each +group. + + Also see *note Commands for Buffers Visiting Files::. + +* Menu: + +* General-Purpose Visit Commands:: +* Visiting Files and Blobs from a Diff:: + + +File: magit.info, Node: General-Purpose Visit Commands, Next: Visiting Files and Blobs from a Diff, Up: Visiting Files and Blobs + +5.8.1 General-Purpose Visit Commands +------------------------------------ + +These commands can be used anywhere to open any blob. Currently no keys +are bound to these commands by default, but that is likely to change. + + -- Command: magit-find-file + This command reads a filename and revision from the user and visits + the respective blob in a buffer. The buffer is displayed in the + selected window. + + -- Command: magit-find-file-other-window + This command reads a filename and revision from the user and visits + the respective blob in a buffer. The buffer is displayed in + another window. + + -- Command: magit-find-file-other-frame + This command reads a filename and revision from the user and visits + the respective blob in a buffer. The buffer is displayed in + another frame. + + +File: magit.info, Node: Visiting Files and Blobs from a Diff, Prev: General-Purpose Visit Commands, Up: Visiting Files and Blobs + +5.8.2 Visiting Files and Blobs from a Diff +------------------------------------------ + +These commands can only be used when point is inside a diff. + +‘<RET>’ (‘magit-diff-visit-file’) + This command visits the appropriate version of the file that the + diff at point is about. + + This commands visits the worktree version of the appropriate file. + The location of point inside the diff determines which file is + being visited. The visited version depends on what changes the + diff is about. + + 1. If the diff shows uncommitted changes (i.e., staged or + unstaged changes), then visit the file in the working tree + (i.e., the same "real" file that ‘find-file’ would visit. In + all other cases visit a "blob" (i.e., the version of a file as + stored in some commit). + + 2. If point is on a removed line, then visit the blob for the + first parent of the commit that removed that line, i.e., the + last commit where that line still exists. + + 3. If point is on an added or context line, then visit the blob + that adds that line, or if the diff shows from more than a + single commit, then visit the blob from the last of these + commits. + + In the file-visiting buffer this command goes to the line that + corresponds to the line that point is on in the diff. + + The buffer is displayed in the selected window. With a prefix + argument the buffer is displayed in another window instead. + + -- User Option: magit-diff-visit-previous-blob + This option controls whether ‘magit-diff-visit-file’ may visit the + previous blob. When this is ‘t’ (the default) and point is on a + removed line in a diff for a committed change, then + ‘magit-diff-visit-file’ visits the blob from the last revision + which still had that line. + + Currently this is only supported for committed changes, for staged + and unstaged changes ‘magit-diff-visit-file’ always visits the file + in the working tree. + +‘C-<return>’ (‘magit-diff-visit-file-worktree’) + This command visits the worktree version of the appropriate file. + The location of point inside the diff determines which file is + being visited. Unlike ‘magit-diff-visit-file’ it always visits the + "real" file in the working tree, i.e the "current version" of the + file. + + In the file-visiting buffer this command goes to the line that + corresponds to the line that point is on in the diff. Lines that + were added or removed in the working tree, the index and other + commits in between are automatically accounted for. + + The buffer is displayed in the selected window. With a prefix + argument the buffer is displayed in another window instead. + + Variants of the above two commands exist that instead visit the file +in another window or in another frame. If you prefer such behavior, +then you may want to change the above key bindings, but note that the +above commands also use another window when invoked with a prefix +argument. + + -- Command: magit-diff-visit-file-other-window + -- Command: magit-diff-visit-file-other-frame + -- Command: magit-diff-visit-worktree-file-other-window + -- Command: magit-diff-visit-worktree-file-other-frame + + +File: magit.info, Node: Blaming, Prev: Visiting Files and Blobs, Up: Inspecting + +5.9 Blaming +=========== + +Also see *note (gitman)git-blame::. + + To start blaming, invoke the ‘magit-file-dispatch’ transient prefix +command. When using the default key bindings, that can be done by +pressing ‘C-c M-g’. When using the recommended bindings, this command +is instead bound to ‘C-c f’. Also see *note Global Bindings::. + + The blaming suffix commands can be invoked directly from the file +dispatch transient. However if you want to set an infix argument, then +you have to enter the blaming sub-prefix first. + +‘C-c f B’ (‘magit-blame’) +‘C-c f b’ (‘magit-blame-addition’) +‘C-c f B b’ +‘C-c f r’ (‘magit-blame-removal’) +‘C-c f B r’ +‘C-c f f’ (‘magit-blame-reverse’) +‘C-c f B f’ +‘C-c f e’ (‘magit-blame-echo’) +‘C-c f B e’ +‘C-c f q’ (‘magit-blame-quit’) +‘C-c f B q’ + Each of these commands is documented individually right below, + alongside their default key bindings. The bindings shown above are + the recommended bindings, which you can enable by following the + instructions in *note Global Bindings::. + +‘C-c M-g B’ (‘magit-blame’) + This transient prefix command binds the following suffix commands + along with the appropriate infix arguments and displays them in a + temporary buffer until a suffix is invoked. + + Note that not all of the following suffixes are available at all +times. For example if ‘magit-blame-mode’ is not enabled, then the +command whose purpose is to turn off that mode would not be of any use +and therefore isn’t available. + +‘C-c M-g b’ (‘magit-blame-addition’) +‘C-c M-g B b’ + This command augments each line or chunk of lines in the current + file-visiting or blob-visiting buffer with information about what + commits last touched these lines. + + If the buffer visits a revision of that file, then history up to + that revision is considered. Otherwise, the file’s full history is + considered, including uncommitted changes. + + If Magit-Blame mode is already turned on in the current buffer then + blaming is done recursively, by visiting REVISION:FILE (using + ‘magit-find-file’), where REVISION is a parent of the revision that + added the current line or chunk of lines. + +‘C-c M-g r’ (‘magit-blame-removal’) +‘C-c M-g B r’ + This command augments each line or chunk of lines in the current + blob-visiting buffer with information about the revision that + removes it. It cannot be used in file-visiting buffers. + + Like ‘magit-blame-addition’, this command can be used recursively. + +‘C-c M-g f’ (‘magit-blame-reverse’) +‘C-c M-g B f’ + This command augments each line or chunk of lines in the current + file-visiting or blob-visiting buffer with information about the + last revision in which a line still existed. + + Like ‘magit-blame-addition’, this command can be used recursively. + +‘C-c M-g e’ (‘magit-blame-echo’) +‘C-c M-g B e’ + This command is like ‘magit-blame-addition’ except that it doesn’t + turn on ‘read-only-mode’ and that it initially uses the + visualization style specified by option ‘magit-blame-echo-style’. + + The following key bindings are available when Magit-Blame mode is +enabled and Read-Only mode is not enabled. These commands are also +available in other buffers; here only the behavior is described that is +relevant in file-visiting buffers that are being blamed. + +‘C-c M-g q’ (‘magit-blame-quit’) +‘C-c M-g B q’ + This command turns off Magit-Blame mode. If the buffer was created + during a recursive blame, then it also kills the buffer. + +‘<RET>’ (‘magit-show-commit’) + This command shows the commit that last touched the line at point. + +‘<SPC>’ (‘magit-diff-show-or-scroll-up’) + This command updates the commit buffer. + + This either shows the commit that last touched the line at point in + the appropriate buffer, or if that buffer is already being + displayed in the current frame and if that buffer contains + information about that commit, then the buffer is scrolled up + instead. + +‘<DEL>’ (‘magit-diff-show-or-scroll-down’) + This command updates the commit buffer. + + This either shows the commit that last touched the line at point in + the appropriate buffer, or if that buffer is already being + displayed in the current frame and if that buffer contains + information about that commit, then the buffer is scrolled down + instead. + + The following key bindings are available when both Magit-Blame mode +and Read-Only mode are enabled. + +‘b’ (‘magit-blame’) + See above. + +‘n’ (‘magit-blame-next-chunk’) + This command moves to the next chunk. + +‘N’ (‘magit-blame-next-chunk-same-commit’) + This command moves to the next chunk from the same commit. + +‘p’ (‘magit-blame-previous-chunk’) + This command moves to the previous chunk. + +‘P’ (‘magit-blame-previous-chunk-same-commit’) + This command moves to the previous chunk from the same commit. + +‘q’ (‘magit-blame-quit’) + This command turns off Magit-Blame mode. If the buffer was created + during a recursive blame, then it also kills the buffer. + +‘M-w’ (‘magit-blame-copy-hash’) + This command saves the hash of the current chunk’s commit to the + kill ring. + + When the region is active, the command saves the region’s content + instead of the hash, like ‘kill-ring-save’ would. + +‘c’ (‘magit-blame-cycle-style’) + This command changes how blame information is visualized in the + current buffer by cycling through the styles specified using the + option ‘magit-blame-styles’. + + Blaming is also controlled using the following options. + + -- User Option: magit-blame-styles + This option defines a list of styles used to visualize blame + information. For now see its doc-string to learn more. + + -- User Option: magit-blame-echo-style + This option specifies the blame visualization style used by the + command ‘magit-blame-echo’. This must be a symbol that is used as + the identifier for one of the styles defined in + ‘magit-blame-styles’. + + -- User Option: magit-blame-time-format + This option specifies the format string used to display times when + showing blame information. + + -- User Option: magit-blame-read-only + This option controls whether blaming a buffer also makes + temporarily read-only. + + -- User Option: magit-blame-disable-modes + This option lists incompatible minor-modes that should be disabled + temporarily when a buffer contains blame information. They are + enabled again when the buffer no longer shows blame information. + + -- User Option: magit-blame-goto-chunk-hook + This hook is run when moving between chunks. + + +File: magit.info, Node: Manipulating, Next: Transferring, Prev: Inspecting, Up: Top + +6 Manipulating +************** + +* Menu: + +* Creating Repository:: +* Cloning Repository:: +* Staging and Unstaging:: +* Applying:: +* Committing:: +* Branching:: +* Merging:: +* Resolving Conflicts:: +* Rebasing:: +* Cherry Picking:: +* Resetting:: +* Stashing:: + + +File: magit.info, Node: Creating Repository, Next: Cloning Repository, Up: Manipulating + +6.1 Creating Repository +======================= + +‘I’ (‘magit-init’) + This command initializes a repository and then shows the status + buffer for the new repository. + + If the directory is below an existing repository, then the user has + to confirm that a new one should be created inside. If the + directory is the root of the existing repository, then the user has + to confirm that it should be reinitialized. + + +File: magit.info, Node: Cloning Repository, Next: Staging and Unstaging, Prev: Creating Repository, Up: Manipulating + +6.2 Cloning Repository +====================== + +To clone a remote or local repository use ‘C’, which is bound to the +command ‘magit-clone’. This command either act as a transient prefix +command, which binds several infix arguments and suffix commands, or it +can invoke ‘git clone’ directly, depending on whether a prefix argument +is used and on the value of ‘magit-clone-always-transient’. + + -- User Option: magit-clone-always-transient + This option controls whether the command ‘magit-clone’ always acts + as a transient prefix command, regardless of whether a prefix + argument is used or not. If ‘t’, then that command always acts as + a transient prefix. If ‘nil’, then a prefix argument has to be + used for it to act as a transient. + +‘C’ (‘magit-clone’) + This command either acts as a transient prefix command as described + above or does the same thing as ‘transient-clone-regular’ as + described below. + + If it acts as a transient prefix, then it binds the following + suffix commands and several infix arguments. + +‘C C’ (‘magit-clone-regular’) + This command creates a regular clone of an existing repository. + The repository and the target directory are read from the user. + +‘C s’ (‘magit-clone-shallow’) + This command creates a shallow clone of an existing repository. + The repository and the target directory are read from the user. By + default the depth of the cloned history is a single commit, but + with a prefix argument the depth is read from the user. + +‘C >’ (‘magit-clone-sparse’) + This command creates a clone of an existing repository and + initializes a sparse checkout, avoiding a checkout of the full + working tree. To add more directories, use the + ‘magit-sparse-checkout’ transient (see *note Sparse checkouts::). + +‘C b’ (‘magit-clone-bare’) + This command creates a bare clone of an existing repository. The + repository and the target directory are read from the user. + +‘C m’ (‘magit-clone-mirror’) + This command creates a mirror of an existing repository. The + repository and the target directory are read from the user. + + The following suffixes are disabled by default. See *note +(transient)Enabling and Disabling Suffixes:: for how to enable them. + +‘C d’ (‘magit-clone-shallow-since’) + This command creates a shallow clone of an existing repository. + Only commits that were committed after a date are cloned, which is + read from the user. The repository and the target directory are + also read from the user. + +‘C e’ (‘magit-clone-shallow-exclude’) + This command creates a shallow clone of an existing repository. + This reads a branch or tag from the user. Commits that are + reachable from that are not cloned. The repository and the target + directory are also read from the user. + + -- User Option: magit-clone-set-remote-head + This option controls whether cloning causes the reference + ‘refs/remotes/<remote>/HEAD’ to be created in the clone. The + default is to delete the reference after running ‘git clone’, which + insists on creating it. This is because the reference has not been + found to be particularly useful as it is not automatically updated + when the ‘HEAD’ of the remote changes. Setting this option to ‘t’ + preserves Git’s default behavior of creating the reference. + + -- User Option: magit-clone-set-remote.pushDefault + This option controls whether the value of the Git variable + ‘remote.pushDefault’ is set after cloning. + + • If ‘t’, then it is always set without asking. + • If ‘ask’, then the users are asked every time they clone a + repository. + • If ‘nil’, then it is never set. + + -- User Option: magit-clone-default-directory + This option control the default directory name used when reading + the destination for a cloning operation. + + • If ‘nil’ (the default), then the value of ‘default-directory’ + is used. + • If a directory, then that is used. + • If a function, then that is called with the remote url as the + only argument and the returned value is used. + + -- User Option: magit-clone-name-alist + This option maps regular expressions, which match repository names, + to repository urls, making it possible for users to enter short + names instead of urls when cloning repositories. + + Each element has the form ‘(REGEXP HOSTNAME USER)’. When the user + enters a name when a cloning command asks for a name or url, then + that is looked up in this list. The first element whose REGEXP + matches is used. + + The format specified by option ‘magit-clone-url-format’ is used to + turn the name into an url, using HOSTNAME and the repository name. + If the provided name contains a slash, then that is used. + Otherwise if the name omits the owner of the repository, then the + default user specified in the matched entry is used. + + If USER contains a dot, then it is treated as a Git variable and + the value of that is used as the username. Otherwise it is used as + the username itself. + + -- User Option: magit-clone-url-format + The format specified by this option is used when turning repository + names into urls. ‘%h’ is the hostname and ‘%n’ is the repository + name, including the name of the owner. The value can be a string + (representing a single static format) or an alist with elements + ‘(HOSTNAME . FORMAT)’ mapping hostnames to formats. When an alist + is used, the ‘t’ key represents the default format. + + Example of a single format string: + + (setq magit-clone-url-format + "git@%h:%n.git") + + Example of by-hostname format strings: + + (setq magit-clone-url-format + '(("git.example.com" . "git@%h:~%n") + (nil . "git@%h:%n.git"))) + + -- User Option: magit-post-clone-hook + Hook run after the Git process has successfully finished cloning + the repository. When the hook is called, ‘default-directory’ is + let-bound to the directory where the repository has been cloned. + + +File: magit.info, Node: Staging and Unstaging, Next: Applying, Prev: Cloning Repository, Up: Manipulating + +6.3 Staging and Unstaging +========================= + +Like Git, Magit can of course stage and unstage complete files. Unlike +Git, it also allows users to gracefully un-/stage individual hunks and +even just part of a hunk. To stage individual hunks and parts of hunks +using Git directly, one has to use the very modal and rather clumsy +interface of a ‘git add --interactive’ session. + + With Magit, on the other hand, one can un-/stage individual hunks by +just moving point into the respective section inside a diff displayed in +the status buffer or a separate diff buffer and typing ‘s’ or ‘u’. To +operate on just parts of a hunk, mark the changes that should be +un-/staged using the region and then press the same key that would be +used to un-/stage. To stage multiple files or hunks at once use a +region that starts inside the heading of such a section and ends inside +the heading of a sibling section of the same type. + + Besides staging and unstaging, Magit also provides several other +"apply variants" that can also operate on a file, multiple files at +once, a hunk, multiple hunks at once, and on parts of a hunk. These +apply variants are described in the next section. + + You can also use Ediff to stage and unstage. See *note Ediffing::. + +‘s’ (‘magit-stage’) + Add the change at point to the staging area. + + With a prefix argument and an untracked file (or files) at point, + stage the file but not its content. This makes it possible to + stage only a subset of the new file’s changes. + +‘S’ (‘magit-stage-modified’) + Stage all changes to files modified in the worktree. Stage all new + content of tracked files and remove tracked files that no longer + exist in the working tree from the index also. With a prefix + argument also stage previously untracked (but not ignored) files. + +‘u’ (‘magit-unstage’) + Remove the change at point from the staging area. + + Only staged changes can be unstaged. But by default this command + performs an action that is somewhat similar to unstaging, when it + is called on a committed change: it reverses the change in the + index but not in the working tree. + +‘U’ (‘magit-unstage-all’) + Remove all changes from the staging area. + + -- User Option: magit-unstage-committed + This option controls whether ‘magit-unstage’ "unstages" committed + changes by reversing them in the index but not the working tree. + The alternative is to raise an error. + +‘M-x magit-reverse-in-index’ + This command reverses the committed change at point in the index + but not the working tree. By default no key is bound directly to + this command, but it is indirectly called when ‘u’ + (‘magit-unstage’) is pressed on a committed change. + + This allows extracting a change from ‘HEAD’, while leaving it in + the working tree, so that it can later be committed using a + separate commit. A typical workflow would be: + + 1. Optionally make sure that there are no uncommitted changes. + 2. Visit the ‘HEAD’ commit and navigate to the change that should + not have been included in that commit. + 3. Type ‘u’ (‘magit-unstage’) to reverse it in the index. This + assumes that ‘magit-unstage-committed’ is non-nil. + 4. Type ‘c e’ to extend ‘HEAD’ with the staged changes, including + those that were already staged before. + 5. Optionally stage the remaining changes using ‘s’ or ‘S’ and + then type ‘c c’ to create a new commit. + +‘M-x magit-reset-index’ + Reset the index to some commit. The commit is read from the user + and defaults to the commit at point. If there is no commit at + point, then it defaults to ‘HEAD’. + +* Menu: + +* Staging from File-Visiting Buffers:: + + +File: magit.info, Node: Staging from File-Visiting Buffers, Up: Staging and Unstaging + +6.3.1 Staging from File-Visiting Buffers +---------------------------------------- + +Fine-grained un-/staging has to be done from the status or a diff +buffer, but it’s also possible to un-/stage all changes made to the file +visited in the current buffer right from inside that buffer. + +‘M-x magit-stage-file’ + When invoked inside a file-visiting buffer, then stage all changes + to that file. In a Magit buffer, stage the file at point if any. + Otherwise prompt for a file to be staged. With a prefix argument + always prompt the user for a file, even in a file-visiting buffer + or when there is a file section at point. + +‘M-x magit-unstage-file’ + When invoked inside a file-visiting buffer, then unstage all + changes to that file. In a Magit buffer, unstage the file at point + if any. Otherwise prompt for a file to be unstaged. With a prefix + argument always prompt the user for a file, even in a file-visiting + buffer or when there is a file section at point. + + +File: magit.info, Node: Applying, Next: Committing, Prev: Staging and Unstaging, Up: Manipulating + +6.4 Applying +============ + +Magit provides several "apply variants": stage, unstage, discard, +reverse, and "regular apply". At least when operating on a hunk they +are all implemented using ‘git apply’, which is why they are called +"apply variants". + + • Stage. Apply a change from the working tree to the index. The + change also remains in the working tree. + + • Unstage. Remove a change from the index. The change remains in + the working tree. + + • Discard. On a staged change, remove it from the working tree and + the index. On an unstaged change, remove it from the working tree + only. + + • Reverse. Reverse a change in the working tree. Both committed and + staged changes can be reversed. Unstaged changes cannot be + reversed. Discard them instead. + + • Apply. Apply a change to the working tree. Both committed and + staged changes can be applied. Unstaged changes cannot be applied + - as they already have been applied. + + The previous section described the staging and unstaging commands. +What follows are the commands which implement the remaining apply +variants. + +‘a’ (‘magit-apply’) + Apply the change at point to the working tree. + + With a prefix argument fallback to a 3-way merge. Doing so causes + the change to be applied to the index as well. + +‘k’ (‘magit-discard’) + Remove the change at point from the working tree. + + On a hunk or file with unresolved conflicts prompt which side to + keep (while discarding the other). If point is within the text of + a side, then keep that side without prompting. + +‘v’ (‘magit-reverse’) + Reverse the change at point in the working tree. + + With a prefix argument fallback to a 3-way merge. Doing so causes + the change to be applied to the index as well. + + With a prefix argument all apply variants attempt a 3-way merge when +appropriate (i.e., when ‘git apply’ is used internally). + + +File: magit.info, Node: Committing, Next: Branching, Prev: Applying, Up: Manipulating + +6.5 Committing +============== + +When the user initiates a commit, Magit calls ‘git commit’ without any +arguments, so Git has to get it from the user. It creates the file +‘.git/COMMIT_EDITMSG’ and then opens that file in an editor. Magit +arranges for that editor to be the Emacsclient. Once the user finishes +the editing session, the Emacsclient exits and Git creates the commit +using the file’s content as message. + +* Menu: + +* Initiating a Commit:: +* Editing Commit Messages:: + + +File: magit.info, Node: Initiating a Commit, Next: Editing Commit Messages, Up: Committing + +6.5.1 Initiating a Commit +------------------------- + +Also see *note (gitman)git-commit::. + +‘c’ (‘magit-commit’) + This transient prefix command binds the following suffix commands + along with the appropriate infix arguments and displays them in a + temporary buffer until a suffix is invoked. + +‘c c’ (‘magit-commit-create’) + Create a new commit on ‘HEAD’. With a prefix argument amend to the + commit at ‘HEAD’ instead. + +‘c a’ (‘magit-commit-amend’) + Amend the last commit. + +‘c e’ (‘magit-commit-extend’) + Amend the last commit, without editing the message. With a prefix + argument keep the committer date, otherwise change it. The option + ‘magit-commit-extend-override-date’ can be used to inverse the + meaning of the prefix argument. + + Non-interactively respect the optional OVERRIDE-DATE argument and + ignore the option. + +‘c w’ (‘magit-commit-reword’) + Reword the last commit, ignoring staged changes. With a prefix + argument keep the committer date, otherwise change it. The option + ‘magit-commit-reword-override-date’ can be used to inverse the + meaning of the prefix argument. + + Non-interactively respect the optional OVERRIDE-DATE argument and + ignore the option. + +‘c f’ (‘magit-commit-fixup’) + Create a fixup commit. + + With a prefix argument the target commit has to be confirmed. + Otherwise the commit at point may be used without confirmation + depending on the value of option ‘magit-commit-squash-confirm’. + +‘c F’ (‘magit-commit-instant-fixup’) + Create a fixup commit and instantly rebase. + +‘c s’ (‘magit-commit-squash’) + Create a squash commit, without editing the squash message. + + With a prefix argument the target commit has to be confirmed. + Otherwise the commit at point may be used without confirmation + depending on the value of option ‘magit-commit-squash-confirm’. + +‘c S’ (‘magit-commit-instant-squash’) + Create a squash commit and instantly rebase. + +‘c A’ (‘magit-commit-augment’) + Create a squash commit, editing the squash message. + + With a prefix argument the target commit has to be confirmed. + Otherwise the commit at point may be used without confirmation + depending on the value of option ‘magit-commit-squash-confirm’. + + -- User Option: magit-commit-ask-to-stage + Whether to ask to stage all unstaged changes when committing and + nothing is staged. + + -- User Option: magit-commit-show-diff + Whether the relevant diff is automatically shown when committing. + + -- User Option: magit-commit-extend-override-date + Whether using ‘magit-commit-extend’ changes the committer date. + + -- User Option: magit-commit-reword-override-date + Whether using ‘magit-commit-reword’ changes the committer date. + + -- User Option: magit-commit-squash-confirm + Whether the commit targeted by squash and fixup has to be + confirmed. When non-nil then the commit at point (if any) is used + as default choice. Otherwise it has to be confirmed. This option + only affects ‘magit-commit-squash’ and ‘magit-commit-fixup’. The + "instant" variants always require confirmation because making an + error while using those is harder to recover from. + + -- User Option: magit-post-commit-hook + Hook run after creating a commit without the user editing a + message. + + This hook is run by ‘magit-refresh’ if ‘this-command’ is a member + of ‘magit-post-commit-hook-commands’. This only includes commands + named ‘magit-commit-*’ that do *not* require that the user edits + the commit message in a buffer. + + Also see ‘git-commit-post-finish-hook’. + + -- User Option: magit-commit-diff-inhibit-same-window + Whether to inhibit use of same window when showing diff while + committing. + + When writing a commit, then a diff of the changes to be committed + is automatically shown. The idea is that the diff is shown in a + different window of the same frame and for most users that just + works. In other words most users can completely ignore this option + because its value doesn’t make a difference for them. + + However for users who configured Emacs to never create a new window + even when the package explicitly tries to do so, then displaying + two new buffers necessarily means that the first is immediately + replaced by the second. In our case the message buffer is + immediately replaced by the diff buffer, which is of course highly + undesirable. + + A workaround is to suppress this user configuration in this + particular case. Users have to explicitly opt-in by toggling this + option. We cannot enable the workaround unconditionally because + that again causes issues for other users: if the frame is too tiny + or the relevant settings too aggressive, then the diff buffer would + end up being displayed in a new frame. + + Also see <https://github.com/magit/magit/issues/4132>. + + +File: magit.info, Node: Editing Commit Messages, Prev: Initiating a Commit, Up: Committing + +6.5.2 Editing Commit Messages +----------------------------- + +After initiating a commit as described in the previous section, two new +buffers appear. One shows the changes that are about to be committed, +while the other is used to write the message. + + Commit messages are edited in an edit session - in the background +‘git’ is waiting for the editor, in our case ‘emacsclient’, to save the +commit message in a file (in most cases ‘.git/COMMIT_EDITMSG’) and then +return. If the editor returns with a non-zero exit status then ‘git’ +does not create the commit. So the most important commands are those +for finishing and aborting the commit. + +‘C-c C-c’ (‘with-editor-finish’) + Finish the current editing session by returning with exit code 0. + Git then creates the commit using the message it finds in the file. + +‘C-c C-k’ (‘with-editor-cancel’) + Cancel the current editing session by returning with exit code 1. + Git then cancels the commit, but leaves the file untouched. + + In addition to being used by ‘git commit’, messages may also be +stored in a ring that persists until Emacs is closed. By default the +message is stored at the beginning and the end of an edit session +(regardless of whether the session is finished successfully or was +canceled). It is sometimes useful to bring back messages from that +ring. + +‘C-c M-s’ (‘git-commit-save-message’) + Save the current buffer content to the commit message ring. + +‘M-p’ (‘git-commit-prev-message’) + Cycle backward through the commit message ring, after saving the + current message to the ring. With a numeric prefix ARG, go back + ARG comments. + +‘M-n’ (‘git-commit-next-message’) + Cycle forward through the commit message ring, after saving the + current message to the ring. With a numeric prefix ARG, go back + ARG comments. + + By default the diff for the changes that are about to be committed +are automatically shown when invoking the commit. To prevent that, +remove ‘magit-commit-diff’ from ‘server-switch-hook’. + + When amending to an existing commit it may be useful to show either +the changes that are about to be added to that commit or to show those +changes alongside those that have already been committed. + +‘C-c C-d’ (‘magit-diff-while-committing’) + While committing, show the changes that are about to be committed. + While amending, invoking the command again toggles between showing + just the new changes or all the changes that will be committed. + +* Menu: + +* Using the Revision Stack:: +* Commit Pseudo Headers:: +* Commit Mode and Hooks:: +* Commit Message Conventions:: + + +File: magit.info, Node: Using the Revision Stack, Next: Commit Pseudo Headers, Up: Editing Commit Messages + +Using the Revision Stack +........................ + +‘C-c C-w’ (‘magit-pop-revision-stack’) + This command inserts a representation of a revision into the + current buffer. It can be used inside buffers used to write commit + messages but also in other buffers such as buffers used to edit + emails or ChangeLog files. + + By default this command pops the revision which was last added to + the ‘magit-revision-stack’ and inserts it into the current buffer + according to ‘magit-pop-revision-stack-format’. Revisions can be + put on the stack using ‘magit-copy-section-value’ and + ‘magit-copy-buffer-revision’. + + If the stack is empty or with a prefix argument it instead reads a + revision in the minibuffer. By using the minibuffer history this + allows selecting an item which was popped earlier or to insert an + arbitrary reference or revision without first pushing it onto the + stack. + + When reading the revision from the minibuffer, then it might not be + possible to guess the correct repository. When this command is + called inside a repository (e.g., while composing a commit + message), then that repository is used. Otherwise (e.g., while + composing an email) then the repository recorded for the top + element of the stack is used (even though we insert another + revision). If not called inside a repository and with an empty + stack, or with two prefix arguments, then read the repository in + the minibuffer too. + + -- User Option: magit-pop-revision-stack-format + This option controls how the command ‘magit-pop-revision-stack’ + inserts a revision into the current buffer. + + The entries on the stack have the format ‘(HASH TOPLEVEL)’ and this + option has the format ‘(POINT-FORMAT EOB-FORMAT INDEX-REGEXP)’, all + of which may be nil or a string (though either one of EOB-FORMAT or + POINT-FORMAT should be a string, and if INDEX-REGEXP is non-nil, + then the two formats should be too). + + First INDEX-REGEXP is used to find the previously inserted entry, + by searching backward from point. The first submatch must match + the index number. That number is incremented by one, and becomes + the index number of the entry to be inserted. If you don’t want to + number the inserted revisions, then use nil for INDEX-REGEXP. + + If INDEX-REGEXP is non-nil then both POINT-FORMAT and EOB-FORMAT + should contain \"%N\", which is replaced with the number that was + determined in the previous step. + + Both formats, if non-nil and after removing %N, are then expanded + using ‘git show --format=FORMAT ...’ inside TOPLEVEL. + + The expansion of POINT-FORMAT is inserted at point, and the + expansion of EOB-FORMAT is inserted at the end of the buffer (if + the buffer ends with a comment, then it is inserted right before + that). + + +File: magit.info, Node: Commit Pseudo Headers, Next: Commit Mode and Hooks, Prev: Using the Revision Stack, Up: Editing Commit Messages + +Commit Pseudo Headers +..................... + +Some projects use pseudo headers in commit messages. Magit colorizes +such headers and provides some commands to insert such headers. + + -- User Option: git-commit-known-pseudo-headers + A list of Git pseudo headers to be highlighted. + +‘C-c C-i’ (‘git-commit-insert-pseudo-header’) + Insert a commit message pseudo header. + +‘C-c C-a’ (‘git-commit-ack’) + Insert a header acknowledging that you have looked at the commit. + +‘C-c C-r’ (‘git-commit-review’) + Insert a header acknowledging that you have reviewed the commit. + +‘C-c C-s’ (‘git-commit-signoff’) + Insert a header to sign off the commit. + +‘C-c C-t’ (‘git-commit-test’) + Insert a header acknowledging that you have tested the commit. + +‘C-c C-o’ (‘git-commit-cc’) + Insert a header mentioning someone who might be interested. + +‘C-c C-p’ (‘git-commit-reported’) + Insert a header mentioning the person who reported the issue being + fixed by the commit. + +‘C-c M-i’ (‘git-commit-suggested’) + Insert a header mentioning the person who suggested the change. + + +File: magit.info, Node: Commit Mode and Hooks, Next: Commit Message Conventions, Prev: Commit Pseudo Headers, Up: Editing Commit Messages + +Commit Mode and Hooks +..................... + +‘git-commit-mode’ is a minor mode that is only used to establish certain +key bindings. This makes it possible to use an arbitrary major mode in +buffers used to edit commit messages. It is even possible to use +different major modes in different repositories, which is useful when +different projects impose different commit message conventions. + + -- User Option: git-commit-major-mode + The value of this option is the major mode used to edit Git commit + messages. + + Because ‘git-commit-mode’ is a minor mode, we don’t use its mode hook +to setup the buffer, except for the key bindings. All other setup +happens in the function ‘git-commit-setup’, which among other things +runs the hook ‘git-commit-setup-hook’. + + -- User Option: git-commit-setup-hook + Hook run at the end of ‘git-commit-setup’. + +The following functions are suitable for this hook: + + -- Function: git-commit-save-message + Save the current buffer content to the commit message ring. + + -- Function: git-commit-setup-changelog-support + After this function is called, ChangeLog entries are treated as + paragraphs. + + -- Function: git-commit-turn-on-auto-fill + Turn on ‘auto-fill-mode’. + + -- Function: git-commit-turn-on-flyspell + Turn on Flyspell mode. Also prevent comments from being checked + and finally check current non-comment text. + + -- Function: git-commit-propertize-diff + Propertize the diff shown inside the commit message buffer. Git + inserts such diffs into the commit message template when the + ‘--verbose’ argument is used. ‘magit-commit’ by default does not + offer that argument because the diff that is shown in a separate + buffer is more useful. But some users disagree, which is why this + function exists. + + -- Function: bug-reference-mode + Hyperlink bug references in the buffer. + + -- Function: with-editor-usage-message + Show usage information in the echo area. + + -- User Option: git-commit-post-finish-hook + Hook run after the user finished writing a commit message. + + This hook is only run after pressing ‘C-c C-c’ in a buffer used to + edit a commit message. If a commit is created without the user + typing a message into a buffer, then this hook is not run. + + This hook is not run until the new commit has been created. If + doing so takes Git longer than one second, then this hook isn’t run + at all. For certain commands such as ‘magit-rebase-continue’ this + hook is never run because doing so would lead to a race condition. + + This hook is only run if ‘magit’ is available. + + Also see ‘magit-post-commit-hook’. + + +File: magit.info, Node: Commit Message Conventions, Prev: Commit Mode and Hooks, Up: Editing Commit Messages + +Commit Message Conventions +.......................... + +Git-Commit highlights certain violations of commonly accepted commit +message conventions. Certain violations even cause Git-Commit to ask +you to confirm that you really want to do that. This nagging can of +course be turned off, but the result of doing that usually is that +instead of some code it’s now the human who is reviewing your commits +who has to waste some time telling you to fix your commits. + + -- User Option: git-commit-summary-max-length + The intended maximal length of the summary line of commit messages. + Characters beyond this column are colorized to indicate that this + preference has been violated. + + -- User Option: git-commit-finish-query-functions + List of functions called to query before performing commit. + + The commit message buffer is current while the functions are + called. If any of them returns nil, then the commit is not + performed and the buffer is not killed. The user should then fix + the issue and try again. + + The functions are called with one argument. If it is non-nil then + that indicates that the user used a prefix argument to force + finishing the session despite issues. Functions should usually + honor this wish and return non-nil. + + By default the only member is ‘git-commit-check-style-conventions’. + + -- Function: git-commit-check-style-conventions + This function checks for violations of certain basic style + conventions. For each violation it asks users if they want to + proceed anyway. + + -- User Option: git-commit-style-convention-checks + This option controls what conventions the function by the same name + tries to enforce. The value is a list of self-explanatory symbols + identifying certain conventions; ‘non-empty-second-line’ and + ‘overlong-summary-line’. + + +File: magit.info, Node: Branching, Next: Merging, Prev: Committing, Up: Manipulating + +6.6 Branching +============= + +* Menu: + +* The Two Remotes:: +* Branch Commands:: +* Branch Git Variables:: +* Auxiliary Branch Commands:: + + +File: magit.info, Node: The Two Remotes, Next: Branch Commands, Up: Branching + +6.6.1 The Two Remotes +--------------------- + +The upstream branch of some local branch is the branch into which the +commits on that local branch should eventually be merged, usually +something like ‘origin/master’. For the ‘master’ branch itself the +upstream branch and the branch it is being pushed to, are usually the +same remote branch. But for a feature branch the upstream branch and +the branch it is being pushed to should differ. + + The commits on feature branches too should _eventually_ end up in a +remote branch such as ‘origin/master’ or ‘origin/maint’. Such a branch +should therefore be used as the upstream. But feature branches +shouldn’t be pushed directly to such branches. Instead a feature branch +‘my-feature’ is usually pushed to ‘my-fork/my-feature’ or if you are a +contributor ‘origin/my-feature’. After the new feature has been +reviewed, the maintainer merges the feature into ‘master’. And finally +‘master’ (not ‘my-feature’ itself) is pushed to ‘origin/master’. + + But new features seldom are perfect on the first try, and so feature +branches usually have to be reviewed, improved, and re-pushed several +times. Pushing should therefore be easy to do, and for that reason many +Git users have concluded that it is best to use the remote branch to +which the local feature branch is being pushed as its upstream. + + But luckily Git has long ago gained support for a push-remote which +can be configured separately from the upstream branch, using the +variables ‘branch.<name>.pushRemote’ and ‘remote.pushDefault’. So we no +longer have to choose which of the two remotes should be used as "the +remote". + + Each of the fetching, pulling, and pushing transient commands +features three suffix commands that act on the current branch and some +other branch. Of these, ‘p’ is bound to a command which acts on the +push-remote, ‘u’ is bound to a command which acts on the upstream, and +‘e’ is bound to a command which acts on any other branch. The status +buffer shows unpushed and unpulled commits for both the push-remote and +the upstream. + + It’s fairly simple to configure these two remotes. The values of all +the variables that are related to fetching, pulling, and pushing (as +well as some other branch-related variables) can be inspected and +changed using the command ‘magit-branch-configure’, which is available +from many transient prefix commands that deal with branches. It is also +possible to set the push-remote or upstream while pushing (see *note +Pushing::). + + +File: magit.info, Node: Branch Commands, Next: Branch Git Variables, Prev: The Two Remotes, Up: Branching + +6.6.2 Branch Commands +--------------------- + +The transient prefix command ‘magit-branch’ is used to create and +checkout branches, and to make changes to existing branches. It is not +used to fetch, pull, merge, rebase, or push branches, i.e., this command +deals with branches themselves, not with the commits reachable from +them. Those features are available from separate transient command. + +‘b’ (‘magit-branch’) + This transient prefix command binds the following suffix commands + and displays them in a temporary buffer until a suffix is invoked. + + By default it also binds and displays the values of some + branch-related Git variables and allows changing their values. + + -- User Option: magit-branch-direct-configure + This option controls whether the transient command ‘magit-branch’ + can be used to directly change the values of Git variables. This + defaults to ‘t’ (to avoid changing key bindings). When set to + ‘nil’, then no variables are displayed by that transient command, + and its suffix command ‘magit-branch-configure’ has to be used + instead to view and change branch related variables. + +‘b C’ (‘magit-branch-configure’) +‘f C’ +‘F C’ +‘P C’ + This transient prefix command binds commands that set the value of + branch-related variables and displays them in a temporary buffer + until the transient is exited. + + With a prefix argument, this command always prompts for a branch. + + Without a prefix argument this depends on whether it was invoked as + a suffix of ‘magit-branch’ and on the + ‘magit-branch-direct-configure’ option. If ‘magit-branch’ already + displays the variables for the current branch, then it isn’t useful + to invoke another transient that displays them for the same branch. + In that case this command prompts for a branch. + + The variables are described in *note Branch Git Variables::. + +‘b b’ (‘magit-checkout’) + Checkout a revision read in the minibuffer and defaulting to the + branch or arbitrary revision at point. If the revision is a local + branch then that becomes the current branch. If it is something + else then ‘HEAD’ becomes detached. Checkout fails if the working + tree or the staging area contain changes. + +‘b n’ (‘magit-branch-create’) + Create a new branch. The user is asked for a branch or arbitrary + revision to use as the starting point of the new branch. When a + branch name is provided, then that becomes the upstream branch of + the new branch. The name of the new branch is also read in the + minibuffer. + + Also see option ‘magit-branch-prefer-remote-upstream’. + +‘b c’ (‘magit-branch-and-checkout’) + This command creates a new branch like ‘magit-branch-create’, but + then also checks it out. + + Also see option ‘magit-branch-prefer-remote-upstream’. + +‘b l’ (‘magit-branch-checkout’) + This command checks out an existing or new local branch. It reads + a branch name from the user offering all local branches and a + subset of remote branches as candidates. Remote branches for which + a local branch by the same name exists are omitted from the list of + candidates. The user can also enter a completely new branch name. + + • If the user selects an existing local branch, then that is + checked out. + + • If the user selects a remote branch, then it creates and + checks out a new local branch with the same name, and + configures the selected remote branch as the push target. + + • If the user enters a new branch name, then it creates and + checks that out, after also reading the starting-point from + the user. + + In the latter two cases the upstream is also set. Whether it is + set to the chosen starting point or something else depends on the + value of ‘magit-branch-adjust-remote-upstream-alist’. + +‘b s’ (‘magit-branch-spinoff’) + This command creates and checks out a new branch starting at and + tracking the current branch. That branch in turn is reset to the + last commit it shares with its upstream. If the current branch has + no upstream or no unpushed commits, then the new branch is created + anyway and the previously current branch is not touched. + + This is useful to create a feature branch after work has already + begun on the old branch (likely but not necessarily "master"). + + If the current branch is a member of the value of option + ‘magit-branch-prefer-remote-upstream’ (which see), then the current + branch will be used as the starting point as usual, but the + upstream of the starting-point may be used as the upstream of the + new branch, instead of the starting-point itself. + + If optional FROM is non-nil, then the source branch is reset to + ‘FROM~’, instead of to the last commit it shares with its upstream. + Interactively, FROM is only ever non-nil, if the region selects + some commits, and among those commits, FROM is the commit that is + the fewest commits ahead of the source branch. + + The commit at the other end of the selection actually does not + matter, all commits between FROM and ‘HEAD’ are moved to the new + branch. If FROM is not reachable from ‘HEAD’ or is reachable from + the source branch’s upstream, then an error is raised. + +‘b S’ (‘magit-branch-spinout’) + This command behaves like ‘magit-branch-spinoff’, except that it + does not change the current branch. If there are any uncommitted + changes, then it behaves exactly like ‘magit-branch-spinoff’. + +‘b x’ (‘magit-branch-reset’) + This command resets a branch, defaulting to the branch at point, to + the tip of another branch or any other commit. + + When the branch being reset is the current branch, then a hard + reset is performed. If there are any uncommitted changes, then the + user has to confirm the reset because those changes would be lost. + + This is useful when you have started work on a feature branch but + realize it’s all crap and want to start over. + + When resetting to another branch and a prefix argument is used, + then the target branch is set as the upstream of the branch that is + being reset. + +‘b k’ (‘magit-branch-delete’) + Delete one or multiple branches. If the region marks multiple + branches, then offer to delete those. Otherwise, prompt for a + single branch to be deleted, defaulting to the branch at point. + + Require confirmation when deleting branches is dangerous in some + way. Option ‘magit-no-confirm’ can be customized to not require + confirmation in certain cases. See its docstring to learn why + confirmation is required by default in certain cases or if a prompt + is confusing. + +‘b m’ (‘magit-branch-rename’) + Rename a branch. The branch and the new name are read in the + minibuffer. With prefix argument the branch is renamed even if + that name conflicts with an existing branch. + + -- User Option: magit-branch-read-upstream-first + When creating a branch, whether to read the upstream branch before + the name of the branch that is to be created. The default is ‘t’, + and I recommend you leave it at that. + + -- User Option: magit-branch-prefer-remote-upstream + This option specifies whether remote upstreams are favored over + local upstreams when creating new branches. + + When a new branch is created, then the branch, commit, or stash at + point is suggested as the starting point of the new branch, or if + there is no such revision at point the current branch. In either + case the user may choose another starting point. + + If the chosen starting point is a branch, then it may also be set + as the upstream of the new branch, depending on the value of the + Git variable ‘branch.autoSetupMerge’. By default this is done for + remote branches, but not for local branches. + + You might prefer to always use some remote branch as upstream. If + the chosen starting point is (1) a local branch, (2) whose name + matches a member of the value of this option, (3) the upstream of + that local branch is a remote branch with the same name, and (4) + that remote branch can be fast-forwarded to the local branch, then + the chosen branch is used as starting point, but its own upstream + is used as the upstream of the new branch. + + Members of this option’s value are treated as branch names that + have to match exactly unless they contain a character that makes + them invalid as a branch name. Recommended characters to use to + trigger interpretation as a regexp are "*" and "^". Some other + characters which you might expect to be invalid, actually are not, + e.g., ".+$" are all perfectly valid. More precisely, if ‘git + check-ref-format --branch STRING’ exits with a non-zero status, + then treat STRING as a regexp. + + Assuming the chosen branch matches these conditions you would end + up with with e.g.: + + feature --upstream--> origin/master + + instead of + + feature --upstream--> master --upstream--> origin/master + + Which you prefer is a matter of personal preference. If you do + prefer the former, then you should add branches such as ‘master’, + ‘next’, and ‘maint’ to the value of this options. + + -- User Option: magit-branch-adjust-remote-upstream-alist + The value of this option is an alist of branches to be used as the + upstream when branching a remote branch. + + When creating a local branch from an ephemeral branch located on a + remote, e.g., a feature or hotfix branch, then that remote branch + should usually not be used as the upstream branch, since the + push-remote already allows accessing it and having both the + upstream and the push-remote reference the same related branch + would be wasteful. Instead a branch like "maint" or "master" + should be used as the upstream. + + This option allows specifying the branch that should be used as the + upstream when branching certain remote branches. The value is an + alist of the form ‘((UPSTREAM . RULE)...)’. The first matching + element is used, the following elements are ignored. + + UPSTREAM is the branch to be used as the upstream for branches + specified by RULE. It can be a local or a remote branch. + + RULE can either be a regular expression, matching branches whose + upstream should be the one specified by UPSTREAM. Or it can be a + list of the only branches that should *not* use UPSTREAM; all other + branches will. Matching is done after stripping the remote part of + the name of the branch that is being branched from. + + If you use a finite set of non-ephemeral branches across all your + repositories, then you might use something like: + + (("origin/master" . ("master" "next" "maint"))) + + Or if the names of all your ephemeral branches contain a slash, at + least in some repositories, then a good value could be: + + (("origin/master" . "/")) + + Of course you can also fine-tune: + + (("origin/maint" . "\\`hotfix/") + ("origin/master" . "\\`feature/")) + + UPSTREAM can be a local branch: + + (("master" . ("master" "next" "maint"))) + + Because the main branch is no longer almost always named "master" you +should also account for other common names: + + (("main" . ("main" "master" "next" "maint")) + ("master" . ("main" "master" "next" "maint"))) + + -- Command: magit-branch-orphan + This command creates and checks out a new orphan branch with + contents from a given revision. + + -- Command: magit-branch-or-checkout + This command is a hybrid between ‘magit-checkout’ and + ‘magit-branch-and-checkout’ and is intended as a replacement for + the former in ‘magit-branch’. + + It first asks the user for an existing branch or revision. If the + user input actually can be resolved as a branch or revision, then + it checks that out, just like ‘magit-checkout’ would. + + Otherwise it creates and checks out a new branch using the input as + its name. Before doing so it reads the starting-point for the new + branch. This is similar to what ‘magit-branch-and-checkout’ does. + + To use this command instead of ‘magit-checkout’ add this to your + init file: + + (transient-replace-suffix 'magit-branch 'magit-checkout + '("b" "dwim" magit-branch-or-checkout)) + + +File: magit.info, Node: Branch Git Variables, Next: Auxiliary Branch Commands, Prev: Branch Commands, Up: Branching + +6.6.3 Branch Git Variables +-------------------------- + +These variables can be set from the transient prefix command +‘magit-branch-configure’. By default they can also be set from +‘magit-branch’. See *note Branch Commands::. + + -- Variable: branch.NAME.merge + Together with ‘branch.NAME.remote’ this variable defines the + upstream branch of the local branch named NAME. The value of this + variable is the full reference of the upstream _branch_. + + -- Variable: branch.NAME.remote + Together with ‘branch.NAME.merge’ this variable defines the + upstream branch of the local branch named NAME. The value of this + variable is the name of the upstream _remote_. + + -- Variable: branch.NAME.rebase + This variable controls whether pulling into the branch named NAME + is done by rebasing or by merging the fetched branch. + + • When ‘true’ then pulling is done by rebasing. + • When ‘false’ then pulling is done by merging. + • When undefined then the value of ‘pull.rebase’ is used. The + default of that variable is ‘false’. + + -- Variable: branch.NAME.pushRemote + This variable specifies the remote that the branch named NAME is + usually pushed to. The value has to be the name of an existing + remote. + + It is not possible to specify the name of _branch_ to push the + local branch to. The name of the remote branch is always the same + as the name of the local branch. + + If this variable is undefined but ‘remote.pushDefault’ is defined, + then the value of the latter is used. By default + ‘remote.pushDefault’ is undefined. + + -- Variable: branch.NAME.description + This variable can be used to describe the branch named NAME. That + description is used, e.g., when turning the branch into a series of + patches. + + The following variables specify defaults which are used if the above +branch-specific variables are not set. + + -- Variable: pull.rebase + This variable specifies whether pulling is done by rebasing or by + merging. It can be overwritten using ‘branch.NAME.rebase’. + + • When ‘true’ then pulling is done by rebasing. + • When ‘false’ (the default) then pulling is done by merging. + + Since it is never a good idea to merge the upstream branch into a + feature or hotfix branch and most branches are such branches, you + should consider setting this to ‘true’, and ‘branch.master.rebase’ + to ‘false’. + + -- Variable: remote.pushDefault + This variable specifies what remote the local branches are usually + pushed to. This can be overwritten per branch using + ‘branch.NAME.pushRemote’. + + The following variables are used during the creation of a branch and +control whether the various branch-specific variables are automatically +set at this time. + + -- Variable: branch.autoSetupMerge + This variable specifies under what circumstances creating a branch + NAME should result in the variables ‘branch.NAME.merge’ and + ‘branch.NAME.remote’ being set according to the starting point used + to create the branch. If the starting point isn’t a branch, then + these variables are never set. + + • When ‘always’ then the variables are set regardless of whether + the starting point is a local or a remote branch. + • When ‘true’ (the default) then the variables are set when the + starting point is a remote branch, but not when it is a local + branch. + • When ‘false’ then the variables are never set. + + -- Variable: branch.autoSetupRebase + This variable specifies whether creating a branch NAME should + result in the variable ‘branch.NAME.rebase’ being set to ‘true’. + + • When ‘always’ then the variable is set regardless of whether + the starting point is a local or a remote branch. + • When ‘local’ then the variable are set when the starting point + is a local branch, but not when it is a remote branch. + • When ‘remote’ then the variable are set when the starting + point is a remote branch, but not when it is a local branch. + • When ‘never’ (the default) then the variable is never set. + + Note that the respective commands always change the repository-local +values. If you want to change the global value, which is used when the +local value is undefined, then you have to do so on the command line, +e.g.: + + git config --global remote.autoSetupMerge always + + For more information about these variables you should also see *note +(gitman)git-config::. Also see *note (gitman)git-branch::. , *note +(gitman)git-checkout::. and *note Pushing::. + + -- User Option: magit-prefer-remote-upstream + This option controls whether commands that read a branch from the + user and then set it as the upstream branch, offer a local or a + remote branch as default completion candidate, when they have the + choice. + + This affects all commands that use ‘magit-read-upstream-branch’ or + ‘magit-read-starting-point’, which includes all commands that + change the upstream and many which create new branches. + + +File: magit.info, Node: Auxiliary Branch Commands, Prev: Branch Git Variables, Up: Branching + +6.6.4 Auxiliary Branch Commands +------------------------------- + +These commands are not available from the transient ‘magit-branch’ by +default. + + -- Command: magit-branch-shelve + This command shelves a branch. This is done by deleting the + branch, and creating a new reference "refs/shelved/BRANCH-NAME" + pointing at the same commit as the branch pointed at. If the + deleted branch had a reflog, then that is preserved as the reflog + of the new reference. + + This is useful if you want to move a branch out of sight, but are + not ready to completely discard it yet. + + -- Command: magit-branch-unshelve + This command unshelves a branch that was previously shelved using + ‘magit-branch-shelve’. This is done by deleting the reference + "refs/shelved/BRANCH-NAME" and creating a branch "BRANCH-NAME" + pointing at the same commit as the deleted reference pointed at. + If the deleted reference had a reflog, then that is restored as the + reflog of the branch. + + +File: magit.info, Node: Merging, Next: Resolving Conflicts, Prev: Branching, Up: Manipulating + +6.7 Merging +=========== + +Also see *note (gitman)git-merge::. For information on how to resolve +merge conflicts see the next section. + +‘m’ (‘magit-merge’) + This transient prefix command binds the following suffix commands + along with the appropriate infix arguments and displays them in a + temporary buffer until a suffix is invoked. + + When no merge is in progress, then the transient features the +following suffix commands. + +‘m m’ (‘magit-merge-plain’) + This command merges another branch or an arbitrary revision into + the current branch. The branch or revision to be merged is read in + the minibuffer and defaults to the branch at point. + + Unless there are conflicts or a prefix argument is used, then the + resulting merge commit uses a generic commit message, and the user + does not get a chance to inspect or change it before the commit is + created. With a prefix argument this does not actually create the + merge commit, which makes it possible to inspect how conflicts were + resolved and to adjust the commit message. + +‘m e’ (‘magit-merge-editmsg’) + This command merges another branch or an arbitrary revision into + the current branch and opens a commit message buffer, so that the + user can make adjustments. The commit is not actually created + until the user finishes with ‘C-c C-c’. + +‘m n’ (‘magit-merge-nocommit’) + This command merges another branch or an arbitrary revision into + the current branch, but does not actually create the merge commit. + The user can then further adjust the merge, even when automatic + conflict resolution succeeded and/or adjust the commit message. + +‘m a’ (‘magit-merge-absorb’) + This command merges another local branch into the current branch + and then removes the former. + + Before the source branch is merged, it is first force pushed to its + push-remote, provided the respective remote branch already exists. + This ensures that the respective pull-request (if any) won’t get + stuck on some obsolete version of the commits that are being + merged. Finally, if ‘magit-branch-pull-request’ was used to create + the merged branch, then the respective remote branch is also + removed. + +‘m i’ (‘magit-merge-into’) + This command merges the current branch into another local branch + and then removes the former. The latter becomes the new current + branch. + + Before the source branch is merged, it is first force pushed to its + push-remote, provided the respective remote branch already exists. + This ensures that the respective pull-request (if any) won’t get + stuck on some obsolete version of the commits that are being + merged. Finally, if ‘magit-branch-pull-request’ was used to create + the merged branch, then the respective remote branch is also + removed. + +‘m s’ (‘magit-merge-squash’) + This command squashes the changes introduced by another branch or + an arbitrary revision into the current branch. This only applies + the changes made by the squashed commits. No information is + preserved that would allow creating an actual merge commit. + Instead of this command you should probably use a command from the + apply transient. + +‘m p’ (‘magit-merge-preview’) + This command shows a preview of merging another branch or an + arbitrary revision into the current branch. + + Note that commands, that normally change how a diff is displayed, + do not work in buffers created by this command, because the + underlying Git command does not support diff arguments. + + When a merge is in progress, then the transient instead features the +following suffix commands. + +‘m m’ (‘magit-merge’) + After the user resolved conflicts, this command proceeds with the + merge. If some conflicts weren’t resolved, then this command + fails. + +‘m a’ (‘magit-merge-abort’) + This command aborts the current merge operation. + + +File: magit.info, Node: Resolving Conflicts, Next: Rebasing, Prev: Merging, Up: Manipulating + +6.8 Resolving Conflicts +======================= + +When merging branches (or otherwise combining or changing history) +conflicts can occur. If you edited two completely different parts of +the same file in two branches and then merge one of these branches into +the other, then Git can resolve that on its own, but if you edit the +same area of a file, then a human is required to decide how the two +versions, or "sides of the conflict", are to be combined into one. + + Here we can only provide a brief introduction to the subject and +point you toward some tools that can help. If you are new to this, then +please also consult Git’s own documentation as well as other resources. + + If a file has conflicts and Git cannot resolve them by itself, then +it puts both versions into the affected file along with special markers +whose purpose is to denote the boundaries of the unresolved part of the +file and between the different versions. These boundary lines begin +with the strings consisting of seven times the same character, one of +‘<’, ‘|’, ‘=’ and ‘>’, and are followed by information about the source +of the respective versions, e.g.: + + <<<<<<< HEAD + Take the blue pill. + ======= + Take the red pill. + >>>>>>> feature + + In this case you have chosen to take the red pill on one branch and +on another you picked the blue pill. Now that you are merging these two +diverging branches, Git cannot possibly know which pill you want to +take. + + To resolve that conflict you have to create a version of the affected +area of the file by keeping only one of the sides, possibly by editing +it in order to bring in the changes from the other side, remove the +other versions as well as the markers, and then stage the result. A +possible resolution might be: + + Take both pills. + + Often it is useful to see not only the two sides of the conflict but +also the "original" version from before the same area of the file was +modified twice on different branches. Instruct Git to insert that +version as well by running this command once: + + git config --global merge.conflictStyle diff3 + + The above conflict might then have looked like this: + + <<<<<<< HEAD + Take the blue pill. + ||||||| merged common ancestors + Take either the blue or the red pill, but not both. + ======= + Take the red pill. + >>>>>>> feature + + If that were the case, then the above conflict resolution would not +have been correct, which demonstrates why seeing the original version +alongside the conflicting versions can be useful. + + You can perform the conflict resolution completely by hand, but Emacs +also provides some packages that help in the process: Smerge, Ediff +(*note (ediff)Top::), and Emerge (*note (emacs)Emerge::). Magit does +not provide its own tools for conflict resolution, but it does make +using Smerge and Ediff more convenient. (Ediff supersedes Emerge, so +you probably don’t want to use the latter anyway.) + + In the Magit status buffer, files with unresolved conflicts are +listed in the "Unstaged changes" and/or "Staged changes" sections. They +are prefixed with the word "unmerged", which in this context essentially +is a synonym for "unresolved". + + Pressing ‘RET’ while point is on such a file section shows a buffer +visiting that file, turns on ‘smerge-mode’ in that buffer, and places +point inside the first area with conflicts. You should then resolve +that conflict using regular edit commands and/or Smerge commands. + + Unfortunately Smerge does not have a manual, but you can get a list +of commands and binding ‘C-c ^ C-h’ and press ‘RET’ while point is on a +command name to read its documentation. + + Normally you would edit one version and then tell Smerge to keep only +that version. Use ‘C-c ^ m’ (‘smerge-keep-mine’) to keep the ‘HEAD’ +version or ‘C-c ^ o’ (‘smerge-keep-other’) to keep the version that +follows "|||||||". Then use ‘C-c ^ n’ to move to the next conflicting +area in the same file. Once you are done resolving conflicts, return to +the Magit status buffer. The file should now be shown as "modified", no +longer as "unmerged", because Smerge automatically stages the file when +you save the buffer after resolving the last conflict. + + Magit now wraps the mentioned Smerge commands, allowing you to use +these key bindings without having to go to the file-visiting buffer. +Additionally ‘k’ (‘magit-discard’) on a hunk with unresolved conflicts +asks which side to keep or, if point is on a side, then it keeps it +without prompting. Similarly ‘k’ on a unresolved file ask which side to +keep. + + Alternatively you could use Ediff, which uses separate buffers for +the different versions of the file. To resolve conflicts in a file +using Ediff press ‘e’ while point is on such a file in the status +buffer. + + Ediff can be used for other purposes as well. For more information +on how to enter Ediff from Magit, see *note Ediffing::. Explaining how +to use Ediff is beyond the scope of this manual, instead see *note +(ediff)Top::. + + If you are unsure whether you should Smerge or Ediff, then use the +former. It is much easier to understand and use, and except for truly +complex conflicts, the latter is usually overkill. + + +File: magit.info, Node: Rebasing, Next: Cherry Picking, Prev: Resolving Conflicts, Up: Manipulating + +6.9 Rebasing +============ + +Also see *note (gitman)git-rebase::. For information on how to resolve +conflicts that occur during rebases see the preceding section. + +‘r’ (‘magit-rebase’) + This transient prefix command binds the following suffix commands + along with the appropriate infix arguments and displays them in a + temporary buffer until a suffix is invoked. + + When no rebase is in progress, then the transient features the +following suffix commands. + + Using one of these commands _starts_ a rebase sequence. Git might +then stop somewhere along the way, either because you told it to do so, +or because applying a commit failed due to a conflict. When that +happens, then the status buffer shows information about the rebase +sequence which is in progress in a section similar to a log section. +See *note Information About In-Progress Rebase::. + + For information about the upstream and the push-remote, see *note The +Two Remotes::. + +‘r p’ (‘magit-rebase-onto-pushremote’) + This command rebases the current branch onto its push-remote. + + With a prefix argument or when the push-remote is either not + configured or unusable, then let the user first configure the + push-remote. + +‘r u’ (‘magit-rebase-onto-upstream’) + This command rebases the current branch onto its upstream branch. + + With a prefix argument or when the upstream is either not + configured or unusable, then let the user first configure the + upstream. + +‘r e’ (‘magit-rebase-branch’) + This command rebases the current branch onto a branch read in the + minibuffer. All commits that are reachable from head but not from + the selected branch TARGET are being rebased. + +‘r s’ (‘magit-rebase-subset’) + This command starts a non-interactive rebase sequence to transfer + commits from START to ‘HEAD’ onto NEWBASE. START has to be + selected from a list of recent commits. + + By default Magit uses the ‘--autostash’ argument, which causes +uncommitted changes to be stored in a stash before the rebase begins. +These changes are restored after the rebase completes and if possible +the stash is removed. If the stash does not apply cleanly, then the +stash is not removed. In case something goes wrong when resolving the +conflicts, this allows you to start over. + + Even though one of the actions is dedicated to interactive rebases, +the transient also features the infix argument ‘--interactive’. This +can be used to turn one of the other, non-interactive rebase variants +into an interactive rebase. + + For example if you want to clean up a feature branch and at the same +time rebase it onto ‘master’, then you could use ‘r-iu’. But we +recommend that you instead do that in two steps. First use ‘ri’ to +cleanup the feature branch, and then in a second step ‘ru’ to rebase it +onto ‘master’. That way if things turn out to be more complicated than +you thought and/or you make a mistake and have to start over, then you +only have to redo half the work. + + Explicitly enabling ‘--interactive’ won’t have an effect on the +following commands as they always use that argument anyway, even if it +is not enabled in the transient. + +‘r i’ (‘magit-rebase-interactive’) + This command starts an interactive rebase sequence. + +‘r f’ (‘magit-rebase-autosquash’) + This command combines squash and fixup commits with their intended + targets. + +‘r m’ (‘magit-rebase-edit-commit’) + This command starts an interactive rebase sequence that lets the + user edit a single older commit. + +‘r w’ (‘magit-rebase-reword-commit’) + This command starts an interactive rebase sequence that lets the + user reword a single older commit. + +‘r k’ (‘magit-rebase-remove-commit’) + This command removes a single older commit using rebase. + + When a rebase is in progress, then the transient instead features the +following suffix commands. + +‘r r’ (‘magit-rebase-continue’) + This command restart the current rebasing operation. + + In some cases this pops up a commit message buffer for you do edit. + With a prefix argument the old message is reused as-is. + +‘r s’ (‘magit-rebase-skip’) + This command skips the current commit and restarts the current + rebase operation. + +‘r e’ (‘magit-rebase-edit’) + This command lets the user edit the todo list of the current rebase + operation. + +‘r a’ (‘magit-rebase-abort’) + This command aborts the current rebase operation, restoring the + original branch. + +* Menu: + +* Editing Rebase Sequences:: +* Information About In-Progress Rebase:: + + +File: magit.info, Node: Editing Rebase Sequences, Next: Information About In-Progress Rebase, Up: Rebasing + +6.9.1 Editing Rebase Sequences +------------------------------ + +‘C-c C-c’ (‘with-editor-finish’) + Finish the current editing session by returning with exit code 0. + Git then uses the rebase instructions it finds in the file. + +‘C-c C-k’ (‘with-editor-cancel’) + Cancel the current editing session by returning with exit code 1. + Git then forgoes starting the rebase sequence. + +‘<RET>’ (‘git-rebase-show-commit’) + Show the commit on the current line in another buffer and select + that buffer. + +‘<SPC>’ (‘git-rebase-show-or-scroll-up’) + Show the commit on the current line in another buffer without + selecting that buffer. If the revision buffer is already visible + in another window of the current frame, then instead scroll that + window up. + +‘<DEL>’ (‘git-rebase-show-or-scroll-down’) + Show the commit on the current line in another buffer without + selecting that buffer. If the revision buffer is already visible + in another window of the current frame, then instead scroll that + window down. + +‘p’ (‘git-rebase-backward-line’) + Move to previous line. + +‘n’ (‘forward-line’) + Move to next line. + +‘M-p’ (‘git-rebase-move-line-up’) + Move the current commit (or command) up. + +‘M-n’ (‘git-rebase-move-line-down’) + Move the current commit (or command) down. + +‘r’ (‘git-rebase-reword’) + Edit message of commit on current line. + +‘e’ (‘git-rebase-edit’) + Stop at the commit on the current line. + +‘s’ (‘git-rebase-squash’) + Meld commit on current line into previous commit, and edit message. + +‘f’ (‘git-rebase-fixup’) + Meld commit on current line into previous commit, discarding the + current commit’s message. + +‘k’ (‘git-rebase-kill-line’) + Kill the current action line. + +‘c’ (‘git-rebase-pick’) + Use commit on current line. + +‘x’ (‘git-rebase-exec’) + Insert a shell command to be run after the proceeding commit. + + If there already is such a command on the current line, then edit + that instead. With a prefix argument insert a new command even + when there already is one on the current line. With empty input + remove the command on the current line, if any. + +‘b’ (‘git-rebase-break’) + Insert a break action before the current line, instructing Git to + return control to the user. + +‘y’ (‘git-rebase-insert’) + Read an arbitrary commit and insert it below current line. + +‘C-x u’ (‘git-rebase-undo’) + Undo some previous changes. Like ‘undo’ but works in read-only + buffers. + + -- User Option: git-rebase-auto-advance + Whether to move to next line after changing a line. + + -- User Option: git-rebase-show-instructions + Whether to show usage instructions inside the rebase buffer. + + -- User Option: git-rebase-confirm-cancel + Whether confirmation is required to cancel. + + When a rebase is performed with the ‘--rebase-merges’ option, the +sequence will include a few other types of actions and the following +commands become relevant. + +‘l’ (‘git-rebase-label’) + This commands inserts a label action or edits the one at point. + +‘t’ (‘git-rebase-reset’) + This command inserts a reset action or edits the one at point. The + prompt will offer the labels that are currently present in the + buffer. + +‘MM’ (‘git-rebase-merge’) + The command inserts a merge action or edits the one at point. The + prompt will offer the labels that are currently present in the + buffer. Specifying a message to reuse via ‘-c’ or ‘-C’ is not + supported; an editor will always be invoked for the merge. + +‘Mt’ (‘git-rebase-merge-toggle-editmsg’) + This command toggles between the ‘-C’ and ‘-c’ options of the merge + action at point. These options both specify a commit whose message + should be reused. The lower-case variant instructs Git to invoke + the editor when creating the merge, allowing the user to edit the + message. + + +File: magit.info, Node: Information About In-Progress Rebase, Prev: Editing Rebase Sequences, Up: Rebasing + +6.9.2 Information About In-Progress Rebase +------------------------------------------ + +While a rebase sequence is in progress, the status buffer features a +section that lists the commits that have already been applied as well as +the commits that still have to be applied. + + The commits are split in two halves. When rebase stops at a commit, +either because the user has to deal with a conflict or because s/he +explicitly requested that rebase stops at that commit, then point is +placed on the commit that separates the two groups, i.e., on ‘HEAD’. +The commits above it have not been applied yet, while the ‘HEAD’ and the +commits below it have already been applied. In between these two groups +of applied and yet-to-be applied commits, there sometimes is a commit +which has been dropped. + + Each commit is prefixed with a word and these words are additionally +shown in different colors to indicate the status of the commits. + + The following colors are used: + + • Commits that use the same foreground color as the ‘default’ face + have not been applied yet. + + • Yellow commits have some special relationship to the commit rebase + stopped at. This is used for the words "join", "goal", "same" and + "work" (see below). + + • Gray commits have already been applied. + + • The blue commit is the ‘HEAD’ commit. + + • The green commit is the commit the rebase sequence stopped at. If + this is the same commit as ‘HEAD’ (e.g., because you haven’t done + anything yet after rebase stopped at the commit, then this commit + is shown in blue, not green). There can only be a green *and* a + blue commit at the same time, if you create one or more new commits + after rebase stops at a commit. + + • Red commits have been dropped. They are shown for reference only, + e.g., to make it easier to diff. + + Of course these colors are subject to the color-theme in use. + + The following words are used: + + • Commits prefixed with ‘pick’, ‘reword’, ‘edit’, ‘squash’, and + ‘fixup’ have not been applied yet. These words have the same + meaning here as they do in the buffer used to edit the rebase + sequence. See *note Editing Rebase Sequences::. When the + ‘--rebase-merges’ option was specified, ‘reset’, ‘label’, and + ‘merge’ lines may also be present. + + • Commits prefixed with ‘done’ and ‘onto’ have already been applied. + It is possible for such a commit to be the ‘HEAD’, in which case it + is blue. Otherwise it is grey. + + • The commit prefixed with ‘onto’ is the commit on top of which + all the other commits are being re-applied. This commit + itself did not have to be re-applied, it is the commit rebase + did rewind to before starting to re-apply other commits. + + • Commits prefixed with ‘done’ have already been re-applied. + This includes commits that have been re-applied but also new + commits that you have created during the rebase. + + • All other commits, those not prefixed with any of the above words, + are in some way related to the commit at which rebase stopped. + + To determine whether a commit is related to the stopped-at commit + their hashes, trees and patch-ids (1) are being compared. The + commit message is not used for this purpose. + + Generally speaking commits that are related to the stopped-at + commit can have any of the used colors, though not all color/word + combinations are possible. + + Words used for stopped-at commits are: + + • When a commit is prefixed with ‘void’, then that indicates + that Magit knows for sure that all the changes in that commit + have been applied using several new commits. This commit is + no longer reachable from ‘HEAD’, and it also isn’t one of the + commits that will be applied when resuming the session. + + • When a commit is prefixed with ‘join’, then that indicates + that the rebase sequence stopped at that commit due to a + conflict - you now have to join (merge) the changes with what + has already been applied. In a sense this is the commit + rebase stopped at, but while its effect is already in the + index and in the worktree (with conflict markers), the commit + itself has not actually been applied yet (it isn’t the + ‘HEAD’). So it is shown in yellow, like the other commits + that still have to be applied. + + • When a commit is prefixed with ‘stop’ or a _blue_ or _green_ + ‘same’, then that indicates that rebase stopped at this + commit, that it is still applied or has been applied again, + and that at least its patch-id is unchanged. + + • When a commit is prefixed with ‘stop’, then that + indicates that rebase stopped at that commit because you + requested that earlier, and its patch-id is unchanged. + It might even still be the exact same commit. + + • When a commit is prefixed with a _blue_ or _green_ + ‘same’, then that indicates that while its tree or hash + changed, its patch-id did not. If it is blue, then it is + the ‘HEAD’ commit (as always for blue). When it is + green, then it no longer is ‘HEAD’ because other commit + have been created since (but before continuing the + rebase). + + • When a commit is prefixed with ‘goal’, a _yellow_ ‘same,’ or + ‘work’, then that indicates that rebase applied that commit + but that you then reset ‘HEAD’ to an earlier commit (likely to + split it up into multiple commits), and that there are some + uncommitted changes remaining which likely (but not + necessarily) originate from that commit. + + • When a commit is prefixed with ‘goal’, then that + indicates that it is still possible to create a new + commit with the exact same tree (the "goal") without + manually editing any files, by committing the index, or + by staging all changes and then committing that. This is + the case when the original tree still exists in the index + or worktree in untainted form. + + • When a commit is prefixed with a yellow ‘same’, then that + indicates that it is no longer possible to create a + commit with the exact same tree, but that it is still + possible to create a commit with the same patch-id. This + would be the case if you created a new commit with other + changes, but the changes from the original commit still + exist in the index or working tree in untainted form. + + • When a commit is prefixed with ‘work’, then that + indicates that you reset ‘HEAD’ to an earlier commit, and + that there are some staged and/or unstaged changes + (likely, but not necessarily) originating from that + commit. However it is no longer possible to create a new + commit with the same tree or at least the same patch-id + because you have already made other changes. + + • When a commit is prefixed with ‘poof’ or ‘gone’, then that + indicates that rebase applied that commit but that you then + reset ‘HEAD’ to an earlier commit (likely to split it up into + multiple commits), and that there are no uncommitted changes. + + • When a commit is prefixed with ‘poof’, then that + indicates that it is no longer reachable from ‘HEAD’, but + that it has been replaced with one or more commits, which + together have the exact same effect. + + • When a commit is prefixed with ‘gone’, then that + indicates that it is no longer reachable from ‘HEAD’ and + that we also cannot determine whether its changes are + still in effect in one or more new commits. They might + be, but if so, then there must also be other changes + which makes it impossible to know for sure. + + Do not worry if you do not fully understand the above. That’s okay, +you will acquire a good enough understanding through practice. + + For other sequence operations such as cherry-picking, a similar +section is displayed, but they lack some of the features described +above, due to limitations in the git commands used to implement them. +Most importantly these sequences only support "picking" a commit but not +other actions such as "rewording", and they do not keep track of the +commits which have already been applied. + + ---------- Footnotes ---------- + + (1) The patch-id is a hash of the _changes_ introduced by a commit. +It differs from the hash of the commit itself, which is a hash of the +result of applying that change (i.e., the resulting trees and blobs) as +well as author and committer information, the commit message, and the +hashes of the parents of the commit. The patch-id hash on the other +hand is created only from the added and removed lines, even line numbers +and whitespace changes are ignored when calculating this hash. The +patch-ids of two commits can be used to answer the question "Do these +commits make the same change?". + + +File: magit.info, Node: Cherry Picking, Next: Resetting, Prev: Rebasing, Up: Manipulating + +6.10 Cherry Picking +=================== + +Also see *note (gitman)git-cherry-pick::. + +‘A’ (‘magit-cherry-pick’) + This transient prefix command binds the following suffix commands + along with the appropriate infix arguments and displays them in a + temporary buffer until a suffix is invoked. + + When no cherry-pick or revert is in progress, then the transient +features the following suffix commands. + +‘A A’ (‘magit-cherry-copy’) + This command copies COMMITS from another branch onto the current + branch. If the region selects multiple commits, then those are + copied, without prompting. Otherwise the user is prompted for a + commit or range, defaulting to the commit at point. + +‘A a’ (‘magit-cherry-apply’) + This command applies the changes in COMMITS from another branch + onto the current branch. If the region selects multiple commits, + then those are used, without prompting. Otherwise the user is + prompted for a commit or range, defaulting to the commit at point. + + This command also has a top-level binding, which can be invoked + without using the transient by typing ‘a’ at the top-level. + + The following commands not only apply some commits to some branch, +but also remove them from some other branch. The removal is performed +using either ‘git-update-ref’ or if necessary ‘git-rebase’. Both +applying commits as well as removing them using ‘git-rebase’ can lead to +conflicts. If that happens, then these commands abort and you not only +have to resolve the conflicts but also finish the process the same way +you would have to if these commands didn’t exist at all. + +‘A h’ (‘magit-cherry-harvest’) + This command moves the selected COMMITS that must be located on + another BRANCH onto the current branch instead, removing them from + the former. When this command succeeds, then the same branch is + current as before. + + Applying the commits on the current branch or removing them from + the other branch can lead to conflicts. When that happens, then + this command stops and you have to resolve the conflicts and then + finish the process manually. + +‘A d’ (‘magit-cherry-donate’) + This command moves the selected COMMITS from the current branch + onto another existing BRANCH, removing them from the former. When + this command succeeds, then the same branch is current as before. + ‘HEAD’ is allowed to be detached initially. + + Applying the commits on the other branch or removing them from the + current branch can lead to conflicts. When that happens, then this + command stops and you have to resolve the conflicts and then finish + the process manually. + +‘A n’ (‘magit-cherry-spinout’) + This command moves the selected COMMITS from the current branch + onto a new branch BRANCH, removing them from the former. When this + command succeeds, then the same branch is current as before. + + Applying the commits on the other branch or removing them from the + current branch can lead to conflicts. When that happens, then this + command stops and you have to resolve the conflicts and then finish + the process manually. + +‘A s’ (‘magit-cherry-spinoff’) + This command moves the selected COMMITS from the current branch + onto a new branch BRANCH, removing them from the former. When this + command succeeds, then the new branch is checked out. + + Applying the commits on the other branch or removing them from the + current branch can lead to conflicts. When that happens, then this + command stops and you have to resolve the conflicts and then finish + the process manually. + + When a cherry-pick or revert is in progress, then the transient +instead features the following suffix commands. + +‘A A’ (‘magit-sequence-continue’) + Resume the current cherry-pick or revert sequence. + +‘A s’ (‘magit-sequence-skip’) + Skip the stopped at commit during a cherry-pick or revert sequence. + +‘A a’ (‘magit-sequence-abort’) + Abort the current cherry-pick or revert sequence. This discards + all changes made since the sequence started. + +* Menu: + +* Reverting:: + + +File: magit.info, Node: Reverting, Up: Cherry Picking + +6.10.1 Reverting +---------------- + +‘V’ (‘magit-revert’) + This transient prefix command binds the following suffix commands + along with the appropriate infix arguments and displays them in a + temporary buffer until a suffix is invoked. + + When no cherry-pick or revert is in progress, then the transient +features the following suffix commands. + +‘V V’ (‘magit-revert-and-commit’) + Revert a commit by creating a new commit. Prompt for a commit, + defaulting to the commit at point. If the region selects multiple + commits, then revert all of them, without prompting. + +‘V v’ (‘magit-revert-no-commit’) + Revert a commit by applying it in reverse to the working tree. + Prompt for a commit, defaulting to the commit at point. If the + region selects multiple commits, then revert all of them, without + prompting. + + When a cherry-pick or revert is in progress, then the transient +instead features the following suffix commands. + +‘V V’ (‘magit-sequence-continue’) + Resume the current cherry-pick or revert sequence. + +‘V s’ (‘magit-sequence-skip’) + Skip the stopped at commit during a cherry-pick or revert sequence. + +‘V a’ (‘magit-sequence-abort’) + Abort the current cherry-pick or revert sequence. This discards + all changes made since the sequence started. + + +File: magit.info, Node: Resetting, Next: Stashing, Prev: Cherry Picking, Up: Manipulating + +6.11 Resetting +============== + +Also see *note (gitman)git-reset::. + +‘x’ (‘magit-reset-quickly’) + Reset the ‘HEAD’ and index to some commit read from the user and + defaulting to the commit at point, and possibly also reset the + working tree. With a prefix argument reset the working tree + otherwise don’t. + +‘X m’ (‘magit-reset-mixed’) + Reset the ‘HEAD’ and index to some commit read from the user and + defaulting to the commit at point. The working tree is kept as-is. + +‘X s’ (‘magit-reset-soft’) + Reset the ‘HEAD’ to some commit read from the user and defaulting + to the commit at point. The index and the working tree are kept + as-is. + +‘X h’ (‘magit-reset-hard’) + Reset the ‘HEAD’, index, and working tree to some commit read from + the user and defaulting to the commit at point. + +‘X k’ (‘magit-reset-keep’) + Reset the ‘HEAD’, index, and working tree to some commit read from + the user and defaulting to the commit at point. Uncommitted + changes are kept as-is. + +‘X i’ (‘magit-reset-index’) + Reset the index to some commit read from the user and defaulting to + the commit at point. Keep the ‘HEAD’ and working tree as-is, so if + the commit refers to the ‘HEAD’, then this effectively unstages all + changes. + +‘X w’ (‘magit-reset-worktree’) + Reset the working tree to some commit read from the user and + defaulting to the commit at point. Keep the ‘HEAD’ and index + as-is. + +‘X f’ (‘magit-file-checkout’) + Update file in the working tree and index to the contents from a + revision. Both the revision and file are read from the user. + + +File: magit.info, Node: Stashing, Prev: Resetting, Up: Manipulating + +6.12 Stashing +============= + +Also see *note (gitman)git-stash::. + +‘z’ (‘magit-stash’) + This transient prefix command binds the following suffix commands + along with the appropriate infix arguments and displays them in a + temporary buffer until a suffix is invoked. + +‘z z’ (‘magit-stash-both’) + Create a stash of the index and working tree. Untracked files are + included according to infix arguments. One prefix argument is + equivalent to ‘--include-untracked’ while two prefix arguments are + equivalent to ‘--all’. + +‘z i’ (‘magit-stash-index’) + Create a stash of the index only. Unstaged and untracked changes + are not stashed. + +‘z w’ (‘magit-stash-worktree’) + Create a stash of unstaged changes in the working tree. Untracked + files are included according to infix arguments. One prefix + argument is equivalent to ‘--include-untracked’ while two prefix + arguments are equivalent to ‘--all’. + +‘z x’ (‘magit-stash-keep-index’) + Create a stash of the index and working tree, keeping index intact. + Untracked files are included according to infix arguments. One + prefix argument is equivalent to ‘--include-untracked’ while two + prefix arguments are equivalent to ‘--all’. + +‘z Z’ (‘magit-snapshot-both’) + Create a snapshot of the index and working tree. Untracked files + are included according to infix arguments. One prefix argument is + equivalent to ‘--include-untracked’ while two prefix arguments are + equivalent to ‘--all’. + +‘z I’ (‘magit-snapshot-index’) + Create a snapshot of the index only. Unstaged and untracked + changes are not stashed. + +‘z W’ (‘magit-snapshot-worktree’) + Create a snapshot of unstaged changes in the working tree. + Untracked files are included according to infix arguments. One + prefix argument is equivalent to ‘--include-untracked’ while two + prefix arguments are equivalent to ‘--all’-. + +‘z a’ (‘magit-stash-apply’) + Apply a stash to the working tree. + + First try ‘git stash apply --index’, which tries to preserve the + index stored in the stash, if any. This may fail because applying + the stash could result in conflicts and those have to be stored in + the index, making it impossible to also store the stash’s index + there as well. + + If the above failed, then try ‘git stash apply’. This fails (with + or without ‘--index’) if there are any uncommitted changes to files + that are also modified in the stash. + + If both of the above failed, then apply using ‘git apply’. If + there are no conflicting files, use ‘--3way’. If there are + conflicting files, then using ‘--3way’ requires that those files + are staged first, which may be undesirable, so prompt the user + whether to use ‘--3way’ or ‘--reject’. + + Customize ‘magit-no-confirm’ if you want to always use ‘--3way’, + without being prompted. + +‘z p’ (‘magit-stash-pop’) + Apply a stash to the working tree. On complete success (if the + stash can be applied without any conflicts, and while preserving + the stash’s index) then remove the stash from stash list. + + First try ‘git stash pop --index’, which tries to preserve the + index stored in the stash, if any. This may fail because applying + the stash could result in conflicts and those have to be stored in + the index, making it impossible to also store the stash’s index + there as well. + + If the above failed, then try ‘git stash apply’. This fails (with + or without ‘--index’) if there are any uncommitted changes to files + that are also modified in the stash. + + If both of the above failed, then apply using ‘git apply’. If + there are no conflicting files, use ‘--3way’. If there are + conflicting files, then using ‘--3way’ requires that those files + are staged first, which may be undesirable, so prompt the user + whether to use ‘--3way’ or ‘--reject’. + + Customize ‘magit-no-confirm’ if you want to always use ‘--3way’, + without being prompted. + +‘z k’ (‘magit-stash-drop’) + Remove a stash from the stash list. When the region is active, + offer to drop all contained stashes. + +‘z v’ (‘magit-stash-show’) + Show all diffs of a stash in a buffer. + +‘z b’ (‘magit-stash-branch’) + Create and checkout a new branch from an existing stash. The new + branch starts at the commit that was current when the stash was + created. + +‘z B’ (‘magit-stash-branch-here’) + Create and checkout a new branch from an existing stash. Use the + current branch or ‘HEAD’ as the starting-point of the new branch. + Then apply the stash, dropping it if it applies cleanly. + +‘z f’ (‘magit-stash-format-patch’) + Create a patch from STASH. + +‘k’ (‘magit-stash-clear’) + Remove all stashes saved in REF’s reflog by deleting REF. + +‘z l’ (‘magit-stash-list’) + List all stashes in a buffer. + + -- User Option: magit-stashes-margin + This option specifies whether the margin is initially shown in + stashes buffers and how it is formatted. + + The value has the form ‘(INIT STYLE WIDTH AUTHOR AUTHOR-WIDTH)’. + + • If INIT is non-nil, then the margin is shown initially. + • STYLE controls how to format the author or committer date. It + can be one of ‘age’ (to show the age of the commit), + ‘age-abbreviated’ (to abbreviate the time unit to a + character), or a string (suitable for ‘format-time-string’) to + show the actual date. Option + ‘magit-log-margin-show-committer-date’ controls which date is + being displayed. + • WIDTH controls the width of the margin. This exists for + forward compatibility and currently the value should not be + changed. + • AUTHOR controls whether the name of the author is also shown + by default. + • AUTHOR-WIDTH has to be an integer. When the name of the + author is shown, then this specifies how much space is used to + do so. + + +File: magit.info, Node: Transferring, Next: Miscellaneous, Prev: Manipulating, Up: Top + +7 Transferring +************** + +* Menu: + +* Remotes:: +* Fetching:: +* Pulling:: +* Pushing:: +* Plain Patches:: +* Maildir Patches:: + + +File: magit.info, Node: Remotes, Next: Fetching, Up: Transferring + +7.1 Remotes +=========== + +* Menu: + +* Remote Commands:: +* Remote Git Variables:: + + +File: magit.info, Node: Remote Commands, Next: Remote Git Variables, Up: Remotes + +7.1.1 Remote Commands +--------------------- + +The transient prefix command ‘magit-remote’ is used to add remotes and +to make changes to existing remotes. This command only deals with +remotes themselves, not with branches or the transfer of commits. Those +features are available from separate transient commands. + + Also see *note (gitman)git-remote::. + +‘M’ (‘magit-remote’) + This transient prefix command binds the following suffix commands + and displays them in a temporary buffer until a suffix is invoked. + + By default it also binds and displays the values of some + remote-related Git variables and allows changing their values. + + -- User Option: magit-remote-direct-configure + This option controls whether remote-related Git variables are + accessible directly from the transient ‘magit-remote’. + + If ‘t’ (the default) and a local branch is checked out, then + ‘magit-remote’ features the variables for the upstream remote of + that branch, or if ‘HEAD’ is detached, for ‘origin’, provided that + exists. + + If ‘nil’, then ‘magit-remote-configure’ has to be used to do so. + +‘M C’ (‘magit-remote-configure’) + This transient prefix command binds commands that set the value of + remote-related variables and displays them in a temporary buffer + until the transient is exited. + + With a prefix argument, this command always prompts for a remote. + + Without a prefix argument this depends on whether it was invoked as + a suffix of ‘magit-remote’ and on the + ‘magit-remote-direct-configure’ option. If ‘magit-remote’ already + displays the variables for the upstream, then it does not make + sense to invoke another transient that displays them for the same + remote. In that case this command prompts for a remote. + + The variables are described in *note Remote Git Variables::. + +‘M a’ (‘magit-remote-add’) + This command add a remote and fetches it. The remote name and url + are read in the minibuffer. + +‘M r’ (‘magit-remote-rename’) + This command renames a remote. Both the old and the new names are + read in the minibuffer. + +‘M u’ (‘magit-remote-set-url’) + This command changes the url of a remote. Both the remote and the + new url are read in the minibuffer. + +‘M k’ (‘magit-remote-remove’) + This command deletes a remote, read in the minibuffer. + +‘M p’ (‘magit-remote-prune’) + This command removes stale remote-tracking branches for a remote + read in the minibuffer. + +‘M P’ (‘magit-remote-prune-refspecs’) + This command removes stale refspecs for a remote read in the + minibuffer. + + A refspec is stale if there no longer exists at least one branch on + the remote that would be fetched due to that refspec. A stale + refspec is problematic because its existence causes Git to refuse + to fetch according to the remaining non-stale refspecs. + + If only stale refspecs remain, then this command offers to either + delete the remote or to replace the stale refspecs with the default + refspec ("+refs/heads/*:refs/remotes/REMOTE/*"). + + This command also removes the remote-tracking branches that were + created due to the now stale refspecs. Other stale branches are + not removed. + + -- User Option: magit-remote-add-set-remote.pushDefault + This option controls whether the user is asked whether they want to + set ‘remote.pushDefault’ after adding a remote. + + If ‘ask’, then users is always ask. If ‘ask-if-unset’, then the + user is only if the variable isn’t set already. If ‘nil’, then the + user isn’t asked and the variable isn’t set. If the value is a + string, then the variable is set without the user being asked, + provided that the name of the added remote is equal to that string + and the variable isn’t already set. + + +File: magit.info, Node: Remote Git Variables, Prev: Remote Commands, Up: Remotes + +7.1.2 Remote Git Variables +-------------------------- + +These variables can be set from the transient prefix command +‘magit-remote-configure’. By default they can also be set from +‘magit-remote’. See *note Remote Commands::. + + -- Variable: remote.NAME.url + This variable specifies the url of the remote named NAME. It can + have multiple values. + + -- Variable: remote.NAME.fetch + The refspec used when fetching from the remote named NAME. It can + have multiple values. + + -- Variable: remote.NAME.pushurl + This variable specifies the url used for pushing to the remote + named NAME. If it is not specified, then ‘remote.NAME.url’ is used + instead. It can have multiple values. + + -- Variable: remote.NAME.push + The refspec used when pushing to the remote named NAME. It can + have multiple values. + + -- Variable: remote.NAME.tagOpts + This variable specifies what tags are fetched by default. If the + value is ‘--no-tags’ then no tags are fetched. If the value is + ‘--tags’, then all tags are fetched. If this variable has no + value, then only tags are fetched that are reachable from fetched + branches. + + +File: magit.info, Node: Fetching, Next: Pulling, Prev: Remotes, Up: Transferring + +7.2 Fetching +============ + +Also see *note (gitman)git-fetch::. For information about the upstream +and the push-remote, see *note The Two Remotes::. + +‘f’ (‘magit-fetch’) + This transient prefix command binds the following suffix commands + along with the appropriate infix arguments and displays them in a + temporary buffer until a suffix is invoked. + +‘f p’ (‘magit-fetch-from-pushremote’) + This command fetches from the current push-remote. + + With a prefix argument or when the push-remote is either not + configured or unusable, then let the user first configure the + push-remote. + +‘f u’ (‘magit-fetch-from-upstream’) + This command fetch from the upstream of the current branch. + + If the upstream is configured for the current branch and names an + existing remote, then use that. Otherwise try to use another + remote: If only a single remote is configured, then use that. + Otherwise if a remote named "origin" exists, then use that. + + If no remote can be determined, then this command is not available + from the ‘magit-fetch’ transient prefix and invoking it directly + results in an error. + +‘f e’ (‘magit-fetch-other’) + This command fetch from a repository read from the minibuffer. + +‘f o’ (‘magit-fetch-branch’) + This command fetches a branch from a remote, both of which are read + from the minibuffer. + +‘f r’ (‘magit-fetch-refspec’) + This command fetches from a remote using an explicit refspec, both + of which are read from the minibuffer. + +‘f a’ (‘magit-fetch-all’) + This command fetches from all remotes. + +‘f m’ (‘magit-fetch-modules’) + This command fetches all submodules. With a prefix argument, it + acts as a transient prefix command, allowing the caller to set + options. + + -- User Option: magit-pull-or-fetch + By default fetch and pull commands are available from separate + transient prefix command. Setting this to ‘t’ adds some (but not + all) of the above suffix commands to the ‘magit-pull’ transient. + + If you do that, then you might also want to change the key binding + for these prefix commands, e.g.: + + (setq magit-pull-or-fetch t) + (define-key magit-mode-map "f" 'magit-pull) ; was magit-fetch + (define-key magit-mode-map "F" nil) ; was magit-pull + + +File: magit.info, Node: Pulling, Next: Pushing, Prev: Fetching, Up: Transferring + +7.3 Pulling +=========== + +Also see *note (gitman)git-pull::. For information about the upstream +and the push-remote, see *note The Two Remotes::. + +‘F’ (‘magit-pull’) + This transient prefix command binds the following suffix commands + and displays them in a temporary buffer until a suffix is invoked. + +‘F p’ (‘magit-pull-from-pushremote’) + This command pulls from the push-remote of the current branch. + + With a prefix argument or when the push-remote is either not + configured or unusable, then let the user first configure the + push-remote. + +‘F u’ (‘magit-pull-from-upstream’) + This command pulls from the upstream of the current branch. + + With a prefix argument or when the upstream is either not + configured or unusable, then let the user first configure the + upstream. + +‘F e’ (‘magit-pull-branch’) + This command pulls from a branch read in the minibuffer. + + +File: magit.info, Node: Pushing, Next: Plain Patches, Prev: Pulling, Up: Transferring + +7.4 Pushing +=========== + +Also see *note (gitman)git-push::. For information about the upstream +and the push-remote, see *note The Two Remotes::. + +‘P’ (‘magit-push’) + This transient prefix command binds the following suffix commands + along with the appropriate infix arguments and displays them in a + temporary buffer until a suffix is invoked. + +‘P p’ (‘magit-push-current-to-pushremote’) + This command pushes the current branch to its push-remote. + + With a prefix argument or when the push-remote is either not + configured or unusable, then let the user first configure the + push-remote. + +‘P u’ (‘magit-push-current-to-upstream’) + This command pushes the current branch to its upstream branch. + + With a prefix argument or when the upstream is either not + configured or unusable, then let the user first configure the + upstream. + +‘P e’ (‘magit-push-current’) + This command pushes the current branch to a branch read in the + minibuffer. + +‘P o’ (‘magit-push-other’) + This command pushes an arbitrary branch or commit somewhere. Both + the source and the target are read in the minibuffer. + +‘P r’ (‘magit-push-refspecs’) + This command pushes one or multiple refspecs to a remote, both of + which are read in the minibuffer. + + To use multiple refspecs, separate them with commas. Completion is + only available for the part before the colon, or when no colon is + used. + +‘P m’ (‘magit-push-matching’) + This command pushes all matching branches to another repository. + + If only one remote exists, then push to that. Otherwise prompt for + a remote, offering the remote configured for the current branch as + default. + +‘P t’ (‘magit-push-tags’) + This command pushes all tags to another repository. + + If only one remote exists, then push to that. Otherwise prompt for + a remote, offering the remote configured for the current branch as + default. + +‘P T’ (‘magit-push-tag’) + This command pushes a tag to another repository. + + One of the infix arguments, ‘--force-with-lease’, deserves a word of +caution. It is passed without a value, which means "permit a force push +as long as the remote-tracking branches match their counterparts on the +remote end". If you’ve set up a tool to do automatic fetches (Magit +itself does not provide such functionality), using ‘--force-with-lease’ +can be dangerous because you don’t actually control or know the state of +the remote-tracking refs. In that case, you should consider setting +‘push.useForceIfIncludes’ to ‘true’ (available since Git 2.30). + + Two more push commands exist, which by default are not available from +the push transient. See their doc-strings for instructions on how to +add them to the transient. + + -- Command: magit-push-implicitly args + This command pushes somewhere without using an explicit refspec. + + This command simply runs ‘git push -v [ARGS]’. ARGS are the infix + arguments. No explicit refspec arguments are used. Instead the + behavior depends on at least these Git variables: ‘push.default’, + ‘remote.pushDefault’, ‘branch.<branch>.pushRemote’, + ‘branch.<branch>.remote’, ‘branch.<branch>.merge’, and + ‘remote.<remote>.push’. + + If you add this suffix to a transient prefix without explicitly + specifying the description, then an attempt is made to predict what + this command will do. For example: + + (transient-insert-suffix 'magit-push \"p\" + '(\"i\" magit-push-implicitly))" + + -- Command: magit-push-to-remote remote args + This command pushes to the remote REMOTE without using an explicit + refspec. The remote is read in the minibuffer. + + This command simply runs ‘git push -v [ARGS] REMOTE’. ARGS are the + infix arguments. No refspec arguments are used. Instead the + behavior depends on at least these Git variables: ‘push.default’, + ‘remote.pushDefault’, ‘branch.<branch>.pushRemote’, + ‘branch.<branch>.remote’, ‘branch.<branch>.merge’, and + ‘remote.<remote>.push’. + + +File: magit.info, Node: Plain Patches, Next: Maildir Patches, Prev: Pushing, Up: Transferring + +7.5 Plain Patches +================= + +‘W’ (‘magit-patch’) + This transient prefix command binds the following suffix commands + along with the appropriate infix arguments and displays them in a + temporary buffer until a suffix is invoked. + +‘W c’ (‘magit-patch-create’) + This command creates patches for a set commits. If the region + marks several commits, then it creates patches for all of them. + Otherwise it functions as a transient prefix command, which + features several infix arguments and binds itself as a suffix + command. When this command is invoked as a suffix of itself, then + it creates a patch using the specified infix arguments. + +‘w a’ (‘magit-patch-apply’) + This command applies a patch. This is a transient prefix command, + which features several infix arguments and binds itself as a suffix + command. When this command is invoked as a suffix of itself, then + it applies a patch using the specified infix arguments. + +‘W s’ (‘magit-patch-save’) + This command creates a patch from the current diff. + + Inside ‘magit-diff-mode’ or ‘magit-revision-mode’ buffers, ‘C-x + C-w’ is also bound to this command. + + It is also possible to save a plain patch file by using ‘C-x C-w’ +inside a ‘magit-diff-mode’ or ‘magit-revision-mode’ buffer. + + +File: magit.info, Node: Maildir Patches, Prev: Plain Patches, Up: Transferring + +7.6 Maildir Patches +=================== + +Also see *note (gitman)git-am::. and *note (gitman)git-apply::. + +‘w’ (‘magit-am’) + This transient prefix command binds the following suffix commands + along with the appropriate infix arguments and displays them in a + temporary buffer until a suffix is invoked. + +‘w w’ (‘magit-am-apply-patches’) + This command applies one or more patches. If the region marks + files, then those are applied as patches. Otherwise this command + reads a file-name in the minibuffer, defaulting to the file at + point. + +‘w m’ (‘magit-am-apply-maildir’) + This command applies patches from a maildir. + +‘w a’ (‘magit-patch-apply’) + This command applies a plain patch. For a longer description see + *note Plain Patches::. This command is only available from the + ‘magit-am’ transient for historic reasons. + + When an "am" operation is in progress, then the transient instead +features the following suffix commands. + +‘w w’ (‘magit-am-continue’) + This command resumes the current patch applying sequence. + +‘w s’ (‘magit-am-skip’) + This command skips the stopped at patch during a patch applying + sequence. + +‘w a’ (‘magit-am-abort’) + This command aborts the current patch applying sequence. This + discards all changes made since the sequence started. + + +File: magit.info, Node: Miscellaneous, Next: Customizing, Prev: Transferring, Up: Top + +8 Miscellaneous +*************** + +* Menu: + +* Tagging:: +* Notes:: +* Submodules:: +* Subtree:: +* Worktree:: +* Sparse checkouts:: +* Bundle:: +* Common Commands:: +* Wip Modes:: +* Commands for Buffers Visiting Files:: +* Minor Mode for Buffers Visiting Blobs:: + + +File: magit.info, Node: Tagging, Next: Notes, Up: Miscellaneous + +8.1 Tagging +=========== + +Also see *note (gitman)git-tag::. + +‘t’ (‘magit-tag’) + This transient prefix command binds the following suffix commands + along with the appropriate infix arguments and displays them in a + temporary buffer until a suffix is invoked. + +‘t t’ (‘magit-tag-create’) + This command creates a new tag with the given NAME at REV. With a + prefix argument it creates an annotated tag. + +‘t r’ (‘magit-tag-release’) + This commands creates a release tag. It assumes that release tags + match ‘magit-release-tag-regexp’. + + First it prompts for the name of the new tag using the highest + existing tag as initial input and leaving it to the user to + increment the desired part of the version string. If you use + unconventional release tags or version numbers (e.g., + ‘v1.2.3-custom.1’), you can set the ‘magit-release-tag-regexp’ and + ‘magit-tag-version-regexp-alist’ variables. + + If ‘--annotate’ is enabled then it prompts for the message of the + new tag. The proposed tag message is based on the message of the + highest tag, provided that that contains the corresponding version + string and substituting the new version string for that. Otherwise + it proposes something like "Foo-Bar 1.2.3", given, for example, a + TAG "v1.2.3" and a repository located at something like + "/path/to/foo-bar". + +‘t k’ (‘magit-tag-delete’) + This command deletes one or more tags. If the region marks + multiple tags (and nothing else), then it offers to delete those. + Otherwise, it prompts for a single tag to be deleted, defaulting to + the tag at point. + +‘t p’ (‘magit-tag-prune’) + This command offers to delete tags missing locally from REMOTE, and + vice versa. + + +File: magit.info, Node: Notes, Next: Submodules, Prev: Tagging, Up: Miscellaneous + +8.2 Notes +========= + +Also see *note (gitman)git-notes::. + +‘T’ (‘magit-notes’) + This transient prefix command binds the following suffix commands + along with the appropriate infix arguments and displays them in a + temporary buffer until a suffix is invoked. + +‘T T’ (‘magit-notes-edit’) + Edit the note attached to a commit, defaulting to the commit at + point. + + By default use the value of Git variable ‘core.notesRef’ or + "refs/notes/commits" if that is undefined. + +‘T r’ (‘magit-notes-remove’) + Remove the note attached to a commit, defaulting to the commit at + point. + + By default use the value of Git variable ‘core.notesRef’ or + "refs/notes/commits" if that is undefined. + +‘T p’ (‘magit-notes-prune’) + Remove notes about unreachable commits. + + It is possible to merge one note ref into another. That may result +in conflicts which have to resolved in the temporary worktree +".git/NOTES_MERGE_WORKTREE". + +‘T m’ (‘magit-notes-merge’) + Merge the notes of a ref read from the user into the current notes + ref. The current notes ref is the value of Git variable + ‘core.notesRef’ or "refs/notes/commits" if that is undefined. + + When a notes merge is in progress then the transient features the +following suffix commands, instead of those listed above. + +‘T c’ (‘magit-notes-merge-commit’) + Commit the current notes ref merge, after manually resolving + conflicts. + +‘T a’ (‘magit-notes-merge-abort’) + Abort the current notes ref merge. + + The following variables control what notes reference ‘magit-notes-*’, +‘git notes’ and ‘git show’ act on and display. Both the local and +global values are displayed and can be modified. + + -- Variable: core.notesRef + This variable specifies the notes ref that is displayed by default + and which commands act on by default. + + -- Variable: notes.displayRef + This variable specifies additional notes ref to be displayed in + addition to the ref specified by ‘core.notesRef’. It can have + multiple values and may end with ‘*’ to display all refs in the + ‘refs/notes/’ namespace (or ‘**’ if some names contain slashes). + + +File: magit.info, Node: Submodules, Next: Subtree, Prev: Notes, Up: Miscellaneous + +8.3 Submodules +============== + +Also see *note (gitman)git-submodule::. + +* Menu: + +* Listing Submodules:: +* Submodule Transient:: + + +File: magit.info, Node: Listing Submodules, Next: Submodule Transient, Up: Submodules + +8.3.1 Listing Submodules +------------------------ + +The command ‘magit-list-submodules’ displays a list of the current +repository’s submodules in a separate buffer. It’s also possible to +display information about submodules directly in the status buffer of +the super-repository by adding ‘magit-insert-modules’ to the hook +‘magit-status-sections-hook’ as described in *note Status Module +Sections::. + + -- Command: magit-list-submodules + This command displays a list of the current repository’s populated + submodules in a separate buffer. + + It can be invoked by pressing ‘RET’ on the section titled + "Modules". + + -- User Option: magit-submodule-list-columns + This option controls what columns are displayed by the command + ‘magit-list-submodules’ and how they are displayed. + + Each element has the form ‘(HEADER WIDTH FORMAT PROPS)’. + + HEADER is the string displayed in the header. WIDTH is the width + of the column. FORMAT is a function that is called with one + argument, the repository identification (usually its basename), and + with ‘default-directory’ bound to the toplevel of its working tree. + It has to return a string to be inserted or nil. PROPS is an alist + that supports the keys ‘:right-align’, ‘:pad-right’ and ‘:sort’. + + The ‘:sort’ function has a weird interface described in the + docstring of ‘tabulated-list--get-sort’. Alternatively ‘<’ and + ‘magit-repolist-version<’ can be used as those functions are + automatically replaced with functions that satisfy the interface. + Set ‘:sort’ to ‘nil’ to inhibit sorting; if unspecified, then the + column is sortable using the default sorter. + + You may wish to display a range of numeric columns using just one + character per column and without any padding between columns, in + which case you should use an appropriate HEADER, set WIDTH to 1, + and set ‘:pad-right’ to 9. ‘+’ is substituted for numbers higher + than 9. + + +File: magit.info, Node: Submodule Transient, Prev: Listing Submodules, Up: Submodules + +8.3.2 Submodule Transient +------------------------- + +‘o’ (‘magit-submodule’) + This transient prefix command binds the following suffix commands + along with the appropriate infix arguments and displays them in a + temporary buffer until a suffix is invoked. + + Some of the below commands default to act on the modules that are +selected using the region. For brevity their description talk about +"the selected modules", but if no modules are selected, then they act on +the current module instead, or if point isn’t on a module, then the read +a single module to act on. With a prefix argument these commands ignore +the selection and the current module and instead act on all suitable +modules. + +‘o a’ (‘magit-submodule-add’) + This commands adds the repository at URL as a module. Optional + PATH is the path to the module relative to the root of the + super-project. If it is nil then the path is determined based on + URL. + +‘o r’ (‘magit-submodule-register’) + This command registers the selected modules by copying their urls + from ".gitmodules" to "$GIT_DIR/config". These values can then be + edited before running ‘magit-submodule-populate’. If you don’t + need to edit any urls, then use the latter directly. + +‘o p’ (‘magit-submodule-populate’) + This command creates the working directory or directories of the + selected modules, checking out the recorded commits. + +‘o u’ (‘magit-submodule-update’) + This command updates the selected modules checking out the recorded + commits. + +‘o s’ (‘magit-submodule-synchronize’) + This command synchronizes the urls of the selected modules, copying + the values from ".gitmodules" to the ".git/config" of the + super-project as well those of the modules. + +‘o d’ (‘magit-submodule-unpopulate’) + This command removes the working directory of the selected modules. + +‘o l’ (‘magit-list-submodules’) + This command displays a list of the current repository’s modules. + +‘o f’ (‘magit-fetch-modules’) + This command fetches all populated modules. With a prefix + argument, it acts as a transient prefix command, allowing the + caller to set options. + + Also fetch the super-repository, because ‘git fetch’ does not + support not doing that. + + +File: magit.info, Node: Subtree, Next: Worktree, Prev: Submodules, Up: Miscellaneous + +8.4 Subtree +=========== + +Also see *note (gitman)git-subtree::. + +‘O’ (‘magit-subtree’) + This transient prefix command binds the two sub-transients; one for + importing a subtree and one for exporting a subtree. + +‘O i’ (‘magit-subtree-import’) + This transient prefix command binds the following suffix commands + along with the appropriate infix arguments and displays them in a + temporary buffer until a suffix is invoked. + + The suffixes of this command import subtrees. + + If the ‘--prefix’ argument is set, then the suffix commands use + that prefix without prompting the user. If it is unset, then they + read the prefix in the minibuffer. + +‘O i a’ (‘magit-subtree-add’) + This command adds COMMIT from REPOSITORY as a new subtree at + PREFIX. + +‘O i c’ (‘magit-subtree-add-commit’) + This command add COMMIT as a new subtree at PREFIX. + +‘O i m’ (‘magit-subtree-merge’) + This command merges COMMIT into the PREFIX subtree. + +‘O i f’ (‘magit-subtree-pull’) + This command pulls COMMIT from REPOSITORY into the PREFIX subtree. + +‘O e’ (‘magit-subtree-export’) + This transient prefix command binds the following suffix commands + along with the appropriate infix arguments and displays them in a + temporary buffer until a suffix is invoked. + + The suffixes of this command export subtrees. + + If the ‘--prefix’ argument is set, then the suffix commands use + that prefix without prompting the user. If it is unset, then they + read the prefix in the minibuffer. + +‘O e p’ (‘magit-subtree-push’) + This command extract the history of the subtree PREFIX and pushes + it to REF on REPOSITORY. + +‘O e s’ (‘magit-subtree-split’) + This command extracts the history of the subtree PREFIX. + + +File: magit.info, Node: Worktree, Next: Sparse checkouts, Prev: Subtree, Up: Miscellaneous + +8.5 Worktree +============ + +Also see *note (gitman)git-worktree::. + +‘Z’ (‘magit-worktree’) + This transient prefix command binds the following suffix commands + and displays them in a temporary buffer until a suffix is invoked. + +‘Z b’ (‘magit-worktree-checkout’) + Checkout BRANCH in a new worktree at PATH. + +‘Z c’ (‘magit-worktree-branch’) + Create a new BRANCH and check it out in a new worktree at PATH. + +‘Z m’ (‘magit-worktree-move’) + Move an existing worktree to a new PATH. + +‘Z k’ (‘magit-worktree-delete’) + Delete a worktree, defaulting to the worktree at point. The + primary worktree cannot be deleted. + +‘Z g’ (‘magit-worktree-status’) + Show the status for the worktree at point. + + If there is no worktree at point, then read one in the minibuffer. + If the worktree at point is the one whose status is already being + displayed in the current buffer, then show it in Dired instead. + + +File: magit.info, Node: Sparse checkouts, Next: Bundle, Prev: Worktree, Up: Miscellaneous + +8.6 Sparse checkouts +==================== + +Sparse checkouts provide a way to restrict the working tree to a subset +of directories. See *note (gitman)git-sparse-checkout::. + + *Warning*: Git introduced the ‘git sparse-checkout’ command in +version 2.25 and still advertises it as experimental and subject to +change. Magit’s interface should be considered the same. In +particular, if Git introduces a backward incompatible change, Magit’s +sparse checkout functionality may be updated in a way that requires a +more recent Git version. + +‘>’ (‘magit-sparse-checkout’) + This transient prefix command binds the following suffix commands + and displays them in a temporary buffer until a suffix is invoked. + +‘> e’ (‘magit-sparse-checkout-enable’) + This command initializes a sparse checkout that includes only the + files in the top-level directory. + + Note that ‘magit-sparse-checkout-set’ and + ‘magit-sparse-checkout-add’ automatically initialize a sparse + checkout if necessary. However, you may want to call + ‘magit-sparse-checkout-enable’ explicitly to re-initialize a sparse + checkout after calling ‘magit-sparse-checkout-disable’, to pass + additional arguments to ‘git sparse-checkout init’, or to execute + the initialization asynchronously. + +‘> s’ (‘magit-sparse-checkout-set’) + This command takes a list of directories and configures the sparse + checkout to include only files in those subdirectories. Any + previously included directories are excluded unless they are in the + provided list of directories. + +‘> a’ (‘magit-sparse-checkout-add’) + This command is like ‘magit-sparse-checkout-set’, but instead adds + the specified list of directories to the set of directories that is + already included in the sparse checkout. + +‘> r’ (‘magit-sparse-checkout-reapply’) + This command applies the currently configured sparse checkout + patterns to the working tree. This is useful to call if excluded + files have been checked out after operations such as merging or + rebasing. + +‘> d’ (‘magit-sparse-checkout-disable’) + This command restores the full checkout. To return to the previous + sparse checkout, call ‘magit-sparse-checkout-enable’. + + A sparse checkout can also be initiated when cloning a repository by +using the ‘magit-clone-sparse’ command in the ‘magit-clone’ transient +(see *note Cloning Repository::). + + If you want the status buffer to indicate when a sparse checkout is +enabled, add the function ‘magit-sparse-checkout-insert-header’ to +‘magit-status-headers-hook’. + + +File: magit.info, Node: Bundle, Next: Common Commands, Prev: Sparse checkouts, Up: Miscellaneous + +8.7 Bundle +========== + +Also see *note (gitman)git-bundle::. + + -- Command: magit-bundle + This transient prefix command binds several suffix commands for + running ‘git bundle’ subcommands and displays them in a temporary + buffer until a suffix is invoked. + + +File: magit.info, Node: Common Commands, Next: Wip Modes, Prev: Bundle, Up: Miscellaneous + +8.8 Common Commands +=================== + + -- Command: magit-switch-to-repository-buffer + -- Command: magit-switch-to-repository-buffer-other-window + -- Command: magit-switch-to-repository-buffer-other-frame + -- Command: magit-display-repository-buffer + These commands read any existing Magit buffer that belongs to the + current repository from the user and then switch to the selected + buffer (without refreshing it). + + The last variant uses ‘magit-display-buffer’ to do so and thus + respects ‘magit-display-buffer-function’. + + These are some of the commands that can be used in all buffers whose +major-modes derive from ‘magit-mode’. There are other common commands +beside the ones below, but these didn’t fit well anywhere else. + +‘C-w’ (‘magit-copy-section-value’) + This command saves the value of the current section to the + ‘kill-ring’, and, provided that the current section is a commit, + branch, or tag section, it also pushes the (referenced) revision to + the ‘magit-revision-stack’. + + When the current section is a branch or a tag, and a prefix + argument is used, then it saves the revision at its tip to the + ‘kill-ring’ instead of the reference name. + + When the region is active, this command saves that to the + ‘kill-ring’, like ‘kill-ring-save’ would, instead of behaving as + described above. If a prefix argument is used and the region is + within a hunk, then it strips the diff marker column and keeps only + either the added or removed lines, depending on the sign of the + prefix argument. + +‘M-w’ (‘magit-copy-buffer-revision’) + This command saves the revision being displayed in the current + buffer to the ‘kill-ring’ and also pushes it to the + ‘magit-revision-stack’. It is mainly intended for use in + ‘magit-revision-mode’ buffers, the only buffers where it is always + unambiguous exactly which revision should be saved. + + Most other Magit buffers usually show more than one revision, in + some way or another, so this command has to select one of them, and + that choice might not always be the one you think would have been + the best pick. + + Outside of Magit ‘M-w’ and ‘C-w’ are usually bound to +‘kill-ring-save’ and ‘kill-region’, and these commands would also be +useful in Magit buffers. Therefore when the region is active, then both +of these commands behave like ‘kill-ring-save’ instead of as described +above. + + +File: magit.info, Node: Wip Modes, Next: Commands for Buffers Visiting Files, Prev: Common Commands, Up: Miscellaneous + +8.9 Wip Modes +============= + +Git keeps *committed* changes around long enough for users to recover +changes they have accidentally deleted. It does so by not garbage +collecting any committed but no longer referenced objects for a certain +period of time, by default 30 days. + + But Git does *not* keep track of *uncommitted* changes in the working +tree and not even the index (the staging area). Because Magit makes it +so convenient to modify uncommitted changes, it also makes it easy to +shoot yourself in the foot in the process. + + For that reason Magit provides a global mode that saves *tracked* +files to work-in-progress references after or before certain actions. +(At present untracked files are never saved and for technical reasons +nothing is saved before the first commit has been created). + + Two separate work-in-progress references are used to track the state +of the index and of the working tree: ‘refs/wip/index/<branchref>’ and +‘refs/wip/wtree/<branchref>’, where ‘<branchref>’ is the full ref of the +current branch, e.g., ‘refs/heads/master’. When the ‘HEAD’ is detached +then ‘HEAD’ is used in place of ‘<branchref>’. + + Checking out another branch (or detaching ‘HEAD’) causes the use of +different wip refs for subsequent changes. + + -- User Option: magit-wip-mode + When this mode is enabled, then uncommitted changes are committed + to dedicated work-in-progress refs whenever appropriate (i.e., when + dataloss would be a possibility otherwise). + + Setting this variable directly does not take effect; either use the + Custom interface to do so or call the respective mode function. + + For historic reasons this mode is implemented on top of four other + ‘magit-wip-*’ modes, which can also be used individually, if you + want finer control over when the wip refs are updated; but that is + discouraged. See *note Legacy Wip Modes::. + + To view the log for a branch and its wip refs use the commands +‘magit-wip-log’ and ‘magit-wip-log-current’. You should use ‘--graph’ +when using these commands. + + -- Command: magit-wip-log + This command shows the log for a branch and its wip refs. With a + negative prefix argument only the worktree wip ref is shown. + + The absolute numeric value of the prefix argument controls how many + "branches" of each wip ref are shown. This is only relevant if the + value of ‘magit-wip-merge-branch’ is ‘nil’. + + -- Command: magit-wip-log-current + This command shows the log for the current branch and its wip refs. + With a negative prefix argument only the worktree wip ref is shown. + + The absolute numeric value of the prefix argument controls how many + "branches" of each wip ref are shown. This is only relevant if the + value of ‘magit-wip-merge-branch’ is ‘nil’. + +‘X w’ (‘magit-reset-worktree’) + This command resets the working tree to some commit read from the + user and defaulting to the commit at point, while keeping the + ‘HEAD’ and index as-is. + + This can be used to restore files to the state committed to a wip + ref. Note that this will discard any unstaged changes that might + have existed before invoking this command (but of course only after + committing that to the working tree wip ref). + + Note that even if you enable ‘magit-wip-mode’ this won’t give you +perfect protection. The most likely scenario for losing changes despite +the use of ‘magit-wip-mode’ is making a change outside Emacs and then +destroying it also outside Emacs. In some such a scenario, Magit, being +an Emacs package, didn’t get the opportunity to keep you from shooting +yourself in the foot. + + When you are unsure whether Magit did commit a change to the wip +refs, then you can explicitly request that all changes to all tracked +files are being committed. + +‘M-x magit-wip-commit’ + This command commits all changes to all tracked files to the index + and working tree work-in-progress refs. Like the modes described + above, it does not commit untracked files, but it does check all + tracked files for changes. Use this command when you suspect that + the modes might have overlooked a change made outside Emacs/Magit. + + -- User Option: magit-wip-namespace + The namespace used for work-in-progress refs. It has to end with a + slash. The wip refs are named ‘<namespace>index/<branchref>’ and + ‘<namespace>wtree/<branchref>’. When snapshots are created while + the ‘HEAD’ is detached then ‘HEAD’ is used in place of + ‘<branchref>’. + + -- User Option: magit-wip-mode-lighter + Mode-line lighter for ‘magit-wip--mode’. + +* Menu: + +* Wip Graph:: +* Legacy Wip Modes:: + + +File: magit.info, Node: Wip Graph, Next: Legacy Wip Modes, Up: Wip Modes + +8.9.1 Wip Graph +--------------- + + -- User Option: magit-wip-merge-branch + This option controls whether the current branch is merged into the + wip refs after a new commit was created on the branch. + + If non-nil and the current branch has new commits, then it is + merged into the wip ref before creating a new wip commit. This + makes it easier to inspect wip history and the wip commits are + never garbage collected. + + If nil and the current branch has new commits, then the wip ref is + reset to the tip of the branch before creating a new wip commit. + With this setting wip commits are eventually garbage collected. + + When ‘magit-wip-merge-branch’ is ‘t’, then the history looks like +this: + + *--*--*--*--*--* refs/wip/index/refs/heads/master + / / / + A-----B-----C refs/heads/master + + When ‘magit-wip-merge-branch’ is ‘nil’, then creating a commit on the +real branch and then making a change causes the wip refs to be recreated +to fork from the new commit. But the old commits on the wip refs are +not lost. They are still available from the reflog. To make it easier +to see when the fork point of a wip ref was changed, an additional +commit with the message "restart autosaving" is created on it (‘xxO’ +commits below are such boundary commits). + + Starting with + + BI0---BI1 refs/wip/index/refs/heads/master + / + A---B refs/heads/master + \ + BW0---BW1 refs/wip/wtree/refs/heads/master + + and committing the staged changes and editing and saving a file would +result in + + BI0---BI1 refs/wip/index/refs/heads/master + / + A---B---C refs/heads/master + \ \ + \ CW0---CW1 refs/wip/wtree/refs/heads/master + \ + BW0---BW1 refs/wip/wtree/refs/heads/master@{2} + + The fork-point of the index wip ref is not changed until some change +is being staged. Likewise just checking out a branch or creating a +commit does not change the fork-point of the working tree wip ref. The +fork-points are not adjusted until there actually is a change that +should be committed to the respective wip ref. + + +File: magit.info, Node: Legacy Wip Modes, Prev: Wip Graph, Up: Wip Modes + +8.9.2 Legacy Wip Modes +---------------------- + +It is recommended that you use the mode ‘magit-wip-mode’ (which see) and +ignore the existence of the following modes, which are preserved for +historic reasons. + + Setting the following variables directly does not take effect; either +use the Custom interface to do so or call the respective mode functions. + + -- User Option: magit-wip-after-save-mode + When this mode is enabled, then saving a buffer that visits a file + tracked in a Git repository causes its current state to be + committed to the working tree wip ref for the current branch. + + -- User Option: magit-wip-after-apply-mode + When this mode is enabled, then applying (i.e., staging, unstaging, + discarding, reversing, and regularly applying) a change to a file + tracked in a Git repository causes its current state to be + committed to the index and/or working tree wip refs for the current + branch. + + If you only ever edit files using Emacs and only ever interact with +Git using Magit, then the above two modes should be enough to protect +each and every change from accidental loss. In practice nobody does +that. Two additional modes exists that do commit to the wip refs before +making changes that could cause the loss of earlier changes. + + -- User Option: magit-wip-before-change-mode + When this mode is enabled, then certain commands commit the + existing changes to the files they are about to make changes to. + + -- User Option: magit-wip-initial-backup-mode + When this mode is enabled, then the current version of a file is + committed to the worktree wip ref before the buffer visiting that + file is saved for the first time since the buffer was created. + + This backs up the same version of the file that ‘backup-buffer’ + would save. While ‘backup-buffer’ uses a backup file, this mode + uses the same worktree wip ref as used by the other Magit Wip + modes. Like ‘backup-buffer’, it only does this once; unless you + kill the buffer and visit the file again only one backup will be + created per Emacs session. + + This mode ignores the variables that affect ‘backup-buffer’ and can + be used along-side that function, which is recommended because it + only backs up files that are tracked in a Git repository. + + -- User Option: magit-wip-after-save-local-mode-lighter + Mode-line lighter for ‘magit-wip-after-save-local-mode’. + + -- User Option: magit-wip-after-apply-mode-lighter + Mode-line lighter for ‘magit-wip-after-apply-mode’. + + -- User Option: magit-wip-before-change-mode-lighter + Mode-line lighter for ‘magit-wip-before-change-mode’. + + -- User Option: magit-wip-initial-backup-mode-lighter + Mode-line lighter for ‘magit-wip-initial-backup-mode’. + + +File: magit.info, Node: Commands for Buffers Visiting Files, Next: Minor Mode for Buffers Visiting Blobs, Prev: Wip Modes, Up: Miscellaneous + +8.10 Commands for Buffers Visiting Files +======================================== + +By default Magit defines a few global key bindings. These bindings are +a compromise between providing no bindings at all and providing the +better bindings I would have liked to use instead. Magit cannot provide +the set of recommended bindings by default because those key sequences +are strictly reserved for bindings added by the user. Also see *note +Global Bindings:: and *note (elisp)Key Binding Conventions::. + + To use the recommended bindings, add this to your init file and +restart Emacs. + + (setq magit-define-global-key-bindings 'recommended) + + If you don’t want Magit to add any bindings to the global keymap at +all, add this to your init file and restart Emacs. + + (setq magit-define-global-key-bindings nil) + +‘C-c f’ (‘magit-file-dispatch’) +‘C-c f s’ (‘magit-stage-file’) +‘C-c f s’ (‘magit-stage-buffer-file’) +‘C-c f u’ (‘magit-unstage-file’) +‘C-c f u’ (‘magit-unstage-buffer-file’) +‘C-c f , x’ (‘magit-file-untrack’) +‘C-c f , r’ (‘magit-file-rename’) +‘C-c f , k’ (‘magit-file-delete’) +‘C-c f , c’ (‘magit-file-checkout’) +‘C-c f D’ (‘magit-diff’) +‘C-c f d’ (‘magit-diff-buffer-file’) +‘C-c f L’ (‘magit-log’) +‘C-c f l’ (‘magit-log-buffer-file’) +‘C-c f t’ (‘magit-log-trace-definition’) +‘C-c f M’ (‘magit-log-merged’) +‘C-c f B’ (‘magit-blame’) +‘C-c f b’ (‘magit-blame-additions’) +‘C-c f r’ (‘magit-blame-removal’) +‘C-c f f’ (‘magit-blame-reverse’) +‘C-c f m’ (‘magit-blame-echo’) +‘C-c f q’ (‘magit-blame-quit’) +‘C-c f p’ (‘magit-blob-previous’) +‘C-c f n’ (‘magit-blob-next’) +‘C-c f v’ (‘magit-find-file’) +‘C-c f V’ (‘magit-blob-visit-file’) +‘C-c f g’ (‘magit-status-here’) +‘C-c f G’ (‘magit-display-repository-buffer’) +‘C-c f c’ (‘magit-commit’) +‘C-c f e’ (‘magit-edit-line-commit’) + Each of these commands is documented individually right below, + alongside their default key bindings. The bindings shown above are + the recommended bindings, which you can enable by following the + instructions further up. + +‘C-c M-g’ (‘magit-file-dispatch’) + This transient prefix command binds the following suffix commands + and displays them in a temporary buffer until a suffix is invoked. + +‘C-c M-g s’ (‘magit-stage-file’) +‘C-c M-g s’ (‘magit-stage-buffer-file’) + Stage all changes to the file being visited in the current buffer. + When not visiting a file, then the first command is used, which + prompts for a file. + +‘C-c M-g u’ (‘magit-unstage-file’) +‘C-c M-g u’ (‘magit-unstage-buffer-file’) + Unstage all changes to the file being visited in the current + buffer. When not visiting a file, then the first command is used, + which prompts for a file. + +‘C-c M-g , x’ (‘magit-file-untrack’) + This command untracks a file read from the user, defaulting to the + visited file. + +‘C-c M-g , r’ (‘magit-file-rename’) + This command renames a file read from the user, defaulting to the + visited file. + +‘C-c M-g , k’ (‘magit-file-delete’) + This command deletes a file read from the user, defaulting to the + visited file. + +‘C-c M-g , c’ (‘magit-file-checkout’) + This command updates a file in the working tree and index to the + contents from a revision. Both the revision and file are read from + the user. + +‘C-c M-g D’ (‘magit-diff’) + This transient prefix command binds several diff suffix commands + and infix arguments and displays them in a temporary buffer until a + suffix is invoked. See *note Diffing::. + + This is the same command that ‘d’ is bound to in Magit buffers. If + this command is invoked from a file-visiting buffer, then the + initial value of the option (‘--’) that limits the diff to certain + file(s) is set to the visited file. + +‘C-c M-g d’ (‘magit-diff-buffer-file’) + This command shows the diff for the file of blob that the current + buffer visits. + + -- User Option: magit-diff-buffer-file-locked + This option controls whether ‘magit-diff-buffer-file’ uses a + dedicated buffer. See *note Modes and Buffers::. + +‘C-c M-g L’ (‘magit-log’) + This transient prefix command binds several log suffix commands and + infix arguments and displays them in a temporary buffer until a + suffix is invoked. See *note Logging::. + + This is the same command that ‘l’ is bound to in Magit buffers. If + this command is invoked from a file-visiting buffer, then the + initial value of the option (‘--’) that limits the log to certain + file(s) is set to the visited file. + +‘C-c M-g l’ (‘magit-log-buffer-file’) + This command shows the log for the file of blob that the current + buffer visits. Renames are followed when a prefix argument is used + or when ‘--follow’ is an active log argument. When the region is + active, the log is restricted to the selected line range. + + -- User Option: magit-log-buffer-file-locked + This option controls whether ‘magit-log-buffer-file’ uses a + dedicated buffer. See *note Modes and Buffers::. + +‘C-c M-g t’ (‘magit-log-trace-definition’) + This command shows the log for the definition at point. + +‘C-c M-g M’ (‘magit-log-merged’) + This command reads a commit and a branch in shows a log concerning + the merge of the former into the latter. This shows multiple + commits even in case of a fast-forward merge. + +‘C-c M-g B’ (‘magit-blame’) + This transient prefix command binds all blaming suffix commands + along with the appropriate infix arguments and displays them in a + temporary buffer until a suffix is invoked. + + For more information about this and the following commands also see + *note Blaming::. + + In addition to the ‘magit-blame’ sub-transient, the dispatch + transient also binds several blaming suffix commands directly. See + *note Blaming:: for information about those commands and bindings. + +‘C-c M-g p’ (‘magit-blob-previous’) + This command visits the previous blob which modified the current + file. + +‘C-c M-g n’ (‘magit-blob-next’) + This command visits the next blob which modified the current file. + +‘C-c M-g v’ (‘magit-find-file’) + This command reads a revision and file and visits the respective + blob. + +‘C-c M-g V’ (‘magit-blob-visit-file’) + This command visits the file from the working tree, corresponding + to the current blob. When visiting a blob or the version from the + index, then it goes to the same location in the respective file in + the working tree. + +‘C-c M-g g’ (‘magit-status-here’) + This command displays the status of the current repository in a + buffer, like ‘magit-status’ does. Additionally it tries to go to + the position in that buffer, which corresponds to the position in + the current file-visiting buffer (if any). + +‘C-c M-g G’ (‘magit-display-repository-buffer’) + This command reads and displays a Magit buffer belonging to the + current repository, without refreshing it. + +‘C-c M-g c’ (‘magit-commit’) + This transient prefix command binds the following suffix commands + along with the appropriate infix arguments and displays them in a + temporary buffer until a suffix is invoked. See *note Initiating a + Commit::. + +‘C-c M-g e’ (‘magit-edit-line-commit’) + This command makes the commit editable that added the current line. + + With a prefix argument it makes the commit editable that removes + the line, if any. The commit is determined using ‘git blame’ and + made editable using ‘git rebase --interactive’ if it is reachable + from ‘HEAD’, or by checking out the commit (or a branch that points + at it) otherwise. + + +File: magit.info, Node: Minor Mode for Buffers Visiting Blobs, Prev: Commands for Buffers Visiting Files, Up: Miscellaneous + +8.11 Minor Mode for Buffers Visiting Blobs +========================================== + +The ‘magit-blob-mode’ enables certain Magit features in blob-visiting +buffers. Such buffers can be created using ‘magit-find-file’ and some +of the commands mentioned below, which also take care of turning on this +minor mode. Currently this mode only establishes a few key bindings, +but this might be extended. + +‘p’ (‘magit-blob-previous’) + Visit the previous blob which modified the current file. + +‘n’ (‘magit-blob-next’) + Visit the next blob which modified the current file. + +‘q’ (‘magit-kill-this-buffer’) + Kill the current buffer. + + +File: magit.info, Node: Customizing, Next: Plumbing, Prev: Miscellaneous, Up: Top + +9 Customizing +************* + +Both Git and Emacs are highly customizable. Magit is both a Git +porcelain as well as an Emacs package, so it makes sense to customize it +using both Git variables as well as Emacs options. However this +flexibility doesn’t come without problems, including but not limited to +the following. + + • Some Git variables automatically have an effect in Magit without + requiring any explicit support. Sometimes that is desirable - in + other cases, it breaks Magit. + + When a certain Git setting breaks Magit but you want to keep using + that setting on the command line, then that can be accomplished by + overriding the value for Magit only by appending something like + ‘("-c" "some.variable=compatible-value")’ to + ‘magit-git-global-arguments’. + + • Certain settings like ‘fetch.prune=true’ are respected by Magit + commands (because they simply call the respective Git command) but + their value is not reflected in the respective transient buffers. + In this case the ‘--prune’ argument in ‘magit-fetch’ might be + active or inactive, but that doesn’t keep the Git variable from + being honored by the suffix commands anyway. So pruning might + happen despite the ‘--prune’ arguments being displayed in a way + that seems to indicate that no pruning will happen. + + I intend to address these and similar issues in a future release. + +* Menu: + +* Per-Repository Configuration:: +* Essential Settings:: + + +File: magit.info, Node: Per-Repository Configuration, Next: Essential Settings, Up: Customizing + +9.1 Per-Repository Configuration +================================ + +Magit can be configured on a per-repository level using both Git +variables as well as Emacs options. + + To set a Git variable for one repository only, simply set it in +‘/path/to/repo/.git/config’ instead of ‘$HOME/.gitconfig’ or +‘/etc/gitconfig’. See *note (gitman)git-config::. + + Similarly, Emacs options can be set for one repository only by +editing ‘/path/to/repo/.dir-locals.el’. See *note (emacs)Directory +Variables::. For example to disable automatic refreshes of +file-visiting buffers in just one huge repository use this: + + • ‘/path/to/huge/repo/.dir-locals.el’ + + ((nil . ((magit-refresh-buffers . nil)))) + + It might only be costly to insert certain information into Magit +buffers for repositories that are exceptionally large, in which case you +can disable the respective section inserters just for that repository: + + • ‘/path/to/tag/invested/repo/.dir-locals.el’ + + ((magit-status-mode + . ((eval . (magit-disable-section-inserter 'magit-insert-tags-header))))) + + -- Function: magit-disable-section-inserter fn + This function disables the section inserter FN in the current + repository. It is only intended for use in ‘.dir-locals.el’ and + ‘.dir-locals-2.el’. + + If you want to apply the same settings to several, but not all, +repositories then keeping the repository-local config files in sync +would quickly become annoying. To avoid that you can create config +files for certain classes of repositories (e.g., "huge repositories") +and then include those files in the per-repository config files. For +example: + + • ‘/path/to/huge/repo/.git/config’ + + [include] + path = /path/to/huge-gitconfig + + • ‘/path/to/huge-gitconfig’ + + [status] + showUntrackedFiles = no + + • ‘$HOME/.emacs.d/init.el’ + + (dir-locals-set-class-variables 'huge-git-repository + '((nil . ((magit-refresh-buffers . nil))))) + + (dir-locals-set-directory-class + "/path/to/huge/repo/" 'huge-git-repository) + + +File: magit.info, Node: Essential Settings, Prev: Per-Repository Configuration, Up: Customizing + +9.2 Essential Settings +====================== + +The next three sections list and discuss several variables that many +users might want to customize, for safety and/or performance reasons. + +* Menu: + +* Safety:: +* Performance:: +* Global Bindings:: + + +File: magit.info, Node: Safety, Next: Performance, Up: Essential Settings + +9.2.1 Safety +------------ + +This section discusses various variables that you might want to change +(or *not* change) for safety reasons. + + Git keeps *committed* changes around long enough for users to recover +changes they have accidentally been deleted. It does not do the same +for *uncommitted* changes in the working tree and not even the index +(the staging area). Because Magit makes it so easy to modify +uncommitted changes, it also makes it easy to shoot yourself in the foot +in the process. For that reason Magit provides three global modes that +save *tracked* files to work-in-progress references after or before +certain actions. See *note Wip Modes::. + + These modes are not enabled by default because of performance +concerns. Instead a lot of potentially destructive commands require +confirmation every time they are used. In many cases this can be +disabled by adding a symbol to ‘magit-no-confirm’ (see *note Completion +and Confirmation::). If you enable the various wip modes then you +should add ‘safe-with-wip’ to this list. + + Similarly it isn’t necessary to require confirmation before moving a +file to the system trash - if you trashed a file by mistake then you can +recover it from there. Option ‘magit-delete-by-moving-to-trash’ +controls whether the system trash is used, which is the case by default. +Nevertheless, ‘trash’ isn’t a member of ‘magit-no-confirm’ - you might +want to change that. + + By default buffers visiting files are automatically reverted when the +visited file changes on disk. This isn’t as risky as it might seem, but +to make an informed decision you should see *note Risk of Reverting +Automatically::. + + +File: magit.info, Node: Performance, Next: Global Bindings, Prev: Safety, Up: Essential Settings + +9.2.2 Performance +----------------- + +After Magit has run ‘git’ for side-effects, it also refreshes the +current Magit buffer and the respective status buffer. This is +necessary because otherwise outdated information might be displayed +without the user noticing. Magit buffers are updated by recreating +their content from scratch, which makes updating simpler and less +error-prone, but also more costly. Keeping it simple and just +re-creating everything from scratch is an old design decision and +departing from that will require major refactoring. + + Meanwhile you can tell Magit to only automatically refresh the +current Magit buffer, but not the status buffer. If you do that, then +the status buffer is only refreshed automatically if it is the current +buffer. + + (setq magit-refresh-status-buffer nil) + + You should also check whether any third-party packages have added +anything to ‘magit-refresh-buffer-hook’, ‘magit-pre-refresh-hook’, and +‘magit-post-refresh-hook’. If so, then check whether those additions +impact performance significantly. + + Magit can be told to refresh buffers verbosely using ‘M-x +magit-toggle-verbose-refresh’. Enabling this helps figuring out which +sections are bottlenecks. Each line printed to the ‘*Messages*’ buffer +contains a section name, the number of seconds it took to show this +section, and from 0 to 2 exclamation marks: the more exclamation marks +the slower the section is. + + Magit also reverts buffers for visited files located inside the +current repository when the visited file changes on disk. That is +implemented on top of ‘auto-revert-mode’ from the built-in library +‘autorevert’. To figure out whether that impacts performance, check +whether performance is significantly worse, when many buffers exist +and/or when some buffers visit files using TRAMP. If so, then this +should help. + + (setq auto-revert-buffer-list-filter + 'magit-auto-revert-repository-buffer-p) + + For alternative approaches see *note Automatic Reverting of +File-Visiting Buffers::. + + If you have enabled any features that are disabled by default, then +you should check whether they impact performance significantly. It’s +likely that they were not enabled by default because it is known that +they reduce performance at least in large repositories. + + If performance is only slow inside certain unusually large +repositories, then you might want to disable certain features on a +per-repository or per-repository-class basis only. See *note +Per-Repository Configuration::. For example it takes a long time to +determine the next and current tag in repository with exceptional +numbers of tags. It would therefore be a good idea to disable +‘magit-insert-tags-headers’, as explained at the mentioned node. + +* Menu: + +* Microsoft Windows Performance:: +* MacOS Performance:: + +Log Performance +............... + +When showing logs, Magit limits the number of commits initially shown in +the hope that this avoids unnecessary work. When ‘--graph’ is used, +then this unfortunately does not have the desired effect for large +histories. Junio, Git’s maintainer, said on the Git mailing list +(<https://www.spinics.net/lists/git/msg232230.html>): "‘--graph’ wants +to compute the whole history and the max-count only affects the output +phase after ‘--graph’ does its computation". + + In other words, it’s not that Git is slow at outputting the +differences, or that Magit is slow at parsing the output - the problem +is that Git first goes outside and has a smoke. + + We actually work around this issue by limiting the number of commits +not only by using ‘-<N>’ but by also using a range. But unfortunately +that’s not always possible. + + When more than a few thousand commits are shown, then the use of +‘--graph’ can slow things down. + + Using ‘--color --graph’ is even slower. Magit uses code that is part +of Emacs to turn control characters into faces. That code is pretty +slow and this is quite noticeable when showing a log with many branches +and merges. For that reason ‘--color’ is not enabled by default +anymore. Consider leaving it at that. + +Diff Performance +................ + +If diffs are slow, then consider turning off some optional diff features +by setting all or some of the following variables to ‘nil’: +‘magit-diff-highlight-indentation’, ‘magit-diff-highlight-trailing’, +‘magit-diff-paint-whitespace’, ‘magit-diff-highlight-hunk-body’, and +‘magit-diff-refine-hunk’. + + When showing a commit instead of some arbitrary diff, then some +additional information is displayed. Calculating this information can +be quite expensive given certain circumstances. If looking at a commit +using ‘magit-revision-mode’ takes considerably more time than looking at +the same commit in ‘magit-diff-mode’, then consider setting +‘magit-revision-insert-related-refs’ to ‘nil’. + + When you are often confronted with diffs that contain deleted files, +then you might want to enable the ‘--irreversible-delete’ argument. If +you do that then diffs still show that a file was deleted but without +also showing the complete deleted content of the file. This argument is +not available by default, see *note (transient)Enabling and Disabling +Suffixes::. Once you have done that you should enable it and save that +setting, see *note (transient)Saving Values::. You should do this in +both the diff (‘d’) and the diff refresh (‘D’) transient popups. + +Refs Buffer Performance +....................... + +When refreshing the "references buffer" is slow, then that’s usually +because several hundred refs are being displayed. The best way to +address that is to display fewer refs, obviously. + + If you are not, or only mildly, interested in seeing the list of +tags, then start by not displaying them: + + (remove-hook 'magit-refs-sections-hook 'magit-insert-tags) + + Then you should also make sure that the listed remote branches +actually all exist. You can do so by pruning branches which no longer +exist using ‘f-pa’. + +Committing Performance +...................... + +When you initiate a commit, then Magit by default automatically shows a +diff of the changes you are about to commit. For large commits this can +take a long time, which is especially distracting when you are +committing large amounts of generated data which you don’t actually +intend to inspect before committing. This behavior can be turned off +using: + + (remove-hook 'server-switch-hook 'magit-commit-diff) + (remove-hook 'with-editor-filter-visit-hook 'magit-commit-diff) + + Then you can type ‘C-c C-d’ to show the diff when you actually want +to see it, but only then. Alternatively you can leave the hook alone +and just type ‘C-g’ in those cases when it takes too long to generate +the diff. If you do that, then you will end up with a broken diff +buffer, but doing it this way has the advantage that you usually get to +see the diff, which is useful because it increases the odds that you +spot potential issues. + + +File: magit.info, Node: Microsoft Windows Performance, Next: MacOS Performance, Up: Performance + +Microsoft Windows Performance +............................. + +In order to update the status buffer, ‘git’ has to be run a few dozen +times. That is problematic on Microsoft Windows, because that operating +system is exceptionally slow at starting processes. Sadly this is an +issue that can only be fixed by Microsoft itself, and they don’t appear +to be particularly interested in doing so. + + Beside the subprocess issue, there are also other Windows-specific +performance issues. Some of these have workarounds. The maintainers of +"Git for Windows" try to improve performance on Windows. Always use the +latest release in order to benefit from the latest performance tweaks. +Magit too tries to work around some Windows-specific issues. + + According to some sources, setting the following Git variables can +also help. + + git config --global core.preloadindex true # default since v2.1 + git config --global core.fscache true # default since v2.8 + git config --global gc.auto 256 + + You should also check whether an anti-virus program is affecting +performance. + + +File: magit.info, Node: MacOS Performance, Prev: Microsoft Windows Performance, Up: Performance + +MacOS Performance +................. + +Before Emacs 26.1 child processes were created using ‘fork’ on macOS. +That needlessly copied GUI resources, which is expensive. The result +was that forking took about 30 times as long on Darwin than on Linux, +and because Magit starts many ‘git’ processes that made quite a +difference. + + So make sure that you are using at least Emacs 26.1, in which case +the faster ‘vfork’ will be used. (The creation of child processes still +takes about twice as long on Darwin compared to Linux.) See (1) for +more information. + + Additionally, ‘git’ installed from a package manager like ‘brew’ or +‘nix’ seems to be slower than the native executable. Profile the ‘git’ +executable you’re running against the one at ‘/usr/bin/git’, and if you +notice a notable difference try using the latter as +‘magit-git-executable’. + + ---------- Footnotes ---------- + + (1) +<https://lists.gnu.org/archive/html/bug-gnu-emacs/2017-04/msg00201.html> + + +File: magit.info, Node: Global Bindings, Prev: Performance, Up: Essential Settings + +9.2.3 Global Bindings +--------------------- + + -- User Option: magit-define-global-key-bindings + This option controls which set of Magit key bindings, if any, may + be added to the global keymap, even before Magit is first used in + the current Emacs session. + + • If the value is ‘nil’, no bindings are added. + + • If ‘default’, maybe add: + + ‘C-x g’ ‘magit-status’ + ‘C-x M-g’ ‘magit-dispatch’ + ‘C-c M-g’ ‘magit-file-dispatch’ + + • If ‘recommended’, maybe add: + + ‘C-x g’ ‘magit-status’ + ‘C-c g’ ‘magit-dispatch’ + ‘C-c f’ ‘magit-file-dispatch’ + + These bindings are strongly recommended, but we cannot use + them by default, because the ‘C-c <LETTER>’ namespace is + strictly reserved for bindings added by the user (see *note + (elisp)Key Binding Conventions::). + + The bindings in the chosen set may be added when ‘after-init-hook’ + is run. Each binding is added if, and only if, at that time no + other key is bound to the same command, and no other command is + bound to the same key. In other words we try to avoid adding + bindings that are unnecessary, as well as bindings that conflict + with other bindings. + + Adding these bindings is delayed until ‘after-init-hook’ is run to + allow users to set the variable anywhere in their init file + (without having to make sure to do so before ‘magit’ is loaded or + autoloaded) and to increase the likelihood that all the potentially + conflicting user bindings have already been added. + + To set this variable use either ‘setq’ or the Custom interface. Do + not use the function ‘customize-set-variable’ because doing that + would cause Magit to be loaded immediately, when that form is + evaluated (this differs from ‘custom-set-variables’, which doesn’t + load the libraries that define the customized variables). + + Setting this variable has no effect if ‘after-init-hook’ has + already been run. + + +File: magit.info, Node: Plumbing, Next: FAQ, Prev: Customizing, Up: Top + +10 Plumbing +*********** + +The following sections describe how to use several of Magit’s core +abstractions to extend Magit itself or implement a separate extension. + + A few of the low-level features used by Magit have been factored out +into separate libraries/packages, so that they can be used by other +packages, without having to depend on Magit. See *note +(with-editor)Top:: for information about ‘with-editor’. ‘transient’ +doesn’t have a manual yet. + + If you are trying to find an unused key that you can bind to a +command provided by your own Magit extension, then checkout +<https://github.com/magit/magit/wiki/Plugin-Dispatch-Key-Registry>. + +* Menu: + +* Calling Git:: +* Section Plumbing:: +* Refreshing Buffers:: +* Conventions:: + + +File: magit.info, Node: Calling Git, Next: Section Plumbing, Up: Plumbing + +10.1 Calling Git +================ + +Magit provides many specialized functions for calling Git. All of these +functions are defined in either ‘magit-git.el’ or ‘magit-process.el’ and +have one of the prefixes ‘magit-run-’, ‘magit-call-’, ‘magit-start-’, or +‘magit-git-’ (which is also used for other things). + + All of these functions accept an indefinite number of arguments, +which are strings that specify command line arguments for Git (or in +some cases an arbitrary executable). These arguments are flattened +before being passed on to the executable; so instead of strings they can +also be lists of strings and arguments that are ‘nil’ are silently +dropped. Some of these functions also require a single mandatory +argument before these command line arguments. + + Roughly speaking, these functions run Git either to get some value or +for side-effects. The functions that return a value are useful to +collect the information necessary to populate a Magit buffer, while the +others are used to implement Magit commands. + + The functions in the value-only group always run synchronously, and +they never trigger a refresh. The function in the side-effect group can +be further divided into subgroups depending on whether they run Git +synchronously or asynchronously, and depending on whether they trigger a +refresh when the executable has finished. + +* Menu: + +* Getting a Value from Git:: +* Calling Git for Effect:: + + +File: magit.info, Node: Getting a Value from Git, Next: Calling Git for Effect, Up: Calling Git + +10.1.1 Getting a Value from Git +------------------------------- + +These functions run Git in order to get a value, an exit status, or +output. Of course you could also use them to run Git commands that have +side-effects, but that should be avoided. + + -- Function: magit-git-exit-code &rest args + Executes git with ARGS and returns its exit code. + + -- Function: magit-git-success &rest args + Executes git with ARGS and returns ‘t’ if the exit code is ‘0’, + ‘nil’ otherwise. + + -- Function: magit-git-failure &rest args + Executes git with ARGS and returns ‘t’ if the exit code is ‘1’, + ‘nil’ otherwise. + + -- Function: magit-git-true &rest args + Executes git with ARGS and returns ‘t’ if the first line printed by + git is the string "true", ‘nil’ otherwise. + + -- Function: magit-git-false &rest args + Executes git with ARGS and returns ‘t’ if the first line printed by + git is the string "false", ‘nil’ otherwise. + + -- Function: magit-git-insert &rest args + Executes git with ARGS and inserts its output at point. + + -- Function: magit-git-string &rest args + Executes git with ARGS and returns the first line of its output. + If there is no output or if it begins with a newline character, + then this returns ‘nil’. + + -- Function: magit-git-lines &rest args + Executes git with ARGS and returns its output as a list of lines. + Empty lines anywhere in the output are omitted. + + -- Function: magit-git-items &rest args + Executes git with ARGS and returns its null-separated output as a + list. Empty items anywhere in the output are omitted. + + If the value of option ‘magit-git-debug’ is non-nil and git exits + with a non-zero exit status, then warn about that in the echo area + and add a section containing git’s standard error in the current + repository’s process buffer. + + -- Function: magit-process-git destination &rest args + Calls Git synchronously in a separate process, returning its exit + code. DESTINATION specifies how to handle the output, like for + ‘call-process’, except that file handlers are supported. Enables + Cygwin’s "noglob" option during the call and ensures unix eol + conversion. + + -- Function: magit-process-file process &optional infile buffer display + &rest args + Processes files synchronously in a separate process. Identical to + ‘process-file’ but temporarily enables Cygwin’s "noglob" option + during the call and ensures unix eol conversion. + + If an error occurs when using one of the above functions, then that +is usually due to a bug, i.e., using an argument which is not actually +supported. Such errors are usually not reported, but when they occur we +need to be able to debug them. + + -- User Option: magit-git-debug + Whether to report errors that occur when using ‘magit-git-insert’, + ‘magit-git-string’, ‘magit-git-lines’, or ‘magit-git-items’. This + does not actually raise an error. Instead a message is shown in + the echo area, and git’s standard error is insert into a new + section in the current repository’s process buffer. + + -- Function: magit-git-str &rest args + This is a variant of ‘magit-git-string’ that ignores the option + ‘magit-git-debug’. It is mainly intended to be used while handling + errors in functions that do respect that option. Using such a + function while handing an error could cause yet another error and + therefore lead to an infinite recursion. You probably won’t ever + need to use this function. + + +File: magit.info, Node: Calling Git for Effect, Prev: Getting a Value from Git, Up: Calling Git + +10.1.2 Calling Git for Effect +----------------------------- + +These functions are used to run git to produce some effect. Most Magit +commands that actually run git do so by using such a function. + + Because we do not need to consume git’s output when using these +functions, their output is instead logged into a per-repository buffer, +which can be shown using ‘$’ from a Magit buffer or ‘M-x magit-process’ +elsewhere. + + These functions can have an effect in two distinct ways. Firstly, +running git may change something, i.e., create or push a new commit. +Secondly, that change may require that Magit buffers are refreshed to +reflect the changed state of the repository. But refreshing isn’t +always desirable, so only some of these functions do perform such a +refresh after git has returned. + + Sometimes it is useful to run git asynchronously. For example, when +the user has just initiated a push, then there is no reason to make her +wait until that has completed. In other cases it makes sense to wait +for git to complete before letting the user do something else. For +example after staging a change it is useful to wait until after the +refresh because that also automatically moves to the next change. + + -- Function: magit-call-git &rest args + Calls git synchronously with ARGS. + + -- Function: magit-call-process program &rest args + Calls PROGRAM synchronously with ARGS. + + -- Function: magit-run-git &rest args + Calls git synchronously with ARGS and then refreshes. + + -- Function: magit-run-git-with-input &rest args + Calls git synchronously with ARGS and sends it the content of the + current buffer on standard input. + + If the current buffer’s ‘default-directory’ is on a remote + filesystem, this function actually runs git asynchronously. But + then it waits for the process to return, so the function itself is + synchronous. + + -- Function: magit-git &rest args + Calls git synchronously with ARGS for side-effects only. This + function does not refresh the buffer. + + -- Function: magit-git-wash washer &rest args + Execute Git with ARGS, inserting washed output at point. Actually + first insert the raw output at point. If there is no output call + ‘magit-cancel-section’. Otherwise temporarily narrow the buffer to + the inserted text, move to its beginning, and then call function + WASHER with ARGS as its sole argument. + + And now for the asynchronous variants. + + -- Function: magit-run-git-async &rest args + Start Git, prepare for refresh, and return the process object. + ARGS is flattened and then used as arguments to Git. + + Display the command line arguments in the echo area. + + After Git returns some buffers are refreshed: the buffer that was + current when this function was called (if it is a Magit buffer and + still alive), as well as the respective Magit status buffer. + Unmodified buffers visiting files that are tracked in the current + repository are reverted if ‘magit-revert-buffers’ is non-nil. + + -- Function: magit-run-git-with-editor &rest args + Export GIT_EDITOR and start Git. Also prepare for refresh and + return the process object. ARGS is flattened and then used as + arguments to Git. + + Display the command line arguments in the echo area. + + After Git returns some buffers are refreshed: the buffer that was + current when this function was called (if it is a Magit buffer and + still alive), as well as the respective Magit status buffer. + + -- Function: magit-start-git input &rest args + Start Git, prepare for refresh, and return the process object. + + If INPUT is non-nil, it has to be a buffer or the name of an + existing buffer. The buffer content becomes the processes standard + input. + + Option ‘magit-git-executable’ specifies the Git executable and + option ‘magit-git-global-arguments’ specifies constant arguments. + The remaining arguments ARGS specify arguments to Git. They are + flattened before use. + + After Git returns, some buffers are refreshed: the buffer that was + current when this function was called (if it is a Magit buffer and + still alive), as well as the respective Magit status buffer. + Unmodified buffers visiting files that are tracked in the current + repository are reverted if ‘magit-revert-buffers’ is non-nil. + + -- Function: magit-start-process &rest args + Start PROGRAM, prepare for refresh, and return the process object. + + If optional argument INPUT is non-nil, it has to be a buffer or the + name of an existing buffer. The buffer content becomes the + processes standard input. + + The process is started using ‘start-file-process’ and then setup to + use the sentinel ‘magit-process-sentinel’ and the filter + ‘magit-process-filter’. Information required by these functions is + stored in the process object. When this function returns the + process has not started to run yet so it is possible to override + the sentinel and filter. + + After the process returns, ‘magit-process-sentinel’ refreshes the + buffer that was current when ‘magit-start-process’ was called (if + it is a Magit buffer and still alive), as well as the respective + Magit status buffer. Unmodified buffers visiting files that are + tracked in the current repository are reverted if + ‘magit-revert-buffers’ is non-nil. + + -- Variable: magit-this-process + The child process which is about to start. This can be used to + change the filter and sentinel. + + -- Variable: magit-process-raise-error + When this is non-nil, then ‘magit-process-sentinel’ raises an error + if git exits with a non-zero exit status. For debugging purposes. + + +File: magit.info, Node: Section Plumbing, Next: Refreshing Buffers, Prev: Calling Git, Up: Plumbing + +10.2 Section Plumbing +===================== + +* Menu: + +* Creating Sections:: +* Section Selection:: +* Matching Sections:: + + +File: magit.info, Node: Creating Sections, Next: Section Selection, Up: Section Plumbing + +10.2.1 Creating Sections +------------------------ + + -- Macro: magit-insert-section &rest args + Insert a section at point. + + TYPE is the section type, a symbol. Many commands that act on the + current section behave differently depending on that type. Also if + a variable ‘magit-TYPE-section-map’ exists, then use that as the + text-property ‘keymap’ of all text belonging to the section (but + this may be overwritten in subsections). TYPE can also have the + form ‘(eval FORM)’ in which case FORM is evaluated at runtime. + + Optional VALUE is the value of the section, usually a string that + is required when acting on the section. + + When optional HIDE is non-nil collapse the section body by default, + i.e., when first creating the section, but not when refreshing the + buffer. Otherwise, expand it by default. This can be overwritten + using ‘magit-section-set-visibility-hook’. When a section is + recreated during a refresh, then the visibility of predecessor is + inherited and HIDE is ignored (but the hook is still honored). + + BODY is any number of forms that actually insert the section’s + heading and body. Optional NAME, if specified, has to be a symbol, + which is then bound to the struct of the section being inserted. + + Before BODY is evaluated the ‘start’ of the section object is set + to the value of ‘point’ and after BODY was evaluated its ‘end’ is + set to the new value of ‘point’; BODY is responsible for moving + ‘point’ forward. + + If it turns out inside BODY that the section is empty, then + ‘magit-cancel-section’ can be used to abort and remove all traces + of the partially inserted section. This can happen when creating a + section by washing Git’s output and Git didn’t actually output + anything this time around. + + -- Function: magit-insert-heading &rest args + Insert the heading for the section currently being inserted. + + This function should only be used inside ‘magit-insert-section’. + + When called without any arguments, then just set the ‘content’ slot + of the object representing the section being inserted to a marker + at ‘point’. The section should only contain a single line when + this function is used like this. + + When called with arguments ARGS, which have to be strings, then + insert those strings at point. The section should not contain any + text before this happens and afterwards it should again only + contain a single line. If the ‘face’ property is set anywhere + inside any of these strings, then insert all of them unchanged. + Otherwise use the ‘magit-section-heading’ face for all inserted + text. + + The ‘content’ property of the section struct is the end of the + heading (which lasts from ‘start’ to ‘content’) and the beginning + of the body (which lasts from ‘content’ to ‘end’). If the value of + ‘content’ is nil, then the section has no heading and its body + cannot be collapsed. If a section does have a heading then its + height must be exactly one line, including a trailing newline + character. This isn’t enforced; you are responsible for getting it + right. The only exception is that this function does insert a + newline character if necessary. + + -- Function: magit-cancel-section + Cancel the section currently being inserted. This exits the + innermost call to ‘magit-insert-section’ and removes all traces of + what has already happened inside that call. + + -- Function: magit-define-section-jumper sym title &optional value + Define an interactive function to go to section SYM. TITLE is the + displayed title of the section. + + +File: magit.info, Node: Section Selection, Next: Matching Sections, Prev: Creating Sections, Up: Section Plumbing + +10.2.2 Section Selection +------------------------ + + -- Function: magit-current-section + Return the section at point. + + -- Function: magit-region-sections &optional condition multiple + Return a list of the selected sections. + + When the region is active and constitutes a valid section + selection, then return a list of all selected sections. This is + the case when the region begins in the heading of a section and + ends in the heading of the same section or in that of a sibling + section. If optional MULTIPLE is non-nil, then the region cannot + begin and end in the same section. + + When the selection is not valid, then return nil. In this case, + most commands that can act on the selected sections will instead + act on the section at point. + + When the region looks like it would in any other buffer then the + selection is invalid. When the selection is valid then the region + uses the ‘magit-section-highlight’ face. This does not apply to + diffs where things get a bit more complicated, but even here if the + region looks like it usually does, then that’s not a valid + selection as far as this function is concerned. + + If optional CONDITION is non-nil, then the selection not only has + to be valid; all selected sections additionally have to match + CONDITION, or nil is returned. See ‘magit-section-match’ for the + forms CONDITION can take. + + -- Function: magit-region-values &optional condition multiple + Return a list of the values of the selected sections. + + Return the values that themselves would be returned by + ‘magit-region-sections’ (which see). + + +File: magit.info, Node: Matching Sections, Prev: Section Selection, Up: Section Plumbing + +10.2.3 Matching Sections +------------------------ + +‘M-x magit-describe-section-briefly’ + Show information about the section at point. This command is + intended for debugging purposes. + + -- Function: magit-section-ident section + Return an unique identifier for SECTION. The return value has the + form ‘((TYPE . VALUE)...)’. + + -- Function: magit-get-section ident &optional root + Return the section identified by IDENT. IDENT has to be a list as + returned by ‘magit-section-ident’. + + -- Function: magit-section-match condition &optional section + Return ‘t’ if SECTION matches CONDITION. SECTION defaults to the + section at point. If SECTION is not specified and there also is no + section at point, then return ‘nil’. + + CONDITION can take the following forms: + • ‘(CONDITION...)’ + + matches if any of the CONDITIONs matches. + + • ‘[CLASS...]’ + + matches if the section’s class is the same as the first CLASS + or a subclass of that; the section’s parent class matches the + second CLASS; and so on. + + • ‘[* CLASS...]’ + + matches sections that match ‘[CLASS...]’ and also recursively + all their child sections. + + • ‘CLASS’ + + matches if the section’s class is the same as CLASS or a + subclass of that; regardless of the classes of the parent + sections. + + Each CLASS should be a class symbol, identifying a class that + derives from ‘magit-section’. For backward compatibility CLASS can + also be a "type symbol". A section matches such a symbol if the + value of its ‘type’ slot is ‘eq’. If a type symbol has an entry in + ‘magit--section-type-alist’, then a section also matches that type + if its class is a subclass of the class that corresponds to the + type as per that alist. + + Note that it is not necessary to specify the complete section + lineage as printed by ‘magit-describe-section-briefly’, unless of + course you want to be that precise. + + -- Function: magit-section-value-if condition &optional section + If the section at point matches CONDITION, then return its value. + + If optional SECTION is non-nil then test whether that matches + instead. If there is no section at point and SECTION is nil, then + return nil. If the section does not match, then return nil. + + See ‘magit-section-match’ for the forms CONDITION can take. + + -- Function: magit-section-case &rest clauses + Choose among clauses on the type of the section at point. + + Each clause looks like (CONDITION BODY...). The type of the + section is compared against each CONDITION; the BODY forms of the + first match are evaluated sequentially and the value of the last + form is returned. Inside BODY the symbol ‘it’ is bound to the + section at point. If no clause succeeds or if there is no section + at point return nil. + + See ‘magit-section-match’ for the forms CONDITION can take. + Additionally a CONDITION of t is allowed in the final clause and + matches if no other CONDITION match, even if there is no section at + point. + + -- Variable: magit-root-section + The root section in the current buffer. All other sections are + descendants of this section. The value of this variable is set by + ‘magit-insert-section’ and you should never modify it. + + For diff related sections a few additional tools exist. + + -- Function: magit-diff-type &optional section + Return the diff type of SECTION. + + The returned type is one of the symbols ‘staged’, ‘unstaged’, + ‘committed’, or ‘undefined’. This type serves a similar purpose as + the general type common to all sections (which is stored in the + ‘type’ slot of the corresponding ‘magit-section’ struct) but takes + additional information into account. When the SECTION isn’t + related to diffs and the buffer containing it also isn’t a + diff-only buffer, then return nil. + + Currently the type can also be one of ‘tracked’ and ‘untracked’, + but these values are not handled explicitly in every place they + should be. A possible fix could be to just return nil here. + + The section has to be a ‘diff’ or ‘hunk’ section, or a section + whose children are of type ‘diff’. If optional SECTION is nil, + return the diff type for the current section. In buffers whose + major mode is ‘magit-diff-mode’ SECTION is ignored and the type is + determined using other means. In ‘magit-revision-mode’ buffers the + type is always ‘committed’. + + -- Function: magit-diff-scope &optional section strict + Return the diff scope of SECTION or the selected section(s). + + A diff’s "scope" describes what part of a diff is selected, it is a + symbol, one of ‘region’, ‘hunk’, ‘hunks’, ‘file’, ‘files’, or + ‘list’. Do not confuse this with the diff "type", as returned by + ‘magit-diff-type’. + + If optional SECTION is non-nil, then return the scope of that, + ignoring the sections selected by the region. Otherwise return the + scope of the current section, or if the region is active and + selects a valid group of diff related sections, the type of these + sections, i.e., ‘hunks’ or ‘files’. If SECTION (or if the current + section that is nil) is a ‘hunk’ section and the region starts and + ends inside the body of a that section, then the type is ‘region’. + + If optional STRICT is non-nil then return nil if the diff type of + the section at point is ‘untracked’ or the section at point is not + actually a ‘diff’ but a ‘diffstat’ section. + + +File: magit.info, Node: Refreshing Buffers, Next: Conventions, Prev: Section Plumbing, Up: Plumbing + +10.3 Refreshing Buffers +======================= + +All commands that create a new Magit buffer or change what is being +displayed in an existing buffer do so by calling ‘magit-mode-setup’. +Among other things, that function sets the buffer local values of +‘default-directory’ (to the top-level of the repository), +‘magit-refresh-function’, and ‘magit-refresh-args’. + + Buffers are refreshed by calling the function that is the local value +of ‘magit-refresh-function’ (a function named ‘magit-*-refresh-buffer’, +where ‘*’ may be something like ‘diff’) with the value of +‘magit-refresh-args’ as arguments. + + -- Macro: magit-mode-setup buffer switch-func mode refresh-func + &optional refresh-args + This function displays and selects BUFFER, turns on MODE, and + refreshes a first time. + + This function displays and optionally selects BUFFER by calling + ‘magit-mode-display-buffer’ with BUFFER, MODE and SWITCH-FUNC as + arguments. Then it sets the local value of + ‘magit-refresh-function’ to REFRESH-FUNC and that of + ‘magit-refresh-args’ to REFRESH-ARGS. Finally it creates the + buffer content by calling REFRESH-FUNC with REFRESH-ARGS as + arguments. + + All arguments are evaluated before switching to BUFFER. + + -- Function: magit-mode-display-buffer buffer mode &optional + switch-function + This function display BUFFER in some window and select it. BUFFER + may be a buffer or a string, the name of a buffer. The buffer is + returned. + + Unless BUFFER is already displayed in the selected frame, store the + previous window configuration as a buffer local value, so that it + can later be restored by ‘magit-mode-bury-buffer’. + + The buffer is displayed and selected using SWITCH-FUNCTION. If + that is ‘nil’ then ‘pop-to-buffer’ is used if the current buffer’s + major mode derives from ‘magit-mode’. Otherwise ‘switch-to-buffer’ + is used. + + -- Variable: magit-refresh-function + The value of this buffer-local variable is the function used to + refresh the current buffer. It is called with ‘magit-refresh-args’ + as arguments. + + -- Variable: magit-refresh-args + The list of arguments used by ‘magit-refresh-function’ to refresh + the current buffer. ‘magit-refresh-function’ is called with these + arguments. + + The value is usually set using ‘magit-mode-setup’, but in some + cases it’s also useful to provide commands that can change the + value. For example, the ‘magit-diff-refresh’ transient can be used + to change any of the arguments used to display the diff, without + having to specify again which differences should be shown, but + ‘magit-diff-more-context’, ‘magit-diff-less-context’ and + ‘magit-diff-default-context’ change just the ‘-U<N>’ argument. In + both case this is done by changing the value of this variable and + then calling this ‘magit-refresh-function’. + + +File: magit.info, Node: Conventions, Prev: Refreshing Buffers, Up: Plumbing + +10.4 Conventions +================ + +Also see *note Completion and Confirmation::. + +* Menu: + +* Theming Faces:: + + +File: magit.info, Node: Theming Faces, Up: Conventions + +10.4.1 Theming Faces +-------------------- + +The default theme uses blue for local branches, green for remote +branches, and goldenrod (brownish yellow) for tags. When creating a new +theme, you should probably follow that example. If your theme already +uses other colors, then stick to that. + + In older releases these reference faces used to have a background +color and a box around them. The basic default faces no longer do so, +to make Magit buffers much less noisy, and you should follow that +example at least with regards to boxes. (Boxes were used in the past to +work around a conflict between the highlighting overlay and text +property backgrounds. That’s no longer necessary because highlighting +no longer causes other background colors to disappear.) Alternatively +you can keep the background color and/or box, but then have to take +special care to adjust ‘magit-branch-current’ accordingly. By default +it looks mostly like ‘magit-branch-local’, but with a box (by default +the former is the only face that uses a box, exactly so that it sticks +out). If the former also uses a box, then you have to make sure that it +differs in some other way from the latter. + + The most difficult faces to theme are those related to diffs, +headings, highlighting, and the region. There are faces that fall into +all four groups - expect to spend some time getting this right. + + The ‘region’ face in the default theme, in both the light and dark +variants, as well as in many other themes, distributed with Emacs or by +third-parties, is very ugly. It is common to use a background color +that really sticks out, which is ugly but if that were the only problem +then it would be acceptable. Unfortunately many themes also set the +foreground color, which ensures that all text within the region is +readable. Without doing that there might be cases where some foreground +color is too close to the region background color to still be readable. +But it also means that text within the region loses all syntax +highlighting. + + I consider the work that went into getting the ‘region’ face right to +be a good indicator for the general quality of a theme. My +recommendation for the ‘region’ face is this: use a background color +slightly different from the background color of the ‘default’ face, and +do not set the foreground color at all. So for a light theme you might +use a light (possibly tinted) gray as the background color of ‘default’ +and a somewhat darker gray for the background of ‘region’. That should +usually be enough to not collide with the foreground color of any other +face. But if some other faces also set a light gray as background +color, then you should also make sure it doesn’t collide with those (in +some cases it might be acceptable though). + + Magit only uses the ‘region’ face when the region is "invalid" by its +own definition. In a Magit buffer the region is used to either select +multiple sibling sections, so that commands which support it act on all +of these sections instead of just the current section, or to select +lines within a single hunk section. In all other cases, the section is +considered invalid and Magit won’t act on it. But such invalid sections +happen, either because the user has not moved point enough yet to make +it valid or because she wants to use a non-magit command to act on the +region, e.g., ‘kill-region’. + + So using the regular ‘region’ face for invalid sections is a feature. +It tells the user that Magit won’t be able to act on it. It’s +acceptable if that face looks a bit odd and even (but less so) if it +collides with the background colors of section headings and other things +that have a background color. + + Magit highlights the current section. If a section has subsections, +then all of them are highlighted. This is done using faces that have +"highlight" in their names. For most sections, +‘magit-section-highlight’ is used for both the body and the heading. +Like the ‘region’ face, it should only set the background color to +something similar to that of ‘default’. The highlight background color +must be different from both the ‘region’ background color and the +‘default’ background color. + + For diff related sections Magit uses various faces to highlight +different parts of the selected section(s). Note that hunk headings, +unlike all other section headings, by default have a background color, +because it is useful to have very visible separators between hunks. +That face ‘magit-diff-hunk-heading’, should be different from both +‘magit-diff-hunk-heading-highlight’ and ‘magit-section-highlight’, as +well as from ‘magit-diff-context’ and ‘magit-diff-context-highlight’. +By default we do that by changing the foreground color. Changing the +background color would lead to complications, and there are already +enough we cannot get around. (Also note that it is generally a good +idea for section headings to always be bold, but only for sections that +have subsections). + + When there is a valid region selecting diff-related sibling sections, +i.e., multiple files or hunks, then the bodies of all these sections use +the respective highlight faces, but additionally the headings instead +use one of the faces ‘magit-diff-file-heading-selection’ or +‘magit-diff-hunk-heading-selection’. These faces have to be different +from the regular highlight variants to provide explicit visual +indication that the region is active. + + When theming diff related faces, start by setting the option +‘magit-diff-refine-hunk’ to ‘all’. You might personally prefer to only +refine the current hunk or not use hunk refinement at all, but some of +the users of your theme want all hunks to be refined, so you have to +cater to that. + + (Also turn on ‘magit-diff-highlight-indentation’, +‘magit-diff-highlight-trailing’, and ‘magit-diff-paint-whitespace’; and +insert some whitespace errors into the code you use for testing.) + + For added lines you have to adjust three faces: ‘magit-diff-added’, +‘magit-diff-added-highlight’, and ‘diff-refined-added’. Make sure that +the latter works well with both of the former, as well as ‘smerge-other’ +and ‘diff-added’. Then do the same for the removed lines, context +lines, lines added by us, and lines added by them. Also make sure the +respective added, removed, and context faces use approximately the same +saturation for both the highlighted and unhighlighted variants. Also +make sure the file and diff headings work nicely with context lines +(e.g., make them look different). Line faces should set both the +foreground and the background color. For example, for added lines use +two different greens. + + It’s best if the foreground color of both the highlighted and the +unhighlighted variants are the same, so you will need to have to find a +color that works well on the highlight and unhighlighted background, the +refine background, and the highlight context background. When there is +an hunk internal region, then the added- and removed-lines background +color is used only within that region. Outside the region the +highlighted context background color is used. This makes it easier to +see what is being staged. With an hunk internal region the hunk heading +is shown using ‘magit-diff-hunk-heading-selection’, and so are the thin +lines that are added around the lines that fall within the region. The +background color of that has to be distinct enough from the various +other involved background colors. + + Nobody said this would be easy. If your theme restricts itself to a +certain set of colors, then you should make an exception here. +Otherwise it would be impossible to make the diffs look good in each and +every variation. Actually you might want to just stick to the default +definitions for these faces. You have been warned. Also please note +that if you do not get this right, this will in some cases look to users +like bugs in Magit - so please do it right or not at all. + + +File: magit.info, Node: FAQ, Next: Debugging Tools, Prev: Plumbing, Up: Top + +Appendix A FAQ +************** + +The next two nodes lists frequently asked questions. For a list of +frequently *and recently* asked questions, i.e., questions that haven’t +made it into the manual yet, see +<https://github.com/magit/magit/wiki/FAQ>. + + Please also see *note Debugging Tools::. + +* Menu: + +* FAQ - How to ...?:: +* FAQ - Issues and Errors:: + + +File: magit.info, Node: FAQ - How to ...?, Next: FAQ - Issues and Errors, Up: FAQ + +A.1 FAQ - How to ...? +===================== + +* Menu: + +* How to pronounce Magit?:: +* How to show git's output?:: +* How to install the gitman info manual?:: +* How to show diffs for gpg-encrypted files?:: +* How does branching and pushing work?:: +* Should I disable VC?:: + + +File: magit.info, Node: How to pronounce Magit?, Next: How to show git's output?, Up: FAQ - How to ...? + +A.1.1 How to pronounce Magit? +----------------------------- + +Either ‘mu[m's] git’ or ‘magi{c => t}’ is fine. + + The slogan is "It’s Magit! The magical Git client", so it makes +sense to pronounce Magit like magic, while taking into account that C +and T do not sound the same. + + The German "Magie" is not pronounced the same as the English "magic", +so if you speak German then you can use the above rationale to justify +using the former pronunciation; ‘Mag{ie => it}’. + + You can also choose to use the former pronunciation just because you +like it better. + + Also see <https://magit.vc/assets/videos/magic.mp4>. Also see +<https://emacs.stackexchange.com/questions/13696>. + + +File: magit.info, Node: How to show git's output?, Next: How to install the gitman info manual?, Prev: How to pronounce Magit?, Up: FAQ - How to ...? + +A.1.2 How to show git’s output? +------------------------------- + +To show the output of recently run git commands, press ‘$’ (or, if that +isn’t available, ‘M-x magit-process-buffer’). This will show a buffer +containing a section per git invocation; as always press ‘TAB’ to expand +or collapse them. + + By default, git’s output is only inserted into the process buffer if +it is run for side-effects. When the output is consumed in some way, +also inserting it into the process buffer would be too expensive. For +debugging purposes, it’s possible to do so anyway by setting +‘magit-git-debug’ to ‘t’. + + +File: magit.info, Node: How to install the gitman info manual?, Next: How to show diffs for gpg-encrypted files?, Prev: How to show git's output?, Up: FAQ - How to ...? + +A.1.3 How to install the gitman info manual? +-------------------------------------------- + +Git’s manpages can be exported as an info manual called ‘gitman’. +Magit’s own info manual links to nodes in that manual instead of the +actual manpages because Info doesn’t support linking to manpages. + + Unfortunately some distributions do not install the ‘gitman’ manual +by default and you will have to install a separate documentation package +to get it. + + Magit patches Info adding the ability to visit links to the ‘gitman’ +Info manual by instead viewing the respective manpage. If you prefer +that approach, then set the value of ‘magit-view-git-manual-method’ to +one of the supported packages ‘man’ or ‘woman’, e.g.: + + (setq magit-view-git-manual-method 'man) + + +File: magit.info, Node: How to show diffs for gpg-encrypted files?, Next: How does branching and pushing work?, Prev: How to install the gitman info manual?, Up: FAQ - How to ...? + +A.1.4 How to show diffs for gpg-encrypted files? +------------------------------------------------ + +Git supports showing diffs for encrypted files, but has to be told to do +so. Since Magit just uses Git to get the diffs, configuring Git also +affects the diffs displayed inside Magit. + + git config --global diff.gpg.textconv "gpg --no-tty --decrypt" + echo "*.gpg filter=gpg diff=gpg" > .gitattributes + + +File: magit.info, Node: How does branching and pushing work?, Next: Should I disable VC?, Prev: How to show diffs for gpg-encrypted files?, Up: FAQ - How to ...? + +A.1.5 How does branching and pushing work? +------------------------------------------ + +Please see *note Branching:: and +<https://emacsair.me/2016/01/17/magit-2.4> + + +File: magit.info, Node: Should I disable VC?, Prev: How does branching and pushing work?, Up: FAQ - How to ...? + +A.1.6 Should I disable VC? +-------------------------- + +If you don’t use VC (the built-in version control interface) then you +might be tempted to disable it, not least because we used to recommend +that you do that. + + We no longer recommend that you disable VC. Doing so would break +useful third-party packages (such as ‘diff-hl’), which depend on VC +being enabled. + + If you choose to disable VC anyway, then you can do so by changing +the value of ‘vc-handled-backends’. + + +File: magit.info, Node: FAQ - Issues and Errors, Prev: FAQ - How to ...?, Up: FAQ + +A.2 FAQ - Issues and Errors +=========================== + +* Menu: + +* Magit is slow:: +* I changed several thousand files at once and now Magit is unusable:: +* I am having problems committing:: +* I am using MS Windows and cannot push with Magit:: +* I am using macOS and SOMETHING works in shell, but not in Magit: I am using macOS and SOMETHING works in shell but not in Magit. +* Expanding a file to show the diff causes it to disappear:: +* Point is wrong in the COMMIT_EDITMSG buffer:: +* The mode-line information isn't always up-to-date:: +* A branch and tag sharing the same name breaks SOMETHING:: +* My Git hooks work on the command-line but not inside Magit:: +* git-commit-mode isn't used when committing from the command-line:: +* Point ends up inside invisible text when jumping to a file-visiting buffer:: +* I am no longer able to save popup defaults:: + + +File: magit.info, Node: Magit is slow, Next: I changed several thousand files at once and now Magit is unusable, Up: FAQ - Issues and Errors + +A.2.1 Magit is slow +------------------- + +See *note Performance:: and *note I changed several thousand files at +once and now Magit is unusable::. + + +File: magit.info, Node: I changed several thousand files at once and now Magit is unusable, Next: I am having problems committing, Prev: Magit is slow, Up: FAQ - Issues and Errors + +A.2.2 I changed several thousand files at once and now Magit is unusable +------------------------------------------------------------------------ + +Magit is currently not expected to work well under such conditions. It +sure would be nice if it did. Reaching satisfactory performance under +such conditions will require some heavy refactoring. This is no small +task but I hope to eventually find the time to make it happen. + + But for now we recommend you use the command line to complete this +one commit. Also see *note Performance::. + + +File: magit.info, Node: I am having problems committing, Next: I am using MS Windows and cannot push with Magit, Prev: I changed several thousand files at once and now Magit is unusable, Up: FAQ - Issues and Errors + +A.2.3 I am having problems committing +------------------------------------- + +That likely means that Magit is having problems finding an appropriate +emacsclient executable. See *note (with-editor)Configuring +With-Editor:: and *note (with-editor)Debugging::. + + +File: magit.info, Node: I am using MS Windows and cannot push with Magit, Next: I am using macOS and SOMETHING works in shell but not in Magit, Prev: I am having problems committing, Up: FAQ - Issues and Errors + +A.2.4 I am using MS Windows and cannot push with Magit +------------------------------------------------------ + +It’s almost certain that Magit is only incidental to this issue. It is +much more likely that this is a configuration issue, even if you can +push on the command line. + + Detailed setup instructions can be found at +<https://github.com/magit/magit/wiki/Pushing-with-Magit-from-Windows>. + + +File: magit.info, Node: I am using macOS and SOMETHING works in shell but not in Magit, Next: Expanding a file to show the diff causes it to disappear, Prev: I am using MS Windows and cannot push with Magit, Up: FAQ - Issues and Errors + +A.2.5 I am using macOS and SOMETHING works in shell, but not in Magit +--------------------------------------------------------------------- + +This usually occurs because Emacs doesn’t have the same environment +variables as your shell. Try installing and configuring +<https://github.com/purcell/exec-path-from-shell>. By default it +synchronizes ‘$PATH’, which helps Magit find the same ‘git’ as the one +you are using on the shell. + + If SOMETHING is "passphrase caching with gpg-agent for commit and/or +tag signing", then you’ll also need to synchronize ‘$GPG_AGENT_INFO’. + + +File: magit.info, Node: Expanding a file to show the diff causes it to disappear, Next: Point is wrong in the COMMIT_EDITMSG buffer, Prev: I am using macOS and SOMETHING works in shell but not in Magit, Up: FAQ - Issues and Errors + +A.2.6 Expanding a file to show the diff causes it to disappear +-------------------------------------------------------------- + +This is probably caused by a customization of a ‘diff.*’ Git variable. +You probably set that variable for a reason, and should therefore only +undo that setting in Magit by customizing ‘magit-git-global-arguments’. + + +File: magit.info, Node: Point is wrong in the COMMIT_EDITMSG buffer, Next: The mode-line information isn't always up-to-date, Prev: Expanding a file to show the diff causes it to disappear, Up: FAQ - Issues and Errors + +A.2.7 Point is wrong in the ‘COMMIT_EDITMSG’ buffer +--------------------------------------------------- + +Neither Magit nor ‘git-commit.el’ fiddle with point in the buffer used +to write commit messages, so something else must be doing it. + + You have probably globally enabled a mode which restores point in +file-visiting buffers. It might be a bit surprising, but when you write +a commit message, then you are actually editing a file. + + So you have to figure out which package is doing it. ‘saveplace’, +‘pointback’, and ‘session’ are likely candidates. These snippets might +help: + + (setq session-name-disable-regexp "\\(?:\\`'\\.git/[A-Z_]+\\'\\)") + + (with-eval-after-load 'pointback + (lambda () + (when (or git-commit-mode git-rebase-mode) + (pointback-mode -1)))) + + +File: magit.info, Node: The mode-line information isn't always up-to-date, Next: A branch and tag sharing the same name breaks SOMETHING, Prev: Point is wrong in the COMMIT_EDITMSG buffer, Up: FAQ - Issues and Errors + +A.2.8 The mode-line information isn’t always up-to-date +------------------------------------------------------- + +Magit is not responsible for the version control information that is +being displayed in the mode-line and looks something like ‘Git-master’. +The built-in "Version Control" package, also known as "VC", updates that +information, and can be told to do so more often: + + (setq auto-revert-check-vc-info t) + + But doing so isn’t good for performance. For more (overly +optimistic) information see *note (emacs)VC Mode Line::. + + If you don’t really care about seeing this information in the +mode-line, but just don’t want to see _incorrect_ information, then +consider simply not displaying it in the mode-line: + + (setq-default mode-line-format + (delete '(vc-mode vc-mode) mode-line-format)) + + +File: magit.info, Node: A branch and tag sharing the same name breaks SOMETHING, Next: My Git hooks work on the command-line but not inside Magit, Prev: The mode-line information isn't always up-to-date, Up: FAQ - Issues and Errors + +A.2.9 A branch and tag sharing the same name breaks SOMETHING +------------------------------------------------------------- + +Or more generally, ambiguous refnames break SOMETHING. + + Magit assumes that refs are named non-ambiguously across the +"refs/heads/", "refs/tags/", and "refs/remotes/" namespaces (i.e., all +the names remain unique when those prefixes are stripped). We consider +ambiguous refnames unsupported and recommend that you use a +non-ambiguous naming scheme. However, if you do work with a repository +that has ambiguous refnames, please report any issues you encounter, so +that we can investigate whether there is a simple fix. + + +File: magit.info, Node: My Git hooks work on the command-line but not inside Magit, Next: git-commit-mode isn't used when committing from the command-line, Prev: A branch and tag sharing the same name breaks SOMETHING, Up: FAQ - Issues and Errors + +A.2.10 My Git hooks work on the command-line but not inside Magit +----------------------------------------------------------------- + +When Magit calls ‘git’ it adds a few global arguments including +‘--literal-pathspecs’ and the ‘git’ process started by Magit then passes +that setting on to other ‘git’ process it starts itself. It does so by +setting the environment variable ‘GIT_LITERAL_PATHSPECS’, not by calling +subprocesses with the ‘--literal-pathspecs’ argument. You can therefore +override this setting in hook scripts using ‘unset +GIT_LITERAL_PATHSPECS’. + + +File: magit.info, Node: git-commit-mode isn't used when committing from the command-line, Next: Point ends up inside invisible text when jumping to a file-visiting buffer, Prev: My Git hooks work on the command-line but not inside Magit, Up: FAQ - Issues and Errors + +A.2.11 ‘git-commit-mode’ isn’t used when committing from the command-line +------------------------------------------------------------------------- + +The reason for this is that ‘git-commit.el’ has not been loaded yet +and/or that the server has not been started yet. These things have +always already been taken care of when you commit from Magit because in +order to do so, Magit has to be loaded and doing that involves loading +‘git-commit’ and starting the server. + + If you want to commit from the command-line, then you have to take +care of these things yourself. Your ‘init.el’ file should contain: + + (require 'git-commit) + (server-mode) + + Instead of ‘(require ’git-commit)‘ you may also use: + + (load "/path/to/magit-autoloads.el") + + You might want to do that because loading ‘git-commit’ causes large +parts of Magit to be loaded. + + There are also some variations of ‘(server-mode)’ that you might want +to try. Personally I use: + + (use-package server + :config (or (server-running-p) (server-mode))) + + Now you can use: + + $ emacs& + $ EDITOR=emacsclient git commit + + However you cannot use: + + $ killall emacs + $ EDITOR="emacsclient --alternate-editor emacs" git commit + + This will actually end up using ‘emacs’, not ‘emacsclient’. If you +do this, then you can still edit the commit message but +‘git-commit-mode’ won’t be used and you have to exit ‘emacs’ to finish +the process. + + Tautology ahead. If you want to be able to use ‘emacsclient’ to +connect to a running ‘emacs’ instance, even though no ‘emacs’ instance +is running, then you cannot use ‘emacsclient’ directly. + + Instead you have to create a script that does something like this: + + Try to use ‘emacsclient’ (without using ‘--alternate-editor’). If +that succeeds, do nothing else. Otherwise start ‘emacs &’ (and +‘init.el’ must call ‘server-start’) and try to use ‘emacsclient’ again. + + +File: magit.info, Node: Point ends up inside invisible text when jumping to a file-visiting buffer, Next: I am no longer able to save popup defaults, Prev: git-commit-mode isn't used when committing from the command-line, Up: FAQ - Issues and Errors + +A.2.12 Point ends up inside invisible text when jumping to a file-visiting buffer +--------------------------------------------------------------------------------- + +This can happen when you type ‘RET’ on a hunk to visit the respective +file at the respective position. One solution to this problem is to use +‘global-reveal-mode’. It makes sure that text around point is always +visible. If that is too drastic for your taste, then you may instead +use ‘magit-diff-visit-file-hook’ to reveal the text, possibly using +‘reveal-post-command’ or for Org buffers ‘org-reveal’. + + +File: magit.info, Node: I am no longer able to save popup defaults, Prev: Point ends up inside invisible text when jumping to a file-visiting buffer, Up: FAQ - Issues and Errors + +A.2.13 I am no longer able to save popup defaults +------------------------------------------------- + +Magit used to use Magit-Popup to implement the transient popup menus. +Now it used Transient instead, which is Magit-Popup’s successor. + + In the older Magit-Popup menus, it was possible to save user settings +(e.g., setting the gpg signing key for commits) by using ‘C-c C-c’ in +the popup buffer. This would dismiss the popup, but save the settings +as the defaults for future popups. + + When switching to Transient menus, this functionality is now +available via ‘C-x C-s’ instead; the ‘C-x’ prefix has other options as +well when using Transient, which will be displayed when it is typed. +See <https://magit.vc/manual/transient/Saving-Values.html#Saving-Values> +for more details. + + +File: magit.info, Node: Debugging Tools, Next: Keystroke Index, Prev: FAQ, Up: Top + +B Debugging Tools +***************** + +Magit and its dependencies provide a few debugging tools, and we +appreciate it very much if you use those tools before reporting an +issue. Please include all relevant output when reporting an issue. + +‘M-x magit-version’ + This command shows the currently used versions of Magit, Git, and + Emacs in the echo area. Non-interactively this just returns the + Magit version. + +‘M-x magit-emacs-Q-command’ + This command shows a debugging shell command in the echo area and + adds it to the kill ring. Paste that command into a shell and run + it. + + This shell command starts ‘emacs’ with only ‘magit’ and its + dependencies loaded. Neither your configuration nor other + installed packages are loaded. This makes it easier to determine + whether some issue lays with Magit or something else. + + If you run Magit from its Git repository, then you should be able + to use ‘make emacs-Q’ instead of the output of this command. + +‘M-x magit-toggle-git-debug’ + This command toggles whether additional git errors are reported. + + Magit basically calls git for one of these two reasons: for + side-effects or to do something with its standard output. + + When git is run for side-effects then its output, including error + messages, go into the process buffer which is shown when using ‘$’. + + When git’s output is consumed in some way, then it would be too + expensive to also insert it into this buffer, but when this option + is non-nil and git returns with a non-zero exit status, then at + least its standard error is inserted into this buffer. + + This is only intended for debugging purposes. Do not enable this + permanently, that would negatively affect performance. Also note + that just because git exits with a non-zero exit status and prints + an error message that usually doesn’t mean that it is an error as + far as Magit is concerned, which is another reason we usually hide + these error messages. Whether some error message is relevant in + the context of some unexpected behavior has to be judged on a case + by case basis. + +‘M-x magit-toggle-verbose-refresh’ + This command toggles whether Magit refreshes buffers verbosely. + Enabling this helps figuring out which sections are bottlenecks. + The additional output can be found in the ‘*Messages*’ buffer. + +‘M-x magit-debug-git-executable’ + This command displays a buffer containing information about the + available and used ‘git’ executable(s), and can be useful when + investigating ‘exec-path’ issues. + + Also see *note Git Executable::. + +‘M-x with-editor-debug’ + This command displays a buffer containing information about the + available and used ‘emacsclient’ executable(s), and can be useful + when investigating why Magit (or rather ‘with-editor’) cannot find + an appropriate ‘emacsclient’ executable. + + Also see *note (with-editor)Debugging::. + +Please also see *note FAQ::. + + +File: magit.info, Node: Keystroke Index, Next: Function and Command Index, Prev: Debugging Tools, Up: Top + +Appendix C Keystroke Index +************************** + + +* Menu: + +* !: Running Git Manually. + (line 13) +* ! !: Running Git Manually. + (line 17) +* ! a: Running Git Manually. + (line 53) +* ! b: Running Git Manually. + (line 56) +* ! g: Running Git Manually. + (line 59) +* ! k: Running Git Manually. + (line 50) +* ! m: Running Git Manually. + (line 62) +* ! p: Running Git Manually. + (line 25) +* ! s: Running Git Manually. + (line 34) +* ! S: Running Git Manually. + (line 38) +* $: Viewing Git Output. (line 17) +* +: Log Buffer. (line 64) +* + <1>: Refreshing Diffs. (line 65) +* -: Log Buffer. (line 67) +* - <1>: Refreshing Diffs. (line 62) +* 0: Refreshing Diffs. (line 68) +* 1: Section Visibility. (line 39) +* 2: Section Visibility. (line 39) +* 3: Section Visibility. (line 39) +* 4: Section Visibility. (line 39) +* 5: Repository List. (line 115) +* :: Running Git Manually. + (line 25) +* =: Log Buffer. (line 59) +* >: Sparse checkouts. (line 17) +* > a: Sparse checkouts. (line 39) +* > d: Sparse checkouts. (line 50) +* > e: Sparse checkouts. (line 21) +* > r: Sparse checkouts. (line 44) +* > s: Sparse checkouts. (line 33) +* ^: Section Movement. (line 28) +* a: Applying. (line 34) +* A: Cherry Picking. (line 9) +* A A: Cherry Picking. (line 17) +* A a: Cherry Picking. (line 23) +* A A <1>: Cherry Picking. (line 85) +* A a <1>: Cherry Picking. (line 91) +* A d: Cherry Picking. (line 51) +* A h: Cherry Picking. (line 40) +* A n: Cherry Picking. (line 62) +* A s: Cherry Picking. (line 72) +* A s <1>: Cherry Picking. (line 88) +* B: Bisecting. (line 9) +* b: Blaming. (line 115) +* b <1>: Branch Commands. (line 13) +* b <2>: Editing Rebase Sequences. + (line 70) +* B B: Bisecting. (line 16) +* B b: Bisecting. (line 32) +* b b: Branch Commands. (line 47) +* b C: Branch Commands. (line 31) +* b c: Branch Commands. (line 63) +* B g: Bisecting. (line 36) +* B k: Bisecting. (line 46) +* b k: Branch Commands. (line 138) +* b l: Branch Commands. (line 69) +* B m: Bisecting. (line 40) +* b m: Branch Commands. (line 149) +* b n: Branch Commands. (line 54) +* B r: Bisecting. (line 51) +* B s: Bisecting. (line 26) +* b s: Branch Commands. (line 91) +* b S: Branch Commands. (line 118) +* b x: Branch Commands. (line 123) +* c: Blaming. (line 141) +* C: Cloning Repository. (line 20) +* c <1>: Initiating a Commit. (line 9) +* c <2>: Editing Rebase Sequences. + (line 59) +* C >: Cloning Repository. (line 38) +* c a: Initiating a Commit. (line 18) +* c A: Initiating a Commit. (line 59) +* C b: Cloning Repository. (line 44) +* C C: Cloning Repository. (line 28) +* c c: Initiating a Commit. (line 14) +* C d: Cloning Repository. (line 55) +* C e: Cloning Repository. (line 61) +* c e: Initiating a Commit. (line 21) +* c f: Initiating a Commit. (line 39) +* c F: Initiating a Commit. (line 46) +* C m: Cloning Repository. (line 48) +* C s: Cloning Repository. (line 32) +* c s: Initiating a Commit. (line 49) +* c S: Initiating a Commit. (line 56) +* c w: Initiating a Commit. (line 30) +* C-<return>: Visiting Files and Blobs from a Diff. + (line 50) +* C-<tab>: Section Visibility. (line 14) +* C-c C-a: Commit Pseudo Headers. + (line 16) +* C-c C-b: Log Buffer. (line 20) +* C-c C-b <1>: Refreshing Diffs. (line 84) +* C-c C-c: Select from Log. (line 21) +* C-c C-c <1>: Editing Commit Messages. + (line 18) +* C-c C-c <2>: Editing Rebase Sequences. + (line 7) +* C-c C-d: Refreshing Diffs. (line 75) +* C-c C-d <1>: Editing Commit Messages. + (line 54) +* C-c C-e: Commands Available in Diffs. + (line 24) +* C-c C-f: Log Buffer. (line 23) +* C-c C-f <1>: Refreshing Diffs. (line 87) +* C-c C-i: Commit Pseudo Headers. + (line 13) +* C-c C-k: Select from Log. (line 26) +* C-c C-k <1>: Editing Commit Messages. + (line 22) +* C-c C-k <2>: Editing Rebase Sequences. + (line 11) +* C-c C-n: Log Buffer. (line 26) +* C-c C-o: Commit Pseudo Headers. + (line 28) +* C-c C-p: Commit Pseudo Headers. + (line 31) +* C-c C-r: Commit Pseudo Headers. + (line 19) +* C-c C-s: Commit Pseudo Headers. + (line 22) +* C-c C-t: Commands Available in Diffs. + (line 15) +* C-c C-t <1>: Commit Pseudo Headers. + (line 25) +* C-c C-w: Using the Revision Stack. + (line 7) +* C-c f: Commands for Buffers Visiting Files. + (line 52) +* C-c f , c: Commands for Buffers Visiting Files. + (line 52) +* C-c f , k: Commands for Buffers Visiting Files. + (line 52) +* C-c f , r: Commands for Buffers Visiting Files. + (line 52) +* C-c f , x: Commands for Buffers Visiting Files. + (line 52) +* C-c f B: Blaming. (line 28) +* C-c f b: Blaming. (line 28) +* C-c f B <1>: Commands for Buffers Visiting Files. + (line 52) +* C-c f b <1>: Commands for Buffers Visiting Files. + (line 52) +* C-c f B b: Blaming. (line 28) +* C-c f B e: Blaming. (line 28) +* C-c f B f: Blaming. (line 28) +* C-c f B q: Blaming. (line 28) +* C-c f B r: Blaming. (line 28) +* C-c f c: Commands for Buffers Visiting Files. + (line 52) +* C-c f D: Commands for Buffers Visiting Files. + (line 52) +* C-c f d: Commands for Buffers Visiting Files. + (line 52) +* C-c f e: Blaming. (line 28) +* C-c f e <1>: Commands for Buffers Visiting Files. + (line 52) +* C-c f f: Blaming. (line 28) +* C-c f f <1>: Commands for Buffers Visiting Files. + (line 52) +* C-c f g: Commands for Buffers Visiting Files. + (line 52) +* C-c f G: Commands for Buffers Visiting Files. + (line 52) +* C-c f L: Commands for Buffers Visiting Files. + (line 52) +* C-c f l: Commands for Buffers Visiting Files. + (line 52) +* C-c f M: Commands for Buffers Visiting Files. + (line 52) +* C-c f m: Commands for Buffers Visiting Files. + (line 52) +* C-c f n: Commands for Buffers Visiting Files. + (line 52) +* C-c f p: Commands for Buffers Visiting Files. + (line 52) +* C-c f q: Blaming. (line 28) +* C-c f q <1>: Commands for Buffers Visiting Files. + (line 52) +* C-c f r: Blaming. (line 28) +* C-c f r <1>: Commands for Buffers Visiting Files. + (line 52) +* C-c f s: Commands for Buffers Visiting Files. + (line 52) +* C-c f s <1>: Commands for Buffers Visiting Files. + (line 52) +* C-c f t: Commands for Buffers Visiting Files. + (line 52) +* C-c f u: Commands for Buffers Visiting Files. + (line 52) +* C-c f u <1>: Commands for Buffers Visiting Files. + (line 52) +* C-c f v: Commands for Buffers Visiting Files. + (line 52) +* C-c f V: Commands for Buffers Visiting Files. + (line 52) +* C-c g: Transient Commands. (line 20) +* C-c M-g: Commands for Buffers Visiting Files. + (line 58) +* C-c M-g , c: Commands for Buffers Visiting Files. + (line 86) +* C-c M-g , k: Commands for Buffers Visiting Files. + (line 82) +* C-c M-g , r: Commands for Buffers Visiting Files. + (line 78) +* C-c M-g , x: Commands for Buffers Visiting Files. + (line 74) +* C-c M-g B: Blaming. (line 34) +* C-c M-g b: Blaming. (line 45) +* C-c M-g B <1>: Commands for Buffers Visiting Files. + (line 137) +* C-c M-g B b: Blaming. (line 45) +* C-c M-g B e: Blaming. (line 76) +* C-c M-g B f: Blaming. (line 68) +* C-c M-g B q: Blaming. (line 87) +* C-c M-g B r: Blaming. (line 60) +* C-c M-g c: Commands for Buffers Visiting Files. + (line 176) +* C-c M-g D: Commands for Buffers Visiting Files. + (line 91) +* C-c M-g d: Commands for Buffers Visiting Files. + (line 101) +* C-c M-g e: Blaming. (line 76) +* C-c M-g e <1>: Commands for Buffers Visiting Files. + (line 182) +* C-c M-g f: Blaming. (line 68) +* C-c M-g g: Commands for Buffers Visiting Files. + (line 166) +* C-c M-g G: Commands for Buffers Visiting Files. + (line 172) +* C-c M-g L: Commands for Buffers Visiting Files. + (line 109) +* C-c M-g l: Commands for Buffers Visiting Files. + (line 119) +* C-c M-g M: Commands for Buffers Visiting Files. + (line 132) +* C-c M-g n: Commands for Buffers Visiting Files. + (line 153) +* C-c M-g p: Commands for Buffers Visiting Files. + (line 149) +* C-c M-g q: Blaming. (line 87) +* C-c M-g r: Blaming. (line 60) +* C-c M-g s: Commands for Buffers Visiting Files. + (line 63) +* C-c M-g s <1>: Commands for Buffers Visiting Files. + (line 63) +* C-c M-g t: Commands for Buffers Visiting Files. + (line 129) +* C-c M-g u: Commands for Buffers Visiting Files. + (line 69) +* C-c M-g u <1>: Commands for Buffers Visiting Files. + (line 69) +* C-c M-g v: Commands for Buffers Visiting Files. + (line 156) +* C-c M-g V: Commands for Buffers Visiting Files. + (line 160) +* C-c M-i: Commit Pseudo Headers. + (line 35) +* C-c M-s: Editing Commit Messages. + (line 33) +* C-c TAB: Section Visibility. (line 14) +* C-w: Common Commands. (line 22) +* C-x g: Status Buffer. (line 23) +* C-x M-g: Transient Commands. (line 20) +* C-x u: Editing Rebase Sequences. + (line 77) +* d: Diffing. (line 22) +* D: Refreshing Diffs. (line 16) +* d c: Diffing. (line 63) +* d d: Diffing. (line 27) +* D f: Refreshing Diffs. (line 45) +* D F: Refreshing Diffs. (line 49) +* D g: Refreshing Diffs. (line 21) +* d p: Diffing. (line 56) +* d r: Diffing. (line 30) +* D r: Refreshing Diffs. (line 41) +* d s: Diffing. (line 48) +* D s: Refreshing Diffs. (line 25) +* d t: Diffing. (line 67) +* D t: Refreshing Diffs. (line 38) +* d u: Diffing. (line 53) +* d w: Diffing. (line 43) +* D w: Refreshing Diffs. (line 31) +* DEL: Log Buffer. (line 50) +* DEL <1>: Commands Available in Diffs. + (line 56) +* DEL <2>: Blaming. (line 103) +* DEL <3>: Editing Rebase Sequences. + (line 25) +* e: Ediffing. (line 10) +* E: Ediffing. (line 21) +* e <1>: Editing Rebase Sequences. + (line 46) +* E c: Ediffing. (line 100) +* E i: Ediffing. (line 94) +* E m: Ediffing. (line 33) +* E M: Ediffing. (line 48) +* E r: Ediffing. (line 25) +* E s: Ediffing. (line 87) +* E t: Ediffing. (line 79) +* E u: Ediffing. (line 91) +* E w: Ediffing. (line 97) +* E z: Ediffing. (line 103) +* f: Repository List. (line 111) +* f <1>: Editing Rebase Sequences. + (line 52) +* f <2>: Fetching. (line 10) +* F: Pulling. (line 10) +* f a: Fetching. (line 45) +* f C: Branch Commands. (line 31) +* F C: Branch Commands. (line 31) +* f e: Fetching. (line 34) +* F e: Pulling. (line 28) +* f m: Fetching. (line 48) +* f o: Fetching. (line 37) +* f p: Fetching. (line 15) +* F p: Pulling. (line 14) +* f r: Fetching. (line 41) +* f u: Fetching. (line 22) +* F u: Pulling. (line 21) +* g: Automatic Refreshing of Magit Buffers. + (line 26) +* G: Automatic Refreshing of Magit Buffers. + (line 34) +* H: Section Types and Values. + (line 14) +* I: Creating Repository. (line 7) +* j: Log Buffer. (line 31) +* j <1>: Commands Available in Diffs. + (line 43) +* k: Viewing Git Output. (line 24) +* k <1>: Applying. (line 40) +* k <2>: Editing Rebase Sequences. + (line 56) +* k <3>: Stashing. (line 118) +* l: Logging. (line 28) +* L: Refreshing Logs. (line 12) +* L <1>: Log Buffer. (line 7) +* L <2>: Log Margin. (line 52) +* l <1>: Editing Rebase Sequences. + (line 94) +* l a: Logging. (line 59) +* l b: Logging. (line 56) +* L d: Log Margin. (line 66) +* L g: Refreshing Logs. (line 17) +* l h: Logging. (line 38) +* l H: Reflog. (line 18) +* l l: Logging. (line 33) +* l L: Logging. (line 53) +* L L: Refreshing Logs. (line 34) +* L L <1>: Log Margin. (line 60) +* L l: Log Margin. (line 63) +* l o: Logging. (line 47) +* l O: Reflog. (line 15) +* l r: Reflog. (line 12) +* L s: Refreshing Logs. (line 21) +* l u: Logging. (line 41) +* L w: Refreshing Logs. (line 27) +* m: Repository List. (line 105) +* m <1>: Merging. (line 10) +* M: Remote Commands. (line 14) +* m a: Merging. (line 42) +* m a <1>: Merging. (line 91) +* M a: Remote Commands. (line 48) +* M C: Remote Commands. (line 32) +* m e: Merging. (line 30) +* m i: Merging. (line 54) +* M k: Remote Commands. (line 60) +* m m: Merging. (line 18) +* m m <1>: Merging. (line 86) +* m n: Merging. (line 36) +* m p: Merging. (line 75) +* M p: Remote Commands. (line 63) +* M P: Remote Commands. (line 67) +* M r: Remote Commands. (line 52) +* m s: Merging. (line 67) +* M u: Remote Commands. (line 56) +* M-1: Section Visibility. (line 45) +* M-2: Section Visibility. (line 45) +* M-3: Section Visibility. (line 45) +* M-4: Section Visibility. (line 45) +* M-<tab>: Section Visibility. (line 29) +* M-n: Section Movement. (line 24) +* M-n <1>: Editing Commit Messages. + (line 41) +* M-n <2>: Editing Rebase Sequences. + (line 40) +* M-p: Section Movement. (line 19) +* M-p <1>: Editing Commit Messages. + (line 36) +* M-p <2>: Editing Rebase Sequences. + (line 37) +* M-w: Blaming. (line 134) +* M-w <1>: Common Commands. (line 39) +* MM: Editing Rebase Sequences. + (line 102) +* Mt: Editing Rebase Sequences. + (line 108) +* n: Section Movement. (line 16) +* n <1>: Blaming. (line 118) +* N: Blaming. (line 121) +* n <2>: Editing Rebase Sequences. + (line 34) +* n <3>: Minor Mode for Buffers Visiting Blobs. + (line 16) +* o: Submodule Transient. (line 7) +* O: Subtree. (line 9) +* o a: Submodule Transient. (line 20) +* o d: Submodule Transient. (line 45) +* O e: Subtree. (line 37) +* O e p: Subtree. (line 48) +* O e s: Subtree. (line 52) +* o f: Submodule Transient. (line 51) +* O i: Subtree. (line 13) +* O i a: Subtree. (line 24) +* O i c: Subtree. (line 28) +* O i f: Subtree. (line 34) +* O i m: Subtree. (line 31) +* o l: Submodule Transient. (line 48) +* o p: Submodule Transient. (line 32) +* o r: Submodule Transient. (line 26) +* o s: Submodule Transient. (line 40) +* o u: Submodule Transient. (line 36) +* p: Section Movement. (line 11) +* p <1>: Blaming. (line 124) +* P: Blaming. (line 127) +* p <2>: Editing Rebase Sequences. + (line 31) +* P <1>: Pushing. (line 10) +* p <3>: Minor Mode for Buffers Visiting Blobs. + (line 13) +* P C: Branch Commands. (line 31) +* P e: Pushing. (line 29) +* P m: Pushing. (line 45) +* P o: Pushing. (line 33) +* P p: Pushing. (line 15) +* P r: Pushing. (line 37) +* P t: Pushing. (line 52) +* P T: Pushing. (line 59) +* P u: Pushing. (line 22) +* q: Quitting Windows. (line 7) +* q <1>: Log Buffer. (line 14) +* q <2>: Blaming. (line 130) +* q <3>: Minor Mode for Buffers Visiting Blobs. + (line 19) +* r: Rebasing. (line 10) +* r <1>: Editing Rebase Sequences. + (line 43) +* r a: Rebasing. (line 111) +* r e: Rebasing. (line 42) +* r e <1>: Rebasing. (line 107) +* r f: Rebasing. (line 79) +* r i: Rebasing. (line 76) +* r k: Rebasing. (line 91) +* r m: Rebasing. (line 83) +* r p: Rebasing. (line 28) +* r r: Rebasing. (line 97) +* r s: Rebasing. (line 47) +* r s <1>: Rebasing. (line 103) +* r u: Rebasing. (line 35) +* r w: Rebasing. (line 87) +* RET: Repository List. (line 102) +* RET <1>: References Buffer. (line 159) +* RET <2>: Visiting Files and Blobs from a Diff. + (line 9) +* RET <3>: Blaming. (line 91) +* RET <4>: Editing Rebase Sequences. + (line 15) +* s: Staging and Unstaging. + (line 29) +* S: Staging and Unstaging. + (line 36) +* s <1>: Editing Rebase Sequences. + (line 49) +* S-<tab>: Section Visibility. (line 33) +* SPC: Log Buffer. (line 41) +* SPC <1>: Commands Available in Diffs. + (line 53) +* SPC <2>: Blaming. (line 94) +* SPC <3>: Editing Rebase Sequences. + (line 19) +* t: Editing Rebase Sequences. + (line 97) +* t <1>: Tagging. (line 9) +* T: Notes. (line 9) +* T a: Notes. (line 47) +* T c: Notes. (line 43) +* t k: Tagging. (line 37) +* T m: Notes. (line 35) +* t p: Tagging. (line 43) +* T p: Notes. (line 28) +* t r: Tagging. (line 18) +* T r: Notes. (line 21) +* t t: Tagging. (line 14) +* T T: Notes. (line 14) +* TAB: Section Visibility. (line 10) +* u: Repository List. (line 108) +* u <1>: Staging and Unstaging. + (line 42) +* U: Staging and Unstaging. + (line 50) +* v: Applying. (line 47) +* V: Reverting. (line 7) +* V a: Reverting. (line 35) +* V s: Reverting. (line 32) +* V V: Reverting. (line 15) +* V v: Reverting. (line 20) +* V V <1>: Reverting. (line 29) +* W: Plain Patches. (line 7) +* w: Maildir Patches. (line 9) +* w a: Plain Patches. (line 20) +* w a <1>: Maildir Patches. (line 23) +* w a <2>: Maildir Patches. (line 38) +* W c: Plain Patches. (line 12) +* w m: Maildir Patches. (line 20) +* W s: Plain Patches. (line 26) +* w s: Maildir Patches. (line 34) +* w w: Maildir Patches. (line 14) +* w w <1>: Maildir Patches. (line 31) +* x: Editing Rebase Sequences. + (line 62) +* x <1>: Resetting. (line 9) +* X f: Resetting. (line 44) +* X h: Resetting. (line 24) +* X i: Resetting. (line 33) +* X k: Resetting. (line 28) +* X m: Resetting. (line 15) +* X s: Resetting. (line 19) +* X w: Resetting. (line 39) +* X w <1>: Wip Modes. (line 64) +* Y: Cherries. (line 18) +* y: References Buffer. (line 7) +* y <1>: Editing Rebase Sequences. + (line 74) +* y c: References Buffer. (line 25) +* y o: References Buffer. (line 30) +* y r: References Buffer. (line 34) +* y y: References Buffer. (line 21) +* z: Stashing. (line 9) +* Z: Worktree. (line 9) +* z a: Stashing. (line 52) +* z b: Stashing. (line 105) +* z B: Stashing. (line 110) +* Z b: Worktree. (line 13) +* Z c: Worktree. (line 16) +* z f: Stashing. (line 115) +* Z g: Worktree. (line 26) +* z i: Stashing. (line 20) +* z I: Stashing. (line 42) +* z k: Stashing. (line 98) +* Z k: Worktree. (line 22) +* z l: Stashing. (line 121) +* Z m: Worktree. (line 19) +* z p: Stashing. (line 74) +* z v: Stashing. (line 102) +* z w: Stashing. (line 24) +* z W: Stashing. (line 46) +* z x: Stashing. (line 30) +* z z: Stashing. (line 14) +* z Z: Stashing. (line 36) + + +File: magit.info, Node: Function and Command Index, Next: Variable Index, Prev: Keystroke Index, Up: Top + +Appendix D Function and Command Index +************************************* + + +* Menu: + +* bug-reference-mode: Commit Mode and Hooks. + (line 48) +* forward-line: Editing Rebase Sequences. + (line 34) +* git-commit-ack: Commit Pseudo Headers. + (line 16) +* git-commit-cc: Commit Pseudo Headers. + (line 28) +* git-commit-check-style-conventions: Commit Message Conventions. + (line 33) +* git-commit-insert-pseudo-header: Commit Pseudo Headers. + (line 13) +* git-commit-next-message: Editing Commit Messages. + (line 41) +* git-commit-prev-message: Editing Commit Messages. + (line 36) +* git-commit-propertize-diff: Commit Mode and Hooks. + (line 40) +* git-commit-reported: Commit Pseudo Headers. + (line 31) +* git-commit-review: Commit Pseudo Headers. + (line 19) +* git-commit-save-message: Editing Commit Messages. + (line 33) +* git-commit-save-message <1>: Commit Mode and Hooks. + (line 26) +* git-commit-setup-changelog-support: Commit Mode and Hooks. + (line 29) +* git-commit-signoff: Commit Pseudo Headers. + (line 22) +* git-commit-suggested: Commit Pseudo Headers. + (line 35) +* git-commit-test: Commit Pseudo Headers. + (line 25) +* git-commit-turn-on-auto-fill: Commit Mode and Hooks. + (line 33) +* git-commit-turn-on-flyspell: Commit Mode and Hooks. + (line 36) +* git-rebase-backward-line: Editing Rebase Sequences. + (line 31) +* git-rebase-break: Editing Rebase Sequences. + (line 70) +* git-rebase-edit: Editing Rebase Sequences. + (line 46) +* git-rebase-exec: Editing Rebase Sequences. + (line 62) +* git-rebase-fixup: Editing Rebase Sequences. + (line 52) +* git-rebase-insert: Editing Rebase Sequences. + (line 74) +* git-rebase-kill-line: Editing Rebase Sequences. + (line 56) +* git-rebase-label: Editing Rebase Sequences. + (line 94) +* git-rebase-merge: Editing Rebase Sequences. + (line 102) +* git-rebase-merge-toggle-editmsg: Editing Rebase Sequences. + (line 108) +* git-rebase-move-line-down: Editing Rebase Sequences. + (line 40) +* git-rebase-move-line-up: Editing Rebase Sequences. + (line 37) +* git-rebase-pick: Editing Rebase Sequences. + (line 59) +* git-rebase-reset: Editing Rebase Sequences. + (line 97) +* git-rebase-reword: Editing Rebase Sequences. + (line 43) +* git-rebase-show-commit: Editing Rebase Sequences. + (line 15) +* git-rebase-show-or-scroll-down: Editing Rebase Sequences. + (line 25) +* git-rebase-show-or-scroll-up: Editing Rebase Sequences. + (line 19) +* git-rebase-squash: Editing Rebase Sequences. + (line 49) +* git-rebase-undo: Editing Rebase Sequences. + (line 77) +* ido-enter-magit-status: Status Buffer. (line 96) +* magit-add-section-hook: Section Hooks. (line 20) +* magit-after-save-refresh-status: Automatic Refreshing of Magit Buffers. + (line 55) +* magit-am: Maildir Patches. (line 9) +* magit-am-abort: Maildir Patches. (line 38) +* magit-am-apply-maildir: Maildir Patches. (line 20) +* magit-am-apply-patches: Maildir Patches. (line 14) +* magit-am-continue: Maildir Patches. (line 31) +* magit-am-skip: Maildir Patches. (line 34) +* magit-apply: Applying. (line 34) +* magit-bisect: Bisecting. (line 9) +* magit-bisect-bad: Bisecting. (line 32) +* magit-bisect-good: Bisecting. (line 36) +* magit-bisect-mark: Bisecting. (line 40) +* magit-bisect-reset: Bisecting. (line 51) +* magit-bisect-run: Bisecting. (line 26) +* magit-bisect-skip: Bisecting. (line 46) +* magit-bisect-start: Bisecting. (line 16) +* magit-blame: Blaming. (line 28) +* magit-blame <1>: Blaming. (line 34) +* magit-blame <2>: Blaming. (line 115) +* magit-blame <3>: Commands for Buffers Visiting Files. + (line 52) +* magit-blame <4>: Commands for Buffers Visiting Files. + (line 137) +* magit-blame-addition: Blaming. (line 28) +* magit-blame-addition <1>: Blaming. (line 45) +* magit-blame-additions: Commands for Buffers Visiting Files. + (line 52) +* magit-blame-copy-hash: Blaming. (line 134) +* magit-blame-cycle-style: Blaming. (line 141) +* magit-blame-echo: Blaming. (line 28) +* magit-blame-echo <1>: Blaming. (line 76) +* magit-blame-echo <2>: Commands for Buffers Visiting Files. + (line 52) +* magit-blame-next-chunk: Blaming. (line 118) +* magit-blame-next-chunk-same-commit: Blaming. (line 121) +* magit-blame-previous-chunk: Blaming. (line 124) +* magit-blame-previous-chunk-same-commit: Blaming. (line 127) +* magit-blame-quit: Blaming. (line 28) +* magit-blame-quit <1>: Blaming. (line 87) +* magit-blame-quit <2>: Blaming. (line 130) +* magit-blame-quit <3>: Commands for Buffers Visiting Files. + (line 52) +* magit-blame-removal: Blaming. (line 28) +* magit-blame-removal <1>: Blaming. (line 60) +* magit-blame-removal <2>: Commands for Buffers Visiting Files. + (line 52) +* magit-blame-reverse: Blaming. (line 28) +* magit-blame-reverse <1>: Blaming. (line 68) +* magit-blame-reverse <2>: Commands for Buffers Visiting Files. + (line 52) +* magit-blob-next: Commands for Buffers Visiting Files. + (line 52) +* magit-blob-next <1>: Commands for Buffers Visiting Files. + (line 153) +* magit-blob-next <2>: Minor Mode for Buffers Visiting Blobs. + (line 16) +* magit-blob-previous: Commands for Buffers Visiting Files. + (line 52) +* magit-blob-previous <1>: Commands for Buffers Visiting Files. + (line 149) +* magit-blob-previous <2>: Minor Mode for Buffers Visiting Blobs. + (line 13) +* magit-blob-visit-file: Commands for Buffers Visiting Files. + (line 52) +* magit-blob-visit-file <1>: Commands for Buffers Visiting Files. + (line 160) +* magit-branch: Branch Commands. (line 13) +* magit-branch-and-checkout: Branch Commands. (line 63) +* magit-branch-checkout: Branch Commands. (line 69) +* magit-branch-configure: Branch Commands. (line 31) +* magit-branch-create: Branch Commands. (line 54) +* magit-branch-delete: Branch Commands. (line 138) +* magit-branch-or-checkout: Branch Commands. (line 257) +* magit-branch-orphan: Branch Commands. (line 253) +* magit-branch-rename: Branch Commands. (line 149) +* magit-branch-reset: Branch Commands. (line 123) +* magit-branch-shelve: Auxiliary Branch Commands. + (line 9) +* magit-branch-spinoff: Branch Commands. (line 91) +* magit-branch-spinout: Branch Commands. (line 118) +* magit-branch-unshelve: Auxiliary Branch Commands. + (line 19) +* magit-builtin-completing-read: Support for Completion Frameworks. + (line 41) +* magit-bundle: Bundle. (line 8) +* magit-call-git: Calling Git for Effect. + (line 28) +* magit-call-process: Calling Git for Effect. + (line 31) +* magit-cancel-section: Creating Sections. (line 69) +* magit-checkout: Branch Commands. (line 47) +* magit-cherry: Cherries. (line 18) +* magit-cherry-apply: Cherry Picking. (line 23) +* magit-cherry-copy: Cherry Picking. (line 17) +* magit-cherry-donate: Cherry Picking. (line 51) +* magit-cherry-harvest: Cherry Picking. (line 40) +* magit-cherry-pick: Cherry Picking. (line 9) +* magit-cherry-spinoff: Cherry Picking. (line 72) +* magit-cherry-spinout: Cherry Picking. (line 62) +* magit-clone: Cloning Repository. (line 20) +* magit-clone-bare: Cloning Repository. (line 44) +* magit-clone-mirror: Cloning Repository. (line 48) +* magit-clone-regular: Cloning Repository. (line 28) +* magit-clone-shallow: Cloning Repository. (line 32) +* magit-clone-shallow-exclude: Cloning Repository. (line 61) +* magit-clone-shallow-since: Cloning Repository. (line 55) +* magit-clone-sparse: Cloning Repository. (line 38) +* magit-commit: Initiating a Commit. (line 9) +* magit-commit <1>: Commands for Buffers Visiting Files. + (line 52) +* magit-commit <2>: Commands for Buffers Visiting Files. + (line 176) +* magit-commit-amend: Initiating a Commit. (line 18) +* magit-commit-augment: Initiating a Commit. (line 59) +* magit-commit-create: Initiating a Commit. (line 14) +* magit-commit-extend: Initiating a Commit. (line 21) +* magit-commit-fixup: Initiating a Commit. (line 39) +* magit-commit-instant-fixup: Initiating a Commit. (line 46) +* magit-commit-instant-squash: Initiating a Commit. (line 56) +* magit-commit-reword: Initiating a Commit. (line 30) +* magit-commit-squash: Initiating a Commit. (line 49) +* magit-completing-read: Support for Completion Frameworks. + (line 57) +* magit-copy-buffer-revision: Common Commands. (line 39) +* magit-copy-section-value: Common Commands. (line 22) +* magit-current-section: Section Selection. (line 6) +* magit-cycle-margin-style: Log Margin. (line 63) +* magit-debug-git-executable: Git Executable. (line 55) +* magit-debug-git-executable <1>: Debugging Tools. (line 57) +* magit-define-section-jumper: Creating Sections. (line 74) +* magit-describe-section: Section Types and Values. + (line 14) +* magit-describe-section-briefly: Section Types and Values. + (line 17) +* magit-describe-section-briefly <1>: Matching Sections. (line 7) +* magit-diff: Diffing. (line 22) +* magit-diff <1>: Commands for Buffers Visiting Files. + (line 52) +* magit-diff <2>: Commands for Buffers Visiting Files. + (line 91) +* magit-diff-buffer-file: Commands for Buffers Visiting Files. + (line 52) +* magit-diff-buffer-file <1>: Commands for Buffers Visiting Files. + (line 101) +* magit-diff-default-context: Refreshing Diffs. (line 68) +* magit-diff-dwim: Diffing. (line 27) +* magit-diff-edit-hunk-commit: Commands Available in Diffs. + (line 24) +* magit-diff-flip-revs: Refreshing Diffs. (line 45) +* magit-diff-less-context: Refreshing Diffs. (line 62) +* magit-diff-more-context: Refreshing Diffs. (line 65) +* magit-diff-paths: Diffing. (line 56) +* magit-diff-range: Diffing. (line 30) +* magit-diff-refresh: Refreshing Diffs. (line 16) +* magit-diff-refresh <1>: Refreshing Diffs. (line 21) +* magit-diff-save-default-arguments: Refreshing Diffs. (line 31) +* magit-diff-scope: Matching Sections. (line 110) +* magit-diff-set-default-arguments: Refreshing Diffs. (line 25) +* magit-diff-show-or-scroll-down: Log Buffer. (line 50) +* magit-diff-show-or-scroll-down <1>: Blaming. (line 103) +* magit-diff-show-or-scroll-up: Log Buffer. (line 41) +* magit-diff-show-or-scroll-up <1>: Blaming. (line 94) +* magit-diff-staged: Diffing. (line 48) +* magit-diff-switch-range-type: Refreshing Diffs. (line 41) +* magit-diff-toggle-file-filter: Refreshing Diffs. (line 49) +* magit-diff-toggle-refine-hunk: Refreshing Diffs. (line 38) +* magit-diff-trace-definition: Commands Available in Diffs. + (line 15) +* magit-diff-type: Matching Sections. (line 88) +* magit-diff-unstaged: Diffing. (line 53) +* magit-diff-visit-file: Visiting Files and Blobs from a Diff. + (line 9) +* magit-diff-visit-file-other-frame: Visiting Files and Blobs from a Diff. + (line 71) +* magit-diff-visit-file-other-window: Visiting Files and Blobs from a Diff. + (line 70) +* magit-diff-visit-file-worktree: Visiting Files and Blobs from a Diff. + (line 50) +* magit-diff-visit-worktree-file-other-frame: Visiting Files and Blobs from a Diff. + (line 73) +* magit-diff-visit-worktree-file-other-window: Visiting Files and Blobs from a Diff. + (line 72) +* magit-diff-while-committing: Refreshing Diffs. (line 75) +* magit-diff-while-committing <1>: Editing Commit Messages. + (line 54) +* magit-diff-working-tree: Diffing. (line 43) +* magit-disable-section-inserter: Per-Repository Configuration. + (line 31) +* magit-discard: Applying. (line 40) +* magit-dispatch: Transient Commands. (line 20) +* magit-display-buffer: Switching Buffers. (line 6) +* magit-display-buffer-fullcolumn-most-v1: Switching Buffers. (line 68) +* magit-display-buffer-fullframe-status-topleft-v1: Switching Buffers. + (line 59) +* magit-display-buffer-fullframe-status-v1: Switching Buffers. + (line 54) +* magit-display-buffer-same-window-except-diff-v1: Switching Buffers. + (line 49) +* magit-display-buffer-traditional: Switching Buffers. (line 42) +* magit-display-repository-buffer: Common Commands. (line 9) +* magit-display-repository-buffer <1>: Commands for Buffers Visiting Files. + (line 52) +* magit-display-repository-buffer <2>: Commands for Buffers Visiting Files. + (line 172) +* magit-ediff: Ediffing. (line 21) +* magit-ediff-compare: Ediffing. (line 25) +* magit-ediff-dwim: Ediffing. (line 10) +* magit-ediff-resolve-all: Ediffing. (line 48) +* magit-ediff-resolve-rest: Ediffing. (line 33) +* magit-ediff-show-commit: Ediffing. (line 100) +* magit-ediff-show-staged: Ediffing. (line 94) +* magit-ediff-show-stash: Ediffing. (line 103) +* magit-ediff-show-unstaged: Ediffing. (line 91) +* magit-ediff-show-working-tree: Ediffing. (line 97) +* magit-ediff-stage: Ediffing. (line 87) +* magit-edit-line-commit: Commands for Buffers Visiting Files. + (line 52) +* magit-edit-line-commit <1>: Commands for Buffers Visiting Files. + (line 182) +* magit-emacs-Q-command: Debugging Tools. (line 16) +* magit-fetch: Fetching. (line 10) +* magit-fetch-all: Fetching. (line 45) +* magit-fetch-branch: Fetching. (line 37) +* magit-fetch-from-pushremote: Fetching. (line 15) +* magit-fetch-from-upstream: Fetching. (line 22) +* magit-fetch-modules: Fetching. (line 48) +* magit-fetch-modules <1>: Submodule Transient. (line 51) +* magit-fetch-other: Fetching. (line 34) +* magit-fetch-refspec: Fetching. (line 41) +* magit-file-checkout: Resetting. (line 44) +* magit-file-checkout <1>: Commands for Buffers Visiting Files. + (line 52) +* magit-file-checkout <2>: Commands for Buffers Visiting Files. + (line 86) +* magit-file-delete: Commands for Buffers Visiting Files. + (line 52) +* magit-file-delete <1>: Commands for Buffers Visiting Files. + (line 82) +* magit-file-dispatch: Commands for Buffers Visiting Files. + (line 52) +* magit-file-dispatch <1>: Commands for Buffers Visiting Files. + (line 58) +* magit-file-rename: Commands for Buffers Visiting Files. + (line 52) +* magit-file-rename <1>: Commands for Buffers Visiting Files. + (line 78) +* magit-file-untrack: Commands for Buffers Visiting Files. + (line 52) +* magit-file-untrack <1>: Commands for Buffers Visiting Files. + (line 74) +* magit-find-file: General-Purpose Visit Commands. + (line 9) +* magit-find-file <1>: Commands for Buffers Visiting Files. + (line 52) +* magit-find-file <2>: Commands for Buffers Visiting Files. + (line 156) +* magit-find-file-other-frame: General-Purpose Visit Commands. + (line 19) +* magit-find-file-other-window: General-Purpose Visit Commands. + (line 14) +* magit-generate-buffer-name-default-function: Naming Buffers. + (line 16) +* magit-get-section: Matching Sections. (line 14) +* magit-git: Calling Git for Effect. + (line 46) +* magit-git-command: Running Git Manually. + (line 25) +* magit-git-command-topdir: Running Git Manually. + (line 17) +* magit-git-exit-code: Getting a Value from Git. + (line 10) +* magit-git-failure: Getting a Value from Git. + (line 17) +* magit-git-false: Getting a Value from Git. + (line 25) +* magit-git-insert: Getting a Value from Git. + (line 29) +* magit-git-items: Getting a Value from Git. + (line 41) +* magit-git-lines: Getting a Value from Git. + (line 37) +* magit-git-mergetool: Running Git Manually. + (line 62) +* magit-git-mergetool <1>: Ediffing. (line 79) +* magit-git-str: Getting a Value from Git. + (line 75) +* magit-git-string: Getting a Value from Git. + (line 32) +* magit-git-success: Getting a Value from Git. + (line 13) +* magit-git-true: Getting a Value from Git. + (line 21) +* magit-git-wash: Calling Git for Effect. + (line 50) +* magit-go-backward: Log Buffer. (line 20) +* magit-go-backward <1>: Refreshing Diffs. (line 84) +* magit-go-forward: Log Buffer. (line 23) +* magit-go-forward <1>: Refreshing Diffs. (line 87) +* magit-hunk-set-window-start: Section Movement. (line 45) +* magit-ido-completing-read: Support for Completion Frameworks. + (line 46) +* magit-init: Creating Repository. (line 7) +* magit-insert-am-sequence: Status Sections. (line 25) +* magit-insert-assumed-unchanged-files: Status Sections. (line 98) +* magit-insert-bisect-log: Status Sections. (line 39) +* magit-insert-bisect-output: Status Sections. (line 33) +* magit-insert-bisect-rest: Status Sections. (line 36) +* magit-insert-diff-filter-header: Status Header Sections. + (line 35) +* magit-insert-error-header: Status Header Sections. + (line 26) +* magit-insert-head-branch-header: Status Header Sections. + (line 38) +* magit-insert-heading: Creating Sections. (line 41) +* magit-insert-ignored-files: Status Sections. (line 83) +* magit-insert-local-branches: References Sections. (line 16) +* magit-insert-merge-log: Status Sections. (line 17) +* magit-insert-modules: Status Module Sections. + (line 12) +* magit-insert-modules-overview: Status Module Sections. + (line 30) +* magit-insert-modules-unpulled-from-pushremote: Status Module Sections. + (line 45) +* magit-insert-modules-unpulled-from-upstream: Status Module Sections. + (line 40) +* magit-insert-modules-unpushed-to-pushremote: Status Module Sections. + (line 55) +* magit-insert-modules-unpushed-to-upstream: Status Module Sections. + (line 50) +* magit-insert-push-branch-header: Status Header Sections. + (line 45) +* magit-insert-rebase-sequence: Status Sections. (line 21) +* magit-insert-recent-commits: Status Sections. (line 110) +* magit-insert-remote-branches: References Sections. (line 19) +* magit-insert-remote-header: Status Header Sections. + (line 58) +* magit-insert-repo-header: Status Header Sections. + (line 55) +* magit-insert-section: Creating Sections. (line 6) +* magit-insert-sequencer-sequence: Status Sections. (line 29) +* magit-insert-skip-worktree-files: Status Sections. (line 92) +* magit-insert-staged-changes: Status Sections. (line 53) +* magit-insert-stashes: Status Sections. (line 56) +* magit-insert-status-headers: Status Header Sections. + (line 12) +* magit-insert-tags: References Sections. (line 22) +* magit-insert-tags-header: Status Header Sections. + (line 49) +* magit-insert-tracked-files: Status Sections. (line 80) +* magit-insert-unpulled-cherries: Status Sections. (line 119) +* magit-insert-unpulled-from-pushremote: Status Sections. (line 66) +* magit-insert-unpulled-from-upstream: Status Sections. (line 62) +* magit-insert-unpulled-or-recent-commits: Status Sections. (line 104) +* magit-insert-unpushed-cherries: Status Sections. (line 125) +* magit-insert-unpushed-to-pushremote: Status Sections. (line 74) +* magit-insert-unpushed-to-upstream: Status Sections. (line 70) +* magit-insert-unstaged-changes: Status Sections. (line 50) +* magit-insert-untracked-files: Status Sections. (line 42) +* magit-insert-upstream-branch-header: Status Header Sections. + (line 41) +* magit-insert-user-header: Status Header Sections. + (line 65) +* magit-jump-to-diffstat-or-diff: Commands Available in Diffs. + (line 43) +* magit-kill-this-buffer: Minor Mode for Buffers Visiting Blobs. + (line 19) +* magit-list-repositories: Repository List. (line 6) +* magit-list-submodules: Listing Submodules. (line 13) +* magit-list-submodules <1>: Submodule Transient. (line 48) +* magit-log: Logging. (line 28) +* magit-log <1>: Commands for Buffers Visiting Files. + (line 52) +* magit-log <2>: Commands for Buffers Visiting Files. + (line 109) +* magit-log-all: Logging. (line 59) +* magit-log-all-branches: Logging. (line 56) +* magit-log-branches: Logging. (line 53) +* magit-log-buffer-file: Commands for Buffers Visiting Files. + (line 52) +* magit-log-buffer-file <1>: Commands for Buffers Visiting Files. + (line 119) +* magit-log-bury-buffer: Log Buffer. (line 14) +* magit-log-current: Logging. (line 33) +* magit-log-double-commit-limit: Log Buffer. (line 64) +* magit-log-half-commit-limit: Log Buffer. (line 67) +* magit-log-head: Logging. (line 38) +* magit-log-maybe-show-more-commits: Section Movement. (line 58) +* magit-log-maybe-update-blob-buffer: Section Movement. (line 72) +* magit-log-maybe-update-revision-buffer: Section Movement. (line 65) +* magit-log-merged: Commands for Buffers Visiting Files. + (line 52) +* magit-log-merged <1>: Commands for Buffers Visiting Files. + (line 132) +* magit-log-move-to-parent: Log Buffer. (line 26) +* magit-log-move-to-revision: Log Buffer. (line 31) +* magit-log-other: Logging. (line 47) +* magit-log-refresh: Refreshing Logs. (line 12) +* magit-log-refresh <1>: Refreshing Logs. (line 17) +* magit-log-refresh <2>: Log Buffer. (line 7) +* magit-log-related: Logging. (line 41) +* magit-log-save-default-arguments: Refreshing Logs. (line 27) +* magit-log-select-pick: Select from Log. (line 21) +* magit-log-select-quit: Select from Log. (line 26) +* magit-log-set-default-arguments: Refreshing Logs. (line 21) +* magit-log-toggle-commit-limit: Log Buffer. (line 59) +* magit-log-trace-definition: Commands for Buffers Visiting Files. + (line 52) +* magit-log-trace-definition <1>: Commands for Buffers Visiting Files. + (line 129) +* magit-margin-settings: Log Margin. (line 52) +* magit-maybe-set-dedicated: Switching Buffers. (line 89) +* magit-merge: Merging. (line 10) +* magit-merge <1>: Merging. (line 86) +* magit-merge-abort: Merging. (line 91) +* magit-merge-absorb: Merging. (line 42) +* magit-merge-editmsg: Merging. (line 30) +* magit-merge-into: Merging. (line 54) +* magit-merge-nocommit: Merging. (line 36) +* magit-merge-plain: Merging. (line 18) +* magit-merge-preview: Merging. (line 75) +* magit-merge-squash: Merging. (line 67) +* magit-mode-bury-buffer: Quitting Windows. (line 7) +* magit-mode-display-buffer: Refreshing Buffers. (line 32) +* magit-mode-quit-window: Quitting Windows. (line 34) +* magit-mode-setup: Refreshing Buffers. (line 17) +* magit-notes: Notes. (line 9) +* magit-notes-edit: Notes. (line 14) +* magit-notes-merge: Notes. (line 35) +* magit-notes-merge-abort: Notes. (line 47) +* magit-notes-merge-commit: Notes. (line 43) +* magit-notes-prune: Notes. (line 28) +* magit-notes-remove: Notes. (line 21) +* magit-patch: Plain Patches. (line 7) +* magit-patch-apply: Plain Patches. (line 20) +* magit-patch-apply <1>: Maildir Patches. (line 23) +* magit-patch-create: Plain Patches. (line 12) +* magit-patch-save: Plain Patches. (line 26) +* magit-pop-revision-stack: Using the Revision Stack. + (line 7) +* magit-process: Viewing Git Output. (line 17) +* magit-process-file: Getting a Value from Git. + (line 57) +* magit-process-git: Getting a Value from Git. + (line 50) +* magit-process-kill: Viewing Git Output. (line 24) +* magit-pull: Pulling. (line 10) +* magit-pull-branch: Pulling. (line 28) +* magit-pull-from-pushremote: Pulling. (line 14) +* magit-pull-from-upstream: Pulling. (line 21) +* magit-push: Pushing. (line 10) +* magit-push-current: Pushing. (line 29) +* magit-push-current-to-pushremote: Pushing. (line 15) +* magit-push-current-to-upstream: Pushing. (line 22) +* magit-push-implicitly: Pushing. (line 74) +* magit-push-matching: Pushing. (line 45) +* magit-push-other: Pushing. (line 33) +* magit-push-refspecs: Pushing. (line 37) +* magit-push-tag: Pushing. (line 59) +* magit-push-tags: Pushing. (line 52) +* magit-push-to-remote: Pushing. (line 91) +* magit-rebase: Rebasing. (line 10) +* magit-rebase-abort: Rebasing. (line 111) +* magit-rebase-autosquash: Rebasing. (line 79) +* magit-rebase-branch: Rebasing. (line 42) +* magit-rebase-continue: Rebasing. (line 97) +* magit-rebase-edit: Rebasing. (line 107) +* magit-rebase-edit-commit: Rebasing. (line 83) +* magit-rebase-interactive: Rebasing. (line 76) +* magit-rebase-onto-pushremote: Rebasing. (line 28) +* magit-rebase-onto-upstream: Rebasing. (line 35) +* magit-rebase-remove-commit: Rebasing. (line 91) +* magit-rebase-reword-commit: Rebasing. (line 87) +* magit-rebase-skip: Rebasing. (line 103) +* magit-rebase-subset: Rebasing. (line 47) +* magit-reflog-current: Reflog. (line 12) +* magit-reflog-head: Reflog. (line 18) +* magit-reflog-other: Reflog. (line 15) +* magit-refresh: Automatic Refreshing of Magit Buffers. + (line 26) +* magit-refresh-all: Automatic Refreshing of Magit Buffers. + (line 34) +* magit-refs-set-show-commit-count: References Buffer. (line 34) +* magit-region-sections: Section Selection. (line 9) +* magit-region-values: Section Selection. (line 35) +* magit-remote: Remote Commands. (line 14) +* magit-remote-add: Remote Commands. (line 48) +* magit-remote-configure: Remote Commands. (line 32) +* magit-remote-prune: Remote Commands. (line 63) +* magit-remote-prune-refspecs: Remote Commands. (line 67) +* magit-remote-remove: Remote Commands. (line 60) +* magit-remote-rename: Remote Commands. (line 52) +* magit-remote-set-url: Remote Commands. (line 56) +* magit-repolist-column-branch: Repository List. (line 51) +* magit-repolist-column-branches: Repository List. (line 58) +* magit-repolist-column-flag: Repository List. (line 64) +* magit-repolist-column-flags: Repository List. (line 76) +* magit-repolist-column-ident: Repository List. (line 40) +* magit-repolist-column-path: Repository List. (line 44) +* magit-repolist-column-stashes: Repository List. (line 61) +* magit-repolist-column-unpulled-from-pushremote: Repository List. + (line 87) +* magit-repolist-column-unpulled-from-upstream: Repository List. + (line 83) +* magit-repolist-column-unpushed-to-pushremote: Repository List. + (line 95) +* magit-repolist-column-unpushed-to-upstream: Repository List. + (line 91) +* magit-repolist-column-upstream: Repository List. (line 54) +* magit-repolist-column-version: Repository List. (line 47) +* magit-repolist-fetch: Repository List. (line 111) +* magit-repolist-find-file-other-frame: Repository List. (line 115) +* magit-repolist-mark: Repository List. (line 105) +* magit-repolist-status: Repository List. (line 102) +* magit-repolist-unmark: Repository List. (line 108) +* magit-reset-hard: Resetting. (line 24) +* magit-reset-index: Staging and Unstaging. + (line 78) +* magit-reset-index <1>: Resetting. (line 33) +* magit-reset-keep: Resetting. (line 28) +* magit-reset-mixed: Resetting. (line 15) +* magit-reset-quickly: Resetting. (line 9) +* magit-reset-soft: Resetting. (line 19) +* magit-reset-worktree: Resetting. (line 39) +* magit-reset-worktree <1>: Wip Modes. (line 64) +* magit-restore-window-configuration: Quitting Windows. (line 24) +* magit-reverse: Applying. (line 47) +* magit-reverse-in-index: Staging and Unstaging. + (line 58) +* magit-revert: Reverting. (line 7) +* magit-revert-and-commit: Reverting. (line 15) +* magit-revert-no-commit: Reverting. (line 20) +* magit-run: Running Git Manually. + (line 13) +* magit-run-git: Calling Git for Effect. + (line 34) +* magit-run-git-async: Calling Git for Effect. + (line 59) +* magit-run-git-gui: Running Git Manually. + (line 59) +* magit-run-git-with-editor: Calling Git for Effect. + (line 71) +* magit-run-git-with-input: Calling Git for Effect. + (line 37) +* magit-run-gitk: Running Git Manually. + (line 50) +* magit-run-gitk-all: Running Git Manually. + (line 53) +* magit-run-gitk-branches: Running Git Manually. + (line 56) +* magit-save-window-configuration: Switching Buffers. (line 80) +* magit-section-backward: Section Movement. (line 11) +* magit-section-backward-siblings: Section Movement. (line 19) +* magit-section-case: Matching Sections. (line 66) +* magit-section-cycle: Section Visibility. (line 14) +* magit-section-cycle-diffs: Section Visibility. (line 29) +* magit-section-cycle-global: Section Visibility. (line 33) +* magit-section-forward: Section Movement. (line 16) +* magit-section-forward-siblings: Section Movement. (line 24) +* magit-section-hide: Section Visibility. (line 55) +* magit-section-hide-children: Section Visibility. (line 67) +* magit-section-ident: Matching Sections. (line 10) +* magit-section-match: Matching Sections. (line 18) +* magit-section-set-window-start: Section Movement. (line 52) +* magit-section-show: Section Visibility. (line 52) +* magit-section-show-children: Section Visibility. (line 62) +* magit-section-show-headings: Section Visibility. (line 58) +* magit-section-show-level-1: Section Visibility. (line 39) +* magit-section-show-level-1-all: Section Visibility. (line 45) +* magit-section-show-level-2: Section Visibility. (line 39) +* magit-section-show-level-2-all: Section Visibility. (line 45) +* magit-section-show-level-3: Section Visibility. (line 39) +* magit-section-show-level-3-all: Section Visibility. (line 45) +* magit-section-show-level-4: Section Visibility. (line 39) +* magit-section-show-level-4-all: Section Visibility. (line 45) +* magit-section-toggle: Section Visibility. (line 10) +* magit-section-toggle-children: Section Visibility. (line 70) +* magit-section-up: Section Movement. (line 28) +* magit-section-value-if: Matching Sections. (line 57) +* magit-sequence-abort: Cherry Picking. (line 91) +* magit-sequence-abort <1>: Reverting. (line 35) +* magit-sequence-continue: Cherry Picking. (line 85) +* magit-sequence-continue <1>: Reverting. (line 29) +* magit-sequence-skip: Cherry Picking. (line 88) +* magit-sequence-skip <1>: Reverting. (line 32) +* magit-shell-command: Running Git Manually. + (line 38) +* magit-shell-command-topdir: Running Git Manually. + (line 34) +* magit-show-commit: Diffing. (line 63) +* magit-show-commit <1>: Blaming. (line 91) +* magit-show-refs: References Buffer. (line 7) +* magit-show-refs-current: References Buffer. (line 25) +* magit-show-refs-head: References Buffer. (line 21) +* magit-show-refs-other: References Buffer. (line 30) +* magit-snapshot-both: Stashing. (line 36) +* magit-snapshot-index: Stashing. (line 42) +* magit-snapshot-worktree: Stashing. (line 46) +* magit-sparse-checkout: Sparse checkouts. (line 17) +* magit-sparse-checkout-add: Sparse checkouts. (line 39) +* magit-sparse-checkout-disable: Sparse checkouts. (line 50) +* magit-sparse-checkout-enable: Sparse checkouts. (line 21) +* magit-sparse-checkout-reapply: Sparse checkouts. (line 44) +* magit-sparse-checkout-set: Sparse checkouts. (line 33) +* magit-stage: Staging and Unstaging. + (line 29) +* magit-stage-buffer-file: Commands for Buffers Visiting Files. + (line 52) +* magit-stage-buffer-file <1>: Commands for Buffers Visiting Files. + (line 63) +* magit-stage-file: Staging from File-Visiting Buffers. + (line 11) +* magit-stage-file <1>: Commands for Buffers Visiting Files. + (line 52) +* magit-stage-file <2>: Commands for Buffers Visiting Files. + (line 63) +* magit-stage-modified: Staging and Unstaging. + (line 36) +* magit-start-git: Calling Git for Effect. + (line 82) +* magit-start-process: Calling Git for Effect. + (line 100) +* magit-stash: Stashing. (line 9) +* magit-stash-apply: Stashing. (line 52) +* magit-stash-both: Stashing. (line 14) +* magit-stash-branch: Stashing. (line 105) +* magit-stash-branch-here: Stashing. (line 110) +* magit-stash-clear: Stashing. (line 118) +* magit-stash-drop: Stashing. (line 98) +* magit-stash-format-patch: Stashing. (line 115) +* magit-stash-index: Stashing. (line 20) +* magit-stash-keep-index: Stashing. (line 30) +* magit-stash-list: Stashing. (line 121) +* magit-stash-pop: Stashing. (line 74) +* magit-stash-show: Diffing. (line 67) +* magit-stash-show <1>: Stashing. (line 102) +* magit-stash-worktree: Stashing. (line 24) +* magit-stashes-maybe-update-stash-buffer: Section Movement. (line 92) +* magit-status: Status Buffer. (line 23) +* magit-status-here: Commands for Buffers Visiting Files. + (line 52) +* magit-status-here <1>: Commands for Buffers Visiting Files. + (line 166) +* magit-status-maybe-update-blob-buffer: Section Movement. (line 87) +* magit-status-maybe-update-revision-buffer: Section Movement. + (line 77) +* magit-status-maybe-update-stash-buffer: Section Movement. (line 82) +* magit-status-quick: Status Buffer. (line 70) +* magit-submodule: Submodule Transient. (line 7) +* magit-submodule-add: Submodule Transient. (line 20) +* magit-submodule-populate: Submodule Transient. (line 32) +* magit-submodule-register: Submodule Transient. (line 26) +* magit-submodule-synchronize: Submodule Transient. (line 40) +* magit-submodule-unpopulate: Submodule Transient. (line 45) +* magit-submodule-update: Submodule Transient. (line 36) +* magit-subtree: Subtree. (line 9) +* magit-subtree-add: Subtree. (line 24) +* magit-subtree-add-commit: Subtree. (line 28) +* magit-subtree-export: Subtree. (line 37) +* magit-subtree-import: Subtree. (line 13) +* magit-subtree-merge: Subtree. (line 31) +* magit-subtree-pull: Subtree. (line 34) +* magit-subtree-push: Subtree. (line 48) +* magit-subtree-split: Subtree. (line 52) +* magit-switch-to-repository-buffer: Common Commands. (line 6) +* magit-switch-to-repository-buffer-other-frame: Common Commands. + (line 8) +* magit-switch-to-repository-buffer-other-window: Common Commands. + (line 7) +* magit-tag: Tagging. (line 9) +* magit-tag-create: Tagging. (line 14) +* magit-tag-delete: Tagging. (line 37) +* magit-tag-prune: Tagging. (line 43) +* magit-tag-release: Tagging. (line 18) +* magit-toggle-buffer-lock: Modes and Buffers. (line 18) +* magit-toggle-git-debug: Debugging Tools. (line 29) +* magit-toggle-margin: Refreshing Logs. (line 34) +* magit-toggle-margin <1>: Log Margin. (line 60) +* magit-toggle-margin-details: Log Margin. (line 66) +* magit-toggle-verbose-refresh: Debugging Tools. (line 52) +* magit-unstage: Staging and Unstaging. + (line 42) +* magit-unstage-all: Staging and Unstaging. + (line 50) +* magit-unstage-buffer-file: Commands for Buffers Visiting Files. + (line 52) +* magit-unstage-buffer-file <1>: Commands for Buffers Visiting Files. + (line 69) +* magit-unstage-file: Staging from File-Visiting Buffers. + (line 18) +* magit-unstage-file <1>: Commands for Buffers Visiting Files. + (line 52) +* magit-unstage-file <2>: Commands for Buffers Visiting Files. + (line 69) +* magit-version: Git Executable. (line 59) +* magit-version <1>: Debugging Tools. (line 11) +* magit-visit-ref: References Buffer. (line 159) +* magit-wip-commit: Wip Modes. (line 85) +* magit-wip-log: Wip Modes. (line 47) +* magit-wip-log-current: Wip Modes. (line 55) +* magit-worktree: Worktree. (line 9) +* magit-worktree-branch: Worktree. (line 16) +* magit-worktree-checkout: Worktree. (line 13) +* magit-worktree-delete: Worktree. (line 22) +* magit-worktree-move: Worktree. (line 19) +* magit-worktree-status: Worktree. (line 26) +* scroll-down: Commands Available in Diffs. + (line 56) +* scroll-up: Commands Available in Diffs. + (line 53) +* with-editor-cancel: Editing Commit Messages. + (line 22) +* with-editor-cancel <1>: Editing Rebase Sequences. + (line 11) +* with-editor-debug: Debugging Tools. (line 64) +* with-editor-finish: Editing Commit Messages. + (line 18) +* with-editor-finish <1>: Editing Rebase Sequences. + (line 7) +* with-editor-usage-message: Commit Mode and Hooks. + (line 51) + + +File: magit.info, Node: Variable Index, Prev: Function and Command Index, Up: Top + +Appendix E Variable Index +************************* + + +* Menu: + +* auto-revert-buffer-list-filter: Automatic Reverting of File-Visiting Buffers. + (line 73) +* auto-revert-interval: Automatic Reverting of File-Visiting Buffers. + (line 69) +* auto-revert-mode: Automatic Reverting of File-Visiting Buffers. + (line 57) +* auto-revert-stop-on-user-input: Automatic Reverting of File-Visiting Buffers. + (line 65) +* auto-revert-use-notify: Automatic Reverting of File-Visiting Buffers. + (line 46) +* auto-revert-verbose: Automatic Reverting of File-Visiting Buffers. + (line 94) +* branch.autoSetupMerge: Branch Git Variables. + (line 71) +* branch.autoSetupRebase: Branch Git Variables. + (line 85) +* branch.NAME.description: Branch Git Variables. + (line 42) +* branch.NAME.merge: Branch Git Variables. + (line 10) +* branch.NAME.pushRemote: Branch Git Variables. + (line 29) +* branch.NAME.rebase: Branch Git Variables. + (line 20) +* branch.NAME.remote: Branch Git Variables. + (line 15) +* core.notesRef: Notes. (line 53) +* git-commit-finish-query-functions: Commit Message Conventions. + (line 18) +* git-commit-known-pseudo-headers: Commit Pseudo Headers. + (line 9) +* git-commit-major-mode: Commit Mode and Hooks. + (line 12) +* git-commit-post-finish-hook: Commit Mode and Hooks. + (line 54) +* git-commit-setup-hook: Commit Mode and Hooks. + (line 21) +* git-commit-style-convention-checks: Commit Message Conventions. + (line 38) +* git-commit-summary-max-length: Commit Message Conventions. + (line 13) +* git-rebase-auto-advance: Editing Rebase Sequences. + (line 80) +* git-rebase-confirm-cancel: Editing Rebase Sequences. + (line 86) +* git-rebase-show-instructions: Editing Rebase Sequences. + (line 83) +* global-auto-revert-mode: Automatic Reverting of File-Visiting Buffers. + (line 21) +* magit-auto-revert-immediately: Automatic Reverting of File-Visiting Buffers. + (line 30) +* magit-auto-revert-mode: Automatic Reverting of File-Visiting Buffers. + (line 17) +* magit-auto-revert-tracked-only: Automatic Reverting of File-Visiting Buffers. + (line 51) +* magit-bisect-show-graph: Bisecting. (line 57) +* magit-blame-disable-modes: Blaming. (line 165) +* magit-blame-echo-style: Blaming. (line 151) +* magit-blame-goto-chunk-hook: Blaming. (line 170) +* magit-blame-read-only: Blaming. (line 161) +* magit-blame-styles: Blaming. (line 147) +* magit-blame-time-format: Blaming. (line 157) +* magit-branch-adjust-remote-upstream-alist: Branch Commands. (line 202) +* magit-branch-direct-configure: Branch Commands. (line 19) +* magit-branch-prefer-remote-upstream: Branch Commands. (line 158) +* magit-branch-read-upstream-first: Branch Commands. (line 153) +* magit-buffer-name-format: Naming Buffers. (line 25) +* magit-bury-buffer-function: Quitting Windows. (line 16) +* magit-cherry-margin: Cherries. (line 21) +* magit-clone-always-transient: Cloning Repository. (line 12) +* magit-clone-default-directory: Cloning Repository. (line 84) +* magit-clone-name-alist: Cloning Repository. (line 94) +* magit-clone-set-remote-head: Cloning Repository. (line 66) +* magit-clone-set-remote.pushDefault: Cloning Repository. (line 75) +* magit-clone-url-format: Cloning Repository. (line 114) +* magit-commit-ask-to-stage: Initiating a Commit. (line 65) +* magit-commit-diff-inhibit-same-window: Initiating a Commit. (line 97) +* magit-commit-extend-override-date: Initiating a Commit. (line 72) +* magit-commit-reword-override-date: Initiating a Commit. (line 75) +* magit-commit-show-diff: Initiating a Commit. (line 69) +* magit-commit-squash-confirm: Initiating a Commit. (line 78) +* magit-completing-read-function: Support for Completion Frameworks. + (line 27) +* magit-define-global-key-bindings: Global Bindings. (line 6) +* magit-diff-adjust-tab-width: Diff Options. (line 17) +* magit-diff-buffer-file-locked: Commands for Buffers Visiting Files. + (line 104) +* magit-diff-extra-stat-arguments: Diff Options. (line 112) +* magit-diff-hide-trailing-cr-characters: Diff Options. (line 77) +* magit-diff-highlight-hunk-region-functions: Diff Options. (line 80) +* magit-diff-highlight-indentation: Diff Options. (line 63) +* magit-diff-highlight-trailing: Diff Options. (line 59) +* magit-diff-paint-whitespace: Diff Options. (line 38) +* magit-diff-paint-whitespace-lines: Diff Options. (line 52) +* magit-diff-refine-hunk: Diff Options. (line 6) +* magit-diff-refine-ignore-whitespace: Diff Options. (line 13) +* magit-diff-unmarked-lines-keep-foreground: Diff Options. (line 105) +* magit-diff-visit-previous-blob: Visiting Files and Blobs from a Diff. + (line 38) +* magit-direct-use-buffer-arguments: Transient Arguments and Buffer Variables. + (line 73) +* magit-display-buffer-function: Switching Buffers. (line 25) +* magit-display-buffer-noselect: Switching Buffers. (line 17) +* magit-dwim-selection: Completion and Confirmation. + (line 42) +* magit-ediff-dwim-resolve-function: Ediffing. (line 105) +* magit-ediff-dwim-show-on-hunks: Ediffing. (line 111) +* magit-ediff-quit-hook: Ediffing. (line 124) +* magit-ediff-show-stash-with-index: Ediffing. (line 118) +* magit-generate-buffer-name-function: Naming Buffers. (line 6) +* magit-git-debug: Viewing Git Output. (line 26) +* magit-git-debug <1>: Getting a Value from Git. + (line 68) +* magit-git-executable: Git Executable. (line 26) +* magit-git-global-arguments: Global Git Arguments. + (line 6) +* magit-keep-region-overlay: The Selection. (line 52) +* magit-list-refs-sortby: Additional Completion Options. + (line 6) +* magit-log-auto-more: Log Buffer. (line 69) +* magit-log-buffer-file-locked: Commands for Buffers Visiting Files. + (line 124) +* magit-log-margin: Log Margin. (line 12) +* magit-log-margin-show-committer-date: Log Margin. (line 44) +* magit-log-section-commit-count: Status Sections. (line 114) +* magit-log-select-margin: Select from Log. (line 28) +* magit-log-show-color-graph-limit: Log Buffer. (line 78) +* magit-log-show-refname-after-summary: Log Buffer. (line 74) +* magit-log-show-signatures-limit: Log Buffer. (line 84) +* magit-log-trace-definition-function: Commands Available in Diffs. + (line 17) +* magit-module-sections-hook: Status Module Sections. + (line 19) +* magit-module-sections-nested: Status Module Sections. + (line 22) +* magit-no-confirm: Action Confirmation. (line 18) +* magit-pop-revision-stack-format: Using the Revision Stack. + (line 34) +* magit-post-clone-hook: Cloning Repository. (line 133) +* magit-post-commit-hook: Initiating a Commit. (line 86) +* magit-post-display-buffer-hook: Switching Buffers. (line 85) +* magit-pre-display-buffer-hook: Switching Buffers. (line 76) +* magit-prefer-remote-upstream: Branch Git Variables. + (line 108) +* magit-prefix-use-buffer-arguments: Transient Arguments and Buffer Variables. + (line 65) +* magit-process-extreme-logging: Viewing Git Output. (line 56) +* magit-process-raise-error: Calling Git for Effect. + (line 125) +* magit-pull-or-fetch: Fetching. (line 52) +* magit-reflog-margin: Reflog. (line 20) +* magit-refresh-args: Refreshing Buffers. (line 52) +* magit-refresh-buffer-hook: Automatic Refreshing of Magit Buffers. + (line 41) +* magit-refresh-function: Refreshing Buffers. (line 47) +* magit-refresh-status-buffer: Automatic Refreshing of Magit Buffers. + (line 46) +* magit-refs-filter-alist: References Buffer. (line 137) +* magit-refs-focus-column-width: References Buffer. (line 75) +* magit-refs-margin: References Buffer. (line 89) +* magit-refs-margin-for-tags: References Buffer. (line 112) +* magit-refs-pad-commit-counts: References Buffer. (line 45) +* magit-refs-primary-column-width: References Buffer. (line 63) +* magit-refs-sections-hook: References Sections. (line 13) +* magit-refs-show-commit-count: References Buffer. (line 36) +* magit-refs-show-remote-prefix: References Buffer. (line 57) +* magit-remote-add-set-remote.pushDefault: Remote Commands. (line 83) +* magit-remote-direct-configure: Remote Commands. (line 20) +* magit-remote-git-executable: Git Executable. (line 32) +* magit-repolist-columns: Repository List. (line 12) +* magit-repository-directories: Status Buffer. (line 57) +* magit-revision-filter-files-on-follow: Revision Buffer. (line 55) +* magit-revision-insert-related-refs: Revision Buffer. (line 6) +* magit-revision-show-gravatars: Revision Buffer. (line 15) +* magit-revision-use-hash-sections: Revision Buffer. (line 31) +* magit-root-section: Matching Sections. (line 81) +* magit-save-repository-buffers: Automatic Saving of File-Visiting Buffers. + (line 13) +* magit-section-cache-visibility: Section Visibility. (line 95) +* magit-section-initial-visibility-alist: Section Visibility. (line 79) +* magit-section-movement-hook: Section Movement. (line 41) +* magit-section-set-visibility-hook: Section Visibility. (line 105) +* magit-section-show-child-count: Section Options. (line 9) +* magit-section-visibility-indicator: Section Visibility. (line 122) +* magit-shell-command-verbose-prompt: Running Git Manually. + (line 43) +* magit-stashes-margin: Stashing. (line 123) +* magit-status-headers-hook: Status Header Sections. + (line 17) +* magit-status-margin: Status Options. (line 6) +* magit-status-sections-hook: Status Sections. (line 10) +* magit-submodule-list-columns: Listing Submodules. (line 20) +* magit-this-process: Calling Git for Effect. + (line 121) +* magit-uniquify-buffer-names: Naming Buffers. (line 65) +* magit-unstage-committed: Staging and Unstaging. + (line 52) +* magit-update-other-window-delay: Section Movement. (line 97) +* magit-visit-ref-behavior: References Buffer. (line 168) +* magit-wip-after-apply-mode: Legacy Wip Modes. (line 18) +* magit-wip-after-apply-mode-lighter: Legacy Wip Modes. (line 54) +* magit-wip-after-save-local-mode-lighter: Legacy Wip Modes. (line 51) +* magit-wip-after-save-mode: Legacy Wip Modes. (line 13) +* magit-wip-before-change-mode: Legacy Wip Modes. (line 31) +* magit-wip-before-change-mode-lighter: Legacy Wip Modes. (line 57) +* magit-wip-initial-backup-mode: Legacy Wip Modes. (line 35) +* magit-wip-initial-backup-mode-lighter: Legacy Wip Modes. (line 60) +* magit-wip-merge-branch: Wip Graph. (line 6) +* magit-wip-mode: Wip Modes. (line 30) +* magit-wip-mode-lighter: Wip Modes. (line 98) +* magit-wip-namespace: Wip Modes. (line 91) +* notes.displayRef: Notes. (line 57) +* pull.rebase: Branch Git Variables. + (line 50) +* remote.NAME.fetch: Remote Git Variables. + (line 14) +* remote.NAME.push: Remote Git Variables. + (line 23) +* remote.NAME.pushurl: Remote Git Variables. + (line 18) +* remote.NAME.tagOpts: Remote Git Variables. + (line 27) +* remote.NAME.url: Remote Git Variables. + (line 10) +* remote.pushDefault: Branch Git Variables. + (line 62) + + + +Tag Table: +Node: Top774 +Node: Introduction6559 +Node: Installation11275 +Node: Installing from Melpa11605 +Node: Installing from the Git Repository12680 +Node: Post-Installation Tasks15494 +Node: Getting Started16779 +Node: Interface Concepts22590 +Node: Modes and Buffers22969 +Node: Switching Buffers24680 +Node: Naming Buffers29419 +Node: Quitting Windows32494 +Node: Automatic Refreshing of Magit Buffers34429 +Node: Automatic Saving of File-Visiting Buffers37310 +Node: Automatic Reverting of File-Visiting Buffers38494 +Node: Risk of Reverting Automatically43479 +Node: Sections45861 +Node: Section Movement46787 +Node: Section Visibility51661 +Node: Section Hooks58348 +Node: Section Types and Values60754 +Node: Section Options62169 +Node: Transient Commands62640 +Node: Transient Arguments and Buffer Variables64116 +Node: Completion Confirmation and the Selection71133 +Node: Action Confirmation71579 +Node: Completion and Confirmation80084 +Node: The Selection83269 +Node: The hunk-internal region86167 +Node: Support for Completion Frameworks87256 +Node: Additional Completion Options92141 +Node: Mouse Support92739 +Node: Running Git93315 +Node: Viewing Git Output93560 +Node: Git Process Status96264 +Node: Running Git Manually97229 +Node: Git Executable99919 +Node: Global Git Arguments102927 +Node: Inspecting103732 +Node: Status Buffer104889 +Node: Status Sections109900 +Node: Status Header Sections115427 +Node: Status Module Sections118046 +Node: Status Options120543 +Node: Repository List121906 +Node: Logging126684 +Node: Refreshing Logs129523 +Node: Log Buffer130944 +Node: Log Margin135767 +Node: Select from Log138920 +Node: Reflog141130 +Node: Cherries142767 +Node: Diffing144605 +Node: Refreshing Diffs147639 +Node: Commands Available in Diffs151328 +Node: Diff Options153841 +Node: Revision Buffer159304 +Node: Ediffing162624 +Node: References Buffer168674 +Node: References Sections179268 +Node: Bisecting180125 +Node: Visiting Files and Blobs182436 +Node: General-Purpose Visit Commands182964 +Node: Visiting Files and Blobs from a Diff183917 +Node: Blaming187361 +Node: Manipulating194349 +Node: Creating Repository194691 +Node: Cloning Repository195228 +Node: Staging and Unstaging201669 +Node: Staging from File-Visiting Buffers205642 +Node: Applying206748 +Node: Committing208821 +Node: Initiating a Commit209404 +Node: Editing Commit Messages214594 +Node: Using the Revision Stack217367 +Node: Commit Pseudo Headers220412 +Node: Commit Mode and Hooks221707 +Node: Commit Message Conventions224565 +Node: Branching226552 +Node: The Two Remotes226778 +Node: Branch Commands229431 +Node: Branch Git Variables242281 +Node: Auxiliary Branch Commands247651 +Node: Merging248767 +Node: Resolving Conflicts252923 +Node: Rebasing258297 +Node: Editing Rebase Sequences263086 +Node: Information About In-Progress Rebase267302 +Ref: Information About In-Progress Rebase-Footnote-1276415 +Node: Cherry Picking277011 +Node: Reverting281345 +Node: Resetting282764 +Node: Stashing284590 +Node: Transferring290971 +Node: Remotes291193 +Node: Remote Commands291345 +Node: Remote Git Variables295384 +Node: Fetching296655 +Node: Pulling299138 +Node: Pushing300164 +Node: Plain Patches304455 +Node: Maildir Patches305926 +Node: Miscellaneous307405 +Node: Tagging307751 +Node: Notes309644 +Node: Submodules311979 +Node: Listing Submodules312197 +Node: Submodule Transient314345 +Node: Subtree316790 +Node: Worktree318721 +Node: Sparse checkouts319797 +Node: Bundle322573 +Node: Common Commands322948 +Node: Wip Modes325576 +Node: Wip Graph330467 +Node: Legacy Wip Modes332780 +Node: Commands for Buffers Visiting Files335667 +Node: Minor Mode for Buffers Visiting Blobs343894 +Node: Customizing344692 +Node: Per-Repository Configuration346288 +Node: Essential Settings348542 +Node: Safety348888 +Node: Performance350649 +Ref: Log Performance353612 +Ref: Diff Performance354917 +Ref: Refs Buffer Performance356258 +Ref: Committing Performance356833 +Node: Microsoft Windows Performance357815 +Node: MacOS Performance359006 +Ref: MacOS Performance-Footnote-1360029 +Node: Global Bindings360111 +Node: Plumbing362339 +Node: Calling Git363168 +Node: Getting a Value from Git364693 +Node: Calling Git for Effect368421 +Node: Section Plumbing374315 +Node: Creating Sections374543 +Node: Section Selection378439 +Node: Matching Sections380235 +Node: Refreshing Buffers386156 +Node: Conventions389300 +Node: Theming Faces389492 +Node: FAQ397597 +Node: FAQ - How to ...?398035 +Node: How to pronounce Magit?398392 +Node: How to show git's output?399195 +Node: How to install the gitman info manual?399981 +Node: How to show diffs for gpg-encrypted files?400951 +Node: How does branching and pushing work?401547 +Node: Should I disable VC?401880 +Node: FAQ - Issues and Errors402483 +Node: Magit is slow403428 +Node: I changed several thousand files at once and now Magit is unusable403721 +Node: I am having problems committing404447 +Node: I am using MS Windows and cannot push with Magit404928 +Node: I am using macOS and SOMETHING works in shell but not in Magit405546 +Node: Expanding a file to show the diff causes it to disappear406380 +Node: Point is wrong in the COMMIT_EDITMSG buffer406968 +Node: The mode-line information isn't always up-to-date408016 +Node: A branch and tag sharing the same name breaks SOMETHING409079 +Node: My Git hooks work on the command-line but not inside Magit409966 +Node: git-commit-mode isn't used when committing from the command-line410812 +Node: Point ends up inside invisible text when jumping to a file-visiting buffer413083 +Node: I am no longer able to save popup defaults413932 +Node: Debugging Tools414913 +Node: Keystroke Index418087 +Node: Function and Command Index459701 +Node: Variable Index517902 + +End Tag Table + + +Local Variables: +coding: utf-8 +End: diff --git a/emacs/elpa/osm-20240929.642/osm-pkg.el b/emacs/elpa/osm-20240929.642/osm-pkg.el @@ -1,11 +0,0 @@ -;; -*- no-byte-compile: t; lexical-binding: nil -*- -(define-package "osm" "20240929.642" - "OpenStreetMap viewer." - '((emacs "28.1") - (compat "30")) - :url "https://github.com/minad/osm" - :commit "2ba02faed5d57da97c1f6e13df36091d68ddefee" - :revdesc "2ba02faed5d5" - :keywords '("network" "multimedia" "hypermedia" "mouse") - :authors '(("Daniel Mendler" . "mail@daniel-mendler.de")) - :maintainers '(("Daniel Mendler" . "mail@daniel-mendler.de"))) diff --git a/emacs/elpa/osm-20240929.642/osm.el b/emacs/elpa/osm-20240929.642/osm.el @@ -1,1828 +0,0 @@ -;;; osm.el --- OpenStreetMap viewer -*- lexical-binding: t -*- - -;; Copyright (C) 2022-2024 Free Software Foundation, Inc. - -;; Author: Daniel Mendler <mail@daniel-mendler.de> -;; Maintainer: Daniel Mendler <mail@daniel-mendler.de> -;; Created: 2022 -;; Package-Version: 20240929.642 -;; Package-Revision: 2ba02faed5d5 -;; Package-Requires: ((emacs "28.1") (compat "30")) -;; URL: https://github.com/minad/osm -;; Keywords: network, multimedia, hypermedia, mouse - -;; This file is part of GNU Emacs. - -;; This program is free software: you can redistribute it and/or modify -;; it under the terms of the GNU General Public License as published by -;; the Free Software Foundation, either version 3 of the License, or -;; (at your option) any later version. - -;; This program is distributed in the hope that it will be useful, -;; but WITHOUT ANY WARRANTY; without even the implied warranty of -;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -;; GNU General Public License for more details. - -;; You should have received a copy of the GNU General Public License -;; along with this program. If not, see <https://www.gnu.org/licenses/>. - -;;; Commentary: - -;; Osm.el is a tile-based map viewer, with a responsive movable and -;; zoomable display. The map can be controlled with the keyboard or with -;; the mouse. The viewer fetches the map tiles in parallel from tile -;; servers via the `curl' program. The package comes with a list of -;; multiple preconfigured tile servers. You can bookmark your favorite -;; locations using regular Emacs bookmarks or create links from Org files -;; to locations. Furthermore the package provides commands to measure -;; distances, search for locations by name and to open and display GPX -;; tracks. - -;; osm.el requires Emacs 28 and depends on the external `curl' program. -;; Emacs must be built with libxml, libjansson, librsvg, libjpeg and -;; libpng support. - -;;; Code: - -(require 'compat) -(require 'bookmark) -(require 'dom) -(eval-when-compile - (require 'cl-lib) - (require 'subr-x)) - -(defgroup osm nil - "OpenStreetMap viewer." - :link '(info-link :tag "Info Manual" "(osm)") - :link '(url-link :tag "Website" "https://github.com/minad/osm") - :link '(emacs-library-link :tag "Library Source" "osm.el") - :group 'web - :prefix "osm-") - -(defcustom osm-curl-options - "--disable --fail --location --silent --max-time 30" - "Curl command line options." - :type 'string) - -(defcustom osm-search-language "en" - "Language used for search results. -Use RFC 1766 abbreviations, e.g.: `en' for English, `de' for German. -A comma-separated specifies descending order of preference. See also -`url-mime-language-string'." - :type 'string) - -(defcustom osm-search-server - "https://nominatim.openstreetmap.org" - "Server used to search for location names. -The server must offer the nominatim.org API." - :type 'string) - -(defcustom osm-server-defaults - '(:min-zoom 2 - :max-zoom 19 - :download-batch 4 - :max-connections 2 - :subdomains ("a" "b" "c")) - "Default server properties. -See also `osm-server-list'." - :type 'plist) - -(defcustom osm-server-list - '((default - :name "Carto" - :description "Standard Carto map provided by OpenStreetMap" - :url "https://%s.tile.openstreetmap.org/%z/%x/%y.png" - :group "Standard" - :copyright ("Map data © {OpenStreetMap|https://www.openstreetmap.org/copyright} contributors" - "Map style © {OpenStreetMap Standard|https://www.openstreetmap.org/copyright}")) - (de - :name "Carto(de)" - :description "Localized Carto map provided by OpenStreetMap Germany" - :url "https://%s.tile.openstreetmap.de/%z/%x/%y.png" - :group "Standard" - :copyright ("Map data © {OpenStreetMap|https://www.openstreetmap.org/copyright} contributors" - "Map style © {OpenStreetMap Deutschland|https://www.openstreetmap.de/germanstyle.html}")) - (fr - :name "Carto(fr)" - :description "Localized Carto map by OpenStreetMap France" - :url "https://%s.tile.openstreetmap.fr/osmfr/%z/%x/%y.png" - :group "Standard" - :copyright ("Map data © {OpenStreetMap|https://www.openstreetmap.org/copyright} contributors" - "Map style © {OpenStreetMap France|https://www.openstreetmap.fr/mentions-legales/}")) - (humanitarian - :name "Humanitarian" - :description "Humanitarian map provided by OpenStreetMap France" - :url "https://%s.tile.openstreetmap.fr/hot/%z/%x/%y.png" - :group "Special Purpose" - :copyright ("Map data © {OpenStreetMap|https://www.openstreetmap.org/copyright} contributors" - "Map style © {Humanitarian OpenStreetMap Team|https://www.hotosm.org/updates/2013-09-29_a_new_window_on_openstreetmap_data}")) - (cyclosm - :name "CyclOSM" - :description "Bicycle-oriented map provided by OpenStreetMap France" - :url "https://%s.tile-cyclosm.openstreetmap.fr/cyclosm/%z/%x/%y.png" - :group "Transportation" - :copyright ("Map data © {OpenStreetMap|https://www.openstreetmap.org/copyright} contributors" - "Map style © {CyclOSM|https://www.cyclosm.org/} contributors")) - (openriverboatmap - :name "OpenRiverBoatMap" - :description "Waterways map provided by OpenStreetMap France" - :url "https://%s.tile.openstreetmap.fr/openriverboatmap/%z/%x/%y.png" - :group "Transportation" - :copyright ("Map data © {OpenStreetMap|https://www.openstreetmap.org/copyright} contributors" - "Map style © {OpenRiverBoatMap|https://github.com/tilery/OpenRiverboatMap}")) - (opentopomap - :name "OpenTopoMap" - :description "Topographical map provided by OpenTopoMap" - :url "https://%s.tile.opentopomap.org/%z/%x/%y.png" - :group "Topographical" - :copyright ("Map data © {OpenStreetMap|https://www.openstreetmap.org/copyright} contributors" - "Map style © {OpenTopoMap|https://www.opentopomap.org} ({CC-BY-SA|https://creativecommons.org/licenses/by-sa/3.0/})" - "Elevation data: {SRTM|https://www2.jpl.nasa.gov/srtm/}")) - (opvn - :name "ÖPNV" :max-zoom 18 - :description "Base layer with public transport information" - :url "http://%s.tile.memomaps.de/tilegen/%z/%x/%y.png" - :group "Transportation" - :copyright ("Map data © {OpenStreetMap|https://www.openstreetmap.org/copyright} contributors" - "Map style © {ÖPNVKarte|https://www.öpnvkarte.de}"))) - "List of tile servers. - -Allowed keys: - :name Server name - :description Server description - :copyright Copyright information - :group Name of server groups for related servers - :url Url with placeholders - :min-zoom Minimum zoom level - :max-zoom Maximum zoom level - :download-batch Number of tiles downloaded via a single connection - :max-connections Maximum number of parallel connections - :subdomains Subdomains used for the %s placeholder - -See also `osm-server-defaults' for default values used for a -server if the property is missing. - -The :url of each server should specify %x, %y, %z and %s placeholders -for the map coordinates. It can optionally use an %s placeholder -for the subdomain and a %k placeholder for an apikey. The apikey -will be retrieved via `auth-source-search' with the :host set to -the domain name and the :user to the string \"apikey\"." - :type '(alist :key-type symbol :value-type plist)) - -(defcustom osm-copyright t - "Display the copyright information above the map." - :type 'boolean) - -(defcustom osm-pin-colors - '((osm-selected . "#e20") - (osm-bookmark . "#f80") - (osm-poi . "#88f") - (osm-home . "#80f") - (osm-track . "#00a")) - "Colors of pins." - :type '(alist :key-type symbol :value-type string)) - -(defcustom osm-track-style - "stroke:#00a;stroke-width:5;stroke-linejoin:round;stroke-linecap:round;opacity:0.4;" - "SVG style used to draw tracks." - :type 'string) - -(defcustom osm-home - (let ((lat (bound-and-true-p calendar-latitude)) - (lon (bound-and-true-p calendar-longitude))) - (if (and lat lon) - (list lat lon 12) - (list 0 0 3))) - "Home coordinates, latitude, longitude and zoom level." - :type '(list :tag "Coordinates" - (number :tag "Latitude ") - (number :tag "Longitude ") - (number :tag "Zoom "))) - -(defcustom osm-large-step 256 - "Scroll step in pixel." - :type 'natnum) - -(defcustom osm-tile-border nil - "Set to t to display thin tile borders. -For debugging set the value to `debug', such that a border is -shown around SVG tiles." - :type '(choice boolean (const debug))) - -(defcustom osm-small-step 16 - "Scroll step in pixel." - :type 'natnum) - -(defcustom osm-server 'default - "Tile server name." - :type 'symbol) - -(defcustom osm-tile-directory - (expand-file-name "var/osm/" user-emacs-directory) - "Tile cache directory." - :type 'string) - -(defcustom osm-max-age 14 - "Maximum tile age in days. -Should be at least 7 days according to the server usage policies." - :type '(choice (const nil) natnum)) - -(defcustom osm-max-tiles 256 - "Number of tiles to keep in the memory cache." - :type '(choice (const nil) natnum)) - -(defun osm--menu-item (menu) - "Generate menu item from MENU." - `(menu-item - "" nil :filter - ,(lambda (&optional _) - (select-window - (posn-window - (event-start last-input-event))) - (if (functionp menu) - (funcall menu) - menu)))) - -(defun osm--mouse-ignore-wheel (_prompt) - "Ignore mouse wheel events during key translation." - (pcase (this-single-command-raw-keys) - ((and `[,e] - (let y (event-basic-type e)) - (guard (symbolp y)) - (guard (string-search "wheel-" (symbol-name y)))) - []) - (k k))) - -(defvar-keymap osm-prefix-map - :doc "Global prefix map of OSM entry points." - "h" #'osm-home - "s" #'osm-search - "v" #'osm-server - "t" #'osm-goto - "j" #'osm-jump - "x" #'osm-gpx-show - "X" #'osm-gpx-hide) - -;;;###autoload (autoload 'osm-prefix-map "osm" nil t 'keymap) -(defalias 'osm-prefix-map osm-prefix-map) - -(defvar-keymap osm-mode-map - :doc "Keymap used by `osm-mode'." - :parent (make-composed-keymap osm-prefix-map special-mode-map) - "<home>" #'osm-home - "+" #'osm-zoom-in - "-" #'osm-zoom-out - "SPC" #'osm-zoom-in - "S-SPC" #'osm-zoom-out - "<mouse-1>" #'osm-mouse-pin - "<mouse-2>" 'org-store-link - "<mouse-3>" #'osm-bookmark-set - "S-<down-mouse-1>" #'ignore - "S-<mouse-1>" #'osm-mouse-track - "<down-mouse-1>" #'osm-mouse-drag - "<down-mouse-2>" #'osm-mouse-drag - "<down-mouse-3>" #'osm-mouse-drag - "<drag-mouse-1>" #'ignore - "<drag-mouse-2>" #'ignore - "<drag-mouse-3>" #'ignore - "<up>" #'osm-up - "<down>" #'osm-down - "<left>" #'osm-left - "<right>" #'osm-right - "C-<up>" #'osm-up-up - "C-<down>" #'osm-down-down - "C-<left>" #'osm-left-left - "C-<right>" #'osm-right-right - "M-<up>" #'osm-up-up - "M-<down>" #'osm-down-down - "M-<left>" #'osm-left-left - "M-<right>" #'osm-right-right - "S-<up>" #'osm-up-up - "S-<down>" #'osm-down-down - "S-<left>" #'osm-left-left - "S-<right>" #'osm-right-right - "n" #'osm-rename - "d" #'osm-delete - "DEL" #'osm-delete - "<deletechar>" #'osm-delete - "c" #'osm-center - "o" #'clone-buffer - "u" #'osm-save-url - "l" 'org-store-link - "b" #'osm-bookmark-set - "X" #'osm-gpx-hide - "<remap> <scroll-down-command>" #'osm-down - "<remap> <scroll-up-command>" #'osm-up - "<" nil - ">" nil) - -(dolist (pin osm-pin-colors) - (setq pin (vector (car pin))) - (define-key key-translation-map pin #'osm--mouse-ignore-wheel) - (define-key osm-mode-map pin #'osm-mouse-select)) - -(easy-menu-define osm-mode-menu osm-mode-map - "Menu for `osm-mode'." - '("OSM" - ["Go home" osm-home] - ["Center" osm-center] - ["Go to coordinates" osm-goto] - ["Jump to pin" osm-jump] - ["Search by name" osm-search] - ["Change tile server" osm-server] - "--" - ["Org Link" org-store-link] - ["Geo Url" osm-save-url] - ["Elisp Link" (osm-save-url t)] - ("Bookmark" - ["Set" osm-bookmark-set] - ["Jump" osm-bookmark-jump] - ["Rename" osm-bookmark-rename] - ["Delete" osm-bookmark-delete]) - "--" - ["Show GPX file" osm-gpx-show] - ["Hide GPX file" osm-gpx-hide] - "--" - ["Clone buffer" clone-buffer] - ["Revert buffer" revert-buffer] - "--" - ["Manual" (info "(osm)")] - ["Customize" (customize-group 'osm)])) - -(defconst osm--placeholder - '(:type svg :width 256 :height 256 - :data "<svg width='256' height='256' version='1.1' xmlns='http://www.w3.org/2000/svg'> - <defs> - <pattern id='grid' width='16' height='16' patternUnits='userSpaceOnUse'> - <path d='m 0 0 l 0 16 16 0' fill='none' stroke='#888888'/> - </pattern> - </defs> - <rect width='256' height='256' fill='url(#grid)'/> -</svg>") - "Placeholder image for tiles.") - -(defvar osm--search-history nil - "Minibuffer history used by command `osm-search'.") - -(defvar osm--jump-history nil - "Minibuffer history used by command `osm-jump'.") - -(defvar osm--server-history nil - "Minibuffer history used by command `osm-server'.") - -(defvar osm--purge-directory 0 - "Last time the tile cache was cleaned.") - -(defvar osm--tile-cache nil - "Global tile memory cache.") - -(defvar osm--tile-age 0 - "Tile age, incremented on every update.") - -(defvar osm--gpx-files nil - "Global list of loaded tracks.") - -(defvar osm--track nil - "List of track coordinates.") - -(defvar osm--download-processes nil - "Globally active download processes.") - -(defvar osm--download-active nil - "Globally active download jobs.") - -(defvar osm--download-subdomain nil - "Subdomain indices to query the servers in a round-robin fashion.") - -(defvar-local osm--download-queue nil - "Buffer-local tile download queue.") - -(defvar-local osm--wx 0 - "Half window width in pixel.") - -(defvar-local osm--wy 0 - "Half window height in pixel.") - -(defvar-local osm--nx 0 - "Number of tiles in x direction.") - -(defvar-local osm--ny 0 - "Number of tiles in y direction.") - -(defvar-local osm--zoom nil - "Zoom level of the map.") - -(defvar-local osm--lat nil - "Latitude coordinate.") - -(defvar-local osm--lon nil - "Longitude coordinate.") - -(defvar-local osm--overlays nil - "Overlay hash table. -Local per buffer since the overlays depend on the zoom level.") - -(defvar-local osm--pin nil - "Currently selected pin.") - -(defmacro osm--each (&rest body) - "Execute BODY in each `osm-mode' buffer." - (cl-with-gensyms (buf) - `(dolist (,buf (buffer-list)) - (when (eq (buffer-local-value 'major-mode ,buf) #'osm-mode) - (with-current-buffer ,buf - ,@body))))) - -(defun osm--server-menu () - "Generate server menu." - (let (menu last-group) - (dolist (server osm-server-list) - (let* ((plist (cdr server)) - (group (plist-get plist :group))) - (unless (equal last-group group) - (push (format "─── %s ───" group) menu) - (setq last-group group)) - (push - `[,(plist-get plist :name) - (osm-server ',(car server)) - :style toggle - :selected (eq osm-server ',(car server))] - menu))) - (easy-menu-create-menu "Server" (nreverse menu)))) - -(defsubst osm--lon-to-normalized-x (lon) - "Convert LON to normalized x coordinate." - (/ (+ lon 180.0) 360.0)) - -(defsubst osm--lat-to-normalized-y (lat) - "Convert LAT to normalized y coordinate." - (setq lat (* lat (/ float-pi 180.0))) - (- 0.5 (/ (log (+ (tan lat) (/ 1.0 (cos lat)))) float-pi 2))) - -(defun osm--boundingbox-to-zoom (lat1 lat2 lon1 lon2) - "Compute zoom level from boundingbox LAT1 to LAT2 and LON1 to LON2." - (let ((w (/ (frame-pixel-width) 256)) - (h (/ (frame-pixel-height) 256))) - (max (osm--server-property :min-zoom) - (min - (osm--server-property :max-zoom) - (min (logb (/ w (abs (- (osm--lon-to-normalized-x lon1) (osm--lon-to-normalized-x lon2))))) - (logb (/ h (abs (- (osm--lat-to-normalized-y lat1) (osm--lat-to-normalized-y lat2)))))))))) - -(defun osm--x-to-lon (x zoom) - "Return longitude in degrees for X/ZOOM." - (- (/ (* x 360.0) 256.0 (expt 2.0 zoom)) 180.0)) - -(defun osm--y-to-lat (y zoom) - "Return latitude in degrees for Y/ZOOM." - (setq y (* float-pi (- 1 (* 2 (/ y 256.0 (expt 2.0 zoom)))))) - (/ (* 180 (atan (/ (- (exp y) (exp (- y))) 2))) float-pi)) - -(defsubst osm--lon-to-x (lon zoom) - "Convert LON/ZOOM to x coordinate in pixel." - (floor (* 256 (expt 2.0 zoom) (osm--lon-to-normalized-x lon)))) - -(defsubst osm--lat-to-y (lat zoom) - "Convert LAT/ZOOM to y coordinate in pixel." - (floor (* 256 (expt 2.0 zoom) (osm--lat-to-normalized-y lat)))) - -(defsubst osm--x () - "Return longitude in pixel of map center." - (osm--lon-to-x osm--lon osm--zoom)) - -(defsubst osm--y () - "Return latitude in pixel of map center." - (osm--lat-to-y osm--lat osm--zoom)) - -(defsubst osm--x0 () - "Return longitude in pixel of top left corner." - (- (osm--x) osm--wx)) - -(defsubst osm--y0 () - "Return latitude in pixel of top left corner." - (- (osm--y) osm--wy)) - -(defun osm--server-property (prop &optional server) - "Return server property PROP for SERVER." - (or (plist-get (alist-get (or server osm-server) osm-server-list) prop) - (plist-get osm-server-defaults prop))) - -(defun osm--tile-url (x y zoom) - "Return tile url for coordinate X, Y and ZOOM." - (let ((url (osm--server-property :url)) - (sub (osm--server-property :subdomains)) - (key (osm--server-property :key))) - (when (and (string-search "%k" url) (not key)) - (require 'auth-source) - (declare-function auth-source-search "auth-source") - (let ((host (string-join - (last (split-string (cadr (split-string url "/" t)) "\\.") 2) - "."))) - (setq key (plist-get - (car (auth-source-search :require '(:user :host :secret) - :host host - :user "apikey")) - :secret)) - (unless key - (warn "No auth source secret found for apikey@%s" host) - (setq key "")) - (setf (plist-get (alist-get osm-server osm-server-list) :key) key))) - (format-spec - url `((?z . ,zoom) (?x . ,x) (?y . ,y) - (?k . ,(if (functionp key) (funcall key) key)) - (?s . ,(nth (mod (alist-get osm-server osm--download-subdomain 0) - (length sub)) - sub)))))) - -(defun osm--tile-file (x y zoom) - "Return tile file name for coordinate X, Y and ZOOM." - (file-name-concat - (expand-file-name osm-tile-directory) - (symbol-name osm-server) - (format "%d-%d-%d.%s" - zoom x y - (file-name-extension - (url-file-nondirectory - (osm--server-property :url)))))) - -(defun osm--enqueue-download (x y) - "Enqueue tile X/Y for download." - (when (let ((n (expt 2 osm--zoom))) (and (>= x 0) (>= y 0) (< x n) (< y n))) - (let ((job (list osm-server osm--zoom x y))) - (unless (or (member job osm--download-queue) (member job osm--download-active)) - (setq osm--download-queue (nconc osm--download-queue (list job))))))) - -(defun osm--download-filter (output) - "Filter function for the download process which receives OUTPUT." - (while (string-match - "\\`\\([0-9]+\\) \\(.*?/\\([^/]+\\)/\\([0-9]+\\)-\\([0-9]+\\)-\\([0-9]+\\)\\.[^\r\n]+\\)\r?\n" - output) - (let ((status (match-string 1 output)) - (file (match-string 2 output)) - (server (intern-soft (match-string 3 output))) - (zoom (string-to-number (match-string 4 output))) - (x (string-to-number (match-string 5 output))) - (y (string-to-number (match-string 6 output)))) - (setq output (substring output (match-end 0))) - (when (equal status "200") - (ignore-errors (rename-file file (string-remove-suffix ".tmp" file) t)) - (osm--each - (when (and (= osm--zoom zoom) (eq osm-server server)) - (osm--display-tile x y (osm--get-tile x y))))) - (cl-callf2 delete (list server zoom x y) osm--download-active) - (delete-file file))) - output) - -(defun osm--download-command () - "Build download command." - (let* ((count 0) - (batch (osm--server-property :download-batch)) - (subs (length (osm--server-property :subdomains))) - (parallel (* subs (osm--server-property :max-connections))) - args jobs job) - (while (and (< count batch) - (setq job (nth (* count parallel) osm--download-queue))) - (pcase-let ((`(,_server ,zoom ,x ,y) job)) - (setq args `(,(osm--tile-url x y zoom) - ,(concat (osm--tile-file x y zoom) ".tmp") - "--output" - ,@args)) - (push job jobs) - (push job osm--download-active) - (cl-incf count))) - (osm--each - (dolist (job jobs) - (cl-callf2 delq job osm--download-queue))) - (cl-callf (lambda (s) (mod (1+ s) subs)) - (alist-get osm-server osm--download-subdomain 0)) - (cons `("curl" "--write-out" "%{http_code} %{filename_effective}\n" - ,@(split-string-and-unquote osm-curl-options) ,@(nreverse args)) - jobs))) - -(defun osm--download () - "Download next tiles from the queue." - (when (and (< (length (alist-get osm-server osm--download-processes)) - (* (length (osm--server-property :subdomains)) - (osm--server-property :max-connections))) - osm--download-queue) - (pcase-let ((`(,command . ,jobs) (osm--download-command)) - (dir (file-name-concat (expand-file-name osm-tile-directory) - (symbol-name osm-server))) - (server osm-server)) - (make-directory dir t) - (push - (make-process - :name "*osm curl*" - :connection-type 'pipe - :noquery t - :command command - :filter - (let ((output "")) - (lambda (_proc out) - (setq output (osm--download-filter (concat output out))) - (force-mode-line-update t))) - :sentinel - (lambda (proc _status) - (dolist (job jobs) - (cl-callf2 delq job osm--download-active)) - (cl-callf2 delq proc (alist-get server osm--download-processes nil t)) - (force-mode-line-update t) - (osm--download))) - (alist-get server osm--download-processes)) - (force-mode-line-update t) - (osm--download)))) - -(defun osm-mouse-drag (event) - "Handle drag EVENT." - (declare (completion ignore)) - (interactive "@e") - (pcase-let* ((`(,sx . ,sy) (posn-x-y (event-start event))) - (win (selected-window)) - (map (define-keymap - "<mouse-movement>" - (lambda (event) - (interactive "e") - (setq event (event-start event)) - (when (eq win (posn-window event)) - (pcase-let ((`(,ex . ,ey) (posn-x-y event))) - (osm--move (- sx ex) (- sy ey)) - (setq sx ex sy ey) - (osm--update))))))) - (setq track-mouse 'dragging) - (set-transient-map map - (lambda () (eq (car-safe last-input-event) 'mouse-movement)) - (lambda () (setq track-mouse nil))))) - -(defun osm--zoom-in-wheel (_n) - "Zoom in with the mouse wheel." - (pcase-let ((`(,x . ,y) (posn-x-y (event-start last-input-event)))) - (when (< osm--zoom (osm--server-property :max-zoom)) - (osm--move (/ (- x osm--wx) 2) (/ (- y osm--wy) 2)) - (osm-zoom-in)))) - -(defun osm--zoom-out-wheel (_n) - "Zoom out with the mouse wheel." - (pcase-let ((`(,x . ,y) (posn-x-y (event-start last-input-event)))) - (when (> osm--zoom (osm--server-property :min-zoom)) - (osm--move (- osm--wx x) (- osm--wy y)) - (osm-zoom-out)))) - -(defun osm-center () - "Center to location of selected pin." - (interactive nil osm-mode) - (osm--barf-unless-osm) - (pcase osm--pin - (`(,lat ,lon ,_id ,name) - (setq osm--lat lat osm--lon lon) - (message "%s" name) - (osm--update)))) - -(defun osm--haversine (lat1 lon1 lat2 lon2) - "Compute distance between LAT1/LON1 and LAT2/LON2 in km." - ;; https://en.wikipedia.org/wiki/Haversine_formula - (let* ((rad (/ float-pi 180)) - (y (sin (* 0.5 rad (- lat2 lat1)))) - (x (sin (* 0.5 rad (- lon2 lon1)))) - (h (+ (* x x) (* (cos (* rad lat1)) (cos (* rad lat2)) y y)))) - (* 2 6371 (atan (sqrt h) (sqrt (- 1 h)))))) - -(defun osm-mouse-track (event) - "Set track pin at location of the click EVENT." - (declare (completion ignore)) - (interactive "@e") - (pcase osm--pin - ((and (guard (not osm--track)) `(,lat ,lon ,_id ,_name)) - (push (list lat lon "WP1") osm--track))) - (osm--set-pin-event event 'osm-track - (format "WP%s" (1+ (length osm--track))) 'quiet) - (pcase-let ((`(,lat ,lon ,_id ,name) osm--pin)) - (push (list lat lon name) osm--track)) - (osm--revert) - (osm--track-length)) - -(defun osm--track-length () - "Echo track length." - (when (cdr osm--track) - (pcase-let* ((len1 0) - (len2 0) - (p osm--track) - (`(,sel-lat ,sel-lon ,_ ,sel-name) osm--pin)) - (while (and (cdr p) (not (and (equal (caar p) sel-lat) - (equal (cadar p) sel-lon)))) - (cl-incf len2 (osm--haversine (caar p) (cadar p) - (caadr p) (cadadr p))) - (pop p)) - (while (cdr p) - (cl-incf len1 (osm--haversine (caar p) (cadar p) - (caadr p) (cadadr p))) - (pop p)) - (message "%s way points, length %.2fkm, %s" - (length osm--track) (+ len1 len2) - (if (or (= len1 0) (= len2 0)) - sel-name - (format "%.2fkm → %s → %.2fkm" - len1 sel-name len2)))))) - -(defun osm--pin-at (event &optional type) - "Get pin of TYPE at EVENT." - (let* ((xy (posn-x-y (event-start event))) - (x (+ (osm--x0) (car xy))) - (y (+ (osm--y0) (cdr xy))) - (min most-positive-fixnum) - found) - (dolist (pin (car (osm--get-overlays (/ x 256) (/ y 256)))) - (pcase-let ((`(,p ,q ,_lat ,_lon ,id ,_name) pin)) - (when (or (not type) (eq type id)) - (let ((d (+ (* (- p x) (- p x)) (* (- q y) (- q y))))) - (when (and (>= q y) (< q (+ y 50)) (>= p (- x 20)) (< p (+ x 20)) (< d min)) - (setq min d found pin)))))) - (cddr found))) - -(defun osm-mouse-pin (event) - "Create location pin at the click EVENT." - (declare (completion ignore)) - (interactive "@e") - (osm--set-pin-event event) - (osm--update)) - -(defun osm-mouse-select (event) - "Select pin at position of click EVENT." - (declare (completion ignore)) - (interactive "@e") - (when (memq (event-basic-type event) '(mouse-1 mouse-2 mouse-3)) - (pcase (osm--pin-at event) - (`(,lat ,lon ,id ,name) - (osm--set-pin id lat lon name (eq id 'osm-track)) - (when (eq id 'osm-track) (osm--track-length)) - (osm--update))))) - -(defun osm-zoom-in (&optional n) - "Zoom N times into the map." - (interactive "p" osm-mode) - (osm--barf-unless-osm) - (setq osm--zoom (max (osm--server-property :min-zoom) - (min (osm--server-property :max-zoom) - (+ osm--zoom (or n 1))))) - (osm--update)) - -(defun osm-zoom-out (&optional n) - "Zoom N times out of the map." - (interactive "p" osm-mode) - (osm-zoom-in (- (or n 1)))) - -(defun osm--move (dx dy) - "Move by DX/DY." - (osm--barf-unless-osm) - (setq osm--lon (osm--x-to-lon (+ (osm--x) dx) osm--zoom) - osm--lat (osm--y-to-lat (+ (osm--y) dy) osm--zoom))) - -(defun osm-right (&optional n) - "Move N small steps to the right." - (interactive "p" osm-mode) - (osm--move (* (or n 1) osm-small-step) 0) - (osm--update)) - -(defun osm-down (&optional n) - "Move N small steps down." - (interactive "p" osm-mode) - (osm--move 0 (* (or n 1) osm-small-step)) - (osm--update)) - -(defun osm-up (&optional n) - "Move N small steps up." - (interactive "p" osm-mode) - (osm-down (- (or n 1)))) - -(defun osm-left (&optional n) - "Move N small steps to the left." - (interactive "p" osm-mode) - (osm-right (- (or n 1)))) - -(defun osm-right-right (&optional n) - "Move N large steps to the right." - (interactive "p" osm-mode) - (osm--move (* (or n 1) osm-large-step) 0) - (osm--update)) - -(defun osm-down-down (&optional n) - "Move N large steps down." - (interactive "p" osm-mode) - (osm--move 0 (* (or n 1) osm-large-step)) - (osm--update)) - -(defun osm-up-up (&optional n) - "Move N large steps up." - (interactive "p" osm-mode) - (osm-down-down (- (or n 1)))) - -(defun osm-left-left (&optional n) - "Move N large steps to the left." - (interactive "p" osm-mode) - (osm-right-right (- (or n 1)))) - -(defun osm--purge-directory () - "Clean tile directory." - (when (and (integerp osm-max-age) - (> (- (float-time) osm--purge-directory) (* 60 60 24))) - (setq osm--purge-directory (float-time)) - (run-with-idle-timer - 30 nil - (lambda () - (dolist (dir (directory-files osm-tile-directory t "\\`[^.]+\\'" t)) - (dolist (file (directory-files - dir t "\\.\\(?:png\\|jpe?g\\)\\(?:\\.tmp\\)?\\'" t)) - (when (> (float-time (time-since - (file-attribute-modification-time - (file-attributes file)))) - (* 60 60 24 osm-max-age)) - (delete-file file))) - (when (directory-empty-p dir) - (ignore-errors (delete-directory dir)))))))) - -(defun osm--check-libraries () - "Check that Emacs is compiled with the necessary libraries." - (let (req) - (unless (display-graphic-p) - (push "graphical display" req)) - (dolist (type '(svg jpeg png)) - (unless (image-type-available-p type) - (push (format "%s support" type) req))) - (unless (libxml-available-p) - (push "libxml" req)) - (unless (json-available-p) - (push "libjansson" req)) - (when req - (error "Osm: Please compile Emacs with the required libraries, %s needed to proceed" - (string-join req ", "))))) - -(define-derived-mode osm-mode special-mode "Osm" - "OpenStreetMap viewer mode." - :interactive nil :abbrev-table nil :syntax-table nil - (osm--check-libraries) - (setq-local osm-server osm-server - line-spacing nil - cursor-type nil - cursor-in-non-selected-windows nil - left-fringe-width 1 - right-fringe-width 1 - left-margin-width 0 - right-margin-width 0 - truncate-lines t - show-trailing-whitespace nil - display-line-numbers nil - buffer-read-only t - fringe-indicator-alist '((truncation . nil)) - revert-buffer-function #'osm--revert - mode-line-process '(:eval (osm--download-queue-info)) - mode-line-position nil - eldoc-documentation-functions nil - mouse-wheel-progressive-speed nil - mwheel-scroll-up-function #'osm--zoom-out-wheel - mwheel-scroll-down-function #'osm--zoom-in-wheel - mwheel-scroll-left-function #'osm--zoom-out-wheel - mwheel-scroll-right-function #'osm--zoom-in-wheel - bookmark-make-record-function #'osm--bookmark-record-default) - (when (boundp 'mwheel-coalesce-scroll-events) - (setq-local mwheel-coalesce-scroll-events t)) - (when (boundp 'pixel-scroll-precision-mode) - (setq-local pixel-scroll-precision-mode nil)) - (add-hook 'change-major-mode-hook #'osm--barf-change-mode nil 'local) - (add-hook 'write-contents-functions #'osm--barf-write nil 'local) - (add-hook 'window-size-change-functions #'osm--resize nil 'local)) - -(defun osm--barf-write () - "Barf for write operation." - (set-buffer-modified-p nil) - (setq buffer-read-only t) - (set-visited-file-name nil) - (error "Writing the buffer to a file is not supported")) - -(defun osm--barf-change-mode () - "Barf for change mode operation." - (error "Changing the major mode is not supported")) - -(defun osm--barf-unless-osm () - "Barf if not an `osm-mode' buffer." - (unless (eq major-mode #'osm-mode) - (error "Not an `osm-mode' buffer"))) - -(defun osm--each-pin (fun) - "Call FUN for each pin on the map." - (pcase osm-home - (`(,lat ,lon ,zoom) - (funcall fun 'osm-home lat lon zoom "Home"))) - (bookmark-maybe-load-default-file) - (cl-loop for bm in bookmark-alist - if (eq (bookmark-prop-get bm 'handler) #'osm-bookmark-jump) do - (pcase-let ((`(,lat ,lon ,zoom) (bookmark-prop-get bm 'coordinates))) - (funcall fun 'osm-bookmark lat lon zoom (car bm)))) - (dolist (file osm--gpx-files) - (cl-loop for (lat lon name) in (cddr file) do - (funcall fun 'osm-poi lat lon 15 name))) - (cl-loop for (lat lon name) in osm--track do - (funcall fun 'osm-track lat lon 15 name))) - -(defun osm--pin-inside-p (x y lat lon) - "Return non-nil if pin at LAT/LON is inside tile X/Y." - (let ((p (/ (osm--lon-to-x lon osm--zoom) 256.0)) - (q (/ (osm--lat-to-y lat osm--zoom) 256.0))) - (and (>= p (- x 0.125)) (< p (+ x 1.125)) - (>= q y) (< q (+ y 1.25))))) - -(defun osm--add-pin (pins id lat lon _zoom name) - "Add pin at LAT/LON with NAME and ID to the PINS hash table." - (let* ((x (osm--lon-to-x lon osm--zoom)) - (y (osm--lat-to-y lat osm--zoom)) - (x0 (/ x 256)) - (y0 (/ y 256)) - (pin (list x y lat lon id name))) - (push pin (gethash (cons x0 y0) pins)) - (cl-loop - for i from -1 to 1 do - (cl-loop - for j from -1 to 0 do - (let ((x1 (/ (+ x (* 32 i)) 256)) - (y1 (/ (+ y (* 64 j)) 256))) - (unless (and (= x0 x1) (= y0 y1)) - (push pin (gethash (cons x1 y1) pins)))))))) - -;; TODO: The Bresenham algorithm used here to add the line segments to the tiles -;; has the issue that lines which go along a tile border may be drawn only -;; partially. Use a more precise algorithm instead. -(defun osm--add-track (tracks seg) - "Add track segment SEG to TRACKS hash table." - (when seg - (let ((p0 (cons (osm--lon-to-x (or (car-safe (cdar seg)) (cdar seg)) osm--zoom) - (osm--lat-to-y (caar seg) osm--zoom)))) - (dolist (pt (cdr seg)) - (let* ((px1 (cdr pt)) - (px1 (osm--lon-to-x (if (consp px1) (car px1) px1) osm--zoom)) - (py1 (osm--lat-to-y (car pt) osm--zoom)) - (pdx (- px1 (car p0))) - (pdy (- py1 (cdr p0)))) - ;; Ignore point if too close to last point - (unless (< (+ (* pdx pdx) (* pdy pdy)) 50) - (let* ((p1 (cons px1 py1)) - (line (cons p0 p1)) - (x0 (/ (car p0) 256)) - (y0 (/ (cdr p0) 256)) - (x1 (/ px1 256)) - (y1 (/ py1 256)) - (sx (if (< x0 x1) 1 -1)) - (sy (if (< y0 y1) 1 -1)) - (dx (* sx (- x1 x0))) - (dy (* sy (- y0 y1))) - (err (+ dx dy))) - ;; Bresenham - (while - (let ((ey (> (* err 2) dy)) - (ex (< (* err 2) dx))) - (push line (gethash (cons x0 y0) tracks)) - (unless (and (= x0 x1) (= y0 y1)) - (when (and ey ex) - (push line (gethash (cons x0 (+ y0 sy)) tracks)) - (push line (gethash (cons (+ x0 sx) y0) tracks))) - (when ey - (cl-incf err dy) - (cl-incf x0 sx)) - (when ex - (cl-incf err dx) - (cl-incf y0 sy)) - t))) - (setq p0 p1)))))))) - -(defun osm--get-overlays (x y) - "Compute overlays and return the overlays in tile X/Y." - (unless (eq (car osm--overlays) osm--zoom) - ;; TODO: Do not compute overlays for the entire map, only for a reasonable - ;; view port around the current center, depending on the size of the - ;; window. Otherwise the spatial hash map for the tracks gets very large if - ;; a line segment spans many tiles. - (let ((pins (make-hash-table :test #'equal)) - (tracks (make-hash-table :test #'equal))) - (osm--each-pin (apply-partially #'osm--add-pin pins)) - (dolist (file osm--gpx-files) - (dolist (seg (cadr file)) - (osm--add-track tracks seg))) - (osm--add-track tracks osm--track) - (setq osm--overlays (list osm--zoom pins tracks)))) - (let ((pins (gethash (cons x y) (cadr osm--overlays))) - (tracks (gethash (cons x y) (caddr osm--overlays)))) - (and (or pins tracks) (cons pins tracks)))) - -(autoload 'svg--image-data "svg") -(defun osm--draw-tile (x y tpin) - "Make tile at X/Y from FILE. -TPIN is an optional pin." - (let ((file (osm--tile-file x y osm--zoom)) - overlays) - (when (file-exists-p file) - (if (or (setq overlays (osm--get-overlays x y)) (eq osm-tile-border t) tpin) - (let* ((areas nil) - (x0 (* 256 x)) - (y0 (* 256 y)) - (svg-pin - (lambda (pin) - (pcase-let* ((`(,p ,q ,_lat ,_lon ,id ,name) pin) - (bg (cdr (assq id osm-pin-colors)))) - (setq p (- p x0) q (- q y0)) - (push `((poly . [,p ,q ,(- p 20) ,(- q 40) ,p ,(- q 50) ,(+ p 20) ,(- q 40) ]) - ,id (help-echo ,(truncate-string-to-width name 40 0 nil t))) - areas) - ;; https://commons.wikimedia.org/wiki/File:Simpleicons_Places_map-marker-1.svg - (format " -<g fill='%s' stroke='#000' stroke-width='9' transform='translate(%s %s) scale(0.09) translate(-256 -512)'> -<path d='M256 0C167.641 0 96 71.625 96 160c0 24.75 5.625 48.219 15.672 -69.125C112.234 230.313 256 512 256 512l142.594-279.375 -C409.719 210.844 416 186.156 416 160C416 71.625 344.375 -0 256 0z M256 256c-53.016 0-96-43-96-96s42.984-96 96-96 -c53 0 96 43 96 96S309 256 256 256z'/> -</g>" bg p q)))) - (svg-text - (concat "<svg width='256' height='256' version='1.1' -xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink'> -<image xlink:href='" - (file-name-nondirectory file) - "' height='256' width='256'/>" - (when-let (track (cdr overlays)) - (format - "<path style='%s' d='%s'/>" - osm-track-style - (let (last) - (mapconcat - (pcase-lambda (`(,beg . ,end)) - (prog1 - (if (equal beg last) - (format "L%s %s" (- (car end) x0) (- (cdr end) y0)) - (format "M%s %sL%s %s" - (- (car beg) x0) (- (cdr beg) y0) - (- (car end) x0) (- (cdr end) y0))) - (setq last end))) - track "")))) - (pcase-exhaustive osm-tile-border - ('nil nil) - ('debug "<path d='M 1 1 L 1 255 255 255 255 1 Z' stroke='#000' stroke-width='2' fill='none'/>") - ('t "<path d='M 0 0 L 0 256 256 256' stroke='#000' fill='none'/>")) - (mapconcat svg-pin (car overlays) "") - (and tpin (funcall svg-pin tpin)) - "</svg>"))) - (list 'image :width 256 :height 256 :type 'svg :base-uri file :data svg-text :map areas)) - (list 'image :width 256 :height 256 :file file :type - (if (member (file-name-extension file) '("jpg" "jpeg")) - 'jpeg 'png)))))) - -(defun osm--get-tile (x y) - "Get tile at X/Y." - (pcase osm--pin - ((and `(,lat ,lon ,_id ,name) - (guard (osm--pin-inside-p x y lat lon))) - (osm--draw-tile x y (list (osm--lon-to-x lon osm--zoom) - (osm--lat-to-y lat osm--zoom) - lat lon 'osm-selected name))) - (_ - (let* ((key `(,osm-server ,osm--zoom ,x . ,y)) - (tile (and osm--tile-cache (gethash key osm--tile-cache)))) - (if tile - (progn (setcar tile osm--tile-age) (cdr tile)) - (setq tile (osm--draw-tile x y nil)) - (when tile - (when osm-max-tiles - (unless osm--tile-cache - (setq osm--tile-cache (make-hash-table :test #'equal :size osm-max-tiles))) - (puthash key (cons osm--tile-age tile) osm--tile-cache)) - tile)))))) - -(defun osm--display-tile (x y tile) - "Display TILE at X/Y." - (let ((i (- x (/ (osm--x0) 256))) - (j (- y (/ (osm--y0) 256)))) - (when (and (>= i 0) (< i osm--nx) (>= j 0) (< j osm--ny)) - (let* ((mx (if (= 0 i) (mod (osm--x0) 256) 0)) - (my (if (= 0 j) (mod (osm--y0) 256) 0)) - (pos (+ (point-min) (* j (1+ osm--nx)) i))) - (unless tile - (setq tile (cons 'image osm--placeholder))) - (with-silent-modifications - (put-text-property - pos (1+ pos) 'display - (if (or (/= 0 mx) (/= 0 my)) - `((slice ,mx ,my ,(- 256 mx) ,(- 256 my)) ,tile) - tile))))))) - -;;;###autoload -(defun osm-home () - "Go to home coordinates." - (interactive) - (pcase osm-home - (`(,lat ,lon ,zoom) - (osm--goto lat lon zoom nil 'osm-home "Home")))) - -(defun osm--download-queue-info () - "Return queue info string." - (when osm--download-processes - (format "[%s/%s/%s]" - (cl-loop for (_ . p) in osm--download-processes sum (length p)) - (length osm--download-active) - (length osm--download-queue)))) - -(defun osm--revert (&rest _) - "Revert osm buffers." - (clear-image-cache t) ;; Make absolutely sure that the tiles are redrawn. - (setq osm--tile-cache nil) - (osm--each - (setq osm--overlays nil) - (osm--update))) - -(defun osm--resize (&rest _) - "Resize buffer." - (when (eq major-mode #'osm-mode) - (osm--update))) - -(defun osm--header-button (text action) - "Format header line button with TEXT and ACTION." - (propertize text - 'keymap (define-keymap "<header-line> <mouse-1>" - (if (commandp action) - (lambda () - (interactive "@") - (call-interactively action)) - action)) - 'face '(:box (:line-width -2 :style released-button)) - 'mouse-face '(:box (:line-width -2 :style pressed-button)))) - -(defun osm--update-header () - "Update header line." - (let* ((meter-per-pixel (/ (* 156543.03 (cos (/ osm--lat (/ 180.0 float-pi)))) (expt 2 osm--zoom))) - (server (osm--server-property :name)) - (meter 1) (idx 0) - (factor '(2 2.5 2)) - (sep #(" " 0 1 (display (space :width (1)))))) - (while (and (< idx 20) (< (/ (* meter (nth (mod idx 3) factor)) meter-per-pixel) 150)) - (setq meter (round (* meter (nth (mod idx 3) factor)))) - (cl-incf idx)) - (setq-local - header-line-format - (list - (osm--header-button " ☰ " (osm--menu-item osm-mode-menu)) sep - (osm--header-button (format " %s " server) - (osm--menu-item #'osm--server-menu)) sep - (osm--header-button " + " #'osm-zoom-in) sep - (osm--header-button " - " #'osm-zoom-out) - (format " Z%-2d " osm--zoom) - #(" " 0 1 (display (space :align-to (- center 15)))) - (format #(" %7.2f° %7.2f°" 0 14 (face bold)) osm--lat osm--lon) - #(" " 0 1 (display (space :align-to (- right 20)))) - (format "%3s " (if (>= meter 1000) (/ meter 1000) meter)) - (if (>= meter 1000) "km " "m ") - #(" " 0 1 (face (:inverse-video t) display (space :width (3)))) - (propertize " " 'face '(:strike-through t) - 'display `(space :width (,(floor (/ meter meter-per-pixel))))) - #(" " 0 1 (face (:inverse-video t) display (space :width (3)))))))) - -(defun osm--update () - "Update map display." - (osm--barf-unless-osm) - (osm--purge-tile-cache) - (osm--purge-directory) - (osm--rename-buffer) - (osm--update-sizes) - (osm--update-header) - (osm--update-buffer) - (osm--update-copyright) - (osm--process-download-queue)) - -(defun osm--update-sizes () - "Update window sizes." - (let* ((windows (or (get-buffer-window-list) (list (frame-root-window)))) - (win-width (cl-loop for w in windows maximize (window-pixel-width w))) - (win-height (cl-loop for w in windows maximize (window-pixel-height w)))) - (setq osm--wx (/ win-width 2) - osm--wy (/ win-height 2) - osm--nx (1+ (ceiling win-width 256)) - osm--ny (1+ (ceiling win-height 256))))) - -(defun osm--copyright-link (text url) - "Format link with TEXT to URL." - (propertize text - 'face 'button - 'mouse-face 'highlight - 'help-echo - (format "Go to %s" url) - 'keymap - (define-keymap "<tab-line> <mouse-1>" - (lambda () - (interactive) - (browse-url url))))) - -(defun osm--update-copyright () - "Update copyright info." - (let ((copyright (and osm-copyright (osm--server-property :copyright)))) - (if (not copyright) - (when (eq 'osm-copyright (car-safe tab-line-format)) - (kill-local-variable 'tab-line-format)) - (setq copyright (replace-regexp-in-string - "{\\(.*?\\)|\\(.*?\\)}" - (lambda (str) - (osm--copyright-link - (match-string 1 str) - (match-string 2 str))) - (concat - " " - (string-join (ensure-list copyright) " | ") - #(" " 0 1 (display (space :align-to (+ 42 right))))))) - (add-face-text-property - 0 (length copyright) - '(:inherit (header-line variable-pitch) :height 0.65) - t copyright) - (setq-local tab-line-format (list 'osm-copyright copyright))))) - -(defun osm--update-buffer () - "Update buffer display." - (with-silent-modifications - (erase-buffer) - (dotimes (_j osm--ny) - (insert (make-string osm--nx ?\s) "\n")) - (put-text-property (point-min) (point-max) 'pointer 'arrow) - (goto-char (point-min)) - (let ((tx (/ (osm--x0) 256)) - (ty (/ (osm--y0) 256))) - (dotimes (j osm--ny) - (dotimes (i osm--nx) - (let* ((x (+ i tx)) - (y (+ j ty)) - (tile (osm--get-tile x y))) - (osm--display-tile x y tile) - (unless tile (osm--enqueue-download x y)))))))) - -(defun osm--process-download-queue () - "Process the download queue." - (setq osm--download-queue - (sort - (cl-loop with tx = (/ (osm--x0) 256) - with ty = (/ (osm--y0) 256) - for job in osm--download-queue - for (_server zoom x y) = job - if (and (= zoom osm--zoom) - (>= x tx) (< x (+ tx osm--nx)) - (>= y ty) (< y (+ ty osm--ny))) - collect job) - (let ((tx (/ (osm--x) 256)) - (ty (/ (osm--y) 256))) - (pcase-lambda (`(,_s1 ,_z1 ,x1 ,y1) `(,_s2 ,_z2 ,x2 ,y2)) - (setq x1 (- x1 tx) y1 (- y1 ty) x2 (- x2 tx) y2 (- y2 ty)) - (< (+ (* x1 x1) (* y1 y1)) (+ (* x2 x2) (* y2 y2))))))) - (osm--download)) - -(defun osm--purge-tile-cache () - "Purge old tiles from the tile cache." - (cl-incf osm--tile-age) - (when (and osm--tile-cache (> (hash-table-count osm--tile-cache) osm-max-tiles)) - (let (items) - (maphash (lambda (k v) (push (list (car v) (cdr v) k) items)) osm--tile-cache) - (setq items (sort items #'car-less-than-car)) - (cl-loop repeat (- (hash-table-count osm--tile-cache) osm-max-tiles) - for (_age tile key) in items do - (image-flush tile t) - (remhash key osm--tile-cache))))) - -(defun osm--bookmark-record-default () - "Make osm bookmark record." - (osm--bookmark-record (osm--bookmark-name osm--lat osm--lon nil) - osm--lat osm--lon nil)) - -(defun osm--bookmark-record (name lat lon loc) - "Make osm bookmark record with NAME and LOC description at LAT/LON." - (setq bookmark-current-bookmark nil) ;; Reset bookmark to use new name - `(,name - (location . ,(osm--location-name lat lon loc 6)) - (coordinates ,lat ,lon ,osm--zoom) - (server . ,osm-server) - (handler . ,#'osm-bookmark-jump))) - -(defun osm--org-link-props () - "Return Org link properties." - (pcase-let* ((`(,lat ,lon ,loc) (osm--fetch-location-data "New Org Link")) - (name (osm--location-name lat lon loc 2))) - (list :type "geo" - :description - (if (eq osm-server (default-value 'osm-server)) - (string-remove-suffix (concat " " (osm--server-property :name)) - name) - name) - :link - (format "geo:%.6f,%.6f;z=%s%s" - lat lon osm--zoom - (if (eq osm-server (default-value 'osm-server)) "" - (format ";s=%s" osm-server)))))) - -(defun osm--rename-buffer () - "Rename current buffer." - (setq list-buffers-directory (osm--location-name osm--lat osm--lon nil 6)) - (rename-buffer - (format "*osm: %s*" (osm--location-name osm--lat osm--lon nil 2)) - 'unique)) - -(defun osm--location-name (lat lon loc prec) - "Format location string LAT/LON with optional LOC description. -The coordinates are formatted with precision PREC." - (format (format "%%s%%.%df° %%.%df° Z%%s %%s" prec prec) - (if loc (concat loc ", ") "") - lat lon osm--zoom (osm--server-property :name))) - -(defun osm--bookmark-name (lat lon loc) - "Return bookmark name for LAT/LON/LOC." - (concat "osm: " (osm--location-name lat lon loc 2))) - -(defun osm--goto (lat lon zoom server id name) - "Go to LAT/LON/ZOOM, change SERVER. -Optionally place pin with ID and NAME." - ;; Server not found - (when (and server (not (assq server osm-server-list))) (setq server nil)) - (with-current-buffer - (or - (and (eq major-mode #'osm-mode) (current-buffer)) - (let ((def-server (or server osm-server)) - (def-lat (or lat (nth 0 osm-home))) - (def-lon (or lon (nth 1 osm-home))) - (def-zoom (or zoom (nth 2 osm-home)))) - ;; Search for existing buffer - (cl-loop - for buf in (buffer-list) thereis - (and (equal (buffer-local-value 'major-mode buf) #'osm-mode) - (equal (buffer-local-value 'osm-server buf) def-server) - (equal (buffer-local-value 'osm--zoom buf) def-zoom) - (equal (buffer-local-value 'osm--lat buf) def-lat) - (equal (buffer-local-value 'osm--lon buf) def-lon) - buf))) - (generate-new-buffer "*osm*")) - (unless (eq major-mode #'osm-mode) - (osm-mode)) - (when (and server (not (eq osm-server server))) - (setq-local osm-server server - osm--download-queue nil)) - (when (or (not (and osm--lon osm--lat)) lat) - (setq osm--lat (or lat (nth 0 osm-home)) - osm--lon (or lon (nth 1 osm-home)) - osm--zoom (or zoom (nth 2 osm-home))) - (when id - (osm--set-pin id osm--lat osm--lon name))) - (prog1 (pop-to-buffer (current-buffer)) - (osm--update)))) - -(defun osm--set-pin (id lat lon name &optional quiet) - "Set pin at LAT/LON with ID and NAME. -Print NAME if not QUIET." - (setq name (or name (format "Location %.6f° %.6f°" lat lon))) - (setq osm--pin (list lat lon (or id 'osm-selected) name)) - (unless quiet (message "%s" name))) - -(defun osm--set-pin-event (event &optional id name quiet) - "Set selection pin with ID and NAME at location of EVENT. -Print NAME if not QUIET." - (pcase-let ((`(,x . ,y) (posn-x-y (event-start event)))) - (osm--set-pin id - (osm--y-to-lat (+ (osm--y0) y) osm--zoom) - (osm--x-to-lon (+ (osm--x0) x) osm--zoom) - name quiet))) - -;;;###autoload -(defun osm-goto (lat lon zoom) - "Go to LAT/LON/ZOOM." - (interactive - (pcase-let ((`(,lat ,lon ,zoom) - (mapcar #'string-to-number - (split-string (read-string "Lat Lon (Zoom): ") nil t)))) - (setq zoom (or zoom osm--zoom 11)) - (unless (and (numberp lat) (numberp lon) (numberp zoom)) - (error "Invalid coordinate")) - (list lat lon zoom))) - (osm--goto lat lon zoom nil 'osm-selected nil) - nil) - -;;;###autoload -(defun osm (&rest link) - "Go to LINK. -When called interactively, call the function `osm-home'." - (interactive (list 'home)) - (pcase link - ('(home) - (osm-home)) - (`(,lat ,lon ,zoom . ,server) - (setq server (car server)) - (unless (and server (symbolp server)) (setq server nil)) ;; Ignore comment - (osm--goto lat lon zoom server 'osm-selected "Elisp Link")) - ((and `(,url . ,_) (guard (stringp url))) - (if (string-match - "\\`geo:\\([0-9.-]+\\),\\([0-9.-]+\\)\\(?:,[0-9.-]+\\)?\\(;.+\\'\\|\\'\\)" url) - (let* ((lat (string-to-number (match-string 1 url))) - (lon (string-to-number (match-string 2 url))) - (args (url-parse-args (match-string 3 url) "")) - (zoom (cdr (assoc "z" args))) - (server (cdr (assoc "s" args)))) - (osm--goto lat lon - (and zoom (string-to-number zoom)) - (and server (intern-soft server)) - 'osm-selected "Geo Link")) - (osm-search (string-remove-prefix "geo:" url)))) - (_ (error "Invalid osm link")))) - -;;;###autoload -(defun osm-bookmark-jump (bm) - "Jump to osm bookmark BM." - (interactive (list (osm--bookmark-read))) - (pcase-let ((`(,lat ,lon ,zoom) (bookmark-prop-get bm 'coordinates))) - (set-buffer (osm--goto lat lon zoom - (bookmark-prop-get bm 'server) - 'osm-bookmark (car bm))))) -(put 'osm-bookmark-jump 'bookmark-handler-type "Osm") - -;;;###autoload -(defun osm-bookmark-delete (bm) - "Delete osm bookmark BM." - (interactive (list (osm--bookmark-read))) - (when (y-or-n-p (format "Delete bookmark `%s'? " bm)) - (bookmark-delete bm) - (setq osm--pin nil) - (osm--revert))) - -;;;###autoload -(defun osm-bookmark-rename (old-name) - "Rename osm bookmark OLD-NAME." - (interactive (list (car (osm--bookmark-read)))) - (let ((new-name (read-from-minibuffer "New name: " old-name nil nil - 'bookmark-history old-name))) - (when osm--pin (setf (cadddr osm--pin) new-name)) - (bookmark-rename old-name new-name) - (osm--revert))) - -(defun osm--bookmark-read () - "Read bookmark name." - (bookmark-maybe-load-default-file) - (or (assoc - (pcase osm--pin - (`(,_lat ,_lon osm-bookmark ,name) name) - (_ (completing-read - "Bookmark: " - (or (cl-loop for bm in bookmark-alist - if (eq (bookmark-prop-get bm 'handler) #'osm-bookmark-jump) - collect (car bm)) - (error "No bookmarks found")) - nil t nil 'bookmark-history))) - bookmark-alist) - (error "No bookmark selected"))) - -(defun osm-bookmark-set () - "Create osm bookmark." - (interactive nil osm-mode) - (osm--barf-unless-osm) - (unwind-protect - (pcase-let* ((`(,lat ,lon ,loc) (osm--fetch-location-data "New Bookmark")) - (def (osm--bookmark-name lat lon loc)) - (name (read-from-minibuffer "Bookmark name: " def nil nil 'bookmark-history def)) - (bookmark-make-record-function - (lambda () (osm--bookmark-record name lat lon loc)))) - (bookmark-set name) - (message "Stored bookmark: %s" name) - (setf (caddr osm--pin) 'osm-bookmark)) - (osm--revert))) - -(defun osm--fetch-location-data (name) - "Fetch location info for NAME." - (when (mouse-event-p last-input-event) - (osm--set-pin-event last-input-event 'osm-selected name)) - (let ((lat (or (car osm--pin) osm--lat)) - (lon (or (cadr osm--pin) osm--lon))) - (osm--set-pin 'osm-selected lat lon name 'quiet) - (message "%s: Fetching name of %.2f° %.2f° from %s..." name lat lon osm-search-server) - ;; Redisplay before slow fetching - (osm--update) - (redisplay) - (list lat lon - (ignore-errors - (alist-get - 'display_name - (osm--fetch-json - (format "%s/reverse?format=json&accept-language=%s&zoom=%s&lat=%s&lon=%s" - osm-search-server osm-search-language - (min 18 (max 3 osm--zoom)) lat lon))))))) - -(defun osm--track-index () - "Return index of selected track way point." - (cl-loop for idx from 0 for (lat lon _) in osm--track - if (and (equal lat (car osm--pin)) (equal lon (cadr osm--pin))) - return idx)) - -(defun osm--track-delete () - "Delete track way point." - (when-let ((idx (osm--track-index))) - ;; Delete pin - (cl-callf2 delq (nth idx osm--track) osm--track) - (setq osm--pin nil - idx (min idx (1- (length osm--track)))) - ;; Select next pin - (pcase (nth idx osm--track) - (`(,lat ,lon ,name) - (osm--set-pin 'osm-track lat lon name 'quiet))) - ;; Rename pins after deletion - (cl-loop for idx from (length osm--track) downto 1 - for pt in osm--track - if (string-match-p "\\`WP[0-9]+\\'" (caddr pt)) do - (setf (caddr pt) (format "WP%s" idx))) - (osm--track-length) - (osm--revert))) - -(defun osm--track-rename () - "Rename track way point." - (when-let ((pt (nth (osm--track-index) osm--track)) - (old-name (caddr pt)) - (new-name (read-from-minibuffer "New name: " old-name nil nil nil old-name))) - (setf (caddr pt) new-name - (cadddr osm--pin) new-name) - (osm--revert))) - -(defun osm-delete () - "Delete selected pin (bookmark or way point)." - (interactive nil osm-mode) - (osm--barf-unless-osm) - (pcase (caddr osm--pin) - ('nil nil) - ('osm-bookmark (osm-bookmark-delete (cadddr osm--pin))) - ('osm-track (osm--track-delete)) - (_ (setq osm--pin nil) (osm--update)))) - -(defun osm-rename () - "Rename selected pin (bookmark or way point)." - (interactive nil osm-mode) - (osm--barf-unless-osm) - (pcase (caddr osm--pin) - ('osm-bookmark (osm-bookmark-rename (cadddr osm--pin))) - ('osm-track (osm--track-rename)))) - -;;;###autoload -(defun osm-jump () - "Jump to named pin." - (interactive) - (let (pins) - (osm--each-pin (lambda (id lat lon zoom name) - (push (list name (capitalize (substring (symbol-name id) 4)) - id lat lon zoom) - pins))) - (pcase (assoc (completing-read - "Jump: " - (lambda (str pred action) - (if (eq action 'metadata) - `(metadata - (group-function - . ,(lambda (pin transform) - (if transform pin - (cadr (assoc pin pins)))))) - (complete-with-action action pins str pred))) - nil t nil 'osm--jump-history) - pins) - (`(,name ,_group ,id ,lat ,lon ,zoom) (osm--goto lat lon zoom nil id name)) - (_ (user-error "No pin selected"))))) - -(defun osm--fetch-json (url) - "Get json from URL." - (osm--check-libraries) - (with-temp-buffer - (let* ((default-process-coding-system '(utf-8-unix . utf-8-unix)) - (status (apply #'call-process "curl" nil (current-buffer) nil - `(,@(split-string-and-unquote osm-curl-options) ,url)))) - (unless (eq status 0) - (error "Fetching %s exited with status %s" url status))) - (goto-char (point-min)) - (json-parse-buffer :array-type 'list :object-type 'alist))) - -(defun osm--search (needle) - "Globally search for NEEDLE and return the list of results." - (message "Contacting %s" osm-search-server) - (mapcar - (lambda (x) - (let ((lat (string-to-number (alist-get 'lat x))) - (lon (string-to-number (alist-get 'lon x)))) - `(,(format "%s (%.6f° %.6f°)" - (alist-get 'display_name x) - lat lon) - ,lat ,lon - ,@(mapcar #'string-to-number (alist-get 'boundingbox x))))) - (osm--fetch-json - (format "%s/search?format=json&accept-language=%s&q=%s" - osm-search-server osm-search-language - (url-encode-url needle))))) - -;;;###autoload -(defun osm-search (needle &optional lucky) - "Globally search for NEEDLE on `osm-search-server' and display the map. -If the prefix argument LUCKY is non-nil take the first result and jump there. -See `osm-search-server' and `osm-search-language' for customization." - (interactive - (list - (minibuffer-with-setup-hook - (lambda () - (when (and (eq completing-read-function #'completing-read-default) - (not (bound-and-true-p vertico-mode))) - ;; Override dreaded `minibuffer-complete-word' for default - ;; completion. When will this keybinding finally get removed from - ;; default completion? - (use-local-map (make-composed-keymap - (define-keymap "SPC" nil) - (current-local-map))))) - (completing-read "Location: " - (osm--sorted-table osm--search-history) - nil nil nil 'osm--search-history)) - current-prefix-arg)) - ;; TODO: Add search bounded to current viewbox, bounded=1, viewbox=x1,y1,x2,y2 - (let* ((results (or (osm--search needle) (error "No results for `%s'" needle))) - (selected - (or - (and (or lucky (not (cdr results))) (car results)) - (assoc - (minibuffer-with-setup-hook - (lambda () - (when (and (eq completing-read-function #'completing-read-default) - (not (bound-and-true-p vertico-mode)) - (not (bound-and-true-p icomplete-mode))) - (let ((message-log-max nil) - (inhibit-message t)) - ;; Show matches immediately for default completion. - (minibuffer-completion-help)))) - (completing-read - (format "Matches for '%s': " needle) - (osm--sorted-table results) - nil t nil t)) - results) - (error "No selection")))) - (osm--goto (cadr selected) (caddr selected) - (apply #'osm--boundingbox-to-zoom (cdddr selected)) - nil 'osm-selected (car selected)))) - -(defun osm--sorted-table (coll) - "Sorted completion table from COLL." - (lambda (str pred action) - (if (eq action 'metadata) - '(metadata (display-sort-function . identity) - (cycle-sort-function . identity)) - (complete-with-action action coll str pred)))) - -;;;###autoload -(defun osm-gpx-show (file) - "Show the tracks of gpx FILE in an `osm-mode' buffer." - (interactive "fGPX file: ") - (osm--check-libraries) - (let ((dom (with-temp-buffer - (insert-file-contents file) - (libxml-parse-xml-region (point-min) (point-max)))) - (min-lat 90) (max-lat -90) (min-lon 180) (max-lon -180)) - (setf (alist-get (abbreviate-file-name file) osm--gpx-files nil nil #'equal) - (cons - (cl-loop - for trk in (dom-children dom) - if (eq (dom-tag trk) 'trk) nconc - (cl-loop - for seg in (dom-children trk) - if (eq (dom-tag seg) 'trkseg) collect - (cl-loop - for pt in (dom-children seg) - if (eq (dom-tag pt) 'trkpt) collect - (let ((lat (string-to-number (dom-attr pt 'lat))) - (lon (string-to-number (dom-attr pt 'lon)))) - (setq min-lat (min lat min-lat) - max-lat (max lat max-lat) - min-lon (min lon min-lon) - max-lon (max lon max-lon)) - (cons lat lon))))) - (cl-loop - for pt in (dom-children dom) - if (eq (dom-tag pt) 'wpt) collect - (let ((lat (string-to-number (dom-attr pt 'lat))) - (lon (string-to-number (dom-attr pt 'lon)))) - (setq min-lat (min lat min-lat) - max-lat (max lat max-lat) - min-lon (min lon min-lon) - max-lon (max lon max-lon)) - (list lat lon (dom-text (dom-child-by-tag pt 'name))))))) - (osm--revert) - (osm--goto (/ (+ min-lat max-lat) 2) (/ (+ min-lon max-lon) 2) - (osm--boundingbox-to-zoom min-lat max-lat min-lon max-lon) - nil nil nil))) - -(defun osm-gpx-hide (file) - "Show the tracks of gpx FILE in an `osm-mode' buffer." - (interactive (list (completing-read "GPX file: " - (or osm--gpx-files - (error "No GPX files shown")) - nil t nil 'file-name-history))) - (cl-callf2 assoc-delete-all file osm--gpx-files) - (osm--revert)) - -(defun osm--server-annotation (cand) - "Annotation for server CAND." - (when-let ((copyright (osm--server-property :copyright (get-text-property 0 'osm--server cand))) - (str - (replace-regexp-in-string - "{\\(.*?\\)|.*?}" - (lambda (str) (match-string 1 str)) - (string-join (ensure-list copyright) " | ") copyright))) - (concat (propertize " " 'display `(space :align-to (- right ,(length str) 2))) - " " - str))) - -(defun osm--server-group (cand transform) - "Group function for server CAND with candidate TRANSFORM." - (if transform - cand - (osm--server-property :group (get-text-property 0 'osm--server cand)))) - -;;;###autoload -(defun osm-server (server) - "Select tile SERVER." - (interactive - (let* ((max-name (cl-loop for (_ . x) in osm-server-list - maximize (length (plist-get x :name)))) - (fmt (concat - (propertize (format "%%-%ds " max-name) - 'face 'font-lock-comment-face) - " %s")) - (servers - (mapcar - (lambda (x) - (propertize - (format fmt - (plist-get (cdr x) :name) - (or (plist-get (cdr x) :description) "")) - 'osm--server (car x))) - osm-server-list)) - (selected (completing-read - "Server: " - (lambda (str pred action) - (if (eq action 'metadata) - `(metadata - (annotation-function - . ,(and osm-copyright #'osm--server-annotation)) - (group-function . ,#'osm--server-group)) - (complete-with-action action servers str pred))) - nil t nil 'osm--server-history - (format fmt - (osm--server-property :name) - (or (osm--server-property :description) ""))))) - (list - (get-text-property 0 'osm--server - (or (car (member selected servers)) - (error "No server selected")))))) - (osm--goto nil nil nil server nil nil)) - -(defun osm-save-url (&optional arg) - "Save coordinates as url in the kill ring. -If prefix ARG is given, store url as Elisp expression." - (interactive "P" osm-mode) - (osm--barf-unless-osm) - (pcase-let* ((`(,lat ,lon ,loc) (osm--fetch-location-data "New Link")) - (server (and (not (eq osm-server (default-value 'osm-server))) osm-server)) - (url (if arg - (format "(osm %.6f %.6f %s%s%s)" - lat lon osm--zoom - (if server (format " '%s" osm-server) "") - (if loc (format " %S" loc) "")) - (format "geo:%.6f,%.6f;z=%s%s%s" - lat lon osm--zoom - (if server (format ";s=%s" osm-server) "") - (if loc (format " (%s)" loc) ""))))) - (kill-new url) - (message "Saved in the kill ring: %s" url))) - -(cl-defun osm-add-server (server - &rest properties - &key name description group url max-connections - max-zoom min-zoom download-batch subdomains copyright) - "Add SERVER with PROPERTIES to `osm-server-list'. -The properties are checked as keyword arguments. See -`osm-server-list' for documentation of the keywords." - (declare (indent 1)) - (ignore name description group url max-connections max-zoom - min-zoom download-batch subdomains copyright) - (dolist (sym '(:name :description :group :url)) - (unless (stringp (plist-get properties sym)) - (error "Server property %s is required" sym))) - (unless (and server (symbolp server)) - (error "Server id must be a symbol")) - (setf (alist-get server osm-server-list) properties) - nil) - -;;;###autoload -(add-to-list 'browse-url-default-handlers '("\\`geo:" . osm)) - -;;;###autoload -(eval-after-load 'ol - (lambda () - (declare-function org-link-set-parameters "ol") - (declare-function osm--org-link-props "ext:osm") - (org-link-set-parameters - "geo" - :follow (lambda (link _) (osm (concat "geo:" link))) - :store (lambda () - (when (eq major-mode 'osm-mode) - (apply 'org-link-store-props (osm--org-link-props))))))) - -(provide 'osm) -;;; osm.el ends here diff --git a/emacs/elpa/osm-20240929.642/osm.elc b/emacs/elpa/osm-20240929.642/osm.elc Binary files differ. diff --git a/emacs/elpa/osm-20240929.642/osm-autoloads.el b/emacs/elpa/osm-20241006.13/osm-autoloads.el diff --git a/emacs/elpa/osm-20241006.13/osm-pkg.el b/emacs/elpa/osm-20241006.13/osm-pkg.el @@ -0,0 +1,11 @@ +;; -*- no-byte-compile: t; lexical-binding: nil -*- +(define-package "osm" "20241006.13" + "OpenStreetMap viewer." + '((emacs "28.1") + (compat "30")) + :url "https://github.com/minad/osm" + :commit "e9db7161f62459d61518888bb7d4aadea15c7b1c" + :revdesc "e9db7161f624" + :keywords '("network" "multimedia" "hypermedia" "mouse") + :authors '(("Daniel Mendler" . "mail@daniel-mendler.de")) + :maintainers '(("Daniel Mendler" . "mail@daniel-mendler.de"))) diff --git a/emacs/elpa/osm-20241006.13/osm.el b/emacs/elpa/osm-20241006.13/osm.el @@ -0,0 +1,1832 @@ +;;; osm.el --- OpenStreetMap viewer -*- lexical-binding: t -*- + +;; Copyright (C) 2022-2024 Free Software Foundation, Inc. + +;; Author: Daniel Mendler <mail@daniel-mendler.de> +;; Maintainer: Daniel Mendler <mail@daniel-mendler.de> +;; Created: 2022 +;; Package-Version: 20241006.13 +;; Package-Revision: e9db7161f624 +;; Package-Requires: ((emacs "28.1") (compat "30")) +;; URL: https://github.com/minad/osm +;; Keywords: network, multimedia, hypermedia, mouse + +;; This file is part of GNU Emacs. + +;; This program is free software: you can redistribute it and/or modify +;; it under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. + +;; This program is distributed in the hope that it will be useful, +;; but WITHOUT ANY WARRANTY; without even the implied warranty of +;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +;; GNU General Public License for more details. + +;; You should have received a copy of the GNU General Public License +;; along with this program. If not, see <https://www.gnu.org/licenses/>. + +;;; Commentary: + +;; Osm.el is a tile-based map viewer, with a responsive movable and +;; zoomable display. The map can be controlled with the keyboard or with +;; the mouse. The viewer fetches the map tiles in parallel from tile +;; servers via the `curl' program. The package comes with a list of +;; multiple preconfigured tile servers. You can bookmark your favorite +;; locations using regular Emacs bookmarks or create links from Org files +;; to locations. Furthermore the package provides commands to measure +;; distances, search for locations by name and to open and display GPX +;; tracks. + +;; osm.el requires Emacs 28 and depends on the external `curl' program. +;; Emacs must be built with libxml, libjansson, librsvg, libjpeg and +;; libpng support. + +;;; Code: + +(require 'compat) +(require 'bookmark) +(require 'dom) +(eval-when-compile + (require 'cl-lib) + (require 'subr-x)) + +(defgroup osm nil + "OpenStreetMap viewer." + :link '(info-link :tag "Info Manual" "(osm)") + :link '(url-link :tag "Website" "https://github.com/minad/osm") + :link '(emacs-library-link :tag "Library Source" "osm.el") + :group 'web + :prefix "osm-") + +(defcustom osm-curl-options + "--disable --fail --location --silent --max-time 30" + "Curl command line options." + :type 'string) + +(defcustom osm-search-language "en" + "Language used for search results. +Use RFC 1766 abbreviations, e.g.: `en' for English, `de' for German. +A comma-separated specifies descending order of preference. See also +`url-mime-language-string'." + :type 'string) + +(defcustom osm-search-server + "https://nominatim.openstreetmap.org" + "Server used to search for location names. +The server must offer the nominatim.org API." + :type 'string) + +(defcustom osm-server-defaults + '(:min-zoom 2 + :max-zoom 19 + :download-batch 4 + :max-connections 2 + :subdomains ("a" "b" "c")) + "Default server properties. +See also `osm-server-list'." + :type 'plist) + +(defcustom osm-server-list + '((default + :name "Carto" + :description "Standard Carto map provided by OpenStreetMap" + :url "https://%s.tile.openstreetmap.org/%z/%x/%y.png" + :group "Standard" + :copyright ("Map data © {OpenStreetMap|https://www.openstreetmap.org/copyright} contributors" + "Map style © {OpenStreetMap Standard|https://www.openstreetmap.org/copyright}")) + (de + :name "Carto(de)" + :description "Localized Carto map provided by OpenStreetMap Germany" + :url "https://%s.tile.openstreetmap.de/%z/%x/%y.png" + :group "Standard" + :copyright ("Map data © {OpenStreetMap|https://www.openstreetmap.org/copyright} contributors" + "Map style © {OpenStreetMap Deutschland|https://www.openstreetmap.de/germanstyle.html}")) + (fr + :name "Carto(fr)" + :description "Localized Carto map by OpenStreetMap France" + :url "https://%s.tile.openstreetmap.fr/osmfr/%z/%x/%y.png" + :group "Standard" + :copyright ("Map data © {OpenStreetMap|https://www.openstreetmap.org/copyright} contributors" + "Map style © {OpenStreetMap France|https://www.openstreetmap.fr/mentions-legales/}")) + (humanitarian + :name "Humanitarian" + :description "Humanitarian map provided by OpenStreetMap France" + :url "https://%s.tile.openstreetmap.fr/hot/%z/%x/%y.png" + :group "Special Purpose" + :copyright ("Map data © {OpenStreetMap|https://www.openstreetmap.org/copyright} contributors" + "Map style © {Humanitarian OpenStreetMap Team|https://www.hotosm.org/updates/2013-09-29_a_new_window_on_openstreetmap_data}")) + (cyclosm + :name "CyclOSM" + :description "Bicycle-oriented map provided by OpenStreetMap France" + :url "https://%s.tile-cyclosm.openstreetmap.fr/cyclosm/%z/%x/%y.png" + :group "Transportation" + :copyright ("Map data © {OpenStreetMap|https://www.openstreetmap.org/copyright} contributors" + "Map style © {CyclOSM|https://www.cyclosm.org/} contributors")) + (openriverboatmap + :name "OpenRiverBoatMap" + :description "Waterways map provided by OpenStreetMap France" + :url "https://%s.tile.openstreetmap.fr/openriverboatmap/%z/%x/%y.png" + :group "Transportation" + :copyright ("Map data © {OpenStreetMap|https://www.openstreetmap.org/copyright} contributors" + "Map style © {OpenRiverBoatMap|https://github.com/tilery/OpenRiverboatMap}")) + (opentopomap + :name "OpenTopoMap" + :description "Topographical map provided by OpenTopoMap" + :url "https://%s.tile.opentopomap.org/%z/%x/%y.png" + :group "Topographical" + :copyright ("Map data © {OpenStreetMap|https://www.openstreetmap.org/copyright} contributors" + "Map style © {OpenTopoMap|https://www.opentopomap.org} ({CC-BY-SA|https://creativecommons.org/licenses/by-sa/3.0/})" + "Elevation data: {SRTM|https://www2.jpl.nasa.gov/srtm/}")) + (opvn + :name "ÖPNV" :max-zoom 18 + :description "Base layer with public transport information" + :url "http://%s.tile.memomaps.de/tilegen/%z/%x/%y.png" + :group "Transportation" + :copyright ("Map data © {OpenStreetMap|https://www.openstreetmap.org/copyright} contributors" + "Map style © {ÖPNVKarte|https://www.öpnvkarte.de}"))) + "List of tile servers. + +Allowed keys: + :name Server name + :description Server description + :copyright Copyright information + :group Name of server groups for related servers + :url Url with placeholders + :min-zoom Minimum zoom level + :max-zoom Maximum zoom level + :download-batch Number of tiles downloaded via a single connection + :max-connections Maximum number of parallel connections + :subdomains Subdomains used for the %s placeholder + +See also `osm-server-defaults' for default values used for a +server if the property is missing. + +The :url of each server should specify %x, %y, %z and %s placeholders +for the map coordinates. It can optionally use an %s placeholder +for the subdomain and a %k placeholder for an apikey. The apikey +will be retrieved via `auth-source-search' with the :host set to +the domain name and the :user to the string \"apikey\"." + :type '(alist :key-type symbol :value-type plist)) + +(defcustom osm-copyright t + "Display the copyright information above the map." + :type 'boolean) + +(defcustom osm-pin-colors + '((osm-selected . "#e20") + (osm-bookmark . "#f80") + (osm-poi . "#88f") + (osm-home . "#80f") + (osm-track . "#00a")) + "Colors of pins." + :type '(alist :key-type symbol :value-type string)) + +(defcustom osm-track-style + "stroke:#00a;stroke-width:5;stroke-linejoin:round;stroke-linecap:round;opacity:0.4;" + "SVG style used to draw tracks." + :type 'string) + +(defcustom osm-home + (let ((lat (bound-and-true-p calendar-latitude)) + (lon (bound-and-true-p calendar-longitude))) + (if (and lat lon) + (list lat lon 12) + (list 0 0 3))) + "Home coordinates, latitude, longitude and zoom level." + :type '(list :tag "Coordinates" + (number :tag "Latitude ") + (number :tag "Longitude ") + (number :tag "Zoom "))) + +(defcustom osm-large-step 256 + "Scroll step in pixel." + :type 'natnum) + +(defcustom osm-tile-border nil + "Set to t to display thin tile borders. +For debugging set the value to `debug', such that a border is +shown around SVG tiles." + :type '(choice boolean (const debug))) + +(defcustom osm-small-step 16 + "Scroll step in pixel." + :type 'natnum) + +(defcustom osm-server 'default + "Tile server name." + :type 'symbol) + +(defcustom osm-tile-directory + (expand-file-name "var/osm/" user-emacs-directory) + "Tile cache directory." + :type 'string) + +(defcustom osm-max-age 14 + "Maximum tile age in days. +Should be at least 7 days according to the server usage policies." + :type '(choice (const nil) natnum)) + +(defcustom osm-max-tiles 256 + "Number of tiles to keep in the memory cache." + :type '(choice (const nil) natnum)) + +(defun osm--menu-item (menu) + "Generate menu item from MENU." + `(menu-item + "" nil :filter + ,(lambda (&optional _) + (select-window + (posn-window + (event-start last-input-event))) + (if (functionp menu) + (funcall menu) + menu)))) + +(defun osm--mouse-ignore-wheel (_prompt) + "Ignore mouse wheel events during key translation." + (pcase (this-single-command-raw-keys) + ((and `[,e] + (let y (event-basic-type e)) + (guard (symbolp y)) + (guard (string-search "wheel-" (symbol-name y)))) + []) + (k k))) + +(defvar-keymap osm-prefix-map + :doc "Global prefix map of OSM entry points." + "h" #'osm-home + "s" #'osm-search + "v" #'osm-server + "t" #'osm-goto + "j" #'osm-jump + "x" #'osm-gpx-show + "X" #'osm-gpx-hide) + +;;;###autoload (autoload 'osm-prefix-map "osm" nil t 'keymap) +(defalias 'osm-prefix-map osm-prefix-map) + +(defvar-keymap osm-mode-map + :doc "Keymap used by `osm-mode'." + :parent (make-composed-keymap osm-prefix-map special-mode-map) + "<home>" #'osm-home + "+" #'osm-zoom-in + "-" #'osm-zoom-out + "SPC" #'osm-zoom-in + "S-SPC" #'osm-zoom-out + "<mouse-1>" #'osm-mouse-pin + "<mouse-2>" 'org-store-link + "<mouse-3>" #'osm-bookmark-set + "S-<down-mouse-1>" #'ignore + "S-<mouse-1>" #'osm-mouse-track + "<down-mouse-1>" #'osm-mouse-drag + "<down-mouse-2>" #'osm-mouse-drag + "<down-mouse-3>" #'osm-mouse-drag + "<drag-mouse-1>" #'ignore + "<drag-mouse-2>" #'ignore + "<drag-mouse-3>" #'ignore + "<up>" #'osm-up + "<down>" #'osm-down + "<left>" #'osm-left + "<right>" #'osm-right + "C-<up>" #'osm-up-up + "C-<down>" #'osm-down-down + "C-<left>" #'osm-left-left + "C-<right>" #'osm-right-right + "M-<up>" #'osm-up-up + "M-<down>" #'osm-down-down + "M-<left>" #'osm-left-left + "M-<right>" #'osm-right-right + "S-<up>" #'osm-up-up + "S-<down>" #'osm-down-down + "S-<left>" #'osm-left-left + "S-<right>" #'osm-right-right + "n" #'osm-rename + "d" #'osm-delete + "DEL" #'osm-delete + "<deletechar>" #'osm-delete + "c" #'osm-center + "o" #'clone-buffer + "u" #'osm-save-url + "l" 'org-store-link + "b" #'osm-bookmark-set + "X" #'osm-gpx-hide + "<remap> <scroll-down-command>" #'osm-down + "<remap> <scroll-up-command>" #'osm-up + "<" nil + ">" nil) + +(dolist (pin osm-pin-colors) + (setq pin (vector (car pin))) + (define-key key-translation-map pin #'osm--mouse-ignore-wheel) + (define-key osm-mode-map pin #'osm-mouse-select)) + +(easy-menu-define osm-mode-menu osm-mode-map + "Menu for `osm-mode'." + '("OSM" + ["Go home" osm-home] + ["Center" osm-center] + ["Go to coordinates" osm-goto] + ["Jump to pin" osm-jump] + ["Search by name" osm-search] + ["Change tile server" osm-server] + "--" + ["Org Link" org-store-link] + ["Geo Url" osm-save-url] + ["Elisp Link" (osm-save-url t)] + ("Bookmark" + ["Set" osm-bookmark-set] + ["Jump" osm-bookmark-jump] + ["Rename" osm-bookmark-rename] + ["Delete" osm-bookmark-delete]) + "--" + ["Show GPX file" osm-gpx-show] + ["Hide GPX file" osm-gpx-hide] + "--" + ["Clone buffer" clone-buffer] + ["Revert buffer" revert-buffer] + "--" + ["Manual" (info "(osm)")] + ["Customize" (customize-group 'osm)])) + +(defconst osm--placeholder + '(:type svg :width 256 :height 256 + :data "<svg width='256' height='256' version='1.1' xmlns='http://www.w3.org/2000/svg'> + <defs> + <pattern id='grid' width='16' height='16' patternUnits='userSpaceOnUse'> + <path d='m 0 0 l 0 16 16 0' fill='none' stroke='#888888'/> + </pattern> + </defs> + <rect width='256' height='256' fill='url(#grid)'/> +</svg>") + "Placeholder image for tiles.") + +(defvar osm--search-history nil + "Minibuffer history used by command `osm-search'.") + +(defvar osm--jump-history nil + "Minibuffer history used by command `osm-jump'.") + +(defvar osm--server-history nil + "Minibuffer history used by command `osm-server'.") + +(defvar osm--purge-directory 0 + "Last time the tile cache was cleaned.") + +(defvar osm--tile-cache nil + "Global tile memory cache.") + +(defvar osm--tile-age 0 + "Tile age, incremented on every update.") + +(defvar osm--gpx-files nil + "Global list of loaded tracks.") + +(defvar osm--track nil + "List of track coordinates.") + +(defvar osm--download-processes nil + "Globally active download processes.") + +(defvar osm--download-active nil + "Globally active download jobs.") + +(defvar osm--download-subdomain nil + "Subdomain indices to query the servers in a round-robin fashion.") + +(defvar-local osm--download-queue nil + "Buffer-local tile download queue.") + +(defvar-local osm--wx 0 + "Half window width in pixel.") + +(defvar-local osm--wy 0 + "Half window height in pixel.") + +(defvar-local osm--nx 0 + "Number of tiles in x direction.") + +(defvar-local osm--ny 0 + "Number of tiles in y direction.") + +(defvar-local osm--zoom nil + "Zoom level of the map.") + +(defvar-local osm--lat nil + "Latitude coordinate.") + +(defvar-local osm--lon nil + "Longitude coordinate.") + +(defvar-local osm--overlays nil + "Overlay hash table. +Local per buffer since the overlays depend on the zoom level.") + +(defvar-local osm--pin nil + "Currently selected pin.") + +(defmacro osm--each (&rest body) + "Execute BODY in each `osm-mode' buffer." + (cl-with-gensyms (buf) + `(dolist (,buf (buffer-list)) + (when (eq (buffer-local-value 'major-mode ,buf) #'osm-mode) + (with-current-buffer ,buf + ,@body))))) + +(defun osm--server-menu () + "Generate server menu." + (let (menu last-group) + (dolist (server osm-server-list) + (let* ((plist (cdr server)) + (group (plist-get plist :group))) + (unless (equal last-group group) + (push (format "─── %s ───" group) menu) + (setq last-group group)) + (push + `[,(plist-get plist :name) + (osm-server ',(car server)) + :style toggle + :selected (eq osm-server ',(car server))] + menu))) + (easy-menu-create-menu "Server" (nreverse menu)))) + +(defsubst osm--lon-to-normalized-x (lon) + "Convert LON to normalized x coordinate." + (/ (+ lon 180.0) 360.0)) + +(defsubst osm--lat-to-normalized-y (lat) + "Convert LAT to normalized y coordinate." + (setq lat (* lat (/ float-pi 180.0))) + (- 0.5 (/ (log (+ (tan lat) (/ 1.0 (cos lat)))) float-pi 2))) + +(defun osm--boundingbox-to-zoom (lat1 lat2 lon1 lon2) + "Compute zoom level from boundingbox LAT1 to LAT2 and LON1 to LON2." + (let ((w (/ (frame-pixel-width) 256)) + (h (/ (frame-pixel-height) 256))) + (max (osm--server-property :min-zoom) + (min + (osm--server-property :max-zoom) + (min (logb (/ w (abs (- (osm--lon-to-normalized-x lon1) (osm--lon-to-normalized-x lon2))))) + (logb (/ h (abs (- (osm--lat-to-normalized-y lat1) (osm--lat-to-normalized-y lat2)))))))))) + +(defun osm--x-to-lon (x zoom) + "Return longitude in degrees for X/ZOOM." + (- (/ (* x 360.0) 256.0 (expt 2.0 zoom)) 180.0)) + +(defun osm--y-to-lat (y zoom) + "Return latitude in degrees for Y/ZOOM." + (setq y (* float-pi (- 1 (* 2 (/ y 256.0 (expt 2.0 zoom)))))) + (/ (* 180 (atan (/ (- (exp y) (exp (- y))) 2))) float-pi)) + +(defsubst osm--lon-to-x (lon zoom) + "Convert LON/ZOOM to x coordinate in pixel." + (floor (* 256 (expt 2.0 zoom) (osm--lon-to-normalized-x lon)))) + +(defsubst osm--lat-to-y (lat zoom) + "Convert LAT/ZOOM to y coordinate in pixel." + (floor (* 256 (expt 2.0 zoom) (osm--lat-to-normalized-y lat)))) + +(defsubst osm--x () + "Return longitude in pixel of map center." + (osm--lon-to-x osm--lon osm--zoom)) + +(defsubst osm--y () + "Return latitude in pixel of map center." + (osm--lat-to-y osm--lat osm--zoom)) + +(defsubst osm--x0 () + "Return longitude in pixel of top left corner." + (- (osm--x) osm--wx)) + +(defsubst osm--y0 () + "Return latitude in pixel of top left corner." + (- (osm--y) osm--wy)) + +(defun osm--server-property (prop &optional server) + "Return server property PROP for SERVER." + (or (plist-get (alist-get (or server osm-server) osm-server-list) prop) + (plist-get osm-server-defaults prop))) + +(defun osm--tile-url (x y zoom) + "Return tile url for coordinate X, Y and ZOOM." + (let ((url (osm--server-property :url)) + (sub (osm--server-property :subdomains)) + (key (osm--server-property :key))) + (when (and (string-search "%k" url) (not key)) + (require 'auth-source) + (declare-function auth-source-search "auth-source") + (let ((host (string-join + (last (split-string (cadr (split-string url "/" t)) "\\.") 2) + "."))) + (setq key (plist-get + (car (auth-source-search :require '(:user :host :secret) + :host host + :user "apikey")) + :secret)) + (unless key + (warn "No auth source secret found for apikey@%s" host) + (setq key "")) + (setf (plist-get (alist-get osm-server osm-server-list) :key) key))) + (format-spec + url `((?z . ,zoom) (?x . ,x) (?y . ,y) + (?k . ,(if (functionp key) (funcall key) key)) + (?s . ,(nth (mod (alist-get osm-server osm--download-subdomain 0) + (length sub)) + sub)))))) + +(defun osm--tile-file (x y zoom) + "Return tile file name for coordinate X, Y and ZOOM." + (file-name-concat + (expand-file-name osm-tile-directory) + (symbol-name osm-server) + (format "%d-%d-%d.%s" + zoom x y + (file-name-extension + (url-file-nondirectory + (osm--server-property :url)))))) + +(defun osm--enqueue-download (x y) + "Enqueue tile X/Y for download." + (when (let ((n (expt 2 osm--zoom))) (and (>= x 0) (>= y 0) (< x n) (< y n))) + (let ((job (list osm-server osm--zoom x y))) + (unless (or (member job osm--download-queue) (member job osm--download-active)) + (setq osm--download-queue (nconc osm--download-queue (list job))))))) + +(defun osm--download-filter (output) + "Filter function for the download process which receives OUTPUT." + (while (string-match + "\\`\\([0-9]+\\) \\(.*?/\\([^/]+\\)/\\([0-9]+\\)-\\([0-9]+\\)-\\([0-9]+\\)\\.[^\r\n]+\\)\r?\n" + output) + (let ((status (match-string 1 output)) + (file (match-string 2 output)) + (server (intern-soft (match-string 3 output))) + (zoom (string-to-number (match-string 4 output))) + (x (string-to-number (match-string 5 output))) + (y (string-to-number (match-string 6 output)))) + (setq output (substring output (match-end 0))) + (when (equal status "200") + (ignore-errors (rename-file file (string-remove-suffix ".tmp" file) t)) + (osm--each + (when (and (= osm--zoom zoom) (eq osm-server server)) + (osm--display-tile x y (osm--get-tile x y))))) + (cl-callf2 delete (list server zoom x y) osm--download-active) + (delete-file file))) + output) + +(defun osm--download-command () + "Build download command." + (let* ((count 0) + (batch (osm--server-property :download-batch)) + (subs (length (osm--server-property :subdomains))) + (parallel (* subs (osm--server-property :max-connections))) + args jobs job) + (while (and (< count batch) + (setq job (nth (* count parallel) osm--download-queue))) + (pcase-let ((`(,_server ,zoom ,x ,y) job)) + (setq args `(,(osm--tile-url x y zoom) + ,(concat (osm--tile-file x y zoom) ".tmp") + "--output" + ,@args)) + (push job jobs) + (push job osm--download-active) + (cl-incf count))) + (osm--each + (dolist (job jobs) + (cl-callf2 delq job osm--download-queue))) + (cl-callf (lambda (s) (mod (1+ s) subs)) + (alist-get osm-server osm--download-subdomain 0)) + (cons `("curl" "--write-out" "%{http_code} %{filename_effective}\n" + ,@(split-string-and-unquote osm-curl-options) ,@(nreverse args)) + jobs))) + +(defun osm--download () + "Download next tiles from the queue." + (when (and (< (length (alist-get osm-server osm--download-processes)) + (* (length (osm--server-property :subdomains)) + (osm--server-property :max-connections))) + osm--download-queue) + (pcase-let ((`(,command . ,jobs) (osm--download-command)) + (dir (file-name-concat (expand-file-name osm-tile-directory) + (symbol-name osm-server))) + (server osm-server)) + (make-directory dir t) + (push + (make-process + :name "*osm curl*" + :connection-type 'pipe + :noquery t + :command command + :filter + (let ((output "")) + (lambda (_proc out) + (setq output (osm--download-filter (concat output out))) + (force-mode-line-update t))) + :sentinel + (lambda (proc _status) + (dolist (job jobs) + (cl-callf2 delq job osm--download-active)) + (cl-callf2 delq proc (alist-get server osm--download-processes nil t)) + (force-mode-line-update t) + (osm--download))) + (alist-get server osm--download-processes)) + (force-mode-line-update t) + (osm--download)))) + +(defun osm-mouse-drag (event) + "Handle drag EVENT." + (declare (completion ignore)) + (interactive "@e") + (pcase-let* ((`(,sx . ,sy) (posn-x-y (event-start event))) + (win (selected-window)) + (map (define-keymap + "<mouse-movement>" + (lambda (event) + (interactive "e") + (setq event (event-start event)) + (when (eq win (posn-window event)) + (pcase-let ((`(,ex . ,ey) (posn-x-y event))) + (osm--move (- sx ex) (- sy ey)) + (setq sx ex sy ey) + (osm--update))))))) + (setq track-mouse 'dragging) + (set-transient-map map + (lambda () (eq (car-safe last-input-event) 'mouse-movement)) + (lambda () (setq track-mouse nil))))) + +(defun osm--zoom-in-wheel (_n) + "Zoom in with the mouse wheel." + (pcase-let ((`(,x . ,y) (posn-x-y (event-start last-input-event)))) + (when (< osm--zoom (osm--server-property :max-zoom)) + (osm--move (/ (- x osm--wx) 2) (/ (- y osm--wy) 2)) + (osm-zoom-in)))) + +(defun osm--zoom-out-wheel (_n) + "Zoom out with the mouse wheel." + (pcase-let ((`(,x . ,y) (posn-x-y (event-start last-input-event)))) + (when (> osm--zoom (osm--server-property :min-zoom)) + (osm--move (- osm--wx x) (- osm--wy y)) + (osm-zoom-out)))) + +(defun osm-center () + "Center to location of selected pin." + (interactive nil osm-mode) + (osm--barf-unless-osm) + (pcase osm--pin + (`(,lat ,lon ,_id ,name) + (setq osm--lat lat osm--lon lon) + (message "%s" name) + (osm--update)))) + +(defun osm--haversine (lat1 lon1 lat2 lon2) + "Compute distance between LAT1/LON1 and LAT2/LON2 in km." + ;; https://en.wikipedia.org/wiki/Haversine_formula + (let* ((rad (/ float-pi 180)) + (y (sin (* 0.5 rad (- lat2 lat1)))) + (x (sin (* 0.5 rad (- lon2 lon1)))) + (h (+ (* x x) (* (cos (* rad lat1)) (cos (* rad lat2)) y y)))) + (* 2 6371 (atan (sqrt h) (sqrt (- 1 h)))))) + +(defun osm-mouse-track (event) + "Set track pin at location of the click EVENT." + (declare (completion ignore)) + (interactive "@e") + (pcase osm--pin + ((and (guard (not osm--track)) `(,lat ,lon ,_id ,_name)) + (push (list lat lon "WP1") osm--track))) + (osm--set-pin-event event 'osm-track + (format "WP%s" (1+ (length osm--track))) 'quiet) + (pcase-let ((`(,lat ,lon ,_id ,name) osm--pin)) + (push (list lat lon name) osm--track)) + (osm--revert) + (osm--track-length)) + +(defun osm--track-length () + "Echo track length." + (when (cdr osm--track) + (pcase-let* ((len1 0) + (len2 0) + (p osm--track) + (`(,sel-lat ,sel-lon ,_ ,sel-name) osm--pin)) + (while (and (cdr p) (not (and (equal (caar p) sel-lat) + (equal (cadar p) sel-lon)))) + (cl-incf len2 (osm--haversine (caar p) (cadar p) + (caadr p) (cadadr p))) + (pop p)) + (while (cdr p) + (cl-incf len1 (osm--haversine (caar p) (cadar p) + (caadr p) (cadadr p))) + (pop p)) + (message "%s way points, length %.2fkm, %s" + (length osm--track) (+ len1 len2) + (if (or (= len1 0) (= len2 0)) + sel-name + (format "%.2fkm → %s → %.2fkm" + len1 sel-name len2)))))) + +(defun osm--pin-at (event &optional type) + "Get pin of TYPE at EVENT." + (let* ((xy (posn-x-y (event-start event))) + (x (+ (osm--x0) (car xy))) + (y (+ (osm--y0) (cdr xy))) + (min most-positive-fixnum) + found) + (dolist (pin (car (osm--get-overlays (/ x 256) (/ y 256)))) + (pcase-let ((`(,p ,q ,_lat ,_lon ,id ,_name) pin)) + (when (or (not type) (eq type id)) + (let ((d (+ (* (- p x) (- p x)) (* (- q y) (- q y))))) + (when (and (>= q y) (< q (+ y 50)) (>= p (- x 20)) (< p (+ x 20)) (< d min)) + (setq min d found pin)))))) + (cddr found))) + +(defun osm-mouse-pin (event) + "Create location pin at the click EVENT." + (declare (completion ignore)) + (interactive "@e") + (osm--set-pin-event event) + (osm--update)) + +(defun osm-mouse-select (event) + "Select pin at position of click EVENT." + (declare (completion ignore)) + (interactive "@e") + (when (memq (event-basic-type event) '(mouse-1 mouse-2 mouse-3)) + (pcase (osm--pin-at event) + (`(,lat ,lon ,id ,name) + (osm--set-pin id lat lon name (eq id 'osm-track)) + (when (eq id 'osm-track) (osm--track-length)) + (osm--update))))) + +(defun osm-zoom-in (&optional n) + "Zoom N times into the map." + (interactive "p" osm-mode) + (osm--barf-unless-osm) + (setq osm--zoom (max (osm--server-property :min-zoom) + (min (osm--server-property :max-zoom) + (+ osm--zoom (or n 1))))) + (osm--update)) + +(defun osm-zoom-out (&optional n) + "Zoom N times out of the map." + (interactive "p" osm-mode) + (osm-zoom-in (- (or n 1)))) + +(defun osm--move (dx dy) + "Move by DX/DY." + (osm--barf-unless-osm) + (setq osm--lon (osm--x-to-lon (+ (osm--x) dx) osm--zoom) + osm--lat (osm--y-to-lat (+ (osm--y) dy) osm--zoom))) + +(defun osm-right (&optional n) + "Move N small steps to the right." + (interactive "p" osm-mode) + (osm--move (* (or n 1) osm-small-step) 0) + (osm--update)) + +(defun osm-down (&optional n) + "Move N small steps down." + (interactive "p" osm-mode) + (osm--move 0 (* (or n 1) osm-small-step)) + (osm--update)) + +(defun osm-up (&optional n) + "Move N small steps up." + (interactive "p" osm-mode) + (osm-down (- (or n 1)))) + +(defun osm-left (&optional n) + "Move N small steps to the left." + (interactive "p" osm-mode) + (osm-right (- (or n 1)))) + +(defun osm-right-right (&optional n) + "Move N large steps to the right." + (interactive "p" osm-mode) + (osm--move (* (or n 1) osm-large-step) 0) + (osm--update)) + +(defun osm-down-down (&optional n) + "Move N large steps down." + (interactive "p" osm-mode) + (osm--move 0 (* (or n 1) osm-large-step)) + (osm--update)) + +(defun osm-up-up (&optional n) + "Move N large steps up." + (interactive "p" osm-mode) + (osm-down-down (- (or n 1)))) + +(defun osm-left-left (&optional n) + "Move N large steps to the left." + (interactive "p" osm-mode) + (osm-right-right (- (or n 1)))) + +(defun osm--purge-directory () + "Clean tile directory." + (when (and (integerp osm-max-age) + (> (- (float-time) osm--purge-directory) (* 60 60 24))) + (setq osm--purge-directory (float-time)) + (run-with-idle-timer + 30 nil + (lambda () + (dolist (dir (directory-files osm-tile-directory t "\\`[^.]+\\'" t)) + (dolist (file (directory-files + dir t "\\.\\(?:png\\|jpe?g\\)\\(?:\\.tmp\\)?\\'" t)) + (when (> (float-time (time-since + (file-attribute-modification-time + (file-attributes file)))) + (* 60 60 24 osm-max-age)) + (delete-file file))) + (when (directory-empty-p dir) + (ignore-errors (delete-directory dir)))))))) + +(defun osm--check-libraries () + "Check that Emacs is compiled with the necessary libraries." + (let (req) + (unless (display-graphic-p) + (push "graphical display" req)) + (dolist (type '(svg jpeg png)) + (unless (image-type-available-p type) + (push (format "%s support" type) req))) + (unless (libxml-available-p) + (push "libxml" req)) + (unless (json-available-p) + (push "libjansson" req)) + (when req + (error "Osm: Please compile Emacs with the required libraries, %s needed to proceed" + (string-join req ", "))))) + +(define-derived-mode osm-mode special-mode "Osm" + "OpenStreetMap viewer mode." + :interactive nil :abbrev-table nil :syntax-table nil + (osm--check-libraries) + (setq-local osm-server osm-server + line-spacing nil + cursor-type nil + cursor-in-non-selected-windows nil + left-fringe-width 1 + right-fringe-width 1 + left-margin-width 0 + right-margin-width 0 + truncate-lines t + show-trailing-whitespace nil + display-line-numbers nil + buffer-read-only t + fringe-indicator-alist '((truncation . nil)) + revert-buffer-function #'osm--revert + mode-line-process '(:eval (osm--download-queue-info)) + mode-line-position nil + mode-line-modified nil + mode-line-mule-info nil + mode-line-remote nil + default-directory (expand-file-name "~/") + eldoc-documentation-functions nil + mouse-wheel-progressive-speed nil + mwheel-scroll-up-function #'osm--zoom-out-wheel + mwheel-scroll-down-function #'osm--zoom-in-wheel + mwheel-scroll-left-function #'osm--zoom-out-wheel + mwheel-scroll-right-function #'osm--zoom-in-wheel + bookmark-make-record-function #'osm--bookmark-record-default) + (when (boundp 'mwheel-coalesce-scroll-events) + (setq-local mwheel-coalesce-scroll-events t)) + (when (boundp 'pixel-scroll-precision-mode) + (setq-local pixel-scroll-precision-mode nil)) + (add-hook 'change-major-mode-hook #'osm--barf-change-mode nil 'local) + (add-hook 'write-contents-functions #'osm--barf-write nil 'local) + (add-hook 'window-size-change-functions #'osm--resize nil 'local)) + +(defun osm--barf-write () + "Barf for write operation." + (set-buffer-modified-p nil) + (setq buffer-read-only t) + (set-visited-file-name nil) + (error "Writing the buffer to a file is not supported")) + +(defun osm--barf-change-mode () + "Barf for change mode operation." + (error "Changing the major mode is not supported")) + +(defun osm--barf-unless-osm () + "Barf if not an `osm-mode' buffer." + (unless (eq major-mode #'osm-mode) + (error "Not an `osm-mode' buffer"))) + +(defun osm--each-pin (fun) + "Call FUN for each pin on the map." + (pcase osm-home + (`(,lat ,lon ,zoom) + (funcall fun 'osm-home lat lon zoom "Home"))) + (bookmark-maybe-load-default-file) + (cl-loop for bm in bookmark-alist + if (eq (bookmark-prop-get bm 'handler) #'osm-bookmark-jump) do + (pcase-let ((`(,lat ,lon ,zoom) (bookmark-prop-get bm 'coordinates))) + (funcall fun 'osm-bookmark lat lon zoom (car bm)))) + (dolist (file osm--gpx-files) + (cl-loop for (lat lon name) in (cddr file) do + (funcall fun 'osm-poi lat lon 15 name))) + (cl-loop for (lat lon name) in osm--track do + (funcall fun 'osm-track lat lon 15 name))) + +(defun osm--pin-inside-p (x y lat lon) + "Return non-nil if pin at LAT/LON is inside tile X/Y." + (let ((p (/ (osm--lon-to-x lon osm--zoom) 256.0)) + (q (/ (osm--lat-to-y lat osm--zoom) 256.0))) + (and (>= p (- x 0.125)) (< p (+ x 1.125)) + (>= q y) (< q (+ y 1.25))))) + +(defun osm--add-pin (pins id lat lon _zoom name) + "Add pin at LAT/LON with NAME and ID to the PINS hash table." + (let* ((x (osm--lon-to-x lon osm--zoom)) + (y (osm--lat-to-y lat osm--zoom)) + (x0 (/ x 256)) + (y0 (/ y 256)) + (pin (list x y lat lon id name))) + (push pin (gethash (cons x0 y0) pins)) + (cl-loop + for i from -1 to 1 do + (cl-loop + for j from -1 to 0 do + (let ((x1 (/ (+ x (* 32 i)) 256)) + (y1 (/ (+ y (* 64 j)) 256))) + (unless (and (= x0 x1) (= y0 y1)) + (push pin (gethash (cons x1 y1) pins)))))))) + +;; TODO: The Bresenham algorithm used here to add the line segments to the tiles +;; has the issue that lines which go along a tile border may be drawn only +;; partially. Use a more precise algorithm instead. +(defun osm--add-track (tracks seg) + "Add track segment SEG to TRACKS hash table." + (when seg + (let ((p0 (cons (osm--lon-to-x (or (car-safe (cdar seg)) (cdar seg)) osm--zoom) + (osm--lat-to-y (caar seg) osm--zoom)))) + (dolist (pt (cdr seg)) + (let* ((px1 (cdr pt)) + (px1 (osm--lon-to-x (if (consp px1) (car px1) px1) osm--zoom)) + (py1 (osm--lat-to-y (car pt) osm--zoom)) + (pdx (- px1 (car p0))) + (pdy (- py1 (cdr p0)))) + ;; Ignore point if too close to last point + (unless (< (+ (* pdx pdx) (* pdy pdy)) 50) + (let* ((p1 (cons px1 py1)) + (line (cons p0 p1)) + (x0 (/ (car p0) 256)) + (y0 (/ (cdr p0) 256)) + (x1 (/ px1 256)) + (y1 (/ py1 256)) + (sx (if (< x0 x1) 1 -1)) + (sy (if (< y0 y1) 1 -1)) + (dx (* sx (- x1 x0))) + (dy (* sy (- y0 y1))) + (err (+ dx dy))) + ;; Bresenham + (while + (let ((ey (> (* err 2) dy)) + (ex (< (* err 2) dx))) + (push line (gethash (cons x0 y0) tracks)) + (unless (and (= x0 x1) (= y0 y1)) + (when (and ey ex) + (push line (gethash (cons x0 (+ y0 sy)) tracks)) + (push line (gethash (cons (+ x0 sx) y0) tracks))) + (when ey + (cl-incf err dy) + (cl-incf x0 sx)) + (when ex + (cl-incf err dx) + (cl-incf y0 sy)) + t))) + (setq p0 p1)))))))) + +(defun osm--get-overlays (x y) + "Compute overlays and return the overlays in tile X/Y." + (unless (eq (car osm--overlays) osm--zoom) + ;; TODO: Do not compute overlays for the entire map, only for a reasonable + ;; view port around the current center, depending on the size of the + ;; window. Otherwise the spatial hash map for the tracks gets very large if + ;; a line segment spans many tiles. + (let ((pins (make-hash-table :test #'equal)) + (tracks (make-hash-table :test #'equal))) + (osm--each-pin (apply-partially #'osm--add-pin pins)) + (dolist (file osm--gpx-files) + (dolist (seg (cadr file)) + (osm--add-track tracks seg))) + (osm--add-track tracks osm--track) + (setq osm--overlays (list osm--zoom pins tracks)))) + (let ((pins (gethash (cons x y) (cadr osm--overlays))) + (tracks (gethash (cons x y) (caddr osm--overlays)))) + (and (or pins tracks) (cons pins tracks)))) + +(autoload 'svg--image-data "svg") +(defun osm--draw-tile (x y tpin) + "Make tile at X/Y from FILE. +TPIN is an optional pin." + (let ((file (osm--tile-file x y osm--zoom)) + overlays) + (when (file-exists-p file) + (if (or (setq overlays (osm--get-overlays x y)) (eq osm-tile-border t) tpin) + (let* ((areas nil) + (x0 (* 256 x)) + (y0 (* 256 y)) + (svg-pin + (lambda (pin) + (pcase-let* ((`(,p ,q ,_lat ,_lon ,id ,name) pin) + (bg (cdr (assq id osm-pin-colors)))) + (setq p (- p x0) q (- q y0)) + (push `((poly . [,p ,q ,(- p 20) ,(- q 40) ,p ,(- q 50) ,(+ p 20) ,(- q 40) ]) + ,id (help-echo ,(truncate-string-to-width name 40 0 nil t))) + areas) + ;; https://commons.wikimedia.org/wiki/File:Simpleicons_Places_map-marker-1.svg + (format " +<g fill='%s' stroke='#000' stroke-width='9' transform='translate(%s %s) scale(0.09) translate(-256 -512)'> +<path d='M256 0C167.641 0 96 71.625 96 160c0 24.75 5.625 48.219 15.672 +69.125C112.234 230.313 256 512 256 512l142.594-279.375 +C409.719 210.844 416 186.156 416 160C416 71.625 344.375 +0 256 0z M256 256c-53.016 0-96-43-96-96s42.984-96 96-96 +c53 0 96 43 96 96S309 256 256 256z'/> +</g>" bg p q)))) + (svg-text + (concat "<svg width='256' height='256' version='1.1' +xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink'> +<image xlink:href='" + (file-name-nondirectory file) + "' height='256' width='256'/>" + (when-let (track (cdr overlays)) + (format + "<path style='%s' d='%s'/>" + osm-track-style + (let (last) + (mapconcat + (pcase-lambda (`(,beg . ,end)) + (prog1 + (if (equal beg last) + (format "L%s %s" (- (car end) x0) (- (cdr end) y0)) + (format "M%s %sL%s %s" + (- (car beg) x0) (- (cdr beg) y0) + (- (car end) x0) (- (cdr end) y0))) + (setq last end))) + track "")))) + (pcase-exhaustive osm-tile-border + ('nil nil) + ('debug "<path d='M 1 1 L 1 255 255 255 255 1 Z' stroke='#000' stroke-width='2' fill='none'/>") + ('t "<path d='M 0 0 L 0 256 256 256' stroke='#000' fill='none'/>")) + (mapconcat svg-pin (car overlays) "") + (and tpin (funcall svg-pin tpin)) + "</svg>"))) + (list 'image :width 256 :height 256 :type 'svg :base-uri file :data svg-text :map areas)) + (list 'image :width 256 :height 256 :file file :type + (if (member (file-name-extension file) '("jpg" "jpeg")) + 'jpeg 'png)))))) + +(defun osm--get-tile (x y) + "Get tile at X/Y." + (pcase osm--pin + ((and `(,lat ,lon ,_id ,name) + (guard (osm--pin-inside-p x y lat lon))) + (osm--draw-tile x y (list (osm--lon-to-x lon osm--zoom) + (osm--lat-to-y lat osm--zoom) + lat lon 'osm-selected name))) + (_ + (let* ((key `(,osm-server ,osm--zoom ,x . ,y)) + (tile (and osm--tile-cache (gethash key osm--tile-cache)))) + (if tile + (progn (setcar tile osm--tile-age) (cdr tile)) + (setq tile (osm--draw-tile x y nil)) + (when tile + (when osm-max-tiles + (unless osm--tile-cache + (setq osm--tile-cache (make-hash-table :test #'equal :size osm-max-tiles))) + (puthash key (cons osm--tile-age tile) osm--tile-cache)) + tile)))))) + +(defun osm--display-tile (x y tile) + "Display TILE at X/Y." + (let ((i (- x (/ (osm--x0) 256))) + (j (- y (/ (osm--y0) 256)))) + (when (and (>= i 0) (< i osm--nx) (>= j 0) (< j osm--ny)) + (let* ((mx (if (= 0 i) (mod (osm--x0) 256) 0)) + (my (if (= 0 j) (mod (osm--y0) 256) 0)) + (pos (+ (point-min) (* j (1+ osm--nx)) i))) + (unless tile + (setq tile (cons 'image osm--placeholder))) + (with-silent-modifications + (put-text-property + pos (1+ pos) 'display + (if (or (/= 0 mx) (/= 0 my)) + `((slice ,mx ,my ,(- 256 mx) ,(- 256 my)) ,tile) + tile))))))) + +;;;###autoload +(defun osm-home () + "Go to home coordinates." + (interactive) + (pcase osm-home + (`(,lat ,lon ,zoom) + (osm--goto lat lon zoom nil 'osm-home "Home")))) + +(defun osm--download-queue-info () + "Return queue info string." + (when osm--download-processes + (format "[%s/%s/%s]" + (cl-loop for (_ . p) in osm--download-processes sum (length p)) + (length osm--download-active) + (length osm--download-queue)))) + +(defun osm--revert (&rest _) + "Revert osm buffers." + (clear-image-cache t) ;; Make absolutely sure that the tiles are redrawn. + (setq osm--tile-cache nil) + (osm--each + (setq osm--overlays nil) + (osm--update))) + +(defun osm--resize (&rest _) + "Resize buffer." + (when (eq major-mode #'osm-mode) + (osm--update))) + +(defun osm--header-button (text action) + "Format header line button with TEXT and ACTION." + (propertize text + 'keymap (define-keymap "<header-line> <mouse-1>" + (if (commandp action) + (lambda () + (interactive "@") + (call-interactively action)) + action)) + 'face '(:box (:line-width -2 :style released-button)) + 'mouse-face '(:box (:line-width -2 :style pressed-button)))) + +(defun osm--update-header () + "Update header line." + (let* ((meter-per-pixel (/ (* 156543.03 (cos (/ osm--lat (/ 180.0 float-pi)))) (expt 2 osm--zoom))) + (server (osm--server-property :name)) + (meter 1) (idx 0) + (factor '(2 2.5 2)) + (sep #(" " 0 1 (display (space :width (1)))))) + (while (and (< idx 20) (< (/ (* meter (nth (mod idx 3) factor)) meter-per-pixel) 150)) + (setq meter (round (* meter (nth (mod idx 3) factor)))) + (cl-incf idx)) + (setq-local + header-line-format + (list + (osm--header-button " ☰ " (osm--menu-item osm-mode-menu)) sep + (osm--header-button (format " %s " server) + (osm--menu-item #'osm--server-menu)) sep + (osm--header-button " + " #'osm-zoom-in) sep + (osm--header-button " - " #'osm-zoom-out) + (format " Z%-2d " osm--zoom) + #(" " 0 1 (display (space :align-to (- center 15)))) + (format #(" %7.2f° %7.2f°" 0 14 (face bold)) osm--lat osm--lon) + #(" " 0 1 (display (space :align-to (- right 20)))) + (format "%3s " (if (>= meter 1000) (/ meter 1000) meter)) + (if (>= meter 1000) "km " "m ") + #(" " 0 1 (face (:inverse-video t) display (space :width (3)))) + (propertize " " 'face '(:strike-through t) + 'display `(space :width (,(floor (/ meter meter-per-pixel))))) + #(" " 0 1 (face (:inverse-video t) display (space :width (3)))))))) + +(defun osm--update () + "Update map display." + (osm--barf-unless-osm) + (osm--purge-tile-cache) + (osm--purge-directory) + (osm--rename-buffer) + (osm--update-sizes) + (osm--update-header) + (osm--update-buffer) + (osm--update-copyright) + (osm--process-download-queue)) + +(defun osm--update-sizes () + "Update window sizes." + (let* ((windows (or (get-buffer-window-list) (list (frame-root-window)))) + (win-width (cl-loop for w in windows maximize (window-pixel-width w))) + (win-height (cl-loop for w in windows maximize (window-pixel-height w)))) + (setq osm--wx (/ win-width 2) + osm--wy (/ win-height 2) + osm--nx (1+ (ceiling win-width 256)) + osm--ny (1+ (ceiling win-height 256))))) + +(defun osm--copyright-link (text url) + "Format link with TEXT to URL." + (propertize text + 'face 'button + 'mouse-face 'highlight + 'help-echo + (format "Go to %s" url) + 'keymap + (define-keymap "<tab-line> <mouse-1>" + (lambda () + (interactive) + (browse-url url))))) + +(defun osm--update-copyright () + "Update copyright info." + (let ((copyright (and osm-copyright (osm--server-property :copyright)))) + (if (not copyright) + (when (eq 'osm-copyright (car-safe tab-line-format)) + (kill-local-variable 'tab-line-format)) + (setq copyright (replace-regexp-in-string + "{\\(.*?\\)|\\(.*?\\)}" + (lambda (str) + (osm--copyright-link + (match-string 1 str) + (match-string 2 str))) + (concat + " " + (string-join (ensure-list copyright) " | ") + #(" " 0 1 (display (space :align-to (+ 42 right))))))) + (add-face-text-property + 0 (length copyright) + '(:inherit (header-line variable-pitch) :height 0.65) + t copyright) + (setq-local tab-line-format (list 'osm-copyright copyright))))) + +(defun osm--update-buffer () + "Update buffer display." + (with-silent-modifications + (erase-buffer) + (dotimes (_j osm--ny) + (insert (make-string osm--nx ?\s) "\n")) + (put-text-property (point-min) (point-max) 'pointer 'arrow) + (goto-char (point-min)) + (let ((tx (/ (osm--x0) 256)) + (ty (/ (osm--y0) 256))) + (dotimes (j osm--ny) + (dotimes (i osm--nx) + (let* ((x (+ i tx)) + (y (+ j ty)) + (tile (osm--get-tile x y))) + (osm--display-tile x y tile) + (unless tile (osm--enqueue-download x y)))))))) + +(defun osm--process-download-queue () + "Process the download queue." + (setq osm--download-queue + (sort + (cl-loop with tx = (/ (osm--x0) 256) + with ty = (/ (osm--y0) 256) + for job in osm--download-queue + for (_server zoom x y) = job + if (and (= zoom osm--zoom) + (>= x tx) (< x (+ tx osm--nx)) + (>= y ty) (< y (+ ty osm--ny))) + collect job) + (let ((tx (/ (osm--x) 256)) + (ty (/ (osm--y) 256))) + (pcase-lambda (`(,_s1 ,_z1 ,x1 ,y1) `(,_s2 ,_z2 ,x2 ,y2)) + (setq x1 (- x1 tx) y1 (- y1 ty) x2 (- x2 tx) y2 (- y2 ty)) + (< (+ (* x1 x1) (* y1 y1)) (+ (* x2 x2) (* y2 y2))))))) + (osm--download)) + +(defun osm--purge-tile-cache () + "Purge old tiles from the tile cache." + (cl-incf osm--tile-age) + (when (and osm--tile-cache (> (hash-table-count osm--tile-cache) osm-max-tiles)) + (let (items) + (maphash (lambda (k v) (push (list (car v) (cdr v) k) items)) osm--tile-cache) + (setq items (sort items #'car-less-than-car)) + (cl-loop repeat (- (hash-table-count osm--tile-cache) osm-max-tiles) + for (_age tile key) in items do + (image-flush tile t) + (remhash key osm--tile-cache))))) + +(defun osm--bookmark-record-default () + "Make osm bookmark record." + (osm--bookmark-record (osm--bookmark-name osm--lat osm--lon nil) + osm--lat osm--lon nil)) + +(defun osm--bookmark-record (name lat lon loc) + "Make osm bookmark record with NAME and LOC description at LAT/LON." + (setq bookmark-current-bookmark nil) ;; Reset bookmark to use new name + `(,name + (location . ,(osm--location-name lat lon loc 6)) + (coordinates ,lat ,lon ,osm--zoom) + (server . ,osm-server) + (handler . ,#'osm-bookmark-jump))) + +(defun osm--org-link-props () + "Return Org link properties." + (pcase-let* ((`(,lat ,lon ,loc) (osm--fetch-location-data "New Org Link")) + (name (osm--location-name lat lon loc 2))) + (list :type "geo" + :description + (if (eq osm-server (default-value 'osm-server)) + (string-remove-suffix (concat " " (osm--server-property :name)) + name) + name) + :link + (format "geo:%.6f,%.6f;z=%s%s" + lat lon osm--zoom + (if (eq osm-server (default-value 'osm-server)) "" + (format ";s=%s" osm-server)))))) + +(defun osm--rename-buffer () + "Rename current buffer." + (setq list-buffers-directory (osm--location-name osm--lat osm--lon nil 6)) + (rename-buffer + (format "*osm: %s*" (osm--location-name osm--lat osm--lon nil 2)) + 'unique)) + +(defun osm--location-name (lat lon loc prec) + "Format location string LAT/LON with optional LOC description. +The coordinates are formatted with precision PREC." + (format (format "%%s%%.%df° %%.%df° Z%%s %%s" prec prec) + (if loc (concat loc ", ") "") + lat lon osm--zoom (osm--server-property :name))) + +(defun osm--bookmark-name (lat lon loc) + "Return bookmark name for LAT/LON/LOC." + (concat "osm: " (osm--location-name lat lon loc 2))) + +(defun osm--goto (lat lon zoom server id name) + "Go to LAT/LON/ZOOM, change SERVER. +Optionally place pin with ID and NAME." + ;; Server not found + (when (and server (not (assq server osm-server-list))) (setq server nil)) + (with-current-buffer + (or + (and (eq major-mode #'osm-mode) (current-buffer)) + (let ((def-server (or server osm-server)) + (def-lat (or lat (nth 0 osm-home))) + (def-lon (or lon (nth 1 osm-home))) + (def-zoom (or zoom (nth 2 osm-home)))) + ;; Search for existing buffer + (cl-loop + for buf in (buffer-list) thereis + (and (equal (buffer-local-value 'major-mode buf) #'osm-mode) + (equal (buffer-local-value 'osm-server buf) def-server) + (equal (buffer-local-value 'osm--zoom buf) def-zoom) + (equal (buffer-local-value 'osm--lat buf) def-lat) + (equal (buffer-local-value 'osm--lon buf) def-lon) + buf))) + (generate-new-buffer "*osm*")) + (unless (eq major-mode #'osm-mode) + (osm-mode)) + (when (and server (not (eq osm-server server))) + (setq-local osm-server server + osm--download-queue nil)) + (when (or (not (and osm--lon osm--lat)) lat) + (setq osm--lat (or lat (nth 0 osm-home)) + osm--lon (or lon (nth 1 osm-home)) + osm--zoom (or zoom (nth 2 osm-home))) + (when id + (osm--set-pin id osm--lat osm--lon name))) + (prog1 (pop-to-buffer (current-buffer)) + (osm--update)))) + +(defun osm--set-pin (id lat lon name &optional quiet) + "Set pin at LAT/LON with ID and NAME. +Print NAME if not QUIET." + (setq name (or name (format "Location %.6f° %.6f°" lat lon))) + (setq osm--pin (list lat lon (or id 'osm-selected) name)) + (unless quiet (message "%s" name))) + +(defun osm--set-pin-event (event &optional id name quiet) + "Set selection pin with ID and NAME at location of EVENT. +Print NAME if not QUIET." + (pcase-let ((`(,x . ,y) (posn-x-y (event-start event)))) + (osm--set-pin id + (osm--y-to-lat (+ (osm--y0) y) osm--zoom) + (osm--x-to-lon (+ (osm--x0) x) osm--zoom) + name quiet))) + +;;;###autoload +(defun osm-goto (lat lon zoom) + "Go to LAT/LON/ZOOM." + (interactive + (pcase-let ((`(,lat ,lon ,zoom) + (mapcar #'string-to-number + (split-string (read-string "Lat Lon (Zoom): ") nil t)))) + (setq zoom (or zoom osm--zoom 11)) + (unless (and (numberp lat) (numberp lon) (numberp zoom)) + (error "Invalid coordinate")) + (list lat lon zoom))) + (osm--goto lat lon zoom nil 'osm-selected nil) + nil) + +;;;###autoload +(defun osm (&rest link) + "Go to LINK. +When called interactively, call the function `osm-home'." + (interactive (list 'home)) + (pcase link + ('(home) + (osm-home)) + (`(,lat ,lon ,zoom . ,server) + (setq server (car server)) + (unless (and server (symbolp server)) (setq server nil)) ;; Ignore comment + (osm--goto lat lon zoom server 'osm-selected "Elisp Link")) + ((and `(,url . ,_) (guard (stringp url))) + (if (string-match + "\\`geo:\\([0-9.-]+\\),\\([0-9.-]+\\)\\(?:,[0-9.-]+\\)?\\(;.+\\'\\|\\'\\)" url) + (let* ((lat (string-to-number (match-string 1 url))) + (lon (string-to-number (match-string 2 url))) + (args (url-parse-args (match-string 3 url) "")) + (zoom (cdr (assoc "z" args))) + (server (cdr (assoc "s" args)))) + (osm--goto lat lon + (and zoom (string-to-number zoom)) + (and server (intern-soft server)) + 'osm-selected "Geo Link")) + (osm-search (string-remove-prefix "geo:" url)))) + (_ (error "Invalid osm link")))) + +;;;###autoload +(defun osm-bookmark-jump (bm) + "Jump to osm bookmark BM." + (interactive (list (osm--bookmark-read))) + (pcase-let ((`(,lat ,lon ,zoom) (bookmark-prop-get bm 'coordinates))) + (set-buffer (osm--goto lat lon zoom + (bookmark-prop-get bm 'server) + 'osm-bookmark (car bm))))) +(put 'osm-bookmark-jump 'bookmark-handler-type "Osm") + +;;;###autoload +(defun osm-bookmark-delete (bm) + "Delete osm bookmark BM." + (interactive (list (osm--bookmark-read))) + (when (y-or-n-p (format "Delete bookmark `%s'? " bm)) + (bookmark-delete bm) + (setq osm--pin nil) + (osm--revert))) + +;;;###autoload +(defun osm-bookmark-rename (old-name) + "Rename osm bookmark OLD-NAME." + (interactive (list (car (osm--bookmark-read)))) + (let ((new-name (read-from-minibuffer "New name: " old-name nil nil + 'bookmark-history old-name))) + (when osm--pin (setf (cadddr osm--pin) new-name)) + (bookmark-rename old-name new-name) + (osm--revert))) + +(defun osm--bookmark-read () + "Read bookmark name." + (bookmark-maybe-load-default-file) + (or (assoc + (pcase osm--pin + (`(,_lat ,_lon osm-bookmark ,name) name) + (_ (completing-read + "Bookmark: " + (or (cl-loop for bm in bookmark-alist + if (eq (bookmark-prop-get bm 'handler) #'osm-bookmark-jump) + collect (car bm)) + (error "No bookmarks found")) + nil t nil 'bookmark-history))) + bookmark-alist) + (error "No bookmark selected"))) + +(defun osm-bookmark-set () + "Create osm bookmark." + (interactive nil osm-mode) + (osm--barf-unless-osm) + (unwind-protect + (pcase-let* ((`(,lat ,lon ,loc) (osm--fetch-location-data "New Bookmark")) + (def (osm--bookmark-name lat lon loc)) + (name (read-from-minibuffer "Bookmark name: " def nil nil 'bookmark-history def)) + (bookmark-make-record-function + (lambda () (osm--bookmark-record name lat lon loc)))) + (bookmark-set name) + (message "Stored bookmark: %s" name) + (setf (caddr osm--pin) 'osm-bookmark)) + (osm--revert))) + +(defun osm--fetch-location-data (name) + "Fetch location info for NAME." + (when (mouse-event-p last-input-event) + (osm--set-pin-event last-input-event 'osm-selected name)) + (let ((lat (or (car osm--pin) osm--lat)) + (lon (or (cadr osm--pin) osm--lon))) + (osm--set-pin 'osm-selected lat lon name 'quiet) + (message "%s: Fetching name of %.2f° %.2f° from %s..." name lat lon osm-search-server) + ;; Redisplay before slow fetching + (osm--update) + (redisplay) + (list lat lon + (ignore-errors + (alist-get + 'display_name + (osm--fetch-json + (format "%s/reverse?format=json&accept-language=%s&zoom=%s&lat=%s&lon=%s" + osm-search-server osm-search-language + (min 18 (max 3 osm--zoom)) lat lon))))))) + +(defun osm--track-index () + "Return index of selected track way point." + (cl-loop for idx from 0 for (lat lon _) in osm--track + if (and (equal lat (car osm--pin)) (equal lon (cadr osm--pin))) + return idx)) + +(defun osm--track-delete () + "Delete track way point." + (when-let ((idx (osm--track-index))) + ;; Delete pin + (cl-callf2 delq (nth idx osm--track) osm--track) + (setq osm--pin nil + idx (min idx (1- (length osm--track)))) + ;; Select next pin + (pcase (nth idx osm--track) + (`(,lat ,lon ,name) + (osm--set-pin 'osm-track lat lon name 'quiet))) + ;; Rename pins after deletion + (cl-loop for idx from (length osm--track) downto 1 + for pt in osm--track + if (string-match-p "\\`WP[0-9]+\\'" (caddr pt)) do + (setf (caddr pt) (format "WP%s" idx))) + (osm--track-length) + (osm--revert))) + +(defun osm--track-rename () + "Rename track way point." + (when-let ((pt (nth (osm--track-index) osm--track)) + (old-name (caddr pt)) + (new-name (read-from-minibuffer "New name: " old-name nil nil nil old-name))) + (setf (caddr pt) new-name + (cadddr osm--pin) new-name) + (osm--revert))) + +(defun osm-delete () + "Delete selected pin (bookmark or way point)." + (interactive nil osm-mode) + (osm--barf-unless-osm) + (pcase (caddr osm--pin) + ('nil nil) + ('osm-bookmark (osm-bookmark-delete (cadddr osm--pin))) + ('osm-track (osm--track-delete)) + (_ (setq osm--pin nil) (osm--update)))) + +(defun osm-rename () + "Rename selected pin (bookmark or way point)." + (interactive nil osm-mode) + (osm--barf-unless-osm) + (pcase (caddr osm--pin) + ('osm-bookmark (osm-bookmark-rename (cadddr osm--pin))) + ('osm-track (osm--track-rename)))) + +;;;###autoload +(defun osm-jump () + "Jump to named pin." + (interactive) + (let (pins) + (osm--each-pin (lambda (id lat lon zoom name) + (push (list name (capitalize (substring (symbol-name id) 4)) + id lat lon zoom) + pins))) + (pcase (assoc (completing-read + "Jump: " + (lambda (str pred action) + (if (eq action 'metadata) + `(metadata + (group-function + . ,(lambda (pin transform) + (if transform pin + (cadr (assoc pin pins)))))) + (complete-with-action action pins str pred))) + nil t nil 'osm--jump-history) + pins) + (`(,name ,_group ,id ,lat ,lon ,zoom) (osm--goto lat lon zoom nil id name)) + (_ (user-error "No pin selected"))))) + +(defun osm--fetch-json (url) + "Get json from URL." + (osm--check-libraries) + (with-temp-buffer + (let* ((default-process-coding-system '(utf-8-unix . utf-8-unix)) + (status (apply #'call-process "curl" nil (current-buffer) nil + `(,@(split-string-and-unquote osm-curl-options) ,url)))) + (unless (eq status 0) + (error "Fetching %s exited with status %s" url status))) + (goto-char (point-min)) + (json-parse-buffer :array-type 'list :object-type 'alist))) + +(defun osm--search (needle) + "Globally search for NEEDLE and return the list of results." + (message "Contacting %s" osm-search-server) + (mapcar + (lambda (x) + (let ((lat (string-to-number (alist-get 'lat x))) + (lon (string-to-number (alist-get 'lon x)))) + `(,(format "%s (%.6f° %.6f°)" + (alist-get 'display_name x) + lat lon) + ,lat ,lon + ,@(mapcar #'string-to-number (alist-get 'boundingbox x))))) + (osm--fetch-json + (format "%s/search?format=json&accept-language=%s&q=%s" + osm-search-server osm-search-language + (url-encode-url needle))))) + +;;;###autoload +(defun osm-search (needle &optional lucky) + "Globally search for NEEDLE on `osm-search-server' and display the map. +If the prefix argument LUCKY is non-nil take the first result and jump there. +See `osm-search-server' and `osm-search-language' for customization." + (interactive + (list + (minibuffer-with-setup-hook + (lambda () + (when (and (eq completing-read-function #'completing-read-default) + (not (bound-and-true-p vertico-mode))) + ;; Override dreaded `minibuffer-complete-word' for default + ;; completion. When will this keybinding finally get removed from + ;; default completion? + (use-local-map (make-composed-keymap + (define-keymap "SPC" nil) + (current-local-map))))) + (completing-read "Location: " + (osm--sorted-table osm--search-history) + nil nil nil 'osm--search-history)) + current-prefix-arg)) + ;; TODO: Add search bounded to current viewbox, bounded=1, viewbox=x1,y1,x2,y2 + (let* ((results (or (osm--search needle) (error "No results for `%s'" needle))) + (selected + (or + (and (or lucky (not (cdr results))) (car results)) + (assoc + (minibuffer-with-setup-hook + (lambda () + (when (and (eq completing-read-function #'completing-read-default) + (not (bound-and-true-p vertico-mode)) + (not (bound-and-true-p icomplete-mode))) + (let ((message-log-max nil) + (inhibit-message t)) + ;; Show matches immediately for default completion. + (minibuffer-completion-help)))) + (completing-read + (format "Matches for '%s': " needle) + (osm--sorted-table results) + nil t nil t)) + results) + (error "No selection")))) + (osm--goto (cadr selected) (caddr selected) + (apply #'osm--boundingbox-to-zoom (cdddr selected)) + nil 'osm-selected (car selected)))) + +(defun osm--sorted-table (coll) + "Sorted completion table from COLL." + (lambda (str pred action) + (if (eq action 'metadata) + '(metadata (display-sort-function . identity) + (cycle-sort-function . identity)) + (complete-with-action action coll str pred)))) + +;;;###autoload +(defun osm-gpx-show (file) + "Show the tracks of gpx FILE in an `osm-mode' buffer." + (interactive "fGPX file: ") + (osm--check-libraries) + (let ((dom (with-temp-buffer + (insert-file-contents file) + (libxml-parse-xml-region (point-min) (point-max)))) + (min-lat 90) (max-lat -90) (min-lon 180) (max-lon -180)) + (setf (alist-get (abbreviate-file-name file) osm--gpx-files nil nil #'equal) + (cons + (cl-loop + for trk in (dom-children dom) + if (eq (dom-tag trk) 'trk) nconc + (cl-loop + for seg in (dom-children trk) + if (eq (dom-tag seg) 'trkseg) collect + (cl-loop + for pt in (dom-children seg) + if (eq (dom-tag pt) 'trkpt) collect + (let ((lat (string-to-number (dom-attr pt 'lat))) + (lon (string-to-number (dom-attr pt 'lon)))) + (setq min-lat (min lat min-lat) + max-lat (max lat max-lat) + min-lon (min lon min-lon) + max-lon (max lon max-lon)) + (cons lat lon))))) + (cl-loop + for pt in (dom-children dom) + if (eq (dom-tag pt) 'wpt) collect + (let ((lat (string-to-number (dom-attr pt 'lat))) + (lon (string-to-number (dom-attr pt 'lon)))) + (setq min-lat (min lat min-lat) + max-lat (max lat max-lat) + min-lon (min lon min-lon) + max-lon (max lon max-lon)) + (list lat lon (dom-text (dom-child-by-tag pt 'name))))))) + (osm--revert) + (osm--goto (/ (+ min-lat max-lat) 2) (/ (+ min-lon max-lon) 2) + (osm--boundingbox-to-zoom min-lat max-lat min-lon max-lon) + nil nil nil))) + +(defun osm-gpx-hide (file) + "Show the tracks of gpx FILE in an `osm-mode' buffer." + (interactive (list (completing-read "GPX file: " + (or osm--gpx-files + (error "No GPX files shown")) + nil t nil 'file-name-history))) + (cl-callf2 assoc-delete-all file osm--gpx-files) + (osm--revert)) + +(defun osm--server-annotation (cand) + "Annotation for server CAND." + (when-let ((copyright (osm--server-property :copyright (get-text-property 0 'osm--server cand))) + (str + (replace-regexp-in-string + "{\\(.*?\\)|.*?}" + (lambda (str) (match-string 1 str)) + (string-join (ensure-list copyright) " | ") copyright))) + (concat (propertize " " 'display `(space :align-to (- right ,(length str) 2))) + " " + str))) + +(defun osm--server-group (cand transform) + "Group function for server CAND with candidate TRANSFORM." + (if transform + cand + (osm--server-property :group (get-text-property 0 'osm--server cand)))) + +;;;###autoload +(defun osm-server (server) + "Select tile SERVER." + (interactive + (let* ((max-name (cl-loop for (_ . x) in osm-server-list + maximize (length (plist-get x :name)))) + (fmt (concat + (propertize (format "%%-%ds " max-name) + 'face 'font-lock-comment-face) + " %s")) + (servers + (mapcar + (lambda (x) + (propertize + (format fmt + (plist-get (cdr x) :name) + (or (plist-get (cdr x) :description) "")) + 'osm--server (car x))) + osm-server-list)) + (selected (completing-read + "Server: " + (lambda (str pred action) + (if (eq action 'metadata) + `(metadata + (annotation-function + . ,(and osm-copyright #'osm--server-annotation)) + (group-function . ,#'osm--server-group)) + (complete-with-action action servers str pred))) + nil t nil 'osm--server-history + (format fmt + (osm--server-property :name) + (or (osm--server-property :description) ""))))) + (list + (get-text-property 0 'osm--server + (or (car (member selected servers)) + (error "No server selected")))))) + (osm--goto nil nil nil server nil nil)) + +(defun osm-save-url (&optional arg) + "Save coordinates as url in the kill ring. +If prefix ARG is given, store url as Elisp expression." + (interactive "P" osm-mode) + (osm--barf-unless-osm) + (pcase-let* ((`(,lat ,lon ,loc) (osm--fetch-location-data "New Link")) + (server (and (not (eq osm-server (default-value 'osm-server))) osm-server)) + (url (if arg + (format "(osm %.6f %.6f %s%s%s)" + lat lon osm--zoom + (if server (format " '%s" osm-server) "") + (if loc (format " %S" loc) "")) + (format "geo:%.6f,%.6f;z=%s%s%s" + lat lon osm--zoom + (if server (format ";s=%s" osm-server) "") + (if loc (format " (%s)" loc) ""))))) + (kill-new url) + (message "Saved in the kill ring: %s" url))) + +(cl-defun osm-add-server (server + &rest properties + &key name description group url max-connections + max-zoom min-zoom download-batch subdomains copyright) + "Add SERVER with PROPERTIES to `osm-server-list'. +The properties are checked as keyword arguments. See +`osm-server-list' for documentation of the keywords." + (declare (indent 1)) + (ignore name description group url max-connections max-zoom + min-zoom download-batch subdomains copyright) + (dolist (sym '(:name :description :group :url)) + (unless (stringp (plist-get properties sym)) + (error "Server property %s is required" sym))) + (unless (and server (symbolp server)) + (error "Server id must be a symbol")) + (setf (alist-get server osm-server-list) properties) + nil) + +;;;###autoload +(add-to-list 'browse-url-default-handlers '("\\`geo:" . osm)) + +;;;###autoload +(eval-after-load 'ol + (lambda () + (declare-function org-link-set-parameters "ol") + (declare-function osm--org-link-props "ext:osm") + (org-link-set-parameters + "geo" + :follow (lambda (link _) (osm (concat "geo:" link))) + :store (lambda () + (when (eq major-mode 'osm-mode) + (apply 'org-link-store-props (osm--org-link-props))))))) + +(provide 'osm) +;;; osm.el ends here diff --git a/emacs/elpa/osm-20241006.13/osm.elc b/emacs/elpa/osm-20241006.13/osm.elc Binary files differ. diff --git a/emacs/elpa/transient-20241004.1739/dir b/emacs/elpa/transient-20241004.1739/dir @@ -0,0 +1,18 @@ +This is the file .../info/dir, which contains the +topmost node of the Info hierarchy, called (dir)Top. +The first time you invoke Info you start off looking at this node. + +File: dir, Node: Top This is the top of the INFO tree + + This (the Directory node) gives a menu of major topics. + Typing "q" exits, "H" lists all Info commands, "d" returns here, + "h" gives a primer for first-timers, + "mEmacs<Return>" visits the Emacs manual, etc. + + In Emacs, you can click mouse button 2 on a menu item or cross reference + to select it. + +* Menu: + +Emacs misc features +* Transient: (transient). Transient Commands. diff --git a/emacs/elpa/transient-20241004.1739/gpl.info b/emacs/elpa/transient-20241004.1739/gpl.info @@ -0,0 +1,721 @@ +This is gpl.info, produced by makeinfo version 6.8 from gpl.texi. + + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> + + Everyone is permitted to copy and distribute verbatim copies of this + license document, but changing it is not allowed. + +Preamble +======== + +The GNU General Public License is a free, copyleft license for software +and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + +TERMS AND CONDITIONS +==================== + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public + License. + + "Copyright" also means copyright-like laws that apply to other + kinds of works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this + License. Each licensee is addressed as "you". "Licensees" and + "recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the + work in a fashion requiring copyright permission, other than the + making of an exact copy. The resulting work is called a "modified + version" of the earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work + based on the Program. + + To "propagate" a work means to do anything with it that, without + permission, would make you directly or secondarily liable for + infringement under applicable copyright law, except executing it on + a computer or modifying a private copy. Propagation includes + copying, distribution (with or without modification), making + available to the public, and in some countries other activities as + well. + + To "convey" a work means any kind of propagation that enables other + parties to make or receive copies. Mere interaction with a user + through a computer network, with no transfer of a copy, is not + conveying. + + An interactive user interface displays "Appropriate Legal Notices" + to the extent that it includes a convenient and prominently visible + feature that (1) displays an appropriate copyright notice, and (2) + tells the user that there is no warranty for the work (except to + the extent that warranties are provided), that licensees may convey + the work under this License, and how to view a copy of this + License. If the interface presents a list of user commands or + options, such as a menu, a prominent item in the list meets this + criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work + for making modifications to it. "Object code" means any non-source + form of a work. + + A "Standard Interface" means an interface that either is an + official standard defined by a recognized standards body, or, in + the case of interfaces specified for a particular programming + language, one that is widely used among developers working in that + language. + + The "System Libraries" of an executable work include anything, + other than the work as a whole, that (a) is included in the normal + form of packaging a Major Component, but which is not part of that + Major Component, and (b) serves only to enable use of the work with + that Major Component, or to implement a Standard Interface for + which an implementation is available to the public in source code + form. A "Major Component", in this context, means a major + essential component (kernel, window system, and so on) of the + specific operating system (if any) on which the executable work + runs, or a compiler used to produce the work, or an object code + interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all + the source code needed to generate, install, and (for an executable + work) run the object code and to modify the work, including scripts + to control those activities. However, it does not include the + work's System Libraries, or general-purpose tools or generally + available free programs which are used unmodified in performing + those activities but which are not part of the work. For example, + Corresponding Source includes interface definition files associated + with source files for the work, and the source code for shared + libraries and dynamically linked subprograms that the work is + specifically designed to require, such as by intimate data + communication or control flow between those subprograms and other + parts of the work. + + The Corresponding Source need not include anything that users can + regenerate automatically from other parts of the Corresponding + Source. + + The Corresponding Source for a work in source code form is that + same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of + copyright on the Program, and are irrevocable provided the stated + conditions are met. This License explicitly affirms your unlimited + permission to run the unmodified Program. The output from running + a covered work is covered by this License only if the output, given + its content, constitutes a covered work. This License acknowledges + your rights of fair use or other equivalent, as provided by + copyright law. + + You may make, run and propagate covered works that you do not + convey, without conditions so long as your license otherwise + remains in force. You may convey covered works to others for the + sole purpose of having them make modifications exclusively for you, + or provide you with facilities for running those works, provided + that you comply with the terms of this License in conveying all + material for which you do not control copyright. Those thus making + or running the covered works for you must do so exclusively on your + behalf, under your direction and control, on terms that prohibit + them from making any copies of your copyrighted material outside + their relationship with you. + + Conveying under any other circumstances is permitted solely under + the conditions stated below. Sublicensing is not allowed; section + 10 makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological + measure under any applicable law fulfilling obligations under + article 11 of the WIPO copyright treaty adopted on 20 December + 1996, or similar laws prohibiting or restricting circumvention of + such measures. + + When you convey a covered work, you waive any legal power to forbid + circumvention of technological measures to the extent such + circumvention is effected by exercising rights under this License + with respect to the covered work, and you disclaim any intention to + limit operation or modification of the work as a means of + enforcing, against the work's users, your or third parties' legal + rights to forbid circumvention of technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you + receive it, in any medium, provided that you conspicuously and + appropriately publish on each copy an appropriate copyright notice; + keep intact all notices stating that this License and any + non-permissive terms added in accord with section 7 apply to the + code; keep intact all notices of the absence of any warranty; and + give all recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, + and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to + produce it from the Program, in the form of source code under the + terms of section 4, provided that you also meet all of these + conditions: + + a. The work must carry prominent notices stating that you + modified it, and giving a relevant date. + + b. The work must carry prominent notices stating that it is + released under this License and any conditions added under + section 7. This requirement modifies the requirement in + section 4 to "keep intact all notices". + + c. You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable + section 7 additional terms, to the whole of the work, and all + its parts, regardless of how they are packaged. This License + gives no permission to license the work in any other way, but + it does not invalidate such permission if you have separately + received it. + + d. If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has + interactive interfaces that do not display Appropriate Legal + Notices, your work need not make them do so. + + A compilation of a covered work with other separate and independent + works, which are not by their nature extensions of the covered + work, and which are not combined with it such as to form a larger + program, in or on a volume of a storage or distribution medium, is + called an "aggregate" if the compilation and its resulting + copyright are not used to limit the access or legal rights of the + compilation's users beyond what the individual works permit. + Inclusion of a covered work in an aggregate does not cause this + License to apply to the other parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms + of sections 4 and 5, provided that you also convey the + machine-readable Corresponding Source under the terms of this + License, in one of these ways: + + a. Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b. Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that + product model, to give anyone who possesses the object code + either (1) a copy of the Corresponding Source for all the + software in the product that is covered by this License, on a + durable physical medium customarily used for software + interchange, for a price no more than your reasonable cost of + physically performing this conveying of source, or (2) access + to copy the Corresponding Source from a network server at no + charge. + + c. Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, + and only if you received the object code with such an offer, + in accord with subsection 6b. + + d. Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to + the Corresponding Source in the same way through the same + place at no further charge. You need not require recipients + to copy the Corresponding Source along with the object code. + If the place to copy the object code is a network server, the + Corresponding Source may be on a different server (operated by + you or a third party) that supports equivalent copying + facilities, provided you maintain clear directions next to the + object code saying where to find the Corresponding Source. + Regardless of what server hosts the Corresponding Source, you + remain obligated to ensure that it is available for as long as + needed to satisfy these requirements. + + e. Convey the object code using peer-to-peer transmission, + provided you inform other peers where the object code and + Corresponding Source of the work are being offered to the + general public at no charge under subsection 6d. + + A separable portion of the object code, whose source code is + excluded from the Corresponding Source as a System Library, need + not be included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means + any tangible personal property which is normally used for personal, + family, or household purposes, or (2) anything designed or sold for + incorporation into a dwelling. In determining whether a product is + a consumer product, doubtful cases shall be resolved in favor of + coverage. For a particular product received by a particular user, + "normally used" refers to a typical or common use of that class of + product, regardless of the status of the particular user or of the + way in which the particular user actually uses, or expects or is + expected to use, the product. A product is a consumer product + regardless of whether the product has substantial commercial, + industrial or non-consumer uses, unless such uses represent the + only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, + procedures, authorization keys, or other information required to + install and execute modified versions of a covered work in that + User Product from a modified version of its Corresponding Source. + The information must suffice to ensure that the continued + functioning of the modified object code is in no case prevented or + interfered with solely because modification has been made. + + If you convey an object code work under this section in, or with, + or specifically for use in, a User Product, and the conveying + occurs as part of a transaction in which the right of possession + and use of the User Product is transferred to the recipient in + perpetuity or for a fixed term (regardless of how the transaction + is characterized), the Corresponding Source conveyed under this + section must be accompanied by the Installation Information. But + this requirement does not apply if neither you nor any third party + retains the ability to install modified object code on the User + Product (for example, the work has been installed in ROM). + + The requirement to provide Installation Information does not + include a requirement to continue to provide support service, + warranty, or updates for a work that has been modified or installed + by the recipient, or for the User Product in which it has been + modified or installed. Access to a network may be denied when the + modification itself materially and adversely affects the operation + of the network or violates the rules and protocols for + communication across the network. + + Corresponding Source conveyed, and Installation Information + provided, in accord with this section must be in a format that is + publicly documented (and with an implementation available to the + public in source code form), and must require no special password + or key for unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of + this License by making exceptions from one or more of its + conditions. Additional permissions that are applicable to the + entire Program shall be treated as though they were included in + this License, to the extent that they are valid under applicable + law. If additional permissions apply only to part of the Program, + that part may be used separately under those permissions, but the + entire Program remains governed by this License without regard to + the additional permissions. + + When you convey a copy of a covered work, you may at your option + remove any additional permissions from that copy, or from any part + of it. (Additional permissions may be written to require their own + removal in certain cases when you modify the work.) You may place + additional permissions on material, added by you to a covered work, + for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material + you add to a covered work, you may (if authorized by the copyright + holders of that material) supplement the terms of this License with + terms: + + a. Disclaiming warranty or limiting liability differently from + the terms of sections 15 and 16 of this License; or + + b. Requiring preservation of specified reasonable legal notices + or author attributions in that material or in the Appropriate + Legal Notices displayed by works containing it; or + + c. Prohibiting misrepresentation of the origin of that material, + or requiring that modified versions of such material be marked + in reasonable ways as different from the original version; or + + d. Limiting the use for publicity purposes of names of licensors + or authors of the material; or + + e. Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f. Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified + versions of it) with contractual assumptions of liability to + the recipient, for any liability that these contractual + assumptions directly impose on those licensors and authors. + + All other non-permissive additional terms are considered "further + restrictions" within the meaning of section 10. If the Program as + you received it, or any part of it, contains a notice stating that + it is governed by this License along with a term that is a further + restriction, you may remove that term. If a license document + contains a further restriction but permits relicensing or conveying + under this License, you may add to a covered work material governed + by the terms of that license document, provided that the further + restriction does not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you + must place, in the relevant source files, a statement of the + additional terms that apply to those files, or a notice indicating + where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in + the form of a separately written license, or stated as exceptions; + the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly + provided under this License. Any attempt otherwise to propagate or + modify it is void, and will automatically terminate your rights + under this License (including any patent licenses granted under the + third paragraph of section 11). + + However, if you cease all violation of this License, then your + license from a particular copyright holder is reinstated (a) + provisionally, unless and until the copyright holder explicitly and + finally terminates your license, and (b) permanently, if the + copyright holder fails to notify you of the violation by some + reasonable means prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is + reinstated permanently if the copyright holder notifies you of the + violation by some reasonable means, this is the first time you have + received notice of violation of this License (for any work) from + that copyright holder, and you cure the violation prior to 30 days + after your receipt of the notice. + + Termination of your rights under this section does not terminate + the licenses of parties who have received copies or rights from you + under this License. If your rights have been terminated and not + permanently reinstated, you do not qualify to receive new licenses + for the same material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or + run a copy of the Program. Ancillary propagation of a covered work + occurring solely as a consequence of using peer-to-peer + transmission to receive a copy likewise does not require + acceptance. However, nothing other than this License grants you + permission to propagate or modify any covered work. These actions + infringe copyright if you do not accept this License. Therefore, + by modifying or propagating a covered work, you indicate your + acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically + receives a license from the original licensors, to run, modify and + propagate that work, subject to this License. You are not + responsible for enforcing compliance by third parties with this + License. + + An "entity transaction" is a transaction transferring control of an + organization, or substantially all assets of one, or subdividing an + organization, or merging organizations. If propagation of a + covered work results from an entity transaction, each party to that + transaction who receives a copy of the work also receives whatever + licenses to the work the party's predecessor in interest had or + could give under the previous paragraph, plus a right to possession + of the Corresponding Source of the work from the predecessor in + interest, if the predecessor has it or can get it with reasonable + efforts. + + You may not impose any further restrictions on the exercise of the + rights granted or affirmed under this License. For example, you + may not impose a license fee, royalty, or other charge for exercise + of rights granted under this License, and you may not initiate + litigation (including a cross-claim or counterclaim in a lawsuit) + alleging that any patent claim is infringed by making, using, + selling, offering for sale, or importing the Program or any portion + of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this + License of the Program or a work on which the Program is based. + The work thus licensed is called the contributor's "contributor + version". + + A contributor's "essential patent claims" are all patent claims + owned or controlled by the contributor, whether already acquired or + hereafter acquired, that would be infringed by some manner, + permitted by this License, of making, using, or selling its + contributor version, but do not include claims that would be + infringed only as a consequence of further modification of the + contributor version. For purposes of this definition, "control" + includes the right to grant patent sublicenses in a manner + consistent with the requirements of this License. + + Each contributor grants you a non-exclusive, worldwide, + royalty-free patent license under the contributor's essential + patent claims, to make, use, sell, offer for sale, import and + otherwise run, modify and propagate the contents of its contributor + version. + + In the following three paragraphs, a "patent license" is any + express agreement or commitment, however denominated, not to + enforce a patent (such as an express permission to practice a + patent or covenant not to sue for patent infringement). To "grant" + such a patent license to a party means to make such an agreement or + commitment not to enforce a patent against the party. + + If you convey a covered work, knowingly relying on a patent + license, and the Corresponding Source of the work is not available + for anyone to copy, free of charge and under the terms of this + License, through a publicly available network server or other + readily accessible means, then you must either (1) cause the + Corresponding Source to be so available, or (2) arrange to deprive + yourself of the benefit of the patent license for this particular + work, or (3) arrange, in a manner consistent with the requirements + of this License, to extend the patent license to downstream + recipients. "Knowingly relying" means you have actual knowledge + that, but for the patent license, your conveying the covered work + in a country, or your recipient's use of the covered work in a + country, would infringe one or more identifiable patents in that + country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or + arrangement, you convey, or propagate by procuring conveyance of, a + covered work, and grant a patent license to some of the parties + receiving the covered work authorizing them to use, propagate, + modify or convey a specific copy of the covered work, then the + patent license you grant is automatically extended to all + recipients of the covered work and works based on it. + + A patent license is "discriminatory" if it does not include within + the scope of its coverage, prohibits the exercise of, or is + conditioned on the non-exercise of one or more of the rights that + are specifically granted under this License. You may not convey a + covered work if you are a party to an arrangement with a third + party that is in the business of distributing software, under which + you make payment to the third party based on the extent of your + activity of conveying the work, and under which the third party + grants, to any of the parties who would receive the covered work + from you, a discriminatory patent license (a) in connection with + copies of the covered work conveyed by you (or copies made from + those copies), or (b) primarily for and in connection with specific + products or compilations that contain the covered work, unless you + entered into that arrangement, or that patent license was granted, + prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting + any implied license or other defenses to infringement that may + otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement + or otherwise) that contradict the conditions of this License, they + do not excuse you from the conditions of this License. If you + cannot convey a covered work so as to satisfy simultaneously your + obligations under this License and any other pertinent obligations, + then as a consequence you may not convey it at all. For example, + if you agree to terms that obligate you to collect a royalty for + further conveying from those to whom you convey the Program, the + only way you could satisfy both those terms and this License would + be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have + permission to link or combine any covered work with a work licensed + under version 3 of the GNU Affero General Public License into a + single combined work, and to convey the resulting work. The terms + of this License will continue to apply to the part which is the + covered work, but the special requirements of the GNU Affero + General Public License, section 13, concerning interaction through + a network will apply to the combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new + versions of the GNU General Public License from time to time. Such + new versions will be similar in spirit to the present version, but + may differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the + Program specifies that a certain numbered version of the GNU + General Public License "or any later version" applies to it, you + have the option of following the terms and conditions either of + that numbered version or of any later version published by the Free + Software Foundation. If the Program does not specify a version + number of the GNU General Public License, you may choose any + version ever published by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future + versions of the GNU General Public License can be used, that + proxy's public statement of acceptance of a version permanently + authorizes you to choose that version for the Program. + + Later license versions may give you additional or different + permissions. However, no additional obligations are imposed on any + author or copyright holder as a result of your choosing to follow a + later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY + APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE + COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" + WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE + RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. + SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL + NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN + WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES + AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR + DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR + CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE + THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA + BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD + PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER + PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF + THE POSSIBILITY OF SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided + above cannot be given local legal effect according to their terms, + reviewing courts shall apply local law that most closely + approximates an absolute waiver of all civil liability in + connection with the Program, unless a warranty or assumption of + liability accompanies a copy of the Program in return for a fee. + +END OF TERMS AND CONDITIONS +=========================== + +How to Apply These Terms to Your New Programs +============================================= + +If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these +terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + ONE LINE TO GIVE THE PROGRAM'S NAME AND A BRIEF IDEA OF WHAT IT DOES. + Copyright (C) YEAR NAME OF AUTHOR + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or (at + your option) any later version. + + This program is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. + + Also add information on how to contact you by electronic and paper +mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + PROGRAM Copyright (C) YEAR NAME OF AUTHOR + This program comes with ABSOLUTELY NO WARRANTY; for details type 'show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type 'show c' for details. + + The hypothetical commands 'show w' and 'show c' should show the +appropriate parts of the General Public License. Of course, your +program's commands might be different; for a GUI interface, you would +use an "about box". + + You should also get your employer (if you work as a programmer) or +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. For more information on this, and how to apply and follow +the GNU GPL, see <https://www.gnu.org/licenses/>. + + The GNU General Public License does not permit incorporating your +program into proprietary programs. If your program is a subroutine +library, you may consider it more useful to permit linking proprietary +applications with the library. If this is what you want to do, use the +GNU Lesser General Public License instead of this License. But first, +please read <https://www.gnu.org/licenses/why-not-lgpl.html>. + + +Tag Table: + +End Tag Table + + +Local Variables: +coding: utf-8 +End: diff --git a/emacs/elpa/transient-20241004.1739/transient-autoloads.el b/emacs/elpa/transient-20241004.1739/transient-autoloads.el @@ -0,0 +1,78 @@ +;;; transient-autoloads.el --- automatically extracted autoloads (do not edit) -*- lexical-binding: t -*- +;; Generated by the `loaddefs-generate' function. + +;; This file is part of GNU Emacs. + +;;; Code: + +(add-to-list 'load-path (or (and load-file-name (directory-file-name (file-name-directory load-file-name))) (car load-path))) + + + +;;; Generated autoloads from transient.el + +(autoload 'transient-insert-suffix "transient" "\ +Insert a SUFFIX into PREFIX before LOC. +PREFIX is a prefix command, a symbol. +SUFFIX is a suffix command or a group specification (of + the same forms as expected by `transient-define-prefix'). +LOC is a command, a key vector, a key description (a string + as returned by `key-description'), or a coordination list + (whose last element may also be a command or key). +Remove a conflicting binding unless optional KEEP-OTHER is + non-nil. +See info node `(transient)Modifying Existing Transients'. + +(fn PREFIX LOC SUFFIX &optional KEEP-OTHER)") +(function-put 'transient-insert-suffix 'lisp-indent-function 'defun) +(autoload 'transient-append-suffix "transient" "\ +Insert a SUFFIX into PREFIX after LOC. +PREFIX is a prefix command, a symbol. +SUFFIX is a suffix command or a group specification (of + the same forms as expected by `transient-define-prefix'). +LOC is a command, a key vector, a key description (a string + as returned by `key-description'), or a coordination list + (whose last element may also be a command or key). +Remove a conflicting binding unless optional KEEP-OTHER is + non-nil. +See info node `(transient)Modifying Existing Transients'. + +(fn PREFIX LOC SUFFIX &optional KEEP-OTHER)") +(function-put 'transient-append-suffix 'lisp-indent-function 'defun) +(autoload 'transient-replace-suffix "transient" "\ +Replace the suffix at LOC in PREFIX with SUFFIX. +PREFIX is a prefix command, a symbol. +SUFFIX is a suffix command or a group specification (of + the same forms as expected by `transient-define-prefix'). +LOC is a command, a key vector, a key description (a string + as returned by `key-description'), or a coordination list + (whose last element may also be a command or key). +See info node `(transient)Modifying Existing Transients'. + +(fn PREFIX LOC SUFFIX)") +(function-put 'transient-replace-suffix 'lisp-indent-function 'defun) +(autoload 'transient-remove-suffix "transient" "\ +Remove the suffix or group at LOC in PREFIX. +PREFIX is a prefix command, a symbol. +LOC is a command, a key vector, a key description (a string + as returned by `key-description'), or a coordination list + (whose last element may also be a command or key). +See info node `(transient)Modifying Existing Transients'. + +(fn PREFIX LOC)") +(function-put 'transient-remove-suffix 'lisp-indent-function 'defun) +(register-definition-prefixes "transient" '("find-function-advised-original" "transient")) + +;;; End of scraped data + +(provide 'transient-autoloads) + +;; Local Variables: +;; version-control: never +;; no-byte-compile: t +;; no-update-autoloads: t +;; no-native-compile: t +;; coding: utf-8-emacs-unix +;; End: + +;;; transient-autoloads.el ends here diff --git a/emacs/elpa/transient-20241004.1739/transient-pkg.el b/emacs/elpa/transient-20241004.1739/transient-pkg.el @@ -0,0 +1,12 @@ +;; -*- no-byte-compile: t; lexical-binding: nil -*- +(define-package "transient" "20241004.1739" + "Transient commands." + '((emacs "26.1") + (compat "30.0.0.0") + (seq "2.24")) + :url "https://github.com/magit/transient" + :commit "fc03c0b75826aa771b682137aa3f4e24130a9e3c" + :revdesc "fc03c0b75826" + :keywords '("extensions") + :authors '(("Jonas Bernoulli" . "emacs.transient@jonas.bernoulli.dev")) + :maintainers '(("Jonas Bernoulli" . "emacs.transient@jonas.bernoulli.dev"))) diff --git a/emacs/elpa/transient-20241004.1739/transient.el b/emacs/elpa/transient-20241004.1739/transient.el @@ -0,0 +1,4604 @@ +;;; transient.el --- Transient commands -*- lexical-binding:t -*- + +;; Copyright (C) 2018-2024 Free Software Foundation, Inc. + +;; Author: Jonas Bernoulli <emacs.transient@jonas.bernoulli.dev> +;; Homepage: https://github.com/magit/transient +;; Keywords: extensions + +;; Package-Version: 20241004.1739 +;; Package-Revision: fc03c0b75826 +;; Package-Requires: ((emacs "26.1") (compat "30.0.0.0") (seq "2.24")) + +;; SPDX-License-Identifier: GPL-3.0-or-later + +;; This file is part of GNU Emacs. + +;; GNU Emacs is free software: you can redistribute it and/or modify +;; it under the terms of the GNU General Public License as published +;; by the Free Software Foundation, either version 3 of the License, +;; or (at your option) any later version. +;; +;; GNU Emacs is distributed in the hope that it will be useful, +;; but WITHOUT ANY WARRANTY; without even the implied warranty of +;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +;; GNU General Public License for more details. +;; +;; You should have received a copy of the GNU General Public License +;; along with this program. If not, see <https://www.gnu.org/licenses/>. + +;;; Commentary: + +;; Transient is the library used to implement the keyboard-driven menus +;; in Magit. It is distributed as a separate package, so that it can be +;; used to implement similar menus in other packages. + +;;; Code: + +(require 'cl-lib) +(require 'compat) +(require 'eieio) +(require 'edmacro) +(require 'format-spec) + +(eval-and-compile + (when (and (featurep 'seq) + (not (fboundp 'seq-keep))) + (unload-feature 'seq 'force))) +(require 'seq) +(unless (fboundp 'seq-keep) + (display-warning 'transient (substitute-command-keys "\ +Transient requires `seq' >= 2.24, +but due to bad defaults, Emacs's package manager, refuses to +upgrade this and other built-in packages to higher releases +from GNU Elpa, when a package specifies that this is needed. + +To fix this, you have to add this to your init file: + + (setq package-install-upgrade-built-in t) + +Then evaluate that expression by placing the cursor after it +and typing \\[eval-last-sexp]. + +Once you have done that, you have to explicitly upgrade `seq': + + \\[package-upgrade] seq \\`RET' + +Then you also must make sure the updated version is loaded, +by evaluating this form: + + (progn (unload-feature 'seq t) (require 'seq)) + +Until you do this, you will get random errors about `seq-keep' +being undefined while using Transient. + +If you don't use the `package' package manager but still get +this warning, then your chosen package manager likely has a +similar defect.") :emergency)) + +(eval-when-compile (require 'subr-x)) + +(declare-function info "info" (&optional file-or-node buffer)) +(declare-function Man-find-section "man" (section)) +(declare-function Man-next-section "man" (n)) +(declare-function Man-getpage-in-background "man" (topic)) + +(defvar Man-notify-method) +(defvar pp-default-function) ; since Emacs 29.1 + +(defmacro transient--with-emergency-exit (id &rest body) + (declare (indent defun)) + (unless (keywordp id) + (setq body (cons id body)) + (setq id nil)) + `(condition-case err + (let ((debugger #'transient--exit-and-debug)) + ,(macroexp-progn body)) + ((debug error) + (transient--emergency-exit ,id) + (signal (car err) (cdr err))))) + +(defun transient--exit-and-debug (&rest args) + (transient--emergency-exit :debugger) + (apply #'debug args)) + +;;; Options + +(defgroup transient nil + "Transient commands." + :group 'extensions) + +(defcustom transient-show-popup t + "Whether to show the current transient in a popup buffer. +\\<transient-map> +- If t, then show the popup as soon as a transient prefix command + is invoked. + +- If nil, then do not show the popup unless the user explicitly + requests it, by pressing \\[transient-show] or a prefix key. + +- If a number, then delay displaying the popup and instead show + a brief one-line summary. If zero or negative, then suppress + even showing that summary and display the pressed key only. + + Show the popup when the user explicitly requests it by pressing + \\[transient-show] or a prefix key. Unless zero, then also show the popup + after that many seconds of inactivity (using the absolute value)." + :package-version '(transient . "0.1.0") + :group 'transient + :type '(choice (const :tag "instantly" t) + (const :tag "on demand" nil) + (const :tag "on demand (no summary)" 0) + (number :tag "after delay" 1))) + +(defcustom transient-enable-popup-navigation t + "Whether navigation commands are enabled in the transient popup. + +While a transient is active the transient popup buffer is not the +current buffer, making it necessary to use dedicated commands to +act on that buffer itself. If this is non-nil, then the following +bindings are available: + +\\<transient-popup-navigation-map>\ +- \\[transient-backward-button] moves the cursor to the previous suffix. +- \\[transient-forward-button] moves the cursor to the next suffix. +- \\[transient-push-button] invokes the suffix the cursor is on. +\\<transient-button-map>\ +- \\`<mouse-1>' and \\`<mouse-2>' invoke the clicked on suffix. +\\<transient-popup-navigation-map>\ +- \\[transient-isearch-backward]\ + and \\[transient-isearch-forward] start isearch in the popup buffer. + +\\`<mouse-1>' and \\`<mouse-2>' are bound in `transient-push-button'. +All other bindings are in `transient-popup-navigation-map'. + +By default \\`M-RET' is bound to `transient-push-button', instead of +\\`RET', because if a transient allows the invocation of non-suffixes +then it is likely that you would want \\`RET' to do what it would do +if no transient were active." + :package-version '(transient . "0.4.0") + :group 'transient + :type 'boolean) + +(defcustom transient-display-buffer-action + '(display-buffer-in-side-window + (side . bottom) + (dedicated . t) + (inhibit-same-window . t)) + "The action used to display the transient popup buffer. + +The transient popup buffer is displayed in a window using + + (display-buffer BUFFER transient-display-buffer-action) + +The value of this option has the form (FUNCTION . ALIST), +where FUNCTION is a function or a list of functions. Each such +function should accept two arguments: a buffer to display and an +alist of the same form as ALIST. See info node `(elisp)Choosing +Window' for details. + +The default is: + + (display-buffer-in-side-window + (side . bottom) + (dedicated . t) + (inhibit-same-window . t)) + +This displays the window at the bottom of the selected frame. +Another useful FUNCTION is `display-buffer-below-selected', which +is what `magit-popup' used by default. For more alternatives see +info node `(elisp)Display Action Functions' and info node +`(elisp)Buffer Display Action Alists'. + +Note that the buffer that was current before the transient buffer +is shown should remain the current buffer. Many suffix commands +act on the thing at point, if appropriate, and if the transient +buffer became the current buffer, then that would change what is +at point. To that effect `inhibit-same-window' ensures that the +selected window is not used to show the transient buffer. + +It may be possible to display the window in another frame, but +whether that works in practice depends on the window-manager. +If the window manager selects the new window (Emacs frame), +then that unfortunately changes which buffer is current. + +If you change the value of this option, then you might also +want to change the value of `transient-mode-line-format'." + :package-version '(transient . "0.7.5") + :group 'transient + :type '(cons (choice function (repeat :tag "Functions" function)) + alist)) + +(defcustom transient-mode-line-format 'line + "The mode-line format for the transient popup buffer. + +If nil, then the buffer has no mode-line. If the buffer is not +displayed right above the echo area, then this probably is not +a good value. + +If `line' (the default) or a natural number, then the buffer +has no mode-line, but a line is drawn is drawn in its place. +If a number is used, that specifies the thickness of the line. +On termcap frames we cannot draw lines, so there `line' and +numbers are synonyms for nil. + +The color of the line is used to indicate if non-suffixes are +allowed and whether they exit the transient. The foreground +color of `transient-key-noop' (if non-suffix are disallowed), +`transient-key-stay' (if allowed and transient stays active), or +`transient-key-exit' (if allowed and they exit the transient) is +used to draw the line. + +Otherwise this can be any mode-line format. +See `mode-line-format' for details." + :package-version '(transient . "0.2.0") + :group 'transient + :type '(choice (const :tag "hide mode-line" nil) + (const :tag "substitute thin line" line) + (number :tag "substitute line with thickness") + (const :tag "name of prefix command" + ("%e" mode-line-front-space + mode-line-buffer-identification)) + (sexp :tag "custom mode-line format"))) + +(defcustom transient-show-common-commands nil + "Whether to show common transient suffixes in the popup buffer. + +These commands are always shown after typing the prefix key +\"C-x\" when a transient command is active. To toggle the value +of this variable use \"C-x t\" when a transient is active." + :package-version '(transient . "0.1.0") + :group 'transient + :type 'boolean) + +(defcustom transient-read-with-initial-input nil + "Whether to use the last history element as initial minibuffer input." + :package-version '(transient . "0.2.0") + :group 'transient + :type 'boolean) + +(defcustom transient-highlight-mismatched-keys nil + "Whether to highlight keys that do not match their argument. + +This only affects infix arguments that represent command-line +arguments. When this option is non-nil, then the key binding +for infix argument are highlighted when only a long argument +\(e.g., \"--verbose\") is specified but no shorthand (e.g., \"-v\"). +In the rare case that a short-hand is specified but does not +match the key binding, then it is highlighted differently. + +The highlighting is done using `transient-mismatched-key' +and `transient-nonstandard-key'." + :package-version '(transient . "0.1.0") + :group 'transient + :type 'boolean) + +(defcustom transient-highlight-higher-levels nil + "Whether to highlight suffixes on higher levels. + +This is primarily intended for package authors. + +When non-nil then highlight the description of suffixes whose +level is above 4, the default of `transient-default-level'. +Assuming you have set that variable to 7, this highlights all +suffixes that won't be available to users without them making +the same customization." + :package-version '(transient . "0.3.6") + :group 'transient + :type 'boolean) + +(defcustom transient-substitute-key-function nil + "Function used to modify key bindings. + +This function is called with one argument, the prefix object, +and must return a key binding description, either the existing +key description it finds in the `key' slot, or a substitution. + +This is intended to let users replace certain prefix keys. It +could also be used to make other substitutions, but that is +discouraged. + +For example, \"=\" is hard to reach using my custom keyboard +layout, so I substitute \"(\" for that, which is easy to reach +using a layout optimized for Lisp. + + (setq transient-substitute-key-function + (lambda (obj) + (let ((key (oref obj key))) + (if (string-match \"\\\\`\\\\(=\\\\)[a-zA-Z]\" key) + (replace-match \"(\" t t key 1) + key)))))" + :package-version '(transient . "0.1.0") + :group 'transient + :type '(choice (const :tag "Transform no keys (nil)" nil) function)) + +(defcustom transient-semantic-coloring t + "Whether to use colors to indicate transient behavior. + +If non-nil, then the key binding of each suffix is colorized to +indicate whether it exits the transient state or not, and the +line that is drawn below the transient popup buffer is used to +indicate the behavior of non-suffix commands." + :package-version '(transient . "0.5.0") + :group 'transient + :type 'boolean) + +(defcustom transient-detect-key-conflicts nil + "Whether to detect key binding conflicts. + +Conflicts are detected when a transient prefix command is invoked +and results in an error, which prevents the transient from being +used." + :package-version '(transient . "0.1.0") + :group 'transient + :type 'boolean) + +(defcustom transient-align-variable-pitch nil + "Whether to align columns pixel-wise in the popup buffer. + +If this is non-nil, then columns are aligned pixel-wise to +support variable-pitch fonts. Keys are not aligned, so you +should use a fixed-pitch font for the `transient-key' face. +Other key faces inherit from that face unless a theme is +used that breaks that relationship. + +This option is intended for users who use a variable-pitch +font for the `default' face. + +Also see `transient-force-fixed-pitch'." + :package-version '(transient . "0.4.0") + :group 'transient + :type 'boolean) + +(defcustom transient-force-fixed-pitch nil + "Whether to force use of monospaced font in the popup buffer. + +Even if you use a proportional font for the `default' face, +you might still want to use a monospaced font in transient's +popup buffer. Setting this option to t causes `default' to +be remapped to `fixed-pitch' in that buffer. + +Also see `transient-align-variable-pitch'." + :package-version '(transient . "0.2.0") + :group 'transient + :type 'boolean) + +(defcustom transient-force-single-column nil + "Whether to force use of a single column to display suffixes. + +This might be useful for users with low vision who use large +text and might otherwise have to scroll in two dimensions." + :package-version '(transient . "0.3.6") + :group 'transient + :type 'boolean) + +(defcustom transient-hide-during-minibuffer-read nil + "Whether to hide the transient buffer while reading in the minibuffer." + :package-version '(transient . "0.4.0") + :group 'transient + :type 'boolean) + +(defconst transient--max-level 7) +(defconst transient--default-child-level 1) +(defconst transient--default-prefix-level 4) + +(defcustom transient-default-level transient--default-prefix-level + "Control what suffix levels are made available by default. + +Each suffix command is placed on a level and each prefix command +has a level, which controls which suffix commands are available. +Integers between 1 and 7 (inclusive) are valid levels. + +The levels of individual transients and/or their individual +suffixes can be changed individually, by invoking the prefix and +then pressing \"C-x l\". + +The default level for both transients and their suffixes is 4. +This option only controls the default for transients. The default +suffix level is always 4. The author of a transient should place +certain suffixes on a higher level if they expect that it won't be +of use to most users, and they should place very important suffixes +on a lower level so that they remain available even if the user +lowers the transient level. + +\(Magit currently places nearly all suffixes on level 4 and lower +levels are not used at all yet. So for the time being you should +not set a lower level here and using a higher level might not +give you as many additional suffixes as you hoped.)" + :package-version '(transient . "0.1.0") + :group 'transient + :type '(choice (const :tag "1 - fewest suffixes" 1) + (const 2) + (const 3) + (const :tag "4 - default" 4) + (const 5) + (const 6) + (const :tag "7 - most suffixes" 7))) + +(defcustom transient-levels-file + (locate-user-emacs-file "transient/levels.el") + "File used to save levels of transients and their suffixes." + :package-version '(transient . "0.1.0") + :group 'transient + :type 'file) + +(defcustom transient-values-file + (locate-user-emacs-file "transient/values.el") + "File used to save values of transients." + :package-version '(transient . "0.1.0") + :group 'transient + :type 'file) + +(defcustom transient-history-file + (locate-user-emacs-file "transient/history.el") + "File used to save history of transients and their infixes." + :package-version '(transient . "0.1.0") + :group 'transient + :type 'file) + +(defcustom transient-history-limit 10 + "Number of history elements to keep when saving to file." + :package-version '(transient . "0.1.0") + :group 'transient + :type 'integer) + +(defcustom transient-save-history t + "Whether to save history of transient commands when exiting Emacs." + :package-version '(transient . "0.1.0") + :group 'transient + :type 'boolean) + +;;; Faces + +(defgroup transient-faces nil + "Faces used by Transient." + :group 'transient) + +(defface transient-heading '((t :inherit font-lock-keyword-face)) + "Face used for headings." + :group 'transient-faces) + +(defface transient-argument '((t :inherit font-lock-string-face :weight bold)) + "Face used for enabled arguments." + :group 'transient-faces) + +(defface transient-inactive-argument '((t :inherit shadow)) + "Face used for inactive arguments." + :group 'transient-faces) + +(defface transient-value '((t :inherit font-lock-string-face :weight bold)) + "Face used for values." + :group 'transient-faces) + +(defface transient-inactive-value '((t :inherit shadow)) + "Face used for inactive values." + :group 'transient-faces) + +(defface transient-unreachable '((t :inherit shadow)) + "Face used for suffixes unreachable from the current prefix sequence." + :group 'transient-faces) + +(defface transient-inapt-suffix '((t :inherit shadow :italic t)) + "Face used for suffixes that are inapt at this time." + :group 'transient-faces) + +(defface transient-active-infix '((t :inherit highlight)) + "Face used for the infix for which the value is being read." + :group 'transient-faces) + +(defface transient-enabled-suffix + '((t :background "green" :foreground "black" :weight bold)) + "Face used for enabled levels while editing suffix levels. +See info node `(transient)Enabling and Disabling Suffixes'." + :group 'transient-faces) + +(defface transient-disabled-suffix + '((t :background "red" :foreground "black" :weight bold)) + "Face used for disabled levels while editing suffix levels. +See info node `(transient)Enabling and Disabling Suffixes'." + :group 'transient-faces) + +(defface transient-higher-level + `((t :box ( :line-width ,(if (>= emacs-major-version 28) (cons -1 -1) -1) + :color ,(let ((color (face-attribute 'shadow :foreground nil t))) + (or (and (not (eq color 'unspecified)) color) + "grey60"))))) + "Face optionally used to highlight suffixes on higher levels. +Also see option `transient-highlight-higher-levels'." + :group 'transient-faces) + +(defface transient-delimiter '((t :inherit shadow)) + "Face used for delimiters and separators. +This includes the parentheses around values and the pipe +character used to separate possible values from each other." + :group 'transient-faces) + +(defface transient-key '((t :inherit font-lock-builtin-face)) + "Face used for keys." + :group 'transient-faces) + +(defface transient-key-stay + `((((class color) (background light)) + :inherit transient-key + :foreground "#22aa22") + (((class color) (background dark)) + :inherit transient-key + :foreground "#ddffdd")) + "Face used for keys of suffixes that don't exit transient state." + :group 'transient-faces) + +(defface transient-key-noop + `((((class color) (background light)) + :inherit transient-key + :foreground "grey80") + (((class color) (background dark)) + :inherit transient-key + :foreground "grey30")) + "Face used for keys of suffixes that currently cannot be invoked." + :group 'transient-faces) + +(defface transient-key-return + `((((class color) (background light)) + :inherit transient-key + :foreground "#aaaa11") + (((class color) (background dark)) + :inherit transient-key + :foreground "#ffffcc")) + "Face used for keys of suffixes that return to the parent transient." + :group 'transient-faces) + +(defface transient-key-exit + `((((class color) (background light)) + :inherit transient-key + :foreground "#aa2222") + (((class color) (background dark)) + :inherit transient-key + :foreground "#ffdddd")) + "Face used for keys of suffixes that exit transient state." + :group 'transient-faces) + +(defface transient-unreachable-key + '((t :inherit (shadow transient-key) :weight normal)) + "Face used for keys unreachable from the current prefix sequence." + :group 'transient-faces) + +(defface transient-nonstandard-key + `((t :box ( :line-width ,(if (>= emacs-major-version 28) (cons -1 -1) -1) + :color "cyan"))) + "Face optionally used to highlight keys conflicting with short-argument. +Also see option `transient-highlight-mismatched-keys'." + :group 'transient-faces) + +(defface transient-mismatched-key + `((t :box ( :line-width ,(if (>= emacs-major-version 28) (cons -1 -1) -1) + :color "magenta"))) + "Face optionally used to highlight keys without a short-argument. +Also see option `transient-highlight-mismatched-keys'." + :group 'transient-faces) + +;;; Persistence + +(defun transient--read-file-contents (file) + (with-demoted-errors "Transient error: %S" + (and (file-exists-p file) + (with-temp-buffer + (insert-file-contents file) + (read (current-buffer)))))) + +(defun transient--pp-to-file (list file) + (make-directory (file-name-directory file) t) + (setq list (cl-sort (copy-sequence list) #'string< :key #'car)) + (with-temp-file file + (let ((print-level nil) + (print-length nil) + (pp-default-function 'pp-28) + (fill-column 999)) + (pp list (current-buffer))))) + +(defvar transient-values + (transient--read-file-contents transient-values-file) + "Values of transient commands. +The value of this variable persists between Emacs sessions +and you usually should not change it manually.") + +(defun transient-save-values () + (transient--pp-to-file transient-values transient-values-file)) + +(defvar transient-levels + (transient--read-file-contents transient-levels-file) + "Levels of transient commands. +The value of this variable persists between Emacs sessions +and you usually should not change it manually.") + +(defun transient-save-levels () + (transient--pp-to-file transient-levels transient-levels-file)) + +(defvar transient-history + (transient--read-file-contents transient-history-file) + "History of transient commands and infix arguments. +The value of this variable persists between Emacs sessions +\(unless `transient-save-history' is nil) and you usually +should not change it manually.") + +(defun transient-save-history () + (setq transient-history + (cl-sort (mapcar (pcase-lambda (`(,key . ,val)) + (cons key (seq-take (delete-dups val) + transient-history-limit))) + transient-history) + #'string< :key #'car)) + (transient--pp-to-file transient-history transient-history-file)) + +(defun transient-maybe-save-history () + "Save the value of `transient-history'. +If `transient-save-history' is nil, then do nothing." + (when transient-save-history + (transient-save-history))) + +(unless noninteractive + (add-hook 'kill-emacs-hook #'transient-maybe-save-history)) + +;;; Classes +;;;; Prefix + +(defclass transient-prefix () + ((prototype :initarg :prototype) + (command :initarg :command) + (level :initarg :level) + (variable :initarg :variable :initform nil) + (init-value :initarg :init-value) + (value) (default-value :initarg :value) + (scope :initarg :scope :initform nil) + (history :initarg :history :initform nil) + (history-pos :initarg :history-pos :initform 0) + (history-key :initarg :history-key :initform nil) + (show-help :initarg :show-help :initform nil) + (info-manual :initarg :info-manual :initform nil) + (man-page :initarg :man-page :initform nil) + (transient-suffix :initarg :transient-suffix :initform nil) + (transient-non-suffix :initarg :transient-non-suffix :initform nil) + (transient-switch-frame :initarg :transient-switch-frame) + (refresh-suffixes :initarg :refresh-suffixes :initform nil) + (incompatible :initarg :incompatible :initform nil) + (suffix-description :initarg :suffix-description) + (variable-pitch :initarg :variable-pitch :initform nil) + (column-widths :initarg :column-widths :initform nil) + (unwind-suffix :documentation "Internal use." :initform nil)) + "Transient prefix command. + +Each transient prefix command consists of a command, which is +stored in a symbol's function slot and an object, which is +stored in the `transient--prefix' property of the same symbol. + +When a transient prefix command is invoked, then a clone of that +object is stored in the global variable `transient--prefix' and +the prototype is stored in the clone's `prototype' slot.") + +;;;; Suffix + +(defclass transient-child () + ((level + :initarg :level + :initform (symbol-value 'transient--default-child-level) + :documentation "Enable if level of prefix is equal or greater.") + (if + :initarg :if + :initform nil + :documentation "Enable if predicate returns non-nil.") + (if-not + :initarg :if-not + :initform nil + :documentation "Enable if predicate returns nil.") + (if-non-nil + :initarg :if-non-nil + :initform nil + :documentation "Enable if variable's value is non-nil.") + (if-nil + :initarg :if-nil + :initform nil + :documentation "Enable if variable's value is nil.") + (if-mode + :initarg :if-mode + :initform nil + :documentation "Enable if major-mode matches value.") + (if-not-mode + :initarg :if-not-mode + :initform nil + :documentation "Enable if major-mode does not match value.") + (if-derived + :initarg :if-derived + :initform nil + :documentation "Enable if major-mode derives from value.") + (if-not-derived + :initarg :if-not-derived + :initform nil + :documentation "Enable if major-mode does not derive from value.") + (inapt + :initform nil) + (inapt-face + :initarg :inapt-face + :initform 'transient-inapt-suffix) + (inapt-if + :initarg :inapt-if + :initform nil + :documentation "Inapt if predicate returns non-nil.") + (inapt-if-not + :initarg :inapt-if-not + :initform nil + :documentation "Inapt if predicate returns nil.") + (inapt-if-non-nil + :initarg :inapt-if-non-nil + :initform nil + :documentation "Inapt if variable's value is non-nil.") + (inapt-if-nil + :initarg :inapt-if-nil + :initform nil + :documentation "Inapt if variable's value is nil.") + (inapt-if-mode + :initarg :inapt-if-mode + :initform nil + :documentation "Inapt if major-mode matches value.") + (inapt-if-not-mode + :initarg :inapt-if-not-mode + :initform nil + :documentation "Inapt if major-mode does not match value.") + (inapt-if-derived + :initarg :inapt-if-derived + :initform nil + :documentation "Inapt if major-mode derives from value.") + (inapt-if-not-derived + :initarg :inapt-if-not-derived + :initform nil + :documentation "Inapt if major-mode does not derive from value.")) + "Abstract superclass for group and suffix classes. + +It is undefined what happens if more than one `if*' predicate +slot is non-nil." + :abstract t) + +(defclass transient-suffix (transient-child) + ((definition :allocation :class :initform nil) + (key :initarg :key) + (command :initarg :command) + (transient :initarg :transient) + (format :initarg :format :initform " %k %d") + (description :initarg :description :initform nil) + (face :initarg :face :initform nil) + (show-help :initarg :show-help :initform nil)) + "Superclass for suffix command.") + +(defclass transient-information (transient-suffix) + ((format :initform " %k %d") + (key :initform " ")) + "Display-only information, aligned with suffix keys. +Technically a suffix object with no associated command.") + +(defclass transient-information* (transient-information) + ((format :initform " %d")) + "Display-only information, aligned with suffix descriptions. +Technically a suffix object with no associated command.") + +(defclass transient-infix (transient-suffix) + ((transient :initform t) + (argument :initarg :argument) + (shortarg :initarg :shortarg) + (value :initform nil) + (init-value :initarg :init-value) + (unsavable :initarg :unsavable :initform nil) + (multi-value :initarg :multi-value :initform nil) + (always-read :initarg :always-read :initform nil) + (allow-empty :initarg :allow-empty :initform nil) + (history-key :initarg :history-key :initform nil) + (reader :initarg :reader :initform nil) + (prompt :initarg :prompt :initform nil) + (choices :initarg :choices :initform nil) + (format :initform " %k %d (%v)")) + "Transient infix command." + :abstract t) + +(defclass transient-argument (transient-infix) () + "Abstract superclass for infix arguments." + :abstract t) + +(defclass transient-switch (transient-argument) () + "Class used for command-line argument that can be turned on and off.") + +(defclass transient-option (transient-argument) () + "Class used for command-line argument that can take a value.") + +(defclass transient-variable (transient-infix) + ((variable :initarg :variable) + (format :initform " %k %d %v")) + "Abstract superclass for infix commands that set a variable." + :abstract t) + +(defclass transient-switches (transient-argument) + ((argument-format :initarg :argument-format) + (argument-regexp :initarg :argument-regexp)) + "Class used for sets of mutually exclusive command-line switches.") + +(defclass transient-files (transient-option) () + ((key :initform "--") + (argument :initform "--") + (multi-value :initform rest) + (reader :initform transient-read-files)) + "Class used for the \"--\" argument or similar. +All remaining arguments are treated as files. +They become the value of this argument.") + +(defclass transient-value-preset (transient-suffix) + ((transient :initform t) + (set :initarg := :initform nil)) + "Class used by the `transient-preset' suffix command.") + +;;;; Group + +(defclass transient-group (transient-child) + ((suffixes :initarg :suffixes :initform nil) + (hide :initarg :hide :initform nil) + (description :initarg :description :initform nil) + (pad-keys :initarg :pad-keys :initform nil) + (info-format :initarg :info-format :initform nil) + (setup-children :initarg :setup-children)) + "Abstract superclass of all group classes." + :abstract t) + +(defclass transient-column (transient-group) () + "Group class that displays each element on a separate line.") + +(defclass transient-row (transient-group) () + "Group class that displays all elements on a single line.") + +(defclass transient-columns (transient-group) () + "Group class that displays elements organized in columns. +Direct elements have to be groups whose elements have to be +commands or strings. Each subgroup represents a column. +This class takes care of inserting the subgroups' elements.") + +(defclass transient-subgroups (transient-group) () + "Group class that wraps other groups. + +Direct elements have to be groups whose elements have to be +commands or strings. This group inserts an empty line between +subgroups. The subgroups are responsible for displaying their +elements themselves.") + +;;; Define + +(defmacro transient-define-prefix (name arglist &rest args) + "Define NAME as a transient prefix command. + +ARGLIST are the arguments that command takes. +DOCSTRING is the documentation string and is optional. + +These arguments can optionally be followed by key-value pairs. +Each key has to be a keyword symbol, either `:class' or a keyword +argument supported by the constructor of that class. The +`transient-prefix' class is used if the class is not specified +explicitly. + +GROUPs add key bindings for infix and suffix commands and specify +how these bindings are presented in the popup buffer. At least +one GROUP has to be specified. See info node `(transient)Binding +Suffix and Infix Commands'. + +The BODY is optional. If it is omitted, then ARGLIST is also +ignored and the function definition becomes: + + (lambda () + (interactive) + (transient-setup \\='NAME)) + +If BODY is specified, then it must begin with an `interactive' +form that matches ARGLIST, and it must call `transient-setup'. +It may however call that function only when some condition is +satisfied; that is one of the reason why you might want to use +an explicit BODY. + +All transients have a (possibly nil) value, which is exported +when suffix commands are called, so that they can consume that +value. For some transients it might be necessary to have a sort +of secondary value, called a scope. Such a scope would usually +be set in the commands `interactive' form and has to be passed +to the setup function: + + (transient-setup \\='NAME nil nil :scope SCOPE) + +\(fn NAME ARGLIST [DOCSTRING] [KEYWORD VALUE]... GROUP... [BODY...])" + (declare (debug ( &define name lambda-list + [&optional lambda-doc] + [&rest keywordp sexp] + [&rest vectorp] + [&optional ("interactive" interactive) def-body])) + (indent defun) + (doc-string 3)) + (pcase-let + ((`(,class ,slots ,suffixes ,docstr ,body ,interactive-only) + (transient--expand-define-args args arglist 'transient-define-prefix))) + `(progn + (defalias ',name + ,(if body + `(lambda ,arglist ,@body) + `(lambda () + (interactive) + (transient-setup ',name)))) + (put ',name 'interactive-only ,interactive-only) + (put ',name 'function-documentation ,docstr) + (put ',name 'transient--prefix + (,(or class 'transient-prefix) :command ',name ,@slots)) + (put ',name 'transient--layout + (list ,@(cl-mapcan (lambda (s) (transient--parse-child name s)) + suffixes)))))) + +(defmacro transient-define-suffix (name arglist &rest args) + "Define NAME as a transient suffix command. + +ARGLIST are the arguments that the command takes. +DOCSTRING is the documentation string and is optional. + +These arguments can optionally be followed by key-value pairs. +Each key has to be a keyword symbol, either `:class' or a +keyword argument supported by the constructor of that class. +The `transient-suffix' class is used if the class is not +specified explicitly. + +The BODY must begin with an `interactive' form that matches +ARGLIST. The infix arguments are usually accessed by using +`transient-args' inside `interactive'. + +\(fn NAME ARGLIST [DOCSTRING] [KEYWORD VALUE]... [BODY...])" + (declare (debug ( &define name lambda-list + [&optional lambda-doc] + [&rest keywordp sexp] + [&optional ("interactive" interactive) def-body])) + (indent defun) + (doc-string 3)) + (pcase-let + ((`(,class ,slots ,_ ,docstr ,body ,interactive-only) + (transient--expand-define-args args arglist 'transient-define-suffix))) + `(progn + (defalias ',name + ,(if (and (not body) class (oref-default class definition)) + `(oref-default ',class definition) + `(lambda ,arglist ,@body))) + (put ',name 'interactive-only ,interactive-only) + (put ',name 'function-documentation ,docstr) + (put ',name 'transient--suffix + (,(or class 'transient-suffix) :command ',name ,@slots))))) + +(defmacro transient-augment-suffix (name &rest args) + "Augment existing command NAME with a new transient suffix object. +Similar to `transient-define-suffix' but define a suffix object only. +\n\(fn NAME [KEYWORD VALUE]...)" + (declare (debug (&define name [&rest keywordp sexp])) + (indent defun)) + (pcase-let + ((`(,class ,slots) + (transient--expand-define-args args nil 'transient-augment-suffix t))) + `(put ',name 'transient--suffix + (,(or class 'transient-suffix) :command ',name ,@slots)))) + +(defmacro transient-define-infix (name arglist &rest args) + "Define NAME as a transient infix command. + +ARGLIST is always ignored and reserved for future use. +DOCSTRING is the documentation string and is optional. + +At least one key-value pair is required. All transient infix +commands are equal to each other (but not eq). It is meaning- +less to define an infix command, without providing at least one +keyword argument (usually `:argument' or `:variable', depending +on the class). The suffix class defaults to `transient-switch' +and can be set using the `:class' keyword. + +The function definitions is always: + + (lambda () + (interactive) + (let ((obj (transient-suffix-object))) + (transient-infix-set obj (transient-infix-read obj))) + (transient--show)) + +`transient-infix-read' and `transient-infix-set' are generic +functions. Different infix commands behave differently because +the concrete methods are different for different infix command +classes. In rare case the above command function might not be +suitable, even if you define your own infix command class. In +that case you have to use `transient-define-suffix' to define +the infix command and use t as the value of the `:transient' +keyword. + +\(fn NAME ARGLIST [DOCSTRING] KEYWORD VALUE [KEYWORD VALUE]...)" + (declare (debug ( &define name lambda-list + [&optional lambda-doc] + keywordp sexp + [&rest keywordp sexp])) + (indent defun) + (doc-string 3)) + (pcase-let + ((`(,class ,slots ,_ ,docstr ,_ ,interactive-only) + (transient--expand-define-args args arglist 'transient-define-infix t))) + `(progn + (defalias ',name #'transient--default-infix-command) + (put ',name 'interactive-only ,interactive-only) + (put ',name 'completion-predicate #'transient--suffix-only) + (put ',name 'function-documentation ,docstr) + (put ',name 'transient--suffix + (,(or class 'transient-switch) :command ',name ,@slots))))) + +(defalias 'transient-define-argument #'transient-define-infix + "Define NAME as a transient infix command. + +Only use this alias to define an infix command that actually +sets an infix argument. To define a infix command that, for +example, sets a variable, use `transient-define-infix' instead. + +\(fn NAME ARGLIST [DOCSTRING] [KEYWORD VALUE]...)") + +(defun transient--default-infix-command () + ;; Most infix commands are but an alias for this command. + "Cannot show any documentation for this transient infix command. + +When you request help for an infix command using `transient-help', that +usually shows the respective man-page and tries to jump to the location +where the respective argument is being described. + +If no man-page is specified for the containing transient menu, then the +docstring is displayed instead, if any. + +If the infix command doesn't have a docstring, as is the case here, then +this docstring is displayed instead, because technically infix commands +are aliases for `transient--default-infix-command'. + +`describe-function' also shows the docstring of the infix command, +falling back to that of the same aliased command." + (interactive) + (let ((obj (transient-suffix-object))) + (transient-infix-set obj (transient-infix-read obj))) + (transient--show)) +(put 'transient--default-infix-command 'interactive-only t) +(put 'transient--default-infix-command 'completion-predicate + #'transient--suffix-only) + +(define-advice find-function-advised-original + (:around (fn func) transient-default-infix) + "Return nil instead of `transient--default-infix-command'. +When using `find-function' to jump to the definition of a transient +infix command/argument, then we want to actually jump to that, not to +the definition of `transient--default-infix-command', which all infix +commands are aliases for." + (let ((val (funcall fn func))) + (and val (not (eq val 'transient--default-infix-command)) val))) + +(eval-and-compile ;transient--expand-define-args + (defun transient--expand-define-args (args &optional arglist form nobody) + ;; ARGLIST and FORM are only optional for backward compatibility. + ;; This is necessary because "emoji.el" from Emacs 29 calls this + ;; function directly, with just one argument. + (unless (listp arglist) + (error "Mandatory ARGLIST is missing")) + (let (class keys suffixes docstr declare (interactive-only t)) + (when (stringp (car args)) + (setq docstr (pop args))) + (while (keywordp (car args)) + (let ((k (pop args)) + (v (pop args))) + (if (eq k :class) + (setq class v) + (push k keys) + (push v keys)))) + (while (let ((arg (car args))) + (or (vectorp arg) + (and arg (symbolp arg)))) + (push (pop args) suffixes)) + (when (eq (car-safe (car args)) 'declare) + (setq declare (car args)) + (setq args (cdr args)) + (when-let ((int (assq 'interactive-only declare))) + (setq interactive-only (cadr int)) + (delq int declare)) + (unless (cdr declare) + (setq declare nil))) + (cond + ((not args)) + (nobody + (error "%s: No function body allowed" form)) + ((not (eq (car-safe (nth (if declare 1 0) args)) 'interactive)) + (error "%s: Interactive form missing" form))) + (list (if (eq (car-safe class) 'quote) + (cadr class) + class) + (nreverse keys) + (nreverse suffixes) + docstr + (if declare (cons declare args) args) + interactive-only)))) + +(defun transient--parse-child (prefix spec) + (cl-typecase spec + (null (error "Invalid transient--parse-child spec: %s" spec)) + (symbol (let ((value (symbol-value spec))) + (if (and (listp value) + (or (listp (car value)) + (vectorp (car value)))) + (cl-mapcan (lambda (s) (transient--parse-child prefix s)) value) + (transient--parse-child prefix value)))) + (vector (and-let* ((c (transient--parse-group prefix spec))) (list c))) + (list (and-let* ((c (transient--parse-suffix prefix spec))) (list c))) + (string (list spec)) + (t (error "Invalid transient--parse-child spec: %s" spec)))) + +(defun transient--parse-group (prefix spec) + (setq spec (append spec nil)) + (cl-symbol-macrolet + ((car (car spec)) + (pop (pop spec))) + (let (level class args) + (when (integerp car) + (setq level pop)) + (when (stringp car) + (setq args (plist-put args :description pop))) + (while (keywordp car) + (let ((key pop) + (val pop)) + (cond ((eq key :class) + (setq class (macroexp-quote val))) + ((or (symbolp val) + (and (listp val) (not (eq (car val) 'lambda)))) + (setq args (plist-put args key (macroexp-quote val)))) + ((setq args (plist-put args key val)))))) + (unless (or spec class (not (plist-get args :setup-children))) + (message "WARNING: %s: When %s is used, %s must also be specified" + 'transient-define-prefix :setup-children :class)) + (list 'vector + (or level transient--default-child-level) + (cond (class) + ((or (vectorp car) + (and car (symbolp car))) + (quote 'transient-columns)) + ((quote 'transient-column))) + (and args (cons 'list args)) + (cons 'list + (cl-mapcan (lambda (s) (transient--parse-child prefix s)) + spec)))))) + +(defun transient--parse-suffix (prefix spec) + (let (level class args) + (cl-symbol-macrolet + ((car (car spec)) + (pop (pop spec))) + (when (integerp car) + (setq level pop)) + (when (or (stringp car) + (vectorp car)) + (setq args (plist-put args :key pop))) + (cond + ((or (stringp car) + (and (eq (car-safe car) 'lambda) + (not (commandp car)))) + (setq args (plist-put args :description pop))) + ((and (symbolp car) + (not (keywordp car)) + (not (commandp car)) + (commandp (cadr spec))) + (setq args (plist-put args :description (macroexp-quote pop))))) + (cond + ((memq car '(:info :info*))) + ((keywordp car) + (error "Need command, argument, `:info' or `:info*'; got `%s'" car)) + ((symbolp car) + (setq args (plist-put args :command (macroexp-quote pop)))) + ;; During macro-expansion this is expected to be a `lambda' + ;; expression. When this is called from a `:setup-children' + ;; function, it may also be a byte-code function object or a + ;; compiled function. However, we never treat a string as a + ;; command, so we have to check for that explicitly. + ((and (commandp car) + (not (stringp car))) + (let ((cmd pop) + (sym (intern + (format + "transient:%s:%s:%d" prefix + (replace-regexp-in-string (plist-get args :key) " " "") + (prog1 gensym-counter (cl-incf gensym-counter)))))) + (setq args (plist-put + args :command + `(prog1 ',sym + (put ',sym 'interactive-only t) + (put ',sym 'completion-predicate #'transient--suffix-only) + (defalias ',sym ,cmd)))))) + ((or (stringp car) + (and car (listp car))) + (let ((arg pop) + (sym nil)) + (cl-typecase arg + (list + (setq args (plist-put args :shortarg (car arg))) + (setq args (plist-put args :argument (cadr arg))) + (setq arg (cadr arg))) + (string + (when-let ((shortarg (transient--derive-shortarg arg))) + (setq args (plist-put args :shortarg shortarg))) + (setq args (plist-put args :argument arg)))) + (setq sym (intern (format "transient:%s:%s" prefix arg))) + (setq args (plist-put + args :command + `(prog1 ',sym + (put ',sym 'interactive-only t) + (put ',sym 'completion-predicate #'transient--suffix-only) + (defalias ',sym #'transient--default-infix-command)))) + (cond ((and car (not (keywordp car))) + (setq class 'transient-option) + (setq args (plist-put args :reader (macroexp-quote pop)))) + ((not (string-suffix-p "=" arg)) + (setq class 'transient-switch)) + ((setq class 'transient-option))))) + ((error "Need command, argument, `:info' or `:info*'; got %s" car))) + (while (keywordp car) + (let ((key pop) + (val pop)) + (cond ((eq key :class) (setq class val)) + ((eq key :level) (setq level val)) + ((eq key :info) + (setq class 'transient-information) + (setq args (plist-put args :description val))) + ((eq key :info*) + (setq class 'transient-information*) + (setq args (plist-put args :description val))) + ((eq (car-safe val) '\,) + (setq args (plist-put args key (cadr val)))) + ((or (symbolp val) + (and (listp val) (not (eq (car val) 'lambda)))) + (setq args (plist-put args key (macroexp-quote val)))) + ((setq args (plist-put args key val))))))) + (when-let* (((not (plist-get args :key))) + (shortarg (plist-get args :shortarg))) + (setq args (plist-put args :key shortarg))) + (list 'list + (or level transient--default-child-level) + (macroexp-quote (or class 'transient-suffix)) + (cons 'list args)))) + +(defun transient--derive-shortarg (arg) + (save-match-data + (and (string-match "\\`\\(-[a-zA-Z]\\)\\(\\'\\|=\\)" arg) + (match-string 1 arg)))) + +(defun transient-command-completion-not-suffix-only-p (symbol _buffer) + "Say whether SYMBOL should be offered as a completion. +If the value of SYMBOL's `completion-predicate' property is +`transient--suffix-only', then return nil, otherwise return t. +This is the case when a command should only ever be used as a +suffix of a transient prefix command (as opposed to bindings +in regular keymaps or by using `execute-extended-command')." + (not (eq (get symbol 'completion-predicate) 'transient--suffix-only))) + +(defalias 'transient--suffix-only #'ignore + "Ignore ARGUMENTS, do nothing, and return nil. +Also see `transient-command-completion-not-suffix-only-p'. +Only use this alias as the value of the `completion-predicate' +symbol property.") + +(when (and (boundp 'read-extended-command-predicate) ; since Emacs 28.1 + (not read-extended-command-predicate)) + (setq read-extended-command-predicate + #'transient-command-completion-not-suffix-only-p)) + +(defun transient-parse-suffix (prefix suffix) + "Parse SUFFIX, to be added to PREFIX. +PREFIX is a prefix command, a symbol. +SUFFIX is a suffix command or a group specification (of + the same forms as expected by `transient-define-prefix'). +Intended for use in a group's `:setup-children' function." + (cl-assert (and prefix (symbolp prefix))) + (eval (car (transient--parse-child prefix suffix)) t)) + +(defun transient-parse-suffixes (prefix suffixes) + "Parse SUFFIXES, to be added to PREFIX. +PREFIX is a prefix command, a symbol. +SUFFIXES is a list of suffix command or a group specification + (of the same forms as expected by `transient-define-prefix'). +Intended for use in a group's `:setup-children' function." + (cl-assert (and prefix (symbolp prefix))) + (mapcar (apply-partially #'transient-parse-suffix prefix) suffixes)) + +;;; Edit + +(defun transient--insert-suffix (prefix loc suffix action &optional keep-other) + (let* ((suf (cl-etypecase suffix + (vector (transient--parse-group prefix suffix)) + (list (transient--parse-suffix prefix suffix)) + (string suffix))) + (mem (transient--layout-member loc prefix)) + (elt (car mem))) + (setq suf (eval suf t)) + (cond + ((not mem) + (message "Cannot insert %S into %s; %s not found" + suffix prefix loc)) + ((or (and (vectorp suffix) (not (vectorp elt))) + (and (listp suffix) (vectorp elt)) + (and (stringp suffix) (vectorp elt))) + (message "Cannot place %S into %s at %s; %s" + suffix prefix loc + "suffixes and groups cannot be siblings")) + (t + (when-let* ((bindingp (listp suf)) + (key (transient--spec-key suf)) + (conflict (car (transient--layout-member key prefix))) + (conflictp + (and (not (and (eq action 'replace) + (eq conflict elt))) + (or (not keep-other) + (eq (plist-get (nth 2 suf) :command) + (plist-get (nth 2 conflict) :command))) + (equal (transient--suffix-predicate suf) + (transient--suffix-predicate conflict))))) + (transient-remove-suffix prefix key)) + (pcase-exhaustive action + ('insert (setcdr mem (cons elt (cdr mem))) + (setcar mem suf)) + ('append (setcdr mem (cons suf (cdr mem)))) + ('replace (setcar mem suf))))))) + +;;;###autoload +(defun transient-insert-suffix (prefix loc suffix &optional keep-other) + "Insert a SUFFIX into PREFIX before LOC. +PREFIX is a prefix command, a symbol. +SUFFIX is a suffix command or a group specification (of + the same forms as expected by `transient-define-prefix'). +LOC is a command, a key vector, a key description (a string + as returned by `key-description'), or a coordination list + (whose last element may also be a command or key). +Remove a conflicting binding unless optional KEEP-OTHER is + non-nil. +See info node `(transient)Modifying Existing Transients'." + (declare (indent defun)) + (transient--insert-suffix prefix loc suffix 'insert keep-other)) + +;;;###autoload +(defun transient-append-suffix (prefix loc suffix &optional keep-other) + "Insert a SUFFIX into PREFIX after LOC. +PREFIX is a prefix command, a symbol. +SUFFIX is a suffix command or a group specification (of + the same forms as expected by `transient-define-prefix'). +LOC is a command, a key vector, a key description (a string + as returned by `key-description'), or a coordination list + (whose last element may also be a command or key). +Remove a conflicting binding unless optional KEEP-OTHER is + non-nil. +See info node `(transient)Modifying Existing Transients'." + (declare (indent defun)) + (transient--insert-suffix prefix loc suffix 'append keep-other)) + +;;;###autoload +(defun transient-replace-suffix (prefix loc suffix) + "Replace the suffix at LOC in PREFIX with SUFFIX. +PREFIX is a prefix command, a symbol. +SUFFIX is a suffix command or a group specification (of + the same forms as expected by `transient-define-prefix'). +LOC is a command, a key vector, a key description (a string + as returned by `key-description'), or a coordination list + (whose last element may also be a command or key). +See info node `(transient)Modifying Existing Transients'." + (declare (indent defun)) + (transient--insert-suffix prefix loc suffix 'replace)) + +;;;###autoload +(defun transient-remove-suffix (prefix loc) + "Remove the suffix or group at LOC in PREFIX. +PREFIX is a prefix command, a symbol. +LOC is a command, a key vector, a key description (a string + as returned by `key-description'), or a coordination list + (whose last element may also be a command or key). +See info node `(transient)Modifying Existing Transients'." + (declare (indent defun)) + (transient--layout-member loc prefix 'remove)) + +(defun transient-get-suffix (prefix loc) + "Return the suffix or group at LOC in PREFIX. +PREFIX is a prefix command, a symbol. +LOC is a command, a key vector, a key description (a string + as returned by `key-description'), or a coordination list + (whose last element may also be a command or key). +See info node `(transient)Modifying Existing Transients'." + (if-let ((mem (transient--layout-member loc prefix))) + (car mem) + (error "%s not found in %s" loc prefix))) + +(defun transient-suffix-put (prefix loc prop value) + "Edit the suffix at LOC in PREFIX, setting PROP to VALUE. +PREFIX is a prefix command, a symbol. +SUFFIX is a suffix command or a group specification (of + the same forms as expected by `transient-define-prefix'). +LOC is a command, a key vector, a key description (a string + as returned by `key-description'), or a coordination list + (whose last element may also be a command or key). +See info node `(transient)Modifying Existing Transients'." + (let ((suf (transient-get-suffix prefix loc))) + (setf (elt suf 2) + (plist-put (elt suf 2) prop value)))) + +(defun transient--layout-member (loc prefix &optional remove) + (let ((val (or (get prefix 'transient--layout) + (error "%s is not a transient command" prefix)))) + (when (listp loc) + (while (integerp (car loc)) + (let* ((children (if (vectorp val) (aref val 3) val)) + (mem (transient--nthcdr (pop loc) children))) + (if (and remove (not loc)) + (let ((rest (delq (car mem) children))) + (if (vectorp val) + (aset val 3 rest) + (put prefix 'transient--layout rest)) + (setq val nil)) + (setq val (if loc (car mem) mem))))) + (setq loc (car loc))) + (if loc + (transient--layout-member-1 (transient--kbd loc) val remove) + val))) + +(defun transient--layout-member-1 (loc layout remove) + (cond ((listp layout) + (seq-some (lambda (elt) (transient--layout-member-1 loc elt remove)) + layout)) + ((vectorp (car (aref layout 3))) + (seq-some (lambda (elt) (transient--layout-member-1 loc elt remove)) + (aref layout 3))) + (remove + (aset layout 3 + (delq (car (transient--group-member loc layout)) + (aref layout 3))) + nil) + ((transient--group-member loc layout)))) + +(defun transient--group-member (loc group) + (cl-member-if (lambda (suffix) + (and (listp suffix) + (let* ((def (nth 2 suffix)) + (cmd (plist-get def :command))) + (if (symbolp loc) + (eq cmd loc) + (equal (transient--kbd + (or (plist-get def :key) + (transient--command-key cmd))) + loc))))) + (aref group 3))) + +(defun transient--kbd (keys) + (when (vectorp keys) + (setq keys (key-description keys))) + (when (stringp keys) + (setq keys (kbd keys))) + keys) + +(defun transient--spec-key (spec) + (let ((plist (nth 2 spec))) + (or (plist-get plist :key) + (transient--command-key + (plist-get plist :command))))) + +(defun transient--command-key (cmd) + (and-let* ((obj (transient--suffix-prototype cmd))) + (cond ((slot-boundp obj 'key) + (oref obj key)) + ((slot-exists-p obj 'shortarg) + (if (slot-boundp obj 'shortarg) + (oref obj shortarg) + (transient--derive-shortarg (oref obj argument))))))) + +(defun transient--nthcdr (n list) + (nthcdr (if (< n 0) (- (length list) (abs n)) n) list)) + +;;; Variables + +(defvar transient-current-prefix nil + "The transient from which this suffix command was invoked. +This is an object representing that transient, use +`transient-current-command' to get the respective command.") + +(defvar transient-current-command nil + "The transient from which this suffix command was invoked. +This is a symbol representing that transient, use +`transient-current-prefix' to get the respective object.") + +(defvar transient-current-suffixes nil + "The suffixes of the transient from which this suffix command was invoked. +This is a list of objects. Usually it is sufficient to instead +use the function `transient-args', which returns a list of +values. In complex cases it might be necessary to use this +variable instead.") + +(defvar transient-exit-hook nil + "Hook run after exiting a transient.") + +(defvar transient-setup-buffer-hook nil + "Hook run when setting up the transient buffer. +That buffer is current and empty when this hook runs.") + +(defvar transient--prefix nil) +(defvar transient--layout nil) +(defvar transient--suffixes nil) + +(defconst transient--stay t "Do not exit the transient.") +(defconst transient--exit nil "Do exit the transient.") + +(defvar transient--exitp nil "Whether to exit the transient.") +(defvar transient--showp nil "Whether to show the transient popup buffer.") +(defvar transient--helpp nil "Whether help-mode is active.") +(defvar transient--editp nil "Whether edit-mode is active.") + +(defvar transient--refreshp nil + "Whether to refresh the transient completely.") + +(defvar transient--all-levels-p nil + "Whether temporary display of suffixes on all levels is active.") + +(defvar transient--timer nil) + +(defvar transient--stack nil) + +(defvar transient--minibuffer-depth 0) + +(defvar transient--buffer-name " *transient*" + "Name of the transient buffer.") + +(defvar transient--buffer nil + "The transient menu buffer.") + +(defvar transient--window nil + "The window used to display the transient popup buffer.") + +(defvar transient--original-window nil + "The window that was selected before the transient was invoked. +Usually it remains selected while the transient is active.") + +(defvar transient--original-buffer nil + "The buffer that was current before the transient was invoked. +Usually it remains current while the transient is active.") + +(defvar transient--restore-winconf nil + "Window configuration to restore after exiting help.") + +(defvar transient--shadowed-buffer nil + "The buffer that is temporarily shadowed by the transient buffer. +This is bound while the suffix predicate is being evaluated and while +drawing in the transient buffer.") + +(defvar transient--pending-suffix nil + "The suffix that is currently being processed. +This is bound while the suffix predicate is being evaluated, +and while functions that return faces are being evaluated.") + +(defvar transient--pending-group nil + "The group that is currently being processed. +This is bound while the suffixes are drawn in the transient buffer.") + +(defvar transient--debug nil + "Whether to put debug information into *Messages*.") + +(defvar transient--history nil) + +(defvar transient--scroll-commands + '(transient-scroll-up + transient-scroll-down + mwheel-scroll + scroll-bar-toolkit-scroll)) + +;;; Identities + +(defun transient-active-prefix (&optional prefixes) + "Return the active transient object. + +Return nil if there is no active transient, if the transient buffer +isn't shown, and while the active transient is suspended (e.g., while +the minibuffer is in use). + +Unlike `transient-current-prefix', which is only ever non-nil in code +that is run directly by a command that is invoked while a transient +is current, this function is also suitable for use in asynchronous +code, such as timers and callbacks (this function's main use-case). + +If optional PREFIXES is non-nil, it must be a prefix command symbol +or a list of symbols, in which case the active transient object is +only returned if it matches one of PREFIXES." + (and transient--showp + transient--prefix + (or (not prefixes) + (memq (oref transient--prefix command) (ensure-list prefixes))) + (or (memq 'transient--pre-command pre-command-hook) + (and (memq t pre-command-hook) + (memq 'transient--pre-command + (default-value 'pre-command-hook)))) + transient--prefix)) + +(defun transient-prefix-object () + "Return the current prefix as an object. + +While a transient is being setup or refreshed (which involves +preparing its suffixes) the variable `transient--prefix' can be +used to access the prefix object. Thus this is what has to be +used in suffix methods such as `transient-format-description', +and in object-specific functions that are stored in suffix slots +such as `description'. + +When a suffix command is invoked (i.e., in its `interactive' form +and function body) then the variable `transient-current-prefix' +has to be used instead. + +Two distinct variables are needed, because any prefix may itself +be used as a suffix of another prefix, and such sub-prefixes have +to be able to tell themselves apart from the prefix they were +invoked from. + +Regular suffix commands, which are not prefixes, do not have to +concern themselves with this distinction, so they can use this +function instead. In the context of a plain suffix, it always +returns the value of the appropriate variable." + (or transient--prefix transient-current-prefix)) + +(defun transient-suffix-object (&optional command) + "Return the object associated with the current suffix command. + +Each suffix commands is associated with an object, which holds +additional information about the suffix, such as its value (in +the case of an infix command, which is a kind of suffix command). + +This function is intended to be called by infix commands, which +are usually aliases of `transient--default-infix-command', which +is defined like this: + + (defun transient--default-infix-command () + (interactive) + (let ((obj (transient-suffix-object))) + (transient-infix-set obj (transient-infix-read obj))) + (transient--show)) + +\(User input is read outside of `interactive' to prevent the +command from being added to `command-history'. See #23.) + +Such commands need to be able to access their associated object +to guide how `transient-infix-read' reads the new value and to +store the read value. Other suffix commands (including non-infix +commands) may also need the object to guide their behavior. + +This function attempts to return the object associated with the +current suffix command even if the suffix command was not invoked +from a transient. (For some suffix command that is a valid thing +to do, for others it is not.) In that case nil may be returned, +if the command was not defined using one of the macros intended +to define such commands. + +The optional argument COMMAND is intended for internal use. If +you are contemplating using it in your own code, then you should +probably use this instead: + + (get COMMAND \\='transient--suffix)" + (when command + (cl-check-type command command)) + (cond + (transient--pending-suffix) + ((or transient--prefix + transient-current-prefix) + (let ((suffixes + (cl-remove-if-not + (lambda (obj) + (eq (oref obj command) + (or command + (if (eq this-command 'transient-set-level) + ;; This is how it can look up for which + ;; command it is setting the level. + this-original-command + this-command)))) + (or transient--suffixes + transient-current-suffixes)))) + (or (and (cdr suffixes) + (cl-find-if + (lambda (obj) + (equal (listify-key-sequence (transient--kbd (oref obj key))) + (listify-key-sequence (this-command-keys)))) + suffixes)) + (car suffixes)))) + ((and-let* ((obj (transient--suffix-prototype (or command this-command))) + (obj (clone obj))) + (progn ; work around debbugs#31840 + (transient-init-scope obj) + (transient-init-value obj) + obj))))) + +(defun transient--suffix-prototype (command) + (or (get command 'transient--suffix) + (seq-some (lambda (cmd) (get cmd 'transient--suffix)) + (function-alias-p command)))) + +;;; Keymaps + +(defvar-keymap transient-base-map + :doc "Parent of other keymaps used by Transient. + +This is the parent keymap of all the keymaps that are used in +all transients: `transient-map' (which in turn is the parent +of the transient-specific keymaps), `transient-edit-map' and +`transient-sticky-map'. + +If you change a binding here, then you might also have to edit +`transient-sticky-map' and `transient-common-commands'. While +the latter isn't a proper transient prefix command, it can be +edited using the same functions as used for transients. + +If you add a new command here, then you must also add a binding +to `transient-predicate-map'." + "ESC ESC ESC" #'transient-quit-all + "C-g" #'transient-quit-one + "C-q" #'transient-quit-all + "C-z" #'transient-suspend + "C-v" #'transient-scroll-up + "C-M-v" #'transient-scroll-down + "<next>" #'transient-scroll-up + "<prior>" #'transient-scroll-down) + +(defvar transient-map + (let ((map (make-sparse-keymap))) + (set-keymap-parent map transient-base-map) + (keymap-set map "C-u" #'universal-argument) + (keymap-set map "C--" #'negative-argument) + (keymap-set map "C-t" #'transient-show) + (keymap-set map "?" #'transient-help) + (keymap-set map "C-h" #'transient-help) + ;; Also bound to "C-x p" and "C-x n" in transient-common-commands. + (keymap-set map "C-M-p" #'transient-history-prev) + (keymap-set map "C-M-n" #'transient-history-next) + (when (fboundp 'other-frame-prefix) ;Emacs >= 28.1 + (keymap-set map "C-x 5 5" 'other-frame-prefix) + (keymap-set map "C-x 4 4" 'other-window-prefix)) + map) + "Top-level keymap used by all transients. + +If you add a new command here, then you must also add a binding +to `transient-predicate-map'. Also see `transient-base-map'.") + +(defvar-keymap transient-edit-map + :doc "Keymap that is active while a transient in is in \"edit mode\"." + :parent transient-base-map + "?" #'transient-help + "C-h" #'transient-help + "C-x l" #'transient-set-level) + +(defvar-keymap transient-sticky-map + :doc "Keymap that is active while an incomplete key sequence is active." + :parent transient-base-map + "C-g" #'transient-quit-seq) + +(defvar transient--common-command-prefixes '(?\C-x)) + +(put 'transient-common-commands + 'transient--layout + (list + (eval + (car (transient--parse-child + 'transient-common-commands + (vector + :hide + (lambda () + (and (not (memq + (car (bound-and-true-p transient--redisplay-key)) + transient--common-command-prefixes)) + (not transient-show-common-commands))) + (vector + "Value commands" + (list "C-x s " "Set" #'transient-set) + (list "C-x C-s" "Save" #'transient-save) + (list "C-x C-k" "Reset" #'transient-reset) + (list "C-x p " "Previous value" #'transient-history-prev) + (list "C-x n " "Next value" #'transient-history-next)) + (vector + "Sticky commands" + ;; Like `transient-sticky-map' except that + ;; "C-g" has to be bound to a different command. + (list "C-g" "Quit prefix or transient" #'transient-quit-one) + (list "C-q" "Quit transient stack" #'transient-quit-all) + (list "C-z" "Suspend transient stack" #'transient-suspend)) + (vector + "Customize" + (list "C-x t" 'transient-toggle-common :description + (lambda () + (if transient-show-common-commands + "Hide common commands" + "Show common permanently"))) + (list "C-x l" "Show/hide suffixes" #'transient-set-level) + (list "C-x a" #'transient-toggle-level-limit))))) + t))) + +(defvar-keymap transient-popup-navigation-map + :doc "One of the keymaps used when popup navigation is enabled. +See `transient-enable-popup-navigation'." + "<down-mouse-1>" #'transient-noop + "<up>" #'transient-backward-button + "<down>" #'transient-forward-button + "C-r" #'transient-isearch-backward + "C-s" #'transient-isearch-forward + "M-RET" #'transient-push-button) + +(defvar-keymap transient-button-map + :doc "One of the keymaps used when popup navigation is enabled. +See `transient-enable-popup-navigation'." + "<mouse-1>" #'transient-push-button + "<mouse-2>" #'transient-push-button) + +(defvar-keymap transient-resume-mode-map + :doc "Keymap for `transient-resume-mode'. + +This keymap remaps every command that would usually just quit the +documentation buffer to `transient-resume', which additionally +resumes the suspended transient." + "<remap> <Man-quit>" #'transient-resume + "<remap> <Info-exit>" #'transient-resume + "<remap> <quit-window>" #'transient-resume) + +(defvar-keymap transient-predicate-map + :doc "Base keymap used to map common commands to their transient behavior. + +The \"transient behavior\" of a command controls, among other +things, whether invoking the command causes the transient to be +exited or not, and whether infix arguments are exported before +doing so. + +Each \"key\" is a command that is common to all transients and +that is bound in `transient-map', `transient-edit-map', +`transient-sticky-map' and/or `transient-common-command'. + +Each binding is a \"pre-command\", a function that controls the +transient behavior of the respective command. + +For transient commands that are bound in individual transients, +the transient behavior is specified using the `:transient' slot +of the corresponding object." + "<transient-suspend>" #'transient--do-suspend + "<transient-help>" #'transient--do-stay + "<transient-set-level>" #'transient--do-stay + "<transient-history-prev>" #'transient--do-stay + "<transient-history-next>" #'transient--do-stay + "<universal-argument>" #'transient--do-stay + "<universal-argument-more>" #'transient--do-stay + "<negative-argument>" #'transient--do-minus + "<digit-argument>" #'transient--do-stay + "<other-frame-prefix>" #'transient--do-stay + "<other-window-prefix>" #'transient--do-stay + "<top-level>" #'transient--do-quit-all + "<transient-quit-all>" #'transient--do-quit-all + "<transient-quit-one>" #'transient--do-quit-one + "<transient-quit-seq>" #'transient--do-stay + "<transient-show>" #'transient--do-stay + "<transient-update>" #'transient--do-stay + "<transient-toggle-common>" #'transient--do-stay + "<transient-set>" #'transient--do-call + "<transient-set-and-exit>" #'transient--do-exit + "<transient-save>" #'transient--do-call + "<transient-save-and-exit>" #'transient--do-exit + "<transient-reset>" #'transient--do-call + "<describe-key-briefly>" #'transient--do-stay + "<describe-key>" #'transient--do-stay + "<transient-scroll-up>" #'transient--do-stay + "<transient-scroll-down>" #'transient--do-stay + "<mwheel-scroll>" #'transient--do-stay + "<scroll-bar-toolkit-scroll>" #'transient--do-stay + "<transient-noop>" #'transient--do-noop + "<transient-mouse-push-button>" #'transient--do-move + "<transient-push-button>" #'transient--do-push-button + "<transient-backward-button>" #'transient--do-move + "<transient-forward-button>" #'transient--do-move + "<transient-isearch-backward>" #'transient--do-move + "<transient-isearch-forward>" #'transient--do-move + ;; If a valid but incomplete prefix sequence is followed by + ;; an unbound key, then Emacs calls the `undefined' command + ;; but does not set `this-command', `this-original-command' + ;; or `real-this-command' accordingly. Instead they are nil. + "<nil>" #'transient--do-warn + ;; Bound to the `mouse-movement' event, this command is similar + ;; to `ignore'. + "<ignore-preserving-kill-region>" #'transient--do-noop) + +(defvar transient--transient-map nil) +(defvar transient--predicate-map nil) +(defvar transient--redisplay-map nil) +(defvar transient--redisplay-key nil) + +(defun transient--push-keymap (var) + (let ((map (symbol-value var))) + (transient--debug " push %s%s" var (if map "" " VOID")) + (when map + (with-demoted-errors "transient--push-keymap: %S" + (internal-push-keymap map 'overriding-terminal-local-map))))) + +(defun transient--pop-keymap (var) + (let ((map (symbol-value var))) + (when map + (transient--debug " pop %s" var) + (with-demoted-errors "transient--pop-keymap: %S" + (internal-pop-keymap map 'overriding-terminal-local-map))))) + +(defun transient--make-transient-map () + (let ((map (make-sparse-keymap))) + (set-keymap-parent map (if transient--editp + transient-edit-map + transient-map)) + (dolist (obj transient--suffixes) + (let ((key (oref obj key))) + (when (vectorp key) + (setq key (key-description key)) + (oset obj key key)) + (when transient-substitute-key-function + (setq key (save-match-data + (funcall transient-substitute-key-function obj))) + (oset obj key key)) + (let* ((kbd (kbd key)) + (cmd (oref obj command)) + (alt (transient--lookup-key map kbd))) + (cond ((not alt) + (define-key map kbd cmd)) + ((eq alt cmd)) + ((transient--inapt-suffix-p obj)) + ((and-let* ((obj (transient-suffix-object alt))) + (transient--inapt-suffix-p obj)) + (define-key map kbd cmd)) + (transient-detect-key-conflicts + (error "Cannot bind %S to %s and also %s" + (string-trim key) cmd alt)) + ((define-key map kbd cmd)))))) + (when-let ((b (keymap-lookup map "-"))) (keymap-set map "<kp-subtract>" b)) + (when-let ((b (keymap-lookup map "="))) (keymap-set map "<kp-equal>" b)) + (when-let ((b (keymap-lookup map "+"))) (keymap-set map "<kp-add>" b)) + (when transient-enable-popup-navigation + ;; `transient--make-redisplay-map' maps only over bindings that are + ;; directly in the base keymap, so that cannot be a composed keymap. + (set-keymap-parent + map (make-composed-keymap + (keymap-parent map) + transient-popup-navigation-map))) + map)) + +(defun transient--make-predicate-map () + (let* ((default (transient--resolve-pre-command + (oref transient--prefix transient-suffix))) + (return (and transient--stack (eq default t))) + (map (make-sparse-keymap))) + (set-keymap-parent map transient-predicate-map) + (when (or (and (slot-boundp transient--prefix 'transient-switch-frame) + (transient--resolve-pre-command + (not (oref transient--prefix transient-switch-frame)))) + (memq (transient--resolve-pre-command + (oref transient--prefix transient-non-suffix)) + '(nil transient--do-warn transient--do-noop))) + (define-key map [handle-switch-frame] #'transient--do-suspend)) + (dolist (obj transient--suffixes) + (let* ((cmd (oref obj command)) + (kind (cond ((get cmd 'transient--prefix) 'prefix) + ((cl-typep obj 'transient-infix) 'infix) + (t 'suffix)))) + (cond + ((oref obj inapt) + (define-key map (vector cmd) #'transient--do-warn-inapt)) + ((slot-boundp obj 'transient) + (define-key map (vector cmd) + (pcase (list kind + (transient--resolve-pre-command (oref obj transient)) + return) + (`(prefix t ,_) #'transient--do-recurse) + (`(prefix nil ,_) #'transient--do-stack) + (`(infix t ,_) #'transient--do-stay) + (`(suffix t ,_) #'transient--do-call) + ('(suffix nil t) #'transient--do-return) + (`(,_ nil ,_) #'transient--do-exit) + (`(,_ ,do ,_) do)))) + ((not (lookup-key transient-predicate-map (vector cmd))) + (define-key map (vector cmd) + (pcase (list kind default return) + (`(prefix ,(or 'transient--do-stay 'transient--do-call) ,_) + #'transient--do-recurse) + (`(prefix t ,_) #'transient--do-recurse) + (`(prefix ,_ ,_) #'transient--do-stack) + (`(infix ,_ ,_) #'transient--do-stay) + (`(suffix t ,_) #'transient--do-call) + ('(suffix nil t) #'transient--do-return) + (`(suffix nil ,_) #'transient--do-exit) + (`(suffix ,do ,_) do))))))) + map)) + +(defun transient--make-redisplay-map () + (setq transient--redisplay-key + (pcase this-command + ('transient-update + (setq transient--showp t) + (setq unread-command-events + (listify-key-sequence (this-single-command-raw-keys)))) + ('transient-quit-seq + (setq unread-command-events + (butlast (listify-key-sequence + (this-single-command-raw-keys)) + 2)) + (butlast transient--redisplay-key)) + (_ nil))) + (let ((topmap (make-sparse-keymap)) + (submap (make-sparse-keymap))) + (when transient--redisplay-key + (define-key topmap (vconcat transient--redisplay-key) submap) + (set-keymap-parent submap transient-sticky-map)) + (map-keymap-internal + (lambda (key def) + (when (and (not (eq key ?\e)) + (listp def) + (keymapp def)) + (define-key topmap (vconcat transient--redisplay-key (list key)) + #'transient-update))) + (if transient--redisplay-key + (let ((key (vconcat transient--redisplay-key))) + (or (lookup-key transient--transient-map key) + (and-let* ((regular (lookup-key local-function-key-map key))) + (lookup-key transient--transient-map (vconcat regular))))) + transient--transient-map)) + topmap)) + +;;; Setup + +(defun transient-setup (&optional name layout edit &rest params) + "Setup the transient specified by NAME. + +This function is called by transient prefix commands to setup the +transient. In that case NAME is mandatory, LAYOUT and EDIT must +be nil and PARAMS may be (but usually is not) used to set, e.g., +the \"scope\" of the transient (see `transient-define-prefix'). + +This function is also called internally, in which case LAYOUT and +EDIT may be non-nil." + (transient--debug 'setup) + (transient--with-emergency-exit :setup + (cond + ((not name) + ;; Switching between regular and edit mode. + (transient--pop-keymap 'transient--transient-map) + (transient--pop-keymap 'transient--redisplay-map) + (setq name (oref transient--prefix command)) + (setq params (list :scope (oref transient--prefix scope)))) + (transient--prefix + ;; Invoked as a ":transient-non-suffix 'transient--do-{stay,call}" + ;; of an outer prefix. Unlike the usual `transient--do-stack', + ;; these predicates fail to clean up after the outer prefix. + (transient--pop-keymap 'transient--transient-map) + (transient--pop-keymap 'transient--redisplay-map)) + ((not (or layout ; resuming parent/suspended prefix + transient-current-command)) ; entering child prefix + (transient--stack-zap)) ; replace suspended prefix, if any + (edit + ;; Returning from help to edit. + (setq transient--editp t))) + (transient--init-objects name layout params) + (transient--init-keymaps) + (transient--history-init transient--prefix) + (setq transient--original-window (selected-window)) + (setq transient--original-buffer (current-buffer)) + (setq transient--minibuffer-depth (minibuffer-depth)) + (transient--redisplay) + (transient--init-transient) + (transient--suspend-which-key-mode))) + +(cl-defgeneric transient-setup-children (group children) + "Setup the CHILDREN of GROUP. +If the value of the `setup-children' slot is non-nil, then call +that function with CHILDREN as the only argument and return the +value. Otherwise return CHILDREN as is." + (if (slot-boundp group 'setup-children) + (funcall (oref group setup-children) children) + children)) + +(defun transient--init-keymaps () + (setq transient--predicate-map (transient--make-predicate-map)) + (setq transient--transient-map (transient--make-transient-map)) + (setq transient--redisplay-map (transient--make-redisplay-map))) + +(defun transient--init-objects (&optional name layout params) + (if name + (setq transient--prefix (transient--init-prefix name params)) + (setq name (oref transient--prefix command))) + (setq transient--refreshp (oref transient--prefix refresh-suffixes)) + (setq transient--layout (or layout (transient--init-suffixes name))) + (setq transient--suffixes (transient--flatten-suffixes transient--layout))) + +(defun transient--init-prefix (name &optional params) + (let ((obj (let ((proto (get name 'transient--prefix))) + (apply #'clone proto + :prototype proto + :level (or (alist-get t (alist-get name transient-levels)) + transient-default-level) + params)))) + (transient--setup-recursion obj) + (transient-init-value obj) + obj)) + +(defun transient--init-suffixes (name) + (let ((levels (alist-get name transient-levels))) + (cl-mapcan (lambda (c) (transient--init-child levels c nil)) + (append (get name 'transient--layout) + (and (not transient--editp) + (get 'transient-common-commands + 'transient--layout)))))) + +(defun transient--flatten-suffixes (layout) + (cl-labels ((s (def) + (cond + ((stringp def) nil) + ((cl-typep def 'transient-information) nil) + ((listp def) (cl-mapcan #'s def)) + ((cl-typep def 'transient-group) + (cl-mapcan #'s (oref def suffixes))) + ((cl-typep def 'transient-suffix) + (list def))))) + (cl-mapcan #'s layout))) + +(defun transient--init-child (levels spec parent) + (cl-etypecase spec + (vector (transient--init-group levels spec parent)) + (list (transient--init-suffix levels spec parent)) + (string (list spec)))) + +(defun transient--init-group (levels spec parent) + (pcase-let ((`(,level ,class ,args ,children) (append spec nil))) + (and-let* (((transient--use-level-p level)) + (obj (apply class :level level args)) + ((transient--use-suffix-p obj)) + ((prog1 t + (when (or (and parent (oref parent inapt)) + (transient--inapt-suffix-p obj)) + (oset obj inapt t)))) + (suffixes (cl-mapcan + (lambda (c) (transient--init-child levels c obj)) + (transient-setup-children obj children)))) + (progn ; work around debbugs#31840 + (oset obj suffixes suffixes) + (list obj))))) + +(defun transient--init-suffix (levels spec parent) + (pcase-let* ((`(,level ,class ,args) spec) + (cmd (plist-get args :command)) + (key (transient--kbd (plist-get args :key))) + (level (or (alist-get (cons cmd key) levels nil nil #'equal) + (alist-get cmd levels) + level))) + (let ((fn (and (symbolp cmd) + (symbol-function cmd)))) + (when (autoloadp fn) + (transient--debug " autoload %s" cmd) + (autoload-do-load fn))) + (when (transient--use-level-p level) + (let ((obj (if (child-of-class-p class 'transient-information) + (apply class :level level args) + (unless (and cmd (symbolp cmd)) + (error "BUG: Non-symbolic suffix command: %s" cmd)) + (if-let ((proto (and cmd (transient--suffix-prototype cmd)))) + (apply #'clone proto :level level args) + (apply class :command cmd :level level args))))) + (cond ((not cmd)) + ((commandp cmd)) + ((or (cl-typep obj 'transient-switch) + (cl-typep obj 'transient-option)) + ;; As a temporary special case, if the package was compiled + ;; with an older version of Transient, then we must define + ;; "anonymous" switch and option commands here. + (defalias cmd #'transient--default-infix-command)) + ((transient--use-suffix-p obj) + (error "Suffix command %s is not defined or autoloaded" cmd))) + (unless (cl-typep obj 'transient-information) + (transient--init-suffix-key obj)) + (when (transient--use-suffix-p obj) + (if (or (and parent (oref parent inapt)) + (transient--inapt-suffix-p obj)) + (oset obj inapt t) + (transient-init-scope obj) + (transient-init-value obj)) + (list obj)))))) + +(cl-defmethod transient--init-suffix-key ((obj transient-suffix)) + (unless (slot-boundp obj 'key) + (error "No key for %s" (oref obj command)))) + +(cl-defmethod transient--init-suffix-key ((obj transient-argument)) + (if (transient-switches--eieio-childp obj) + (cl-call-next-method obj) + (when-let* (((not (slot-boundp obj 'shortarg))) + (shortarg (transient--derive-shortarg (oref obj argument)))) + (oset obj shortarg shortarg)) + (unless (slot-boundp obj 'key) + (if (slot-boundp obj 'shortarg) + (oset obj key (oref obj shortarg)) + (error "No key for %s" (oref obj command)))))) + +(defun transient--use-level-p (level &optional edit) + (or transient--all-levels-p + (and transient--editp (not edit)) + (and (>= level 1) + (<= level (oref transient--prefix level))))) + +(defun transient--use-suffix-p (obj) + (let ((transient--shadowed-buffer (current-buffer)) + (transient--pending-suffix obj)) + (transient--do-suffix-p + (oref obj if) + (oref obj if-not) + (oref obj if-nil) + (oref obj if-non-nil) + (oref obj if-mode) + (oref obj if-not-mode) + (oref obj if-derived) + (oref obj if-not-derived) + t))) + +(defun transient--inapt-suffix-p (obj) + (let ((transient--shadowed-buffer (current-buffer)) + (transient--pending-suffix obj)) + (transient--do-suffix-p + (oref obj inapt-if) + (oref obj inapt-if-not) + (oref obj inapt-if-nil) + (oref obj inapt-if-non-nil) + (oref obj inapt-if-mode) + (oref obj inapt-if-not-mode) + (oref obj inapt-if-derived) + (oref obj inapt-if-not-derived) + nil))) + +(defun transient--do-suffix-p + (if if-not if-nil if-non-nil if-mode if-not-mode if-derived if-not-derived + default) + (cond + (if (funcall if)) + (if-not (not (funcall if-not))) + (if-non-nil (symbol-value if-non-nil)) + (if-nil (not (symbol-value if-nil))) + (if-mode (if (atom if-mode) + (eq major-mode if-mode) + (memq major-mode if-mode))) + (if-not-mode (not (if (atom if-not-mode) + (eq major-mode if-not-mode) + (memq major-mode if-not-mode)))) + (if-derived (if (or (atom if-derived) + (>= emacs-major-version 30)) + (derived-mode-p if-derived) + (apply #'derived-mode-p if-derived))) + (if-not-derived (not (if (or (atom if-not-derived) + (>= emacs-major-version 30)) + (derived-mode-p if-not-derived) + (apply #'derived-mode-p if-not-derived)))) + (default))) + +(defun transient--suffix-predicate (spec) + (let ((plist (nth 2 spec))) + (seq-some (lambda (prop) + (and-let* ((pred (plist-get plist prop))) + (list prop pred))) + '( :if :if-not + :if-nil :if-non-nil + :if-mode :if-not-mode + :if-derived :if-not-derived + :inapt-if :inapt-if-not + :inapt-if-nil :inapt-if-non-nil + :inapt-if-mode :inapt-if-not-mode + :inapt-if-derived :inapt-if-not-derived)))) + +;;; Flow-Control + +(defun transient--init-transient () + (transient--debug 'init-transient) + (transient--push-keymap 'transient--transient-map) + (transient--push-keymap 'transient--redisplay-map) + (add-hook 'pre-command-hook #'transient--pre-command) + (add-hook 'post-command-hook #'transient--post-command) + (advice-add 'recursive-edit :around #'transient--recursive-edit) + (when transient--exitp + ;; This prefix command was invoked as the suffix of another. + ;; Prevent `transient--post-command' from removing the hooks + ;; that we just added. + (setq transient--exitp 'replace))) + +(defun transient--refresh-transient () + (transient--debug 'refresh-transient) + (transient--pop-keymap 'transient--predicate-map) + (transient--pop-keymap 'transient--transient-map) + (transient--pop-keymap 'transient--redisplay-map) + (if (eq transient--refreshp 'updated-value) + ;; Preserve the prefix value this once, because the + ;; invoked suffix indicates that it has updated that. + (setq transient--refreshp (oref transient--prefix refresh-suffixes)) + ;; Otherwise update the prefix value from suffix values. + (oset transient--prefix value (transient-get-value))) + (transient--init-objects) + (transient--init-keymaps) + (transient--push-keymap 'transient--transient-map) + (transient--push-keymap 'transient--redisplay-map) + (transient--redisplay)) + +(defun transient--pre-command () + (transient--debug 'pre-command) + (transient--with-emergency-exit :pre-command + ;; The use of `overriding-terminal-local-map' does not prevent the + ;; lookup of command remappings in the overridden maps, which can + ;; lead to a suffix being remapped to a non-suffix. We have to undo + ;; the remapping in that case. However, remapping a non-suffix to + ;; another should remain possible. + (when (and (transient--get-pre-command this-original-command 'suffix) + (not (transient--get-pre-command this-command 'suffix))) + (setq this-command this-original-command)) + (cond + ((memq this-command '(transient-update transient-quit-seq)) + (transient--pop-keymap 'transient--redisplay-map)) + ((and transient--helpp + (not (memq this-command '(transient-quit-one + transient-quit-all)))) + (cond + ((transient-help) + (transient--do-suspend) + (setq this-command 'transient-suspend) + (transient--pre-exit)) + ((not (transient--edebug-command-p)) + (setq this-command 'transient-undefined)))) + ((and transient--editp + (transient-suffix-object) + (not (memq this-command '(transient-quit-one + transient-quit-all + transient-help)))) + (setq this-command 'transient-set-level) + (transient--wrap-command)) + (t + (setq transient--exitp nil) + (let ((exitp (eq (transient--call-pre-command) transient--exit))) + (transient--wrap-command) + (when exitp + (transient--pre-exit))))))) + +(defun transient--pre-exit () + (transient--debug 'pre-exit) + (transient--delete-window) + (transient--timer-cancel) + (transient--pop-keymap 'transient--transient-map) + (transient--pop-keymap 'transient--redisplay-map) + (unless transient--showp + (let ((message-log-max nil)) + (message ""))) + (setq transient--transient-map nil) + (setq transient--predicate-map nil) + (setq transient--redisplay-map nil) + (setq transient--redisplay-key nil) + (setq transient--helpp nil) + (setq transient--editp nil) + (setq transient--prefix nil) + (setq transient--layout nil) + (setq transient--suffixes nil) + (setq transient--original-window nil) + (setq transient--original-buffer nil) + (setq transient--window nil)) + +(defun transient--delete-window () + (when (window-live-p transient--window) + (let ((win transient--window) + (remain-in-minibuffer-window + (and (minibuffer-selected-window) + (selected-window)))) + (cond + ((eq (car (window-parameter win 'quit-restore)) 'other) + ;; Window used to display another buffer. + (set-window-parameter win 'no-other-window + (window-parameter win 'prev--no-other-window)) + (set-window-parameter win 'prev--no-other-window nil)) + ((with-demoted-errors "Error while exiting transient: %S" + (delete-window win)))) + (when (buffer-live-p transient--buffer) + (kill-buffer transient--buffer)) + (setq transient--buffer nil) + (when remain-in-minibuffer-window + (select-window remain-in-minibuffer-window))))) + +(defun transient--export () + (setq transient-current-prefix transient--prefix) + (setq transient-current-command (oref transient--prefix command)) + (setq transient-current-suffixes transient--suffixes) + (transient--history-push transient--prefix)) + +(defun transient--suspend-override (&optional nohide) + (transient--debug 'suspend-override) + (transient--timer-cancel) + (cond ((and (not nohide) transient-hide-during-minibuffer-read) + (transient--delete-window)) + ((and transient--prefix transient--redisplay-key) + (setq transient--redisplay-key nil) + (when transient--showp + (if-let ((win (minibuffer-selected-window))) + (with-selected-window win + (transient--show)) + (transient--show))))) + (transient--pop-keymap 'transient--transient-map) + (transient--pop-keymap 'transient--redisplay-map) + (remove-hook 'pre-command-hook #'transient--pre-command) + (remove-hook 'post-command-hook #'transient--post-command)) + +(defun transient--resume-override (&optional _ignore) + (transient--debug 'resume-override) + (when (and transient--showp transient-hide-during-minibuffer-read) + (transient--show)) + (transient--push-keymap 'transient--transient-map) + (transient--push-keymap 'transient--redisplay-map) + (add-hook 'pre-command-hook #'transient--pre-command) + (add-hook 'post-command-hook #'transient--post-command)) + +(defun transient--recursive-edit (fn) + (transient--debug 'recursive-edit) + (if (not transient--prefix) + (funcall fn) + (transient--suspend-override (bound-and-true-p edebug-active)) + (funcall fn) ; Already unwind protected. + (cond ((memq this-command '(top-level abort-recursive-edit)) + (setq transient--exitp t) + (transient--post-exit) + (transient--delete-window)) + (transient--prefix + (transient--resume-override))))) + +(defmacro transient--with-suspended-override (&rest body) + (let ((depth (make-symbol "depth")) + (setup (make-symbol "setup")) + (exit (make-symbol "exit"))) + `(if (and transient--transient-map + (memq transient--transient-map + overriding-terminal-local-map)) + (let ((,depth (1+ (minibuffer-depth))) ,setup ,exit) + (setq ,setup + (lambda () "@transient--with-suspended-override" + (transient--debug 'minibuffer-setup) + (remove-hook 'minibuffer-setup-hook ,setup) + (transient--suspend-override))) + (setq ,exit + (lambda () "@transient--with-suspended-override" + (transient--debug 'minibuffer-exit) + (when (= (minibuffer-depth) ,depth) + (transient--resume-override)))) + (unwind-protect + (progn + (add-hook 'minibuffer-setup-hook ,setup) + (add-hook 'minibuffer-exit-hook ,exit) + ,@body) + (remove-hook 'minibuffer-setup-hook ,setup) + (remove-hook 'minibuffer-exit-hook ,exit))) + ,@body))) + +(defun transient--wrap-command () + (static-if (>= emacs-major-version 30) + (letrec + ((prefix transient--prefix) + (suffix this-command) + (advice + (lambda (fn &rest args) + (interactive + (lambda (spec) + (let ((abort t)) + (unwind-protect + (prog1 (let ((debugger #'transient--exit-and-debug)) + (advice-eval-interactive-spec spec)) + (setq abort nil)) + (when abort + (when-let ((unwind (oref prefix unwind-suffix))) + (transient--debug 'unwind-interactive) + (funcall unwind suffix)) + (advice-remove suffix advice) + (oset prefix unwind-suffix nil)))))) + (unwind-protect + (let ((debugger #'transient--exit-and-debug)) + (apply fn args)) + (when-let ((unwind (oref prefix unwind-suffix))) + (transient--debug 'unwind-command) + (funcall unwind suffix)) + (advice-remove suffix advice) + (oset prefix unwind-suffix nil))))) + (when (symbolp this-command) + (advice-add suffix :around advice '((depth . -99)))) + (cl-assert + (>= emacs-major-version 30) nil + "Emacs was downgraded, making it necessary to recompile Transient")) + ;; (< emacs-major-version 30) + (let* ((prefix transient--prefix) + (suffix this-command) + (advice nil) + (advice-interactive + (lambda (spec) + (let ((abort t)) + (unwind-protect + (prog1 (let ((debugger #'transient--exit-and-debug)) + (advice-eval-interactive-spec spec)) + (setq abort nil)) + (when abort + (when-let ((unwind (oref prefix unwind-suffix))) + (transient--debug 'unwind-interactive) + (funcall unwind suffix)) + (advice-remove suffix advice) + (oset prefix unwind-suffix nil)))))) + (advice-body + (lambda (fn &rest args) + (unwind-protect + (let ((debugger #'transient--exit-and-debug)) + (apply fn args)) + (when-let ((unwind (oref prefix unwind-suffix))) + (transient--debug 'unwind-command) + (funcall unwind suffix)) + (advice-remove suffix advice) + (oset prefix unwind-suffix nil))))) + (setq advice `(lambda (fn &rest args) + (interactive ,advice-interactive) + (apply ',advice-body fn args))) + (when (symbolp this-command) + (advice-add suffix :around advice '((depth . -99))))))) + +(defun transient--premature-post-command () + (and (equal (this-command-keys-vector) []) + (= (minibuffer-depth) + (1+ transient--minibuffer-depth)) + (progn + (transient--debug 'premature-post-command) + (transient--suspend-override) + (oset (or transient--prefix transient-current-prefix) + unwind-suffix + (if transient--exitp + #'transient--post-exit + #'transient--resume-override)) + t))) + +(defun transient--post-command () + (unless (transient--premature-post-command) + (transient--debug 'post-command) + (transient--with-emergency-exit :post-command + (cond (transient--exitp (transient--post-exit)) + ;; If `this-command' is the current transient prefix, then we + ;; have already taken care of updating the transient buffer... + ((and (eq this-command (oref transient--prefix command)) + ;; ... but if `prefix-arg' is non-nil, then the values + ;; of `this-command' and `real-this-command' are untrue + ;; because `prefix-command-preserve-state' changes them. + ;; We cannot use `current-prefix-arg' because it is set + ;; too late (in `command-execute'), and if it were set + ;; earlier, then we likely still would not be able to + ;; rely on it, and `prefix-command-preserve-state-hook' + ;; would have to be used to record that a universal + ;; argument is in effect. + (not prefix-arg))) + (transient--refreshp + (transient--refresh-transient)) + ((let ((old transient--redisplay-map) + (new (transient--make-redisplay-map))) + (unless (equal old new) + (transient--pop-keymap 'transient--redisplay-map) + (setq transient--redisplay-map new) + (transient--push-keymap 'transient--redisplay-map)) + (transient--redisplay))))) + (setq transient-current-prefix nil) + (setq transient-current-command nil) + (setq transient-current-suffixes nil))) + +(defun transient--post-exit (&optional command) + (transient--debug 'post-exit) + (unless (and (eq transient--exitp 'replace) + (or transient--prefix + ;; The current command could act as a prefix, + ;; but decided not to call `transient-setup', + ;; or it is prevented from doing so because it + ;; uses the minibuffer and the user aborted + ;; that. + (prog1 nil + (if (let ((obj (transient-suffix-object command))) + (and (slot-boundp obj 'transient) + (oref obj transient))) + ;; This sub-prefix is a transient suffix; + ;; go back to outer prefix, by calling + ;; `transient--stack-pop' further down. + (setq transient--exitp nil) + (transient--stack-zap))))) + (remove-hook 'pre-command-hook #'transient--pre-command) + (remove-hook 'post-command-hook #'transient--post-command) + (advice-remove 'recursive-edit #'transient--recursive-edit)) + (let ((resume (and transient--stack + (not (memq transient--exitp '(replace suspend)))))) + (unless (or resume (eq transient--exitp 'replace)) + (setq transient--showp nil)) + (setq transient--exitp nil) + (setq transient--helpp nil) + (setq transient--editp nil) + (setq transient--all-levels-p nil) + (setq transient--minibuffer-depth 0) + (run-hooks 'transient-exit-hook) + (when resume + (transient--stack-pop)))) + +(defun transient--stack-push () + (transient--debug 'stack-push) + (push (list (oref transient--prefix command) + transient--layout + transient--editp + :transient-suffix (oref transient--prefix transient-suffix) + :scope (oref transient--prefix scope)) + transient--stack)) + +(defun transient--stack-pop () + (transient--debug 'stack-pop) + (and transient--stack + (prog1 t (apply #'transient-setup (pop transient--stack))))) + +(defun transient--stack-zap () + (transient--debug 'stack-zap) + (setq transient--stack nil)) + +(defun transient--redisplay () + (if (or (eq transient-show-popup t) + transient--showp) + (unless + (or (memq this-command transient--scroll-commands) + (and (or (memq this-command '(mouse-drag-region + mouse-set-region)) + (equal (key-description (this-command-keys-vector)) + "<mouse-movement>")) + (and (eq (current-buffer) transient--buffer)))) + (transient--show)) + (when (and (numberp transient-show-popup) + (not (zerop transient-show-popup)) + (not transient--timer)) + (transient--timer-start)) + (transient--show-brief))) + +(defun transient--timer-start () + (setq transient--timer + (run-at-time (abs transient-show-popup) nil + (lambda () + (transient--timer-cancel) + (transient--show) + (let ((message-log-max nil)) + (message "")))))) + +(defun transient--timer-cancel () + (when transient--timer + (cancel-timer transient--timer) + (setq transient--timer nil))) + +(defun transient--debug (arg &rest args) + (when transient--debug + (let ((inhibit-message (not (eq transient--debug 'message)))) + (if (symbolp arg) + (message "-- %-22s (cmd: %s, event: %S, exit: %s%s)" + arg + (cond ((and (symbolp this-command) this-command)) + ((fboundp 'help-fns-function-name) + (help-fns-function-name this-command)) + ((byte-code-function-p this-command) + "#[...]") + (this-command)) + (key-description (this-command-keys-vector)) + transient--exitp + (cond ((keywordp (car args)) + (format ", from: %s" + (substring (symbol-name (car args)) 1))) + ((stringp (car args)) + (concat ", " (apply #'format args))) + ((functionp (car args)) + (concat ", " (apply (car args) (cdr args)))) + (""))) + (apply #'message arg args))))) + +(defun transient--emergency-exit (&optional id) + "Exit the current transient command after an error occurred. +When no transient is active (i.e., when `transient--prefix' is +nil) then do nothing. Optional ID is a keyword identifying the +exit." + (transient--debug 'emergency-exit id) + (when transient--prefix + (setq transient--stack nil) + (setq transient--exitp t) + (transient--pre-exit) + (transient--post-exit))) + +;;; Pre-Commands + +(defun transient--call-pre-command () + (if-let ((fn (transient--get-pre-command this-command))) + (let ((action (funcall fn))) + (when (eq action transient--exit) + (setq transient--exitp (or transient--exitp t))) + action) + (if (let ((keys (this-command-keys-vector))) + (eq (aref keys (1- (length keys))) ?\C-g)) + (setq this-command 'transient-noop) + (unless (transient--edebug-command-p) + (setq this-command 'transient-undefined))) + transient--stay)) + +(defun transient--get-pre-command (&optional cmd enforce-type) + (or (and (not (eq enforce-type 'non-suffix)) + (symbolp cmd) + (lookup-key transient--predicate-map (vector cmd))) + (and (not (eq enforce-type 'suffix)) + (transient--resolve-pre-command + (oref transient--prefix transient-non-suffix) + t)))) + +(defun transient--resolve-pre-command (pre &optional resolve-boolean) + (cond ((booleanp pre) + (if resolve-boolean + (if pre #'transient--do-stay #'transient--do-warn) + pre)) + ((string-match-p "--do-" (symbol-name pre)) pre) + ((let ((sym (intern (format "transient--do-%s" pre)))) + (if (functionp sym) sym pre))))) + +(defun transient--do-stay () + "Call the command without exporting variables and stay transient." + transient--stay) + +(defun transient--do-noop () + "Call `transient-noop' and stay transient." + (setq this-command 'transient-noop) + transient--stay) + +(defun transient--do-warn () + "Call `transient-undefined' and stay transient." + (setq this-command 'transient-undefined) + transient--stay) + +(defun transient--do-warn-inapt () + "Call `transient-inapt' and stay transient." + (setq this-command 'transient-inapt) + transient--stay) + +(defun transient--do-call () + "Call the command after exporting variables and stay transient." + (transient--export) + transient--stay) + +(defun transient--do-return () + "Call the command after exporting variables and return to parent prefix. +If there is no parent prefix, then behave like `transient--do-exit'." + (if (not transient--stack) + (transient--do-exit) + (transient--export) + transient--exit)) + +(defun transient--do-exit () + "Call the command after exporting variables and exit the transient." + (transient--export) + (transient--stack-zap) + transient--exit) + +(defun transient--do-leave () + "Call the command without exporting variables and exit the transient." + (transient--stack-zap) + transient--exit) + +(defun transient--do-push-button () + "Call the command represented by the activated button. +Use that command's pre-command to determine transient behavior." + (if (and (mouse-event-p last-command-event) + (not (eq (posn-window (event-start last-command-event)) + transient--window))) + transient--stay + (setq this-command + (with-selected-window transient--window + (get-text-property (if (mouse-event-p last-command-event) + (posn-point (event-start last-command-event)) + (point)) + 'command))) + (transient--call-pre-command))) + +(defun transient--do-recurse () + "Call the transient prefix command, preparing for return to active transient. +If there is no parent prefix, then just call the command." + (transient--do-stack)) + +(defun transient--setup-recursion (prefix-obj) + (when transient--stack + (let ((command (oref prefix-obj command))) + (when-let ((suffix-obj (transient-suffix-object command))) + (when (memq (if (slot-boundp suffix-obj 'transient) + (oref suffix-obj transient) + (oref transient-current-prefix transient-suffix)) + (list t #'transient--do-recurse)) + (oset prefix-obj transient-suffix t)))))) + +(defun transient--do-stack () + "Call the transient prefix command, stacking the active transient. +Push the active transient to the transient stack." + (transient--export) + (transient--stack-push) + (setq transient--exitp 'replace) + transient--exit) + +(defun transient--do-replace () + "Call the transient prefix command, replacing the active transient. +Do not push the active transient to the transient stack." + (transient--export) + (setq transient--exitp 'replace) + transient--exit) + +(defun transient--do-suspend () + "Suspend the active transient, saving the transient stack." + (transient--stack-push) + (setq transient--exitp 'suspend) + transient--exit) + +(defun transient--do-quit-one () + "If active, quit help or edit mode, else exit the active transient." + (cond (transient--helpp + (setq transient--helpp nil) + transient--stay) + (transient--editp + (setq transient--editp nil) + (transient-setup) + transient--stay) + (prefix-arg + transient--stay) + (transient--exit))) + +(defun transient--do-quit-all () + "Exit all transients without saving the transient stack." + (transient--stack-zap) + transient--exit) + +(defun transient--do-move () + "Call the command if `transient-enable-popup-navigation' is non-nil. +In that case behave like `transient--do-stay', otherwise similar +to `transient--do-warn'." + (unless transient-enable-popup-navigation + (setq this-command 'transient-inhibit-move)) + transient--stay) + +(defun transient--do-minus () + "Call `negative-argument' or pivot to `transient-update'. +If `negative-argument' is invoked using \"-\" then preserve the +prefix argument and pivot to `transient-update'." + (when (equal (this-command-keys) "-") + (setq this-command 'transient-update)) + transient--stay) + +(put 'transient--do-stay 'transient-face 'transient-key-stay) +(put 'transient--do-noop 'transient-face 'transient-key-noop) +(put 'transient--do-warn 'transient-face 'transient-key-noop) +(put 'transient--do-warn-inapt 'transient-face 'transient-key-noop) +(put 'transient--do-call 'transient-face 'transient-key-stay) +(put 'transient--do-return 'transient-face 'transient-key-return) +(put 'transient--do-exit 'transient-face 'transient-key-exit) +(put 'transient--do-leave 'transient-face 'transient-key-exit) + +(put 'transient--do-recurse 'transient-face 'transient-key-stay) +(put 'transient--do-stack 'transient-face 'transient-key-stay) +(put 'transient--do-replace 'transient-face 'transient-key-exit) +(put 'transient--do-suspend 'transient-face 'transient-key-exit) + +(put 'transient--do-quit-one 'transient-face 'transient-key-return) +(put 'transient--do-quit-all 'transient-face 'transient-key-exit) +(put 'transient--do-move 'transient-face 'transient-key-stay) +(put 'transient--do-minus 'transient-face 'transient-key-stay) + +;;; Commands +;;;; Noop + +(defun transient-noop () + "Do nothing at all." + (interactive)) + +(defun transient-undefined () + "Warn the user that the pressed key is not bound to any suffix." + (interactive) + (transient--invalid "Unbound suffix")) + +(defun transient-inapt () + "Warn the user that the invoked command is inapt." + (interactive) + (transient--invalid "Inapt command")) + +(defun transient--invalid (msg) + (ding) + (message "%s: `%s' (Use `%s' to abort, `%s' for help)%s" + msg + (propertize (key-description (this-single-command-keys)) + 'face 'font-lock-warning-face) + (propertize "C-g" 'face 'transient-key) + (propertize "?" 'face 'transient-key) + ;; `this-command' is `transient-undefined' or `transient-inapt'. + ;; Show the command (`this-original-command') the user actually + ;; tried to invoke. + (if-let ((cmd (or (ignore-errors (symbol-name this-original-command)) + (ignore-errors (symbol-name this-command))))) + (format " [%s]" (propertize cmd 'face 'font-lock-warning-face)) + "")) + (unless (and transient--transient-map + (memq transient--transient-map overriding-terminal-local-map)) + (let ((transient--prefix (or transient--prefix 'sic))) + (transient--emergency-exit)) + (view-lossage) + (other-window 1) + (display-warning 'transient "Inconsistent transient state detected. +This should never happen. +Please open an issue and post the shown command log." :error))) + +(defun transient-inhibit-move () + "Warn the user that popup navigation is disabled." + (interactive) + (message "To enable use of `%s', please customize `%s'" + this-original-command + 'transient-enable-popup-navigation)) + +;;;; Core + +(defun transient-quit-all () + "Exit all transients without saving the transient stack." + (interactive)) + +(defun transient-quit-one () + "Exit the current transients, returning to outer transient, if any." + (interactive)) + +(defun transient-quit-seq () + "Abort the current incomplete key sequence." + (interactive)) + +(defun transient-update () + "Redraw the transient's state in the popup buffer." + (interactive) + (setq prefix-arg current-prefix-arg)) + +(defun transient-show () + "Show the transient's state in the popup buffer." + (interactive) + (setq transient--showp t)) + +(defun transient-push-button () + "Invoke the suffix command represented by this button." + (interactive)) + +;;;; Suspend + +(defun transient-suspend () + "Suspend the current transient. +It can later be resumed using `transient-resume', while no other +transient is active." + (interactive)) + +(define-minor-mode transient-resume-mode + "Auxiliary minor-mode used to resume a transient after viewing help.") + +(defun transient-resume () + "Resume a previously suspended stack of transients." + (interactive) + (cond (transient--stack + (let ((winconf transient--restore-winconf)) + (kill-local-variable 'transient--restore-winconf) + (when transient-resume-mode + (transient-resume-mode -1) + (quit-window)) + (when winconf + (set-window-configuration winconf))) + (transient--stack-pop)) + (transient-resume-mode + (kill-local-variable 'transient--restore-winconf) + (transient-resume-mode -1) + (quit-window)) + (t + (message "No suspended transient command")))) + +;;;; Help + +(defun transient-help (&optional interactive) + "Show help for the active transient or one of its suffixes.\n\n(fn)" + (interactive (list t)) + (if interactive + (setq transient--helpp t) + (with-demoted-errors "transient-help: %S" + (when (lookup-key transient--transient-map + (this-single-command-raw-keys)) + (setq transient--helpp nil) + (let ((winconf (current-window-configuration))) + (transient-show-help + (if (eq this-original-command 'transient-help) + transient--prefix + (or (transient-suffix-object) + this-original-command))) + (setq-local transient--restore-winconf winconf)) + (fit-window-to-buffer nil (frame-height) (window-height)) + (transient-resume-mode) + (message (substitute-command-keys + "Type \\`q' to resume transient command.")) + t)))) + +;;;; Level + +(defun transient-set-level (&optional command level) + "Set the level of the transient or one of its suffix commands." + (interactive + (let ((command this-original-command) + (prefix (oref transient--prefix command))) + (and (or (not (eq command 'transient-set-level)) + (and transient--editp + (setq command prefix))) + (list command + (let ((keys (this-single-command-raw-keys))) + (and (lookup-key transient--transient-map keys) + (progn + (transient--show) + (string-to-number + (transient--read-number-N + (format "Set level for `%s': " command) + nil nil (not (eq command prefix))))))))))) + (cond + ((not command) + (setq transient--editp t) + (transient-setup)) + (level + (let* ((prefix (oref transient--prefix command)) + (alist (alist-get prefix transient-levels)) + (akey command)) + (cond ((eq command prefix) + (oset transient--prefix level level) + (setq akey t)) + (t + (oset (transient-suffix-object command) level level) + (when (cdr (cl-remove-if-not (lambda (obj) + (eq (oref obj command) command)) + transient--suffixes)) + (setq akey (cons command (this-command-keys)))))) + (setf (alist-get akey alist) level) + (setf (alist-get prefix transient-levels) alist)) + (transient-save-levels) + (transient--show)) + (t + (transient-undefined)))) + +(transient-define-suffix transient-toggle-level-limit () + "Toggle whether to temporarily displayed suffixes on all levels." + :description + (lambda () + (cond + ((= transient-default-level transient--max-level) + "Always displaying all levels") + (transient--all-levels-p + (format "Hide suffix %s" + (propertize + (format "levels > %s" (oref (transient-prefix-object) level)) + 'face 'transient-higher-level))) + ("Show all suffix levels"))) + :inapt-if (lambda () (= transient-default-level transient--max-level)) + :transient t + (interactive) + (setq transient--all-levels-p (not transient--all-levels-p)) + (setq transient--refreshp t)) + +;;;; Value + +(defun transient-set () + "Set active transient's value for this Emacs session." + (interactive) + (transient-set-value (transient-prefix-object))) + +(defalias 'transient-set-and-exit #'transient-set + "Set active transient's value for this Emacs session and exit.") + +(defun transient-save () + "Save active transient's value for this and future Emacs sessions." + (interactive) + (transient-save-value (transient-prefix-object))) + +(defalias 'transient-save-and-exit #'transient-save + "Save active transient's value for this and future Emacs sessions and exit.") + +(defun transient-reset () + "Clear the set and saved values of the active transient." + (interactive) + (transient-reset-value (transient-prefix-object))) + +(defun transient-history-next () + "Switch to the next value used for the active transient." + (interactive) + (let* ((obj transient--prefix) + (pos (1- (oref obj history-pos))) + (hst (oref obj history))) + (if (< pos 0) + (user-error "End of history") + (oset obj history-pos pos) + (oset obj value (nth pos hst)) + (mapc #'transient-init-value transient--suffixes)))) + +(defun transient-history-prev () + "Switch to the previous value used for the active transient." + (interactive) + (let* ((obj transient--prefix) + (pos (1+ (oref obj history-pos))) + (hst (oref obj history)) + (len (length hst))) + (if (> pos (1- len)) + (user-error "End of history") + (oset obj history-pos pos) + (oset obj value (nth pos hst)) + (mapc #'transient-init-value transient--suffixes)))) + +(transient-define-suffix transient-preset () + "Put this preset into action." + :class transient-value-preset + (interactive) + (transient-prefix-set (oref (transient-suffix-object) set))) + +;;;; Auxiliary + +(defun transient-toggle-common () + "Toggle whether common commands are permanently shown." + (interactive) + (setq transient-show-common-commands (not transient-show-common-commands))) + +(defun transient-toggle-debug () + "Toggle debugging statements for transient commands." + (interactive) + (setq transient--debug (not transient--debug)) + (message "Debugging transient %s" + (if transient--debug "enabled" "disabled"))) + +(transient-define-suffix transient-echo-arguments (arguments) + "Show the transient's active ARGUMENTS in the echo area. +Intended for use in prefixes used for demonstration purposes, +such as when suggesting a new feature or reporting an issue." + :transient t + :description "Echo arguments" + :key "x" + (interactive (list (transient-args transient-current-command))) + (message "%s: %s" + (key-description (this-command-keys)) + (mapconcat (lambda (arg) + (propertize (if (string-match-p " " arg) + (format "%S" arg) + arg) + 'face 'transient-argument)) + arguments " "))) + +;;; Value +;;;; Init + +(cl-defgeneric transient-init-scope (obj) + "Set the scope of the suffix object OBJ. + +The scope is actually a property of the transient prefix, not of +individual suffixes. However it is possible to invoke a suffix +command directly instead of from a transient. In that case, if +the suffix expects a scope, then it has to determine that itself +and store it in its `scope' slot. + +This function is called for all suffix commands, but unless a +concrete method is implemented this falls through to the default +implementation, which is a noop.") + +(cl-defmethod transient-init-scope ((_ transient-suffix)) + "Noop." nil) + +(cl-defgeneric transient-init-value (_) + "Set the initial value of the object OBJ. + +This function is called for all prefix and suffix commands. + +For suffix commands (including infix argument commands) the +default implementation is a noop. Classes derived from the +abstract `transient-infix' class must implement this function. +Non-infix suffix commands usually don't have a value." + nil) + +(cl-defmethod transient-init-value :around ((obj transient-prefix)) + "If bound, then call OBJ's `init-value' function. +Otherwise call the primary method according to object's class." + (if (slot-boundp obj 'init-value) + (funcall (oref obj init-value) obj) + (cl-call-next-method obj))) + +(cl-defmethod transient-init-value :around ((obj transient-infix)) + "If bound, then call OBJ's `init-value' function. +Otherwise call the primary method according to object's class." + (if (slot-boundp obj 'init-value) + (funcall (oref obj init-value) obj) + (cl-call-next-method obj))) + +(cl-defmethod transient-init-value ((obj transient-prefix)) + (if (slot-boundp obj 'value) + (oref obj value) + (oset obj value + (if-let ((saved (assq (oref obj command) transient-values))) + (cdr saved) + (transient-default-value obj))))) + +(cl-defmethod transient-init-value ((obj transient-argument)) + (oset obj value + (let ((value (oref transient--prefix value)) + (argument (and (slot-boundp obj 'argument) + (oref obj argument))) + (multi-value (oref obj multi-value)) + (case-fold-search nil) + (regexp (if (slot-exists-p obj 'argument-regexp) + (oref obj argument-regexp) + (format "\\`%s\\(.*\\)" (oref obj argument))))) + (if (memq multi-value '(t rest)) + (cdr (assoc argument value)) + (let ((match (lambda (v) + (and (stringp v) + (string-match regexp v) + (match-string 1 v))))) + (if multi-value + (delq nil (mapcar match value)) + (cl-some match value))))))) + +(cl-defmethod transient-init-value ((obj transient-switch)) + (oset obj value + (car (member (oref obj argument) + (oref transient--prefix value))))) + +;;;; Default + +(cl-defgeneric transient-default-value (_) + "Return the default value." + nil) + +(cl-defmethod transient-default-value ((obj transient-prefix)) + (if-let ((default (and (slot-boundp obj 'default-value) + (oref obj default-value)))) + (if (functionp default) + (funcall default) + default) + nil)) + +;;;; Read + +(cl-defgeneric transient-infix-read (obj) + "Determine the new value of the infix object OBJ. + +This function merely determines the value; `transient-infix-set' +is used to actually store the new value in the object. + +For most infix classes this is done by reading a value from the +user using the reader specified by the `reader' slot (using the +`transient-infix' method described below). + +For some infix classes the value is changed without reading +anything in the minibuffer, i.e., the mere act of invoking the +infix command determines what the new value should be, based +on the previous value.") + +(cl-defmethod transient-infix-read :around ((obj transient-infix)) + "Refresh the transient buffer and call the next method. + +Also wrap `cl-call-next-method' with two macros: +- `transient--with-suspended-override' allows use of minibuffer. +- `transient--with-emergency-exit' arranges for the transient to + be exited in case of an error." + (transient--show) + (transient--with-emergency-exit :infix-read + (transient--with-suspended-override + (cl-call-next-method obj)))) + +(cl-defmethod transient-infix-read ((obj transient-infix)) + "Read a value while taking care of history. + +This method is suitable for a wide variety of infix commands, +including but not limited to inline arguments and variables. + +If you do not use this method for your own infix class, then +you should likely replicate a lot of the behavior of this +method. If you fail to do so, then users might not appreciate +the lack of history, for example. + +Only for very simple classes that toggle or cycle through a very +limited number of possible values should you replace this with a +simple method that does not handle history. (E.g., for a command +line switch the only possible values are \"use it\" and \"don't use +it\", in which case it is pointless to preserve history.)" + (with-slots (value multi-value always-read allow-empty choices) obj + (if (and value + (not multi-value) + (not always-read) + transient--prefix) + (oset obj value nil) + (let* ((enable-recursive-minibuffers t) + (reader (oref obj reader)) + (choices (if (functionp choices) (funcall choices) choices)) + (prompt (transient-prompt obj)) + (value (if multi-value (string-join value ",") value)) + (history-key (or (oref obj history-key) + (oref obj command))) + (transient--history (alist-get history-key transient-history)) + (transient--history (if (or (null value) + (eq value (car transient--history))) + transient--history + (cons value transient--history))) + (initial-input (and transient-read-with-initial-input + (car transient--history))) + (history (if initial-input + (cons 'transient--history 1) + 'transient--history)) + (value + (cond + (reader (funcall reader prompt initial-input history)) + (multi-value + (completing-read-multiple prompt choices nil nil + initial-input history)) + (choices + (completing-read prompt choices nil t initial-input history)) + ((read-string prompt initial-input history))))) + (cond ((and (equal value "") (not allow-empty)) + (setq value nil)) + ((and (equal value "\"\"") allow-empty) + (setq value ""))) + (when value + (when (and (bound-and-true-p ivy-mode) + (stringp (car transient--history))) + (set-text-properties 0 (length (car transient--history)) nil + (car transient--history))) + (setf (alist-get history-key transient-history) + (delete-dups transient--history))) + value)))) + +(cl-defmethod transient-infix-read ((obj transient-switch)) + "Toggle the switch on or off." + (if (oref obj value) nil (oref obj argument))) + +(cl-defmethod transient-infix-read ((obj transient-switches)) + "Cycle through the mutually exclusive switches. +The last value is \"don't use any of these switches\"." + (let ((choices (mapcar (apply-partially #'format (oref obj argument-format)) + (oref obj choices)))) + (if-let ((value (oref obj value))) + (cadr (member value choices)) + (car choices)))) + +(cl-defmethod transient-infix-read ((command symbol)) + "Elsewhere use the reader of the infix command COMMAND. +Use this if you want to share an infix's history with a regular +stand-alone command." + (if-let ((obj (transient--suffix-prototype command))) + (cl-letf (((symbol-function #'transient--show) #'ignore)) + (transient-infix-read obj)) + (error "Not a suffix command: `%s'" command))) + +;;;; Readers + +(defun transient-read-file (prompt _initial-input _history) + "Read a file." + (file-local-name (expand-file-name (read-file-name prompt)))) + +(defun transient-read-existing-file (prompt _initial-input _history) + "Read an existing file." + (file-local-name (expand-file-name (read-file-name prompt nil nil t)))) + +(defun transient-read-directory (prompt _initial-input _history) + "Read a directory." + (file-local-name (expand-file-name (read-directory-name prompt)))) + +(defun transient-read-existing-directory (prompt _initial-input _history) + "Read an existing directory." + (file-local-name (expand-file-name (read-directory-name prompt nil nil t)))) + +(defun transient-read-number-N0 (prompt initial-input history) + "Read a natural number (including zero) and return it as a string." + (transient--read-number-N prompt initial-input history t)) + +(defun transient-read-number-N+ (prompt initial-input history) + "Read a natural number (excluding zero) and return it as a string." + (transient--read-number-N prompt initial-input history nil)) + +(defun transient--read-number-N (prompt initial-input history include-zero) + (save-match-data + (cl-block nil + (while t + (let ((str (read-from-minibuffer prompt initial-input nil nil history))) + (when (or (string-equal str "") + (string-match-p (if include-zero + "\\`\\(0\\|[1-9][0-9]*\\)\\'" + "\\`[1-9][0-9]*\\'") + str)) + (cl-return str))) + (message "Please enter a natural number (%s zero)." + (if include-zero "including" "excluding")) + (sit-for 1))))) + +(defun transient-read-date (prompt default-time _history) + "Read a date using `org-read-date' (which see)." + (require 'org) + (when (fboundp 'org-read-date) + (org-read-date 'with-time nil nil prompt default-time))) + +;;;; Prompt + +(cl-defgeneric transient-prompt (obj) + "Return the prompt to be used to read infix object OBJ's value.") + +(cl-defmethod transient-prompt ((obj transient-infix)) + "Return the prompt to be used to read infix object OBJ's value. + +This implementation should be suitable for almost all infix +commands. + +If the value of OBJ's `prompt' slot is non-nil, then it must be +a string or a function. If it is a string, then use that. If +it is a function, then call that with OBJ as the only argument. +That function must return a string, which is then used as the +prompt. + +Otherwise, if the value of either the `argument' or `variable' +slot of OBJ is a string, then base the prompt on that (preferring +the former), appending either \"=\" (if it appears to be a +command-line option) or \": \". + +Finally fall through to using \"(BUG: no prompt): \" as the +prompt." + (if-let ((prompt (oref obj prompt))) + (let ((prompt (if (functionp prompt) + (funcall prompt obj) + prompt))) + (if (stringp prompt) + prompt + "(BUG: no prompt): ")) + (or (and-let* ((arg (and (slot-boundp obj 'argument) (oref obj argument)))) + (if (and (stringp arg) (string-suffix-p "=" arg)) + arg + (concat arg ": "))) + (and-let* ((var (and (slot-boundp obj 'variable) (oref obj variable)))) + (and (stringp var) + (concat var ": "))) + "(BUG: no prompt): "))) + +;;;; Set + +(cl-defgeneric transient-infix-set (obj value) + "Set the value of infix object OBJ to VALUE.") + +(cl-defmethod transient-infix-set ((obj transient-infix) value) + "Set the value of infix object OBJ to VALUE." + (oset obj value value)) + +(cl-defmethod transient-infix-set :after ((obj transient-argument) value) + "Unset incompatible infix arguments." + (when-let* ((value) + (val (transient-infix-value obj)) + (arg (if (slot-boundp obj 'argument) + (oref obj argument) + (oref obj argument-format))) + (spec (oref transient--prefix incompatible)) + (filter (lambda (x rule) + (and (member x rule) + (remove x rule)))) + (incomp (nconc + (cl-mapcan (apply-partially filter arg) spec) + (and (not (equal val arg)) + (cl-mapcan (apply-partially filter val) spec))))) + (dolist (obj transient--suffixes) + (when-let* (((cl-typep obj 'transient-argument)) + (val (transient-infix-value obj)) + (arg (if (slot-boundp obj 'argument) + (oref obj argument) + (oref obj argument-format))) + ((if (equal val arg) + (member arg incomp) + (or (member val incomp) + (member arg incomp))))) + (transient-infix-set obj nil))))) + +(defun transient-prefix-set (value) + "Set the value of the active transient prefix to VALUE. +Intended for use by transient suffix commands." + (oset transient--prefix value value) + (setq transient--refreshp 'updated-value)) + +(cl-defgeneric transient-set-value (obj) + "Persist the value of the transient prefix OBJ. +Only intended for use by `transient-set'. +Also see `transient-prefix-set'.") + +(cl-defmethod transient-set-value ((obj transient-prefix)) + (oset (oref obj prototype) value (transient-get-value)) + (transient--history-push obj)) + +;;;; Save + +(cl-defgeneric transient-save-value (obj) + "Save the value of the transient prefix OBJ.") + +(cl-defmethod transient-save-value ((obj transient-prefix)) + (let ((value (transient-get-value))) + (oset (oref obj prototype) value value) + (setf (alist-get (oref obj command) transient-values) value) + (transient-save-values)) + (transient--history-push obj)) + +;;;; Reset + +(cl-defgeneric transient-reset-value (obj) + "Clear the set and saved values of the transient prefix OBJ.") + +(cl-defmethod transient-reset-value ((obj transient-prefix)) + (let ((value (transient-default-value obj))) + (oset obj value value) + (oset (oref obj prototype) value value) + (setf (alist-get (oref obj command) transient-values nil 'remove) nil) + (transient-save-values)) + (transient--history-push obj) + (mapc #'transient-init-value transient--suffixes)) + +;;;; Get + +(defun transient-args (prefix) + "Return the value of the transient prefix command PREFIX. +If the current command was invoked from the transient prefix +command PREFIX, then return the active infix arguments. If +the current command was not invoked from PREFIX, then return +the set, saved or default value for PREFIX." + (cl-mapcan #'transient--get-wrapped-value (transient-suffixes prefix))) + +(defun transient-suffixes (prefix) + "Return the suffix objects of the transient prefix command PREFIX." + (if (eq transient-current-command prefix) + transient-current-suffixes + (let ((transient--prefix (transient--init-prefix prefix))) + (transient--flatten-suffixes + (transient--init-suffixes prefix))))) + +(defun transient-get-value () + (transient--with-emergency-exit :get-value + (cl-mapcan (lambda (obj) + (and (or (not (slot-exists-p obj 'unsavable)) + (not (oref obj unsavable))) + (transient--get-wrapped-value obj))) + (or transient--suffixes transient-current-suffixes)))) + +(defun transient--get-wrapped-value (obj) + (and-let* ((value (transient-infix-value obj))) + (pcase-exhaustive (and (slot-exists-p obj 'multi-value) + (oref obj multi-value)) + ('nil (list value)) + ((or 't 'rest) (list value)) + ('repeat value)))) + +(cl-defgeneric transient-infix-value (obj) + "Return the value of the suffix object OBJ. + +This function is called by `transient-args' (which see), meaning +this function is how the value of a transient is determined so +that the invoked suffix command can use it. + +Currently most values are strings, but that is not set in stone. +Nil is not a value, it means \"no value\". + +Usually only infixes have a value, but see the method for +`transient-suffix'.") + +(cl-defmethod transient-infix-value ((_ transient-suffix)) + "Return nil, which means \"no value\". + +Infix arguments contribute the transient's value while suffix +commands consume it. This function is called for suffixes anyway +because a command that both contributes to the transient's value +and also consumes it is not completely unconceivable. + +If you define such a command, then you must define a derived +class and implement this function because this default method +does nothing." nil) + +(cl-defmethod transient-infix-value ((obj transient-infix)) + "Return the value of OBJ's `value' slot." + (oref obj value)) + +(cl-defmethod transient-infix-value ((obj transient-option)) + "Return ARGUMENT and VALUE as a unit or nil if the latter is nil." + (and-let* ((value (oref obj value))) + (let ((arg (oref obj argument))) + (pcase-exhaustive (oref obj multi-value) + ('nil (concat arg value)) + ((or 't 'rest) (cons arg value)) + ('repeat (mapcar (lambda (v) (concat arg v)) value)))))) + +(cl-defmethod transient-infix-value ((_ transient-variable)) + "Return nil, which means \"no value\". + +Setting the value of a variable is done by, well, setting the +value of the variable. I.e., this is a side-effect and does +not contribute to the value of the transient." + nil) + +;;;; Utilities + +(defun transient-arg-value (arg args) + "Return the value of ARG as it appears in ARGS. + +For a switch return a boolean. For an option return the value as +a string, using the empty string for the empty value, or nil if +the option does not appear in ARGS." + (if (string-suffix-p "=" arg) + (save-match-data + (and-let* ((match (let ((case-fold-search nil) + (re (format "\\`%s\\(?:=\\(.+\\)\\)?\\'" + (substring arg 0 -1)))) + (cl-find-if (lambda (a) + (and (stringp a) + (string-match re a))) + args)))) + (or (match-string 1 match) ""))) + (and (member arg args) t))) + +(defun transient-scope () + "Return the value of the `scope' slot of the current prefix." + (oref (transient-prefix-object) scope)) + +;;; History + +(cl-defgeneric transient--history-key (obj) + "Return OBJ's history key. +If the value of the `history-key' slot is non-nil, then return +that. Otherwise return the value of the `command' slot." + (or (oref obj history-key) + (oref obj command))) + +(cl-defgeneric transient--history-push (obj) + "Push the current value of OBJ to its entry in `transient-history'." + (let ((key (transient--history-key obj))) + (setf (alist-get key transient-history) + (let ((args (transient-get-value))) + (cons args (delete args (alist-get key transient-history))))))) + +(cl-defgeneric transient--history-init (obj) + "Initialize OBJ's `history' slot. +This is the transient-wide history; many individual infixes also +have a history of their own.") + +(cl-defmethod transient--history-init ((obj transient-prefix)) + "Initialize OBJ's `history' slot from the variable `transient-history'." + (let ((val (oref obj value))) + (oset obj history + (cons val (delete val (alist-get (transient--history-key obj) + transient-history)))))) + +;;; Draw + +(defun transient--show-brief () + (let ((message-log-max nil)) + (if (and transient-show-popup (<= transient-show-popup 0)) + (message "%s-" (key-description (this-command-keys))) + (message + "%s- [%s] %s" + (key-description (this-command-keys)) + (oref transient--prefix command) + (mapconcat + #'identity + (sort + (cl-mapcan + (lambda (suffix) + (let ((key (kbd (oref suffix key)))) + ;; Don't list any common commands. + (and (not (memq (oref suffix command) + `(,(lookup-key transient-map key) + ,(lookup-key transient-sticky-map key) + ;; From transient-common-commands: + transient-set + transient-save + transient-history-prev + transient-history-next + transient-quit-one + transient-toggle-common + transient-set-level))) + (list (propertize (oref suffix key) 'face 'transient-key))))) + transient--suffixes) + #'string<) + (propertize "|" 'face 'transient-delimiter)))))) + +(defun transient--show () + (transient--timer-cancel) + (setq transient--showp t) + (let ((transient--shadowed-buffer (current-buffer)) + (focus nil)) + (setq transient--buffer (get-buffer-create transient--buffer-name)) + (with-current-buffer transient--buffer + (when transient-enable-popup-navigation + (setq focus (or (button-get (point) 'command) + (and (not (bobp)) + (button-get (1- (point)) 'command)) + (transient--heading-at-point)))) + (erase-buffer) + (run-hooks 'transient-setup-buffer-hook) + (when transient-force-fixed-pitch + (transient--force-fixed-pitch)) + (setq window-size-fixed t) + (when (bound-and-true-p tab-line-format) + (setq tab-line-format nil)) + (setq header-line-format nil) + (setq mode-line-format + (if (or (natnump transient-mode-line-format) + (eq transient-mode-line-format 'line)) + nil + transient-mode-line-format)) + (setq mode-line-buffer-identification + (symbol-name (oref transient--prefix command))) + (if transient-enable-popup-navigation + (setq-local cursor-in-non-selected-windows 'box) + (setq cursor-type nil)) + (setq display-line-numbers nil) + (setq show-trailing-whitespace nil) + (transient--insert-groups) + (when (or transient--helpp transient--editp) + (transient--insert-help)) + (when-let ((line (transient--separator-line))) + (insert line))) + (unless (window-live-p transient--window) + (setq transient--window + (display-buffer transient--buffer + transient-display-buffer-action))) + (when (window-live-p transient--window) + (with-selected-window transient--window + (set-window-parameter nil 'prev--no-other-window + (window-parameter nil 'no-other-window)) + (set-window-parameter nil 'no-other-window t) + (goto-char (point-min)) + (when transient-enable-popup-navigation + (transient--goto-button focus)) + (transient--fit-window-to-buffer transient--window))))) + +(defun transient--fit-window-to-buffer (window) + (let ((window-resize-pixelwise t) + (window-size-fixed nil)) + (if (eq (car (window-parameter window 'quit-restore)) 'other) + ;; Grow but never shrink window that previously displayed + ;; another buffer and is going to display that again. + (fit-window-to-buffer window nil (window-height window)) + (fit-window-to-buffer window nil 1)))) + +(defun transient--separator-line () + (and-let* ((height (cond ((not window-system) nil) + ((natnump transient-mode-line-format) + transient-mode-line-format) + ((eq transient-mode-line-format 'line) 1))) + (face `(,@(and (>= emacs-major-version 27) '(:extend t)) + :background + ,(or (face-foreground (transient--key-face nil 'non-suffix) + nil t) + "#gray60")))) + (concat (propertize "__" 'face face 'display `(space :height (,height))) + (propertize "\n" 'face face 'line-height t)))) + +(defmacro transient-with-shadowed-buffer (&rest body) + "While in the transient buffer, temporarily make the shadowed buffer current." + (declare (indent 0) (debug t)) + `(with-current-buffer (or transient--shadowed-buffer (current-buffer)) + ,@body)) + +(defun transient--insert-groups () + (let ((groups (cl-mapcan (lambda (group) + (let ((hide (oref group hide))) + (and (not (and (functionp hide) + (transient-with-shadowed-buffer + (funcall hide)))) + (list group)))) + transient--layout))) + (while-let ((group (pop groups))) + (transient--insert-group group) + (when groups + (insert ?\n))))) + +(defvar transient--max-group-level 1) + +(cl-defgeneric transient--insert-group (group) + "Format GROUP and its elements and insert the result.") + +(cl-defmethod transient--insert-group :around ((group transient-group)) + "Insert GROUP's description, if any." + (when-let ((desc (transient-with-shadowed-buffer + (transient-format-description group)))) + (insert desc ?\n)) + (let ((transient--max-group-level + (max (oref group level) transient--max-group-level)) + (transient--pending-group group)) + (cl-call-next-method group))) + +(cl-defmethod transient--insert-group ((group transient-row)) + (transient--maybe-pad-keys group) + (dolist (suffix (oref group suffixes)) + (insert (transient-with-shadowed-buffer (transient-format suffix))) + (insert " ")) + (insert ?\n)) + +(cl-defmethod transient--insert-group ((group transient-column) + &optional skip-empty) + (transient--maybe-pad-keys group) + (dolist (suffix (oref group suffixes)) + (let ((str (transient-with-shadowed-buffer (transient-format suffix)))) + (unless (and (not skip-empty) (equal str "")) + (insert str) + (unless (string-match-p ".\n\\'" str) + (insert ?\n)))))) + +(cl-defmethod transient--insert-group ((group transient-columns)) + (if transient-force-single-column + (dolist (group (oref group suffixes)) + (transient--insert-group group t)) + (let* ((columns + (mapcar + (lambda (column) + (transient--maybe-pad-keys column group) + (transient-with-shadowed-buffer + `(,@(and-let* ((desc (transient-format-description column))) + (list desc)) + ,@(let ((transient--pending-group column)) + (mapcar #'transient-format (oref column suffixes)))))) + (oref group suffixes))) + (stops (transient--column-stops columns))) + (dolist (row (apply #'transient--mapn #'list columns)) + (let ((stops stops)) + (dolist (cell row) + (let ((stop (pop stops))) + (when cell + (transient--align-to stop) + (insert cell))))) + (insert ?\n))))) + +(cl-defmethod transient--insert-group ((group transient-subgroups)) + (let ((subgroups (oref group suffixes))) + (while-let ((subgroup (pop subgroups))) + (transient--maybe-pad-keys subgroup group) + (transient--insert-group subgroup) + (when subgroups + (insert ?\n))))) + +(cl-defgeneric transient-format (obj) + "Format and return OBJ for display. + +When this function is called, then the current buffer is some +temporary buffer. If you need the buffer from which the prefix +command was invoked to be current, then do so by temporarily +making `transient--original-buffer' current.") + +(cl-defmethod transient-format ((arg string)) + "Return the string ARG after applying the `transient-heading' face." + (propertize arg 'face 'transient-heading)) + +(cl-defmethod transient-format ((_ null)) + "Return a string containing just the newline character." + "\n") + +(cl-defmethod transient-format ((arg integer)) + "Return a string containing just the ARG character." + (char-to-string arg)) + +(cl-defmethod transient-format :around ((obj transient-suffix)) + "Add additional formatting if appropriate. +When reading user input for this infix, then highlight it. +When edit-mode is enabled, then prepend the level information. +When `transient-enable-popup-navigation' is non-nil then format +as a button." + (let ((str (cl-call-next-method obj))) + (when (and (cl-typep obj 'transient-infix) + (eq (oref obj command) this-original-command) + (active-minibuffer-window)) + (setq str (transient--add-face str 'transient-active-infix))) + (when transient--editp + (setq str (concat (let ((level (oref obj level))) + (propertize (format " %s " level) + 'face (if (transient--use-level-p level t) + 'transient-enabled-suffix + 'transient-disabled-suffix))) + str))) + (when (and transient-enable-popup-navigation + (slot-boundp obj 'command)) + (setq str (make-text-button str nil + 'type 'transient + 'command (oref obj command)))) + str)) + +(cl-defmethod transient-format ((obj transient-infix)) + "Return a string generated using OBJ's `format'. +%k is formatted using `transient-format-key'. +%d is formatted using `transient-format-description'. +%v is formatted using `transient-format-value'." + (format-spec (oref obj format) + `((?k . ,(transient-format-key obj)) + (?d . ,(transient-format-description obj)) + (?v . ,(transient-format-value obj))))) + +(cl-defmethod transient-format ((obj transient-suffix)) + "Return a string generated using OBJ's `format'. +%k is formatted using `transient-format-key'. +%d is formatted using `transient-format-description'." + (format-spec (oref obj format) + `((?k . ,(transient-format-key obj)) + (?d . ,(transient-format-description obj))))) + +(cl-defgeneric transient-format-key (obj) + "Format OBJ's `key' for display and return the result.") + +(cl-defmethod transient-format-key :around ((obj transient-suffix)) + "Add `transient-inapt-suffix' face if suffix is inapt." + (let ((str (cl-call-next-method))) + (if (oref obj inapt) + (transient--add-face str 'transient-inapt-suffix) + str))) + +(cl-defmethod transient-format-key ((obj transient-suffix)) + "Format OBJ's `key' for display and return the result." + (let ((key (if (slot-boundp obj 'key) (oref obj key) "")) + (cmd (and (slot-boundp obj 'command) (oref obj command)))) + (when-let ((width (oref transient--pending-group pad-keys))) + (setq key (truncate-string-to-width key width nil ?\s))) + (if transient--redisplay-key + (let ((len (length transient--redisplay-key)) + (seq (cl-coerce (edmacro-parse-keys key t) 'list))) + (cond + ((member (seq-take seq len) + (list transient--redisplay-key + (thread-last transient--redisplay-key + (cl-substitute ?- 'kp-subtract) + (cl-substitute ?= 'kp-equal) + (cl-substitute ?+ 'kp-add)))) + (let ((pre (key-description (vconcat (seq-take seq len)))) + (suf (key-description (vconcat (seq-drop seq len))))) + (setq pre (string-replace "RET" "C-m" pre)) + (setq pre (string-replace "TAB" "C-i" pre)) + (setq suf (string-replace "RET" "C-m" suf)) + (setq suf (string-replace "TAB" "C-i" suf)) + ;; We use e.g., "-k" instead of the more correct "- k", + ;; because the former is prettier. If we did that in + ;; the definition, then we want to drop the space that + ;; is reinserted above. False-positives are possible + ;; for silly bindings like "-C-c C-c". + (unless (string-search " " key) + (setq pre (string-replace " " "" pre)) + (setq suf (string-replace " " "" suf))) + (concat (propertize pre 'face 'transient-unreachable-key) + (and (string-prefix-p (concat pre " ") key) " ") + (propertize suf 'face (transient--key-face cmd)) + (save-excursion + (and (string-match " +\\'" key) + (propertize (match-string 0 key) + 'face 'fixed-pitch)))))) + ((transient--lookup-key transient-sticky-map (kbd key)) + (propertize key 'face (transient--key-face cmd))) + (t + (propertize key 'face 'transient-unreachable-key)))) + (propertize key 'face (transient--key-face cmd))))) + +(cl-defmethod transient-format-key :around ((obj transient-argument)) + "Handle `transient-highlight-mismatched-keys'." + (let ((key (cl-call-next-method obj))) + (cond + ((not transient-highlight-mismatched-keys) key) + ((not (slot-boundp obj 'shortarg)) + (transient--add-face key 'transient-nonstandard-key)) + ((not (string-equal key (oref obj shortarg))) + (transient--add-face key 'transient-mismatched-key)) + (key)))) + +(cl-defgeneric transient-format-description (obj) + "Format OBJ's `description' for display and return the result.") + +(cl-defmethod transient-format-description ((obj transient-suffix)) + "The `description' slot may be a function, in which case that is +called inside the correct buffer (see `transient--insert-group') +and its value is returned to the caller." + (transient--get-description obj)) + +(cl-defmethod transient-format-description ((obj transient-value-preset)) + (pcase-let* (((eieio description key set) obj) + ((eieio value) transient--prefix) + (active (seq-set-equal-p set value))) + (format + "%s %s" + (propertize (or description (format "Preset %s" key)) + 'face (and active 'transient-argument)) + (format (propertize "(%s)" 'face 'transient-delimiter) + (mapconcat (lambda (arg) + (propertize + arg 'face (cond (active 'transient-argument) + ((member arg value) + '((:weight demibold) + transient-inactive-argument)) + ('transient-inactive-argument)))) + set " "))))) + +(cl-defmethod transient-format-description ((obj transient-group)) + "Format the description by calling the next method. +If the result doesn't use the `face' property at all, then apply the +face `transient-heading' to the complete string." + (and-let* ((desc (transient--get-description obj))) + (cond ((oref obj inapt) + (propertize desc 'face 'transient-inapt-suffix)) + ((text-property-not-all 0 (length desc) 'face nil desc) + desc) + ((propertize desc 'face 'transient-heading))))) + +(cl-defmethod transient-format-description :around ((obj transient-suffix)) + "Format the description by calling the next method. +If the result is nil, then use \"(BUG: no description)\" as the +description. If the OBJ's `key' is currently unreachable, then +apply the face `transient-unreachable' to the complete string." + (let ((desc (or (cl-call-next-method obj) + (and (slot-boundp transient--prefix 'suffix-description) + (funcall (oref transient--prefix suffix-description) + obj))))) + (if desc + (when-let ((face (transient--get-face obj 'face))) + (setq desc (transient--add-face desc face t))) + (setq desc (propertize "(BUG: no description)" 'face 'error))) + (when (if transient--all-levels-p + (> (oref obj level) transient--default-prefix-level) + (and transient-highlight-higher-levels + (> (max (oref obj level) transient--max-group-level) + transient--default-prefix-level))) + (setq desc (transient--add-face desc 'transient-higher-level))) + (when-let ((inapt-face (and (oref obj inapt) + (transient--get-face obj 'inapt-face)))) + (setq desc (transient--add-face desc inapt-face))) + (when (and (slot-boundp obj 'key) + (transient--key-unreachable-p obj)) + (setq desc (transient--add-face desc 'transient-unreachable))) + desc)) + +(cl-defgeneric transient-format-value (obj) + "Format OBJ's value for display and return the result.") + +(cl-defmethod transient-format-value ((obj transient-suffix)) + (propertize (oref obj argument) + 'face (if (oref obj value) + 'transient-argument + 'transient-inactive-argument))) + +(cl-defmethod transient-format-value ((obj transient-option)) + (let ((argument (oref obj argument))) + (if-let ((value (oref obj value))) + (pcase-exhaustive (oref obj multi-value) + ('nil + (concat (propertize argument 'face 'transient-argument) + (propertize value 'face 'transient-value))) + ((or 't 'rest) + (concat (propertize (if (string-suffix-p " " argument) + argument + (concat argument " ")) + 'face 'transient-argument) + (propertize (mapconcat #'prin1-to-string value " ") + 'face 'transient-value))) + ('repeat + (mapconcat (lambda (value) + (concat (propertize argument 'face 'transient-argument) + (propertize value 'face 'transient-value))) + value " "))) + (propertize argument 'face 'transient-inactive-argument)))) + +(cl-defmethod transient-format-value ((obj transient-switches)) + (with-slots (value argument-format choices) obj + (format (propertize argument-format + 'face (if value + 'transient-argument + 'transient-inactive-argument)) + (format + (propertize "[%s]" 'face 'transient-delimiter) + (mapconcat + (lambda (choice) + (propertize choice 'face + (if (equal (format argument-format choice) value) + 'transient-value + 'transient-inactive-value))) + choices + (propertize "|" 'face 'transient-delimiter)))))) + +(cl-defmethod transient--get-description ((obj transient-child)) + (and-let* ((desc (oref obj description))) + (if (functionp desc) + (if (= (car (transient--func-arity desc)) 1) + (funcall desc obj) + (funcall desc)) + desc))) + +(cl-defmethod transient--get-face ((obj transient-suffix) slot) + (and-let* (((slot-boundp obj slot)) + (face (slot-value obj slot))) + (if (and (not (facep face)) + (functionp face)) + (let ((transient--pending-suffix obj)) + (if (= (car (transient--func-arity face)) 1) + (funcall face obj) + (funcall face))) + face))) + +(defun transient--add-face (string face &optional append beg end) + (let ((str (copy-sequence string))) + (add-face-text-property (or beg 0) (or end (length str)) face append str) + str)) + +(defun transient--key-face (&optional cmd enforce-type) + (or (and transient-semantic-coloring + (not transient--helpp) + (not transient--editp) + (or (and cmd (get cmd 'transient-face)) + (get (transient--get-pre-command cmd enforce-type) + 'transient-face))) + (if cmd 'transient-key 'transient-key-noop))) + +(defun transient--key-unreachable-p (obj) + (and transient--redisplay-key + (let ((key (oref obj key))) + (not (or (equal (seq-take (cl-coerce (edmacro-parse-keys key t) 'list) + (length transient--redisplay-key)) + transient--redisplay-key) + (transient--lookup-key transient-sticky-map (kbd key))))))) + +(defun transient--lookup-key (keymap key) + (let ((val (lookup-key keymap key))) + (and val (not (integerp val)) val))) + +(defun transient--maybe-pad-keys (group &optional parent) + (when-let ((pad (or (oref group pad-keys) + (and parent (oref parent pad-keys))))) + (oset group pad-keys + (apply #'max + (if (integerp pad) pad 0) + (seq-keep (lambda (suffix) + (and (eieio-object-p suffix) + (slot-boundp suffix 'key) + (length (oref suffix key)))) + (oref group suffixes)))))) + +(defun transient--pixel-width (string) + (save-window-excursion + (with-temp-buffer + (insert string) + (set-window-dedicated-p nil nil) + (set-window-buffer nil (current-buffer)) + (car (window-text-pixel-size + nil (line-beginning-position) (point)))))) + +(defun transient--column-stops (columns) + (let* ((var-pitch (or transient-align-variable-pitch + (oref transient--prefix variable-pitch))) + (char-width (and var-pitch (transient--pixel-width " ")))) + (transient--seq-reductions-from + (apply-partially #'+ (* 2 (if var-pitch char-width 1))) + (transient--mapn + (lambda (cells min) + (apply #'max + (if min (if var-pitch (* min char-width) min) 0) + (mapcar (if var-pitch #'transient--pixel-width #'length) cells))) + columns + (oref transient--prefix column-widths)) + 0))) + +(defun transient--align-to (stop) + (unless (zerop stop) + (insert (if (or transient-align-variable-pitch + (oref transient--prefix variable-pitch)) + (propertize " " 'display `(space :align-to (,stop))) + (make-string (max 0 (- stop (current-column))) ?\s))))) + +(defun transient-command-summary-or-name (obj) + "Return the summary or name of the command represented by OBJ. + +If the command has a doc-string, then return the first line of +that, else its name. + +Intended to be temporarily used as the `:suffix-description' of +a prefix command, while porting a regular keymap to a transient." + (let ((command (oref obj command))) + (if-let ((doc (documentation command))) + (propertize (car (split-string doc "\n")) 'face 'font-lock-doc-face) + (propertize (symbol-name command) 'face 'font-lock-function-name-face)))) + +;;; Help + +(cl-defgeneric transient-show-help (obj) + "Show documentation for the command represented by OBJ.") + +(cl-defmethod transient-show-help ((obj transient-prefix)) + "Call `show-help' if non-nil, else show `info-manual', +if non-nil, else show the `man-page' if non-nil, else use +`describe-function'." + (with-slots (show-help info-manual man-page command) obj + (cond (show-help (funcall show-help obj)) + (info-manual (transient--show-manual info-manual)) + (man-page (transient--show-manpage man-page)) + ((transient--describe-function command))))) + +(cl-defmethod transient-show-help ((obj transient-suffix)) + "Call `show-help' if non-nil, else use `describe-function'. +Also used to dispatch showing documentation for the current +prefix. If the suffix is a sub-prefix, then also call the +prefix method." + (cond + ((eq this-command 'transient-help) + (transient-show-help transient--prefix)) + ((let ((prefix (get (oref obj command) + 'transient--prefix))) + (and prefix (not (eq (oref transient--prefix command) this-command)) + (prog1 t (transient-show-help prefix))))) + ((if-let ((show-help (oref obj show-help))) + (funcall show-help obj) + (transient--describe-function this-command))))) + +(cl-defmethod transient-show-help ((obj transient-infix)) + "Call `show-help' if non-nil, else show the `man-page' +if non-nil, else use `describe-function'. When showing the +manpage, then try to jump to the correct location." + (if-let ((show-help (oref obj show-help))) + (funcall show-help obj) + (if-let ((man-page (oref transient--prefix man-page)) + (argument (and (slot-boundp obj 'argument) + (oref obj argument)))) + (transient--show-manpage man-page argument) + (transient--describe-function this-command)))) + +;; `cl-generic-generalizers' doesn't support `command' et al. +(cl-defmethod transient-show-help (cmd) + "Show the command doc-string." + (transient--describe-function cmd)) + +(defmacro transient-with-help-window (&rest body) + "Evaluate BODY, send output to *Help* buffer, and display it in a window. +Select the help window, and make the help buffer current and return it." + (declare (indent 0)) + `(let ((buffer nil) + (help-window-select t)) + (with-help-window (help-buffer) + ,@body + (setq buffer (current-buffer))) + (set-buffer buffer))) + +(defun transient--describe-function (fn) + (let* ((buffer nil) + (help-window-select t) + (temp-buffer-window-setup-hook + (cons (lambda () (setq buffer (current-buffer))) + temp-buffer-window-setup-hook))) + (describe-function fn) + (set-buffer buffer))) + +(defun transient--show-manual (manual) + (info manual)) + +(defun transient--show-manpage (manpage &optional argument) + (require 'man) + (let* ((Man-notify-method 'meek) + (buf (Man-getpage-in-background manpage)) + (proc (get-buffer-process buf))) + (while (and proc (eq (process-status proc) 'run)) + (accept-process-output proc)) + (switch-to-buffer buf) + (when argument + (transient--goto-argument-description argument)))) + +(defun transient--goto-argument-description (arg) + (goto-char (point-min)) + (let ((case-fold-search nil) + ;; This matches preceding/proceeding options. Options + ;; such as "-a", "-S[<keyid>]", and "--grep=<pattern>" + ;; are matched by this regex without the shy group. + ;; The ". " in the shy group is for options such as + ;; "-m parent-number", and the "-[^[:space:]]+ " is + ;; for options such as "--mainline parent-number" + (others "-\\(?:. \\|-[^[:space:]]+ \\)?[^[:space:]]+")) + (when (re-search-forward + (if (equal arg "--") + ;; Special case. + "^[\t\s]+\\(--\\(?: \\|$\\)\\|\\[--\\]\\)" + ;; Should start with whitespace and may have + ;; any number of options before and/or after. + (format + "^[\t\s]+\\(?:%s, \\)*?\\(?1:%s\\)%s\\(?:, %s\\)*$" + others + ;; Options don't necessarily end in an "=" + ;; (e.g., "--gpg-sign[=<keyid>]") + (string-remove-suffix "=" arg) + ;; Simple options don't end in an "=". Splitting this + ;; into 2 cases should make getting false positives + ;; less likely. + (if (string-suffix-p "=" arg) + ;; "[^[:space:]]*[^.[:space:]]" matches the option + ;; value, which is usually after the option name + ;; and either '=' or '[='. The value can't end in + ;; a period, as that means it's being used at the + ;; end of a sentence. The space is for options + ;; such as '--mainline parent-number'. + "\\(?: \\|\\[?=\\)[^[:space:]]*[^.[:space:]]" + ;; Either this doesn't match anything (e.g., "-a"), + ;; or the option is followed by a value delimited + ;; by a "[", "<", or ":". A space might appear + ;; before this value, as in "-f <file>". The + ;; space alternative is for options such as + ;; "-m parent-number". + "\\(?:\\(?: \\| ?[\\[<:]\\)[^[:space:]]*[^.[:space:]]\\)?") + others)) + nil t) + (goto-char (match-beginning 1))))) + +(defun transient--insert-help () + (unless (looking-back "\n\n" 2) + (insert "\n")) + (when transient--helpp + (insert + (format (propertize "\ +Type a %s to show help for that suffix command, or %s to show manual. +Type %s to exit help.\n" + 'face 'transient-heading) + (propertize "<KEY>" 'face 'transient-key) + (propertize "?" 'face 'transient-key) + (propertize "C-g" 'face 'transient-key)))) + (when transient--editp + (unless transient--helpp + (insert + (format (propertize "\ +Type a %s to set level for that suffix command. +Type %s to set what levels are available for this prefix command.\n" + 'face 'transient-heading) + (propertize "<KEY>" 'face 'transient-key) + (propertize "C-x l" 'face 'transient-key)))) + (with-slots (level) transient--prefix + (insert + (format (propertize " +Suffixes on levels %s are available. +Suffixes on levels %s and %s are unavailable.\n" + 'face 'transient-heading) + (propertize (format "1-%s" level) + 'face 'transient-enabled-suffix) + (propertize " 0 " + 'face 'transient-disabled-suffix) + (propertize (format ">=%s" (1+ level)) + 'face 'transient-disabled-suffix)))))) + +;;; Popup Navigation + +(defun transient-scroll-up (&optional arg) + "Scroll text of transient popup window upward ARG lines. +If ARG is nil scroll near full screen. This is a wrapper +around `scroll-up-command' (which see)." + (interactive "^P") + (with-selected-window transient--window + (scroll-up-command arg))) + +(defun transient-scroll-down (&optional arg) + "Scroll text of transient popup window down ARG lines. +If ARG is nil scroll near full screen. This is a wrapper +around `scroll-down-command' (which see)." + (interactive "^P") + (with-selected-window transient--window + (scroll-down-command arg))) + +(defun transient-backward-button (n) + "Move to the previous button in the transient popup buffer. +See `backward-button' for information about N." + (interactive "p") + (with-selected-window transient--window + (backward-button n t))) + +(defun transient-forward-button (n) + "Move to the next button in the transient popup buffer. +See `forward-button' for information about N." + (interactive "p") + (with-selected-window transient--window + (forward-button n t))) + +(define-button-type 'transient + 'face nil + 'keymap transient-button-map) + +(defun transient--goto-button (command) + (cond + ((stringp command) + (when (re-search-forward (concat "^" (regexp-quote command)) nil t) + (goto-char (match-beginning 0)))) + (command + (while (and (ignore-errors (forward-button 1)) + (not (eq (button-get (button-at (point)) 'command) command)))) + (unless (eq (button-get (button-at (point)) 'command) command) + (goto-char (point-min)) + (forward-button 1))))) + +(defun transient--heading-at-point () + (and (eq (get-text-property (point) 'face) 'transient-heading) + (let ((beg (line-beginning-position))) + (buffer-substring-no-properties + beg (next-single-property-change + beg 'face nil (line-end-position)))))) + +;;; Compatibility +;;;; Popup Isearch + +(defvar-keymap transient--isearch-mode-map + :parent isearch-mode-map + "<remap> <isearch-exit>" #'transient-isearch-exit + "<remap> <isearch-cancel>" #'transient-isearch-cancel + "<remap> <isearch-abort>" #'transient-isearch-abort) + +(defun transient-isearch-backward (&optional regexp-p) + "Do incremental search backward. +With a prefix argument, do an incremental regular expression +search instead." + (interactive "P") + (transient--isearch-setup) + (let ((isearch-mode-map transient--isearch-mode-map)) + (isearch-mode nil regexp-p))) + +(defun transient-isearch-forward (&optional regexp-p) + "Do incremental search forward. +With a prefix argument, do an incremental regular expression +search instead." + (interactive "P") + (transient--isearch-setup) + (let ((isearch-mode-map transient--isearch-mode-map)) + (isearch-mode t regexp-p))) + +(defun transient-isearch-exit () + "Like `isearch-exit' but adapted for `transient'." + (interactive) + (isearch-exit) + (transient--isearch-exit)) + +(defun transient-isearch-cancel () + "Like `isearch-cancel' but adapted for `transient'." + (interactive) + (condition-case nil (isearch-cancel) (quit)) + (transient--isearch-exit)) + +(defun transient-isearch-abort () + "Like `isearch-abort' but adapted for `transient'." + (interactive) + (let ((around (lambda (fn) + (condition-case nil (funcall fn) (quit)) + (transient--isearch-exit)))) + (advice-add 'isearch-cancel :around around) + (unwind-protect + (isearch-abort) + (advice-remove 'isearch-cancel around)))) + +(defun transient--isearch-setup () + (select-window transient--window) + (transient--suspend-override t)) + +(defun transient--isearch-exit () + (select-window transient--original-window) + (transient--resume-override)) + +;;;; Edebug + +(defun transient--edebug-command-p () + (and (bound-and-true-p edebug-active) + (or (memq this-command '(top-level abort-recursive-edit)) + (string-prefix-p "edebug" (symbol-name this-command))))) + +;;;; Miscellaneous + +(cl-pushnew (list nil (concat "^\\s-*(" + (eval-when-compile + (regexp-opt + '("transient-define-prefix" + "transient-define-suffix" + "transient-define-infix" + "transient-define-argument") + t)) + "\\s-+\\(" lisp-mode-symbol-regexp "\\)") + 2) + lisp-imenu-generic-expression :test #'equal) + +(declare-function which-key-mode "ext:which-key" (&optional arg)) + +(defun transient--suspend-which-key-mode () + (when (bound-and-true-p which-key-mode) + (which-key-mode -1) + (add-hook 'transient-exit-hook #'transient--resume-which-key-mode))) + +(defun transient--resume-which-key-mode () + (unless transient--prefix + (which-key-mode 1) + (remove-hook 'transient-exit-hook #'transient--resume-which-key-mode))) + +(defun transient-bind-q-to-quit () + "Modify some keymaps to bind \"q\" to the appropriate quit command. + +\"C-g\" is the default binding for such commands now, but Transient's +predecessor Magit-Popup used \"q\" instead. If you would like to get +that binding back, then call this function in your init file like so: + + (with-eval-after-load \\='transient + (transient-bind-q-to-quit)) + +Individual transients may already bind \"q\" to something else +and such a binding would shadow the quit binding. If that is the +case then \"Q\" is bound to whatever \"q\" would have been bound +to by setting `transient-substitute-key-function' to a function +that does that. Of course \"Q\" may already be bound to something +else, so that function binds \"M-q\" to that command instead. +Of course \"M-q\" may already be bound to something else, but +we stop there." + (keymap-set transient-base-map "q" #'transient-quit-one) + (keymap-set transient-sticky-map "q" #'transient-quit-seq) + (setq transient-substitute-key-function + #'transient-rebind-quit-commands)) + +(defun transient-rebind-quit-commands (obj) + "See `transient-bind-q-to-quit'." + (let ((key (oref obj key))) + (cond ((string-equal key "q") "Q") + ((string-equal key "Q") "M-q") + (key)))) + +(defun transient--force-fixed-pitch () + (require 'face-remap) + (face-remap-reset-base 'default) + (face-remap-add-relative 'default 'fixed-pitch)) + +(defun transient--func-arity (fn) + (func-arity (advice--cd*r (if (symbolp fn) (symbol-function fn) fn)))) + +(defun transient--seq-reductions-from (function sequence initial-value) + (let ((acc (list initial-value))) + (seq-doseq (elt sequence) + (push (funcall function (car acc) elt) acc)) + (nreverse acc))) + +(defun transient--mapn (function &rest lists) + "Apply FUNCTION to elements of LISTS. +Like `cl-mapcar' but while that stops when the shortest list +is exhausted, continue until the longest list is, using nil +as stand-in for elements of exhausted lists." + (let (result) + (while (catch 'more (mapc (lambda (l) (and l (throw 'more t))) lists) nil) + (push (apply function (mapcar #'car-safe lists)) result) + (setq lists (mapcar #'cdr lists))) + (nreverse result))) + +;;; Font-Lock + +(defconst transient-font-lock-keywords + (eval-when-compile + `((,(concat "(" + (regexp-opt (list "transient-define-prefix" + "transient-define-infix" + "transient-define-argument" + "transient-define-suffix") + t) + "\\_>[ \t'(]*" + "\\(\\(?:\\sw\\|\\s_\\)+\\)?") + (1 'font-lock-keyword-face) + (2 'font-lock-function-name-face nil t))))) + +(font-lock-add-keywords 'emacs-lisp-mode transient-font-lock-keywords) + +;;; Auxiliary Classes +;;;; `transient-lisp-variable' + +(defclass transient-lisp-variable (transient-variable) + ((reader :initform #'transient-lisp-variable--reader) + (always-read :initform t) + (set-value :initarg :set-value :initform #'set)) + "[Experimental] Class used for Lisp variables.") + +(cl-defmethod transient-init-value ((obj transient-lisp-variable)) + (oset obj value (symbol-value (oref obj variable)))) + +(cl-defmethod transient-infix-set ((obj transient-lisp-variable) value) + (funcall (oref obj set-value) + (oref obj variable) + (oset obj value value))) + +(cl-defmethod transient-format-description ((obj transient-lisp-variable)) + (or (cl-call-next-method obj) + (symbol-name (oref obj variable)))) + +(cl-defmethod transient-format-value ((obj transient-lisp-variable)) + (propertize (prin1-to-string (oref obj value)) + 'face 'transient-value)) + +(cl-defmethod transient-prompt ((obj transient-lisp-variable)) + (if (and (slot-boundp obj 'prompt) + (oref obj prompt)) + (cl-call-next-method obj) + (format "Set %s: " (oref obj variable)))) + +(defun transient-lisp-variable--reader (prompt initial-input _history) + (read--expression prompt initial-input)) + +;;; _ +(provide 'transient) +;; Local Variables: +;; indent-tabs-mode: nil +;; checkdoc-symbol-words: ("command-line" "edit-mode" "help-mode") +;; End: +;;; transient.el ends here diff --git a/emacs/elpa/transient-20241004.1739/transient.info b/emacs/elpa/transient-20241004.1739/transient.info @@ -0,0 +1,3331 @@ +This is transient.info, produced by makeinfo version 6.8 from +transient.texi. + + Copyright (C) 2018–2024 Free Software Foundation, Inc. + + You can redistribute this document and/or modify it under the terms + of the GNU General Public License as published by the Free Software + Foundation, either version 3 of the License, or (at your option) + any later version. + + This document is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + +INFO-DIR-SECTION Emacs misc features +START-INFO-DIR-ENTRY +* Transient: (transient). Transient Commands. +END-INFO-DIR-ENTRY + + +File: transient.info, Node: Top, Next: Introduction, Up: (dir) + +Transient User and Developer Manual +*********************************** + +Transient is the library used to implement the keyboard-driven “menus” +in Magit. It is distributed as a separate package, so that it can be +used to implement similar menus in other packages. + + This manual can be bit hard to digest when getting started. A useful +resource to get over that hurdle is Psionic K’s interactive tutorial, +available at <https://github.com/positron-solutions/transient-showcase>. + +This manual is for Transient version 0.7.7. + + Copyright (C) 2018–2024 Free Software Foundation, Inc. + + You can redistribute this document and/or modify it under the terms + of the GNU General Public License as published by the Free Software + Foundation, either version 3 of the License, or (at your option) + any later version. + + This document is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + +* Menu: + +* Introduction:: +* Usage:: +* Modifying Existing Transients:: +* Defining New Commands:: +* Classes and Methods:: +* FAQ:: +* Keystroke Index:: +* Command and Function Index:: +* Variable Index:: +* Concept Index:: +* GNU General Public License:: + +— The Detailed Node Listing — + +Usage + +* Invoking Transients:: +* Aborting and Resuming Transients:: +* Common Suffix Commands:: +* Saving Values:: +* Using History:: +* Getting Help for Suffix Commands:: +* Enabling and Disabling Suffixes:: +* Other Commands:: +* Configuration:: + +Defining New Commands + +* Technical Introduction:: +* Defining Transients:: +* Binding Suffix and Infix Commands:: +* Defining Suffix and Infix Commands:: +* Using Infix Arguments:: +* Transient State:: + +Binding Suffix and Infix Commands + +* Group Specifications:: +* Suffix Specifications:: + + +Classes and Methods + +* Group Classes:: +* Group Methods:: +* Prefix Classes:: +* Suffix Classes:: +* Suffix Methods:: +* Prefix Slots:: +* Suffix Slots:: +* Predicate Slots:: + +Suffix Methods + +* Suffix Value Methods:: +* Suffix Format Methods:: + + + + +File: transient.info, Node: Introduction, Next: Usage, Prev: Top, Up: Top + +1 Introduction +************** + +Transient is the library used to implement the keyboard-driven “menus” +in Magit. It is distributed as a separate package, so that it can be +used to implement similar menus in other packages. + + This manual can be bit hard to digest when getting started. A useful +resource to get over that hurdle is Psionic K’s interactive tutorial, +available at <https://github.com/positron-solutions/transient-showcase>. + +Some things that Transient can do +================================= + + • Display current state of arguments + • Display and manage lifecycle of modal bindings + • Contextual user interface + • Flow control for wizard-like composition of interactive forms + • History & persistence + • Rendering arguments for controlling CLI programs + +Complexity in CLI programs +========================== + +Complexity tends to grow with time. How do you manage the complexity of +commands? Consider the humble shell command ‘ls’. It now has over +_fifty_ command line options. Some of these are boolean flags (‘ls +-l’). Some take arguments (‘ls --sort=s’). Some have no effect unless +paired with other flags (‘ls -lh’). Some are mutually exclusive. Some +shell commands even have so many options that they introduce +_subcommands_ (‘git branch’, ‘git commit’), each with their own rich set +of options (‘git branch -f’). + +Using Transient for composing interactive commands +================================================== + +What about Emacs commands used interactively? How do these handle +options? One solution is to make many versions of the same command, so +you don’t need to! Consider: ‘delete-other-windows’ vs. +‘delete-other-windows-vertically’ (among many similar examples). + + Some Emacs commands will simply prompt you for the next "argument" +(‘M-x switch-to-buffer’). Another common solution is to use prefix +arguments which usually start with ‘C-u’. Sometimes these are sensibly +numerical in nature (‘C-u 4 M-x forward-paragraph’ to move forward 4 +paragraphs). But sometimes they function instead as boolean "switches" +(‘C-u C-SPACE’ to jump to the last mark instead of just setting it, ‘C-u +C-u C-SPACE’ to unconditionally set the mark). Since there aren’t many +standards for the use of prefix options, you have to read the command’s +documentation to find out what the possibilities are. + + But when an Emacs command grows to have a truly large set of options +and arguments, with dependencies between them, lots of option values, +etc., these simple approaches just don’t scale. Transient is designed +to solve this issue. Think of it as the humble prefix argument ‘C-u’, +_raised to the power of 10_. Like ‘C-u’, it is key driven. Like the +shell, it supports boolean "flag" options, options that take arguments, +and even "sub-commands", with their own options. But instead of +searching through a man page or command documentation, well-designed +transients _guide_ their users to the relevant set of options (and even +their possible values!) directly, taking into account any important +pre-existing Emacs settings. And while for shell commands like ‘ls’, +there is only one way to "execute" (hit ‘Return’!), transients can +"execute" using multiple different keys tied to one of many +self-documenting _actions_ (imagine having 5 different colored return +keys on your keyboard!). Transients make navigating and setting large, +complex groups of command options and arguments easy. Fun even. Once +you’ve tried it, it’s hard to go back to the ‘C-u what can I do here +again?’ way. + + +File: transient.info, Node: Usage, Next: Modifying Existing Transients, Prev: Introduction, Up: Top + +2 Usage +******* + +* Menu: + +* Invoking Transients:: +* Aborting and Resuming Transients:: +* Common Suffix Commands:: +* Saving Values:: +* Using History:: +* Getting Help for Suffix Commands:: +* Enabling and Disabling Suffixes:: +* Other Commands:: +* Configuration:: + + +File: transient.info, Node: Invoking Transients, Next: Aborting and Resuming Transients, Up: Usage + +2.1 Invoking Transients +======================= + +A transient prefix command is invoked like any other command by pressing +the key that is bound to that command. The main difference to other +commands is that a transient prefix command activates a transient +keymap, which temporarily binds the transient’s infix and suffix +commands. Bindings from other keymaps may, or may not, be disabled +while the transient state is in effect. + + There are two kinds of commands that are available after invoking a +transient prefix command; infix and suffix commands. Infix commands set +some value (which is then shown in a popup buffer), without leaving the +transient. Suffix commands, on the other hand, usually quit the +transient and they may use the values set by the infix commands, i.e., +the infix *arguments*. + + Instead of setting arguments to be used by a suffix command, infix +commands may also set some value by side-effect, e.g., by setting the +value of some variable. + + +File: transient.info, Node: Aborting and Resuming Transients, Next: Common Suffix Commands, Prev: Invoking Transients, Up: Usage + +2.2 Aborting and Resuming Transients +==================================== + +To quit the transient without invoking a suffix command press ‘C-g’. + + Key bindings in transient keymaps may be longer than a single event. +After pressing a valid prefix key, all commands whose bindings do not +begin with that prefix key are temporarily unavailable and grayed out. +To abort the prefix key press ‘C-g’ (which in this case only quits the +prefix key, but not the complete transient). + + A transient prefix command can be bound as a suffix of another +transient. Invoking such a suffix replaces the current transient state +with a new transient state, i.e., the available bindings change and the +information displayed in the popup buffer is updated accordingly. +Pressing ‘C-g’ while a nested transient is active only quits the +innermost transient, causing a return to the previous transient. + + ‘C-q’ or ‘C-z’ on the other hand always exits all transients. If you +use the latter, then you can later resume the stack of transients using +‘M-x transient-resume’. + +‘C-g’ (‘transient-quit-seq’) +‘C-g’ (‘transient-quit-one’) + This key quits the currently active incomplete key sequence, if + any, or else the current transient. When quitting the current + transient, it returns to the previous transient, if any. + + Transient’s predecessor bound ‘q’ instead of ‘C-g’ to the quit +command. To learn how to get that binding back see +‘transient-bind-q-to-quit’’s documentation string. + +‘C-q’ (‘transient-quit-all’) + This command quits the currently active incomplete key sequence, if + any, and all transients, including the active transient and all + suspended transients, if any. + +‘C-z’ (‘transient-suspend’) + Like ‘transient-quit-all’, this command quits an incomplete key + sequence, if any, and all transients. Additionally, it saves the + stack of transients so that it can easily be resumed (which is + particularly useful if you quickly need to do “something else” and + the stack is deeper than a single transient, and/or you have + already changed the values of some infix arguments). + + Note that only a single stack of transients can be saved at a time. + If another stack is already saved, then saving a new stack discards + the previous stack. + +‘M-x transient-resume’ + This command resumes the previously suspended stack of transients, + if any. + + +File: transient.info, Node: Common Suffix Commands, Next: Saving Values, Prev: Aborting and Resuming Transients, Up: Usage + +2.3 Common Suffix Commands +========================== + +A few shared suffix commands are available in all transients. These +suffix commands are not shown in the popup buffer by default. + + This includes the aborting commands mentioned in the previous +section, as well as some other commands that are all bound to ‘C-x KEY’. +After ‘C-x’ is pressed, a section featuring all these common commands is +temporarily shown in the popup buffer. After invoking one of them, the +section disappears again. Note, however, that one of these commands is +described as “Show common permanently”; invoke that if you want the +common commands to always be shown for all transients. + +‘C-x t’ (‘transient-toggle-common’) + This command toggles whether the generic commands that are common + to all transients are always displayed or only after typing the + incomplete prefix key sequence ‘C-x’. This only affects the + current Emacs session. + + -- User Option: transient-show-common-commands + This option controls whether shared suffix commands are shown + alongside the transient-specific infix and suffix commands. By + default, the shared commands are not shown to avoid overwhelming + the user with too many options. + + While a transient is active, pressing ‘C-x’ always shows the common + commands. The value of this option can be changed for the current + Emacs session by typing ‘C-x t’ while a transient is active. + + The other common commands are described in either the previous or in +one of the following sections. + + Some of Transient’s key bindings differ from the respective bindings +of Magit-Popup; see *note FAQ:: for more information. + + +File: transient.info, Node: Saving Values, Next: Using History, Prev: Common Suffix Commands, Up: Usage + +2.4 Saving Values +================= + +After setting the infix arguments in a transient, the user can save +those arguments for future invocations. + + Most transients will start out with the saved arguments when they are +invoked. There are a few exceptions, though. Some transients are +designed so that the value that they use is stored externally as the +buffer-local value of some variable. Invoking such a transient again +uses the buffer-local value. (1) + + If the user does not save the value and just exits using a regular +suffix command, then the value is merely saved to the transient’s +history. That value won’t be used when the transient is next invoked, +but it is easily accessible (see *note Using History::). + +‘C-x s’ (‘transient-set’) + This command saves the value of the active transient for this Emacs + session. + +‘C-x C-s’ (‘transient-save’) + Save the value of the active transient persistently across Emacs + sessions. + +‘C-x C-k’ (‘transient-reset’) + Clear the set and saved values of the active transient. + + -- User Option: transient-values-file + This option names the file that is used to persist the values of + transients between Emacs sessions. + + ---------- Footnotes ---------- + + (1) ‘magit-diff’ and ‘magit-log’ are two prominent examples, and +their handling of buffer-local values is actually a bit more complicated +than outlined above and even customizable. + + +File: transient.info, Node: Using History, Next: Getting Help for Suffix Commands, Prev: Saving Values, Up: Usage + +2.5 Using History +================= + +Every time the user invokes a suffix command the transient’s current +value is saved to its history. These values can be cycled through the +same way one can cycle through the history of commands that read +user-input in the minibuffer. + +‘C-M-p’ (‘transient-history-prev’) +‘C-x p’ + This command switches to the previous value used for the active + transient. + +‘C-M-n’ (‘transient-history-next’) +‘C-x n’ + This command switches to the next value used for the active + transient. + + In addition to the transient-wide history, Transient of course +supports per-infix history. When an infix reads user-input using the +minibuffer, the user can use the regular minibuffer history commands to +cycle through previously used values. Usually the same keys as those +mentioned above are bound to those commands. + + Authors of transients should arrange for different infix commands +that read the same kind of value to also use the same history key (see +*note Suffix Slots::). + + Both kinds of history are saved to a file when Emacs is exited. + + -- User Option: transient-history-file + This option names the file that is used to persist the history of + transients and their infixes between Emacs sessions. + + -- User Option: transient-history-limit + This option controls how many history elements are kept at the time + the history is saved in ‘transient-history-file’. + + +File: transient.info, Node: Getting Help for Suffix Commands, Next: Enabling and Disabling Suffixes, Prev: Using History, Up: Usage + +2.6 Getting Help for Suffix Commands +==================================== + +Transients can have many suffixes and infixes that the user might not be +familiar with. To make it trivial to get help for these, Transient +provides access to the documentation directly from the active transient. + +‘C-h’ (‘transient-help’) + This command enters help mode. When help mode is active, typing a + key shows information about the suffix command that the key + normally is bound to (instead of invoking it). Pressing ‘C-h’ a + second time shows information about the _prefix_ command. + + After typing a key, the stack of transient states is suspended and + information about the suffix command is shown instead. Typing ‘q’ + in the help buffer buries that buffer and resumes the transient + state. + + What sort of documentation is shown depends on how the transient was +defined. For infix commands that represent command-line arguments this +ideally shows the appropriate manpage. ‘transient-help’ then tries to +jump to the correct location within that. Info manuals are also +supported. The fallback is to show the command’s documentation string, +for non-infix suffixes this is usually appropriate. + + +File: transient.info, Node: Enabling and Disabling Suffixes, Next: Other Commands, Prev: Getting Help for Suffix Commands, Up: Usage + +2.7 Enabling and Disabling Suffixes +=================================== + +The user base of a package that uses transients can be very diverse. +This is certainly the case for Magit; some users have been using it and +Git for a decade, while others are just getting started now. + + For that reason a mechanism is needed that authors can use to +classify a transient’s infixes and suffixes along the +essentials...everything spectrum. We use the term “levels” to describe +that mechanism. + + Each suffix command is placed on a level and each transient has a +level (called “transient-level”), which controls which suffix commands +are available. Integers between 1 and 7 (inclusive) are valid levels. +For suffixes, 0 is also valid; it means that the suffix is not displayed +at any level. + + The levels of individual transients and/or their individual suffixes +can be changed interactively, by invoking the transient and then +pressing ‘C-x l’ to enter the “edit” mode, see below. + + The default level for both transients and their suffixes is 4. The +‘transient-default-level’ option only controls the default for +transients. The default suffix level is always 4. The authors of +transients should place certain suffixes on a higher level, if they +expect that it won’t be of use to most users, and they should place very +important suffixes on a lower level, so that they remain available even +if the user lowers the transient level. + + -- User Option: transient-default-level + This option controls which suffix levels are made available by + default. It sets the transient-level for transients for which the + user has not set that individually. + + -- User Option: transient-levels-file + This option names the file that is used to persist the levels of + transients and their suffixes between Emacs sessions. + +‘C-x l’ (‘transient-set-level’) + This command enters edit mode. When edit mode is active, then all + infixes and suffixes that are currently usable are displayed along + with their levels. The colors of the levels indicate whether they + are enabled or not. The level of the transient is also displayed + along with some usage information. + + In edit mode, pressing the key that would usually invoke a certain + suffix instead prompts the user for the level that suffix should be + placed on. + + Help mode is available in edit mode. + + To change the transient level press ‘C-x l’ again. + + To exit edit mode press ‘C-g’. + + Note that edit mode does not display any suffixes that are not + currently usable. ‘magit-rebase’, for example, shows different + suffixes depending on whether a rebase is already in progress or + not. The predicates also apply in edit mode. + + Therefore, to control which suffixes are available given a certain + state, you have to make sure that that state is currently active. + +‘C-x a’ (‘transient-toggle-level-limit’) + This command toggle whether suffixes that are on levels higher than + the level specified by ‘transient-default-level’ are temporarily + available anyway. + + +File: transient.info, Node: Other Commands, Next: Configuration, Prev: Enabling and Disabling Suffixes, Up: Usage + +2.8 Other Commands +================== + +When invoking a transient in a small frame, the transient window may not +show the complete buffer, making it necessary to scroll, using the +following commands. These commands are never shown in the transient +window, and the key bindings are the same as for ‘scroll-up-command’ and +‘scroll-down-command’ in other buffers. + + -- Command: transient-scroll-up arg + This command scrolls text of transient popup window upward ARG + lines. If ARG is ‘nil’, then it scrolls near full screen. This is + a wrapper around ‘scroll-up-command’ (which see). + + -- Command: transient-scroll-down arg + This command scrolls text of transient popup window down ARG lines. + If ARG is ‘nil’, then it scrolls near full screen. This is a + wrapper around ‘scroll-down-command’ (which see). + + +File: transient.info, Node: Configuration, Prev: Other Commands, Up: Usage + +2.9 Configuration +================= + +More options are described in *note Common Suffix Commands::, in *note +Saving Values::, in *note Using History:: and in *note Enabling and +Disabling Suffixes::. + +Essential Options +----------------- + +Also see *note Common Suffix Commands::. + + -- User Option: transient-show-popup + This option controls whether the current transient’s infix and + suffix commands are shown in the popup buffer. + + • If ‘t’ (the default) then the popup buffer is shown as soon as + a transient prefix command is invoked. + + • If ‘nil’, then the popup buffer is not shown unless the user + explicitly requests it, by pressing an incomplete prefix key + sequence. + + • If a number, then the a brief one-line summary is shown + instead of the popup buffer. If zero or negative, then not + even that summary is shown; only the pressed key itself is + shown. + + The popup is shown when the user explicitly requests it by + pressing an incomplete prefix key sequence. Unless this is + zero, the popup is shown after that many seconds of inactivity + (using the absolute value). + + -- User Option: transient-enable-popup-navigation + This option controls whether navigation commands are enabled in the + transient popup buffer. + + While a transient is active the transient popup buffer is not the + current buffer, making it necessary to use dedicated commands to + act on that buffer itself. This is disabled by default. If this + option is non-‘nil’, then the following features are available: + + • ‘<UP>’ moves the cursor to the previous suffix. + • ‘<DOWN>’ moves the cursor to the next suffix. + • ‘<RET>’ invokes the suffix the cursor is on. + • ‘mouse-1’ invokes the clicked on suffix. + • ‘C-s’ and ‘C-r’ start isearch in the popup buffer. + + -- User Option: transient-display-buffer-action + This option specifies the action used to display the transient + popup buffer. The transient popup buffer is displayed in a window + using ‘(display-buffer BUFFER transient-display-buffer-action)’. + + The value of this option has the form ‘(FUNCTION . ALIST)’, where + FUNCTION is a function or a list of functions. Each such function + should accept two arguments: a buffer to display and an alist of + the same form as ALIST. See *note (elisp)Choosing Window::, for + details. + + The default is: + + (display-buffer-in-side-window + (side . bottom) + (inhibit-same-window . t) + (window-parameters (no-other-window . t))) + + This displays the window at the bottom of the selected frame. + Another useful FUNCTION is ‘display-buffer-below-selected’, which + is what ‘magit-popup’ used by default. For more alternatives see + *note (elisp)Buffer Display Action Functions::, and *note + (elisp)Buffer Display Action Alists::. + + Note that the buffer that was current before the transient buffer + is shown should remain the current buffer. Many suffix commands + act on the thing at point, if appropriate, and if the transient + buffer became the current buffer, then that would change what is at + point. To that effect ‘inhibit-same-window’ ensures that the + selected window is not used to show the transient buffer. + + It may be possible to display the window in another frame, but + whether that works in practice depends on the window-manager. If + the window manager selects the new window (Emacs frame), then that + unfortunately changes which buffer is current. + + If you change the value of this option, then you might also want to + change the value of ‘transient-mode-line-format’. + +Accessibility Options +--------------------- + + -- User Option: transient-force-single-column + This option controls whether the use of a single column to display + suffixes is enforced. This might be useful for users with low + vision who use large text and might otherwise have to scroll in two + dimensions. + +Auxiliary Options +----------------- + + -- User Option: transient-mode-line-format + This option controls whether the transient popup buffer has a + mode-line, separator line, or neither. + + If ‘nil’, then the buffer has no mode-line. If the buffer is not + displayed right above the echo area, then this probably is not a + good value. + + If ‘line’ (the default) or a natural number, then the buffer has no + mode-line, but a line is drawn is drawn in its place. If a number + is used, that specifies the thickness of the line. On termcap + frames we cannot draw lines, so there ‘line’ and numbers are + synonyms for ‘nil’. + + The color of the line is used to indicate if non-suffixes are + allowed and whether they exit the transient. The foreground color + of ‘transient-key-noop’ (if non-suffix are disallowed), + ‘transient-key-stay’ (if allowed and transient stays active), or + ‘transient-key-exit’ (if allowed and they exit the transient) is + used to draw the line. + + Otherwise this can be any mode-line format. See *note (elisp)Mode + Line Format::, for details. + + -- User Option: transient-semantic-coloring + This option controls whether colors are used to indicate the + transient behavior of commands. + + If non-‘nil’, then the key binding of each suffix is colorized to + indicate whether it exits the transient state or not. The color of + the prefix is indicated using the line that is drawn when the value + of ‘transient-mode-line-format’ is ‘line’. + + -- User Option: transient-highlight-mismatched-keys + This option controls whether key bindings of infix commands that do + not match the respective command-line argument should be + highlighted. For other infix commands this option has no effect. + + When this option is non-‘nil’, the key binding for an infix + argument is highlighted when only a long argument (e.g., + ‘--verbose’) is specified but no shorthand (e.g., ‘-v’). In the + rare case that a shorthand is specified but the key binding does + not match, then it is highlighted differently. + + Highlighting mismatched key bindings is useful when learning the + arguments of the underlying command-line tool; you wouldn’t want to + learn any short-hands that do not actually exist. + + The highlighting is done using one of the faces + ‘transient-mismatched-key’ and ‘transient-nonstandard-key’. + + -- User Option: transient-substitute-key-function + This function is used to modify key bindings. If the value of this + option is ‘nil’ (the default), then no substitution is performed. + + This function is called with one argument, the prefix object, and + must return a key binding description, either the existing key + description it finds in the ‘key’ slot, or the key description that + replaces the prefix key. It could be used to make other + substitutions, but that is discouraged. + + For example, ‘=’ is hard to reach using my custom keyboard layout, + so I substitute ‘(’ for that, which is easy to reach using a layout + optimized for lisp. + + (setq transient-substitute-key-function + (lambda (obj) + (let ((key (oref obj key))) + (if (string-match "\\`\\(=\\)[a-zA-Z]" key) + (replace-match "(" t t key 1) + key)))) + + -- User Option: transient-read-with-initial-input + This option controls whether the last history element is used as + the initial minibuffer input when reading the value of an infix + argument from the user. If ‘nil’, there is no initial input and + the first element has to be accessed the same way as the older + elements. + + -- User Option: transient-hide-during-minibuffer-read + This option controls whether the transient buffer is hidden while + user input is being read in the minibuffer. + + -- User Option: transient-align-variable-pitch + This option controls whether columns are aligned pixel-wise in the + popup buffer. + + If this is non-‘nil’, then columns are aligned pixel-wise to + support variable-pitch fonts. Keys are not aligned, so you should + use a fixed-pitch font for the ‘transient-key’ face. Other key + faces inherit from that face unless a theme is used that breaks + that relationship. + + This option is intended for users who use a variable-pitch font for + the ‘default’ face. + + -- User Option: transient-force-fixed-pitch + This option controls whether to force the use of a monospaced font + in popup buffer. Even if you use a proportional font for the + ‘default’ face, you might still want to use a monospaced font in + transient’s popup buffer. Setting this option to ‘t’ causes + ‘default’ to be remapped to ‘fixed-pitch’ in that buffer. + +Developer Options +----------------- + +These options are mainly intended for developers. + + -- User Option: transient-detect-key-conflicts + This option controls whether key binding conflicts should be + detected at the time the transient is invoked. If so, this results + in an error, which prevents the transient from being used. Because + of that, conflicts are ignored by default. + + Conflicts cannot be determined earlier, i.e., when the transient is + being defined and when new suffixes are being added, because at + that time there can be false-positives. It is actually valid for + multiple suffixes to share a common key binding, provided the + predicates of those suffixes prevent that more than one of them is + enabled at a time. + + -- User Option: transient-highlight-higher-levels + This option controls whether suffixes that would not be available + by default are highlighted. + + When non-‘nil’ then the descriptions of suffixes are highlighted if + their level is above 4, the default of ‘transient-default-level’. + Assuming you have set that variable to 7, this highlights all + suffixes that won’t be available to users without them making the + same customization. + + +File: transient.info, Node: Modifying Existing Transients, Next: Defining New Commands, Prev: Usage, Up: Top + +3 Modifying Existing Transients +******************************* + +To an extent, transients can be customized interactively, see *note +Enabling and Disabling Suffixes::. This section explains how existing +transients can be further modified non-interactively. Let’s begin with +an example: + + (transient-append-suffix 'magit-patch-apply "-3" + '("-R" "Apply in reverse" "--reverse")) + + This inserts a new infix argument to toggle the ‘--reverse’ argument +after the infix argument that toggles ‘-3’ in ‘magit-patch-apply’. + + The following functions share a few arguments: + + • PREFIX is a transient prefix command, a symbol. + + • SUFFIX is a transient infix or suffix specification in the same + form as expected by ‘transient-define-prefix’. Note that an infix + is a special kind of suffix. Depending on context “suffixes” means + “suffixes (including infixes)” or “non-infix suffixes”. Here it + means the former. See *note Suffix Specifications::. + + SUFFIX may also be a group in the same form as expected by + ‘transient-define-prefix’. See *note Group Specifications::. + + • LOC is a command, a key vector, a key description (a string as + returned by ‘key-description’), or a list specifying coordinates + (the last element may also be a command or key). For example ‘(1 0 + -1)’ identifies the last suffix (‘-1’) of the first subgroup (‘0’) + of the second group (‘1’). + + If LOC is a list of coordinates, then it can be used to identify a + group, not just an individual suffix command. + + The function ‘transient-get-suffix’ can be useful to determine + whether a certain coordination list identifies the suffix or group + that you expect it to identify. In hairy cases it may be necessary + to look at the definition of the transient prefix command. + + These functions operate on the information stored in the +‘transient--layout’ property of the PREFIX symbol. Suffix entries in +that tree are not objects but have the form ‘(LEVEL CLASS PLIST)’, where +PLIST should set at least ‘:key’, ‘:description’ and ‘:command’. + + -- Function: transient-insert-suffix prefix loc suffix &optional + keep-other + -- Function: transient-append-suffix prefix loc suffix &optional + keep-other + These functions insert the suffix or group SUFFIX into PREFIX + before or after LOC. + + Conceptually adding a binding to a transient prefix is similar to + adding a binding to a keymap, but this is complicated by the fact + that multiple suffix commands can be bound to the same key, + provided they are never active at the same time, see *note + Predicate Slots::. + + Unfortunately both false-positives and false-negatives are + possible. To deal with the former use non-‘nil’ KEEP-OTHER. To + deal with the latter remove the conflicting binding explicitly. + + -- Function: transient-replace-suffix prefix loc suffix + This function replaces the suffix or group at LOC in PREFIX with + suffix or group SUFFIX. + + -- Function: transient-remove-suffix prefix loc + This function removes the suffix or group at LOC in PREFIX. + + -- Function: transient-get-suffix prefix loc + This function returns the suffix or group at LOC in PREFIX. The + returned value has the form mentioned above. + + -- Function: transient-suffix-put prefix loc prop value + This function edits the suffix or group at LOC in PREFIX, by + setting the PROP of its plist to VALUE. + + Most of these functions do not signal an error if they cannot perform +the requested modification. The functions that insert new suffixes show +a warning if LOC cannot be found in PREFIX without signaling an error. +The reason for doing it like this is that establishing a key binding +(and that is what we essentially are trying to do here) should not +prevent the rest of the configuration from loading. Among these +functions only ‘transient-get-suffix’ and ‘transient-suffix-put’ may +signal an error. + + +File: transient.info, Node: Defining New Commands, Next: Classes and Methods, Prev: Modifying Existing Transients, Up: Top + +4 Defining New Commands +*********************** + +* Menu: + +* Technical Introduction:: +* Defining Transients:: +* Binding Suffix and Infix Commands:: +* Defining Suffix and Infix Commands:: +* Using Infix Arguments:: +* Transient State:: + + +File: transient.info, Node: Technical Introduction, Next: Defining Transients, Up: Defining New Commands + +4.1 Technical Introduction +========================== + +Taking inspiration from prefix keys and prefix arguments, Transient +implements a similar abstraction involving a prefix command, infix +arguments and suffix commands. + + When the user calls a transient prefix command, a transient +(temporary) keymap is activated, which binds the transient’s infix and +suffix commands, and functions that control the transient state are +added to ‘pre-command-hook’ and ‘post-command-hook’. The available +suffix and infix commands and their state are shown in a popup buffer +until the transient state is exited by invoking a suffix command. + + Calling an infix command causes its value to be changed. How that is +done depends on the type of the infix command. The simplest case is an +infix command that represents a command-line argument that does not take +a value. Invoking such an infix command causes the switch to be toggled +on or off. More complex infix commands may read a value from the user, +using the minibuffer. + + Calling a suffix command usually causes the transient to be exited; +the transient keymaps and hook functions are removed, the popup buffer +no longer shows information about the (no longer bound) suffix commands, +the values of some public global variables are set, while some internal +global variables are unset, and finally the command is actually called. +Suffix commands can also be configured to not exit the transient. + + A suffix command can, but does not have to, use the infix arguments +in much the same way any command can choose to use or ignore the prefix +arguments. For a suffix command that was invoked from a transient, the +variable ‘transient-current-suffixes’ and the function ‘transient-args’ +serve about the same purpose as the variables ‘prefix-arg’ and +‘current-prefix-arg’ do for any command that was called after the prefix +arguments have been set using a command such as ‘universal-argument’. + + Transient can be used to implement simple “command dispatchers”. The +main benefit then is that the user can see all the available commands in +a popup buffer, which can be thought of as a “menus”. That is useful by +itself because it frees the user from having to remember all the keys +that are valid after a certain prefix key or command. Magit’s +‘magit-dispatch’ (on ‘C-x M-g’) command is an example of using Transient +to merely implement a command dispatcher. + + In addition to that, Transient also allows users to interactively +pass arguments to commands. These arguments can be much more complex +than what is reasonable when using prefix arguments. There is a limit +to how many aspects of a command can be controlled using prefix +arguments. Furthermore, what a certain prefix argument means for +different commands can be completely different, and users have to read +documentation to learn and then commit to memory what a certain prefix +argument means to a certain command. + + Transient suffix commands, on the other hand, can accept dozens of +different arguments without the user having to remember anything. When +using Transient, one can call a command with arguments that are just as +complex as when calling the same function non-interactively from Lisp. + + Invoking a transient suffix command with arguments is similar to +invoking a command in a shell with command-line completion and history +enabled. One benefit of the Transient interface is that it remembers +history not only on a global level (“this command was invoked using +these arguments, and previously it was invoked using those other +arguments”), but also remembers the values of individual arguments +independently. See *note Using History::. + + After a transient prefix command is invoked, ‘C-h KEY’ can be used to +show the documentation for the infix or suffix command that ‘KEY’ is +bound to (see *note Getting Help for Suffix Commands::), and infixes and +suffixes can be removed from the transient using ‘C-x l KEY’. Infixes +and suffixes that are disabled by default can be enabled the same way. +See *note Enabling and Disabling Suffixes::. + + Transient ships with support for a few different types of specialized +infix commands. A command that sets a command line option, for example, +has different needs than a command that merely toggles a boolean flag. +Additionally, Transient provides abstractions for defining new types, +which the author of Transient did not anticipate (or didn’t get around +to implementing yet). + + Note that suffix commands also support regular prefix arguments. A +suffix command may even be called with both infix and prefix arguments +at the same time. If you invoke a command as a suffix of a transient +prefix command, but also want to pass prefix arguments to it, then first +invoke the prefix command, and only after doing that invoke the prefix +arguments, before finally invoking the suffix command. If you instead +began by providing the prefix arguments, then those would apply to the +prefix command, not the suffix command. Likewise, if you want to change +infix arguments before invoking a suffix command with prefix arguments, +then change the infix arguments before invoking the prefix arguments. +In other words, regular prefix arguments always apply to the next +command, and since transient prefix, infix and suffix commands are just +regular commands, the same applies to them. (Regular prefix keys behave +differently because they are not commands at all, instead they are just +incomplete key sequences, and those cannot be interrupted with prefix +commands.) + + +File: transient.info, Node: Defining Transients, Next: Binding Suffix and Infix Commands, Prev: Technical Introduction, Up: Defining New Commands + +4.2 Defining Transients +======================= + +A transient consists of a prefix command and at least one suffix +command, though usually a transient has several infix and suffix +commands. The below macro defines the transient prefix command *and* +binds the transient’s infix and suffix commands. In other words, it +defines the complete transient, not just the transient prefix command +that is used to invoke that transient. + + -- Macro: transient-define-prefix name arglist [docstring] [keyword + value]... group... [body...] + This macro defines NAME as a transient prefix command and binds the + transient’s infix and suffix commands. + + ARGLIST are the arguments that the prefix command takes. DOCSTRING + is the documentation string and is optional. + + These arguments can optionally be followed by keyword-value pairs. + Each key has to be a keyword symbol, either ‘:class’ or a keyword + argument supported by the constructor of that class. The + ‘transient-prefix’ class is used if the class is not specified + explicitly. + + GROUPs add key bindings for infix and suffix commands and specify + how these bindings are presented in the popup buffer. At least one + GROUP has to be specified. See *note Binding Suffix and Infix + Commands::. + + The BODY is optional. If it is omitted, then ARGLIST is ignored + and the function definition becomes: + + (lambda () + (interactive) + (transient-setup 'NAME)) + + If BODY is specified, then it must begin with an ‘interactive’ form + that matches ARGLIST, and it must call ‘transient-setup’. It may, + however, call that function only when some condition is satisfied. + + All transients have a (possibly ‘nil’) value, which is exported + when suffix commands are called, so that they can consume that + value. For some transients it might be necessary to have a sort of + secondary value, called a “scope”. Such a scope would usually be + set in the command’s ‘interactive’ form and has to be passed to the + setup function: + + (transient-setup 'NAME nil nil :scope SCOPE) + + For example, the scope of the ‘magit-branch-configure’ transient is + the branch whose variables are being configured. + + +File: transient.info, Node: Binding Suffix and Infix Commands, Next: Defining Suffix and Infix Commands, Prev: Defining Transients, Up: Defining New Commands + +4.3 Binding Suffix and Infix Commands +===================================== + +The macro ‘transient-define-prefix’ is used to define a transient. This +defines the actual transient prefix command (see *note Defining +Transients::) and adds the transient’s infix and suffix bindings, as +described below. + + Users and third-party packages can add additional bindings using +functions such as ‘transient-insert-suffix’ (see *note Modifying +Existing Transients::). These functions take a “suffix specification” +as one of their arguments, which has the same form as the specifications +used in ‘transient-define-prefix’. + +* Menu: + +* Group Specifications:: +* Suffix Specifications:: + + +File: transient.info, Node: Group Specifications, Next: Suffix Specifications, Up: Binding Suffix and Infix Commands + +4.3.1 Group Specifications +-------------------------- + +The suffix and infix commands of a transient are organized in groups. +The grouping controls how the descriptions of the suffixes are outlined +visually but also makes it possible to set certain properties for a set +of suffixes. + + Several group classes exist, some of which organize suffixes in +subgroups. In most cases the class does not have to be specified +explicitly, but see *note Group Classes::. + + Groups are specified in the call to ‘transient-define-prefix’, using +vectors. Because groups are represented using vectors, we cannot use +square brackets to indicate an optional element and instead use curly +brackets to do the latter. + + Group specifications then have this form: + + [{LEVEL} {DESCRIPTION} {KEYWORD VALUE}... ELEMENT...] + + The LEVEL is optional and defaults to 4. See *note Enabling and +Disabling Suffixes::. + + The DESCRIPTION is optional. If present, it is used as the heading +of the group. + + The KEYWORD-VALUE pairs are optional. Each keyword has to be a +keyword symbol, either ‘:class’ or a keyword argument supported by the +constructor of that class. + + • One of these keywords, ‘:description’, is equivalent to specifying + DESCRIPTION at the very beginning of the vector. The + recommendation is to use ‘:description’ if some other keyword is + also used, for consistency, or DESCRIPTION otherwise, because it + looks better. + + • Likewise ‘:level’ is equivalent to LEVEL. + + • Other important keywords include the ‘:if...’ keywords. These + keywords control whether the group is available in a certain + situation. + + For example, one group of the ‘magit-rebase’ transient uses ‘:if + magit-rebase-in-progress-p’, which contains the suffixes that are + useful while rebase is already in progress; and another that uses + ‘:if-not magit-rebase-in-progress-p’, which contains the suffixes + that initiate a rebase. + + These predicates can also be used on individual suffixes and are + only documented once, see *note Predicate Slots::. + + • The value of ‘:hide’, if non-‘nil’, is a predicate that controls + whether the group is hidden by default. The key bindings for + suffixes of a hidden group should all use the same prefix key. + Pressing that prefix key should temporarily show the group and its + suffixes, which assumes that a predicate like this is used: + + (lambda () + (eq (car transient--redisplay-key) + ?\C-c)) ; the prefix key shared by all bindings + + • The value of ‘:setup-children’, if non-‘nil’, is a function that + takes one argument, a potentially list of children, and must return + a list of children or an empty list. This can either be used to + somehow transform the group’s children that were defined the normal + way, or to dynamically create the children from scratch. + + The returned children must have the same form as stored in the + prefix’s ‘transient--layout’ property, but it is often more + convenient to use the same form as understood by + ‘transient-define-prefix’, described below. If you use the latter + approach, you can use the ‘transient-parse-suffixes’ and + ‘transient-parse-suffix’ functions to transform them from the + convenient to the expected form. Depending on the used group + class, ‘transient-parse-suffixes’’s SUFFIXES must be a list of + group vectors (for ‘transient-columns’) or a list of suffix lists + (for all other group classes). + + If you explicitly specify children and then transform them using + ‘:setup-children’, then the class of the group is determined as + usual, based on explicitly specified children. + + If you do not explicitly specify children and thus rely solely on + ‘:setup-children’, then you must specify the class using ‘:class’. + For backward compatibility, if you fail to do so, + ‘transient-column’ is used and a warning is displayed. This + warning will eventually be replaced with an error. + + (transient-define-prefix my-finder-by-keyword () + "Select a keyword and list matching packages." + ;; The real `finder-by-keyword' is more convenient + ;; of course, but that is not the point here. + [:class transient-columns + :setup-children + (lambda (_) + (transient-parse-suffixes + 'my-finder-by-keyword + (let ((char (1- ?A))) + (mapcar ; a list ... + (lambda (partition) + (vconcat ; of group vectors ... + (mapcar (lambda (elt) + (let ((keyword (symbol-name (car elt)))) + ; ... where each suffix is a list + (list (format "%c" (cl-incf char)) + keyword + (lambda () + (interactive) + (finder-list-matches keyword))))) + partition))) + (seq-partition finder-known-keywords 7)))))]) + + • The boolean ‘:pad-keys’ argument controls whether keys of all + suffixes contained in a group are right padded, effectively + aligning the descriptions. + + The ELEMENTs are either all subgroups, or all suffixes and strings. +(At least currently no group type exists that would allow mixing +subgroups with commands at the same level, though in principle there is +nothing that prevents that.) + + If the ELEMENTs are not subgroups, then they can be a mixture of +lists, which specify commands, and strings. Strings are inserted +verbatim into the buffer. The empty string can be used to insert gaps +between suffixes, which is particularly useful if the suffixes are +outlined as a table. + + Inside group specifications, including inside contained suffix +specifications, nothing has to be quoted and quoting anyway is invalid. +The value following a keyword, can be explicitly unquoted using ‘,’. +This feature is experimental and should be avoided. + + The form of suffix specifications is documented in the next node. + + +File: transient.info, Node: Suffix Specifications, Prev: Group Specifications, Up: Binding Suffix and Infix Commands + +4.3.2 Suffix Specifications +--------------------------- + +A transient’s suffix and infix commands are bound when the transient +prefix command is defined using ‘transient-define-prefix’, see *note +Defining Transients::. The commands are organized into groups, see +*note Group Specifications::. Here we describe the form used to bind an +individual suffix command. + + The same form is also used when later binding additional commands +using functions such as ‘transient-insert-suffix’, see *note Modifying +Existing Transients::. + + Note that an infix is a special kind of suffix. Depending on context +“suffixes” means “suffixes (including infixes)” or “non-infix suffixes”. +Here it means the former. + + Suffix specifications have this form: + + ([LEVEL] [KEY [DESCRIPTION]] COMMAND|ARGUMENT [KEYWORD VALUE]...) + + LEVEL, KEY and DESCRIPTION can also be specified using the KEYWORDs +‘:level’, ‘:key’ and ‘:description’. If the object that is associated +with COMMAND sets these properties, then they do not have to be +specified here. You can however specify them here anyway, possibly +overriding the object’s values just for the binding inside this +transient. + + • LEVEL is the suffix level, an integer between 1 and 7. See *note + Enabling and Disabling Suffixes::. + + • KEY is the key binding, either a vector or key description string. + + • DESCRIPTION is the description, either a string or a function that + takes zero or one arguments (the suffix object) and returns a + string. The function should be a lambda expression to avoid + ambiguity. In some cases a symbol that is bound as a function + would also work but to be safe you should use ‘:description’ in + that case. + + The next element is either a command or an argument. This is the +only argument that is mandatory in all cases. + + • COMMAND should be a symbol that is bound as a function, which has + to be defined or at least autoloaded as a command by the time the + containing prefix command is invoked. + + Any command will do; it does not need to have an object associated + with it (as would be the case if ‘transient-define-suffix’ or + ‘transient-define-infix’ were used to define it). + + COMMAND can also be a ‘lambda’ expression. + + As mentioned above, the object that is associated with a command + can be used to set the default for certain values that otherwise + have to be set in the suffix specification. Therefore if there is + no object, then you have to make sure to specify the KEY and the + DESCRIPTION. + + As a special case, if you want to add a command that might be + neither defined nor autoloaded, you can use a workaround like: + + (transient-insert-suffix 'some-prefix "k" + '("!" "Ceci n'est pas une commande" no-command + :if (lambda () (featurep 'no-library)))) + + Instead of ‘featurep’ you could also use ‘require’ with a non-‘nil’ + value for NOERROR. + + • The mandatory argument can also be a command-line argument, a + string. In that case an anonymous command is defined and bound. + + Instead of a string, this can also be a list of two strings, in + which case the first string is used as the short argument (which + can also be specified using ‘:shortarg’) and the second as the long + argument (which can also be specified using ‘:argument’). + + Only the long argument is displayed in the popup buffer. See + ‘transient-detect-key-conflicts’ for how the short argument may be + used. + + Unless the class is specified explicitly, the appropriate class is + guessed based on the long argument. If the argument ends with ‘=’ + (e.g., ‘--format=’) then ‘transient-option’ is used, otherwise + ‘transient-switch’. + + Finally, details can be specified using optional KEYWORD-VALUE pairs. +Each keyword has to be a keyword symbol, either ‘:class’ or a keyword +argument supported by the constructor of that class. See *note Suffix +Slots::. + + +File: transient.info, Node: Defining Suffix and Infix Commands, Next: Using Infix Arguments, Prev: Binding Suffix and Infix Commands, Up: Defining New Commands + +4.4 Defining Suffix and Infix Commands +====================================== + +Note that an infix is a special kind of suffix. Depending on context +“suffixes” means “suffixes (including infixes)” or “non-infix suffixes”. + + -- Macro: transient-define-suffix name arglist [docstring] [keyword + value]... body... + This macro defines NAME as a transient suffix command. + + ARGLIST are the arguments that the command takes. DOCSTRING is the + documentation string and is optional. + + These arguments can optionally be followed by keyword-value pairs. + Each keyword has to be a keyword symbol, either ‘:class’ or a + keyword argument supported by the constructor of that class. The + ‘transient-suffix’ class is used if the class is not specified + explicitly. + + The BODY must begin with an ‘interactive’ form that matches + ARGLIST. The infix arguments are usually accessed by using + ‘transient-args’ inside ‘interactive’. + + -- Macro: transient-define-infix name arglist [docstring] [keyword + value]... + This macro defines NAME as a transient infix command. + + ARGLIST is always ignored (but mandatory never-the-less) and + reserved for future use. DOCSTRING is the documentation string and + is optional. + + At least one key-value pair is required. All transient infix + commands are ‘equal’ to each other (but not ‘eq’). It is + meaningless to define an infix command, without providing at least + one keyword argument (usually ‘:argument’ or ‘:variable’, depending + on the class). The suffix class defaults to ‘transient-switch’ and + can be set using the ‘:class’ keyword. + + The function definition is always: + + (lambda () + (interactive) + (let ((obj (transient-suffix-object))) + (transient-infix-set obj (transient-infix-read obj))) + (transient--show)) + + ‘transient-infix-read’ and ‘transient-infix-set’ are generic + functions. Different infix commands behave differently because the + concrete methods are different for different infix command classes. + In rare cases the above command function might not be suitable, + even if you define your own infix command class. In that case you + have to use ‘transient-define-suffix’ to define the infix command + and use ‘t’ as the value of the ‘:transient’ keyword. + + -- Macro: transient-define-argument name arglist [docstring] [keyword + value]... + This macro defines NAME as a transient infix command. + + This is an alias for ‘transient-define-infix’. Only use this alias + to define an infix command that actually sets an infix argument. + To define an infix command that, for example, sets a variable, use + ‘transient-define-infix’ instead. + + +File: transient.info, Node: Using Infix Arguments, Next: Transient State, Prev: Defining Suffix and Infix Commands, Up: Defining New Commands + +4.5 Using Infix Arguments +========================= + +The functions and the variables described below allow suffix commands to +access the value of the transient from which they were invoked; which is +the value of its infix arguments. These variables are set when the user +invokes a suffix command that exits the transient, but before actually +calling the command. + + When returning to the command-loop after calling the suffix command, +the arguments are reset to ‘nil’ (which causes the function to return +‘nil’ too). + + Like for Emacs’s prefix arguments, it is advisable, but not +mandatory, to access the infix arguments inside the command’s +‘interactive’ form. The preferred way of doing that is to call the +‘transient-args’ function, which for infix arguments serves about the +same purpose as ‘prefix-arg’ serves for prefix arguments. + + -- Function: transient-args prefix + This function returns the value of the transient prefix command + PREFIX. + + If the current command was invoked from the transient prefix + command PREFIX, then it returns the active infix arguments. If the + current command was not invoked from PREFIX, then it returns the + set, saved or default value for PREFIX. + + -- Function: transient-arg-value arg args + This function return the value of ARG as it appears in ARGS. + + For a switch a boolean is returned. For an option the value is + returned as a string, using the empty string for the empty value, + or ‘nil’ if the option does not appear in ARGS. + + -- Function: transient-suffixes prefix + This function returns the suffixes of the transient prefix command + PREFIX. This is a list of objects. This function should only be + used if you need the objects (as opposed to just their values) and + if the current command is not being invoked from PREFIX. + + -- Variable: transient-current-suffixes + The suffixes of the transient from which this suffix command was + invoked. This is a list of objects. Usually it is sufficient to + instead use the function ‘transient-args’, which returns a list of + values. In complex cases it might be necessary to use this + variable instead, i.e., if you need access to information beside + the value. + + -- Variable: transient-current-command + The transient from which this suffix command was invoked. The + returned value is a symbol, the transient prefix command. + + -- Variable: transient-current-prefix + The transient from which this suffix command was invoked. The + returned value is a ‘transient-prefix’ object, which holds + information associated with the transient prefix command. + + -- Function: transient-active-prefix + This function returns the active transient object. Return ‘nil’ if + there is no active transient, if the transient buffer isn’t shown, + and while the active transient is suspended (e.g., while the + minibuffer is in use). + + Unlike ‘transient-current-prefix’, which is only ever non-‘nil’ in + code that is run directly by a command that is invoked while a + transient is current, this function is also suitable for use in + asynchronous code, such as timers and callbacks (this function’s + main use-case). + + If optional PREFIXES is non-‘nil’, it must be a prefix command + symbol or a list of symbols, in which case the active transient + object is only returned if it matches one of the PREFIXES. + + +File: transient.info, Node: Transient State, Prev: Using Infix Arguments, Up: Defining New Commands + +4.6 Transient State +=================== + +Invoking a transient prefix command “activates” the respective +transient, i.e., it puts a transient keymap into effect, which binds the +transient’s infix and suffix commands. + + The default behavior while a transient is active is as follows: + + • Invoking an infix command does not affect the transient state; the + transient remains active. + + • Invoking a (non-infix) suffix command “deactivates” the transient + state by removing the transient keymap and performing some + additional cleanup. + + • Invoking a command that is bound in a keymap other than the + transient keymap is disallowed and trying to do so results in a + warning. This does not “deactivate” the transient. + + The behavior can be changed for all suffixes of a particular prefix +and/or for individual suffixes. The values should nearly always be +booleans, but certain functions, called “pre-commands”, can also be +used. These functions are named ‘transient--do-VERB’, and the symbol +‘VERB’ can be used as a shorthand. + + A boolean is interpreted as answering the question "does the +transient stay active, when this command is invoked?" ‘t’ means that +the transient stays active, while ‘nil’ means that invoking the command +exits the transient. + + Note that when the suffix is a “sub-prefix”, invoking that command +always activates that sub-prefix, causing the outer prefix to no longer +be active and displayed. Here ‘t’ means that when you exit the inner +prefix, then the outer prefix becomes active again, while ‘nil’ means +that all outer prefixes are exited at once. + + • The behavior for non-suffixes can be set for a particular prefix, + by the prefix’s ‘transient-non-suffix’ slot to a boolean, a + suitable pre-command function, or a shorthand for such a function. + See *note Pre-commands for Non-Suffixes::. + + • The common behavior for the suffixes of a particular prefix can be + set using the prefix’s ‘transient-suffixes’ slot. + + The value specified in this slot does *not* affect infixes. + Because it affects both regular suffixes as well as sub-prefixes, + which have different needs, it is best to avoid explicitly + specifying a function. + + • The behavior of an individual suffix can be changed using its + ‘transient’ slot. While it is usually best to use a boolean, for + this slot it can occasionally make sense to specify a function + explicitly. + + Note that this slot can be set when defining a suffix command using + ‘transient-define-suffix’ and/or in the definition of the prefix. + If set in both places, then the latter takes precedence, as usual. + + The available pre-command functions are documented in the following +sub-sections. They are called by ‘transient--pre-command’, a function +on ‘pre-command-hook’, and the value that they return determines whether +the transient is exited. To do so the value of one of the constants +‘transient--exit’ or ‘transient--stay’ is used (that way we don’t have +to remember if ‘t’ means “exit” or “stay”). + + Additionally, these functions may change the value of ‘this-command’ +(which explains why they have to be called using ‘pre-command-hook’), +call ‘transient-export’, ‘transient--stack-zap’ or +‘transient--stack-push’; and set the values of ‘transient--exitp’, +‘transient--helpp’ or ‘transient--editp’. + + For completeness sake, some notes about complications: + + • The transient-ness of certain built-in suffix commands is specified + using ‘transient-predicate-map’. This is a special keymap, which + binds commands to pre-commands (as opposed to keys to commands) and + takes precedence over the prefix’s ‘transient-suffix’ slot, but not + the suffix’s ‘transient’ slot. + + • While a sub-prefix is active we nearly always want ‘C-g’ to take + the user back to the “super-prefix”, even when the other suffixes + don’t do that. However, in rare cases this may not be desirable, + and that makes the following complication necessary: + + For ‘transient-suffix’ objects the ‘transient’ slot is unbound. We + can ignore that for the most part because ‘nil’ and the slot being + unbound are treated as equivalent, and mean “do exit”. That isn’t + actually true for suffixes that are sub-prefixes though. For such + suffixes unbound means “do exit but allow going back”, which is the + default, while ‘nil’ means “do exit permanently”, which requires + that slot to be explicitly set to that value. + +Pre-commands for Infixes +------------------------ + +The default for infixes is ‘transient--do-stay’. This is also the only +function that makes sense for infixes, which is why this predicate is +used even if the value of the prefix’s ‘transient-suffix’ slot is ‘t’. +In extremely rare cases, one might want to use something else, which can +be done by setting the infix’s ‘transient’ slot directly. + + -- Function: transient--do-stay + Call the command without exporting variables and stay transient. + +Pre-commands for Suffixes +------------------------- + +By default, invoking a suffix causes the transient to be exited. + + The behavior for an individual suffix command can be changed by +setting its ‘transient’ slot to a boolean (which is highly recommended), +or to one of the following pre-commands. + + -- Function: transient--do-exit + Call the command after exporting variables and exit the transient. + + -- Function: transient--do-return + Call the command after exporting variables and return to the parent + prefix. If there is no parent prefix, then call + ‘transient--do-exit’. + + -- Function: transient--do-call + Call the command after exporting variables and stay transient. + + The following pre-commands are only suitable for sub-prefixes. It is +not necessary to explicitly use these predicates because the correct +predicate is automatically picked based on the value of the ‘transient’ +slot for the sub-prefix itself. + + -- Function: transient--do-recurse + Call the transient prefix command, preparing for return to active + transient. + + Whether we actually return to the parent transient is ultimately + under the control of each invoked suffix. The difference between + this pre-command and ‘transient--do-stack’ is that it changes the + value of the ‘transient-suffix’ slot to ‘t’. + + If there is no parent transient, then only call this command and + skip the second step. + + -- Function: transient--do-stack + Call the transient prefix command, stacking the active transient. + Push the active transient to the transient stack. + + Unless ‘transient--do-recurse’ is explicitly used, this pre-command + is automatically used for suffixes that are prefixes themselves, + i.e., for sub-prefixes. + + -- Function: transient--do-replace + Call the transient prefix command, replacing the active transient. + Do not push the active transient to the transient stack. + + Unless ‘transient--do-recurse’ is explicitly used, this pre-command + is automatically used for suffixes that are prefixes themselves, + i.e., for sub-prefixes. + + -- Function: transient--do-suspend + Suspend the active transient, saving the transient stack. + + This is used by the command ‘transient-suspend’ and optionally also + by “external events” such as ‘handle-switch-frame’. Such bindings + should be added to ‘transient-predicate-map’. + +Pre-commands for Non-Suffixes +----------------------------- + +By default, non-suffixes (commands that are bound in other keymaps +beside the transient keymap) cannot be invoked. Trying to invoke such a +command results in a warning and the transient stays active. + + If you want a different behavior, then set the ‘transient-non-suffix’ +slot of the transient prefix command. The value should be a boolean, +answering the question, "is it allowed to invoke non-suffix commands?, a +pre-command function, or a shorthand for such a function. + + If the value is ‘t’, then non-suffixes can be invoked, when it is +‘nil’ (the default) then they cannot be invoked. + + The only other recommended value is ‘leave’. If that is used, then +non-suffixes can be invoked, but if one is invoked, then that exits the +transient. + + -- Function: transient--do-warn + Call ‘transient-undefined’ and stay transient. + + -- Function: transient--do-stay + Call the command without exporting variables and stay transient. + + -- Function: transient--do-leave + Call the command without exporting variables and exit the + transient. + +Special Pre-Commands +-------------------- + + -- Function: transient--do-quit-one + If active, quit help or edit mode, else exit the active transient. + + This is used when the user pressed ‘C-g’. + + -- Function: transient--do-quit-all + Exit all transients without saving the transient stack. + + This is used when the user pressed ‘C-q’. + + -- Function: transient--do-suspend + Suspend the active transient, saving the transient stack. + + This is used when the user pressed ‘C-z’. + + +File: transient.info, Node: Classes and Methods, Next: FAQ, Prev: Defining New Commands, Up: Top + +5 Classes and Methods +********************* + +Transient uses classes and generic functions to make it possible to +define new types of suffix commands that are similar to existing types, +but behave differently in some aspects. It does the same for groups and +prefix commands, though at least for prefix commands that *currently* +appears to be less important. + + Every prefix, infix and suffix command is associated with an object, +which holds information that controls certain aspects of its behavior. +This happens in two ways. + + • Associating a command with a certain class gives the command a + type. This makes it possible to use generic functions to do + certain things that have to be done differently depending on what + type of command it acts on. + + That in turn makes it possible for third-parties to add new types + without having to convince the maintainer of Transient that that + new type is important enough to justify adding a special case to a + dozen or so functions. + + • Associating a command with an object makes it possible to easily + store information that is specific to that particular command. + + Two commands may have the same type, but obviously their key + bindings and descriptions still have to be different, for example. + + The values of some slots are functions. The ‘reader’ slot for + example holds a function that is used to read a new value for an + infix command. The values of such slots are regular functions. + + Generic functions are used when a function should do something + different based on the type of the command, i.e., when all commands + of a certain type should behave the same way but different from the + behavior for other types. Object slots that hold a regular + function as value are used when the task that they perform is + likely to differ even between different commands of the same type. + +* Menu: + +* Group Classes:: +* Group Methods:: +* Prefix Classes:: +* Suffix Classes:: +* Suffix Methods:: +* Prefix Slots:: +* Suffix Slots:: +* Predicate Slots:: + + +File: transient.info, Node: Group Classes, Next: Group Methods, Up: Classes and Methods + +5.1 Group Classes +================= + +The type of a group can be specified using the ‘:class’ property at the +beginning of the class specification, e.g., ‘[:class transient-columns +...]’ in a call to ‘transient-define-prefix’. + + • The abstract ‘transient-child’ class is the base class of both + ‘transient-group’ (and therefore all groups) as well as of + ‘transient-suffix’ (and therefore all suffix and infix commands). + + This class exists because the elements (or “children”) of certain + groups can be other groups instead of suffix and infix commands. + + • The abstract ‘transient-group’ class is the superclass of all other + group classes. + + • The ‘transient-column’ class is the simplest group. + + This is the default “flat” group. If the class is not specified + explicitly and the first element is not a vector (i.e., not a + group), then this class is used. + + This class displays each element on a separate line. + + • The ‘transient-row’ class displays all elements on a single line. + + • The ‘transient-columns’ class displays commands organized in + columns. + + Direct elements have to be groups whose elements have to be + commands or strings. Each subgroup represents a column. This + class takes care of inserting the subgroups’ elements. + + This is the default “nested” group. If the class is not specified + explicitly and the first element is a vector (i.e., a group), then + this class is used. + + • The ‘transient-subgroups’ class wraps other groups. + + Direct elements have to be groups whose elements have to be + commands or strings. This group inserts an empty line between + subgroups. The subgroups themselves are responsible for displaying + their elements. + + +File: transient.info, Node: Group Methods, Next: Prefix Classes, Prev: Group Classes, Up: Classes and Methods + +5.2 Group Methods +================= + + -- Function: transient-setup-children group children + This generic function can be used to setup the children or a group. + + The default implementation usually just returns the children + unchanged, but if the ‘setup-children’ slot of GROUP is non-‘nil’, + then it calls that function with CHILDREN as the only argument and + returns the value. + + The children are given as a (potentially empty) list consisting of + either group or suffix specifications. These functions can make + arbitrary changes to the children including constructing new + children from scratch. + + -- Function: transient--insert-group group + This generic function formats the group and its elements and + inserts the result into the current buffer, which is a temporary + buffer. The contents of that buffer are later inserted into the + popup buffer. + + Functions that are called by this function may need to operate in + the buffer from which the transient was called. To do so they can + temporarily make the ‘transient--source-buffer’ the current buffer. + + +File: transient.info, Node: Prefix Classes, Next: Suffix Classes, Prev: Group Methods, Up: Classes and Methods + +5.3 Prefix Classes +================== + +Currently the ‘transient-prefix’ class is being used for all prefix +commands and there is only a single generic function that can be +specialized based on the class of a prefix command. + + -- Function: transient--history-init obj + This generic function is called while setting up the transient and + is responsible for initializing the ‘history’ slot. This is the + transient-wide history; many individual infixes also have a history + of their own. + + The default (and currently only) method extracts the value from the + global variable ‘transient-history’. + + A transient prefix command’s object is stored in the +‘transient--prefix’ property of the command symbol. While a transient +is active, a clone of that object is stored in the variable +‘transient--prefix’. A clone is used because some changes that are made +to the active transient’s object should not affect later invocations. + + +File: transient.info, Node: Suffix Classes, Next: Suffix Methods, Prev: Prefix Classes, Up: Classes and Methods + +5.4 Suffix Classes +================== + + • All suffix and infix classes derive from ‘transient-suffix’, which + in turn derives from ‘transient-child’, from which + ‘transient-group’ also derives (see *note Group Classes::). + + • All infix classes derive from the abstract ‘transient-infix’ class, + which in turn derives from the ‘transient-suffix’ class. + + Infixes are a special type of suffixes. The primary difference is + that infixes always use the ‘transient--do-stay’ pre-command, while + non-infix suffixes use a variety of pre-commands (see *note + Transient State::). Doing that is most easily achieved by using + this class, though theoretically it would be possible to define an + infix class that does not do so. If you do that then you get to + implement many methods. + + Also, infixes and non-infix suffixes are usually defined using + different macros (see *note Defining Suffix and Infix Commands::). + + • Classes used for infix commands that represent arguments should be + derived from the abstract ‘transient-argument’ class. + + • The ‘transient-switch’ class (or a derived class) is used for infix + arguments that represent command-line switches (arguments that do + not take a value). + + • The ‘transient-option’ class (or a derived class) is used for infix + arguments that represent command-line options (arguments that do + take a value). + + • The ‘transient-switches’ class can be used for a set of mutually + exclusive command-line switches. + + • The ‘transient-files’ class can be used for a ‘--’ argument that + indicates that all remaining arguments are files. + + • Classes used for infix commands that represent variables should + derived from the abstract ‘transient-variable’ class. + + • The ‘transient-information’ class is special in that suffixes that + use this class are not associated with a command and thus also not + with any key binding. Such suffixes are only used to display + arbitrary information, and that anywhere a suffix can appear. + Display-only suffix specifications take this form: + + ([LEVEL] :info DESCRIPTION [KEYWORD VALUE]...) + + The ‘:info’ keyword argument replaces the ‘:description’ keyword + used for other suffix classes. Other keyword arguments that you + might want to set, include ‘:face’, predicate keywords (such as + ‘:if’), and ‘:format’. By default the value of ‘:format’ includes + ‘%k’, which for this class is replaced with the empty string or + spaces, if keys are being padded in the containing group. + + Magit defines additional classes, which can serve as examples for the +fancy things you can do without modifying Transient. Some of these +classes will likely get generalized and added to Transient. For now +they are very much subject to change and not documented. + + +File: transient.info, Node: Suffix Methods, Next: Prefix Slots, Prev: Suffix Classes, Up: Classes and Methods + +5.5 Suffix Methods +================== + +To get information about the methods implementing these generic +functions use ‘describe-function’. + +* Menu: + +* Suffix Value Methods:: +* Suffix Format Methods:: + + +File: transient.info, Node: Suffix Value Methods, Next: Suffix Format Methods, Up: Suffix Methods + +5.5.1 Suffix Value Methods +-------------------------- + + -- Function: transient-init-value obj + This generic function sets the initial value of the object OBJ. + + This function is called for all suffix commands, but unless a + concrete method is implemented this falls through to the default + implementation, which is a noop. In other words this usually only + does something for infix commands, but note that this is not + implemented for the abstract class ‘transient-infix’, so if your + class derives from that directly, then you must implement a method. + + -- Function: transient-infix-read obj + This generic function determines the new value of the infix object + OBJ. + + This function merely determines the value; ‘transient-infix-set’ is + used to actually store the new value in the object. + + For most infix classes this is done by reading a value from the + user using the reader specified by the ‘reader’ slot (using the + ‘transient-infix-value’ method described below). + + For some infix classes the value is changed without reading + anything in the minibuffer, i.e., the mere act of invoking the + infix command determines what the new value should be, based on the + previous value. + + -- Function: transient-prompt obj + This generic function returns the prompt to be used to read infix + object OBJ’s value. + + -- Function: transient-infix-set obj value + This generic function sets the value of infix object OBJ to VALUE. + + -- Function: transient-infix-value obj + This generic function returns the value of the suffix object OBJ. + + This function is called by ‘transient-args’ (which see), meaning + this function is how the value of a transient is determined so that + the invoked suffix command can use it. + + Currently most values are strings, but that is not set in stone. + ‘nil’ is not a value, it means “no value”. + + Usually only infixes have a value, but see the method for + ‘transient-suffix’. + + -- Function: transient-init-scope obj + This generic function sets the scope of the suffix object OBJ. + + The scope is actually a property of the transient prefix, not of + individual suffixes. However it is possible to invoke a suffix + command directly instead of from a transient. In that case, if the + suffix expects a scope, then it has to determine that itself and + store it in its ‘scope’ slot. + + This function is called for all suffix commands, but unless a + concrete method is implemented this falls through to the default + implementation, which is a noop. + + +File: transient.info, Node: Suffix Format Methods, Prev: Suffix Value Methods, Up: Suffix Methods + +5.5.2 Suffix Format Methods +--------------------------- + + -- Function: transient-format obj + This generic function formats and returns OBJ for display. + + When this function is called, then the current buffer is some + temporary buffer. If you need the buffer from which the prefix + command was invoked to be current, then do so by temporarily making + ‘transient--source-buffer’ current. + + -- Function: transient-format-key obj + This generic function formats OBJ’s ‘key’ for display and returns + the result. + + -- Function: transient-format-description obj + This generic function formats OBJ’s ‘description’ for display and + returns the result. + + -- Function: transient-format-value obj + This generic function formats OBJ’s value for display and returns + the result. + + -- Function: transient-show-help obj + Show help for the prefix, infix or suffix command represented by + OBJ. + + Regardless of OBJ’s type, if its ‘show-help’ slot is non-nil, that + must be a function, which takes OBJ is its only argument. It must + prepare, display and return a buffer, and select the window used to + display it. The ‘transient-show-help-window’ macro is intended for + use in such functions. + + For prefixes, show the info manual, if that is specified using the + ‘info-manual’ slot. Otherwise, show the manpage if that is + specified using the ‘man-page’ slot. Otherwise, show the command’s + documentation string. + + For suffixes, show the command’s documentation string. + + For infixes, show the manpage if that is specified. Otherwise show + the command’s documentation string. + + -- Macro: transient-with-help-window &rest body + Evaluate BODY, send output to ‘*Help*’ buffer, and display it in a + window. Select the help window, and make the help buffer current + and return it. + + +File: transient.info, Node: Prefix Slots, Next: Suffix Slots, Prev: Suffix Methods, Up: Classes and Methods + +5.6 Prefix Slots +================ + + • ‘show-help’, ‘man-page’ or ‘info-manual’ can be used to specify the + documentation for the prefix and its suffixes. The command + ‘transient-help’ uses the function ‘transient-show-help’ (which + see) to lookup and use these values. + + • ‘history-key’ If multiple prefix commands should share a single + value, then this slot has to be set to the same value for all of + them. You probably don’t want that. + + • ‘transient-suffix’ and ‘transient-non-suffix’ play a part when + determining whether the currently active transient prefix command + remains active/transient when a suffix or arbitrary non-suffix + command is invoked. See *note Transient State::. + + • ‘refresh-suffixes’ Normally suffix objects and keymaps are only + setup once, when the prefix is invoked. Setting this to ‘t’, + causes them to be recreated after every command. This is useful + when using ‘:if...’ predicates, and those need to be rerun for some + reason. Doing this is somewhat costly, and there is a risk of + losing state, so this is disabled by default and still considered + experimental. + + • ‘incompatible’ A list of lists. Each sub-list specifies a set of + mutually exclusive arguments. Enabling one of these arguments + causes the others to be disabled. An argument may appear in + multiple sub-lists. Arguments must me given in the same form as + used in the ‘argument’ or ‘argument-format’ slot of the respective + suffix objects, usually something like ‘--switch’ or ‘--option=%s’. + For options and ‘transient-switches’ suffixes it is also possible + to match against a specific value, as returned by + ‘transient-infix-value’, for example, ‘--option=one’. + + • ‘scope’ For some transients it might be necessary to have a sort of + secondary value, called a “scope”. See ‘transient-define-prefix’. + +Internal Prefix Slots +--------------------- + +These slots are mostly intended for internal use. They should not be +set in calls to ‘transient-define-prefix’. + + • ‘prototype’ When a transient prefix command is invoked, then a + clone of that object is stored in the global variable + ‘transient--prefix’ and the prototype is stored in the clone’s + ‘prototype’ slot. + + • ‘command’ The command, a symbol. Each transient prefix command + consists of a command, which is stored in a symbol’s function slot + and an object, which is stored in the ‘transient--prefix’ property + of the same symbol. + + • ‘level’ The level of the prefix commands. The suffix commands + whose layer is equal or lower are displayed. See *note Enabling + and Disabling Suffixes::. + + • ‘value’ The likely outdated value of the prefix. Instead of + accessing this slot directly you should use the function + ‘transient-get-value’, which is guaranteed to return the up-to-date + value. + + • ‘history’ and ‘history-pos’ are used to keep track of historic + values. Unless you implement your own ‘transient-infix-read’ + method you should not have to deal with these slots. + + +File: transient.info, Node: Suffix Slots, Next: Predicate Slots, Prev: Prefix Slots, Up: Classes and Methods + +5.7 Suffix Slots +================ + +Here we document most of the slots that are only available for suffix +objects. Some slots are shared by suffix and group objects, they are +documented in *note Predicate Slots::. + + Also see *note Suffix Classes::. + +Slots of ‘transient-suffix’ +--------------------------- + + • ‘key’ The key, a key vector or a key description string. + + • ‘command’ The command, a symbol. + + • ‘transient’ Whether to stay transient. See *note Transient + State::. + + • ‘format’ The format used to display the suffix in the popup buffer. + It must contain the following %-placeholders: + + • ‘%k’ For the key. + • ‘%d’ For the description. + • ‘%v’ For the infix value. Non-infix suffixes don’t have a + value. + + • ‘description’ The description, either a string or a function, which + is called with zero or one argument (the suffix object), and + returns a string. + + • ‘face’ Face used for the description. In simple cases it is easier + to use this instead of using a function as ‘description’ and adding + the styling there. ‘face’ is appended using + ‘add-face-text-property’. + + • ‘show-help’ A function used to display help for the suffix. If + unspecified, the prefix controls how help is displayed for its + suffixes. See also function ‘transient-show-help’. + +Slots of ‘transient-infix’ +-------------------------- + +Some of these slots are only meaningful for some of the subclasses. +They are defined here anyway to allow sharing certain methods. + + • ‘argument’ The long argument, e.g., ‘--verbose’. + + • ‘shortarg’ The short argument, e.g., ‘-v’. + + • ‘value’ The value. Should not be accessed directly. + + • ‘init-value’ Function that is responsible for setting the object’s + value. If bound, then this is called with the object as the only + argument. Usually this is not bound, in which case the object’s + primary ‘transient-init-value’ method is called instead. + + • ‘unsavable’ Whether the value of the suffix is not saved as part of + the prefixes. + + • ‘multi-value’ For options, whether the option can have multiple + values. If this is non-‘nil’, then the values are read using + ‘completing-read-multiple’ by default and if you specify your own + reader, then it should read the values using that function or + similar. + + Supported non-‘nil’ values are: + + • Use ‘rest’ for an option that can have multiple values. This + is useful e.g., for an ‘--’ argument that indicates that all + remaining arguments are files (such as ‘git log -- file1 + file2’). + + In the list returned by ‘transient-args’ such an option and + its values are represented by a single list of the form + ‘(ARGUMENT . VALUES)’. + + • Use ‘repeat’ for an option that can be specified multiple + times. + + In the list returned by ‘transient-args’ each instance of the + option and its value appears separately in the usual from, for + example: ‘("--another-argument" "--option=first" + "--option=second")’. + + In both cases the option’s values have to be specified in the + default value of a prefix using the same format as returned by + ‘transient-args’, e.g., ‘("--other" "--o=1" "--o=2" ("--" "f1" + "f2"))’. + + • ‘always-read’ For options, whether to read a value on every + invocation. If this is ‘nil’, then options that have a value are + simply unset and have to be invoked a second time to set a new + value. + + • ‘allow-empty’ For options, whether the empty string is a valid + value. + + • ‘history-key’ The key used to store the history. This defaults to + the command name. This is useful when multiple infixes should + share the same history because their values are of the same kind. + + • ‘reader’ The function used to read the value of an infix. Not used + for switches. The function takes three arguments, PROMPT, + INITIAL-INPUT and HISTORY, and must return a string. + + • ‘prompt’ The prompt used when reading the value, either a string or + a function that takes the object as the only argument and which + returns a prompt string. + + • ‘choices’ A list of valid values, or a function that returns such a + list. The latter is not implemented for ‘transient-switches’, + because I couldn’t think of a use-case. How exactly the choices + are used varies depending on the class of the suffix. + +Slots of ‘transient-variable’ +----------------------------- + + • ‘variable’ The variable. + +Slots of ‘transient-switches’ +----------------------------- + + • ‘argument-format’ The display format. Must contain ‘%s’, one of + the ‘choices’ is substituted for that. E.g., ‘--%s-order’. + + • ‘argument-regexp’ The regexp used to match any one of the switches. + E.g., ‘\\(--\\(topo\\|author-date\\|date\\)-order\\)’. + + +File: transient.info, Node: Predicate Slots, Prev: Suffix Slots, Up: Classes and Methods + +5.8 Predicate Slots +=================== + +Suffix and group objects share some predicate slots that control whether +a group or suffix should be available depending on some state. Only one +of these slots can be used at the same time. It is undefined what +happens if you use more than one. + + • ‘if’ Enable if predicate returns non-‘nil’. + • ‘if-not’ Enable if predicate returns ‘nil’. + • ‘if-non-nil’ Enable if variable’s value is non-‘nil’. + • ‘if-nil’ Enable if variable’s value is ‘nil’. + • ‘if-mode’ Enable if major-mode matches value. + • ‘if-not-mode’ Enable if major-mode does not match value. + • ‘if-derived’ Enable if major-mode derives from value. + • ‘if-not-derived’ Enable if major-mode does not derive from value. + + By default these predicates run when the prefix command is invoked, +but this can be changes, using the ‘refresh-suffixes’ prefix slot. See +*note Prefix Slots::. + + One more slot is shared between group and suffix classes, ‘level’. +Like the slots documented above, it is a predicate, but it is used for a +different purpose. The value has to be an integer between 1 and 7. +‘level’ controls whether a suffix or a group should be available +depending on user preference. See *note Enabling and Disabling +Suffixes::. + + +File: transient.info, Node: FAQ, Next: Keystroke Index, Prev: Classes and Methods, Up: Top + +Appendix A FAQ +************** + +A.1 Can I control how the popup buffer is displayed? +==================================================== + +Yes, see ‘transient-display-buffer-action’ in *note Configuration::. + +A.2 How can I copy text from the popup buffer? +============================================== + +To be able to mark text in Transient’s popup buffer using the mouse, you +have to add the below binding. Note that for technical reasons, the +region won’t be visualized, while doing so. After you have quit the +transient popup, you will be able to yank it in another buffer. + + (keymap-set transient-predicate-map + "<mouse-set-region>" + #'transient--do-stay) + +A.3 How can I autoload prefix and suffix commands? +================================================== + +If your package only supports Emacs 30, just prefix the definition with +‘;;;###autoload’. If your package supports released versions of Emacs, +you unfortunately have to use a long form autoload comment as described +in *note (elisp)Autoload::. + + ;;;###autoload (autoload 'magit-dispatch "magit" nil t) + (transient-define-prefix magit-dispatch () + ...) + +A.4 How does Transient compare to prefix keys and universal arguments? +====================================================================== + +See +<https://github.com/magit/transient/wiki/Comparison-with-prefix-keys-and-universal-arguments>. + +A.5 How does Transient compare to Magit-Popup and Hydra? +======================================================== + +See +<https://github.com/magit/transient/wiki/Comparison-with-other-packages>. + +A.6 Why did some of the key bindings change? +============================================ + +You may have noticed that the bindings for some of the common commands +do *not* have the prefix ‘C-x’ and that furthermore some of these +commands are grayed out while others are not. That unfortunately is a +bit confusing if the section of common commands is not shown +permanently, making the following explanation necessary. + + The purpose of usually hiding that section but showing it after the +user pressed the respective prefix key is to conserve space and not +overwhelm users with too much noise, while allowing the user to quickly +list common bindings on demand. + + That however should not keep us from using the best possible key +bindings. The bindings that do use a prefix do so to avoid wasting too +many non-prefix bindings, keeping them available for use in individual +transients. The bindings that do not use a prefix and that are *not* +grayed out are very important bindings that are *always* available, even +when invoking the “common command key prefix” or *any other* +transient-specific prefix. The non-prefix keys that *are* grayed out +however, are not available when any incomplete prefix key sequence is +active. They do not use the “common command key prefix” because it is +likely that users want to invoke them several times in a row and e.g., +‘M-p M-p M-p’ is much more convenient than ‘C-x M-p C-x M-p C-x M-p’. + + You may also have noticed that the “Set” command is bound to ‘C-x s’, +while Magit-Popup used to bind ‘C-c C-c’ instead. I have seen several +users praise the latter binding (sic), so I did not change it +willy-nilly. The reason that I changed it is that using different +prefix keys for different common commands, would have made the temporary +display of the common commands even more confusing, i.e., after pressing +‘C-c’ all the bindings that begin with the ‘C-x’ prefix would be grayed +out. + + Using a single prefix for common commands key means that all other +potential prefix keys can be used for transient-specific commands +*without* the section of common commands also popping up. ‘C-c’ in +particular is a prefix that I want to (and already do) use for Magit, +and also using that for a common command would prevent me from doing so. + + (Also see the next question.) + +A.7 Why does ‘q’ not quit popups anymore? +========================================= + +I agree that ‘q’ is a good binding for commands that quit something. +This includes quitting whatever transient is currently active, but it +also includes quitting whatever it is that some specific transient is +controlling. The transient ‘magit-blame’ for example binds ‘q’ to the +command that turns ‘magit-blame-mode’ off. + + So I had to decide if ‘q’ should quit the active transient (like +Magit-Popup used to) or whether ‘C-g’ should do that instead, so that +‘q’ could be bound in individual transient to whatever commands make +sense for them. Because all other letters are already reserved for use +by individual transients, I have decided to no longer make an exception +for ‘q’. + + If you want to get ‘q’’s old binding back then you can do so. Doing +that is a bit more complicated than changing a single key binding, so I +have implemented a function, ‘transient-bind-q-to-quit’ that makes the +necessary changes. See its documentation string for more information. + + +File: transient.info, Node: Keystroke Index, Next: Command and Function Index, Prev: FAQ, Up: Top + +Appendix B Keystroke Index +************************** + + +* Menu: + +* C-g: Aborting and Resuming Transients. + (line 27) +* C-g <1>: Aborting and Resuming Transients. + (line 27) +* C-h: Getting Help for Suffix Commands. + (line 11) +* C-M-n: Using History. (line 18) +* C-M-p: Using History. (line 13) +* C-q: Aborting and Resuming Transients. + (line 36) +* C-x a: Enabling and Disabling Suffixes. + (line 68) +* C-x C-k: Saving Values. (line 29) +* C-x C-s: Saving Values. (line 25) +* C-x l: Enabling and Disabling Suffixes. + (line 43) +* C-x n: Using History. (line 18) +* C-x p: Using History. (line 13) +* C-x s: Saving Values. (line 21) +* C-x t: Common Suffix Commands. + (line 18) +* C-z: Aborting and Resuming Transients. + (line 41) + + +File: transient.info, Node: Command and Function Index, Next: Variable Index, Prev: Keystroke Index, Up: Top + +Appendix C Command and Function Index +************************************* + + +* Menu: + +* transient--do-call: Transient State. (line 125) +* transient--do-exit: Transient State. (line 117) +* transient--do-leave: Transient State. (line 193) +* transient--do-quit-all: Transient State. (line 205) +* transient--do-quit-one: Transient State. (line 200) +* transient--do-recurse: Transient State. (line 133) +* transient--do-replace: Transient State. (line 153) +* transient--do-return: Transient State. (line 120) +* transient--do-stack: Transient State. (line 145) +* transient--do-stay: Transient State. (line 105) +* transient--do-stay <1>: Transient State. (line 190) +* transient--do-suspend: Transient State. (line 161) +* transient--do-suspend <1>: Transient State. (line 210) +* transient--do-warn: Transient State. (line 187) +* transient--history-init: Prefix Classes. (line 10) +* transient--insert-group: Group Methods. (line 19) +* transient-active-prefix: Using Infix Arguments. + (line 61) +* transient-append-suffix: Modifying Existing Transients. + (line 51) +* transient-arg-value: Using Infix Arguments. + (line 31) +* transient-args: Using Infix Arguments. + (line 22) +* transient-define-argument: Defining Suffix and Infix Commands. + (line 57) +* transient-define-infix: Defining Suffix and Infix Commands. + (line 26) +* transient-define-prefix: Defining Transients. (line 13) +* transient-define-suffix: Defining Suffix and Infix Commands. + (line 9) +* transient-format: Suffix Format Methods. + (line 6) +* transient-format-description: Suffix Format Methods. + (line 18) +* transient-format-key: Suffix Format Methods. + (line 14) +* transient-format-value: Suffix Format Methods. + (line 22) +* transient-get-suffix: Modifying Existing Transients. + (line 73) +* transient-help: Getting Help for Suffix Commands. + (line 11) +* transient-history-next: Using History. (line 18) +* transient-history-prev: Using History. (line 13) +* transient-infix-read: Suffix Value Methods. + (line 16) +* transient-infix-set: Suffix Value Methods. + (line 36) +* transient-infix-value: Suffix Value Methods. + (line 39) +* transient-init-scope: Suffix Value Methods. + (line 52) +* transient-init-value: Suffix Value Methods. + (line 6) +* transient-insert-suffix: Modifying Existing Transients. + (line 49) +* transient-prompt: Suffix Value Methods. + (line 32) +* transient-quit-all: Aborting and Resuming Transients. + (line 36) +* transient-quit-one: Aborting and Resuming Transients. + (line 27) +* transient-quit-seq: Aborting and Resuming Transients. + (line 27) +* transient-remove-suffix: Modifying Existing Transients. + (line 70) +* transient-replace-suffix: Modifying Existing Transients. + (line 66) +* transient-reset: Saving Values. (line 29) +* transient-resume: Aborting and Resuming Transients. + (line 53) +* transient-save: Saving Values. (line 25) +* transient-scroll-down: Other Commands. (line 17) +* transient-scroll-up: Other Commands. (line 12) +* transient-set: Saving Values. (line 21) +* transient-set-level: Enabling and Disabling Suffixes. + (line 43) +* transient-setup-children: Group Methods. (line 6) +* transient-show-help: Suffix Format Methods. + (line 26) +* transient-suffix-put: Modifying Existing Transients. + (line 77) +* transient-suffixes: Using Infix Arguments. + (line 38) +* transient-suspend: Aborting and Resuming Transients. + (line 41) +* transient-toggle-common: Common Suffix Commands. + (line 18) +* transient-toggle-level-limit: Enabling and Disabling Suffixes. + (line 68) +* transient-with-help-window: Suffix Format Methods. + (line 46) + + +File: transient.info, Node: Variable Index, Next: Concept Index, Prev: Command and Function Index, Up: Top + +Appendix D Variable Index +************************* + + +* Menu: + +* transient-align-variable-pitch: Configuration. (line 185) +* transient-current-command: Using Infix Arguments. + (line 52) +* transient-current-prefix: Using Infix Arguments. + (line 56) +* transient-current-suffixes: Using Infix Arguments. + (line 44) +* transient-default-level: Enabling and Disabling Suffixes. + (line 33) +* transient-detect-key-conflicts: Configuration. (line 210) +* transient-display-buffer-action: Configuration. (line 51) +* transient-enable-popup-navigation: Configuration. (line 36) +* transient-force-fixed-pitch: Configuration. (line 198) +* transient-force-single-column: Configuration. (line 93) +* transient-hide-during-minibuffer-read: Configuration. (line 181) +* transient-highlight-higher-levels: Configuration. (line 223) +* transient-highlight-mismatched-keys: Configuration. (line 135) +* transient-history-file: Using History. (line 33) +* transient-history-limit: Using History. (line 37) +* transient-levels-file: Enabling and Disabling Suffixes. + (line 38) +* transient-mode-line-format: Configuration. (line 102) +* transient-read-with-initial-input: Configuration. (line 174) +* transient-semantic-coloring: Configuration. (line 126) +* transient-show-common-commands: Common Suffix Commands. + (line 23) +* transient-show-popup: Configuration. (line 15) +* transient-substitute-key-function: Configuration. (line 153) +* transient-values-file: Saving Values. (line 31) + + +File: transient.info, Node: Concept Index, Next: GNU General Public License, Prev: Variable Index, Up: Top + +Appendix E Concept Index +************************ + + +* Menu: + +* aborting transients: Aborting and Resuming Transients. + (line 6) +* classes and methods: Classes and Methods. (line 6) +* command dispatchers: Technical Introduction. + (line 39) +* common suffix commands: Common Suffix Commands. + (line 6) +* defining infix commands: Defining Suffix and Infix Commands. + (line 6) +* defining suffix commands: Defining Suffix and Infix Commands. + (line 6) +* disabling suffixes: Enabling and Disabling Suffixes. + (line 6) +* enabling suffixes: Enabling and Disabling Suffixes. + (line 6) +* getting help: Getting Help for Suffix Commands. + (line 6) +* group specifications: Group Specifications. (line 6) +* invoking transients: Invoking Transients. (line 6) +* levels: Enabling and Disabling Suffixes. + (line 10) +* modifying existing transients: Modifying Existing Transients. + (line 6) +* quit transient: Aborting and Resuming Transients. + (line 6) +* resuming transients: Aborting and Resuming Transients. + (line 6) +* saving values of arguments: Saving Values. (line 6) +* scope of a transient: Defining Transients. (line 43) +* suffix specifications: Suffix Specifications. + (line 6) +* transient state: Transient State. (line 6) +* transient-level: Enabling and Disabling Suffixes. + (line 15) +* value history: Using History. (line 6) + + +File: transient.info, Node: GNU General Public License, Prev: Concept Index, Up: Top + +Appendix F GNU General Public License +************************************* + + Version 3, 29 June 2007 + + Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/> + + Everyone is permitted to copy and distribute verbatim copies of this + license document, but changing it is not allowed. + +Preamble +======== + +The GNU General Public License is a free, copyleft license for software +and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program—to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers’ and authors’ protection, the GPL clearly explains +that there is no warranty for this free software. For both users’ and +authors’ sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users’ freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + +TERMS AND CONDITIONS +==================== + + 0. Definitions. + + “This License” refers to version 3 of the GNU General Public + License. + + “Copyright” also means copyright-like laws that apply to other + kinds of works, such as semiconductor masks. + + “The Program” refers to any copyrightable work licensed under this + License. Each licensee is addressed as “you”. “Licensees” and + “recipients” may be individuals or organizations. + + To “modify” a work means to copy from or adapt all or part of the + work in a fashion requiring copyright permission, other than the + making of an exact copy. The resulting work is called a “modified + version” of the earlier work or a work “based on” the earlier work. + + A “covered work” means either the unmodified Program or a work + based on the Program. + + To “propagate” a work means to do anything with it that, without + permission, would make you directly or secondarily liable for + infringement under applicable copyright law, except executing it on + a computer or modifying a private copy. Propagation includes + copying, distribution (with or without modification), making + available to the public, and in some countries other activities as + well. + + To “convey” a work means any kind of propagation that enables other + parties to make or receive copies. Mere interaction with a user + through a computer network, with no transfer of a copy, is not + conveying. + + An interactive user interface displays “Appropriate Legal Notices” + to the extent that it includes a convenient and prominently visible + feature that (1) displays an appropriate copyright notice, and (2) + tells the user that there is no warranty for the work (except to + the extent that warranties are provided), that licensees may convey + the work under this License, and how to view a copy of this + License. If the interface presents a list of user commands or + options, such as a menu, a prominent item in the list meets this + criterion. + + 1. Source Code. + + The “source code” for a work means the preferred form of the work + for making modifications to it. “Object code” means any non-source + form of a work. + + A “Standard Interface” means an interface that either is an + official standard defined by a recognized standards body, or, in + the case of interfaces specified for a particular programming + language, one that is widely used among developers working in that + language. + + The “System Libraries” of an executable work include anything, + other than the work as a whole, that (a) is included in the normal + form of packaging a Major Component, but which is not part of that + Major Component, and (b) serves only to enable use of the work with + that Major Component, or to implement a Standard Interface for + which an implementation is available to the public in source code + form. A “Major Component”, in this context, means a major + essential component (kernel, window system, and so on) of the + specific operating system (if any) on which the executable work + runs, or a compiler used to produce the work, or an object code + interpreter used to run it. + + The “Corresponding Source” for a work in object code form means all + the source code needed to generate, install, and (for an executable + work) run the object code and to modify the work, including scripts + to control those activities. However, it does not include the + work’s System Libraries, or general-purpose tools or generally + available free programs which are used unmodified in performing + those activities but which are not part of the work. For example, + Corresponding Source includes interface definition files associated + with source files for the work, and the source code for shared + libraries and dynamically linked subprograms that the work is + specifically designed to require, such as by intimate data + communication or control flow between those subprograms and other + parts of the work. + + The Corresponding Source need not include anything that users can + regenerate automatically from other parts of the Corresponding + Source. + + The Corresponding Source for a work in source code form is that + same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of + copyright on the Program, and are irrevocable provided the stated + conditions are met. This License explicitly affirms your unlimited + permission to run the unmodified Program. The output from running + a covered work is covered by this License only if the output, given + its content, constitutes a covered work. This License acknowledges + your rights of fair use or other equivalent, as provided by + copyright law. + + You may make, run and propagate covered works that you do not + convey, without conditions so long as your license otherwise + remains in force. You may convey covered works to others for the + sole purpose of having them make modifications exclusively for you, + or provide you with facilities for running those works, provided + that you comply with the terms of this License in conveying all + material for which you do not control copyright. Those thus making + or running the covered works for you must do so exclusively on your + behalf, under your direction and control, on terms that prohibit + them from making any copies of your copyrighted material outside + their relationship with you. + + Conveying under any other circumstances is permitted solely under + the conditions stated below. Sublicensing is not allowed; section + 10 makes it unnecessary. + + 3. Protecting Users’ Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological + measure under any applicable law fulfilling obligations under + article 11 of the WIPO copyright treaty adopted on 20 December + 1996, or similar laws prohibiting or restricting circumvention of + such measures. + + When you convey a covered work, you waive any legal power to forbid + circumvention of technological measures to the extent such + circumvention is effected by exercising rights under this License + with respect to the covered work, and you disclaim any intention to + limit operation or modification of the work as a means of + enforcing, against the work’s users, your or third parties’ legal + rights to forbid circumvention of technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program’s source code as you + receive it, in any medium, provided that you conspicuously and + appropriately publish on each copy an appropriate copyright notice; + keep intact all notices stating that this License and any + non-permissive terms added in accord with section 7 apply to the + code; keep intact all notices of the absence of any warranty; and + give all recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, + and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to + produce it from the Program, in the form of source code under the + terms of section 4, provided that you also meet all of these + conditions: + + a. The work must carry prominent notices stating that you + modified it, and giving a relevant date. + + b. The work must carry prominent notices stating that it is + released under this License and any conditions added under + section 7. This requirement modifies the requirement in + section 4 to “keep intact all notices”. + + c. You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable + section 7 additional terms, to the whole of the work, and all + its parts, regardless of how they are packaged. This License + gives no permission to license the work in any other way, but + it does not invalidate such permission if you have separately + received it. + + d. If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has + interactive interfaces that do not display Appropriate Legal + Notices, your work need not make them do so. + + A compilation of a covered work with other separate and independent + works, which are not by their nature extensions of the covered + work, and which are not combined with it such as to form a larger + program, in or on a volume of a storage or distribution medium, is + called an “aggregate” if the compilation and its resulting + copyright are not used to limit the access or legal rights of the + compilation’s users beyond what the individual works permit. + Inclusion of a covered work in an aggregate does not cause this + License to apply to the other parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms + of sections 4 and 5, provided that you also convey the + machine-readable Corresponding Source under the terms of this + License, in one of these ways: + + a. Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b. Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that + product model, to give anyone who possesses the object code + either (1) a copy of the Corresponding Source for all the + software in the product that is covered by this License, on a + durable physical medium customarily used for software + interchange, for a price no more than your reasonable cost of + physically performing this conveying of source, or (2) access + to copy the Corresponding Source from a network server at no + charge. + + c. Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, + and only if you received the object code with such an offer, + in accord with subsection 6b. + + d. Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to + the Corresponding Source in the same way through the same + place at no further charge. You need not require recipients + to copy the Corresponding Source along with the object code. + If the place to copy the object code is a network server, the + Corresponding Source may be on a different server (operated by + you or a third party) that supports equivalent copying + facilities, provided you maintain clear directions next to the + object code saying where to find the Corresponding Source. + Regardless of what server hosts the Corresponding Source, you + remain obligated to ensure that it is available for as long as + needed to satisfy these requirements. + + e. Convey the object code using peer-to-peer transmission, + provided you inform other peers where the object code and + Corresponding Source of the work are being offered to the + general public at no charge under subsection 6d. + + A separable portion of the object code, whose source code is + excluded from the Corresponding Source as a System Library, need + not be included in conveying the object code work. + + A “User Product” is either (1) a “consumer product”, which means + any tangible personal property which is normally used for personal, + family, or household purposes, or (2) anything designed or sold for + incorporation into a dwelling. In determining whether a product is + a consumer product, doubtful cases shall be resolved in favor of + coverage. For a particular product received by a particular user, + “normally used” refers to a typical or common use of that class of + product, regardless of the status of the particular user or of the + way in which the particular user actually uses, or expects or is + expected to use, the product. A product is a consumer product + regardless of whether the product has substantial commercial, + industrial or non-consumer uses, unless such uses represent the + only significant mode of use of the product. + + “Installation Information” for a User Product means any methods, + procedures, authorization keys, or other information required to + install and execute modified versions of a covered work in that + User Product from a modified version of its Corresponding Source. + The information must suffice to ensure that the continued + functioning of the modified object code is in no case prevented or + interfered with solely because modification has been made. + + If you convey an object code work under this section in, or with, + or specifically for use in, a User Product, and the conveying + occurs as part of a transaction in which the right of possession + and use of the User Product is transferred to the recipient in + perpetuity or for a fixed term (regardless of how the transaction + is characterized), the Corresponding Source conveyed under this + section must be accompanied by the Installation Information. But + this requirement does not apply if neither you nor any third party + retains the ability to install modified object code on the User + Product (for example, the work has been installed in ROM). + + The requirement to provide Installation Information does not + include a requirement to continue to provide support service, + warranty, or updates for a work that has been modified or installed + by the recipient, or for the User Product in which it has been + modified or installed. Access to a network may be denied when the + modification itself materially and adversely affects the operation + of the network or violates the rules and protocols for + communication across the network. + + Corresponding Source conveyed, and Installation Information + provided, in accord with this section must be in a format that is + publicly documented (and with an implementation available to the + public in source code form), and must require no special password + or key for unpacking, reading or copying. + + 7. Additional Terms. + + “Additional permissions” are terms that supplement the terms of + this License by making exceptions from one or more of its + conditions. Additional permissions that are applicable to the + entire Program shall be treated as though they were included in + this License, to the extent that they are valid under applicable + law. If additional permissions apply only to part of the Program, + that part may be used separately under those permissions, but the + entire Program remains governed by this License without regard to + the additional permissions. + + When you convey a copy of a covered work, you may at your option + remove any additional permissions from that copy, or from any part + of it. (Additional permissions may be written to require their own + removal in certain cases when you modify the work.) You may place + additional permissions on material, added by you to a covered work, + for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material + you add to a covered work, you may (if authorized by the copyright + holders of that material) supplement the terms of this License with + terms: + + a. Disclaiming warranty or limiting liability differently from + the terms of sections 15 and 16 of this License; or + + b. Requiring preservation of specified reasonable legal notices + or author attributions in that material or in the Appropriate + Legal Notices displayed by works containing it; or + + c. Prohibiting misrepresentation of the origin of that material, + or requiring that modified versions of such material be marked + in reasonable ways as different from the original version; or + + d. Limiting the use for publicity purposes of names of licensors + or authors of the material; or + + e. Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f. Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified + versions of it) with contractual assumptions of liability to + the recipient, for any liability that these contractual + assumptions directly impose on those licensors and authors. + + All other non-permissive additional terms are considered “further + restrictions” within the meaning of section 10. If the Program as + you received it, or any part of it, contains a notice stating that + it is governed by this License along with a term that is a further + restriction, you may remove that term. If a license document + contains a further restriction but permits relicensing or conveying + under this License, you may add to a covered work material governed + by the terms of that license document, provided that the further + restriction does not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you + must place, in the relevant source files, a statement of the + additional terms that apply to those files, or a notice indicating + where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in + the form of a separately written license, or stated as exceptions; + the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly + provided under this License. Any attempt otherwise to propagate or + modify it is void, and will automatically terminate your rights + under this License (including any patent licenses granted under the + third paragraph of section 11). + + However, if you cease all violation of this License, then your + license from a particular copyright holder is reinstated (a) + provisionally, unless and until the copyright holder explicitly and + finally terminates your license, and (b) permanently, if the + copyright holder fails to notify you of the violation by some + reasonable means prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is + reinstated permanently if the copyright holder notifies you of the + violation by some reasonable means, this is the first time you have + received notice of violation of this License (for any work) from + that copyright holder, and you cure the violation prior to 30 days + after your receipt of the notice. + + Termination of your rights under this section does not terminate + the licenses of parties who have received copies or rights from you + under this License. If your rights have been terminated and not + permanently reinstated, you do not qualify to receive new licenses + for the same material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or + run a copy of the Program. Ancillary propagation of a covered work + occurring solely as a consequence of using peer-to-peer + transmission to receive a copy likewise does not require + acceptance. However, nothing other than this License grants you + permission to propagate or modify any covered work. These actions + infringe copyright if you do not accept this License. Therefore, + by modifying or propagating a covered work, you indicate your + acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically + receives a license from the original licensors, to run, modify and + propagate that work, subject to this License. You are not + responsible for enforcing compliance by third parties with this + License. + + An “entity transaction” is a transaction transferring control of an + organization, or substantially all assets of one, or subdividing an + organization, or merging organizations. If propagation of a + covered work results from an entity transaction, each party to that + transaction who receives a copy of the work also receives whatever + licenses to the work the party’s predecessor in interest had or + could give under the previous paragraph, plus a right to possession + of the Corresponding Source of the work from the predecessor in + interest, if the predecessor has it or can get it with reasonable + efforts. + + You may not impose any further restrictions on the exercise of the + rights granted or affirmed under this License. For example, you + may not impose a license fee, royalty, or other charge for exercise + of rights granted under this License, and you may not initiate + litigation (including a cross-claim or counterclaim in a lawsuit) + alleging that any patent claim is infringed by making, using, + selling, offering for sale, or importing the Program or any portion + of it. + + 11. Patents. + + A “contributor” is a copyright holder who authorizes use under this + License of the Program or a work on which the Program is based. + The work thus licensed is called the contributor’s “contributor + version”. + + A contributor’s “essential patent claims” are all patent claims + owned or controlled by the contributor, whether already acquired or + hereafter acquired, that would be infringed by some manner, + permitted by this License, of making, using, or selling its + contributor version, but do not include claims that would be + infringed only as a consequence of further modification of the + contributor version. For purposes of this definition, “control” + includes the right to grant patent sublicenses in a manner + consistent with the requirements of this License. + + Each contributor grants you a non-exclusive, worldwide, + royalty-free patent license under the contributor’s essential + patent claims, to make, use, sell, offer for sale, import and + otherwise run, modify and propagate the contents of its contributor + version. + + In the following three paragraphs, a “patent license” is any + express agreement or commitment, however denominated, not to + enforce a patent (such as an express permission to practice a + patent or covenant not to sue for patent infringement). To “grant” + such a patent license to a party means to make such an agreement or + commitment not to enforce a patent against the party. + + If you convey a covered work, knowingly relying on a patent + license, and the Corresponding Source of the work is not available + for anyone to copy, free of charge and under the terms of this + License, through a publicly available network server or other + readily accessible means, then you must either (1) cause the + Corresponding Source to be so available, or (2) arrange to deprive + yourself of the benefit of the patent license for this particular + work, or (3) arrange, in a manner consistent with the requirements + of this License, to extend the patent license to downstream + recipients. “Knowingly relying” means you have actual knowledge + that, but for the patent license, your conveying the covered work + in a country, or your recipient’s use of the covered work in a + country, would infringe one or more identifiable patents in that + country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or + arrangement, you convey, or propagate by procuring conveyance of, a + covered work, and grant a patent license to some of the parties + receiving the covered work authorizing them to use, propagate, + modify or convey a specific copy of the covered work, then the + patent license you grant is automatically extended to all + recipients of the covered work and works based on it. + + A patent license is “discriminatory” if it does not include within + the scope of its coverage, prohibits the exercise of, or is + conditioned on the non-exercise of one or more of the rights that + are specifically granted under this License. You may not convey a + covered work if you are a party to an arrangement with a third + party that is in the business of distributing software, under which + you make payment to the third party based on the extent of your + activity of conveying the work, and under which the third party + grants, to any of the parties who would receive the covered work + from you, a discriminatory patent license (a) in connection with + copies of the covered work conveyed by you (or copies made from + those copies), or (b) primarily for and in connection with specific + products or compilations that contain the covered work, unless you + entered into that arrangement, or that patent license was granted, + prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting + any implied license or other defenses to infringement that may + otherwise be available to you under applicable patent law. + + 12. No Surrender of Others’ Freedom. + + If conditions are imposed on you (whether by court order, agreement + or otherwise) that contradict the conditions of this License, they + do not excuse you from the conditions of this License. If you + cannot convey a covered work so as to satisfy simultaneously your + obligations under this License and any other pertinent obligations, + then as a consequence you may not convey it at all. For example, + if you agree to terms that obligate you to collect a royalty for + further conveying from those to whom you convey the Program, the + only way you could satisfy both those terms and this License would + be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have + permission to link or combine any covered work with a work licensed + under version 3 of the GNU Affero General Public License into a + single combined work, and to convey the resulting work. The terms + of this License will continue to apply to the part which is the + covered work, but the special requirements of the GNU Affero + General Public License, section 13, concerning interaction through + a network will apply to the combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new + versions of the GNU General Public License from time to time. Such + new versions will be similar in spirit to the present version, but + may differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the + Program specifies that a certain numbered version of the GNU + General Public License “or any later version” applies to it, you + have the option of following the terms and conditions either of + that numbered version or of any later version published by the Free + Software Foundation. If the Program does not specify a version + number of the GNU General Public License, you may choose any + version ever published by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future + versions of the GNU General Public License can be used, that + proxy’s public statement of acceptance of a version permanently + authorizes you to choose that version for the Program. + + Later license versions may give you additional or different + permissions. However, no additional obligations are imposed on any + author or copyright holder as a result of your choosing to follow a + later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY + APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE + COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” + WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, + INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE + RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. + SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL + NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN + WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES + AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR + DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR + CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE + THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA + BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD + PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER + PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF + THE POSSIBILITY OF SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided + above cannot be given local legal effect according to their terms, + reviewing courts shall apply local law that most closely + approximates an absolute waiver of all civil liability in + connection with the Program, unless a warranty or assumption of + liability accompanies a copy of the Program in return for a fee. + +END OF TERMS AND CONDITIONS +=========================== + +How to Apply These Terms to Your New Programs +============================================= + +If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these +terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least the +“copyright” line and a pointer to where the full notice is found. + + ONE LINE TO GIVE THE PROGRAM'S NAME AND A BRIEF IDEA OF WHAT IT DOES. + Copyright (C) YEAR NAME OF AUTHOR + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or (at + your option) any later version. + + This program is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. + + Also add information on how to contact you by electronic and paper +mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + PROGRAM Copyright (C) YEAR NAME OF AUTHOR + This program comes with ABSOLUTELY NO WARRANTY; for details type ‘show w’. + This is free software, and you are welcome to redistribute it + under certain conditions; type ‘show c’ for details. + + The hypothetical commands ‘show w’ and ‘show c’ should show the +appropriate parts of the General Public License. Of course, your +program’s commands might be different; for a GUI interface, you would +use an “about box”. + + You should also get your employer (if you work as a programmer) or +school, if any, to sign a “copyright disclaimer” for the program, if +necessary. For more information on this, and how to apply and follow +the GNU GPL, see <https://www.gnu.org/licenses/>. + + The GNU General Public License does not permit incorporating your +program into proprietary programs. If your program is a subroutine +library, you may consider it more useful to permit linking proprietary +applications with the library. If this is what you want to do, use the +GNU Lesser General Public License instead of this License. But first, +please read <https://www.gnu.org/licenses/why-not-lgpl.html>. + + + +Tag Table: +Node: Top763 +Node: Introduction2976 +Ref: Some things that Transient can do3504 +Ref: Complexity in CLI programs3857 +Ref: Using Transient for composing interactive commands4458 +Node: Usage6700 +Node: Invoking Transients7068 +Node: Aborting and Resuming Transients8147 +Node: Common Suffix Commands10768 +Node: Saving Values12604 +Ref: Saving Values-Footnote-113975 +Node: Using History14168 +Node: Getting Help for Suffix Commands15742 +Node: Enabling and Disabling Suffixes17120 +Node: Other Commands20408 +Node: Configuration21384 +Ref: Essential Options21664 +Ref: Accessibility Options25325 +Ref: Auxiliary Options25648 +Ref: Developer Options30611 +Node: Modifying Existing Transients31859 +Node: Defining New Commands36051 +Node: Technical Introduction36414 +Node: Defining Transients42115 +Node: Binding Suffix and Infix Commands44582 +Node: Group Specifications45440 +Node: Suffix Specifications51968 +Node: Defining Suffix and Infix Commands56181 +Node: Using Infix Arguments59229 +Node: Transient State62866 +Ref: Pre-commands for Infixes67681 +Ref: Pre-commands for Suffixes68201 +Ref: Pre-commands for Non-Suffixes70655 +Ref: Special Pre-Commands71791 +Node: Classes and Methods72299 +Node: Group Classes74483 +Node: Group Methods76410 +Node: Prefix Classes77663 +Node: Suffix Classes78754 +Node: Suffix Methods81841 +Node: Suffix Value Methods82162 +Node: Suffix Format Methods84920 +Node: Prefix Slots86945 +Ref: Internal Prefix Slots89082 +Node: Suffix Slots90339 +Ref: Slots of transient-suffix90707 +Ref: Slots of transient-infix91890 +Ref: Slots of transient-variable95186 +Ref: Slots of transient-switches95288 +Node: Predicate Slots95651 +Node: FAQ97086 +Ref: Can I control how the popup buffer is displayed?97215 +Ref: How can I copy text from the popup buffer?97396 +Ref: How can I autoload prefix and suffix commands?97890 +Ref: How does Transient compare to prefix keys and universal arguments?98364 +Ref: How does Transient compare to Magit-Popup and Hydra?98607 +Ref: Why did some of the key bindings change?98801 +Ref: Why does q not quit popups anymore?101154 +Node: Keystroke Index102257 +Node: Command and Function Index104122 +Node: Variable Index110988 +Node: Concept Index113261 +Node: GNU General Public License115997 + +End Tag Table + + +Local Variables: +coding: utf-8 +End: diff --git a/emacs/elpa/vertico-20241004.1350/vertico-autoloads.el b/emacs/elpa/vertico-20241004.1350/vertico-autoloads.el @@ -0,0 +1,372 @@ +;;; vertico-autoloads.el --- automatically extracted autoloads (do not edit) -*- lexical-binding: t -*- +;; Generated by the `loaddefs-generate' function. + +;; This file is part of GNU Emacs. + +;;; Code: + +(add-to-list 'load-path (or (and load-file-name (directory-file-name (file-name-directory load-file-name))) (car load-path))) + + + +;;; Generated autoloads from vertico.el + +(defvar vertico-mode nil "\ +Non-nil if Vertico mode is enabled. +See the `vertico-mode' command +for a description of this minor mode. +Setting this variable directly does not take effect; +either customize it (see the info node `Easy Customization') +or call the function `vertico-mode'.") +(custom-autoload 'vertico-mode "vertico" nil) +(autoload 'vertico-mode "vertico" "\ +VERTical Interactive COmpletion. + +This is a global minor mode. If called interactively, toggle the +`Vertico mode' mode. If the prefix argument is positive, enable +the mode, and if it is zero or negative, disable the mode. + +If called from Lisp, toggle the mode if ARG is `toggle'. Enable +the mode if ARG is nil, omitted, or is a positive number. +Disable the mode if ARG is a negative number. + +To check whether the minor mode is enabled in the current buffer, +evaluate `(default-value \\='vertico-mode)'. + +The mode's hook is called both when the mode is enabled and when +it is disabled. + +(fn &optional ARG)" t) +(register-definition-prefixes "vertico" '("vertico-")) + + +;;; Generated autoloads from vertico-buffer.el + +(defvar vertico-buffer-mode nil "\ +Non-nil if Vertico-Buffer mode is enabled. +See the `vertico-buffer-mode' command +for a description of this minor mode. +Setting this variable directly does not take effect; +either customize it (see the info node `Easy Customization') +or call the function `vertico-buffer-mode'.") +(custom-autoload 'vertico-buffer-mode "vertico-buffer" nil) +(autoload 'vertico-buffer-mode "vertico-buffer" "\ +Display Vertico like a regular buffer in a large window. + +This is a global minor mode. If called interactively, toggle the +`Vertico-Buffer mode' mode. If the prefix argument is positive, +enable the mode, and if it is zero or negative, disable the mode. + +If called from Lisp, toggle the mode if ARG is `toggle'. Enable +the mode if ARG is nil, omitted, or is a positive number. +Disable the mode if ARG is a negative number. + +To check whether the minor mode is enabled in the current buffer, +evaluate `(default-value \\='vertico-buffer-mode)'. + +The mode's hook is called both when the mode is enabled and when +it is disabled. + +(fn &optional ARG)" t) +(register-definition-prefixes "vertico-buffer" '("vertico-buffer-")) + + +;;; Generated autoloads from vertico-directory.el + +(autoload 'vertico-directory-enter "vertico-directory" "\ +Enter directory or exit completion with current candidate. +Exit with current input if prefix ARG is given. + +(fn &optional ARG)" t) +(autoload 'vertico-directory-up "vertico-directory" "\ +Delete N names before point. + +(fn &optional N)" t) +(autoload 'vertico-directory-delete-char "vertico-directory" "\ +Delete N directories or chars before point. + +(fn &optional N)" t) +(autoload 'vertico-directory-delete-word "vertico-directory" "\ +Delete N directories or words before point. + +(fn &optional N)" t) +(autoload 'vertico-directory-tidy "vertico-directory" "\ +Tidy shadowed file name, see `rfn-eshadow-overlay'.") + + +;;; Generated autoloads from vertico-flat.el + +(defvar vertico-flat-mode nil "\ +Non-nil if Vertico-Flat mode is enabled. +See the `vertico-flat-mode' command +for a description of this minor mode. +Setting this variable directly does not take effect; +either customize it (see the info node `Easy Customization') +or call the function `vertico-flat-mode'.") +(custom-autoload 'vertico-flat-mode "vertico-flat" nil) +(autoload 'vertico-flat-mode "vertico-flat" "\ +Flat, horizontal display for Vertico. + +This is a global minor mode. If called interactively, toggle the +`Vertico-Flat mode' mode. If the prefix argument is positive, +enable the mode, and if it is zero or negative, disable the mode. + +If called from Lisp, toggle the mode if ARG is `toggle'. Enable +the mode if ARG is nil, omitted, or is a positive number. +Disable the mode if ARG is a negative number. + +To check whether the minor mode is enabled in the current buffer, +evaluate `(default-value \\='vertico-flat-mode)'. + +The mode's hook is called both when the mode is enabled and when +it is disabled. + +(fn &optional ARG)" t) +(register-definition-prefixes "vertico-flat" '("vertico-flat-")) + + +;;; Generated autoloads from vertico-grid.el + +(defvar vertico-grid-mode nil "\ +Non-nil if Vertico-Grid mode is enabled. +See the `vertico-grid-mode' command +for a description of this minor mode. +Setting this variable directly does not take effect; +either customize it (see the info node `Easy Customization') +or call the function `vertico-grid-mode'.") +(custom-autoload 'vertico-grid-mode "vertico-grid" nil) +(autoload 'vertico-grid-mode "vertico-grid" "\ +Grid display for Vertico. + +This is a global minor mode. If called interactively, toggle the +`Vertico-Grid mode' mode. If the prefix argument is positive, +enable the mode, and if it is zero or negative, disable the mode. + +If called from Lisp, toggle the mode if ARG is `toggle'. Enable +the mode if ARG is nil, omitted, or is a positive number. +Disable the mode if ARG is a negative number. + +To check whether the minor mode is enabled in the current buffer, +evaluate `(default-value \\='vertico-grid-mode)'. + +The mode's hook is called both when the mode is enabled and when +it is disabled. + +(fn &optional ARG)" t) +(register-definition-prefixes "vertico-grid" '("vertico-grid-")) + + +;;; Generated autoloads from vertico-indexed.el + +(defvar vertico-indexed-mode nil "\ +Non-nil if Vertico-Indexed mode is enabled. +See the `vertico-indexed-mode' command +for a description of this minor mode.") +(custom-autoload 'vertico-indexed-mode "vertico-indexed" nil) +(autoload 'vertico-indexed-mode "vertico-indexed" "\ +Prefix candidates with indices. + +This is a global minor mode. If called interactively, toggle the +`Vertico-Indexed mode' mode. If the prefix argument is positive, +enable the mode, and if it is zero or negative, disable the mode. + +If called from Lisp, toggle the mode if ARG is `toggle'. Enable +the mode if ARG is nil, omitted, or is a positive number. +Disable the mode if ARG is a negative number. + +To check whether the minor mode is enabled in the current buffer, +evaluate `(default-value \\='vertico-indexed-mode)'. + +The mode's hook is called both when the mode is enabled and when +it is disabled. + +(fn &optional ARG)" t) +(register-definition-prefixes "vertico-indexed" '("vertico-indexed-")) + + +;;; Generated autoloads from vertico-mouse.el + +(defvar vertico-mouse-mode nil "\ +Non-nil if Vertico-Mouse mode is enabled. +See the `vertico-mouse-mode' command +for a description of this minor mode.") +(custom-autoload 'vertico-mouse-mode "vertico-mouse" nil) +(autoload 'vertico-mouse-mode "vertico-mouse" "\ +Mouse support for Vertico. + +This is a global minor mode. If called interactively, toggle the +`Vertico-Mouse mode' mode. If the prefix argument is positive, +enable the mode, and if it is zero or negative, disable the mode. + +If called from Lisp, toggle the mode if ARG is `toggle'. Enable +the mode if ARG is nil, omitted, or is a positive number. +Disable the mode if ARG is a negative number. + +To check whether the minor mode is enabled in the current buffer, +evaluate `(default-value \\='vertico-mouse-mode)'. + +The mode's hook is called both when the mode is enabled and when +it is disabled. + +(fn &optional ARG)" t) +(register-definition-prefixes "vertico-mouse" '("vertico-mouse-")) + + +;;; Generated autoloads from vertico-multiform.el + +(defvar vertico-multiform-mode nil "\ +Non-nil if Vertico-Multiform mode is enabled. +See the `vertico-multiform-mode' command +for a description of this minor mode. +Setting this variable directly does not take effect; +either customize it (see the info node `Easy Customization') +or call the function `vertico-multiform-mode'.") +(custom-autoload 'vertico-multiform-mode "vertico-multiform" nil) +(autoload 'vertico-multiform-mode "vertico-multiform" "\ +Configure Vertico in various forms per command. + +This is a global minor mode. If called interactively, toggle the +`Vertico-Multiform mode' mode. If the prefix argument is +positive, enable the mode, and if it is zero or negative, disable +the mode. + +If called from Lisp, toggle the mode if ARG is `toggle'. Enable +the mode if ARG is nil, omitted, or is a positive number. +Disable the mode if ARG is a negative number. + +To check whether the minor mode is enabled in the current buffer, +evaluate `(default-value \\='vertico-multiform-mode)'. + +The mode's hook is called both when the mode is enabled and when +it is disabled. + +(fn &optional ARG)" t) +(register-definition-prefixes "vertico-multiform" '("vertico-multiform-")) + + +;;; Generated autoloads from vertico-quick.el + +(autoload 'vertico-quick-jump "vertico-quick" "\ +Jump to candidate using quick keys." t) +(autoload 'vertico-quick-exit "vertico-quick" "\ +Exit with candidate using quick keys." t) +(autoload 'vertico-quick-insert "vertico-quick" "\ +Insert candidate using quick keys." t) +(register-definition-prefixes "vertico-quick" '("vertico-quick")) + + +;;; Generated autoloads from vertico-repeat.el + +(autoload 'vertico-repeat-save "vertico-repeat" "\ +Save Vertico session for `vertico-repeat'. +This function must be registered as `minibuffer-setup-hook'.") +(autoload 'vertico-repeat-next "vertico-repeat" "\ +Repeat Nth next Vertico completion session. +This command must be called from an existing Vertico session +after `vertico-repeat-previous'. + +(fn N)" t) +(autoload 'vertico-repeat-previous "vertico-repeat" "\ +Repeat Nth previous Vertico completion session. +If called from an existing Vertico session, restore the input and +selected candidate for the current command. + +(fn N)" t) +(autoload 'vertico-repeat-select "vertico-repeat" "\ +Select a Vertico session from the session history and repeat it. +If called from an existing Vertico session, you can select among +previous sessions for the current command." t) +(autoload 'vertico-repeat "vertico-repeat" "\ +Repeat last Vertico session. +If prefix ARG is non-nil, offer completion menu to select from session history. + +(fn &optional ARG)" t) +(register-definition-prefixes "vertico-repeat" '("vertico-repeat-")) + + +;;; Generated autoloads from vertico-reverse.el + +(defvar vertico-reverse-mode nil "\ +Non-nil if Vertico-Reverse mode is enabled. +See the `vertico-reverse-mode' command +for a description of this minor mode. +Setting this variable directly does not take effect; +either customize it (see the info node `Easy Customization') +or call the function `vertico-reverse-mode'.") +(custom-autoload 'vertico-reverse-mode "vertico-reverse" nil) +(autoload 'vertico-reverse-mode "vertico-reverse" "\ +Reverse the Vertico display. + +This is a global minor mode. If called interactively, toggle the +`Vertico-Reverse mode' mode. If the prefix argument is positive, +enable the mode, and if it is zero or negative, disable the mode. + +If called from Lisp, toggle the mode if ARG is `toggle'. Enable +the mode if ARG is nil, omitted, or is a positive number. +Disable the mode if ARG is a negative number. + +To check whether the minor mode is enabled in the current buffer, +evaluate `(default-value \\='vertico-reverse-mode)'. + +The mode's hook is called both when the mode is enabled and when +it is disabled. + +(fn &optional ARG)" t) +(register-definition-prefixes "vertico-reverse" '("vertico-reverse-map")) + + +;;; Generated autoloads from vertico-suspend.el + +(autoload 'vertico-suspend "vertico-suspend" "\ +Suspend the current completion session. +If the command is invoked from within the Vertico minibuffer, the +current session is suspended. If the command is invoked from +outside the minibuffer, the active minibuffer is either selected +or the latest completion session is restored." t) +(register-definition-prefixes "vertico-suspend" '("vertico-suspend--")) + + +;;; Generated autoloads from vertico-unobtrusive.el + +(defvar vertico-unobtrusive-mode nil "\ +Non-nil if Vertico-Unobtrusive mode is enabled. +See the `vertico-unobtrusive-mode' command +for a description of this minor mode. +Setting this variable directly does not take effect; +either customize it (see the info node `Easy Customization') +or call the function `vertico-unobtrusive-mode'.") +(custom-autoload 'vertico-unobtrusive-mode "vertico-unobtrusive" nil) +(autoload 'vertico-unobtrusive-mode "vertico-unobtrusive" "\ +Unobtrusive display for Vertico. + +This is a global minor mode. If called interactively, toggle the +`Vertico-Unobtrusive mode' mode. If the prefix argument is +positive, enable the mode, and if it is zero or negative, disable +the mode. + +If called from Lisp, toggle the mode if ARG is `toggle'. Enable +the mode if ARG is nil, omitted, or is a positive number. +Disable the mode if ARG is a negative number. + +To check whether the minor mode is enabled in the current buffer, +evaluate `(default-value \\='vertico-unobtrusive-mode)'. + +The mode's hook is called both when the mode is enabled and when +it is disabled. + +(fn &optional ARG)" t) +(register-definition-prefixes "vertico-unobtrusive" '("vertico-unobtrusive--restore")) + +;;; End of scraped data + +(provide 'vertico-autoloads) + +;; Local Variables: +;; version-control: never +;; no-byte-compile: t +;; no-update-autoloads: t +;; no-native-compile: t +;; coding: utf-8-emacs-unix +;; End: + +;;; vertico-autoloads.el ends here diff --git a/emacs/elpa/vertico-20241004.1350/vertico-buffer.el b/emacs/elpa/vertico-20241004.1350/vertico-buffer.el @@ -0,0 +1,216 @@ +;;; vertico-buffer.el --- Display Vertico like a regular buffer -*- lexical-binding: t -*- + +;; Copyright (C) 2021-2024 Free Software Foundation, Inc. + +;; Author: Daniel Mendler <mail@daniel-mendler.de> +;; Maintainer: Daniel Mendler <mail@daniel-mendler.de> +;; Created: 2021 +;; Package-Requires: ((emacs "28.1") (compat "30") (vertico "1.9")) +;; URL: https://github.com/minad/vertico + +;; This file is part of GNU Emacs. + +;; This program is free software: you can redistribute it and/or modify +;; it under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. + +;; This program is distributed in the hope that it will be useful, +;; but WITHOUT ANY WARRANTY; without even the implied warranty of +;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +;; GNU General Public License for more details. + +;; You should have received a copy of the GNU General Public License +;; along with this program. If not, see <https://www.gnu.org/licenses/>. + +;;; Commentary: + +;; This package is a Vertico extension, which displays Vertico like a +;; regular buffer in a large window instead of the miniwindow. The +;; buffer display can be enabled by the `vertico-buffer-mode'. + +;; The mode can be enabled globally or via `vertico-multiform-mode' +;; per command or completion category. Alternatively the buffer +;; display can be toggled temporarily with M-B if +;; `vertico-multiform-mode' is enabled. + +;;; Code: + +(require 'vertico) + +(defcustom vertico-buffer-hide-prompt t + "Hide prompt in the minibuffer." + :group 'vertico + :type 'boolean) + +(defcustom vertico-buffer-display-action + '(display-buffer-use-least-recent-window) + "Display action for the Vertico buffer." + :group 'vertico + :type `(choice + (const :tag "Least recently used window" + (display-buffer-use-least-recent-window)) + (const :tag "Reuse some window" + (display-buffer-reuse-window)) + (const :tag "Left of current window" + (display-buffer-in-direction + (direction . left) + (window-width . 0.3))) + (const :tag "Right of current window" + (display-buffer-in-direction + (direction . right) + (window-height . 0.3))) + (const :tag "Above current window" + (display-buffer-in-direction + (direction . above) + (window-height . ,(+ 3 vertico-count)))) + (const :tag "Below current window" + (display-buffer-in-direction + (direction . below) + (window-height . ,(+ 3 vertico-count)))) + (const :tag "Bottom of frame" + (display-buffer-at-bottom + (window-height . ,(+ 3 vertico-count)))) + (const :tag "Side window on the right" + (display-buffer-in-side-window + (side . right) + (window-width . 0.3))) + (const :tag "Side window on the left" + (display-buffer-in-side-window + (side . left) + (window-width . 0.3))) + (const :tag "Side window at the top" + (display-buffer-in-side-window + (window-height . ,(+ 3 vertico-count)) + (side . top))) + (const :tag "Side window at the bottom" + (display-buffer-in-side-window + (window-height . ,(+ 3 vertico-count)) + (side . bottom))) + (sexp :tag "Other"))) + +(defvar-local vertico-buffer--restore nil) + +(defun vertico-buffer--redisplay (win) + "Redisplay window WIN." + (when-let ((mbwin (active-minibuffer-window)) + ((eq (window-buffer mbwin) (current-buffer)))) + (unless (eq win mbwin) + (setq-local truncate-lines (< (window-point win) + (* 0.8 (window-width win)))) + (set-window-point win (point)) + (set-window-hscroll win 0)) + (when vertico-buffer-hide-prompt + (window-resize mbwin (- (window-pixel-height mbwin)) nil nil 'pixelwise) + (set-window-vscroll mbwin 3)) + (when transient-mark-mode + (with-silent-modifications + (vertico--remove-face (point-min) (point-max) 'region) + (when (use-region-p) + (add-face-text-property + (max (minibuffer-prompt-end) (region-beginning)) + (region-end) 'region)))) + (let ((old cursor-in-non-selected-windows) + (new (and (eq (selected-window) mbwin) + (if (memq cursor-type '(nil t)) 'box cursor-type)))) + (unless (eq new old) + (setq-local cursor-in-non-selected-windows new) + (force-mode-line-update t))))) + +(defun vertico-buffer--setup () + "Setup buffer display." + (let* ((action vertico-buffer-display-action) + (old-wins (mapcar (lambda (w) (cons w (window-buffer w))) (window-list))) + win old-buf tmp-buf + (_ (unwind-protect + (progn + (with-current-buffer + (setq tmp-buf (generate-new-buffer "*vertico-buffer*")) + ;; Set a fake major mode such that + ;; `display-buffer-reuse-mode-window' does not take over! + (setq major-mode 'vertico-buffer-mode)) + ;; Temporarily select the original window such that + ;; `display-buffer-same-window' works. + (setq win (with-minibuffer-selected-window + (display-buffer tmp-buf action)) + old-buf (alist-get win old-wins)) + (set-window-buffer win (current-buffer))) + (kill-buffer tmp-buf))) + (old-no-other (window-parameter win 'no-other-window)) + (old-no-delete (window-parameter win 'no-delete-other-windows)) + (old-state (buffer-local-set-state + cursor-in-non-selected-windows cursor-in-non-selected-windows + show-trailing-whitespace nil + truncate-lines t + face-remapping-alist (copy-tree `((mode-line-inactive mode-line) + ,@face-remapping-alist)) + mode-line-format + (when mode-line-format ;; Do not override if nil + (list (format #(" %s%s " 1 3 (face mode-line-buffer-id)) + (replace-regexp-in-string ":? *\\'" "" + (minibuffer-prompt)) + (let ((depth (recursion-depth))) + (if (< depth 2) "" (format " [%s]" depth)))))) + vertico-count (- (/ (window-pixel-height win) + (default-line-height)) 2)))) + (set-window-parameter win 'no-other-window t) + (set-window-parameter win 'no-delete-other-windows t) + (set-window-dedicated-p win t) + (overlay-put vertico--candidates-ov 'window win) + (when (and vertico-buffer-hide-prompt vertico--count-ov) + (overlay-put vertico--count-ov 'window win)) + (setq-local vertico-buffer--restore (make-symbol "vertico-buffer--restore")) + (fset vertico-buffer--restore + (lambda () + (with-selected-window (active-minibuffer-window) + (when vertico-buffer--restore + (when transient-mark-mode + (with-silent-modifications + (vertico--remove-face (point-min) (point-max) 'region))) + (remove-hook 'pre-redisplay-functions #'vertico-buffer--redisplay 'local) + (remove-hook 'minibuffer-exit-hook vertico-buffer--restore) + (fset vertico-buffer--restore nil) + (kill-local-variable 'vertico-buffer--restore) + (buffer-local-restore-state old-state) + (overlay-put vertico--candidates-ov 'window nil) + (when vertico--count-ov (overlay-put vertico--count-ov 'window nil)) + (cond + ((and (window-live-p win) (buffer-live-p old-buf)) + (set-window-parameter win 'no-other-window old-no-other) + (set-window-parameter win 'no-delete-other-windows old-no-delete) + (set-window-dedicated-p win nil) + (set-window-buffer win old-buf)) + ;; Check `window-parent' since the window may be a sole window + ;; (gh:minad/vertico#496). + ((and (window-live-p win) (window-parent win)) + (delete-window win))) + (when vertico-buffer-hide-prompt + (set-window-vscroll nil 0)))))) + ;; We cannot use a buffer-local minibuffer-exit-hook here. The hook will + ;; not be called when abnormally exiting the minibuffer from another buffer + ;; via `keyboard-escape-quit'. + (add-hook 'minibuffer-exit-hook vertico-buffer--restore) + (add-hook 'pre-redisplay-functions #'vertico-buffer--redisplay nil 'local))) + +;;;###autoload +(define-minor-mode vertico-buffer-mode + "Display Vertico like a regular buffer in a large window." + :global t :group 'vertico + ;; Shrink current minibuffer window + (when-let ((win (active-minibuffer-window))) + (unless (frame-root-window-p win) + (window-resize win (- (window-pixel-height win)) nil nil 'pixelwise)) + (with-selected-window win + (cond + ((and vertico-buffer-mode vertico--input (not vertico-buffer--restore)) + (vertico-buffer--setup)) + ((and (not vertico-buffer-mode) vertico-buffer--restore) + (funcall vertico-buffer--restore)))))) + +(cl-defmethod vertico--resize-window (_height &context (vertico-buffer-mode (eql t)))) + +(cl-defmethod vertico--setup :after (&context (vertico-buffer-mode (eql t))) + (vertico-buffer--setup)) + +(provide 'vertico-buffer) +;;; vertico-buffer.el ends here diff --git a/emacs/elpa/vertico-20241004.1350/vertico-directory.el b/emacs/elpa/vertico-20241004.1350/vertico-directory.el @@ -0,0 +1,119 @@ +;;; vertico-directory.el --- Ido-like directory navigation for Vertico -*- lexical-binding: t -*- + +;; Copyright (C) 2021-2024 Free Software Foundation, Inc. + +;; Author: Daniel Mendler <mail@daniel-mendler.de> +;; Maintainer: Daniel Mendler <mail@daniel-mendler.de> +;; Created: 2021 +;; Package-Requires: ((emacs "28.1") (compat "30") (vertico "1.9")) +;; URL: https://github.com/minad/vertico + +;; This file is part of GNU Emacs. + +;; This program is free software: you can redistribute it and/or modify +;; it under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. + +;; This program is distributed in the hope that it will be useful, +;; but WITHOUT ANY WARRANTY; without even the implied warranty of +;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +;; GNU General Public License for more details. + +;; You should have received a copy of the GNU General Public License +;; along with this program. If not, see <https://www.gnu.org/licenses/>. + +;;; Commentary: + +;; This package is a Vertico extension, which provides Ido-like +;; directory navigation commands. The commands can be bound in the +;; `vertico-map'. Furthermore a cleanup function for shadowed file +;; paths is provided. +;; +;; (keymap-set vertico-map "RET" #'vertico-directory-enter) +;; (keymap-set vertico-map "DEL" #'vertico-directory-delete-char) +;; (keymap-set vertico-map "M-DEL" #'vertico-directory-delete-word) +;; (add-hook 'rfn-eshadow-update-overlay-hook #'vertico-directory-tidy) + +;;; Code: + +(require 'vertico) +(eval-when-compile (require 'subr-x)) + +;;;###autoload +(defun vertico-directory-enter (&optional arg) + "Enter directory or exit completion with current candidate. +Exit with current input if prefix ARG is given." + (interactive "P") + (if-let (((not arg)) + ((>= vertico--index 0)) + ((eq 'file (vertico--metadata-get 'category))) + ;; Check vertico--base for stepwise file path completion + ((not (equal vertico--base ""))) + (cand (vertico--candidate)) + ((or (string-suffix-p "/" cand) + (and (vertico--remote-p cand) + (string-suffix-p ":" cand)))) + ;; Handle /./ and /../ manually instead of via `expand-file-name' + ;; and `abbreviate-file-name', such that we don't accidentally + ;; perform unwanted substitutions in the existing completion. + ((progn + (setq cand (string-replace "/./" "/" cand)) + (unless (string-suffix-p "/../../" cand) + (setq cand (replace-regexp-in-string "/[^/|:]+/\\.\\./\\'" "/" cand))) + (not (equal (minibuffer-contents-no-properties) cand))))) + (progn + (delete-minibuffer-contents) + (insert cand)) + (vertico-exit arg))) + +;;;###autoload +(defun vertico-directory-up (&optional n) + "Delete N names before point." + (interactive "p") + (when (and (> (point) (minibuffer-prompt-end)) + (eq 'file (vertico--metadata-get 'category))) + (let ((path (buffer-substring-no-properties (minibuffer-prompt-end) (point))) + found) + (when (string-match-p "\\`~[^/]*/\\'" path) + (delete-minibuffer-contents) + (insert (expand-file-name path))) + (dotimes (_ (or n 1) found) + (save-excursion + (let ((end (point))) + (goto-char (1- end)) + (when (search-backward "/" (minibuffer-prompt-end) t) + (delete-region (1+ (point)) end) + (setq found t)))))))) + +;;;###autoload +(defun vertico-directory-delete-char (&optional n) + "Delete N directories or chars before point." + (interactive "p") + (unless (and (eq (char-before) ?/) (vertico-directory-up n)) + (delete-char (- n)))) + +;;;###autoload +(defun vertico-directory-delete-word (&optional n) + "Delete N directories or words before point." + (interactive "p") + (unless (and (eq (char-before) ?/) (vertico-directory-up n)) + (let ((pt (point))) + (backward-word n) + (delete-region pt (point))))) + +;;;###autoload +(defun vertico-directory-tidy () + "Tidy shadowed file name, see `rfn-eshadow-overlay'." + (when (eq this-command #'self-insert-command) + (dolist (ov '(tramp-rfn-eshadow-overlay rfn-eshadow-overlay)) + (when (and (boundp ov) + (setq ov (symbol-value ov)) + (overlay-buffer ov) + (= (point) (point-max)) + (or (>= (- (point) (overlay-end ov)) 2) + (eq ?/ (char-before (- (point) 2))))) + (delete-region (overlay-start ov) (overlay-end ov)))))) + +(provide 'vertico-directory) +;;; vertico-directory.el ends here diff --git a/emacs/elpa/vertico-20241004.1350/vertico-flat.el b/emacs/elpa/vertico-20241004.1350/vertico-flat.el @@ -0,0 +1,138 @@ +;;; vertico-flat.el --- Flat, horizontal display for Vertico -*- lexical-binding: t -*- + +;; Copyright (C) 2021-2024 Free Software Foundation, Inc. + +;; Author: Daniel Mendler <mail@daniel-mendler.de> +;; Maintainer: Daniel Mendler <mail@daniel-mendler.de> +;; Created: 2021 +;; Package-Requires: ((emacs "28.1") (compat "30") (vertico "1.9")) +;; URL: https://github.com/minad/vertico + +;; This file is part of GNU Emacs. + +;; This program is free software: you can redistribute it and/or modify +;; it under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. + +;; This program is distributed in the hope that it will be useful, +;; but WITHOUT ANY WARRANTY; without even the implied warranty of +;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +;; GNU General Public License for more details. + +;; You should have received a copy of the GNU General Public License +;; along with this program. If not, see <https://www.gnu.org/licenses/>. + +;;; Commentary: + +;; This package is a Vertico extension providing a horizontal display. +;; +;; The mode can be enabled globally or via `vertico-multiform-mode' +;; per command or completion category. Alternatively the flat display +;; can be toggled temporarily with M-F if `vertico-multiform-mode' is +;; enabled. +;; +;; The flat display can be made to look like `ido-mode' by setting +;; `vertico-cycle' to t. See also the `vertico-flat-format' +;; configuration variable for further tweaks. + +;;; Code: + +(require 'vertico) +(eval-when-compile (require 'cl-lib)) + +(defcustom vertico-flat-max-lines 1 + "Maximal number of lines to use." + :type 'natnum + :group 'vertico) + +(defcustom vertico-flat-format + '(:multiple #("{%s}" 0 1 (face minibuffer-prompt) + 3 4 (face minibuffer-prompt)) + :single #("[%s]" 0 1 (face minibuffer-prompt) + 1 3 (face success) 3 4 (face minibuffer-prompt)) + :prompt #("(%s)" 0 1 (face minibuffer-prompt) + 3 4 (face minibuffer-prompt)) + :separator #(" | " 0 3 (face minibuffer-prompt)) + :ellipsis #("…" 0 1 (face minibuffer-prompt)) + :no-match "[No match]") + "Formatting strings." + :type 'plist + :group 'vertico) + +(defcustom vertico-flat-annotate nil + "Annotate candidates." + :type 'boolean + :group 'vertico) + +(defvar-keymap vertico-flat-map + :doc "Additional keymap activated in flat mode." + "<remap> <left-char>" #'vertico-previous + "<remap> <right-char>" #'vertico-next) + +;;;###autoload +(define-minor-mode vertico-flat-mode + "Flat, horizontal display for Vertico." + :global t :group 'vertico + ;; Shrink current minibuffer window + (when-let ((win (active-minibuffer-window))) + (unless (frame-root-window-p win) + (window-resize win (- (window-pixel-height win)) nil nil 'pixelwise))) + (cl-callf2 rassq-delete-all vertico-flat-map minor-mode-map-alist) + (when vertico-flat-mode + (push `(vertico--input . ,vertico-flat-map) minor-mode-map-alist))) + +(cl-defmethod vertico--display-candidates (candidates &context (vertico-flat-mode (eql t))) + (setq-local truncate-lines nil + resize-mini-windows t) + (move-overlay vertico--candidates-ov (point-max) (point-max)) + (overlay-put + vertico--candidates-ov 'after-string + (concat #(" " 0 1 (cursor t)) + (cond + ((and (not candidates) (plist-get vertico-flat-format :no-match))) + ((and (= vertico--total 1) (= vertico--index 0) + (when-let ((fmt (plist-get vertico-flat-format :single))) + (format fmt (substring-no-properties (car candidates)))))) + (t (format (plist-get vertico-flat-format (if (< vertico--index 0) :prompt :multiple)) + (string-join candidates (plist-get vertico-flat-format :separator)))))))) + +(cl-defmethod vertico--arrange-candidates (&context (vertico-flat-mode (eql t))) + (let* ((index (max 0 vertico--index)) (count vertico-count) + (candidates (nthcdr vertico--index vertico--candidates)) + (width (- (* vertico-flat-max-lines (- (vertico--window-width) 4)) + (length (plist-get vertico-flat-format :left)) + (length (plist-get vertico-flat-format :separator)) + (length (plist-get vertico-flat-format :right)) + (length (plist-get vertico-flat-format :ellipsis)) + (car (posn-col-row (posn-at-point (1- (point-max))))))) + (result) (wrapped)) + (while (and candidates (not (eq wrapped (car candidates))) + (> width 0) (> count 0)) + (let ((cand (pop candidates)) (prefix "") (suffix "")) + (setq cand (funcall vertico--hilit (substring cand))) + (pcase (and vertico-flat-annotate (vertico--affixate (list cand))) + (`((,c ,p ,s)) (setq cand c prefix p suffix s))) + (when (string-search "\n" cand) + (setq cand (vertico--truncate-multiline cand width))) + (setq cand (string-trim + (replace-regexp-in-string + "[ \t]+" + (lambda (x) (apply #'propertize " " (text-properties-at 0 x))) + (vertico--format-candidate cand prefix suffix index vertico--index))) + index (1+ index) + count (1- count) + width (- width (string-width cand) (length (plist-get vertico-flat-format :separator)))) + (when (or (not result) (> width 0)) + (push cand result)) + (when (and vertico-cycle (not candidates)) + (setq candidates vertico--candidates index 0 + wrapped (nth vertico--index vertico--candidates))))) + (when (if wrapped + (> vertico--total (- vertico-count count)) + (and (/= vertico--total 0) (/= index vertico--total))) + (push (plist-get vertico-flat-format :ellipsis) result)) + (nreverse result))) + +(provide 'vertico-flat) +;;; vertico-flat.el ends here diff --git a/emacs/elpa/vertico-20241004.1350/vertico-grid.el b/emacs/elpa/vertico-20241004.1350/vertico-grid.el @@ -0,0 +1,173 @@ +;;; vertico-grid.el --- Grid display for Vertico -*- lexical-binding: t -*- + +;; Copyright (C) 2021-2024 Free Software Foundation, Inc. + +;; Author: Daniel Mendler <mail@daniel-mendler.de> +;; Maintainer: Daniel Mendler <mail@daniel-mendler.de> +;; Created: 2021 +;; Package-Requires: ((emacs "28.1") (compat "30") (vertico "1.9")) +;; URL: https://github.com/minad/vertico + +;; This file is part of GNU Emacs. + +;; This program is free software: you can redistribute it and/or modify +;; it under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. + +;; This program is distributed in the hope that it will be useful, +;; but WITHOUT ANY WARRANTY; without even the implied warranty of +;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +;; GNU General Public License for more details. + +;; You should have received a copy of the GNU General Public License +;; along with this program. If not, see <https://www.gnu.org/licenses/>. + +;;; Commentary: + +;; This package is a Vertico extension providing a grid display. +;; +;; The mode can be enabled globally or via `vertico-multiform-mode' +;; per command or completion category. Alternatively the grid display +;; can be toggled temporarily with M-G if `vertico-multiform-mode' is +;; enabled. + +;;; Code: + +(require 'vertico) +(eval-when-compile + (require 'cl-lib) + (require 'subr-x)) + +(defcustom vertico-grid-min-columns 2 + "Minimal number of grid columns." + :type 'natnum + :group 'vertico) + +(defcustom vertico-grid-max-columns 8 + "Maximal number of grid columns." + :type 'natnum + :group 'vertico) + +(defcustom vertico-grid-annotate 0 + "Reserved characters for the annotations." + :type 'natnum + :group 'vertico) + +(defcustom vertico-grid-separator + #(" | " 3 4 (display (space :width (1)) face (:inherit shadow :inverse-video t))) + "Separator between columns." + :type 'string + :group 'vertico) + +(defcustom vertico-grid-lookahead 100 + "Number of candidates to lookahead for column number computation. +When scrolling beyond this limit, candidates may be truncated." + :type 'natnum + :group 'vertico) + +(defvar-keymap vertico-grid-map + :doc "Additional keymap activated in grid mode." + "<remap> <left-char>" #'vertico-grid-left + "<remap> <right-char>" #'vertico-grid-right + "<remap> <scroll-down-command>" #'vertico-grid-scroll-down + "<remap> <scroll-up-command>" #'vertico-grid-scroll-up) + +(defvar-local vertico-grid--columns vertico-grid-min-columns + "Current number of grid columns.") + +(defun vertico-grid-left (&optional n) + "Move N columns to the left in the grid." + (interactive "p") + (vertico-grid-right (- (or n 1)))) + +(defun vertico-grid-right (&optional n) + "Move N columns to the right in the grid." + (interactive "p") + (let* ((page (* vertico-count vertico-grid--columns)) + (x1 (/ (% vertico--index page) vertico-count)) + (cols (min (1- vertico-grid--columns) + (+ x1 (/ (- vertico--total vertico--index 1) vertico-count)))) + (x2 (if vertico-cycle + (mod (+ x1 (or n 1)) (1+ cols)) + (min cols (max 0 (+ x1 (or n 1))))))) + (vertico--goto (+ vertico--index (* vertico-count (- x2 x1)))))) + +(defun vertico-grid-scroll-down (&optional n) + "Go back by N pages." + (interactive "p") + (vertico--goto (max 0 (- vertico--index (* (or n 1) vertico-grid--columns vertico-count))))) + +(defun vertico-grid-scroll-up (&optional n) + "Go forward by N pages." + (interactive "p") + (vertico-grid-scroll-down (- (or n 1)))) + +;;;###autoload +(define-minor-mode vertico-grid-mode + "Grid display for Vertico." + :global t :group 'vertico + ;; Shrink current minibuffer window + (when-let ((win (active-minibuffer-window))) + (unless (frame-root-window-p win) + (window-resize win (- (window-pixel-height win)) nil nil 'pixelwise))) + (cl-callf2 rassq-delete-all vertico-grid-map minor-mode-map-alist) + (when vertico-grid-mode + (push `(vertico--input . ,vertico-grid-map) minor-mode-map-alist))) + +(cl-defmethod vertico--arrange-candidates (&context (vertico-grid-mode (eql t))) + (when (<= vertico--index 0) + (let ((w 1)) + (cl-loop repeat vertico-grid-lookahead for cand in vertico--candidates do + (setq w (max w (+ vertico-grid-annotate (length cand))))) + (setq vertico-grid--columns + (max vertico-grid-min-columns + (min vertico-grid-max-columns + (floor (vertico--window-width) (+ w (length vertico-grid-separator)))))))) + (let* ((sep (length vertico-grid-separator)) + (count (* vertico-count vertico-grid--columns)) + (start (* count (floor (max 0 vertico--index) count))) + (width (- (/ (vertico--window-width) vertico-grid--columns) sep)) + (cands (funcall (if (> vertico-grid-annotate 0) #'vertico--affixate #'identity) + (cl-loop repeat count for c in (nthcdr start vertico--candidates) + collect (funcall vertico--hilit (substring c))))) + (cands (cl-loop + for cand in cands for index from 0 collect + (let (prefix suffix) + (when (consp cand) + (setq prefix (cadr cand) suffix (caddr cand) cand (car cand))) + (when (string-search "\n" cand) + (setq cand (vertico--truncate-multiline cand width))) + (truncate-string-to-width + (string-trim + (replace-regexp-in-string + "[ \t]+" + (lambda (x) (apply #'propertize " " (text-properties-at 0 x))) + (vertico--format-candidate cand prefix suffix (+ index start) start))) + width)))) + (width (make-vector vertico-grid--columns 0))) + (dotimes (col vertico-grid--columns) + (dotimes (row vertico-count) + (aset width col (max + (aref width col) + (string-width (or (nth (+ row (* col vertico-count)) cands) "")))))) + (dotimes (col (1- vertico-grid--columns)) + (cl-incf (aref width (1+ col)) (+ (aref width col) sep))) + (cl-loop for row from 0 to (1- (min vertico-count vertico--total)) collect + (let ((line (list "\n"))) + (cl-loop for col from (1- vertico-grid--columns) downto 0 do + (when-let ((cand (nth (+ row (* col vertico-count)) cands))) + (push cand line) + (when (> col 0) + (push vertico-grid-separator line) + (push (propertize " " 'display + `(space :align-to (+ left ,(aref width (1- col))))) line)))) + (string-join line))))) + +;; Do not show Vertico commands in M-X +(dolist (sym '(vertico-grid-left vertico-grid-right + vertico-grid-scroll-up vertico-grid-scroll-down)) + (put sym 'completion-predicate #'vertico--command-p)) + +(provide 'vertico-grid) +;;; vertico-grid.el ends here diff --git a/emacs/elpa/vertico-20241004.1350/vertico-indexed.el b/emacs/elpa/vertico-20241004.1350/vertico-indexed.el @@ -0,0 +1,83 @@ +;;; vertico-indexed.el --- Select indexed candidates -*- lexical-binding: t -*- + +;; Copyright (C) 2021-2024 Free Software Foundation, Inc. + +;; Author: Daniel Mendler <mail@daniel-mendler.de> +;; Maintainer: Daniel Mendler <mail@daniel-mendler.de> +;; Created: 2021 +;; Package-Requires: ((emacs "28.1") (compat "30") (vertico "1.9")) +;; URL: https://github.com/minad/vertico + +;; This file is part of GNU Emacs. + +;; This program is free software: you can redistribute it and/or modify +;; it under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. + +;; This program is distributed in the hope that it will be useful, +;; but WITHOUT ANY WARRANTY; without even the implied warranty of +;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +;; GNU General Public License for more details. + +;; You should have received a copy of the GNU General Public License +;; along with this program. If not, see <https://www.gnu.org/licenses/>. + +;;; Commentary: + +;; This package is a Vertico extension, which prefixes candidates with indices +;; if enabled via `vertico-indexed-mode'. It allows you to select candidates +;; with prefix arguments. This is designed to be a faster alternative to +;; selecting a candidate with `vertico-next' and `vertico-previous'. + +;;; Code: + +(require 'vertico) + +(defface vertico-indexed + '((t :height 0.75 :inherit font-lock-comment-face)) + "Face used for the candidate index prefix." + :group 'vertico-faces) + +(defcustom vertico-indexed-start 0 + "Start of the indexing." + :group 'vertico + :type 'natnum) + +(defvar vertico-indexed--commands + '(vertico-insert vertico-exit vertico-directory-enter)) +(defvar-local vertico-indexed--min 0) +(defvar-local vertico-indexed--max 0) + +;;;###autoload +(define-minor-mode vertico-indexed-mode + "Prefix candidates with indices." + :global t :group 'vertico) + +(cl-defmethod vertico--prepare :before (&context (vertico-indexed-mode (eql t))) + (when (and prefix-arg (memq this-command vertico-indexed--commands)) + (let ((index (+ vertico-indexed--min + (- (prefix-numeric-value prefix-arg) + vertico-indexed-start)))) + (if (and (>= index vertico-indexed--min) + (<= index vertico-indexed--max) + (/= vertico--total 0)) + (setq vertico--index index prefix-arg nil) + (minibuffer-message "Out of range") + (setq this-command #'ignore))))) + +(cl-defmethod vertico--format-candidate :around + (cand prefix suffix index start &context (vertico-indexed-mode (eql t))) + (setq vertico-indexed--min start vertico-indexed--max index) + (cl-call-next-method + cand + (concat (propertize (format + (if (> (+ vertico-indexed-start vertico-count) 10) + "%2d " "%1d ") + (+ (- index start) vertico-indexed-start)) + 'face 'vertico-indexed) + prefix) + suffix index start)) + +(provide 'vertico-indexed) +;;; vertico-indexed.el ends here diff --git a/emacs/elpa/vertico-20241004.1350/vertico-mouse.el b/emacs/elpa/vertico-20241004.1350/vertico-mouse.el @@ -0,0 +1,94 @@ +;;; vertico-mouse.el --- Mouse support for Vertico -*- lexical-binding: t -*- + +;; Copyright (C) 2021-2024 Free Software Foundation, Inc. + +;; Author: Daniel Mendler <mail@daniel-mendler.de> +;; Maintainer: Daniel Mendler <mail@daniel-mendler.de> +;; Created: 2021 +;; Package-Requires: ((emacs "28.1") (compat "30") (vertico "1.9")) +;; URL: https://github.com/minad/vertico + +;; This file is part of GNU Emacs. + +;; This program is free software: you can redistribute it and/or modify +;; it under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. + +;; This program is distributed in the hope that it will be useful, +;; but WITHOUT ANY WARRANTY; without even the implied warranty of +;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +;; GNU General Public License for more details. + +;; You should have received a copy of the GNU General Public License +;; along with this program. If not, see <https://www.gnu.org/licenses/>. + +;;; Commentary: + +;; This package is a Vertico extension, which adds mouse support. + +;;; Code: + +(require 'vertico) + +(defface vertico-mouse + '((t :inherit highlight)) + "Face used for mouse highlighting." + :group 'vertico-faces) + +(defun vertico-mouse--index (event) + "Return candidate index at EVENT." + (when-let ((object (posn-object (event-end event))) + ((consp object))) + (get-text-property (cdr object) 'vertico-mouse--index (car object)))) + +(defun vertico-mouse--click (key) + "Create command handling mouse click, behave like KEY press." + (lambda (event) + (interactive "e") + ;; Mouse clicks can even happen if another window is selected. + (with-selected-window (active-minibuffer-window) + (when-let ((vertico--index (vertico-mouse--index event)) + (cmd (keymap-local-lookup key))) + (funcall cmd))))) + +(defvar-keymap vertico-mouse-map + :doc "Additional keymap activated in mouse mode." + "<mouse-1>" (vertico-mouse--click "RET") + "<mouse-3>" (vertico-mouse--click "TAB")) +(fset 'vertico-mouse-map vertico-mouse-map) + +(defun vertico-mouse--scroll-up (n) + "Scroll up by N lines." + (vertico--goto (max 0 (+ vertico--index n)))) + +(defun vertico-mouse--scroll-down (n) + "Scroll down by N lines." + (vertico-mouse--scroll-up (- n))) + +;;;###autoload +(define-minor-mode vertico-mouse-mode + "Mouse support for Vertico." + :global t :group 'vertico) + +(cl-defmethod vertico--format-candidate + :around (cand prefix suffix index start &context (vertico-mouse-mode (eql t))) + (setq cand (cl-call-next-method cand prefix + (concat suffix #(" " 0 1 (display (space :align-to right)))) + index start)) + (add-text-properties 0 (1- (length cand)) + `(vertico-mouse--index ,index + mouse-face vertico-mouse keymap vertico-mouse-map) + cand) + cand) + +(cl-defmethod vertico--setup :after (&context (vertico-mouse-mode (eql t))) + (when (boundp 'mwheel-coalesce-scroll-events) + (setq-local mwheel-coalesce-scroll-events t)) + (when (boundp 'pixel-scroll-precision-mode) + (setq-local pixel-scroll-precision-mode nil)) + (setq-local mwheel-scroll-up-function #'vertico-mouse--scroll-up + mwheel-scroll-down-function #'vertico-mouse--scroll-down)) + +(provide 'vertico-mouse) +;;; vertico-mouse.el ends here diff --git a/emacs/elpa/vertico-20241004.1350/vertico-multiform.el b/emacs/elpa/vertico-20241004.1350/vertico-multiform.el @@ -0,0 +1,220 @@ +;;; vertico-multiform.el --- Configure Vertico in different forms per command -*- lexical-binding: t -*- + +;; Copyright (C) 2021-2024 Free Software Foundation, Inc. + +;; Author: Daniel Mendler <mail@daniel-mendler.de> +;; Maintainer: Daniel Mendler <mail@daniel-mendler.de> +;; Created: 2021 +;; Package-Requires: ((emacs "28.1") (compat "30") (vertico "1.9")) +;; URL: https://github.com/minad/vertico + +;; This file is part of GNU Emacs. + +;; This program is free software: you can redistribute it and/or modify +;; it under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. + +;; This program is distributed in the hope that it will be useful, +;; but WITHOUT ANY WARRANTY; without even the implied warranty of +;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +;; GNU General Public License for more details. + +;; You should have received a copy of the GNU General Public License +;; along with this program. If not, see <https://www.gnu.org/licenses/>. + +;;; Commentary: + +;; This package is a Vertico extension for fine tuning the Vertico +;; display and other minibuffer modes per command or completion +;; category. For some commands you may want to use the +;; `vertico-buffer' display and for completion categories like file +;; you prefer the `vertico-grid-mode'. +;; +;; Example: +;; +;; (setq vertico-multiform-commands +;; '((consult-line buffer) +;; (consult-imenu reverse buffer) +;; (execute-extended-command flat))) +;; +;; (setq vertico-multiform-categories +;; '((file buffer grid) +;; (imenu (:not indexed mouse)) +;; (symbol (vertico-sort-function . vertico-sort-alpha)))) +;; +;; (vertico-multiform-mode) +;; +;; Temporary toggling between the different display modes is possible. +;; The following keys are bound in the `vertico-multiform-map'. +;; +;; M-B -> `vertico-multiform-buffer' +;; M-F -> `vertico-multiform-flat' +;; M-G -> `vertico-multiform-grid' +;; M-R -> `vertico-multiform-reverse' +;; M-U -> `vertico-multiform-unobtrusive' +;; M-V -> `vertico-multiform-vertical' +;; +;;; Code: + +(require 'vertico) +(eval-when-compile (require 'cl-lib)) + +(defcustom vertico-multiform-commands nil + "Alist of commands/regexps and list of settings to turn on per command. +Takes precedence over `vertico-multiform-categories'. A setting +can either be a mode symbol, a function, an inverted mode symbol +or function, or a cons cell of variable name and value. The key +t can be used to specify catch all/default settings. The value +of `this-command' is used as key for the lookup." + :group 'vertico + :type '(alist :key-type (choice symbol regexp (const t)) :value-type (repeat sexp))) + +(defcustom vertico-multiform-categories nil + "Alist of categories/regexps and list of settings to turn on per category. +See `vertico-multiform-commands' on details about the settings. The +category settings have lower precedence than +`vertico-multiform-commands'." + :group 'vertico + :type '(alist :key-type (choice symbol regexp (const t)) :value-type (repeat sexp))) + +(defvar vertico-multiform--stack nil) + +(defun vertico-multiform--toggle (arg) + "Toggle modes from stack depending on ARG." + (when-let ((win (active-minibuffer-window)) + (modes (car vertico-multiform--stack))) + (when (> arg 0) (setq modes (reverse modes))) + (with-selected-window win + (dolist (m modes) + (if (eq (car-safe m) :not) + (funcall (cdr m) (- arg)) + (funcall m arg)))))) + +(defun vertico-multiform--lookup (key list) + "Lookup symbolic KEY in LIST. +The keys in LIST can be symbols or regexps." + (and (symbolp key) + (let (case-fold-search) + (seq-find (pcase-lambda (`(,x . ,_)) + (cond + ((eq x t)) + ((symbolp x) (eq key x)) + ((string-match-p x (symbol-name key))))) + list)))) + +(defun vertico-multiform--setup () + "Enable modes at minibuffer setup." + (let ((cat (compat-call completion-metadata-get + (completion-metadata (buffer-substring-no-properties + (minibuffer-prompt-end) + (max (minibuffer-prompt-end) (point))) + minibuffer-completion-table + minibuffer-completion-predicate) + 'category)) + (exit (make-symbol "vertico-multiform--exit")) + (depth (recursion-depth)) + (modes nil)) + (fset exit (lambda () + (when (= depth (recursion-depth)) + (remove-hook 'minibuffer-exit-hook exit) + (vertico-multiform--toggle -1) + (pop vertico-multiform--stack)))) + (add-hook 'minibuffer-exit-hook exit) + (dolist (x (cdr (or (vertico-multiform--lookup this-command vertico-multiform-commands) + (vertico-multiform--lookup cat vertico-multiform-categories)))) + (pcase x + (`(:not . ,fs) + (dolist (f fs) + (let ((sym (and (symbolp f) (intern-soft (format "vertico-%s-mode" f))))) + (push (cons :not (if (and sym (fboundp sym)) sym f)) modes)))) + ((or (pred functionp) (pred symbolp)) + (let ((sym (and (symbolp x) (intern-soft (format "vertico-%s-mode" x))))) + (push (if (and sym (fboundp sym)) sym x) modes))) + (`(,k . ,v) (set (make-local-variable k) v)) + (_ (error "Invalid multiform setting %S" x)))) + (push modes vertico-multiform--stack) + (vertico-multiform--toggle 1) + (vertico--setup))) + +(defvar-keymap vertico-multiform-map + :doc "Additional keymap activated in multiform mode.") + +;;;###autoload +(define-minor-mode vertico-multiform-mode + "Configure Vertico in various forms per command." + :global t :group 'vertico + (when (/= (recursion-depth) 0) + (warn "vertico-multiform must not be toggled from recursive minibuffers")) + (when vertico-multiform--stack + (warn "vertico-multiform state is inconsistent") + (setq vertico-multiform--stack nil)) + (cl-callf2 rassq-delete-all vertico-multiform-map minor-mode-map-alist) + (when vertico-multiform-mode + (push `(vertico--input . ,vertico-multiform-map) minor-mode-map-alist))) + +(cl-defmethod vertico--advice (&context (vertico-multiform-mode (eql t)) &rest app) + (unwind-protect + (progn + (vertico-multiform--toggle -1) + (minibuffer-with-setup-hook #'vertico-multiform--setup + (apply app))) + (vertico-multiform--toggle 1))) + +(defun vertico-multiform--temporary-mode (mode arg) + "Enable or disable MODE temporarily in minibuffer given ARG. +ARG can be nil, t, -1, 1 or toggle." + (unless (minibufferp) + (user-error "`%s' must be called inside the minibuffer" this-command)) + (unless vertico-multiform-mode + (user-error "`vertico-multiform-mode' is not enabled")) + (setq arg (pcase arg + ('toggle (not (and (boundp mode) (symbol-value mode)))) + ((or 'nil 't) arg) + (_ (> arg 0)))) + (unless (eq arg (and (boundp mode) (symbol-value mode))) + (funcall mode (if arg 1 -1)) + (let ((modes (car vertico-multiform--stack)) + (not-mode (cons :not mode))) + (when arg + (cl-rotatef not-mode mode)) + (if (member mode modes) + (setcar vertico-multiform--stack (remove mode modes)) + (push not-mode (car vertico-multiform--stack)))))) + +(defvar vertico-multiform--display-modes nil) +(defvar-local vertico-multiform--display-last nil) + +(defun vertico-multiform-vertical (&optional mode) + "Toggle to display MODE temporarily in minibuffer. +MODE defaults to the vertical display." + (interactive) + (let (last) + (dolist (m vertico-multiform--display-modes) + (when (and (boundp m) (symbol-value m)) + (setq last m) + (vertico-multiform--temporary-mode m -1))) + (when (eq last mode) + (setq mode vertico-multiform--display-last)) + (when mode + (vertico-multiform--temporary-mode mode 1)) + (setq vertico-multiform--display-last last))) + +(pcase-dolist (`(,key ,name) '(("M-B" buffer) + ("M-F" flat) + ("M-G" grid) + ("M-R" reverse) + ("M-U" unobtrusive) ;; must come after flat + ("M-V" vertical))) + (let ((toggle (intern (format "vertico-multiform-%s" name)))) + (unless (eq name 'vertical) + (let ((mode (intern (format "vertico-%s-mode" name)))) + (defalias toggle + (lambda () (interactive) (vertico-multiform-vertical mode)) + (format "Toggle the %s display." name)) + (push mode vertico-multiform--display-modes))) + (put toggle 'completion-predicate #'vertico--command-p) + (keymap-set vertico-multiform-map key toggle))) + +(provide 'vertico-multiform) +;;; vertico-multiform.el ends here diff --git a/emacs/elpa/vertico-20241004.1350/vertico-pkg.el b/emacs/elpa/vertico-20241004.1350/vertico-pkg.el @@ -0,0 +1,11 @@ +;; -*- no-byte-compile: t; lexical-binding: nil -*- +(define-package "vertico" "20241004.1350" + "VERTical Interactive COmpletion." + '((emacs "28.1") + (compat "30")) + :url "https://github.com/minad/vertico" + :commit "e826dfcb14af5e2cfd88ed110d0208ddc2d37788" + :revdesc "e826dfcb14af" + :keywords '("convenience" "files" "matching" "completion") + :authors '(("Daniel Mendler" . "mail@daniel-mendler.de")) + :maintainers '(("Daniel Mendler" . "mail@daniel-mendler.de"))) diff --git a/emacs/elpa/vertico-20241004.1350/vertico-quick.el b/emacs/elpa/vertico-20241004.1350/vertico-quick.el @@ -0,0 +1,143 @@ +;;; vertico-quick.el --- Quick keys for Vertico -*- lexical-binding: t -*- + +;; Copyright (C) 2021-2024 Free Software Foundation, Inc. + +;; Author: Daniel Mendler <mail@daniel-mendler.de> +;; Maintainer: Daniel Mendler <mail@daniel-mendler.de> +;; Created: 2021 +;; Package-Requires: ((emacs "28.1") (compat "30") (vertico "1.9")) +;; URL: https://github.com/minad/vertico + +;; This file is part of GNU Emacs. + +;; This program is free software: you can redistribute it and/or modify +;; it under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. + +;; This program is distributed in the hope that it will be useful, +;; but WITHOUT ANY WARRANTY; without even the implied warranty of +;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +;; GNU General Public License for more details. + +;; You should have received a copy of the GNU General Public License +;; along with this program. If not, see <https://www.gnu.org/licenses/>. + +;;; Commentary: + +;; This package is a Vertico extension, which prefixes candidates with +;; quick keys. Typing these quick keys allows you to select the +;; candidate in front of them. This is designed to be a faster +;; alternative to selecting a candidate with `vertico-next' and +;; `vertico-previous'. +;; (keymap-set vertico-map "M-q" #'vertico-quick-insert) +;; (keymap-set vertico-map "C-q" #'vertico-quick-exit) + +;;; Code: + +(require 'vertico) +(eval-when-compile + (require 'cl-lib) + (require 'subr-x)) + +(defface vertico-quick1 + '((((class color) (min-colors 88) (background dark)) + :background "#0050af" :foreground "white" :inherit bold) + (((class color) (min-colors 88) (background light)) + :background "#7feaff" :foreground "black" :inherit bold) + (t :background "blue" :foreground "white" :inherit bold)) + "Face used for the first quick key." + :group 'vertico-faces) + +(defface vertico-quick2 + '((((class color) (min-colors 88) (background dark)) + :background "#7f1f7f" :foreground "white" :inherit bold) + (((class color) (min-colors 88) (background light)) + :background "#ffaaff" :foreground "black" :inherit bold) + (t :background "magenta" :foreground "white" :inherit bold)) + "Face used for the second quick key." + :group 'vertico-faces) + +(defcustom vertico-quick1 "asdfgh" + "Single level quick keys." + :type 'string + :group 'vertico) + +(defcustom vertico-quick2 "jkluionm" + "Two level quick keys." + :type 'string + :group 'vertico) + +(defun vertico-quick--keys (two index start) + "Format quick keys prefix. +INDEX is the current candidate index. +START is the index of the first displayed candidate. +TWO is non-nil if two keys should be displayed." + (let ((fst (length vertico-quick1)) + (snd (length vertico-quick2)) + (idx (- index start))) + (if (>= idx fst) + (let ((first (elt vertico-quick2 (mod (/ (- idx fst) fst) snd))) + (second (elt vertico-quick1 (mod (- idx fst) fst)))) + (cond + ((eq first two) + (list + (concat " " (propertize (char-to-string second) 'face 'vertico-quick1)) + (cons second index))) + (two + (list " ")) + (t + (list + (concat (propertize (char-to-string first) 'face 'vertico-quick1) + (propertize (char-to-string second) 'face 'vertico-quick2)) + (cons first (list first)))))) + (let ((first (elt vertico-quick1 (mod idx fst)))) + (if two + (list " ") + (list + (concat (propertize (char-to-string first) 'face 'vertico-quick1) " ") + (cons first index))))))) + +(defun vertico-quick--read (&optional first) + "Read quick key given FIRST pressed key." + (cl-letf* ((list nil) + (orig (symbol-function #'vertico--format-candidate)) + ((symbol-function #'vertico--format-candidate) + (lambda (cand prefix suffix index start) + (pcase-let ((`(,keys . ,events) (vertico-quick--keys first index start))) + (setq list (nconc events list)) + (if (bound-and-true-p vertico-flat-mode) + (setq keys (string-replace " " "" keys) + cand (string-trim cand) + cand (substring cand (min (length cand) (length keys)))) + (setq keys (concat keys (make-string (max 1 (- (length prefix) 2)) ?\s)))) + (funcall orig cand keys suffix index start))))) + (vertico--exhibit) + (alist-get (read-key) list))) + +;;;###autoload +(defun vertico-quick-jump () + "Jump to candidate using quick keys." + (interactive) + (if (= vertico--total 0) + (and (minibuffer-message "No match") nil) + (let ((idx (vertico-quick--read))) + (when (consp idx) (setq idx (vertico-quick--read (car idx)))) + (when idx (setq vertico--index idx))))) + +;;;###autoload +(defun vertico-quick-exit () + "Exit with candidate using quick keys." + (interactive) + (when (vertico-quick-jump) + (vertico-exit))) + +;;;###autoload +(defun vertico-quick-insert () + "Insert candidate using quick keys." + (interactive) + (when (vertico-quick-jump) + (vertico-insert))) + +(provide 'vertico-quick) +;;; vertico-quick.el ends here diff --git a/emacs/elpa/vertico-20241004.1350/vertico-repeat.el b/emacs/elpa/vertico-20241004.1350/vertico-repeat.el @@ -0,0 +1,237 @@ +;;; vertico-repeat.el --- Repeat Vertico sessions -*- lexical-binding: t -*- + +;; Copyright (C) 2021-2024 Free Software Foundation, Inc. + +;; Author: Daniel Mendler <mail@daniel-mendler.de> +;; Maintainer: Daniel Mendler <mail@daniel-mendler.de> +;; Created: 2021 +;; Package-Requires: ((emacs "28.1") (compat "30") (vertico "1.9")) +;; URL: https://github.com/minad/vertico + +;; This file is part of GNU Emacs. + +;; This program is free software: you can redistribute it and/or modify +;; it under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. + +;; This program is distributed in the hope that it will be useful, +;; but WITHOUT ANY WARRANTY; without even the implied warranty of +;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +;; GNU General Public License for more details. + +;; You should have received a copy of the GNU General Public License +;; along with this program. If not, see <https://www.gnu.org/licenses/>. + +;;; Commentary: + +;; This package is a Vertico extension, which enables repetition of +;; Vertico sessions via the `vertico-repeat', `vertico-repeat-previous' +;; and `vertico-repeat-select' commands. If the repeat commands are +;; called from an existing Vertico minibuffer session, only sessions +;; corresponding to the current minibuffer command are offered via +;; completion. +;; +;; It is necessary to register a minibuffer setup hook, which saves +;; the Vertico state for repetition. In order to save the history +;; across Emacs sessions, enable `savehist-mode' and add +;; `vertico-repeat-history' to `savehist-additional-variables'. +;; +;; (keymap-global-set "M-R" #'vertico-repeat) +;; (keymap-set vertico-map "M-P" #'vertico-repeat-previous) +;; (keymap-set vertico-map "M-N" #'vertico-repeat-next) +;; (keymap-set vertico-map "S-<prior>" #'vertico-repeat-previous) +;; (keymap-set vertico-map "S-<next>" #'vertico-repeat-next) +;; (add-hook 'minibuffer-setup-hook #'vertico-repeat-save) +;; +;; See also the related extension `vertico-suspend', which uses a +;; different technique, relying on recursive minibuffers to suspend +;; the current completion session temporarily while preserving the +;; entire state. + +;;; Code: + +(require 'vertico) +(eval-when-compile (require 'cl-lib)) + +(defcustom vertico-repeat-filter + '(vertico-repeat + vertico-repeat-select + execute-extended-command + execute-extended-command-for-buffer) + "List of commands to filter out from the history." + :type '(repeat symbol) + :group 'vertico) + +(defcustom vertico-repeat-transformers + (list #'vertico-repeat--filter-empty + #'vertico-repeat--filter-commands) + "List of functions to apply to history element before saving." + :type '(repeat function) + :group 'vertico) + +(declare-function vertico-multiform-vertical "ext:vertico-multiform") +(defvar vertico-multiform--display-modes) +(defvar vertico-repeat-history nil) +(defvar-local vertico-repeat--command nil) +(defvar-local vertico-repeat--input nil) +(defvar-local vertico-repeat--step nil) +(defvar-local vertico-repeat--pos 0) + +(defun vertico-repeat--filter-commands (session) + "Filter SESSION if command is listed in `vertico-repeat-filter'." + (and (not (memq (car session) vertico-repeat-filter)) session)) + +(defun vertico-repeat--filter-empty (session) + "Filter SESSION if input is empty." + (and (cadr session) (not (equal (cadr session) "")) session)) + +(defun vertico-repeat--save-input () + "Save current minibuffer input." + (setq vertico-repeat--input (minibuffer-contents-no-properties))) + +(defun vertico-repeat--current () + "Return the current session datum." + `(,vertico-repeat--command + ,vertico-repeat--input + ,@(and vertico--lock-candidate + (>= vertico--index 0) + (list (substring-no-properties + (nth vertico--index vertico--candidates)))) + ,@(and (bound-and-true-p vertico-multiform-mode) + (ensure-list + (seq-find (lambda (x) (and (boundp x) (symbol-value x))) + vertico-multiform--display-modes))))) + +(defun vertico-repeat--save-exit () + "Save command session in `vertico-repeat-history'." + (let ((session (vertico-repeat--current)) + (transform vertico-repeat-transformers)) + (while (and transform (setq session (funcall (pop transform) session)))) + (when session + (add-to-history 'vertico-repeat-history session)))) + +(defun vertico-repeat--restore (session) + "Restore Vertico SESSION for `vertico-repeat'." + (delete-minibuffer-contents) + (insert (cadr session)) + (setq vertico--lock-candidate + (when-let ((cand (seq-find #'stringp (cddr session)))) + (vertico--update) + (when-let ((idx (seq-position vertico--candidates cand))) + (setq vertico--index idx) + t))) + ;; Restore display modes if not modifying the current session + (when-let (((not (and vertico-repeat--command + (eq vertico-repeat--command (car session))))) + (mode (seq-find #'symbolp (cddr session))) + ((bound-and-true-p vertico-multiform-mode)) + ((not (and (boundp mode) (symbol-value mode))))) + (vertico-multiform-vertical mode)) + (vertico--exhibit)) + +(defun vertico-repeat--run (session) + "Run Vertico completion SESSION." + (unless session + (user-error "No repeatable session")) + (if (and vertico-repeat--command (eq vertico-repeat--command (car session))) + (vertico-repeat--restore session) + (minibuffer-with-setup-hook + (apply-partially #'vertico-repeat--restore session) + (command-execute (setq this-command (car session)))))) + +;;;###autoload +(defun vertico-repeat-save () + "Save Vertico session for `vertico-repeat'. +This function must be registered as `minibuffer-setup-hook'." + (when (and vertico--input (symbolp this-command)) + (setq vertico-repeat--command this-command) + (add-hook 'post-command-hook #'vertico-repeat--save-input nil 'local) + (add-hook 'minibuffer-exit-hook #'vertico-repeat--save-exit nil 'local))) + +;;;###autoload +(defun vertico-repeat-next (n) + "Repeat Nth next Vertico completion session. +This command must be called from an existing Vertico session +after `vertico-repeat-previous'." + (interactive "p") + (vertico-repeat-previous (- n))) + +;;;###autoload +(defun vertico-repeat-previous (n) + "Repeat Nth previous Vertico completion session. +If called from an existing Vertico session, restore the input and +selected candidate for the current command." + (interactive "p") + (vertico-repeat--run + (if (not vertico-repeat--command) + (and (> n 0) (nth (1- n) vertico-repeat-history)) + (cond + ((not vertico-repeat--step) + (setq vertico-repeat--step + (cons (vertico-repeat--current) + (cl-loop for h in vertico-repeat-history + if (eq (car h) vertico-repeat--command) collect h)))) + ((= vertico-repeat--pos 0) + (setcar vertico-repeat--step (vertico-repeat--current)))) + (cl-incf n vertico-repeat--pos) + (when-let (((>= n 0)) (session (nth n vertico-repeat--step))) + (setq vertico-repeat--pos n) + session)))) + +;;;###autoload +(defun vertico-repeat-select () + "Select a Vertico session from the session history and repeat it. +If called from an existing Vertico session, you can select among +previous sessions for the current command." + (interactive) + (vertico-repeat--run + (let* ((current-cmd vertico-repeat--command) + (trimmed + (delete-dups + (or + (cl-loop + for session in vertico-repeat-history + if (or (not current-cmd) (eq (car session) current-cmd)) + collect + (list + (symbol-name (car session)) + (replace-regexp-in-string + "\\s-+" " " + (string-trim (cadr session))) + session)) + (user-error "No repeatable session")))) + (max-cmd (cl-loop for (cmd . _) in trimmed + maximize (string-width cmd))) + (formatted (cl-loop + for (cmd input session) in trimmed collect + (cons + (concat + (and (not current-cmd) + (propertize cmd 'face 'font-lock-function-name-face)) + (and (not current-cmd) + (make-string (- max-cmd (string-width cmd) -4) ?\s)) + input) + session))) + (enable-recursive-minibuffers t)) + (cdr (assoc (completing-read + (if current-cmd + (format "History of %s: " current-cmd) + "Completion history: ") + (lambda (str pred action) + (if (eq action 'metadata) + '(metadata (display-sort-function . identity) + (cycle-sort-function . identity)) + (complete-with-action action formatted str pred))) + nil t nil t) + formatted))))) + +;;;###autoload +(defun vertico-repeat (&optional arg) + "Repeat last Vertico session. +If prefix ARG is non-nil, offer completion menu to select from session history." + (interactive "P") + (if arg (vertico-repeat-select) (vertico-repeat-previous 1))) + +(provide 'vertico-repeat) +;;; vertico-repeat.el ends here diff --git a/emacs/elpa/vertico-20241004.1350/vertico-reverse.el b/emacs/elpa/vertico-20241004.1350/vertico-reverse.el @@ -0,0 +1,79 @@ +;;; vertico-reverse.el --- Reverse the Vertico display -*- lexical-binding: t -*- + +;; Copyright (C) 2021-2024 Free Software Foundation, Inc. + +;; Author: Daniel Mendler <mail@daniel-mendler.de> +;; Maintainer: Daniel Mendler <mail@daniel-mendler.de> +;; Created: 2021 +;; Package-Requires: ((emacs "28.1") (compat "30") (vertico "1.9")) +;; URL: https://github.com/minad/vertico + +;; This file is part of GNU Emacs. + +;; This program is free software: you can redistribute it and/or modify +;; it under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. + +;; This program is distributed in the hope that it will be useful, +;; but WITHOUT ANY WARRANTY; without even the implied warranty of +;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +;; GNU General Public License for more details. + +;; You should have received a copy of the GNU General Public License +;; along with this program. If not, see <https://www.gnu.org/licenses/>. + +;;; Commentary: + +;; This package is a Vertico extension, which reverses the list of +;; candidates. +;; +;; The mode can be enabled globally or via `vertico-multiform-mode' +;; per command or completion category. Alternatively the reverse +;; display can be toggled temporarily with M-R if +;; `vertico-multiform-mode' is enabled. + +;;; Code: + +(require 'vertico) +(eval-when-compile (require 'cl-lib)) + +(defvar-keymap vertico-reverse-map + :doc "Additional keymap activated in reverse mode." + "<remap> <beginning-of-buffer>" #'vertico-last + "<remap> <minibuffer-beginning-of-buffer>" #'vertico-last + "<remap> <end-of-buffer>" #'vertico-first + "<remap> <scroll-down-command>" #'vertico-scroll-up + "<remap> <scroll-up-command>" #'vertico-scroll-down + "<remap> <next-line>" #'vertico-previous + "<remap> <previous-line>" #'vertico-next + "<remap> <next-line-or-history-element>" #'vertico-previous + "<remap> <previous-line-or-history-element>" #'vertico-next + "<remap> <backward-paragraph>" #'vertico-next-group + "<remap> <forward-paragraph>" #'vertico-previous-group) + +;;;###autoload +(define-minor-mode vertico-reverse-mode + "Reverse the Vertico display." + :global t :group 'vertico + ;; Reset overlays + (dolist (buf (buffer-list)) + (when-let ((ov (buffer-local-value 'vertico--candidates-ov buf))) + (overlay-put ov 'before-string nil))) + (cl-callf2 rassq-delete-all vertico-reverse-map minor-mode-map-alist) + (when vertico-reverse-mode + (push `(vertico--input . ,vertico-reverse-map) minor-mode-map-alist))) + +(cl-defmethod vertico--display-candidates (lines &context (vertico-reverse-mode (eql t))) + (move-overlay vertico--candidates-ov (point-min) (point-min)) + (setq lines (nreverse lines)) + (unless (eq vertico-resize t) + (setq lines (nconc (make-list (max 0 (- vertico-count (length lines))) "\n") lines))) + (let ((string (apply #'concat lines))) + (add-face-text-property 0 (length string) 'default 'append string) + (overlay-put vertico--candidates-ov 'before-string string) + (overlay-put vertico--candidates-ov 'after-string nil)) + (vertico--resize-window (length lines))) + +(provide 'vertico-reverse) +;;; vertico-reverse.el ends here diff --git a/emacs/elpa/vertico-20241004.1350/vertico-suspend.el b/emacs/elpa/vertico-20241004.1350/vertico-suspend.el @@ -0,0 +1,109 @@ +;;; vertico-suspend.el --- Suspend the current Vertico session -*- lexical-binding: t -*- + +;; Copyright (C) 2021-2024 Free Software Foundation, Inc. + +;; Author: Daniel Mendler <mail@daniel-mendler.de> +;; Maintainer: Daniel Mendler <mail@daniel-mendler.de> +;; Created: 2023 +;; Package-Requires: ((emacs "28.1") (compat "30") (vertico "1.9")) +;; URL: https://github.com/minad/vertico + +;; This file is part of GNU Emacs. + +;; This program is free software: you can redistribute it and/or modify +;; it under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. + +;; This program is distributed in the hope that it will be useful, +;; but WITHOUT ANY WARRANTY; without even the implied warranty of +;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +;; GNU General Public License for more details. + +;; You should have received a copy of the GNU General Public License +;; along with this program. If not, see <https://www.gnu.org/licenses/>. + +;;; Commentary: + +;; This package is a Vertico extension providing the `vertico-suspend' +;; command to suspend the current Vertico completion session. If +;; `vertico-suspend' is called from within the currently active +;; Vertico minibuffer, the completion session is suspended. Otherwise +;; the last session is restored. It is possible to suspend multiple +;; nested Vertico sessions. Note that `vertico-suspend' requires that +;; recursive minibuffers are enabled by setting the customizable +;; variable `enable-recursive-minibuffers' to t. +;; +;; (keymap-global-set "M-S" #'vertico-suspend) +;; +;; See also the related extension `vertico-repeat', which uses a +;; different technique, storing a completion session history. +;; +;; There exists a small issue with `vertico-suspend'. The setting +;; `echo-keystrokes' does not work. Unfortunately this cannot be +;; fixed without modifying the C source of Emacs, since Emacs forcibly +;; disables echo if a minibuffer is active. + +;;; Code: + +(require 'vertico) + +(defvar vertico-buffer--restore) +(declare-function vertico-buffer-mode "ext:vertico-buffer") +(defvar-local vertico-suspend--ov nil) + +;;;###autoload +(defun vertico-suspend () + "Suspend the current completion session. +If the command is invoked from within the Vertico minibuffer, the +current session is suspended. If the command is invoked from +outside the minibuffer, the active minibuffer is either selected +or the latest completion session is restored." + (interactive) + (unless enable-recursive-minibuffers + (user-error "Recursive minibuffers must be enabled")) + (advice-add #'set-minibuffer-message :around #'vertico-suspend--message) + (if-let ((win (active-minibuffer-window)) + (buf (window-buffer win)) + ((buffer-local-value 'vertico--input buf))) + (cond + ((minibufferp) + (add-hook 'pre-redisplay-functions #'vertico-suspend--unselect nil 'local) + (setq vertico-suspend--ov (make-overlay (point-min) (point-max) nil t t)) + (overlay-put vertico-suspend--ov 'invisible t) + (overlay-put vertico-suspend--ov 'priority 1000) + (overlay-put vertico--candidates-ov 'before-string nil) + (overlay-put vertico--candidates-ov 'after-string nil) + (set-window-parameter win 'no-other-window t) + (when (bound-and-true-p vertico-buffer-mode) + (vertico-buffer-mode -1) + (setq vertico-buffer--restore #'ignore)) + (vertico-suspend--unselect)) + (t + (select-window win) + (set-window-parameter win 'no-other-window nil) + (remove-hook 'pre-redisplay-functions #'vertico-suspend--unselect 'local) + (when vertico-suspend--ov + (delete-overlay vertico-suspend--ov) + (setq vertico-suspend--ov nil)) + (when (eq #'ignore (bound-and-true-p vertico-buffer--restore)) + (setq vertico-buffer--restore nil) + (vertico-buffer-mode 1)))) + (user-error "No Vertico session to suspend or resume"))) + +(defun vertico-suspend--unselect (&rest _) + "Ensure that suspended minibuffer is not selected." + (let ((win (get-buffer-window))) + (when (eq win (selected-window)) + (unless (frame-root-window-p win) + (window-resize win (- (window-pixel-height win)) nil nil 'pixelwise)) + (select-window (minibuffer-selected-window) t)))) + +(defun vertico-suspend--message (&rest app) + "Apply APP in non-suspended minibuffers, otherwise bail out." + (when-let ((win (active-minibuffer-window)) + ((not (buffer-local-value 'vertico-suspend--ov (window-buffer win))))) + (apply app))) + +(provide 'vertico-suspend) +;;; vertico-suspend.el ends here diff --git a/emacs/elpa/vertico-20241004.1350/vertico-unobtrusive.el b/emacs/elpa/vertico-20241004.1350/vertico-unobtrusive.el @@ -0,0 +1,67 @@ +;;; vertico-unobtrusive.el --- Unobtrusive display for Vertico -*- lexical-binding: t -*- + +;; Copyright (C) 2021-2024 Free Software Foundation, Inc. + +;; Author: Daniel Mendler <mail@daniel-mendler.de> +;; Maintainer: Daniel Mendler <mail@daniel-mendler.de> +;; Created: 2021 +;; Package-Requires: ((emacs "28.1") (compat "30") (vertico "1.9")) +;; URL: https://github.com/minad/vertico + +;; This file is part of GNU Emacs. + +;; This program is free software: you can redistribute it and/or modify +;; it under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. + +;; This program is distributed in the hope that it will be useful, +;; but WITHOUT ANY WARRANTY; without even the implied warranty of +;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +;; GNU General Public License for more details. + +;; You should have received a copy of the GNU General Public License +;; along with this program. If not, see <https://www.gnu.org/licenses/>. + +;;; Commentary: + +;; This package is a Vertico extension providing a unobtrusive +;; display. The unobtrusive display only shows the topmost candidate +;; and nothing else, it is a simple derivative of `vertico-flat-mode'. +;; +;; The mode can be enabled globally or via `vertico-multiform-mode' +;; per command or completion category. Alternatively the unobtrusive +;; display can be toggled temporarily with M-U if +;; `vertico-multiform-mode' is enabled. + +;;; Code: + +(require 'vertico-flat) + +(defvar vertico-unobtrusive--restore nil) + +;;;###autoload +(define-minor-mode vertico-unobtrusive-mode + "Unobtrusive display for Vertico." + :global t :group 'vertico + (cond + ((and vertico-unobtrusive-mode (not vertico-unobtrusive--restore)) + (push '(vertico-current . default) (default-value 'face-remapping-alist)) + (setq vertico-unobtrusive--restore (cons vertico-count vertico-count-format) + vertico-count 1 + vertico-count-format nil + vertico-flat-format `(:separator nil :ellipsis nil ,@vertico-flat-format))) + ((and (not vertico-unobtrusive-mode) vertico-unobtrusive--restore) + (cl-callf2 delete '(vertico-current . default) + (default-value 'face-remapping-alist)) + (setq vertico-count (car vertico-unobtrusive--restore) + vertico-count-format (cdr vertico-unobtrusive--restore) + vertico-flat-format (nthcdr 4 vertico-flat-format) + vertico-unobtrusive--restore nil))) + (vertico-flat-mode (if vertico-unobtrusive-mode 1 -1))) + +(cl-defmethod vertico--setup :before (&context (vertico-unobtrusive-mode (eql t))) + (redisplay)) + +(provide 'vertico-unobtrusive) +;;; vertico-unobtrusive.el ends here diff --git a/emacs/elpa/vertico-20241004.1350/vertico.el b/emacs/elpa/vertico-20241004.1350/vertico.el @@ -0,0 +1,762 @@ +;;; vertico.el --- VERTical Interactive COmpletion -*- lexical-binding: t -*- + +;; Copyright (C) 2021-2024 Free Software Foundation, Inc. + +;; Author: Daniel Mendler <mail@daniel-mendler.de> +;; Maintainer: Daniel Mendler <mail@daniel-mendler.de> +;; Created: 2021 +;; Package-Version: 20241004.1350 +;; Package-Revision: e826dfcb14af +;; Package-Requires: ((emacs "28.1") (compat "30")) +;; URL: https://github.com/minad/vertico +;; Keywords: convenience, files, matching, completion + +;; This file is part of GNU Emacs. + +;; This program is free software: you can redistribute it and/or modify +;; it under the terms of the GNU General Public License as published by +;; the Free Software Foundation, either version 3 of the License, or +;; (at your option) any later version. + +;; This program is distributed in the hope that it will be useful, +;; but WITHOUT ANY WARRANTY; without even the implied warranty of +;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +;; GNU General Public License for more details. + +;; You should have received a copy of the GNU General Public License +;; along with this program. If not, see <https://www.gnu.org/licenses/>. + +;;; Commentary: + +;; Vertico provides a performant and minimalistic vertical completion UI +;; based on the default completion system. By reusing the built-in +;; facilities, Vertico achieves full compatibility with built-in Emacs +;; completion commands and completion tables. + +;;; Code: + +(require 'compat) +(eval-when-compile + (require 'cl-lib) + (require 'subr-x)) + +(defgroup vertico nil + "VERTical Interactive COmpletion." + :link '(info-link :tag "Info Manual" "(vertico)") + :link '(url-link :tag "Website" "https://github.com/minad/vertico") + :link '(emacs-library-link :tag "Library Source" "vertico.el") + :group 'convenience + :group 'minibuffer + :prefix "vertico-") + +(defcustom vertico-count-format (cons "%-6s " "%s/%s") + "Format string used for the candidate count." + :type '(choice (const :tag "No candidate count" nil) (cons string string))) + +(defcustom vertico-group-format + (concat #(" " 0 4 (face vertico-group-separator)) + #(" %s " 0 4 (face vertico-group-title)) + #(" " 0 1 (face vertico-group-separator display (space :align-to right)))) + "Format string used for the group title." + :type '(choice (const :tag "No group titles" nil) string)) + +(defcustom vertico-count 10 + "Maximal number of candidates to show." + :type 'natnum) + +(defcustom vertico-preselect 'directory + "Configure if the prompt or first candidate is preselected. +- prompt: Always select the prompt. +- first: Select the first candidate, allow prompt selection. +- no-prompt: Like first, but forbid selection of the prompt entirely. +- directory: Like first, but select the prompt if it is a directory." + :type '(choice (const prompt) (const first) (const no-prompt) (const directory))) + +(defcustom vertico-scroll-margin 2 + "Number of lines at the top and bottom when scrolling. +The value should lie between 0 and vertico-count/2." + :type 'natnum) + +(defcustom vertico-resize resize-mini-windows + "How to resize the Vertico minibuffer window, see `resize-mini-windows'." + :type '(choice (const :tag "Fixed" nil) + (const :tag "Shrink and grow" t) + (const :tag "Grow-only" grow-only))) + +(defcustom vertico-cycle nil + "Enable cycling for `vertico-next' and `vertico-previous'." + :type 'boolean) + +(defcustom vertico-multiline + (cons #("↲" 0 1 (face vertico-multiline)) #("…" 0 1 (face vertico-multiline))) + "Replacements for multiline strings." + :type '(cons (string :tag "Newline") (string :tag "Truncation"))) + +(defcustom vertico-sort-function #'vertico-sort-history-length-alpha + "Default sorting function, used if no `display-sort-function' is specified." + :type `(choice + (const :tag "No sorting" nil) + (const :tag "By history, length and alpha" ,#'vertico-sort-history-length-alpha) + (const :tag "By history and alpha" ,#'vertico-sort-history-alpha) + (const :tag "By length and alpha" ,#'vertico-sort-length-alpha) + (const :tag "Alphabetically" ,#'vertico-sort-alpha) + (function :tag "Custom function"))) + +(defcustom vertico-sort-override-function nil + "Override sort function which overrides the `display-sort-function'." + :type '(choice (const nil) function)) + +(defgroup vertico-faces nil + "Faces used by Vertico." + :group 'vertico + :group 'faces) + +(defface vertico-multiline '((t :inherit shadow)) + "Face used to highlight multiline replacement characters.") + +(defface vertico-group-title '((t :inherit shadow :slant italic)) + "Face used for the title text of the candidate group headlines.") + +(defface vertico-group-separator '((t :inherit shadow :strike-through t)) + "Face used for the separator lines of the candidate groups.") + +(defface vertico-current '((t :inherit highlight :extend t)) + "Face used to highlight the currently selected candidate.") + +(defvar-keymap vertico-map + :doc "Vertico minibuffer keymap derived from `minibuffer-local-map'." + :parent minibuffer-local-map + "<remap> <beginning-of-buffer>" #'vertico-first + "<remap> <minibuffer-beginning-of-buffer>" #'vertico-first + "<remap> <end-of-buffer>" #'vertico-last + "<remap> <scroll-down-command>" #'vertico-scroll-down + "<remap> <scroll-up-command>" #'vertico-scroll-up + "<remap> <next-line>" #'vertico-next + "<remap> <previous-line>" #'vertico-previous + "<remap> <next-line-or-history-element>" #'vertico-next + "<remap> <previous-line-or-history-element>" #'vertico-previous + "<remap> <backward-paragraph>" #'vertico-previous-group + "<remap> <forward-paragraph>" #'vertico-next-group + "<remap> <exit-minibuffer>" #'vertico-exit + "<remap> <kill-ring-save>" #'vertico-save + "M-RET" #'vertico-exit-input + "TAB" #'vertico-insert) + +(defvar-local vertico--hilit #'identity + "Lazy candidate highlighting function.") + +(defvar-local vertico--history-hash nil + "History hash table and corresponding base string.") + +(defvar-local vertico--candidates-ov nil + "Overlay showing the candidates.") + +(defvar-local vertico--count-ov nil + "Overlay showing the number of candidates.") + +(defvar-local vertico--index -1 + "Index of current candidate or negative for prompt selection.") + +(defvar-local vertico--scroll 0 + "Scroll position.") + +(defvar-local vertico--input nil + "Cons of last minibuffer contents and point or t.") + +(defvar-local vertico--candidates nil + "List of candidates.") + +(defvar-local vertico--metadata nil + "Completion metadata.") + +(defvar-local vertico--base "" + "Base string, which is concatenated with the candidate.") + +(defvar-local vertico--total 0 + "Length of the candidate list `vertico--candidates'.") + +(defvar-local vertico--lock-candidate nil + "Lock-in current candidate.") + +(defvar-local vertico--lock-groups nil + "Lock-in current group order.") + +(defvar-local vertico--all-groups nil + "List of all group titles.") + +(defvar-local vertico--groups nil + "List of current group titles.") + +(defvar-local vertico--allow-prompt nil + "Prompt selection is allowed.") + +(defun vertico--history-hash () + "Recompute history hash table and return it." + (or (and (equal (car vertico--history-hash) vertico--base) (cdr vertico--history-hash)) + (let* ((base vertico--base) + (base-len (length base)) + (hist (and (not (eq minibuffer-history-variable t)) ;; Disabled for `t'. + (symbol-value minibuffer-history-variable))) + (hash (make-hash-table :test #'equal :size (length hist))) + (file-p (and (> base-len 0) ;; Step-wise completion, unlike `project-find-file' + (eq minibuffer-history-variable 'file-name-history))) + (curr-file (when-let ((win (and file-p (minibuffer-selected-window))) + (file (buffer-file-name (window-buffer win)))) + (abbreviate-file-name file)))) + (cl-loop for elem in hist for index from 0 do + (when (and (not (equal curr-file elem)) ;; Deprioritize current file + (or (= base-len 0) + (and (>= (length elem) base-len) + (eq t (compare-strings base 0 base-len elem 0 base-len))))) + (let ((file-sep (and file-p (string-search "/" elem base-len)))) + ;; Drop base string from history elements & special file handling. + (when (or (> base-len 0) file-sep) + (setq elem (substring elem base-len (and file-sep (1+ file-sep))))) + (unless (gethash elem hash) (puthash elem index hash))))) + (cdr (setq vertico--history-hash (cons base hash)))))) + +(defun vertico--length-string< (x y) + "Sorting predicate which compares X and Y first by length then by `string<'." + (or (< (length x) (length y)) (and (= (length x) (length y)) (string< x y)))) + +(defun vertico--sort-decorated (list) + "Sort decorated LIST and remove decorations." + (setq list (sort list #'car-less-than-car)) + (cl-loop for item on list do (setcar item (cdar item))) + list) + +(defmacro vertico--define-sort (by bsize bindex bpred pred) + "Generate optimized sorting function. +The function is configured by BY, BSIZE, BINDEX, BPRED and PRED." + `(defun ,(intern (mapconcat #'symbol-name `(vertico sort ,@by) "-")) (candidates) + ,(concat "Sort candidates by " (mapconcat #'symbol-name by ", ") ".") + (let* ((buckets (make-vector ,bsize nil)) + ,@(and (eq (car by) 'history) '((hhash (vertico--history-hash)) (hcands)))) + (dolist (% candidates) + ;; Find recent candidate in history or fill bucket + (,@(if (not (eq (car by) 'history)) `(progn) + `(if-let ((idx (gethash % hhash))) (push (cons idx %) hcands))) + (let ((idx (min ,(1- bsize) ,bindex))) + (aset buckets idx (cons % (aref buckets idx)))))) + (nconc ,@(and (eq (car by) 'history) '((vertico--sort-decorated hcands))) + (mapcan (lambda (bucket) (sort bucket #',bpred)) + (nbutlast (append buckets nil))) + ;; Last bucket needs special treatment + (sort (aref buckets ,(1- bsize)) #',pred))))) + +(vertico--define-sort (history length alpha) 32 (length %) string< vertico--length-string<) +(vertico--define-sort (history alpha) 32 (if (equal % "") 0 (/ (aref % 0) 4)) string< string<) +(vertico--define-sort (length alpha) 32 (length %) string< vertico--length-string<) +(vertico--define-sort (alpha) 32 (if (equal % "") 0 (/ (aref % 0) 4)) string< string<) + +(defun vertico--affixate (cands) + "Annotate CANDS with annotation function." + (if-let ((aff (vertico--metadata-get 'affixation-function))) + (funcall aff cands) + (if-let ((ann (vertico--metadata-get 'annotation-function))) + (cl-loop for cand in cands collect + (let ((suff (or (funcall ann cand) ""))) + ;; The default completion UI adds the `completions-annotations' + ;; face if no other faces are present. + (unless (text-property-not-all 0 (length suff) 'face nil suff) + (setq suff (propertize suff 'face 'completions-annotations))) + (list cand "" suff))) + (cl-loop for cand in cands collect (list cand "" ""))))) + +(defun vertico--move-to-front (elem list) + "Move ELEM to front of LIST." + (if-let ((found (member elem list))) ;; No duplicates, compare with Corfu. + (nconc (list (car found)) (delq (setcar found nil) list)) + list)) + +(defun vertico--filter-completions (&rest args) + "Compute all completions for ARGS with lazy highlighting." + (dlet ((completion-lazy-hilit t) (completion-lazy-hilit-fn nil)) + (static-if (>= emacs-major-version 30) + (cons (apply #'completion-all-completions args) completion-lazy-hilit-fn) + (cl-letf* ((orig-pcm (symbol-function #'completion-pcm--hilit-commonality)) + (orig-flex (symbol-function #'completion-flex-all-completions)) + ((symbol-function #'completion-flex-all-completions) + (lambda (&rest args) + ;; Unfortunately for flex we have to undo the lazy highlighting, since flex uses + ;; the completion-score for sorting, which is applied during highlighting. + (cl-letf (((symbol-function #'completion-pcm--hilit-commonality) orig-pcm)) + (apply orig-flex args)))) + ((symbol-function #'completion-pcm--hilit-commonality) + (lambda (pattern cands) + (setq completion-lazy-hilit-fn + (lambda (x) + ;; `completion-pcm--hilit-commonality' sometimes throws an internal error + ;; for example when entering "/sudo:://u". + (condition-case nil + (car (completion-pcm--hilit-commonality pattern (list x))) + (t x)))) + cands)) + ((symbol-function #'completion-hilit-commonality) + (lambda (cands prefix &optional base) + (setq completion-lazy-hilit-fn + (lambda (x) (car (completion-hilit-commonality (list x) prefix base)))) + (and cands (nconc cands base))))) + (cons (apply #'completion-all-completions args) completion-lazy-hilit-fn))))) + +(defun vertico--metadata-get (prop) + "Return PROP from completion metadata." + (compat-call completion-metadata-get vertico--metadata prop)) + +(defun vertico--sort-function () + "Return the sorting function." + (or vertico-sort-override-function + (vertico--metadata-get 'display-sort-function) + vertico-sort-function)) + +(defun vertico--recompute (pt content) + "Recompute state given PT and CONTENT." + (pcase-let* ((table minibuffer-completion-table) + (pred minibuffer-completion-predicate) + (before (substring content 0 pt)) + (after (substring content pt)) + ;; bug#47678: `completion-boundaries' fails for `partial-completion' + ;; if the cursor is moved before the slashes of "~//". + ;; See also corfu.el which has the same issue. + (bounds (condition-case nil + (completion-boundaries before table pred after) + (t (cons 0 (length after))))) + (field (substring content (car bounds) (+ pt (cdr bounds)))) + ;; `minibuffer-completing-file-name' has been obsoleted by the completion category + (completing-file (eq 'file (vertico--metadata-get 'category))) + (`(,all . ,hl) (vertico--filter-completions content table pred pt vertico--metadata)) + (base (or (when-let ((z (last all))) (prog1 (cdr z) (setcdr z nil))) 0)) + (vertico--base (substring content 0 base)) + (def (or (car-safe minibuffer-default) minibuffer-default)) + (groups) (def-missing) (lock)) + ;; Filter the ignored file extensions. We cannot use modified predicate for this filtering, + ;; since this breaks the special casing in the `completion-file-name-table' for `file-exists-p' + ;; and `file-directory-p'. + (when completing-file (setq all (completion-pcm--filename-try-filter all))) + ;; Sort using the `display-sort-function' or the Vertico sort functions + (setq all (delete-consecutive-dups (funcall (or (vertico--sort-function) #'identity) all))) + ;; Move special candidates: "field" appears at the top, before "field/", before default value + (when (stringp def) + (setq all (vertico--move-to-front def all))) + (when (and completing-file (not (string-suffix-p "/" field))) + (setq all (vertico--move-to-front (concat field "/") all))) + (setq all (vertico--move-to-front field all)) + (when-let ((fun (and all (vertico--metadata-get 'group-function)))) + (setq groups (vertico--group-by fun all) all (car groups))) + (setq def-missing (and def (equal content "") (not (member def all))) + lock (and vertico--lock-candidate ;; Locked position of old candidate. + (if (< vertico--index 0) -1 + (seq-position all (nth vertico--index vertico--candidates))))) + `((vertico--base . ,vertico--base) + (vertico--metadata . ,vertico--metadata) + (vertico--candidates . ,all) + (vertico--total . ,(length all)) + (vertico--hilit . ,(or hl #'identity)) + (vertico--allow-prompt . ,(and (not (eq vertico-preselect 'no-prompt)) + (or def-missing (eq vertico-preselect 'prompt) + (memq minibuffer--require-match + '(nil confirm confirm-after-completion))))) + (vertico--lock-candidate . ,lock) + (vertico--groups . ,(cadr groups)) + (vertico--all-groups . ,(or (caddr groups) vertico--all-groups)) + (vertico--index . ,(or lock + (if (or def-missing (eq vertico-preselect 'prompt) (not all) + (and completing-file (eq vertico-preselect 'directory) + (= (length vertico--base) (length content)) + (test-completion content table pred))) + -1 0)))))) + +(defun vertico--cycle (list n) + "Rotate LIST to position N." + (nconc (copy-sequence (nthcdr n list)) (seq-take list n))) + +(defun vertico--group-by (fun elems) + "Group ELEMS by FUN." + (let ((ht (make-hash-table :test #'equal)) titles groups) + ;; Build hash table of groups + (cl-loop for elem on elems + for title = (funcall fun (car elem) nil) do + (if-let ((group (gethash title ht))) + (setcdr group (setcdr (cdr group) elem)) ;; Append to tail of group + (puthash title (cons elem elem) ht) ;; New group element (head . tail) + (push title titles))) + (setq titles (nreverse titles)) + ;; Cycle groups if `vertico--lock-groups' is set + (when-let ((vertico--lock-groups) + (group (seq-find (lambda (group) (gethash group ht)) + vertico--all-groups))) + (setq titles (vertico--cycle titles (seq-position titles group)))) + ;; Build group list + (dolist (title titles) + (push (gethash title ht) groups)) + ;; Unlink last tail + (setcdr (cdar groups) nil) + (setq groups (nreverse groups)) + ;; Link groups + (let ((link groups)) + (while (cdr link) + (setcdr (cdar link) (caadr link)) + (pop link))) + ;; Check if new groups are found + (dolist (group vertico--all-groups) + (remhash group ht)) + (list (caar groups) titles + (if (hash-table-empty-p ht) vertico--all-groups titles)))) + +(defun vertico--remote-p (path) + "Return t if PATH is a remote path." + (string-match-p "\\`/[^/|:]+:" (substitute-in-file-name path))) + +(defun vertico--update (&optional interruptible) + "Update state, optionally INTERRUPTIBLE." + (let* ((pt (max 0 (- (point) (minibuffer-prompt-end)))) + (content (minibuffer-contents-no-properties)) + (input (cons content pt))) + (unless (or (and interruptible (input-pending-p)) (equal vertico--input input)) + ;; Redisplay to make input immediately visible before expensive candidate + ;; recomputation (gh:minad/vertico#89). No redisplay during init because + ;; of flicker. + (when (and interruptible (consp vertico--input)) + ;; Prevent recursive exhibit from timer (`consult-vertico--refresh'). + (cl-letf (((symbol-function #'vertico--exhibit) #'ignore)) (redisplay))) + (pcase (let ((vertico--metadata (completion-metadata (substring content 0 pt) + minibuffer-completion-table + minibuffer-completion-predicate))) + ;; If Tramp is used, do not compute the candidates in an + ;; interruptible fashion, since this will break the Tramp + ;; password and user name prompts (See gh:minad/vertico#23). + (if (or (not interruptible) + (and (eq 'file (vertico--metadata-get 'category)) + (or (vertico--remote-p content) (vertico--remote-p default-directory)))) + (vertico--recompute pt content) + (let ((non-essential t)) + (while-no-input (vertico--recompute pt content))))) + ('nil (abort-recursive-edit)) + ((and state (pred consp)) + (setq vertico--input input) + (dolist (s state) (set (car s) (cdr s)))))))) + +(defun vertico--display-string (str) + "Return display STR without display and invisible properties." + (let ((end (length str)) (pos 0) chunks) + (while (< pos end) + (let ((nextd (next-single-property-change pos 'display str end)) + (disp (get-text-property pos 'display str))) + (if (stringp disp) + (let ((face (get-text-property pos 'face str))) + (when face + (add-face-text-property 0 (length disp) face t (setq disp (concat disp)))) + (setq pos nextd chunks (cons disp chunks))) + (while (< pos nextd) + (let ((nexti (next-single-property-change pos 'invisible str nextd))) + (unless (or (get-text-property pos 'invisible str) + (and (= pos 0) (= nexti end))) ;; full string -> no allocation + (push (substring str pos nexti) chunks)) + (setq pos nexti)))))) + (if chunks (apply #'concat (nreverse chunks)) str))) + +(defun vertico--window-width () + "Return minimum width of windows, which display the minibuffer." + (cl-loop for win in (get-buffer-window-list) minimize (window-width win))) + +(defun vertico--truncate-multiline (str max) + "Truncate multiline STR to MAX." + (let ((pos 0) (res "")) + (while (and (< (length res) (* 2 max)) (string-match "\\(\\S-+\\)\\|\\s-+" str pos)) + (setq res (concat res (if (match-end 1) (match-string 0 str) + (if (string-search "\n" (match-string 0 str)) + (car vertico-multiline) " "))) + pos (match-end 0))) + (truncate-string-to-width (string-trim res) max 0 nil (cdr vertico-multiline)))) + +(defun vertico--compute-scroll () + "Compute new scroll position." + (let ((off (max (min vertico-scroll-margin (/ vertico-count 2)) 0)) + (corr (if (= vertico-scroll-margin (/ vertico-count 2)) (1- (mod vertico-count 2)) 0))) + (setq vertico--scroll (min (max 0 (- vertico--total vertico-count)) + (max 0 (+ vertico--index off 1 (- vertico-count)) + (min (- vertico--index off corr) vertico--scroll)))))) + +(defun vertico--format-group-title (title cand) + "Format group TITLE given the current CAND." + (when (string-prefix-p title cand) + ;; Highlight title if title is a prefix of the candidate + (setq cand (propertize cand 'face 'vertico-group-title) + title (substring (funcall vertico--hilit cand) 0 (length title))) + (vertico--remove-face 0 (length title) 'completions-first-difference title)) + (format (concat vertico-group-format "\n") title)) + +(defun vertico--format-count () + "Format the count string." + (format (car vertico-count-format) + (format (cdr vertico-count-format) + (cond ((>= vertico--index 0) (1+ vertico--index)) + (vertico--allow-prompt "*") + (t "!")) + vertico--total))) + +(defun vertico--display-count () + "Update count overlay `vertico--count-ov'." + (move-overlay vertico--count-ov (point-min) (point-min)) + (overlay-put vertico--count-ov 'before-string + (if vertico-count-format (vertico--format-count) ""))) + +(defun vertico--prompt-selection () + "Highlight the prompt if selected." + (let ((inhibit-modification-hooks t)) + (if (and (< vertico--index 0) vertico--allow-prompt) + (add-face-text-property (minibuffer-prompt-end) (point-max) 'vertico-current 'append) + (vertico--remove-face (minibuffer-prompt-end) (point-max) 'vertico-current)))) + +(defun vertico--remove-face (beg end face &optional obj) + "Remove FACE between BEG and END from OBJ." + (while (< beg end) + (let ((next (next-single-property-change beg 'face obj end))) + (when-let ((val (get-text-property beg 'face obj))) + (put-text-property beg next 'face (remq face (ensure-list val)) obj)) + (setq beg next)))) + +(defun vertico--exhibit () + "Exhibit completion UI." + (let ((buffer-undo-list t)) ;; Overlays affect point position and undo list! + (vertico--update 'interruptible) + (vertico--prompt-selection) + (vertico--display-count) + (vertico--display-candidates (vertico--arrange-candidates)))) + +(defun vertico--goto (index) + "Go to candidate with INDEX." + (setq vertico--index + (max (if (or vertico--allow-prompt (= 0 vertico--total)) -1 0) + (min index (1- vertico--total))) + vertico--lock-candidate (or (>= vertico--index 0) vertico--allow-prompt))) + +(defun vertico--candidate (&optional hl) + "Return current candidate string with optional highlighting if HL is non-nil." + (let ((content (substring (or (car-safe vertico--input) (minibuffer-contents-no-properties))))) + (cond + ((>= vertico--index 0) + (let ((cand (substring (nth vertico--index vertico--candidates)))) + ;; XXX Drop the completions-common-part face which is added by the + ;; `completion--twq-all' hack. This should better be fixed in Emacs + ;; itself, the corresponding code is already marked as fixme. + (vertico--remove-face 0 (length cand) 'completions-common-part cand) + (concat vertico--base (if hl (funcall vertico--hilit cand) cand)))) + ((and (equal content "") (or (car-safe minibuffer-default) minibuffer-default))) + (t content)))) + +(defun vertico--match-p (input) + "Return t if INPUT is a valid match." + (let ((rm minibuffer--require-match)) + (or (memq rm '(nil confirm-after-completion)) + (equal "" input) ;; Null completion, returns default value + (if (functionp rm) (funcall rm input) ;; Emacs 29 supports functions + (test-completion input minibuffer-completion-table minibuffer-completion-predicate)) + (if (eq rm 'confirm) (eq (ignore-errors (read-char "Confirm")) 13) + (minibuffer-message "Match required") nil)))) + +(cl-defgeneric vertico--format-candidate (cand prefix suffix index _start) + "Format CAND given PREFIX, SUFFIX and INDEX." + (setq cand (vertico--display-string (concat prefix cand suffix "\n"))) + (when (= index vertico--index) + (add-face-text-property 0 (length cand) 'vertico-current 'append cand)) + cand) + +(cl-defgeneric vertico--arrange-candidates () + "Arrange candidates." + (vertico--compute-scroll) + (let ((curr-line 0) lines) + ;; Compute group titles + (let* (title (index vertico--scroll) + (group-fun (and vertico-group-format (vertico--metadata-get 'group-function))) + (candidates + (vertico--affixate + (cl-loop repeat vertico-count for c in (nthcdr index vertico--candidates) + collect (funcall vertico--hilit (substring c)))))) + (pcase-dolist ((and cand `(,str . ,_)) candidates) + (when-let ((new-title (and group-fun (funcall group-fun str nil)))) + (unless (equal title new-title) + (setq title new-title) + (push (vertico--format-group-title title str) lines)) + (setcar cand (funcall group-fun str 'transform))) + (when (= index vertico--index) + (setq curr-line (length lines))) + (push (cons index cand) lines) + (cl-incf index))) + ;; Drop excess lines + (setq lines (nreverse lines)) + (cl-loop for count from (length lines) above vertico-count do + (if (< curr-line (/ count 2)) + (nbutlast lines) + (setq curr-line (1- curr-line) lines (cdr lines)))) + ;; Format candidates + (let ((max-width (- (vertico--window-width) 4)) start) + (cl-loop for line on lines do + (pcase (car line) + (`(,index ,cand ,prefix ,suffix) + (setq start (or start index)) + (when (string-search "\n" cand) + (setq cand (vertico--truncate-multiline cand max-width))) + (setcar line (vertico--format-candidate cand prefix suffix index start)))))) + lines)) + +(cl-defgeneric vertico--display-candidates (lines) + "Update candidates overlay `vertico--candidates-ov' with LINES." + (move-overlay vertico--candidates-ov (point-max) (point-max)) + (overlay-put vertico--candidates-ov 'after-string + (apply #'concat #(" " 0 1 (cursor t)) (and lines "\n") lines)) + (vertico--resize-window (length lines))) + +(cl-defgeneric vertico--resize-window (height) + "Resize active minibuffer window to HEIGHT." + (setq-local truncate-lines (< (point) (* 0.8 (vertico--window-width))) + resize-mini-windows 'grow-only + max-mini-window-height 1.0) + (unless truncate-lines (set-window-hscroll nil 0)) + (unless (frame-root-window-p (active-minibuffer-window)) + (unless vertico-resize (setq height (max height vertico-count))) + (let ((dp (- (max (cdr (window-text-pixel-size)) + (* (default-line-height) (1+ height))) + (window-pixel-height)))) + (when (or (and (> dp 0) (/= height 0)) + (and (< dp 0) (eq vertico-resize t))) + (window-resize nil dp nil nil 'pixelwise))))) + +(cl-defgeneric vertico--prepare () + "Ensure that the state is prepared before running the next command." + (when (and (symbolp this-command) (string-prefix-p "vertico-" (symbol-name this-command))) + (vertico--update))) + +(cl-defgeneric vertico--setup () + "Setup completion UI." + (setq-local scroll-margin 0 + vertico--input t + completion-auto-help nil + completion-show-inline-help nil + vertico--candidates-ov (make-overlay (point-max) (point-max) nil t t) + vertico--count-ov (make-overlay (point-min) (point-min) nil t t)) + (overlay-put vertico--count-ov 'priority 1) ;; For `minibuffer-depth-indicate-mode' + (use-local-map vertico-map) + (add-hook 'pre-command-hook #'vertico--prepare nil 'local) + (add-hook 'post-command-hook #'vertico--exhibit nil 'local)) + +(cl-defgeneric vertico--advice (&rest app) + "Advice for completion function, apply APP." + (minibuffer-with-setup-hook #'vertico--setup (apply app))) + +(defun vertico-first () + "Go to first candidate, or to the prompt when the first candidate is selected." + (interactive) + (vertico--goto (if (> vertico--index 0) 0 -1))) + +(defun vertico-last () + "Go to last candidate." + (interactive) + (vertico--goto (1- vertico--total))) + +(defun vertico-scroll-down (&optional n) + "Go back by N pages." + (interactive "p") + (vertico--goto (max 0 (- vertico--index (* (or n 1) vertico-count))))) + +(defun vertico-scroll-up (&optional n) + "Go forward by N pages." + (interactive "p") + (vertico-scroll-down (- (or n 1)))) + +(defun vertico-next (&optional n) + "Go forward N candidates." + (interactive "p") + (let ((index (+ vertico--index (or n 1)))) + (vertico--goto + (cond + ((not vertico-cycle) index) + ((= vertico--total 0) -1) + (vertico--allow-prompt (1- (mod (1+ index) (1+ vertico--total)))) + (t (mod index vertico--total)))))) + +(defun vertico-previous (&optional n) + "Go backward N candidates." + (interactive "p") + (vertico-next (- (or n 1)))) + +(defun vertico-exit (&optional arg) + "Exit minibuffer with current candidate or input if prefix ARG is given." + (interactive "P") + (when (and (not arg) (>= vertico--index 0)) + (vertico-insert)) + (when (vertico--match-p (minibuffer-contents-no-properties)) + (exit-minibuffer))) + +(defun vertico-next-group (&optional n) + "Cycle N groups forward. +When the prefix argument is 0, the group order is reset." + (interactive "p") + (when (cdr vertico--groups) + (if (setq vertico--lock-groups (not (eq n 0))) + (setq vertico--groups (vertico--cycle vertico--groups + (let ((len (length vertico--groups))) + (- len (mod (- (or n 1)) len)))) + vertico--all-groups (vertico--cycle vertico--all-groups + (seq-position vertico--all-groups + (car vertico--groups)))) + (setq vertico--groups nil + vertico--all-groups nil)) + (setq vertico--lock-candidate nil + vertico--input nil))) + +(defun vertico-previous-group (&optional n) + "Cycle N groups backward. +When the prefix argument is 0, the group order is reset." + (interactive "p") + (vertico-next-group (- (or n 1)))) + +(defun vertico-exit-input () + "Exit minibuffer with input." + (interactive) + (vertico-exit t)) + +(defun vertico-save () + "Save current candidate to kill ring." + (interactive) + (if (or (use-region-p) (not transient-mark-mode)) + (call-interactively #'kill-ring-save) + (kill-new (vertico--candidate)))) + +(defun vertico-insert () + "Insert current candidate in minibuffer." + (interactive) + ;; XXX There is a small bug here, depending on interpretation. When completing + ;; "~/emacs/master/li|/calc" where "|" is the cursor, then the returned + ;; candidate only includes the prefix "~/emacs/master/lisp/", but not the + ;; suffix "/calc". Default completion has the same problem when selecting in + ;; the *Completions* buffer. See bug#48356. + (when (> vertico--total 0) + (let ((vertico--index (max 0 vertico--index))) + (insert (prog1 (vertico--candidate) (delete-minibuffer-contents)))))) + +;;;###autoload +(define-minor-mode vertico-mode + "VERTical Interactive COmpletion." + :global t :group 'vertico + (dolist (fun '(completing-read-default completing-read-multiple)) + (if vertico-mode + (advice-add fun :around #'vertico--advice) + (advice-remove fun #'vertico--advice)))) + +(defun vertico--command-p (_sym buffer) + "Return non-nil if Vertico is active in BUFFER." + (buffer-local-value 'vertico--input buffer)) + +;; Do not show Vertico commands in M-X +(dolist (sym '(vertico-next vertico-next-group vertico-previous vertico-previous-group + vertico-scroll-down vertico-scroll-up vertico-exit vertico-insert + vertico-exit-input vertico-save vertico-first vertico-last + vertico-repeat-previous ;; autoloads in vertico-repeat.el + vertico-quick-jump vertico-quick-exit vertico-quick-insert ;; autoloads in vertico-quick.el + vertico-directory-up vertico-directory-enter ;; autoloads in vertico-directory.el + vertico-directory-delete-char vertico-directory-delete-word)) + (put sym 'completion-predicate #'vertico--command-p)) + +(provide 'vertico) +;;; vertico.el ends here