id
stringlengths
8
14
url
stringlengths
40
58
title
stringlengths
2
150
date_created
stringdate
2008-09-06 22:17:14
2024-03-31 23:12:03
text
stringlengths
149
7.14M
thread-66734
https://emacs.stackexchange.com/questions/66734
org-mode spreadsheet formula, can one use the result of org-babel block?
2021-07-18T15:23:17.797
# Question Title: org-mode spreadsheet formula, can one use the result of org-babel block? I'm trying to find a way to use the output of existing org-babel block in org-mode spreadsheet formulae without rewriting them in emacs-lisp. Is it possible? TBLFM line is pseudo code, it is syntactically invalid. ``` #+NAME: currencyRateOnDate #+BEGIN_SRC http :pretty :select .[0].rate GET https://bank.gov.ua/NBUStatService/v1/statdirectory/exchange?valcode=USD&date=${date}&json #+END_SRC | Name | Date | Currency rate | |------+----------+---------------| | Foo | 20210125 | | #+TBLFM: $3=currencyRateOnDate(date=$2) #+CALL: currencyRateOnDate(date="20210714") #+RESULTS: : 27.3216 ``` or alternatively, is it possible to wrap existing org-babel blocks(e.g. in http, ruby "languages") as emacs-lisp wrapped blocks(which could be easily called in org-mode spreadsheet formula)? # Answer After quite a bit of fighting trying to create a wrapper emacs-lisp function I found the `org-sbe` macro that solves this exact problem. To make it work, I've changed TBLFM definition to the following: ``` #+TBLFM: $3='(org-sbe "currencyRateOnDate" (date $2))' ``` org-sbe macro docs: > org-sbe org-sbe is a Lisp macro in \`ob-table.el'. > > (org-sbe SOURCE-BLOCK &rest VARIABLES) > > Return the results of calling SOURCE-BLOCK with VARIABLES. Each element of VARIABLES should be a two element list, whose first element is the name of the variable and second element is a string of its value. The following call to \`org-sbe' would be equivalent to the following source code block. > > (org-sbe 'source-block (n $2) (m 3)) > > #+begin\_src emacs-lisp :var results=source-block(n=val\_at\_col\_2, m=3) :results silent results #+end\_src > > NOTE: by default string variable names are interpreted as references to source-code blocks, to force interpretation of a cell's value as a string, prefix the identifier a "$" (e.g., "$$2" instead of "$2" or "$@2$2" instead of "@2$2"). > > NOTE: it is also possible to pass header arguments to the code block. In this case a table cell should hold the string value of the header argument which can then be passed before all variables as shown in the example below. > > | 1 | 2 | :file nothing.png | nothing.png | #+TBLFM: @1$4='(org-sbe test-sbe $3 (x $1) (y $2)) > 5 votes --- Tags: org-mode, org-babel ---
thread-66735
https://emacs.stackexchange.com/questions/66735
How to specify relative path to a file inside init.el
2021-07-18T15:36:02.047
# Question Title: How to specify relative path to a file inside init.el I have something like this inside my init file: ``` (when (file-readable-p "/absolute/path/to/config.org") (org-babel-load-file (expand-file-name "/absolute/path/to/config.org"))) ``` Where `config.org` is in the same directory as `init.el`. I want to be able to specify a relative path to `init.el` so that emacs can find the config file no matter where the init file is located on any device. However, when I tried `"./config.org"` that is interpreted relative to the directory where emacs is opened, not where `init.el` is located. How can I specify a path relative to `init.el`? I'm using emacs-28, if that matters. # Answer > 2 votes When your init file is loaded, the current directory, that is, the value of variable **`default-directory`**, is the directory where your init file is, by default. That is, that's the value unless your init file does something that changes `default-directory`. So you can just use the value of `default-directory`. For example if you use a function that accepts a file name without the directory part, then just use the file name without the directory part, and `default-directory` will be understood. Or if you use a function that needs an absolute file name, then use `expand-file-name` without specifying optional arg `DEFAULT-DIRECTORY` (or passing it as `nil`). E.g.: ``` (when (file-readable-p "config.org") (org-babel-load-file (expand-file-name "config.org"))) ``` which is the same as: ``` (when (file-readable-p (expand-file-name "config.org")) (org-babel-load-file (expand-file-name "config.org"))) ``` which is the same as: ``` (when (file-readable-p (expand-file-name "config.org" default-directory)) (org-babel-load-file (expand-file-name "config.org" default-directory))) ``` --- Tags: init-file, filenames ---
thread-66744
https://emacs.stackexchange.com/questions/66744
How to prevent copy-directory from choking on Unix socket files?
2021-07-19T04:29:37.833
# Question Title: How to prevent copy-directory from choking on Unix socket files? I need to copy a directory tree that holds Unix socket files somewhere inside. As Unix sockets cannot be copied, when I use `copy-directory`, the `copy-file` function used by `copy-directory` throws an error because it cannot copy the Unix socket file. In an attempt to resolve that problem I wrote a advice for `copy-file`, called `copy-only-file` that copies only files, and skip Unix sockets: ``` (defun copy-only-file (file newname &optional ok-if-already-exists keep-time preserve-uid-gid preserve-permissions) "Copy files but not Unix sockets." (unless (unix-socket-p file) (copy-file file newname ok-if-already-exists keep-time preserve-uid-gid preserve-permissions))) ``` Then later, inside another function, the code sets up the advice temporarily to copy the directory tree: ``` ;; inside some function... (advice-add 'copy-file :override #'copy-only-file) (copy-directory (directory-file-name source-dirpath) (directory-file-name destination-dirpath)) (advice-remove 'copy-file #'copy-only-file) ``` This being a recursive call, running the code causes too many recursions and the code eventually fails with the error **(error Lisp nesting exceeds ‘max-lisp-eval-depth’)** I thought of using a `:before` advice to filter out files that would be Unix socket files, but then is it possible to *not* call the function being advised when some criteria is met? Or would I have to pass the same file to the FILE and NEWFILE argument of `copy-file` so that no copy is done because OK-IF-ALREADY-EXISTS would be nil? I have also thought about re-defining the function using defalias to keep access to the original `copy-file`: ``` (defalias 'original-copy-file #'copy-file) (defun copy-file (file newname &optional ok-if-already-exists keep-time preserve-uid-gid preserve-permissions) "Copy files but not Unix sockets." (unless (socket-p file) (original-copy-file file newname ok-if-already-exists keep-time preserve-uid-gid preserve-permissions))) ``` That seems to work, but is it guaranteed to always work? It feels like a kludge to me. And I'm not clear on how I would restore the original `copy-file`. What is the proper way to handle this type of scenario? # Answer > 1 votes `:override` replaces the advised function with your own function, so when your function tries to call the original it is actually calling itself. I recommend using `:around` advice instead. ``` (defun copy-only-file (original-copy-file file &rest args) "Copy files but not Unix sockets." (unless (unix-socket-p file) (apply original-copy-file file args))) ``` Then to add the advice run `(advice-add 'copy-file :around #'copy-only-file)` See chapter 13.11.3 Ways to compose advice in the Elisp manual for all the different ways to compose advice. --- Tags: files, advice, nadvice, socket ---
thread-66743
https://emacs.stackexchange.com/questions/66743
Delete all non-word characters between two words
2021-07-19T01:34:43.017
# Question Title: Delete all non-word characters between two words I am often in a situation where there are two words with a bunch of symbols in between like this: ``` word1|); }; } word2 ``` Now I'd like to delete those symbols + whitespace between the words and maybe replace them with a single space, depending on what I want to do afterwards. This should work similar to `M-\` and `C-SPC` but for non-word characters other than whitespace too: ``` word1| word2 ``` `M-d` does delete those symbols but it also deletes the word behind them which I don't want: ``` word1| ``` `C-SPC M-f M-b C-w` technically works but is cumbersome. Bonus: Sometimes I also only want to delete one set of symbols (separated by whitespace): ``` word1| }; } word2 ``` In all of these cases I usually revert to using evil-mode with its definition of a word and delete operation but I'd like to have a pure emacs solution in my toolbelt too. # Answer Select the region where you want this occur, and ``` M-x query-replace-regexp \W+ RET <space> ``` C-M % \W+ RET ## Other solution : Evaluate and save in your init file : ``` (defun removes-all-no-letter () "Removes any non-alphabetic character around the point or following the current word. Insert a space char instead." (interactive) (while (looking-at-p "\\w") (forward-char)) (while (looking-at-p "\\W") (backward-char)) (forward-char) (while (looking-at-p "\\W") (delete-char 1)) (insert " ")) (bind-key "C-c u" #'removes-all-no-letter) ``` I arbitrarely bind the function to C-c u, The choice is yours. > 3 votes --- Tags: deletion ---
thread-66739
https://emacs.stackexchange.com/questions/66739
Emacs >27.1: How to highlight in different colors for variables inside `fstring` in python-mode
2021-07-18T18:42:40.243
# Question Title: Emacs >27.1: How to highlight in different colors for variables inside `fstring` in python-mode I am using `python-mode` which colors the parameters. When I concatinate strings the variable color is represented as different: On the other hand, if I use `fstring`, the variable is not represented as different color: Please note that, if I enter non-existing variable, `python-mode` detects it: **\[Q\]** Is there any way to give a color to variables inside a `fstring` in `python-mode` for Emacs version `>27.1`? --- Related answer for Emacs `<27.1`: https://emacs.stackexchange.com/a/55186/18414 When I apply it, it messes up all the original coloring in `Python-mode`. Everything becomes white except strings. # Answer I am using this: ``` (if (version< "27.0" emacs-version) (setq python-font-lock-keywords-maximum-decoration (append python-font-lock-keywords-maximum-decoration '(("f\\(['\"]\\{1,3\\}\\)\\(.+?\\)\\1" ("{[^}]*?}" (progn (goto-char (match-beginning 0)) (match-end 0)) (goto-char (match-end 0)) (0 font-lock-variable-name-face t))))))) ``` > 1 votes --- Tags: python, faces, font-lock, syntax-highlighting ---
thread-66386
https://emacs.stackexchange.com/questions/66386
Org-capture template containing a date relative to when an email was received
2021-06-19T11:16:16.203
# Question Title: Org-capture template containing a date relative to when an email was received As the title describes, I want to be able to create an org-capture template which allows me to specify a relative date (say, 2 days) from when an email was received and print it out. The solution below uses the current date and so does not work. The alternative would be to use the available org-capture template `%:date-timestamp` or similar but that does not allow me to specify a date relative to when it was received (as far as I know). Thank you in advance for any help. ``` (setq org-capture-templates ("c" "Client-email" item (file+headline "~/org/NOTES.org" "Client reply queue") "- [ ] [[mu4e:msgid:%:message-id][%:fromname]] DEADLINE: %(org-insert-time-stamp (org-read-date nil t \"+2d\"))")) ``` # Answer > 1 votes One can use one `org-read` to read the date from the mail and another one to increment the number of days as you wish. The following replacement of the relevant snippet of code does work for me: ``` %(org-insert-time-stamp (org-read-date nil t \"++2d\" nil (org-read-date nil t \"%:date\"))) ``` --- Tags: org-mode, mu4e, org-capture, time-date ---
thread-32648
https://emacs.stackexchange.com/questions/32648
In org mode, how do I reference a figure?
2017-05-07T19:59:11.063
# Question Title: In org mode, how do I reference a figure? I have a figure declared like this: ``` #+CAPTION: Google NGrams Viewer Search #+NAME: fig:ngrams [[file:ngrams.png]] ``` And I'd like to reference it, so that I can write, e.g. `Please refer to Figure [[some magic thing here]]` and have it output `Please refer to Figure 1`. I'm using pandoc to convert from .org to .pdf. I've been trying writing `[[fig:ngrams]]`, as in `Please refer to Figure [[fig:ngrams]]`, but neither Pandoc nor pandoc-citeproc seem to understand that kind of link, and they transform it to `Please refer to Figure fig:ngrams`. # Answer > 9 votes There is another way to reference figures, by using `#+NAME:` before the figure. For example: ``` #+CAPTION: Example of the process #+NAME: fig:theprocess [[./Images/process.png]] ``` And later in the place where you need the reference, you add an internal link: ``` And as can be seen in figure [[fig:theprocess]], the process... ``` This works nicely with latex export. # Answer > 11 votes Figured it out myself. Turns out with the latest pandoc and pandoc-crossref you can do this: ``` #+CAPTION: Google NGrams Viewer Searches #+LABEL: fig:ngrams [[file:ngrams.png]] ``` Then: `Please refer to [cite:@fig:ngrams].` # Answer > 9 votes You can also use org-ref. Then you can use ref:ngrams to reference a figure. This works well with LaTeX export. It probably works with pandoc too. --- Tags: org-mode, pandoc ---
thread-15009
https://emacs.stackexchange.com/questions/15009
Delete files to Trash on OS X
2015-08-24T15:37:45.400
# Question Title: Delete files to Trash on OS X Is there a best, most future-proof method of setting emacs on OS X to delete files to the trash? I tried the instructions here: ``` (setq delete-by-moving-to-trash t) (defun system-move-file-to-trash (file) "Use \"trash\" to move FILE to the system trash. When using Homebrew, install it using \"brew install trash\"." (call-process (executable-find "trash") nil 0 nil file)) ``` but they don't work: ``` Trashing... (wrong-type-argument stringp nil) ``` Also, it feels wrong to have to install a separate program in order for Emacs to be able to trash files. Furthermore, I won't remember to install the "trash" program the next time I do a clean OS X install. Update: I added this to my .emacs and removed the call to `trash` and it seems to work. I wonder why Emacs on OSX defaults to the FreeDesktop `~/.local/share/Trash` location. ``` (setq trash-directory "~/.Trash") ``` # Answer The following is required: ``` (setq delete-by-moving-to-trash t) (setq trash-directory "~/.Trash") ``` The function `move-file-to-trash` has three tests: **(1)** whether `trash-directory` is defined; **(2)** whether `(fboundp 'system-move-file-to-trash)`; and, **(3)** `(t . . .` the *catch-all* that uses `~/.local/share...` The *second* test always fails on OSX 10.6.8 when built with the standard option of `--with-ns`. I don't have access at the moment to other versions of OSX. > 9 votes # Answer Define the function `system-move-file-to-trash` in this way should be enough: ``` (defun system-move-file-to-trash (file) (call-process "trash" nil nil nil file)) ``` if you don't have `trash` installed, Emacs will tell you. then, don't set the variable `trash-directory` since `trash` does that for you. About Emacs's trash behavior: > move-file-to-trash is an interactive compiled Lisp function in ‘files.el’. > > (move-file-to-trash FILENAME) > > Move the file (or directory) named FILENAME to the trash. When ‘delete-by-moving-to-trash’ is non-nil, this function is called by ‘delete-file’ and ‘delete-directory’ instead of deleting files outright. > > If the function ‘system-move-file-to-trash’ is defined, call it with FILENAME as an argument. Otherwise, if ‘trash-directory’ is non-nil, move FILENAME to that directory. Otherwise, trash FILENAME using the freedesktop.org conventions, like the GNOME, KDE and XFCE desktop environments. Emacs only moves files to "home trash", ignoring per-volume trashcans. I guess `(setq trash-directory "~/.Trash")` is not working: Finder will not be able to recover these files since it (at least) doesn't know where these files come from. > 4 votes # Answer I've been using the osx-trash package. It works with or without the `trash` command line utility, and integrates properly with the macOS Trash directory. > 3 votes # Answer According to my investigation (on MacOS 10.14 with Emacs 28.0.50). ### For those, who DON'T really need `"Put Back"` feature It's enough to configure: ``` (setq delete-by-moving-to-trash t) (if (eq system-type 'darwin) (setq trash-directory "~/.Trash")) ``` `delete-by-moving-to-trash` is available/updated since `Emacs 23.1`. `trash-directory` is available/updated since `Emacs 23.2`. So this is expected to be a working solution for many (or majority) of `MacOS` `Emacs` users. ### For those who DO want to use `"Put Back"` feature The issue is not something specific to `Emacs` app only. On `MacOS`, `"Put Back"` feature is enabled only for those files that were deleted by `Finder`. (At least it used to be so and works this way on my system too.) Possible workarounds: * Use the package osx-trash (with/out `brew install trash`). * `brew install trash` and call `trash -F` command from an init-file. Examples to base the solution on: osx-trash package code or EmacsWiki. * Do not install `trash` library, but call `Finder` with an `Applescript`. Examples to base the solution on: osx-trash package code again or use ns-do-applescript. * Use Emacs Mac port that more fully integrates `Emacs` into `MacOS`. There's a Homebrew adaptation of this package. * Implement in `Emacs` core. (That's a bit separate topic, so I'm just mentioning the possibility.) > 0 votes --- Tags: osx, deletion ---
thread-66728
https://emacs.stackexchange.com/questions/66728
How to filter search results by path pattern?
2021-07-17T12:12:21.630
# Question Title: How to filter search results by path pattern? I'm using Projectile with ripgrep. I can search project lines by some pattern, as an example: `test 42` will match strings like this `so, test is not 42 at all` I would like to be able to add additional pattern to the search string which would take all search results and display only those containing pattern in file path, like this: `test 42 | app migrations` will match results like this src/**app**/lib/**migrations**/file.txt: so, **test** is not **42** at all Example: I want to search word "text" in all project files containing "test\_dir" in any place within file path relative to project's root # Answer EDIT A very basic code example to achieve fuzzy search using a single grep would be: ``` (defun custom-counsel-function (str) (or (ivy-more-chars) (progn (let ((str (split-string str))) (counsel--async-command (format "rg --max-columns 240 --with-filename --no-heading --line-number --color never '%s' | grep %s" (car str) (cadr str)))) '("" "working...")))) ;;;###autoload (defun custom-counsel (&optional initial-input) "Call the \"locate\" shell command. INITIAL-INPUT can be given as the initial minibuffer input." (interactive) (let ((default-directory (read-directory-name "Start search from directory: "))) (ivy-read "Ripgrep: " #'custom-counsel-function :initial-input initial-input :dynamic-collection t :history 'counsel-locate-history :action (lambda (file) (with-ivy-window (when file (find-file file)))) :unwind #'counsel-delete-process :caller 'counsel-locate))) ``` The `rg` and `grep` patterns can be entered by separating them using a single space. For sure there are nicer ways to achieve this, but it takes some more time to inspect the Ivy (or any other completion framework) API. END EDIT From `M-x man` `rg` we find that this can be achieved using the `-g` flag. Now neither `projectile-ripgrep` nor the `ripgrep-regexp` command allow you to pass arguments to `rg` when called interactively (you can look at their definitions to see how they work). However, `counsel-rg` of the swiper/Ivy package does allow for passing arguments, and an example of how to use it is given in its docstring (and probably there exist helm and possibly consult alternatives for this also). For filtering on directory paths, be sure to read well the documentation after `-g` in `rg`'s `man`-page. For example, to filter for files that are located in some-path `dir-example/file.ext` relative from your initial search directory, you could search for the following: `ripgrep-pattern -- -g dir*/*` > 2 votes --- Tags: search, projectile, grep, ripgrep ---
thread-66762
https://emacs.stackexchange.com/questions/66762
Hiding certain directories in the recentf list
2021-07-20T12:04:25.560
# Question Title: Hiding certain directories in the recentf list After every OCaml programming session, my recentf list is polluted with directories such as ``` /private/var/folders/jn/l00kvy6n15s3slnk5khz1gh00000gn/T/ocamlformatbldUeV.ml /private/var/folders/jn/l00kvy6n15s3slnk5khz1gh00000gn/T/ocamlformatpSSLHo.ml ``` generated by `ocamlformat`. I want these to be hidden from the list, by blacklisting `/private/var/folders/`. How can I achieve this? I have looked up functions starting with `recentf-`, but `recentf` seems to not provide any functions to do this. # Answer > 2 votes Evaluate : ``` (add-to-list 'recentf-exclude "/private/var/folders/.*") ``` To activate it permanently, save it in your init file (`.emacs` or `.emacs.d/init.el`). --- Tags: recentf ---
thread-66765
https://emacs.stackexchange.com/questions/66765
How to insert an org-deadline from lisp with a warning period?
2021-07-20T14:37:28.863
# Question Title: How to insert an org-deadline from lisp with a warning period? The org documentation tells us that we can use special syntax for a deadline to have a warning period: > You can specify a different lead time for warnings for a specific deadlines using the following syntax. Here is an example with a warning period of 5 days ‘DEADLINE: \<2004-02-29 Sun -5d\>’. This warning is deactivated if the task gets scheduled and you set org-agenda-skip-deadline-prewarning-if-scheduled to t. This is also supported by Orgzly, where I want to use it. I'd assume that I could call `org-deadline` with this syntax but it just throws out the warning period: ``` (org-deadline nil "<2021-07-20 Tue -1d>") ;; => DEADLINE: <2021-07-20 Tue> ``` The documentation of `org-deadline` says > With two universal prefix arguments, prompt for a warning delay. But this doesn't help me since I don't want to call interactively. Since my entries get automatically updated by calendar sync I also have the requirement that the previous *DEADLINE:* entry has to get removed in this case, which is automatically handled by `org-deadline`. I assume I could handle this with `org-remove-timestamp-with-keyword` but I'm not sure which function to use for timestamp insertion if `org-deadline` doesn't support the warning period syntax. How do I insert a deadline from elisp with a warning period? # Answer > 1 votes Per NickD's comment this may well be a bug. In the meantime, it looks like this does what you're aiming for (or at least points you in the right direction): ``` (defun dunne//add-deadline-warning (w) (save-excursion (org-back-to-heading t) (let* ((regexp org-deadline-time-regexp)) (if (not (re-search-forward regexp (line-end-position 2) t)) (user-error "No deadline information to update") (let* ((rpl0 (match-string 1)) (rpl (replace-regexp-in-string " -[0-9]+[hdwmy]" "" rpl0))) (replace-match (concat org-deadline-string " <" rpl (format " -%dd" w) ">") t t)))))) (defun dunne//add-deadline-with-warning (w) (org-deadline nil) (dunne//add-deadline-warning w)) ``` I mined the contents of `dunne//add-deadline-warning` from the two-prefix case in `org--deadline-or-schedule` and ripped out the logic to handle existing deadlines / allow selecting a warning date. --- Tags: org-mode, org-agenda, deadline, timestamped ---
thread-66769
https://emacs.stackexchange.com/questions/66769
How to uncomment multiple expressions in Lisp code?
2021-07-20T19:57:47.967
# Question Title: How to uncomment multiple expressions in Lisp code? I am using Emacs, Slime, Paredit, and other packages to work on Common Lisp (SBCL). It is really useful to comment out multiple expressions while debugging. For instance, suppose I have these placeholder expressions: ``` ( ( ) ( (( ) ( ( ) )))) ``` I can use the keybinding `C-M-SPC` which run's the command `mark-sexp` on the second line. This character `-!-` will be used to represent the cursor position. ``` ( ( ) -!-( (( ) ( ( ) )))) ``` After invoking selecting the region, I can use the command `comment-dwin` to comment the appropriate expressions. Then, Emacs automatically does (using ParEdit): ``` ( ( ) -!-;; ( ;; (( ) ;; ( ( ) ;; ))) ) ``` This is great. I just need to learn how to revert this after some editions inside the content of the expressions. Since there were other modifications, I cannot use `undo`. So, how can I remove the `;;` comments in a smart way? A friend mentioned something like `rectangle-select` but I could not find it. # Answer In emacs, `comment-dwim` (bound to `M-;`) is its own inverse (AKA, *involution*): > Insert or realign comment on current line; if the region is active, comment or uncomment the region instead I.e., to uncomment the commented region, select and activate the region and hit `M-;`. If you want to avoid activating the region, `C-u M-x comment-region RET` will un-comment it. PS1. Rectangle operations are documented in the manual: `C-h i m Emacs RET m Rectangles RET`. PS2. See also https://stackoverflow.com/a/65649128/850781 for commenting parts of code. > 3 votes --- Tags: comment ---
thread-66767
https://emacs.stackexchange.com/questions/66767
Magit becomes very slow in spacemacs
2021-07-20T15:08:18.247
# Question Title: Magit becomes very slow in spacemacs I am a on and off spacemacs user for a long time but I have recently started working on some bigger projects and so I started investing some more time into improving my workflow and in particular I have started using the git layer to get some neat magit commands which are much more convenient than running everything in command line. However I have a problem when I use magit: at startup everything works fine but the more I use it the more every command starts taking time until it becomes practically unusable. When I reach this point, I can restart emacs and it starts working quickly again for a while, but soon enough the problem comes back. I am running everything on ubuntu 20.04 and I haven't been able to find anything online about this problem. It seems like magit and helm combine badly on windows leading to slow behavior, so I tried with the ivy layer instead of helm, but that did not solve it. Here is what the profiler looks like, when i tried to stage a hunk in the project, after having kept emacs running for some time: ``` - command-execute 21876 81% - call-interactively 21876 81% - funcall-interactively 21876 81% - magit-stage 19915 74% - magit-apply-hunk 19915 74% - magit-apply-patch 19915 74% - magit-refresh 19899 74% - magit-refresh-buffer 19899 74% - apply 19875 74% - magit-status-refresh-buffer 19819 74% - magit-run-section-hook 19810 73% - apply 19810 73% - magit-insert-unpushed-to-upstream-or-recent 19006 70% - magit-insert-unpushed-to-upstream 19006 70% - magit-insert-log 18991 70% - magit-git-wash 18991 70% + #<compiled 0x1d3fb1d> 18986 70% + magit-git-insert 5 0% magit-log-insert-child-count 4 0% + magit-insert-unpulled-from-upstream 436 1% + magit-insert-unstaged-changes 168 0% + magit-insert-stashes 76 0% + magit-insert-status-headers 62 0% + magit-insert-staged-changes 62 0% + magit-section-show 9 0% + magit-section-goto-successor 56 0% + magit-run-git-with-input 16 0% + spacemacs/helm-M-x-fuzzy-matching 1244 4% + magit-next-line 384 1% + magit-previous-line 329 1% + magit-section-toggle 4 0% + magit-todos--async-when-done 4584 17% + redisplay_internal (C function) 130 0% + global-hl-line-highlight 78 0% + timer-event-handler 45 0% + ... 30 0% + magit-section-update-highlight 20 0% evil--jump-hook 4 0% + winner-save-old-configurations 3 0% + evil-repeat-post-hook 2 0% ``` Apparently the problem is with the `compiled command` which I have no idea what it is. Maybe it is worth mentioning that the project I am working on is pretty big (~100 branches and as many tags) albeit only a few of them are actually present locally. I also have an almost vanilla configuration of spacemacs, with only various layers installed but almost no custom settings, I am just loading the custom emacs mode for contributing to the software frama-c (file frama-c-recommended.el at the following address) Why does it becomes so slow, and how to fix that? EDIT: I didn't see that I could explore the `compiled` item, so here is more complete result of the profiler ``` - command-execute 21876 81% - call-interactively 21876 81% - funcall-interactively 21876 81% - magit-stage 19915 74% - magit-apply-hunk 19915 74% - magit-apply-patch 19915 74% - magit-refresh 19899 74% - magit-refresh-buffer 19899 74% - apply 19875 74% - magit-status-refresh-buffer 19819 74% - magit-run-section-hook 19810 73% - apply 19810 73% - magit-insert-unpushed-to-upstream-or-recent 19006 70% - magit-insert-unpushed-to-upstream 19006 70% - magit-insert-log 18991 70% - magit-git-wash 18991 70% - #<compiled 0x1d3fb1d> 18986 70% - apply 18986 70% - magit-log-wash-log 18986 70% - magit-wash-sequence 18986 70% - #<compiled 0x1957ab9> 18986 70% - apply 18986 70% - magit-log-wash-rev 15956 59% - jit-lock-after-change 6011 22% - run-hook-with-args 6003 22% font-lock-extend-jit-lock-region-after-change 2984 11% - put-text-property 3008 11% - jit-lock-after-change 3000 11% - run-hook-with-args 3000 11% font-lock-extend-jit-lock-region-after-change 1552 5% - magit-delete-line 2325 8% - jit-lock-after-change 2189 8% - run-hook-with-args 2189 8% font-lock-extend-jit-lock-region-after-change 1461 5% magit-format-ref-labels 20 0% + magit-section 16 0% + run-hook-with-args-until-success 12 0% + eieio-oref 12 0% + magit-insert-child-count 8 0% + eieio-oset 4 0% + magit-log-format-margin 4 0% + magit-git-insert 5 0% magit-log-insert-child-count 4 0% + magit-insert-unpulled-from-upstream 436 1% + magit-insert-unstaged-changes 168 0% + magit-insert-stashes 76 0% + magit-insert-status-headers 62 0% + magit-insert-staged-changes 62 0% + magit-section-show 9 0% + magit-section-goto-successor 56 0% + magit-run-git-with-input 16 0% + spacemacs/helm-M-x-fuzzy-matching 1244 4% + magit-next-line 384 1% + magit-previous-line 329 1% + magit-section-toggle 4 0% + magit-todos--async-when-done 4584 17% + redisplay_internal (C function) 130 0% + global-hl-line-highlight 78 0% + timer-event-handler 45 0% + ... 30 0% + magit-section-update-highlight 20 0% evil--jump-hook 4 0% + winner-save-old-configurations 3 0% + evil-repeat-post-hook 2 0% ``` # Answer > 3 votes I'm not Magit guy. But looks you need avoid calling `magit-refresh`. The easiest way is to turn on `magit-inhibit-refresh`. Here is definition of `magit-apply-patch`, Disable `magit-refresh` inside `magit-apply-patch` temporarily, ``` (defun my-magit-apply-patch-hack (orig-func &rest args) (let* ((magit-inhibit-refresh t)) (apply orig-func args))) (advice-add 'magit-apply-patch :around #'my-magit-apply-patch-hack) ``` Or you can advice the caller of `magit-apply-patch`. Similar to the above code. Or you can toggle the flag globally by `M-x my-toggle-magit-refresh`, ``` (defun my-toggle-magit-fresh () "Toggle magit refresh flag." (interactive) (setq magit-inhibit-refresh (not magit-inhibit-refresh)) (message "magit-inhibit-refresh=%s" magit-inhibit-refresh)) ``` --- Tags: spacemacs, magit, helm ---
thread-44192
https://emacs.stackexchange.com/questions/44192
How to unhighlight after searching in evil mode?
2018-08-19T15:41:14.233
# Question Title: How to unhighlight after searching in evil mode? I have a text file opened in Spacemacs with evil mode on. When I search for a term by means of `/term` `[Enter]` then found "term"s are highlighed. How do I remove that highlighting? I tried `/` `[Enter]` \- that didn't work. The highlighting will stick around even after switching to insert mode. # Answer You can achieve the same as entering `:noh` with the command `evil-ex-nohighlight`. But since you are using spacemacs, it can be even simpler: hit `SPC s c` to clear highlights. > 14 votes # Answer Do it just like you would do in Vim (I've checked, `/ RET` doesn't work with `:set hlsearch`), use `:noh`. > 4 votes # Answer With the idea that @EFLS mentioned, I added these lines to my `.spacemacs` file: ``` (defun dotspacemacs/init () (setq-default ;; ... your other settings ;; ---------------------------------- ;; don't hightlight search / results evil-ex-substitute-highlight-all nil evil-ex-search-persistent-highlight nil ;; ---------------------------------- ;; ... your other settings )) ``` > 0 votes --- Tags: spacemacs, evil ---
thread-42277
https://emacs.stackexchange.com/questions/42277
link to a given page of an epub file from org mode
2018-06-26T21:30:05.580
# Question Title: link to a given page of an epub file from org mode Is it possible to make a link from org mode to a given page or section of an epub file (epub warp) ? I know that with "pdfview:./filename.pdf::6" we can have access to the page 6 of the pdf file. So I tried "file:filename.epub": it opens the epub file in another buffer. But it opens it at the index section. How to specify the page/section to open? I tried something like "file:filename.epub::num\_in\_the\_epub\_file.xhtml#ch3" or several variations around that but it does not work. I also tried M-x org-store-link / M-x org-insert-link but it seems that it does not work with epub file... Any ideas? Thanks by advance # Answer > 1 votes Using `nov.el`, `C-c``l` (`org-store-link`) at point in epub file + `C-c``C-l` (`org-insert-link`) at point where link is needed worked for me. The resultant link would look something like this: ``` [[nov:~/Calibre Library/Sonke Ahrens/How to Take Smart Notes_ One Simple Technique to Boost Writing, Learning and Thinking - for Stud (29)/How to Take Smart Notes_ One Simple Techni - Sonke Ahrens.epub::7:16535][link]] ``` --- Tags: org-mode ---
thread-66694
https://emacs.stackexchange.com/questions/66694
mu4e smart refiling to variable maildir
2021-07-14T10:33:58.703
# Question Title: mu4e smart refiling to variable maildir Mu4e documentation has an example of smart refiling, whereby you can choose which maildir to refile an email based on the properties of that email. I'd like to do that, except the destination maildir's name is a property of the email (specifically the :to property). Probably easiest to explain in an example. In the documentation: ``` (setq mu4e-refile-folder (lambda (msg) (cond ;; messages to the mu mailing list go to the /mu folder ((mu4e-message-contact-field-matches msg :to "mu-discuss@googlegroups.com") "/mu") ;; ........[ SNIP ] ))) ``` In this example all emails to a googlegroups `mu-discuss@googlegroups.com` end up in the `/mu` maildir. I'd like to go one further. I'd like `%anything%@googlegroups.com` to go to the maildir `/googlegroups/%anything%`, for any value of `%anything%`. # Answer Wow, what a ride into the world of elisp. I think I got it so that it works, well enough for my modest needs anyway (don't care about cross-posting, case differences etc). As with most things, you get more responses on SE by posting code than with an open-ended question such as I did originally, and I am happy to improve upon this snippet with suggestions. This really is my first non-toy function I've ever created in elisp. Massive props to the creators or mu4e and s.el. Both these packages are beautifully documented and made the learning experience a heck of a lot more pleasant. You will need the s.el package for `s-suffix?`, `s-downcase` (not that it's strictly needed), and `s-chop-suffix` ``` (defun personal/refile-maildir (msg) "Refile based on a message's characteristics" (let* ((to-addresses (mu4e-message-field msg :to)) (maillist-addr (cl-find-if (lambda (to) (s-suffix? "@googlegroups.com" (cdr to))) to-addresses))) (cond (maillist-addr (concat "/googlegroups." (s-chop-suffix "@googlegroups.com" (s-downcase (cdr maillist-addr))))) (t "/Archive")))) ``` Guaranteed there are cuter answers out there so I will not mark this question as solved for a while, in case anyone wants to chip in with a better solution. > 0 votes --- Tags: mu4e ---
thread-66784
https://emacs.stackexchange.com/questions/66784
Emacs icons not appearing as expected
2021-07-21T20:28:34.290
# Question Title: Emacs icons not appearing as expected I am having some issue implementing a custom eshell prompt found here but I am having issue with icons. For some reason, I have not been able to get any of the icons using the unicode provided, most of them are blank. The *faicon folder* is showing a `|` character instead of the `folder-o` icon which is what the unicode is for. Is there a package I need to enable these icons? ``` (require 'dash) (require 's) (require 'cl) (require 'magit) (setq default-process-coding-system '(utf-8-unix . utf-8-unix)) (defmacro with-face (STR &rest PROPS) "Return STR propertized with PROPS." `(propertize ,STR 'face (list ,@PROPS))) (defmacro esh-section (NAME ICON FORM &rest PROPS) "Build eshell section NAME with ICON prepended to evaled FORM with PROPS." `(setq ,NAME (lambda () (when ,FORM (-> ,ICON (concat esh-section-delim ,FORM) (with-face ,@PROPS)))))) (defun esh-acc (acc x) "Accumulator for evaluating and concatenating esh-sections." (--if-let (funcall x) (if (s-blank? acc) it (concat acc esh-sep it)) acc)) (defun esh-prompt-func () "Build `eshell-prompt-function'" (concat esh-header (-reduce-from 'esh-acc "" eshell-funcs) "\n" eshell-prompt-string)) (esh-section esh-dir "\xf07c" ;  (faicon folder) (abbreviate-file-name (eshell/pwd)) '(:foreground "gold" :bold ultra-bold :underline t)) (esh-section esh-git "\xe907" ;  (git icon) (magit-get-current-branch) '(:foreground "pink")) (esh-section esh-clock "\xf017" ;  (clock icon) (format-time-string "%H:%M" (current-time)) '(:foreground "forest green")) ;; Below I implement a "prompt number" section (setq esh-prompt-num 0) (add-hook 'eshell-exit-hook (lambda () (setq esh-prompt-num 0))) (advice-add 'eshell-send-input :before (lambda (&rest args) (setq esh-prompt-num (incf esh-prompt-num)))) (esh-section esh-num "\xf0c9" ;  (list icon) (number-to-string esh-prompt-num) '(:foreground "brown")) ;; Separator between esh-sections (setq esh-sep " ") ; or " | " ;; Separator between an esh-section icon and form (setq esh-section-delim " ") ;; Eshell prompt header (setq esh-header "\n ") ; or "\n┌─" ;; Eshell prompt regexp and string. Unless you are varying the prompt by eg. ;; your login, these can be the same. (setq eshell-prompt-regexp " ") ; or "└─> " (setq eshell-prompt-string " ") ; or "└─> " ;; Choose which eshell-funcs to enable (setq eshell-funcs (list esh-dir esh-git esh-clock esh-num)) ;; Enable the new eshell prompt (setq eshell-prompt-function 'esh-prompt-func) ``` # Answer I found out there was an issue with my fonts as I could not reference the icons using the unicode directly until after I installed the `all-the-icons` package. I then ran `M-x all-the-icons-install-fonts` Per the documentation, I added that package and edited my file to include the following ``` (require 'all-the-icons) ... ;; Use 'prepend for the NS and Mac ports or Emacs will crash. (set-fontset-font t 'unicode (font-spec :family "FontAwesome") nil 'prepend) (set-fontset-font t 'unicode (font-spec :family "all-the-icons") nil 'prepend) ... ;;Usage of icons should be like so (esh-section esh-dir (all-the-icons-faicon "folder-open") ;  (faicon folder) (abbreviate-file-name (eshell/pwd)) '(:foreground "gold")) (esh-section esh-git (all-the-icons-alltheicon "git") ;  (git icon) (magit-get-current-branch) '(:foreground "pink")) ;; After installing and requiring the packages, I was able to use the ;;unicode for the icons as expected, although some were no longer available ;;in the version used in all-the-icons Font Awesome ver 4. (esh-section esh-clock "\xf017" ;  (clock icon) (format-time-string "%H:%M" (current-time)) '(:foreground "forest green")) ... (esh-section esh-num "\xf0c9" ;  (list icon) (number-to-string esh-prompt-num) '(:foreground "brown")) ``` After making the changes to my file I load this file in my eshell profile file. My prompt now looks as I expected My gist is here if you would like to check it out. I am running macOS Big Sur > 2 votes --- Tags: eshell, icons ---
thread-35497
https://emacs.stackexchange.com/questions/35497
Does emacs have an option to display build settings?
2017-09-13T09:30:27.910
# Question Title: Does emacs have an option to display build settings? Does emacs have an option or some internal command that displays build time settings and whatever features it supports? A good example is the `nginx -V` command which lists the `./configure` options it was compiled with. # Answer Take a look at the `system-configuration-options` variable. Here's an example, which is the result of running `C-h v system-configuration-options` ``` system-configuration-options is a variable defined in `C source code'. Its value is "--prefix=/usr/local/emacs 'CFLAGS=-O2 -march=native -pipe -falign-functions=64 -fomit-frame-pointer -ftracer -funit-at-a-time -fweb -fforce-addr -fpeel-loops -funswitch-loops -frename-registers -mfpmath=sse -ffast-math -fno-finite-math-only -fstack-check' PKG_CONFIG_PATH=/usr/share/pkgconfig" Documentation: String containing the configuration options Emacs was built with. For more information check the manuals. ``` Here is how to print the contents on the command line: ``` emacs -nw -q --batch --eval '(message system-configuration-options)' ``` > 46 votes # Answer Dunno about a command-line switch, but: 1. If you use library `emacsbug+.el`, which enhances standard library `emacsbug.el`, then you can use command `ebp-insert-version` with a prefix arg, to insert the complete version info, including some build info, in the current buffer. This is the same version info that is included when you use command `report-emacs-bug`. For example: ``` In GNU Emacs 25.2.1 (x86_64-w64-mingw32) of 2017-04-24 Windowing system distributor `Microsoft Corp.', version 6.1.7601 Configured using: `configure --without-dbus --without-compress-install 'CFLAGS=-O2 -static -g3'' ``` 2. Without library `emacsbug+.el`, you can use standard command `emacs-version`, to give you a subset of that info. With a prefix arg it inserts the info in the current buffer. For example: ``` GNU Emacs 25.2.1 (x86_64-w64-mingw32) of 2017-04-24 ``` > 4 votes # Answer In addition to `system-configuration-options` which lists the options that were used for the invocation of `configure` when the emacs executable was built, there is also `system-configuration-features` which were the features that were enabled (either explicitly or by default) for that `configure` run. Here's what emacs-27.2 on Fedora 33 says about these two variables: ``` system-configuration-options is a variable defined in ‘C source code’. Its value is "--build=x86_64-redhat-linux-gnu --host=x86_64-redhat-linux-gnu --program-prefix= --disable-dependency-tracking --prefix=/usr --exec-prefix=/usr --bindir=/usr/bin --sbindir=/usr/sbin --sysconfdir=/etc --datadir=/usr/share --includedir=/usr/include --libdir=/usr/lib64 --libexecdir=/usr/libexec --localstatedir=/var --sharedstatedir=/var/lib --mandir=/usr/share/man --infodir=/usr/share/info --with-dbus --with-gif --with-jpeg --with-png --with-rsvg --with-tiff --with-xft --with-xpm --with-x-toolkit=gtk3 --with-gpm=no --with-xwidgets --with-modules --with-harfbuzz --with-cairo --with-json build_alias=x86_64-redhat-linux-gnu host_alias=x86_64-redhat-linux-gnu CC=gcc 'CFLAGS=-DMAIL_USE_LOCKF -O2 -flto=auto -ffat-lto-objects -fexceptions -g -grecord-gcc-switches -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -specs=/usr/lib/rpm/redhat/redhat-hardened-cc1 -fstack-protector-strong -specs=/usr/lib/rpm/redhat/redhat-annobin-cc1 -m64 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection' LDFLAGS=-Wl,-z,relro PKG_CONFIG_PATH=:/usr/lib64/pkgconfig:/usr/share/pkgconfig" Documentation: String containing the configuration options Emacs was built with. ``` and ``` system-configuration-features is a variable defined in ‘C source code’. Its value is "XPM JPEG TIFF GIF PNG RSVG CAIRO SOUND DBUS GSETTINGS GLIB NOTIFY INOTIFY ACL LIBSELINUX GNUTLS LIBXML2 FREETYPE HARFBUZZ M17N_FLT LIBOTF ZLIB TOOLKIT_SCROLL_BARS GTK3 X11 XDBE XIM MODULES THREADS XWIDGETS LIBSYSTEMD JSON PDUMPER GMP" Probably introduced at or before Emacs version 25.1. Documentation: String listing some of the main features this Emacs was compiled with. An element of the form "FOO" generally means that HAVE_FOO was defined during the build. This is mainly intended for diagnostic purposes in bug reports. Don’t rely on it for testing whether a feature you want to use is available. ``` I don't know why the last paragraph says not to rely on it for testing (I guess there are better methods to test for specific features, e.g. `cairo-version-string` or `libgnutls-version`), but it should probably be heeded. Nevertheless, it is a useful summary. BTW, here's a bash command line to see it: ``` strings $(command -v emacs) | grep Id ``` or ``` emacs --batch --eval '(message system-configuration-features)' ``` > 3 votes --- Tags: config, build ---
thread-66523
https://emacs.stackexchange.com/questions/66523
How to export a gantt chart in pdf or png format using taskjuggler and/or org-mode
2021-06-30T06:30:50.860
# Question Title: How to export a gantt chart in pdf or png format using taskjuggler and/or org-mode I managed to get taskjuggler up and running along emacs/org-mode. After reading the manual entries here and here I can export my project into html but I cannot export the Gantt chart into pdf, as hinted at the end of this section. The workflow seems to be 1) export the project into a `.tjp` file and then 2) use the GUI to do `File->Print`. However, the version that I am using `tj3 (TaskJuggler) 3.7.1` does not have a GUI as far as I know. I have tried to look for a command that would allow me to export the tjp file into pdf, e.g., export but without luck. I am looking for a solution that allows me to obtain a Gantt Chart in a format which can be inserted in a document, although I prefer `pdf` format and to be able to do it from inside emacs org-mode. Thank you in advance. **Update** Apparently the standard way to achieve this is to export the html into pdf using a web browser or packages available in linux distros, e.g. wkhtmltoimage and wkhtmltopdf. However, the main problems that I find with these solutions are that 1) for long projects they partially hide the project and show a frozen scrollbar (major issue), and 2) they do not isolate the gantt chart (minor) # Answer > 0 votes I'm no expert by any means but one partial solution is proposed here: Basically they say to print the page from a web browser while visiting the `.html` file generated by `org-taskjuggler-export-process-and-open`. However, at least on Firefox the generated `pdf` skips the colors and arrows, rendering the result kind of useless. And the general workarounds seem unnecessarily complicated. I'm using `tj3` same as you, and `man tj3` does not even mention the word `pdf`. I hope they come up with a less hacky solution. # Answer > 0 votes The process is: * export the Org mode file (say `foo.org`) to a `tjp` file (`foo.tjp`). * process the `tjp` file with tj3: \`tj3 foo.tjp * view the resulting HTML (`Plan.html`) file with a browser (both Firefox and Chrome worked for me). * Print from the browser to PDF, but make sure to first open `More settings` and select the `Background graphics` (Chrome) or `Print backgrounds` (Firefox) option. Then click `Save`. It's probably possible to do the last two steps through a CLI command, so that it could be done from inside Emacs, but I don't know how to do that off the top of my head. EDIT: I don't know about Firefox but Chrome can print to PDF from the command line with this bash command: ``` /opt/google/chrome/chrome --headless --print-to-pdf file://$PWD/Plan.html ``` You might have to change the path to the `chrome` executable. --- Tags: org-mode, org-export, pdf, project, exporting ---
thread-66779
https://emacs.stackexchange.com/questions/66779
How this guy do glow(neon) text
2021-07-21T14:09:38.603
# Question Title: How this guy do glow(neon) text I think everything is clear from this video. https://vimeo.com/22798433 I am interested in how to make the text exactly like that. Here's another example but this is vs code https://youtu.be/cxjP4731Av8?t=111 # Answer > 1 votes you could have a look at the emacs-live config used in the video, or more generally use a terminal emulator with graphic effects like cool-retro-term and run emacs from a shell. --- Tags: themes ---
thread-66797
https://emacs.stackexchange.com/questions/66797
How to use `--no-edit` flag in a `git commit --amend` process inside magit?
2021-07-22T14:00:16.077
# Question Title: How to use `--no-edit` flag in a `git commit --amend` process inside magit? If I am using the terminal, after staging some changes, I can do: ``` git commit --amend --no-edit ``` This will insert the staged changes on the previous commit. The editor to edit the message was **not open** to do it. If I try the same on Magit, I can stage (s), commit (c), and amend (a). At this point, there is a window to edit the previous commit message. Of course, I can simply press `C-c C-c` to finish the process without changing anything. It would have the same effect as using the `--no-edit` flag. But, is there a way to use the `--no-edit` flag in Magit so that this edition window is not even necessary? # Answer That's exactly what `c e` (“extend”) does. And conversely, to change the commit message without amending the commit with the staged changes, there's `c w` (“reword”). > 6 votes --- Tags: magit, git ---
thread-66799
https://emacs.stackexchange.com/questions/66799
Why this magit process happens after pushing some changes to a remote repository? How to avoid it?
2021-07-22T14:26:45.253
# Question Title: Why this magit process happens after pushing some changes to a remote repository? How to avoid it? After pushing some changes to a remote repository using magit, Emacs shows this process running: ``` git-credenti... 72390 run *git-creden... /dev/pts/1 git credential-cache--daemon /home/pedro/.git-credential-cache/socket ``` It seems to be connected to the fact that I typed my username and password before doing the push. Why does this happen? How to fix it? Killing the buffer? After using `C-x C-b` (list buffer), I was not able to press `D` to execute the deletion with `X` later. It was necessary to kill it with `C-x k`. # Answer This process provides the credential cache, so that you don't have to enter your password each time you pull, push or other otherwise access that remote. If you don't need the cache anymore, you can kill the process in the usual way, for example from the `list-processes` buffer, or with the `kill-process` function. Magit doesn't currently offer a command to directly kill the credential cache daemon process. If you don't want credentials to be cached, you can disable this altogether by setting `magit-credential-cache-daemon-socket` (with `setq` or via Customize). > 2 votes --- Tags: magit, git, networking ---
thread-42285
https://emacs.stackexchange.com/questions/42285
How to disable line wrapping in LaTeX layer?
2018-06-27T16:13:55.550
# Question Title: How to disable line wrapping in LaTeX layer? The LaTeX Layer by default wraps a line after column 85 by inserting a new line while typing and moving the current word to the new line. When the line is a comment, it even automatically inserts the comment prefix. How can one disable this behaviour? The emacs variables `word-wrap` and `truncate-lines` seem to have nothing to do with this, they only change how text is displayed while the above behaviour actually inserts new lines. # Answer As largely seen on the web, adding off-switch for the `auto-fill` minor mode to the `(La)TeX` major mode won't work anymore, not even with `'append`. As duianto states, the solution has been properly documented in the `auto-fill` section of the `LaTeX` layer (in development). Change LaTeX's layer line ``` latex ``` to ``` (latex :variables latex-enable-auto-fill nil) ``` > 2 votes # Answer **Update 2022-07: This does not work anymore.** See other answers for a working solution. The automatic wrapping is done by the minor mode `auto-fill-mode` (as hinted by DoMiNeLa10). To disable it, add this to function `dotspacemacs/user-config` in `.spacemacs`: ``` (add-hook 'latex-mode-hook #'spacemacs/toggle-auto-fill-mode-off) ``` There is also the `latex/auto-fill-mode`, but that doesn't seem to be a mode itself (doc: "Toggle auto-fill-mode using the custom auto-fill function."). See the layer documentation for auto-fill for fine-grained (latex specific) control of where auto-fill should be enabled. > 3 votes --- Tags: spacemacs, wrapping ---
thread-66804
https://emacs.stackexchange.com/questions/66804
Access hash table by value, not key?
2021-07-22T16:55:56.190
# Question Title: Access hash table by value, not key? **Q:** how can I access a hash table by its *value*, not its *key*? Association lists can be accessed via either their key or their value: ``` (setq alist '((a .1) (b . 2) (c . 3))) (assoc 'a alist) ; => (a . 1) (rassoc 3 alist) ; => (c . 3) ``` Is there a hash table analog to `rassoc` that would allow me to find the *key* in the hash table associated with *value*? # Answer 1. There's no predefined function for this, as far as I know. 2. It's wrong to speak of *the* key associated with a given value. There can be more than one key with the same value. 3. I use these functions (defined in `apu.el`): ``` (defun apu-get-hash-keys (value hash-table &optional value-test-function) "Return a list of keys associated with VALUE in HASH-TABLE. Optional arg VALUE-TEST-FUNCTION (default `equal') is the equality predicate used to compare values." (setq value-test-function (or value-test-function #'equal)) (let ((keys ())) (maphash (lambda (key val) (when (funcall value-test-function val value) (push key keys))) hash-table) keys)) (defun apu-get-a-hash-key (value hash-table &optional value-test-function) "Return a hash key associated with VALUE in HASH-TABLE. If there is more than one such key then it is undefined which is returned. Optional arg VALUE-TEST-FUNCTION (default `equal') is the equality predicate used to compare values." (setq value-test-function (or value-test-function #'equal)) (catch 'get-a-hash-key (maphash (lambda (key val) (when (funcall value-test-function val value) (throw 'get-a-hash-key key))) hash-table) nil)) ``` > 3 votes --- Tags: elisp, hash-tables ---
thread-66808
https://emacs.stackexchange.com/questions/66808
How to make this mode work in all buffers except for the SLIME's REPL buffer?
2021-07-22T17:59:24.647
# Question Title: How to make this mode work in all buffers except for the SLIME's REPL buffer? I have this minor mode set to work on all buffers: ``` ;; John Mercouris centered point mode ;; Homepage: https://github.com/jmercouris/emacs-centered-point (define-minor-mode centered-point-mode "Alaways center the cursor in the middle of the screen." :lighter "..." (cond (centered-point-mode (add-hook 'post-command-hook 'line-change)) (t (remove-hook 'post-command-hook 'line-change)))) (defun line-change () (when (eq (get-buffer-window) (selected-window)) (recenter))) (provide 'centeredpoint) (centered-point-mode t) ``` This is close to what I want. I wished this was a global mode working on all buffers, except for the SLIME's REPL buffer. How can I insert this exception in my config files? What should I change on: ``` (centered-point-mode t) ``` # Answer > 2 votes Something like ``` (add-hook 'slime-repl-mode-hook (lambda () (centered-point-mode -1))) ``` which toggles the mode off in slime REPLs. --- Tags: init-file, minor-mode, global-mode ---
thread-66791
https://emacs.stackexchange.com/questions/66791
How to properly fill a whole Org buffer programmatically?
2021-07-22T04:36:12.870
# Question Title: How to properly fill a whole Org buffer programmatically? I'm trying to fill programmatically an Org buffer (especially the elements `quote-block`, `paragraph` and `item`). Note that all following attempts contains a `(org-cycle '(64))` because they all don't work when headings are not fully expanded (not sure why). **First attempt** ``` (defun test/org-fill-whole-buffer-1 () (interactive) (org-cycle '(64)) (mark-whole-buffer) (org-fill-paragraph nil (list (point-min) (point-max)))) ``` It works partially: * items right above a quote block are not filled; * items after multiple line breaks are not filled. And per the documentation, `mark-whole-buffer` should not be called programmatically. **Second attempt** ``` (defun test/org-fill-whole-buffer-2 () (interactive) (org-cycle '(64)) (save-excursion (org-element-map (org-element-parse-buffer 'element) 'paragraph (lambda (elt) (when-let* ((target-point (org-element-property :contents-begin elt))) (goto-char target-point) (org-fill-paragraph nil t)))))) ``` This obviously doesn't work (or works randomly) because once the first element is filled, the position of the subsequent ones is not correct anymore. **Third attempt** Improved version of `test/org-fill-whole-buffer-2`: fill elements in reverse order of their appearances. Now the elements positions are correct as they are not altered by previous `org-fill-paragraph` calls. ``` (defun test/org-fill-whole-buffer-3 (types) "Fill Org elements of TYPES in the whole Org buffer." (interactive (list 'paragraph)) (org-cycle '(64)) (save-excursion (mapc (lambda (n) (goto-char n) (org-fill-paragraph nil t)) (reverse (org-element-map (org-element-parse-buffer 'element) types (lambda (elt) (when-let* ((target-point (org-element-property :contents-begin elt))) target-point))))))) ``` However, there are still some issues I can't really understand. 1. For instance, assuming that all nodes are folded, and that I call `(test/org-fill-whole-buffer-3 'paragraph)`, I obtain this: But then if I `M-x undo-tree-undo`, fold headings, and call again `(test/org-fill-whole-buffer-3 'paragraph)`, I obtain this: 2. The function seems to be also "point-dependent", meaning that if I `goto-char` onto a problematic item (see point 1) before calling `(test/org-fill-whole-buffer-3 'paragraph)`, then that item would fill properly at the first time as the second picture showed (but not other problematic items). 3. Interestingly, `test/org-fill-whole-buffer-1` doesn't have the issue of point 1, but have issue with some items. So, one may think that calling `(test/org-fill-whole-buffer-1)` and `(test/org-fill-whole-buffer-3 'item)` successively would work as they complete each other. Nope, that doesn't work for a mysterious reason. For these reasons, I had trouble to make a minimal reproducible example to illustrate issues I have with `test/org-fill-whole-buffer-3`. But the essence of this question is still "**how to fill a whole Org buffer programmatically, included Org elements `quote-block`, `paragraph` and `item` ?**", so any brand-new solution is welcomed. **EDIT**: Here are pastebin links of my real world Org buffer. Special attention should be made on the two items containing `org-dict-tlfi` links (see the pictures above). The expected result is as shown in the second picture, which could be achieved interactively with `M-q` (`org-fill-paragraph`) at the beginning of the unfilled item. Org mode version: 9.4.4 # Answer This seems to give the expected result for me: ``` (defun custom-org-fill () (interactive) (save-excursion (org-with-wide-buffer (cl-loop for el in (reverse (org-element-map (org-element-parse-buffer) '(paragraph quote-block item) #'identity)) do (goto-char (org-element-property :contents-begin el)) (org-fill-paragraph))))) ``` > 1 votes --- Tags: org-mode, fill-paragraph ---
thread-66809
https://emacs.stackexchange.com/questions/66809
emacs still makes backup files even after I tell it not to
2021-07-22T19:55:18.263
# Question Title: emacs still makes backup files even after I tell it not to (I did restart emacs after adding config) I'm on GNU Emacs 28.0.50 (build 1, aarch64-apple-darwin20.5.0) of 2021-06-07 My config: ``` (setq make-backup-files nil) ;disable backup (setq backup-inhibited t) ;disable auto save (setq auto-save-default nil) ``` What could be going on? # Answer > 0 votes You seem to be highlighting a lock file, not a backup file. --- Tags: auto-save ---
thread-66813
https://emacs.stackexchange.com/questions/66813
How to avoid emacs pop-up security warning for code eval
2021-07-23T08:45:36.413
# Question Title: How to avoid emacs pop-up security warning for code eval How to disable this pop-up warning for orgmode commands such as: ``` shell:ls *.org ``` For which I would wish just to click once? Thanks! # Answer `(setq org-confirm-shell-link-function nil)` But: > Shell links can be dangerous: just think about a link > > ``` > [[shell:rm -rf ~/*][Google Search]] > > ``` > > This link would show up in your Org document as "Google Search", but really it would remove your entire home directory. Therefore we advise against setting this variable to nil. Just change it to ‘y-or-n-p’ if you want to confirm with a single keystroke rather than having to type "yes". Cf. `C-h f org-confirm-shell-link-function` See also `org-link-shell-skip-confirm-regexp`. You can allow specific commands through it. But beware of the possibility of a command like `ls *.org && rm -rf ~/*`: `^ls.*` is obviously not enough. > 2 votes --- Tags: org-mode, warning, eval, security ---
thread-66789
https://emacs.stackexchange.com/questions/66789
New `wrong-number-of-arguments` error from `desktop-change-dir` and other commands
2021-07-22T00:37:06.607
# Question Title: New `wrong-number-of-arguments` error from `desktop-change-dir` and other commands (This has started happening with other commands too, but I don't remember which.) Previously when I ran `M-x desktop-change-dir` I would be prompted to enter a folder, whereupon Emacs would load the `.emacs-desktop` saved there. Now it loads only one file from the `.emacs-desktop`, and then gives the error below. My `.emacs` dotfile does not include the string `desktop` anywhere, and hever has, so I don't think it's responsible. It's possible I'm now on a newer version of Emacs (I use NixOS and have it upgrade things nightly). I don't know what I was on before, but lately running `M-x emacs-version` prints ``` GNU Emacs 27.2 (build 1, x86_64-pc-linux-gnu, GTK+ Version 3.24.27, cairo version 1.16.0) ``` Here's the error: ``` Debugger entered--Lisp error: (wrong-number-of-arguments (0 . 0) 1) org-roam-mode(1) desktop-create-buffer(208 "/home/jeff/nix/jbb-config/packages.nix" "packages.nix" nix-mode (override-global-mode global-auto-revert-mode beacon-mode org-roam-mode) 2221 (538 nil) nil nil ((tab-width . 2) (indent-tabs-mode) (buffer-display-time 24781 5953 925334 220000) (buffer-file-coding-system . undecided-unix)) ((mark-ring (538)))) eval-buffer(#<buffer *load*> nil "/home/jeff/nix/jbb-config/.emacs.desktop" nil t) ; Reading at buffer position 3145 load-with-code-conversion("/home/jeff/nix/jbb-config/.emacs.desktop" "/home/jeff/nix/jbb-config/.emacs.desktop" t t) load("/home/jeff/nix/jbb-config/.emacs.desktop" t t t) desktop-read("/home/jeff/nix/jbb-config/") desktop-change-dir("~/nix/jbb-config/") funcall-interactively(desktop-change-dir "~/nix/jbb-config/") call-interactively(desktop-change-dir record nil) command-execute(desktop-change-dir record) execute-extended-command(nil "desktop-change-dir" "desk-ch") funcall-interactively(execute-extended-command nil "desktop-change-dir" "desk-ch") call-interactively(execute-extended-command nil nil) command-execute(execute-extended-command) ``` # Answer > 1 votes Sounds like whatever was saved in your desktop file is the problem. Some code there is calling `org-roam` and passing it an argument, but it expects *zero* arguments. You can try bisecting your desktop file. Or you can just toss that desktop file and create a new one. (OP confirmed that creating a new desktop file solved the problem.) --- Tags: debugging, arguments, error ---
thread-66816
https://emacs.stackexchange.com/questions/66816
Emacs 27: How to jump to backward found word when switched into reverse incremental search?
2021-07-23T14:29:17.477
# Question Title: Emacs 27: How to jump to backward found word when switched into reverse incremental search? I am trying to apply following solution(How to jump to backward found word when switched into reverse incremental search?) into `Emacs >27.1`, (which works in emacs 26.3): > ``` > (define-advice isearch-repeat (:before (direction) goto-other-end) > "If reversing, start the search from the other end of the current match." > (unless (eq isearch-forward (eq direction 'forward)) > (when isearch-other-end > (goto-char isearch-other-end)))) > > ``` But I am having following error message when I use `emacs >27.1`: ``` Wrong number of arguments: (lambda (direction) "If reversing, start the search \ from the other end of the current match." (if (eq isearch-forward (eq direction\ 'forward)) nil (if isearch-other-end (progn (goto-char isearch-other-end))))),\ 2 ``` How could I fix this error? # Answer > 1 votes 1. It's always more informative to set `debug-on-error` to `t` and repro the error, then post the backtrace (at least the beginning). That will show the complete error message, which tells what function raised the error and how many args it expected versus how many it received. 2. After Emacs 26.3, function `isearch-repeat`, which you are advising, and *whose advice accepts only one argument*, was changed to *accept either one or two args*. ``` (defun isearch-repeat (direction) ; Emacs 26.3 ``` ``` (defun isearch-repeat (direction &optional count) ; Emacs 27.1 and later ``` So try this - it matches the lambda list of the Emacs 27 `isearch-repeat`: ``` (define-advice isearch-repeat (:before (direction &optional count) goto-other-end) "If reversing, start the search from the other end of the current match." (unless (eq isearch-forward (eq direction 'forward)) (when isearch-other-end (goto-char isearch-other-end)))) ``` --- Tags: debugging, isearch, error ---
thread-66771
https://emacs.stackexchange.com/questions/66771
How can I override an OS key binding in Emacs?
2021-07-20T21:33:59.287
# Question Title: How can I override an OS key binding in Emacs? One of my major modes defines the key binding `C-M-t`, but every time I use it, my operating system (Ubuntu Linux) intercepts the key binding and opens a terminal. The OS key binding overrides the Emacs key binding. How can I make sure my Emacs key binding takes precedence over the OS key binding? # Answer > 2 votes When running emacs under a graphical desktop environment, the DE uses certain keybindings for its own purposes (maximizing/minimizing/moving windows, manipulating desktops, etc.). If you try to use such a keybinding in your emacs, the DE intercepts it, and *Emacs will never see it*. If you really, really want to use that keybinding in Emacs, the only way to do it is to convince the DE to not intercept it. How to do that varies by DE, but there is usually some sort of a `Settings` app, where you can (re)configure such keybindings. E.g. in my Gnome environment, the Settings app has a `Keyboard Shortcuts` tab where (some) such things can be configured. Other DEs will have different methods, so YMWV. # Answer > 0 votes The solution to my problem was found outside of Emacs. Using the Settings on Ubuntu I did: ``` Settings > Keyboard Shortcuts > Launchers > Launch Terminal > Backspace to disable the keyboard shortcut ``` I hope this will also help me to use less the Ubuntu terminal and use more `shell-mode` or `eshell` inside Emacs. I also want to use more Magit instead of using git on Ubuntu's terminal. --- Tags: key-bindings ---
thread-62015
https://emacs.stackexchange.com/questions/62015
Closing emacs results in "Current desktop was not loaded from a file" even though desktop-save-mode was set before start
2020-11-30T16:41:16.323
# Question Title: Closing emacs results in "Current desktop was not loaded from a file" even though desktop-save-mode was set before start I have set the following things in my .el file (not init.el): ``` (setq desktop-dirname "~/.emacs.d/desktop/" desktop-base-file-name "emacs.desktop" desktop-base-lock-name "lock" desktop-path (list desktop-dirname) desktop-save t desktop-files-not-to-save "^$" ;reload tramp paths desktop-load-locked-desktop nil desktop-auto-save-timeout 30) (desktop-save-mode 1) ``` Although the desktop file is saved/updated to `~/.emacs.d/desktop` the following happens. When I try to close emacs I get the following message: > "Current desktop was not loaded from a file. Overwrite this desktop file?" Even if I choose to overwrite it (and close emacs), the exact same thing happens the next time closing emacs. # Answer This is the result of not including (desktop-read) in your setup. DON'T DO ONLY THIS: ``` (desktop-save-mode 1) ``` But rather do both of these: ``` (desktop-save-mode 1) (desktop-read) ``` (desktop-read) is the thing that "reads current desktop from a file". > 1 votes --- Tags: desktop ---
thread-64078
https://emacs.stackexchange.com/questions/64078
Remove old clock entries
2021-03-23T22:29:54.707
# Question Title: Remove old clock entries I'm clocking the time spent on daily tasks like email and for that I have a "Daily Routine" TODO entry. Clocking in this task adds a new clock line everyday, leading to a very populated CLOCK drawer. I'd like to limit its size by either a maximum number of clock entries by removing the older ones or better, removing the entries older than some date. Ideally, I'd like to find a function that tidies the clock drawer of an entry, to be added to the clock-in or clock-out hook. Any idea how to achieve that ? # Answer Here is what I came up with: ``` (defun jc-org-clock-remove-old-clock-entries (n) "Remove clock entries whose end is older than N weeks in current subtree. Skip over dangling clock entries." (interactive "nnumber of weeks: ") (save-excursion (org-back-to-heading t) (org-map-tree (lambda () (let ((drawer (re-search-forward org-clock-drawer-start-re (save-excursion (org-end-of-subtree)) t)) (case-fold-search t)) (when drawer (let ((re org-clock-line-re) (end (save-excursion (re-search-forward org-clock-drawer-end-re (save-excursion (org-end-of-subtree)) nil))) ) (while (re-search-forward re end t) (skip-chars-forward " \t\r") (looking-at org-tr-regexp-both) (when (>= (/ (time-to-number-of-days (org-time-since (match-string-no-properties 2))) 7) (float n)) (kill-whole-line)) )))))) (org-clock-remove-empty-clock-drawer) )) ``` It should work if your clocking uses either a specific :CLOCK: drawer or the default :LOGBOOK: drawer, according to the value of the org-clock-into-drawer variable. > 0 votes # Answer Have a look at `org-clock-remove-empty-clock-drawer`. It uses `org-map-tree` and a regular expression based on `org-clock-drawer-name` to find the `:LOGBOOK:` drawers. You can use the same logic to get `point` to the start of `:LOGBOOK:` and then handle all `CLOCK:` entries on a line-by-line basis. To parse the timestamps, you can use `org-ts-regexp-both` and `org-element-timestamp-parser`. Afterwards, you can use `kill-whole-line` to get rid of the entry. So in short: 1. Find the next `:LOGBOOK:` via `re-search-forward` 2. Go forward a single line 3. Check the start of the line. * If it starts with `:END:`, stop the clock handling for the current drawer * If it starts with `CLOCK:`, search for the next timestamp. 1. If it's too old, remove the whole line with `kill-whole-line`. 2. Otherwise continue to the next line * goto 3. > 1 votes --- Tags: org-mode, org-clock ---
thread-66817
https://emacs.stackexchange.com/questions/66817
Org-mode LaTeX previews image size too large
2021-07-23T15:05:17.263
# Question Title: Org-mode LaTeX previews image size too large **SOLVED: REMOVE `#+SETUPFILE:` HEADER. SORRY FOR WASTING YOUR TIME** I am having the same issue as described in this Reddit post from a few weeks ago: basically the preview images generated for a given latex fragment in the file are too large **vertically** and make the file unreadable. I started out using `dvipng` (the default) to generate the images. I've played around with adding ``` (setq org-format-latex-options (plist-put org-format-latex-options :scale 2.0)) ``` to my config: this made the rendered latex larger (which was helpful) but unfortunately did not cut down the size of the images (which in fact got larger). I've also tried switching form `dvipng` to `dvisvgm`, the latter just gave the error ``` Latex-preview not working; Please adjust ‘dvisvgm’ part of ‘org-preview-latex-process-alist’ ``` like in this post. Finally, I have also tried the `texfrag` package, which kind of works, but only after setting the scale and generating previews, getting an error, and then generating previews again. It doesn't work with `#+STARTUP: latexpreview`. **EDIT:** As requested, here is a brief snippet of an `org-roam` file that produces unwieldy previews: ``` #+title: Kullback-Leibler divergence #+roam_tags: "machine learning" "statistics" "probability" * Kullback-Leibler Divergence For two continuous probability distributions of one dimension $P$ and $Q$, the Kullback-Leibler (KL) divergence, also known as the relative entropy, gives a measure of the difference between them. The definition is as follows: \begin{eqnarray} \label{eq:KL} D_Q(P) = \int_{\infty}^{\infty} dx ~ P(x) \log \left(frac{P(x)}{Q(x)} \right) \,, \end{eqnarray} from which we can see that the KL divergence is not symmetric - $D_Q(P)$ is a measure of the divergence of $P$ from $Q$, while $D_P(Q)$ measures the divergence of $Q$ from $P$, and these are in general different. ``` (I don't think `org-roam` has anything to do with this, just a handy example) **EDIT2:** Emacs 27.2 and Org mode version 9.4.4 `GNU Emacs 27.2 (build 1, x86_64-pc-linux-gnu, GTK+ Version 3.24.27, cairo version 1.17.4) of 2021-03-26` `Org mode version 9.4.4 (release_9.4.4 @ /usr/share/emacs/27.2/lisp/org/)` **EDIT3:** Here is the current setup of `org-preview-latex-process-alist`: ``` Value: ((dvipng :programs ("latex" "dvipng") :description "dvi > png" :message "you need to install the programs: latex and dvipng." :image-input-type "dvi" :image-output-type "png" :image-size-adjust (1.0 . 1.0) :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f") :image-converter ("dvipng -D %D -T tight -o %O %f")) (dvisvgm :programs ("latex" "dvisvgm") :description "dvi > svg" :message "you need to install the programs: latex and dvisvgm." :image-input-type "dvi" :image-output-type "svg" :image-size-adjust (1.7 . 1.5) :latex-compiler ("latex -interaction nonstopmode -output-directory %o %f") :image-converter ("dvisvgm %f -n -b min -c %S -o %O")) (imagemagick :programs ("latex" "convert") :description "pdf > png" :message "you need to install the programs: latex and imagemagick." :image-input-type "pdf" :image-output-type "png" :image-size-adjust (1.0 . 1.0) :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f") :image-converter ("convert -density %D -trim -antialias %f -quality 100 %O"))) ``` # Answer # Table of Contents 1. Test 1 2. Test 2 3. Resolution The issue described here is a partial resolution of this post I raised yesterday The problem is that LaTeX previews generated from org files I was creating were too large, took very long to process and made the text unreadable due to their size. After some help from @NickD, I realized that the problem was that I was using a setupfile for LaTeX export for some of the other files in the same folder! But it took a long time to figure out why this was a problem. I created two files, `test1.org` and `test2.org`. Initially, both contain the same pieces of LaTeX terms, and I placed both in a separate folder. `test1.org` was a standard `.org` file, while `test2.org` included the header for the setup file. # Test 1 Here is what `test1.org` looked like in raw form: and here is what it looks like after applying previews with `C-c C-x C-l`: The previews are actually good! They are appropriately scaled in font, and the size of the preview images means they fit inside sentences. # Test 2 Here is `test2.org`, where we include the setup file header `#+SETUPFILE: ~/org/latex/latex<sub>template.org</sub>`: Now we apply the previews: This looks exactly the same as `test1.org`! I am not sure, but I believe that `org-latex-preview` must be coded to reuse already generated previews – in this case, I think the previews from `test1.org`, which were previously created, are added to this file. I added some new LaTeX fragments to `test2.org`: Now, applying the previews, I find that the previous paragraph reuses the same previews as before and appears perfectly fine. But the newly added LaTeX now has previews which are as bad as the initial issue I was having: oversized images which disrupt sentences: # Resolution So I guess what I have to do is to delete all the generated latex previews in my main `org-roam` folder, and remove `#+SETUPFILE: ~/org/latex/latex<sub>template.org</sub>`. I think the main problem with the size arises from the template requiring `\usepackage{fullpate}` \- after removing this the size seems OK, but I haven't done a full check. The other problem of it taking way too long to generate previews still remains. This is slightly unsatisfactory, as I would like to have the option of both having reasonably sized LaTeX previews, as well as be able to export my notes to a `.pdf` via LaTeX, in the format that I specified. I also have some nice `\newcommand` redefinitions that I am used to using. > 0 votes --- Tags: org-mode, latex, preview-latex, org-roam ---
thread-66828
https://emacs.stackexchange.com/questions/66828
split org file into smaller ones
2021-07-24T16:06:14.590
# Question Title: split org file into smaller ones I want to split one big org file into smaller files. I have found function which do this but it's also exports it to html. So how can I just export the content? Without this function (org-html-export-as-html) ? ``` (defun my-org-export-each-level-1-headline-to-html (&optional scope) (interactive) (org-map-entries (lambda () (let* ((title (car (last (org-get-outline-path t)))) (dir (file-name-directory buffer-file-name)) (filename (concat dir title ".html"))) (org-narrow-to-subtree) (org-html-export-as-html) (write-file filename) (kill-current-buffer) (widen))) "LEVEL=1" scope)) ``` Here is similar topic but with exporting to md files split every single org headline in a org file to separate md/org files # Answer > 4 votes Try the following functions. Below it's your function adapted to split top level headlines into different Org files. ``` (defun my-org-export-each-level-1-headline-to-org (&optional scope) (interactive) (org-map-entries (lambda () (let* ((title (car (last (org-get-outline-path t)))) (dir (file-name-directory buffer-file-name)) (filename (concat dir title ".org")) content) (org-narrow-to-subtree) (setq content (buffer-substring-no-properties (point-min) (point-max))) (with-temp-buffer (insert content) (write-file filename)) (widen))) "LEVEL=1" scope)) ``` This one is the function you referred adapted to split every headlines into different Org files. ``` (defun my-org-export-each-headline-to-org (&optional scope) "Export each headline to an Org file with the title as filename. If SCOPE is nil headlines in the current buffer are exported. For other valid values for SCOPE see `org-map-entries'. Already existing files are overwritten." (interactive) ;; Widen buffer temporarily as narrowing would affect the exporting. (org-with-wide-buffer (save-mark-and-excursion ;; Loop through each headline. (org-map-entries (lambda () ;; Get the plain headline text without statistics and make filename. (let* ((title (car (last (org-get-outline-path t)))) (buffer (current-buffer)) (dir (file-name-directory buffer-file-name)) (filename (concat dir title ".org")) beg end) (setq beg (point)) (outline-next-preface) (setq end (point)) (with-temp-buffer (insert-buffer-substring buffer beg end) (write-file filename)))) nil scope)))) ``` --- Tags: org-mode, org-export ---
thread-46678
https://emacs.stackexchange.com/questions/46678
org-fill-paragraph in a list with checkboxes doesn't take into account the checkboxes
2018-12-19T07:46:20.210
# Question Title: org-fill-paragraph in a list with checkboxes doesn't take into account the checkboxes I'm trying to figure out a way to change the behavior of org-fill-paragraph for a list with checkboxes. I would like the indentation to take into account the checkbox, but here is what I see: ``` - This is a long line in a plain list and fill-paragraph works as I expect it would (it takes into account the marker for the list in the indentation) - [ ] But when I write a long line with a checkboxed list, the behavior of fill-paragraph is to ignore the checkbox and indent as if the checkbox is not there - [ ] This is the way I would like to see a long line in a checkboxed list. Currently, the only way I can achieve it is by manually adding spaces in the beginning of the line ``` I realize that some people may prefer the current behavior, but is there a way for me to achieve my desired behavior? Thanks # Answer > 3 votes The key is to play with `adaptive-fill-function` which should return a fill-prefix, a string which prefix newlines of the filled item. It will work because the call chain is `org-fill-paragraph` \> `org-fill-element` \> `fill-region-as-paragraph` \> `fill-context-prefix`. If you `C-h f fill-context-prefix`, it says > Compute a fill prefix from the text between FROM and TO. This uses the variables ‘adaptive-fill-regexp’ and ‘**adaptive-fill-function**’ and ‘adaptive-fill-first-line-regexp’. ‘paragraph-start’ also plays a role; we reject a prefix based on a one-line paragraph if that prefix would act as a paragraph-separator. and `C-h v adaptive-fill-function` says > Function to call to choose a fill prefix for a paragraph. A nil return value means the function has not determined the fill prefix. First, define the function below. Its job is returning a string of spaces whose the length is the one of `- [ ]` if your are in a item, otherwise `nil`. ``` (defun my/item-cb-fill-function () (save-excursion (when-let* ((beg (org-in-item-p)) (beg-line-end (save-excursion (goto-char beg) (line-end-position))) (line (buffer-substring-no-properties beg beg-line-end)) (match (string-match "\\([[:space:]]*-[[:space:]]*[][ ]+\\).*" line))) (make-string (length (match-string 1 line)) ? )))) ``` Now you can define your custom `org-fill-paragraph` : ``` (defun my/org-fill-paragraph (&optional justify region) (interactive) (let ((adaptive-fill-function #'my/item-cb-fill-function)) (org-fill-paragraph justify region))) ``` --- Tags: org-mode, fill-paragraph ---
thread-66831
https://emacs.stackexchange.com/questions/66831
Mollyguard specific functions (delete-frame)?
2021-07-24T21:20:50.820
# Question Title: Mollyguard specific functions (delete-frame)? I have recently started using multiple frames regularly. I keep accidentally hitting `C-x 5 0` instead of `C-x 5 o`. I do want to still be able to close frames, but I want an "are you sure? (y/n)" or similar prompt first. Is there anything built-in that can simply wrap a function in to prompt, or am I left inventing my own lisp to do so? I am hoping for something generic that I can easily reuse for other functions/hotkeys. Google gives me numerous but unrelated results. # Answer A popular `y/n` built-in function is `y-or-n-p`. To write up this answer, I first typed `C-h k C-x 5 0` and saw that it was bound to `delete-frame` with two optional arguments being `FRAME` and `FORCE`; i.e., the `*Help*` buffer displayed (in part): `(delete-frame &optional FRAME FORCE)`. From there, I wrote up a simple function and rebound `C-x 5 0` to the new function. Stringing together functions and rebinding keyboard shortcuts to suit the needs of a particular user is, in my opinion, the Emacs way of doing things. The variable `ctl-x-5-map` is defined in `subr.el`. ``` (defun my-delete-frame (&optional frame force) "My doc-string." (interactive) (if (y-or-n-p "Shall we execute `delete-frame'?: ") (delete-frame frame force) (message "my-delete-frame: You have chosen _not_ to execute `delete-frame'!"))) (define-key ctl-x-5-map "0" 'my-delete-frame) ``` > 1 votes --- Tags: key-bindings, minibuffer, prompt, confirmation ---
thread-66823
https://emacs.stackexchange.com/questions/66823
How to execute parameterized src block via elisp and get result?
2021-07-24T01:49:33.967
# Question Title: How to execute parameterized src block via elisp and get result? I have a src block to get a value from some table: ``` #+NAME: ref #+BEGIN_SRC emacs-lisp :var name="" table=main (let ((key (if (symbolp name) (symbol-name name) name))) (nth 2 (assoc key table))) #+END_SRC ``` In Org I can execute this by: ``` #+CALL: ref("value") ``` How can I do the same only in Lisp? I tried this: ``` (defun a/ref (params) (save-excursion (goto-char (point-min)) (org-babel-goto-named-src-block "ref") (org-babel-execute-src-block nil nil params) (org-babel-read-result))) (a/ref '(("value"))) ``` But it didn't work # Answer > 2 votes I think what you are looking for is related to the library of babel. In this example, I construct something similar to the babel-call org element and use it to get the info needed for `org-babel-execute-src-block` to execute it with the argument. ``` #+name: main | x | 1 | a | | value | 2 | b | #+NAME: ref #+BEGIN_SRC emacs-lisp :var name="" table=main (let ((key (if (symbolp name) (symbol-name name) name))) (nth 2 (assoc key table))) #+END_SRC #+call: ref("value") #+RESULTS: : b The equivalent in elisp is: #+BEGIN_SRC emacs-lisp (org-babel-execute-src-block nil (org-babel-lob-get-info '(babel-call (:call "ref" :arguments "\"value\"")))) #+END_SRC #+RESULTS: : b ``` --- Tags: org-mode, org-babel ---
thread-66834
https://emacs.stackexchange.com/questions/66834
How to remove emacs frametitle and surrounding space
2021-07-25T00:56:08.270
# Question Title: How to remove emacs frametitle and surrounding space (setq frame-title-format "") removes the emacs frame title but leaves a blank space. How can I remove this blank space? I want to remove this blank space so that I have more screen space for viewing the buffer on a small laptop screen. # Answer You need to have emacs built with an option to eliminate the titlebar entirely. If you use emacs-plus this is easy. Build with the --no-titlebar option. One complication is that you'll then need to use a tiling window manager to manage emacs frames. > 0 votes --- Tags: frame-title-format ---
thread-5359
https://emacs.stackexchange.com/questions/5359
How can I troubleshoot a very slow Emacs?
2014-12-14T01:39:11.973
# Question Title: How can I troubleshoot a very slow Emacs? I am writing a document and I have a problem with Emacs' performance that I think appeared just yesterday. I haven't made any alterations in my init file or installed any new packages. The problem is that while I am writing, there's a very noticeable lag between pressing the letters on the keyboard and having them show up on the screen. Sometimes I watch them still printing on the screen after I have finished typing the word. I don't know if there are other issues except the speed of typing (I can only guess that there are) but I haven't noticed them. **What can cause this problem?** Is it caused by Emacs or it is due to my pc's performance? Generally what are the variables that affect Emacs' performance? *My Emacs' version is GNU Emacs 24.3.1* The major active mode is: 1. LaTeX and the minor active modes are: 1. Auto-Complete 2. Auto-Composition 3. Auto-Compression 4. Auto-Encryption 5. Blink-Cursor 6. File-Name-Shadow 7. Font-Lock 8. Global-Auto-Complete 9. Global-Font-Lock Global-Hl-Line 10. Line-Number 11. Mouse-Wheel 12. Shell-Dirtrack 13. Show-Paren 14. Smartparens 15. Smartparens-Global 16. Tooltip Transient-Mark # Answer > 89 votes > What can cause this problem? Is it caused by Emacs or it is due to my pc's performance? Generally what are the variables that affect Emacs' performance? Emacs has around 50,000 internal variables and a few thousand external packages averaging at a few dozen variables each, you can't expect someone to answer this in a general sense. :-) You can see that just by looking at the comments thread under your question. There are half a dozen different suggestions in there, all equally valid. # What can you do to pinpoint the problem? ### Option 1: Disable modes Start disabling those minor-modes you've listed, and see which one solves you performance issue. I would start with `smartparens`, `auto-complete`, `line-number` and `font-lock`, and then follow down the list. *"I didn't have this problem yesterday"* means very little, **don't rely on it** too heavily. Just start disabling minor-modes until something solves it. If none of the minor-modes fix your issue, then start commenting out portions of your init file until you find out which snippet was causing this. In any case, ask a new question when you have something more specific. ### Option 2: The profiler 1. Invoke `M-x profiler-start RET RET` (the second `RET` is to confirm `cpu`); 2. Do some typing, preferably an entire paragraph or more; 3. Invoke `M-x profiler-report`. That will give you a buffer describing the cpu time taken by each function. Hitting `TAB` on a line expands it to display the functions inside it. Navigate this buffer until you find out which function is taking so much CPU time. # What do I do afterwards? Once you find the function or package or snippet causing lag you can (in no particular order): * Ask a new question here regarding **that specific minor-mode** (or function or snippet). * Report a bug to the package maintainer. + Check the comments at the top of the package's source file. If it contains a URL (specially on github), there's probably an issue tracker there. + Some packages offer a command like `M-x PACKAGE-bug-report`. + His or her email should be at the top of the package's source file. * If it's a built-in package, you can report it with `M-x report-emacs-bug`. * Even for packages that are not built-in, you can ask for help at the `help-gnu-emacs` mailing list. # Answer > 6 votes In addition, there is also a potential factor that will *significantly* slow down Emacs: **Font Configuration**. It may sound amusing, but it *really* matters. If there are lots of non-Latin characters that can't be found in most fonts (for example, CJK) in your buffer, it will take a long time for Emacs to get the fallback font, thus making it very slow. If this is the case, making a proper font configuration will be very likely to solve the problem. For example, if you are using Chinese heavily (like me), one lazy solution should be getting a proper font that supports Chinese (such as Sarasa Gothic, whose non-CJK parts are also well-designed) and then make it the default via Options -\> Set Default Font... or by putting something like this in your `.emacs` file: ``` (custom-set-faces '(default ((t (:family "Sarasa Fixed SC" :foundry "outline" :slant normal :weight normal :height 120 :width normal))))) ``` Since I don't know the details about what kind of script the OP is using, I cannot offer more suggestions. However, this solution is often overlooked! (PS: When I was using Emacs on Windows for the first time, it was unbearably slow when reading the tutorial in Chinese, even though I hadn't installed any packages. After a proper font configuration, everything went well.) # Answer > 1 votes Org-mode is capable of being the cause of Emacs running slow. Org-mode files can grow to massive size without you noticing (thanks to the collapsed headings), and the mere existence of a buffer visiting such a file is enough to slow Emacs to a crawl, even if you have no frames that show the buffer. Killing the buffer or switching it to text-mode will return Emacs to normal speed. --- Tags: performance ---
thread-66837
https://emacs.stackexchange.com/questions/66837
:tstart and :tend not seeming to work in org-clock-table, however, :block does seem to work
2021-07-25T05:16:39.907
# Question Title: :tstart and :tend not seeming to work in org-clock-table, however, :block does seem to work I can generate a clock table for the whole month with: ``` #+BEGIN: clocktable :scope agenda :maxlevel 5 :block 2021-07 :hidefiles t :fileskip0 t :link t ``` This properly generates a clock table showing all items in my agenda logged in July. Now, I want to restrict to only a specific range of days in July. I'm working off of the clocktable docs to achieve this. ``` #+BEGIN: clocktable :scope agenda :maxlevel 5 :block 2021-07 :tstart "<2021-07-22 Thu>" :tend "<2021-7-25 Sun>" :hidefiles t :fileskip0 t :link t ``` This doesn't work, it generates an identical table to the first one. ``` #+BEGIN: clocktable :scope agenda :maxlevel 5 :block nil :tstart "<2021-07-20>" :tend "<2021-7-25>" :hidefiles t :fileskip0 t :link t ``` This doesn't work, it generates a blank table (there are definitely times recorded in this range, by the way, I confirmed by generating tables in their buffers, and comparing the results to the working first example, so I know `agenda` is properly catching those files). ``` #+BEGIN: clocktable :scope agenda :maxlevel 5 :tstart "<2021-07-20>" :tend "<2021-7-25>" :hidefiles t :fileskip0 t :link t ``` This doesn't work, it generates an empty table as well. I thought perhaps the `block` is a parent filter, and that `:tstart` and `:tend` filter within that filter, so I tried. ``` #+BEGIN: clocktable :scope agenda :maxlevel 5 :block 2021 :tstart "<2021-07-20>" :tend "<2021-7-25>" :hidefiles t :fileskip0 t :link t ``` This generates a table for the whole year, with the caption ``` #+CAPTION: Clock summary at [2021-07-25 Sun 13:15], for the year 2021. ``` No errors, the only message I get is `Updating dynamic block ‘clocktable’ at line 8...done`. **What's the correct way to use `:tstart` and `:tend` to generate an org-clock-table that covers a specific range of days?** # Answer > 2 votes This works for me: ``` #+BEGIN: clocktable :scope org-agenda-files :tstart "<2021-07-01 Thu>" :tend "<2021-07-25 Sun>" :maxlevel 8 :hidefiles t :fileskip0 t :link t ``` Looks like you should write "\<2021-**07**-25"\> instead of "\<2021-**7**-25"\>. (P.S. no `:block` needed). Cf. `C-h f org-parse-time-string` and `C-h v org-ts-regexp0`. --- Tags: org-mode, org-clock-table ---
thread-66840
https://emacs.stackexchange.com/questions/66840
How do I bind C-x <someKey> to a key in god-mode?
2021-07-25T10:13:55.823
# Question Title: How do I bind C-x <someKey> to a key in god-mode? I really like god-mode (https://github.com/emacsorphanage/god-mode), but one thing that bothers me about it is that i use commands such as C-x k, C-x b, C-x 1 ect. all the time. It doesnt feel efficient to have to use 3 key presses in god-mode to execute them (x 'space' 'someKey'). I never use the C-q command (Quoted-insert), so **How can I make the 'q' key do the equivalent of "x 'space'" when in god-mode?** I would like to be able to do the following: q 1 === x 'space' 1 === C-x 1 === delete-other-windows q o === x 'space' o === C-x o === other-window ect. Without having to write a lot of individual bindings in my init.el. Here is an excerpt from my current god-mode config: ``` (defcustom god-mode-alist '((nil . "C-") ;;Control ("g" . "M-") ;;Meta ("G" . "C-M-") ;;Control+Meta ("m" . "C-M-") ("z" . "s-") ;;Super ("i" . "H-") ;;Hyper ("t" . "A-") ;;Alt ("q" . "A-") ;;Alt ) "List of keys and their associated modifer." :group 'god :type '(alist)) (require 'god-mode) (god-mode) (global-set-key (kbd ";") #'god-mode-all) (global-set-key (kbd "C-;") #'god-mode-all) (global-set-key (kbd "C-'") (lambda ()(interactive)(insert-char #x3B))) ;"insert semicolon" (setq god-exempt-major-modes nil) (setq god-exempt-predicates nil) (define-key god-local-mode-map (kbd ".") #'repeat) ... (global-set-key (kbd "A-o") (kbd "C-x o")) ;other-window (global-set-key (kbd "A-b") (kbd "C-x b")) ;switch-to-buffer (global-set-key (kbd "A-u") (kbd "C-x u")) ;undo (global-set-key (kbd "A-0") (kbd "C-x 0")) ;delete-window (global-set-key (kbd "A-1") (kbd "C-x 1")) ;delete-otherwindows (global-set-key (kbd "A-2") (kbd "C-x 2")) ;split-window-below (global-set-key (kbd "A-3") (kbd "C-x 3")) ;split-window-right ... ``` So right now I just bind q to the "Alt" modifier key, and then create a lot of manual bindings, which is also a sad waste of a good modifier key. If it is possible to create a function for it, then I think I could bind the function to the q key like this: (define-key god-local-mode-map (kbd "q") #'some-function) like I did when I bound the "." key to the repeat function. # Answer One option is: ``` (with-eval-after-load "god-mode" (define-key god-local-mode-map "q" ctl-x-map)) ``` That won't account for keys bound in non-global keymaps, which may or may not be an issue. If you need this to work for arbitrary key bindings, https://emacs.stackexchange.com/a/66633/454 is an answer to a similar question, and you could use the same `unread-command-events` approach here. > 0 votes --- Tags: key-bindings ---
thread-66826
https://emacs.stackexchange.com/questions/66826
Set the default background color in spacemacs
2021-07-24T14:25:16.820
# Question Title: Set the default background color in spacemacs I'm trying to set the default background color to black in spacemacs. I'm setting the following theme in my `init.el` file: ``` dotspacemacs-themes '(afternoon molokai) ``` In my `user-config.el` file I've tried setting the background color as follows: ``` (set-background-color "black") ``` I've also tried setting the default font's background color: ``` (custom-set-faces '(default ((t (:background "black"))))) ``` I can see it flicker to black during startup but then it goes back to the theme color (which is `#181A26`) How can I get this to stick? # Answer It looks like setting background color using `set-background-color` is the right way to go. I had some code that was setting up (but not using) transparency which seems to have messed up the background color for some reason. > 0 votes --- Tags: spacemacs, themes ---
thread-66849
https://emacs.stackexchange.com/questions/66849
How to move to the next highlight?
2021-07-26T08:13:10.933
# Question Title: How to move to the next highlight? How can I jump to the next beginning of a string highlighted by a command such as `highlight-regexp` or `highlight-lines-matching-regexp`? # Answer > 2 votes C-u C-s allows you to search for a regexp forward. C-s again recalls the last regexp used. The following function finds the beginning of the next highlighted region. It prompts for a highlight color so that is not really comfortable. I know it but I do not know the exact circumstance you want to use it. You can easily improve it. ``` (defun beginning-of-next-highlighted-region (&optional hl) "Moves the point before the first following character that highlighted with the HL highlight or at end of buffer" (interactive (list (hi-lock-read-face-name) )) (while(let ((fc (get-text-property (point)'face) )) (and (consp fc )(memq hl fc) )) (forward-char)) (while (let ((fc (get-text-property (point)'face) )) (or (not (consp fc )) (not (memq hl fc)))) (forward-char))) ``` You can bind it at any key sequence you want ``` (bind-key (kbd "C-c h") #'beginning-of-next-highlighted-region) ``` --- Tags: highlighting, motion ---
thread-66851
https://emacs.stackexchange.com/questions/66851
Include subtree header in filename when exporting subtree from org-mode
2021-07-26T12:21:41.147
# Question Title: Include subtree header in filename when exporting subtree from org-mode At $dayjob I take notes using org-mode and from time to time end up sharing these as exported PDF's or HTML files. When I export a subtree these notes end up overwriting the same file over and over again, the file `workbook-2021.pdf` when using i.e. `C-c C-e C-s l p`. I would like to have subtrees export to a file named `workbook-2021-headline.pdf`. Using code shared by Melioratus on the Emacs Stack Exchange I was able to write a function that finds the current headline and removes non-alphanumeric characters. ``` (defun headline-title() (let* ((headline (save-mark-and-excursion (outline-previous-heading) (org-element-property :title (org-element-at-point))))) (replace-regexp-in-string "[^[:alnum:]-_]" "-" headline))) ``` I then want for this string to be appended to the filename of the current org-file when exporting the subtree. So given the following file named `export-subtree.org` and that the cursor is standing under the heading of "Works of wizards" then the file name would be `export-subtree-Works-of-wizards.pdf`: ``` * Week 1 ** 2021-01-01 *** Concerning Hobbits A word or two about their lore. *** Works of wizards Many more about wandering| wizards. ``` But this is where my Emacs foo comes short. I really don't know where to start. Because I do not want to be adding a property to every headline I want to export with a different name as many other answers on this network suggests. # Answer > 2 votes Try this function: ``` (defun my/org-export-headline (&optional backend async subtreep visible-only body-only ext-plist) "Export the current Org headline using BACKEND. The available backends are the ones of `org-export-backends' and 'pdf. When optional argument SUBTREEP is non-nil, transcode the sub-tree at point, extracting information from the headline properties first. When optional argument VISIBLE-ONLY is non-nil, don't export contents of hidden elements. When optional argument BODY-ONLY is non-nil, only return body code, without surrounding template. Optional argument EXT-PLIST, when provided, is a property list with external parameters overriding Org default settings, but still inferior to file-local settings." (interactive) (let* ((backend (unless backend (intern (completing-read "Available backends: " (append org-export-backends '(pdf)))))) (headline (car (last (org-get-outline-path t)))) (headline-alnum (replace-regexp-in-string "[^[:alnum:]-_]" "-" headline)) (file-prefix (file-name-sans-extension (buffer-file-name))) (filename (format "%s-%s.%s" file-prefix headline-alnum (if (eq backend 'pdf) "tex" backend)))) (org-narrow-to-subtree) (org-export-to-file (if (eq backend 'pdf) 'latex backend) filename async subtreep visible-only body-only ext-plist (when (eq backend 'pdf) (lambda (file) (org-latex-compile file)))) (widen))) ``` Usage: `M-x my/org-export-headline` and select a backend (*e.g.* pdf, html, etc.). It may look over-complicated, but it is in fact really simple. To let it support pdf export, I inspired myself from `org-latex-export-to-pdf` which unfortunately force you to use its filename. I also make it support `org-export-to-file` extra parameters as `org-latex-export-to-pdf` does and copy-pasted its docstring. If you ignore the conditional `(if (eq backend 'pdf) ...)`, it's really a matter of narrowing, `org-export-to-file`, then widening. --- Tags: org-mode, org-export ---
thread-66855
https://emacs.stackexchange.com/questions/66855
How do you insert propertized text with keymap and mouse-face
2021-07-26T17:39:39.360
# Question Title: How do you insert propertized text with keymap and mouse-face I am trying to insert propertized text that is clickable like this: ``` (let ((buf (get-buffer-create "*test*"))) (with-current-buffer buf (read-only-mode -1) (erase-buffer) (org-mode) (insert (propertize "clickable" 'font-lock-face '(:foreground "red") 'keymap (let ((map (make-sparse-keymap))) (define-key map (kbd "<mouse-1>") (lambda () (interactive) (message-box "clicked"))) map) 'mouse-face 'highlight 'help-echo "Bad key, click to replace.")) (read-only-mode +1)) (display-buffer-in-side-window buf '((side . right)))) ``` However, The keymap and mouse-face properties seem to be lost and I only see these properties: ``` There are text properties here: font-lock-face (:foreground "red") fontified t help-echo [Show] [back] ``` Am I missing some critical thing that causes these to be stripped out? # Answer (Changing my comment to a (partial) answer, as comments can be deleted at any time.) If you comment out the sexp `(org-mode)` then your initial code works (except for the red text, for which you'd need to use property `face`, not `font-lock-face`, or else define font-locking for your buffer). Maybe check which part of Org mode is interfering. > 0 votes # Answer This is a solution that works to make clickable text like I wanted. ``` (let ((buf (get-buffer-create "*test*"))) (with-current-buffer buf (read-only-mode -1) (erase-buffer) (org-mode) (insert-button "clickable" 'face '(:foreground "red") 'keymap (let ((map (make-sparse-keymap))) (define-key map (kbd "<mouse-1>") (lambda () (interactive) (message-box "clicked"))) map) 'mouse-face 'highlight 'help-echo "Bad key, click to replace.") (read-only-mode +1)) (add-text-properties (point-min) (point-max) '(mouse-face highlight)) (display-buffer-in-side-window buf '((side . right)))) ``` I am still not sure why the keymap and mouse-face properties get stripped in the original question though. I guess the difference is this uses an overlay. If I use `insert-text-button` it also does not work as desired. > 0 votes --- Tags: org-mode, text-properties ---
thread-66861
https://emacs.stackexchange.com/questions/66861
Change org-html-home/up-format locally within an org file
2021-07-26T22:56:28.660
# Question Title: Change org-html-home/up-format locally within an org file Looking for a way to change the org-html-home/up-format within my org file. I've learned that you can change the variable within emacs via: ``` (setq org-html-home/up-format "<a href=\"%s\">Up</a> , <a href=\"%s\">Home</a>") ``` But I want to specify it within the file, similar to how you would specify options: ``` #+options: toc:nil ``` I've tried: ``` #+html_home/up_format: <p>Test</p> #+options: html-home/up-format:<p>Test</p> ``` with no luck and documentation is sparse. # Answer You will need to enable the `#+BIND` keyword by adding this to your init file and restarting emacs ``` (setq org-export-allow-org-bind-keywords t) ``` You can also customize this variable (which allows you to skip the restart). Then you can assign to export-related variables even if there is no option for them (as in this case), by adding the following header to your Org mode file: ``` #+BIND: org-html-home/up-format "<a href=\"%s\">Up</a> , <a href=\"%s\">Home</a>" ``` When you export the file, the `#+BIND` directive does the equivalent of the `setq` in your question. The binding is temporary and only lasts while you are exporting the file. You can find a description of this in the "Export Settings" section of the manual which you can get to with `C-h i g (org)Export settings`. > 1 votes --- Tags: org-mode, org-export, html ---
thread-66868
https://emacs.stackexchange.com/questions/66868
Do MELPA packages get updated automatically?
2021-07-27T17:50:33.070
# Question Title: Do MELPA packages get updated automatically? The website says they do: > Automatic updates - new commits result in new packages But I ask because if I go `M-x list-packages` and hit `U` there are many upgrades available for packages under the "melpa" archive. # Answer > 3 votes It means that MELPA packages are up-to-date towards upstream Git repositories. You still have to upgrade them yourself or using a package like `auto-package-update`. See also "Does use-package keep packages automatically updated?". --- Tags: package-repositories ---
thread-66871
https://emacs.stackexchange.com/questions/66871
Create a new named buffer with a function
2021-07-28T05:21:15.407
# Question Title: Create a new named buffer with a function I want to create a keyboard shortcut that will prompt me for a string and then open a new `ansi-term` buffer with that string as the buffer name. How would I do this? # Answer To write-up this answer, I first typed `C-h f ansi-term RET` and saw that the `*Help*` buffer let me know that there are two possible arguments, one mandatory being `PROGRAM`, and the secondary optional being `NEW-BUFFER-NAME`. From there, I wrote the function `my-ansi-term` asking the user to input the `new-buffer-name` (if not provided programmatically), and to ask the user for the `program` name (if not provided programmatically) ... which will default to the same defaults that are included in the original function `ansi-term` if no `program` is specified. \[This information was derived by typing `M-x find-function RET ansi-term RET` and reading the code.\] I arbitrarily chose the keyboard shortcut of the `f5` key. Inasmuch as the variable `explicit-shell-file-name` is not defined in Emacs 27 until the library `term.el` is loaded, I chose to define it with a `nil` value (which is the default value in the aforementioned library). ``` (defvar explicit-shell-file-name nil) (defun my-ansi-term (&optional program new-buffer-name) "Doc-string." (interactive) (let ((program (if program program (read-string "PROGRAM: " nil nil (or explicit-shell-file-name (getenv "ESHELL") shell-file-name)))) (new-buffer-name (if new-buffer-name new-buffer-name (read-string "NEW-BUFFER-NAME: ")))) (ansi-term program new-buffer-name))) (global-set-key [f5] 'my-ansi-term) ``` > 1 votes --- Tags: buffers, functions ---
thread-66877
https://emacs.stackexchange.com/questions/66877
How to detect if a paragraph has been filled?
2021-07-28T12:02:55.443
# Question Title: How to detect if a paragraph has been filled? **Q:** how can I detect, programmatically, if a paragraph has been filled? `fill-paragraph` (synonyms fail me) fills a paragraph, and related `fill-*` functions do analogous things. Is there a way to detect, programmatically, if a paragraph has already been filled? # Answer > 0 votes Here is an ugly hack that works for me: ``` (defun fill-paragraph-p () (let ((hash (buffer-hash)) result) (save-excursion (fill-paragraph nil t) (setq result (equal hash (buffer-hash))) (prog1 result (unless result (undo-start) (undo-more 1)))))) ``` It's simple: hash the current buffer, fill the paragraph, then compare the hash of the buffer and the old hash. If it's the same, the paragraph is filled; otherwise, is not, and we undo `fill-paragraph`. --- Tags: fill-paragraph ---
thread-66729
https://emacs.stackexchange.com/questions/66729
Why does Slime have the two commands `C-down` and `M-n`?
2021-07-17T19:10:13.060
# Question Title: Why does Slime have the two commands `C-down` and `M-n`? I am new to the Common Lisp universe. In order to code in Common Lisp, I have started using Emacs and Slime (among other stuff, such as ParEdit). Emacs is another universe on its own. I realized that there are some counter-intuitive things in the emacs universe which, after a while, they start to make sense (such as using `C-n` instead of scroll down with the mouse or using the `down` arrow key). Sometimes, I need to see an explanation to clarify things and solve the classic "you do not know that you do not know" problems. One thing that intrigues me on Slime is the commands `M-n` and `C-down`. Both do roughly the same thing. Using the describe-key command I can see the definitions: > M-n runs the command slime-repl-next-input (found in slime-repl-mode-map), which is an interactive Lisp function in ‘slime-repl.el’. > > It is bound to M-n, . > > (slime-repl-next-input) > > Cycle forwards through input history. See ‘slime-repl-previous-input’. > > With a prefix-arg, do replacement from the mark. And: > C-down runs the command slime-repl-forward-input (found in slime-repl-mode-map), which is an interactive Lisp function in ‘slime-repl.el’. > > It is bound to . > > (slime-repl-forward-input) > > Cycle forwards through input history. What is the rationale of having both? Just giving the users an option to use arrow keys and another option that avoids arrow keys? Am I missing something about its architecture/design? # Answer You were close to figure it out, but you needed to dig a little bit deeper. These commands are completely different beasts. I'll explain with an example, using `slime-repl-previous-input` (bound to `M-p`) and `slime-repl-backward-input` (bound to `C-up`), without loss of generality. Start the REPL and evaluate the following s-exps: `(* 2 2)` and `(+ 2 2)`. At the next prompt, calling either of the functions does the same. What if you type `(+ M-p`? (Think for a while). Bingo, you're asking to get all of the previous commands that start with `"(+"`! Whereas typing `(+ C-up` would simply scroll up through all the history. In practice, I don't ever use `C-up/down`. Why are those commands there? Because on a typical bash shell, you cycle through commands with the up/down arrow keys. Notice that in Slime you need to prefix it with Control, otherwise you'd be moving the cursor up/down lines. Yes, Emacs is 2-dimensional, whereas the command line is 1-dimensional. Tip: If you're a beginner, don't use a nuclear power station to power a laptop. Before using ParEdit, take a look at `(info "(emacs) Parentheses")`. Copy this s-exp into Emacs and evaluate it with `C-x C-e`. > 1 votes --- Tags: repl, slime ---
thread-66888
https://emacs.stackexchange.com/questions/66888
Disabling memory consuming gifs in eww mode
2021-07-28T20:36:45.090
# Question Title: Disabling memory consuming gifs in eww mode I am looking for a way to disable or remove aspects of a page which might too memory intensive. For instance this page when opened in eww readable mode has a gif which hogs a lot of the memory. Is there a way to disable the gif at the top of the page or even to remove parts of the page? Thanks so much! # Answer > 1 votes There is indeed! Add the following to your `init.el`: `(setq shr-image-animate nil)`. --- Tags: eww ---
thread-40781
https://emacs.stackexchange.com/questions/40781
indent cl-loop to respect `if else` statements
2018-04-01T12:07:32.010
# Question Title: indent cl-loop to respect `if else` statements I have a hard time writing and reading cl-loops with they way they're indented by default as I can't easily tell what the control flow is: ``` (cl-loop for x below 10 if (cl-oddp x) collect x into odds and if (memq x funny-numbers) return (cdr it) end else collect x into evens finally return (vector odds evens)) ``` I'd like it to be indented like how it's shown in its documentation: ``` (cl-loop for x below 10 if (cl-oddp x) collect x into odds and if (memq x funny-numbers) return (cdr it) end else collect x into evens finally return (vector odds evens)) ``` I know this has to do with `Indenting Macros` manual page. And possibly this question on indenting a common lisp loop in emacs. Additionally, I've looked at a post on irreal and this question on the indentation of lisp forms. The general idea I got from reading is to use `(declare (indent n))` where n is an integer. I see this works for simple examples. However, how I want the `cl-loop` to be indented seems too complex for this. I need to tell emacs to recognize the specific `if` `else` keywords in the cl-loop. I am confused as I don't see a clear way to properly indent `cl-loop`. Any ideas? # Answer > 0 votes It seems that you can achieve your desired indentation style by doing ``` (setq lisp-indent-function 'common-lisp-indent-function) ``` --- Tags: indentation, cl-lib ---
thread-66878
https://emacs.stackexchange.com/questions/66878
Yasnippet-snippets indention not correct for Python functions
2021-07-28T12:11:32.477
# Question Title: Yasnippet-snippets indention not correct for Python functions Yasnippet-snippets contains a snippet for Python mode to create a function with a docstring. The indention is not correct when I use it, I think it maybe has to do with some Spacemacs settings, but I can not find the source. Are you using spacemacs and does this snippet indent correctly for you? See here for Github issue. # Answer You need the following to preserve the spaces or tabs. ``` # expand-env: ((yas-indent-line 'fixed) (yas-wrap-around-region 'nil)) ``` > 0 votes --- Tags: python, yasnippet ---
thread-66891
https://emacs.stackexchange.com/questions/66891
org mode agenda - load new org files without restart
2021-07-29T00:02:14.327
# Question Title: org mode agenda - load new org files without restart I am new to org and agenda, so this might be a newbie question... I like to keep my daily notes in date-stamped files, and using the code snips below I am able to have emacs load them on startup. **But** if I add a new .org file to `~/org/daily-notes` **after** emacs is running, I have to completely restart to make it show up on the agenda :( In my startup .el code I have tried the following two solutions: ``` (after! org (setq org-agenda-files (directory-files-recursively "~/org/" "\\.org$"))) ``` and ``` (after! org (setq org-agenda-files '("~/org/daily-notes/" "~/org/projects"))) ``` both of these successfully load .org files, the first one searches sub-directories. I don't expect emacs to magically watch the directory, but there has to be some command I can run to re-consume those folders... Thank you for your help :) # Answer I can think of three methods (in the following, for definiteness, I assume you use the recursive method to construct `org-agenda-files` in your init file; the changes required for the list method should be obvious). In increasing order of complexity: **Interactively add every new agenda file** If you create a new file, add content and at some point you decide that the file needs to contribute to your agenda, you can add the file to `org-agenda-files` using `C-c [` (which is bound to `org-agenda-file-to-front`). If you then create a new agenda, or refresh an existing one with `g`, the file will contribute to the agenda during the current emacs session. If you save the file in a directory that is used to set `org-agenda-files` during initialization (e.g. with your recursive setting above, you save it in the file `~/org/my_subdir/my_file.org`, i.e. in a subdirectory of `~/org` with a file name that has a `.org` suffix), the initialization code will include that file in `org-agenda-files` every time afterwards, so it will contribute to your agenda. **Re-evaluate `org-agenda-files` on demand** Instead of interactively adding files, you can create a bunch of them, save them under the `~/org` directory, in files whose name have the `.org` suffix, and then after you are done and before you recreate/refresh the agenda, re-evaluate `org-agenda-files`. That can be done in various ways: switch to the `*scratch*` buffer, type the same sexpr that you used in the init file: ``` (setq org-agenda-files (directory-files-recursively "~/org/" "\\.org$")) ``` and then press `C-j`: the `*scratch*` buffer should be in `lisp-interaction-mode` where `C-j` is bound to `eval-print-last-sexp`. That will give a new value to `org-agenda-files` and print it out so you can verify it. Recreating/refreshing the agenda will use the new value of `org-agenda-files` so the newly added files will contribute to it. Slight variations of this are: * re-evaluate by opening your init file, finding the expression that initializes `org-agenda-files` in the first place, position the cursor after the closing paren and pressing `C-x C-e`: the init file should be in `emacs-lisp-mode` (like all `.el` files) where `C-x C-e` is bound to `eval-last-sexp`. In this case the value is printed in the `Echo Area` (and will be probably elided because it will be too long), but also in the *Messages* buffer where you can go and verify it. * you can write a command to do the re-evaluation and bind it to a key: ``` (defun ndk/refresh-org-agenda-files () (interactive) (setq org-agenda-files (directory-files-recursively "~/org/" "\\.org$"))) ;; I'm assuming that `C-c z` - one of the keys that is reserved for ;; end-user use - is undefined. You can bind the function above to it ;; in the global map, so that it is always available - unless a mode redefines it... (global-set-key (kbd "C-c z") #'ndk/refresh-org-agenda-files) ;; ... or you add the binding to the org-mode-map, ;; so that it is only available in Org mode buffers. (define-key org-mode-map (kbd "C-c z") #'ndk/refresh-org-agenda-files) ``` Now pressing `C-c z` will execute the command and re-evaluate `org-agenda-files` based on the new contents. **Have emacs monitor the directory automatically** On Linux (and some other OSes), you can use `inotify` to monitor the directory: when some event happens, `inotify` can tell you about it and you can call e.g. the above function to refresh `org-agenda-files` when a change happens. The trick is to have *Emacs* do the listening and the refreshing automatically. The idea is to create an asynchronous sub-process that uses inotify to monitor changes to the directory and, when a change is detected, to run the function above to re-evaluate `org-agenda-files` using the newly-changed contents. Here is a bash command line that monitors a directory recursively: ``` inotifywait -e create -e delete -m -r ~/src/inotifywait/watched ``` Then when a file (or directory) is created or deleted in the `watched` directory or one of its subdirectories, the command prints out a message. E.g. here is what is printed out when I create and then delete a file `z` in the (already existing) `watched/e` subdirectory and then create and remove a subdirectory `f` under the `watched` directory: ``` $ inotifywait -e create -e delete -m -r ~/src/inotifywait/watched Setting up watches. Beware: since -r was given, this may take a while! Watches established. /home/me/src/inotifywait/watched/e/ CREATE z /home/me/src/inotifywait/watched/e/ DELETE z /home/me/src/inotifywait/watched/ CREATE,ISDIR f /home/me/src/inotifywait/watched/ DELETE,ISDIR f ... ``` The command runs continuously (because of the `-m` monitoring option), watches every subdirectory (`-r`) of the given directory, printing out messages to its *stdout* whenever a file or a directory is created or deleted under it. You should read the man page inotifywait(1) for all the gory details. One caveat: doing `-r` on a *large* directory hierarchy can have adverse effects on your system performance: `inotify` has to set up watches on *every* subdirectory (and depending on the events, perhaps on *every* file); doing it on a handful of directories with a few tens or hundreds of files should be no problem on a modern machine with lots of memory, but YMMV, so "Caveat Emptor"! Now to have *emacs* do all this: run the above command as an asynchronous subprocess, watch its output and whenever it sees something interesting in that output, call the above function to re-evaluate `org-agenda-files`. To start the process, you need to add something like the following bit of code to your init file (or evaluate it by hand if you want to test things out: `C-x C-e` after the closing paren in an `emacs-lisp` buffer will do it): ``` (setq ndk/inotify-org-agenda-process (make-process :name "ndk-inotify-org-agenda" :command `("inotifywait" "-e" "create" "-e" "delete" "-m" "-r" ,(expand-file-name "~/org")) :buffer (get-buffer-create "*ndk/inotify-org-agenda-process-buffer*") :connection-type 'pipe :stderr (get-buffer-create "*ndk/inotify-org-agenda-process-stderr*"))) ``` This uses the low-level `make-process` to create a process that runs the given command. It arranges so that the `stdout` of the command is inserted into the process buffer `*ndk/inotify-org-agenda-process-buffer*` and its `stderr` is inserted into the `*ndk/inotify-org-agenda-process-stderr*` buffer. If you evaluate this code and visit those two buffers, you should be able to see output from the command whenever you create or delete a file in the `~/org` directory or its subdirectories (it will also produce output when you create or delete a subdirectory, which we'll have to filter out, since the ultimate aim is to detect creation or deletion of Org mode files). We now have to add a `process filter` to the above, so that we can examine the output and act accordingly. Read the "Processes" chapter in the Emacs Lisp Manual with `C-h i g(elisp)Processes`. In particular, the section `Receiving Output from Processes` describes `process filters`. To add a process filter, we define a filter function and change the call to `make-process` above to specify the filter: ``` (setq ndk/inotify-org-agenda-process (make-process :name "ndk-inotify-org-agenda" :command `("inotifywait" "-e" "create" "-e" "delete" "-m" "-r" ,(expand-file-name "~/org")) :buffer (get-buffer-create "*ndk/inotify-org-agenda-process-buffer*") :connection-type 'pipe :filter #'ndk/inotify-org-agenda-process-filter :stderr (get-buffer-create "*ndk/inotify-org-agenda-process-stderr*"))) (defun ndk/inotify-org-agenda-process-filter (proc txt) (when (buffer-live-p (process-buffer proc)) (display-buffer (process-buffer proc)) (with-current-buffer (process-buffer proc) (let ((begin (marker-position (process-mark proc)))) ;; Insert the text, advancing the process marker. (goto-char (process-mark proc)) (insert-before-markers txt) (set-marker (process-mark proc) (point)) (goto-char (process-mark proc)) ;; the above is pretty generic: the reason we need a custom ;; filter function is so that we can test whether the process ;; output indicates that we should refresh ;; `org-agenda-files'. We remember where the previous output ;; had ended in `begin'; so the new output is the region ;; between `begin' and the current `point'. We pass that ;; information to the checker and if it returns non-nil, we ;; refresh `org-agenda-files'. (if (ndk/update-org-agenda-file-list? begin (point)) (ndk/refresh-org-agenda-files)))))) ``` If you don't specify a process filter, a default one is used that adds the output of the process to the process buffer. Here we define a custom filter that does the same thing but adds a few wrinkles. Filter functions take two arguments: the process and the string that the process has output since the last time the filter was called. We remember where the previous output ended, i.e. where our new output should go: that's the process mark. We make sure to go to that marker before inserting the new output, pushing any markers forward as we do so. We then set the process mark to the end of the new text and make sure that we go there (this should be a no-op, but a little paranoia never hurt). That's fairly generic: just about any filter would do a similar thing (but since this is the first filter I've ever written, if there are any problems, this is where I would look first: I wonder if this simple filter is *too* simple, although I have not seen any problems with it - yet). Now for the particular stuff: given the beginning and end of the insertion, we can always grab it and pass it to the checker to see if there are new files named 'foo.org' that were created; if so, we call `ndk/refresh-org-agenda-files` to go get the new list (the latter function was defined above). Although the checker should probably check e.g. that what was created or deleted was actually an Org file (and not e.g. a directory or a non-Org file), that's a bit involved and would make this long answer even longer. So I just provide a dummy implementation here which always returns `t` (i.e. whatever `inotify` reports, we *always* refresh `org-agenda-files`), and leave the "real" implementation to the interested reader: it's an exercise in parsing strings but does not have much to do with processes. Here's the dummy implementation: ``` (defun ndk/update-org-agenda-file-list? (begin end) " Check whether the contents of the buffer (assumed to contain the output of the inotify process) in the region between `begin' and `end', indicate that we need to refresh `org-agenda-files'." ;; This is a simple example that always returns `t' (i.e.*anything* ;; added to or removed from the directory will trigger a refresh of ;; `org-agenda-files'). ;; ;; But you could add some filtering, e.g. grab the contents of the ;; buffer using `buffer-substring' and parse it to figure out if the ;; file(s) that were added or removed should affect the agenda list ;; (e.g. adding or removing a subdirectory or a file that does not ;; end in `.org' should not trigger a a refresh). There may be some ;; addditional complications as well: it is not necessarily true ;; that the output of the command is spat out to the filter function ;; in one piece, so it may be necessary to deal with partial ;; lines. The simple implementation sidesteps these complications ;; but they must be kept in mind in general. t) ``` The comment describes some details of a possible implementation and some caveats that might arise (although I have not seen them in practice). If you want to kill the process and the associated buffers, here's a (rough-and-ready) function to do it: ``` (defun ndk/inotify-org-agenda-process-cleanup () (interactive) (delete-process ndk/inotify-org-agenda-process) (let ((kill-buffer-query-functions nil)) (kill-buffer "*ndk/inotify-org-agenda-process-buffer*") (kill-buffer "*ndk/inotify-org-agenda-process-stderr*"))) ``` Invoke with `M-x ndk/inotify-org-agenda-process-cleanup`. It kills the process and the two buffers, no questions asked, but it leaves a lot to be desired, in particular error handling. > 3 votes --- Tags: org-mode, org-agenda ---
thread-66864
https://emacs.stackexchange.com/questions/66864
Any Elisp equivalent of Python's inspect.cleandoc?
2021-07-27T14:06:12.417
# Question Title: Any Elisp equivalent of Python's inspect.cleandoc? When working with code generation, Python's `inspect.cleandoc` is quite useful, as it allows to write inline code in a multi-line string and then automatically adjust the indentation. ``` # -- Input: def generate_code(): return inspect.cleandoc(f""" if cond(): do_stuff() else: do_other_stuff() """) print(generate_code()) # -- Output: if cond(): do_stuff() else: do_other_stuff() ``` Is there any similar convenience function in Emacs Lisp? ## Motivation Since it came up: The motivation for the question was trying to improve the following snippet: ``` (with-temp-buffer (insert "\nimport os" "\nimport sys" "\ndef _dotemacs_shellsend_setup():" "\n sourcefile = " (format "%S" source-file) "\n sourcedir = os.path.dirname(sourcefile)" "\n print()" "\n print(f'Sending file {sourcefile}...')" "\n if os.getcwd() != sourcedir:" "\n os.chdir(sourcedir)" "\n print(f'{os.getcwd() = }')" "\n if sys.argv[:1] != [sourcefile]:" "\n sys.argv[:1] = [sourcefile]" "\n print(f'{sys.argv[0] = }')" "\n_dotemacs_shellsend_setup()") (python-shell-send-buffer nil msg)) ``` While editing this code, I several times ended up forgetting trailing newlines (hence moving them to the front), or accidentally deleting trailing double-quotes. What I want to do instead is something like ``` (with-temp-buffer (insert (UNKNOWN-FUNCTION (concat " import os" import sys" def _dotemacs_shellsend_setup(): sourcefile = " (format "%S" source-file) " sourcedir = os.path.dirname(sourcefile) print() print(f'Sending file {sourcefile}...') if os.getcwd() != sourcedir: os.chdir(sourcedir) print(f'{os.getcwd() = }') if sys.argv[:1] != [sourcefile]: sys.argv[:1] = [sourcefile] print(f'{sys.argv[0] = }') _dotemacs_shellsend_setup()") (python-shell-send-buffer nil msg)))) ``` The aim is to strip the common indentation of all lines, in order to generate correctly *not*-indented Python code, while keeping the indentation of the in-code template consistent with the surrounding code structure. While such a function wouldn't be *too* hard to write, I am interested in whether there is builtin functionality for this. # Answer I would just leverage python for this. ``` (shell-command-to-string (format "python -c \"import inspect; print(inspect.cleandoc('''%s'''))\"" (let ((source-file "test.py")) (concat " import os import sys def _dotemacs_shellsend_setup(): sourcefile = " (format "%S" source-file) " sourcedir = os.path.dirname(sourcefile) print() print(f'Sending file {sourcefile}...') if os.getcwd() != sourcedir: os.chdir(sourcedir) print(f'{os.getcwd() = }') if sys.argv[:1] != [sourcefile]: sys.argv[:1] = [sourcefile] print(f'{sys.argv[0] = }') _dotemacs_shellsend_setup()")))) ``` This outputs a string: ``` import os import sys def _dotemacs_shellsend_setup(): sourcefile = test.py sourcedir = os.path.dirname(sourcefile) print() print(f'Sending file {sourcefile}...') if os.getcwd() != sourcedir: os.chdir(sourcedir) print(f'{os.getcwd() = }') if sys.argv[:1] != [sourcefile]: sys.argv[:1] = [sourcefile] print(f'{sys.argv[0] = }') _dotemacs_shellsend_setup() ``` > 1 votes --- Tags: indentation ---
thread-66873
https://emacs.stackexchange.com/questions/66873
Pandas output in Scimax
2021-07-28T07:07:09.427
# Question Title: Pandas output in Scimax In Scimax, when I evaluate a pandas DataFrame (DF) in an Ipython block, ``` #+BEGIN_SRC ipython data = [ ['a', 'foo', 'bar'], ['FOO', 'and', 'BAR'] ] pd.DataFrame(data) #+END_SRC ``` It produces both a plain text representation of the DF as well as a pop-up html. I was wondering how I could disable this web page pop-up and possibly replace it with an inline image of the DF? # Answer > 0 votes This is a tricky issue. The formatting is controlled by functions that are set in `ob-ipython-mime-formatters`. The html formatting is controlled by `ob-ipython-format-text/html`. The issue is that the output is raw html, which is very inconvenient in an org-file, especially when it is very long. `ob-ipython-preview-html` was an approach to put an overlay on the html blocks. How that is done is in `ob-ipython-html-font-lock`. To get what you want, you should create a function like `ob-ipython-format-text/html` that would create a temp html file, run the html to image program, save it and put a link to the image that would show it. I have had mixed luck converting html to images. A reasonable alternative might be to just save the html to a file, and link to it. Some ways to suppress the html output are: Use `:display text/plain` in the src block header. or write your own formatter like this: ``` (defun my-format-html (_file _value) "") (setf (cdr (assoc 'text/html ob-ipython-mime-formatters)) 'my-format-html) ``` I am transitioning away from ob-ipython in scimax, and moving towards emacs-jupyter. # Answer > 1 votes I don't use Scimax. I had a look at the codebase and I suspect that adding the following to your `init.el` will fix it: `(setq ob-ipython-preview-html nil)` --- Tags: org-mode, org-babel ---
thread-67893
https://emacs.stackexchange.com/questions/67893
Never delete recentf entries
2021-07-29T09:49:12.690
# Question Title: Never delete recentf entries I have all my files in `recentf`, weeks of file visiting history ; But recently, entries have been randomly disappearing ; This is disrupting my workflow in a big, bad way. Questions: 1. How can I make sure that no external package is tampering with my `recentf` file? 2. If the former is not possible, then, is there a way to "watchdog" this file so that I know if and when something is being written to it? # Answer Customize `recentf-max-saved-items` and set it to `nil`. The doc string of the variable (`C-h v recent-max-saved-items`) says: > recentf-max-saved-items is a variable defined in ‘recentf.el’. Its value is 20 > > You can customize this variable. > > Documentation: > > Maximum number of items of the recent list that will be saved. A nil value means to save the whole list. See the command ‘recentf-save-list’. > 1 votes --- Tags: recentf ---
thread-61466
https://emacs.stackexchange.com/questions/61466
Is it possible to auto-save a file when focus is switch to another tab?
2020-10-29T13:09:28.957
# Question Title: Is it possible to auto-save a file when focus is switch to another tab? I am not sure that this possible but I have I two splitted panes while using `tmux` inside `iTerm2` and I am using `emacs daemon`. I am using `iTerm`'s keybinding to switch between tabs. One one of them `emacs` is open and on the another one `shell` is open. ``` --------------- |file |$ | | | | | | | --------------- ``` I usually make a change on the file and switch to other tab (that is on `shell`) to run the test. * During this whenever I switch to other tab is it possible for `emacs` to save the file automatically triggered by the iTerm's keybinding to switch between tabs without using `C-x C-s`? * If not from the shell can I force emacs save all its open files right before running its tests? # Answer > 1 votes The short answer is that Emacs running in a terminal cannot observe GUI events such as switching to another tab. If you want Emacs to observe GUI events, run a GUI Emacs. (This may be possible using a companion program, but even so this would depend to some extent on the goodwill of iTerm2. If it's at all possible, it's not easy and may have side effects in conditions that you may or may not care about such as attaching Emacs windows to terminals provided by different terminal emulators.) On the other hand, it's pretty easy to remotely ask Emacs to save. This assumes that you're running the Emacs server: either start Emacs with `emacs --daemon` or run `(server-start)` from your init file. To remotely ask Emacs to save all buffers, run the shell command ``` emacsclient -e '(save-some-buffers t)' ``` # Answer > 1 votes Take a look at `after-focus-change-function`. You can advise this function with an `:before` function to save all buffers. That's easily accomplished by using an anonymous function like: ``` (lambda () (save-some-buffers t)) ``` like @alper suggested. You can use the `advice-add` function or the `define-advice` macro like so ``` (advice-add 'after-focus-change-function :before #'(lambda () (save-some-buffers t))) ``` or ``` (define-advice after-focus-change-function (:before ()) (save-some-buffers t)) ``` # Answer > 0 votes super-save-mode to saves the buffer automatically when focus moves away from it. I do not use emacs in terminals, so I do not know if this works out of the box there, but I am pretty sure it can be configured to do what you want. --- Tags: auto-save ---
thread-66870
https://emacs.stackexchange.com/questions/66870
mu4e can't send mail "smtpmail-send-it: Sending failed: 502 5.7.0 anonymous login not supported"
2021-07-28T01:05:21.090
# Question Title: mu4e can't send mail "smtpmail-send-it: Sending failed: 502 5.7.0 anonymous login not supported" I am trying to configure mu4e protonmail. I can read my messages just fine, but attempting to send a message results in: ``` smtpmail-send-it: Sending failed: 502 5.7.0 anonymous login not supported ``` I followed these three links to the letter and they all result in the same error: ``` https://gist.github.com/azzamsa/174096975df0e16b5bf7e919ba90fce2/ https://doubleloop.net/2019/09/06/emacs-mu4e-mbsync-and-protonmail/ https://gist.github.com/A6GibKm/238b754a4a90051f60906b9efa3e8000 ``` I am running emacs-nox 27.2 on Arch Linux. If I can provide any additional information, please let me know. Edit 1: Some more info: When I attempt to send an email from protonmail (gmail works fine), emacs prompts this message: ``` Certificate information Issued by: 127.0.0.1 Issued to: Proton Technologies AG Hostname: 127.0.0.1 Public key: RSA, signature: RSA-SHA256 Session: TLS1.3, key: ECDHE-RSA, cipher: AES-256-GCM, mac: AEAD Security level: Medium Valid: From 2021-07-28 to 2041-07-23 The TLS connection to 127.0.0.1:1025 is insecure for the following reasons: * certificate signer was not found (self-signed) * the certificate was signed by an unknown and therefore untrusted authority * certificate could not be verified ``` It asks if I want to "Continue Connecting" in light of the above message. When I say yes, that is when I get the `anonymous login not supported` error that I discussed above. Edit 2: For reference, here is my protonmail context: ``` (make-mu4e-context :name "protonmail" :match-func (lambda (msg) (when msg (string-prefix-p "/m-soda-protonmail" (mu4e-message-field msg :maildir)))) :vars '((user-mail-address . "my email") (user-full-name . "my name") (mu4e-drafts-folder . "/protonmail/Drafts") (mu4e-sent-folder . "/protonmail/Sent") (mu4e-refile-folder . "/protonmail/All Mail") (mu4e-trash-folder . "/protonmail/Trash") (message-send-mail-function . smtpmail-send-it) (smtpmail-auth-credentials . "/home/marc/.config/mu4e/protonmailpass.gpg") (smtpmail-smtp-server . "127.0.0.1") (starttls-use-gnutls . t) (smtpmail-stream-type . starttls) (smtpmail-smtp-service . 1025)))) ``` # Answer > 0 votes I found the solution. My problem was probably caused by a bug. Correct me if I'm wrong. The key referenced by `smtpmail-auth-credentials` MUST be stored as ~/.authinfo.gpg Interestingly enough, the value assigned to `smtpmail-auth-credentials` (mine was "/home/marc/.config/mu4e/protonmailpass.gpg" above) can be anything. The function will always reference ~/.authinfo.gpg regardless of how it is assigned in your config file. I will do some more digging, and if it is indeed a bug, I will make report to the maintainer of mu4e. Hope this helps. --- Tags: mu4e, smtpmail ---
thread-3654
https://emacs.stackexchange.com/questions/3654
filename completion using company-mode
2014-11-17T15:37:54.727
# Question Title: filename completion using company-mode I enabled company using the following commands in my init.el: ``` (require 'company) (add-hook 'after-init-hook 'global-company-mode) ``` However I'm not getting filename completion, although there is some provider in the source and also the website mentions it's supported. I start typing /home/emmanuel... and nothing happens, although I would expect the completion to start offering options? Also, how does company-mode autodetect completion for relative paths, I think I read it's supported, but I'm not sure how it would detect it, without the initial "/" as a tip? # Answer > 8 votes You have to run `company-files` for file completion. You can bind a different map for the files completion completion with ``` (define-key global-map (kbd "C-.") 'company-files) ``` Also make sure you have the company-files in company-backends (`M-x` \> customize-group \> company \> company backends) # Answer > 15 votes As @Jesse already pointed out, what you want here is the `company-files` backend. There are several different ways to use it: 1. Bind a key to call `company-files` directly. 2. Use command `company-begin-backend`. This prompts you for the backend to use, then offers completion candidates. 3. Use `company-other-backend` to rotate through the list of backends (see next item). This can be used to trigger completion or it can be used after company mode has been triggered to switch to a different set of completion candidates. You may want to assign a key binding in the company map, e.g. `(define-key company-active-map (kbd "C-e") #'company-other-backend)` 4. Configure the variable `company-backends`. Company mode traverses this list in order to find a backend that accepts the current prefix (i.e. the text before point). It is entirely possible to have a backend in the list that accepts the current prefix but does not offer any completion candidates, at which point company mode won't auto-complete anything. You can customize the list to order the backends in a way that meets your needs. A few examples of modifying `company-backends`: If you only ever wanted to complete filenames, you could make that your only backend: ``` (setq company-backends '(company-files)) ``` That seems unlikely, so you're better off putting your most commonly used backend first and then using one of options mentioned earlier to switch backends or invoke one by name when you need something else. You can also configure a 'group' backend that creates a merged set of completion candidates. Try this, for example: ``` (setq company-backends '((company-capf company-dabbrev-code company-files))) ``` This specifies a single backend that merges the candidates from three other backends. It will give you results from completion-at-point, dabbrev, and the file system. You can use mode hooks to specify a different set of backends for different major modes. For example: ``` (add-hook 'org-mode-hook (lambda () (setq-local company-backends '((company-files company-dabbrev))))) (add-hook 'emacs-lisp-mode-hook (lambda () (setq-local company-backends '((company-capf company-dabbrev-code))))) ``` # Answer > 1 votes You must give either an absolute or a relative path to your eshell command, ``` $ cat ./some-file # yey! $ cat /another-file # yey! $ cat some-file # fail :( ``` Otherwise, the `company-files--grab-existing-name` function returns `nil`. You can edebug the said function and check that that is the case. Check and update the `company-files--regexps` to support the last case also if you feel brave enough and you are sure it doesn't break other stuff. --- Tags: completion, company-mode ---
thread-67902
https://emacs.stackexchange.com/questions/67902
reftex select buffer
2021-07-29T19:11:03.510
# Question Title: reftex select buffer I use auctex/reftex with pdftools for preview. I use a vertical split C-x 3 of the emacs frame with the left buffer being the pdf preview and the right buffer being the latex file. When I invoke reftex select buffer with keystrokes C-c ) the reftex buffer and latex buffer take the entire frame hiding the pdf preview. Is it possible to customize the reftex select buffer so that: (i) it appears only in the right half of the frame below my latex file and (ii) the reftex and latex buffers do not hide the pdf preview. # Answer Looking at the code, this is not possible by default. However, you could easily modify the code to achieve it. For that, change the line: ``` (switch-to-buffer-other-window "*RefTeX Select*") ``` in the function `reftex-select-with-char` to: ``` (select-window (display-buffer-below-selected (get-buffer-create "*RefTeX Select*") nil)) ``` and similar for the subsequent created windows (the code contains useful comments for 'discovering' lines/functions that create new windows). You might also submit a feature request to make it customizable (e.g. by using the function `display-buffer-in-direction`) to the bug-gnu-emacs mailing list. > 0 votes --- Tags: pdf-tools, reftex-mode ---
thread-66863
https://emacs.stackexchange.com/questions/66863
org-mode: How to have directory-wide file tags merged with tags at file level?
2021-07-27T12:45:37.243
# Question Title: org-mode: How to have directory-wide file tags merged with tags at file level? org-mode has the `org-file-tags` variable which is populated by the `#+FILETAGS` cookie at the file level. Would it be possible to specify file tags at directory level and still be able to specify additional file level tags inside the individual files? For example, to have this in `.dir-locals.el`, to mark all files in the "work" folder as "work": ``` (("work" . ((org-mode . ((org-file-tags . '("work"))))))) ``` and have in `work/project1.org`: ``` #+FILETAGS: :project1: * Header This header has both tags 'work' and 'project1'. ``` The problem with this setup is that the value in `.dir-locals.el` overwrites the local file tags, while I would like to have them merged. # Answer > 1 votes You could try this advice solution. It seems to work for me. The idea is get the filetags line and read it in a temp buffer, and then combine them with the original tags. The cadr line is a little odd, but the tags sometimes came out as quoted list, and that is how I unquoted it. ``` (defun get-buffer-filetags-advice (orig-func &rest args) (let ((orig-tags (apply orig-func args)) (ft (cadr (assoc "FILETAGS" (org-collect-keywords '("FILETAGS")))))) (when (eq 'quote (car orig-tags)) (setq orig-tags (cadr orig-tags))) (delete-dups (apply #'append orig-tags (with-temp-buffer (insert "#+filetags: " ft) (org-mode) (org-get-buffer-tags)))))) (advice-add 'org-get-tags :around 'get-buffer-filetags-advice) ;; to remove the advice ;; (advice-remove 'org-get-tags 'get-buffer-filetags-advice) ``` --- Tags: org-mode ---
thread-67907
https://emacs.stackexchange.com/questions/67907
Org mode: Simple "if" formula on my table throws an error
2021-07-30T23:22:16.067
# Question Title: Org mode: Simple "if" formula on my table throws an error I have a very simple table that looks like this: ``` | Fabricant | Catégorie | Animal | Nombre | |-----------+-----------+------------------------+--------| | Pearson | Camp | Bœuf | 1 | | Pearson | | Castor | 1 | | Pearson | | Chèvre | 2 | | Pearson | | Cougar | 2 | ``` On which I apply this `if` formula as I have seen on the org mode documentation: ``` #+TBLFM: $5 = if($4 < 2, test, string('')) ``` But it throws an error: ``` | Fabricant | Catégorie | Animal | Nombre | | |-----------+-----------+------------------------+--------+--------| | Pearson | Camp | Bœuf | 1 | #ERROR | | Pearson | | Castor | 1 | #ERROR | | Pearson | | Chèvre | 2 | #ERROR | | Pearson | | Cougar | 2 | #ERROR | ``` I'm very new to Org mode, Emacs and spreadsheet formulas in general so I don't know what I'm doing wrong. # Answer I don't know well the formula syntax for `calc`, but it seems that if you follow exactly the syntax of string constant that the documentation uses, it will work. Namely, replace `''` by `""`: ``` #+TBLFM: $5 = if($4 < 2, test, string("")) ``` Can't explain why, though. There is also a formula syntax for Emacs Lisp that you might find more intuitive. In your case, it translates to: ``` #+TBLFM: $5 = '(if (< (string-to-number $4) 2) "test" "") ``` which can be made shorter, as @gigiair pointed out, using `N` mode switch (all referenced elements will be numbers): ``` #+TBLFM: $5 = '(if (< $4 2) "test" ""); N ``` You might also find useful to toggle the formula debugger `org-table-toggle-formula-debugger` (`C-c {`) which would show you the expansion of the formula and an error message if applicable. > 3 votes --- Tags: org-mode, org-table, spreadsheet, formula ---
thread-67911
https://emacs.stackexchange.com/questions/67911
Tangle current src block and process it in another
2021-07-31T09:15:32.470
# Question Title: Tangle current src block and process it in another How can I run the `test` src block ****without leaving the `code` src block****? Currently I must leave `code`, goto `test`, hit `C-c C-c` , go back to continue work on `code` ``` #+NAME: code #+BEGIN_SRC sh :tangle /tmp/foo.sh foo="bar" #+END_SRC #+NAME: test #+BEGIN_SRC sh :var DUMMY=(progn (org-babel-goto-named-src-block "code") (org-babel-tangle '(4))) :results output echo "Process tests on this file": cat /tmp/foo.sh #+END_SRC #+RESULTS: : Process tests on this file: : foo="bar" ``` Using the promising looking `#+begin_src sh :tangle /tmp/foo.sh :var DUMMY=(progn (org-babel-goto-named-src-block "test") (org-babel-execute-src-block))` on the `code` src block returns `Lisp nesting exceeds ‘max-lisp-eval-depth’` --- Org mode version 9.4.5 # Answer > 1 votes Don't do it with babel: do it in lisp - define a function to do what you want and bind it to a key. You can then execute the function from anywhere using that key. Something like this: ``` #+begin_src elisp (defun ndk/org-babel-evaluate-test-block-from-code-block () (interactive) (save-excursion (org-babel-goto-named-src-block "code") (org-babel-execute-src-block) (org-babel-goto-named-src-block "test") (org-babel-execute-src-block))) (define-key org-mode-map (kbd "C-c z") #'ndk/org-babel-evaluate-test-block-from-code-block) #+end_src ``` Pressing `C-c z` from anywhere in the buffer will do the evaluations and leave `point` unchanged. If you do it from the code block, that's where you will remain. --- Tags: org-babel, tangle ---
thread-20766
https://emacs.stackexchange.com/questions/20766
Display recursive folder sizes in-line in dired?
2016-03-05T02:38:07.433
# Question Title: Display recursive folder sizes in-line in dired? I'd like to display the recursive size (the value that would be reported by `du`) of folder contents in-line in the dired buffer as an additional column or in place of the directory file size. Is this already possible with dired/dired+ or a related package? I've done some digging and found some discussion of this sort of functionality, but nothing that integrates that size information back into the graphical interface of dired. # Answer > 8 votes Indeed, Alex is right. If your Emacs version is \>=24.4, then you can try \`dired-du' library. It's available from the ELPA repository. Once you've installed this lib: If your current buffer is in Dired mode, then you can do: ``` C-x M-r ``` that toggles the \`dired-du-mode' and displays the recursive size of the directories 'in place' in the Dired buffer. If you visit a new Dired buffer, then it will show recursive buffers as well, until you toggle off the mode. Another tip: ``` C-x C-h ``` This toggles the size format. There are 3 formats: 1. Default one from \`ls' command. 2. Human readable format. 3. Numeric format with thousands comma separator. You can customize the option \`dired-du-size-format' to make your size formar choice persistent. # Answer > 2 votes If you find dired-du slow, you can instruct it to use duc: ``` ;; Index the filesystem regularly (when (executable-find "duc") (run-with-timer 0 3600 (defun my-index-duc () (start-process "duc" nil "duc" "index" "/home")))) ;; Let dired show true directory sizes (require 'dired-du) (when (and (executable-find "duc") (not (string-match-p "Error" (shell-command-to-string "duc info")))) (setq dired-du-used-space-program '("duc" "ls -bD")) (add-hook 'dired-mode-hook #'dired-du-mode))) ``` --- Tags: dired, files ---
thread-67910
https://emacs.stackexchange.com/questions/67910
Can not filter agenda by more than one category
2021-07-31T08:37:17.833
# Question Title: Can not filter agenda by more than one category Update: The same happens when I run `org-agenda-filter` and enter `+work+home`. The agenda is empty. Entering only `work` or `home` works, also excluding multiple tags with `-work-calendar` works fine. My custom agenda setting "Work and Home" looks like this `(org-agenda-category-filter-preset '("+work" "+home"))` But when I call this agenda, it is empty. Having only one category works though: ``` (org-agenda-category-filter-preset '("+work")) ``` or ``` (org-agenda-category-filter-preset '("+home")) ``` Multiple exclusions work, too: ``` (org-agenda-category-filter-preset '("-home" "-calendar")) ``` What am I missing? org-version: 9.3, emacs-version 27.1 # Answer > 1 votes You are asking for entries that are tagged with *both* tags. Do you have any such entries? It seems more likely that the two categories are mutually exclusive. In that case, you get no results because there are no entries with both tags, and the implied operator is `&` (i.e. AND). The "Matching tags and properties" section of the manual (which you can get to with `C-h i g (org)Matching tags and properties`) says the following: > A search string can use Boolean operators ‘&’ for AND and ‘|’ for OR. ‘&’ binds more strongly than ‘|’. Parentheses are currently not implemented. Each element in the search is either a tag, a regular expression matching tags, or an expression like ‘PROPERTY OPERATOR VALUE’ with a comparison operator, accessing a property value. Each element may be preceded by ‘-’ to select against it, and ‘+’ is syntactic sugar for positive selection. The AND operator ‘&’ is optional when ‘+’ or ‘-’ is present. Here are some examples, using only tags. > > ‘+work-boss’ > > Select headlines tagged ‘work’, but discard those also tagged ‘boss’. > > ‘work|laptop’ > > Selects lines tagged ‘work’ or ‘laptop’. So, if you want to find entries that have *either* tag, then the search should be `+home|+work` or `home|work` as in the second example above. That works e.g with `m` (`org-tags-list`) from the agenda menu, but it doesn't work with the severely limited forms of search that are implemented by `org-agenda-filter`: this function applies each successive tag as a filter, so it implicitly does an `AND`. Similarly for `org-agenda-category-preset-filter`. But the OP mentions a custom agenda setting, so I wonder if the question is an X-Y question: if so, it may be that the chosen implementation should be abandoned and a different implementation be substituted in its place. One possibility is the super-agenda package as mentioned in the comments. But it may be that a custom block agenda would satisfy the OP's requirements, e.g.: ``` (setq org-agenda-custom-commands '(("H" "Home- and Work-related tasks" ((agenda "") (tags "home") (tags "work"))))) ``` as discussed in the "Block agenda" section of the manual, which you can get to with `C-h i g (org)Block agenda`. --- Tags: org-mode, org-agenda ---
thread-67920
https://emacs.stackexchange.com/questions/67920
How to define different font-lock-variable-name-face respect to different modes
2021-07-31T18:07:51.240
# Question Title: How to define different font-lock-variable-name-face respect to different modes By default `font-lock-variable-name-face` is defined as follows: ``` '(font-lock-variable-name-face ((t (:foreground "black" :weight bold)))) ``` Would it be possible to change its color for different modes such as for `shell-mode`: I have tried the following, which did not have any effect: ``` (add-hook 'shell-mode-hook (lambda () '(font-lock-variable-name-face ((t (:foreground "LightGoldenrod" :weight bold)))))) ``` --- `dracula-theme.el` is located under `~/.emacs.d/themes`: https://github.com/dracula/emacs/blob/master/dracula-theme.el minimal.el: ``` (add-to-list 'custom-theme-load-path "~/.emacs.d/themes") (load-theme 'dracula t) (defun my-shell-mode-faces () (face-remap-add-relative 'font-lock-variable-name-face '(:foreground "LightGoldenrod" :weight bold))) (add-hook 'shell-mode-hook 'my-shell-mode-faces) ``` # Answer My previous answer in this forum to a similar thread did not include an example using a major-mode hook How to modify-face for a specific buffer? , so I chose to write up this new answer. The function `face-remap-add-relative` sets the variable `face-remapping-alist` (responsible for buffer-local faces), which the manual recommends be set using the aforementioned function: https://www.gnu.org/software/emacs/manual/html\_node/elisp/Face-Remapping.html ``` (defun my-shell-mode-faces () (face-remap-add-relative 'font-lock-variable-name-face '(:foreground "LightGoldenrod" :weight bold))) (add-hook 'shell-mode-hook 'my-shell-mode-faces) ``` > 4 votes --- Tags: major-mode, customize-face ---
thread-67921
https://emacs.stackexchange.com/questions/67921
WHAT is the emacs tutorial command?
2021-07-31T20:39:21.007
# Question Title: WHAT is the emacs tutorial command? It says `C-h t` in a vague forum manual but I don't have that, how do I access this feature. # Answer It's `M-x help-with-tutorial` (`M` is the `Alt` key). But I suggest using `M-x help-with-tutorial-spec-language`, > 1 votes --- Tags: help ---
thread-67924
https://emacs.stackexchange.com/questions/67924
Org mode: Insert the result of a table formula between two existing columns
2021-08-01T00:32:13.310
# Question Title: Org mode: Insert the result of a table formula between two existing columns I have a very simple table like this: ``` | A | B | C | |---+---+----| | 1 | 2 | 15 | | 1 | 2 | 32 | | 1 | 2 | 81 | ``` I want to apply a formula that calculate the sum between A and B and insert the result just after the B column but before the C one. The formula is easy but… ``` #+TBLFM: $? = $1+$2 ``` …I don't know what to put in place of `$?`. How can I achieve that? # Answer > -1 votes An elisp formula can do the trick : ``` | A | B | | C | |---+---+---+----| | 1 | 2 | 3 | 15 | | 1 | 2 | 3 | 32 | | 1 | 2 | 3 | 81 | #+TBLFM: $4='(progn(org-table-analyze)(when (eq 3 org-table-current-ncol) (org-table-insert-column)) (+ $1 $2));N ``` --- Tags: org-mode, org-table, spreadsheet, formula ---
thread-67926
https://emacs.stackexchange.com/questions/67926
How does Emacs decide whether a frame's background-mode is light or dark, and how can I affect the decision?
2021-08-01T08:23:04.667
# Question Title: How does Emacs decide whether a frame's background-mode is light or dark, and how can I affect the decision? I am finding that in some cases (e.g. when `TERM=xterm-16color`), the expression ``` (frame-parameter nil 'background-mode) ``` ...evaluates to `light` when it is in fact a dark background. How does Emacs decide the value of a frame's `background-mode` at startup, and how can I affect the decision? **EDIT:** I realize that I can always run `(setq frame-background-mode 'whatever)`, but this is not what I mean by "affect the decision" above. Rather, I mean: how can I modify the way I invoke Emacs (including the shell environment in which I invoke it) so that its default algorithm for setting `frame-background-mode` at startup *gets it right*. **EDIT2:** I do not see how the answers to Emacs Blue color too dark answer my post's main question, namely: how does Emacs figure out the value it should set `frame-background-mode` to at startup? (For the sake of this question, assume that there is no `.emacs`/initialization file at startup.) # Answer Have a look at the code for `frame-set-background-mode` and `frame-terminal-default-bg-mode`. The latter "checks the ‘frame-background-mode’ variable, the X resource named "backgroundMode" (if FRAME is an X frame), and finally the ‘background-mode’ terminal parameter." Customize the `frame-background-mode` user option to enforce a value. Individual terminals/emulators are handled via the various files in the `lisp/term/` directory; e.g.: `/usr/local/share/emacs/27.2/lisp/term/` (but depending on how Emacs is installed); or else refer to https://git.savannah.gnu.org/cgit/emacs.git/tree/lisp/term See the `README` file in that directory for details of how Emacs selects which of those files to load. Once you've established which file is in use, you would need to read the code to see how backgrounds are established, as functionality can vary between terminals. > 2 votes --- Tags: faces, frame-parameters ---
thread-66857
https://emacs.stackexchange.com/questions/66857
Why is byte compiler issuing a warning on one of these 2 de Morgan equivalent expressions?
2021-07-26T18:32:02.440
# Question Title: Why is byte compiler issuing a warning on one of these 2 de Morgan equivalent expressions? Assuming that the symbol foo is not defined nor declared with a defvar or let form, the following code generates a byte-compiler warning in Emacs 26.3 and 27.2: ``` (defun f-or () "Use or." (when (or (null (boundp 'foo)) (null foo)) ;=> ``Warning: reference to free variable ‘foo’`` (message "foo is not set"))) ``` However, the following, longer, but de Morgan equivalent code does **not** generate a byte-compiler warning: ``` (defun f-and () "Use and." (when (null (and (boundp 'foo) foo)) ; no warning here! (message "foo is not set"))) ``` Replacing `null` for its alias `not`, using `(unless X ...)` instead of `(when (not X) ...` changes nothing, as expected. **Question:** Why does Emacs byte-compiler generate a warning for the expression using the `or` form but not for the expression using the `and` form? Should this be reported as a byte compiler improvement request to *not* generate this invalid warning in both cases? # Answer After submitting a bug report for this that was rejected I better understand the overall intent of the byte compiler as it was best described by Lars Ingebrigtsen in his closing remark: > "The issue isn't that the compiler warning is wrong -- it's correct; but we suppress it in very particular situations where it'll obviously not lead to any problems." The byte-compiler is inconsistent in its warning generation but that's an implementation decision. * In both scenarios above the code will run without errors but in both case the `foo` symbol is unbound (a free variable) and a warning reporting it as a free variable is not incorrect. * The implementers of the byte-compiler have chosen to inhibit the warning in valid code scenarios that are often seen, but not all. * That's a implementation decision as valid as any other that I hope this question/answer ticket will clarify for others that might run into this. Now the easy way out to prevent this byte-compiler warning is to place a `(defvar foo)` form above the code, something I did not mention before because I wanted to concentrate on the warning generation aspect. The loop is closed. > 2 votes --- Tags: byte-compilation, warning ---
thread-67928
https://emacs.stackexchange.com/questions/67928
Org mode: Using elisp formula to automatically sort tables
2021-08-01T10:37:45.230
# Question Title: Org mode: Using elisp formula to automatically sort tables I'm trying to use table formulas to automatically sort my tables. I have made this: ``` | Animal | Nombre | |----------+--------| | Bison | 5 | | Vache | 4 | | Aligator | 7 | | Chèvre | 4 | | Wapiti | 6 | | Sanglier | 41 | | Porc | 0 | #+TBLFM: $1 = '(org-table-sort-lines nil ?a) ``` However it produces a weird result, it replaces all string in the `$1` column by the number `2`: ``` | Animal | Nombre | |--------+--------| | 2 | 7 | | 2 | 5 | | 2 | 4 | | 2 | 0 | | 2 | 41 | | 2 | 4 | | 2 | 6 | ``` That's obviously not what I want to do and I have no idea why it is doing this. I tried using a relative notation to start from the second row: ``` #+TBLFM: @<<$1 = '(org-table-sort-lines nil ?a) ``` The result is better but still not perfect: ``` | Animal | Nombre | |----------+--------| | 2 | 7 | | Bison | 5 | | Chèvre | 4 | | Porc | 0 | | Sanglier | 41 | | Vache | 4 | | Wapiti | 6 | ``` # Answer `org-table-sort-lines` does not return the sorted table as your first formula assumes: instead, it operates by side-effect, modifying the table in place. It just so happens that the last thing it calls is `(move-column 2)` to move the cursor to the second column (of the screen, not the table - I'm oversimplifying here, but the details really don't matter much), and that function returns the column number (in this case 2). That is then the value assigned to the whole of the first column. Turn on formula debugging with `C-c {` to see what it's doing: you'll see that it sorts the table in a first pass and then assigns 2 to the first column when you continue. Your second formula "mostly works" because it's only affecting directly the top row of the table: again, the table is sorted by side-effect and then the value it returns is assigned to the `@1$1` cell of the table. What you really want to do is to throw away the result, but I don't know of a way to do that. As in your other question, however, I suggest you do *NOT* use formulas for such operations. You can interactively sort the table once and for all: you do not need to do that from a formula. EDIT: Here is an implementation of my suggestion to use a source code block: ``` #+name: animals | Animal | Nombre | |----------+--------| | Bison | 5 | | Vache | 4 | | Aligator | 7 | | Chèvre | 4 | | Wapiti | 6 | | Sanglier | 41 | | Porc | 0 | #+begin_src elisp :var tbl=animals :colnames yes (sort tbl (lambda (x y) (string-lessp (car x) (car y))))) #+end_src #+RESULTS: | Animal | Nombre | |----------+--------| | Aligator | 7 | | Bison | 5 | | Chèvre | 4 | | Porc | 0 | | Sanglier | 41 | | Vache | 4 | | Wapiti | 6 | ``` This depends on the fact that the table is represented in lisp as a list of rows and each row is a list of cells, with non-numeric cells represented as strings , e.g. the above table is represented like this: ``` (("Bison" 5) ("Vache" 4) ("Aligator" 7) ("Chèvre 4) ("Wapiti" 6) ("Sanglier" 41) ("Porc" 0)) ``` The `sort` function sorts a list using a predicate, i.e. a function that takes two arguments and returns non-nil if the first argument should sort before the second. In our case, the elements are two-element lists and we need to take the `car` of each element to get the names, which we compare using `string-lessp`. Do `C-h v sort` to find out more about the `sort` function. > 1 votes --- Tags: org-mode, org-table, spreadsheet, formula ---
thread-44898
https://emacs.stackexchange.com/questions/44898
how to map <C-M-left>, <C-M-right> etc to the correct hex codes in iterm2
2018-09-23T12:58:35.860
# Question Title: how to map <C-M-left>, <C-M-right> etc to the correct hex codes in iterm2 I'm looking to configure iterm2 to output the correct hexcodes that correspond to in emacs. There's a whole bunch of mappings predefined but it's very cryptic. I'm a little bit lost as to how these mappings are translated and if there is a table of how these mappings work. # Answer > 5 votes You can add: ``` For C-M-left: Send escape sequence: [1;7D For C-M-right: Send escape sequence: [1;7C For C-M-up: Send escape sequence: [1;7A For C-M-down: Send escape sequence: [1;7B ``` And this will work with Emacs if you set the term in iTerm2 to be reported as `xterm`. To know how to figure all this out, well its complicated, and I just went down this rabbit whole myself, so here I'll explain it all. ### How terminals work First off, you have to understand how Terminals work. Basically a terminal will get the input from the keyboard or mouse directly. So when you type or use the mouse, the terminal receives the exact keys that were pressed. The terminal's job is to translate those pressed keys or mouse events into actual text. So when you press on the key `A`, the terminal receives that signal from the keyboard, and its the terminal that decides if this key should map to the character `a`. You could imagine a terminal in a different keyboard layout might actually choose that the `A` key on your US keyboard when in AZERTY should actually map to the character `q`. So the terminal's job is to translate from actual keyboard and mouse events into characters to send to the connected shell or command line application. That means when an application is running in your shell, it does not receive the actual keyboard and mouse events, but instead it receives characters as translated by the terminal. Now because terminals are super old, this translation of keyboard and mouse events to characters only supported the ASCII character range, which is composed of 128 total characters. By default, most terminal will do the right thing when translating the simple keyboard events that have clear direct mappings to ASCII. For example, all pressed single letter keys `a-z` (as per the keyboard layout) becomes their corresponding ASCII (97 to 122 range). Now all of those keys pressed with the `Shift` modifier held or `CapsLock` turned on will map to their corresponding upper-case character `A-Z` (65 to 90 range). So when it comes to those normal mappings that have a simple logical correspondence to the ASCII characters, generally it all works, and no custom mapping in your Terminal need to be configured. *Where things get weird is that 128 characters is not enough to represent all possible keyboard and mouse events.* What happened since then is that first, Terminals were extended to support Unicode with UTF-8 encoding. UTF-8 was chosen, because it is backwards compatible with ASCII. That means that if you were to press the keys on some keyboard that logically map to some Unicode character, say the character `Բ`, well the Terminal would send over that character using UTF-8 encoding to the shell or application its connected too. But even though they now support Unicode, there are some keyboard and mouse event that have no representation in Unicode, because Unicode is not meant for keyboard and mouse events, its meant for representing text. So the question (ASCII or Unicode) is what character should map to some keyboard event like: `Ctrl+Alt+Home` ? Logically, none of these are characters, the `Home` button doesn't represent a character, neither does `Ctrl` or `Alt`. Now in Unicode you have some characters for these, for example the MacOS Ctrl character is which is Unicode U+2303, but even then, you wouldn't want the `Ctrl` key to map to U+2303, because then what if you wanted to actually type U+2303 so that inside VIM it typed ? So you can't use the Unicode for indicating a Ctrl key-press using the macOS Unicode control character or it would now be ambiguous with if you are actually trying to type the control character or are just pressing the Ctrl key. Now in ASCII, it turned out people had something called `Function Keys`, basically the range 0 to 31 and 127. Those are called as such because they were meant to perform a function instead of printing a character. So back in the days, people thought that apart from typing a few characters to have them printed, there would be a common set of typing functions someone could run and those would map to the character codes in ASCII 0 to 31 and 127. For example, ASCII 127 is DEL (Delete), which was meant to call the delete character function to delete a typed character. ASCII 13 was meant to run the carriage return function, to introduce a new line, and so on. Naturally, for those functions that still make sense, Terminals also generally do the correct mapping for those. So pressing the `Delete` key will send the ASCII 127 character to the shell or application. So this will work great for TAB, Backspace, Escape, Return, and Delete. The other functions don't make as much sense nowadays. For example, you have `start of header` which is too concrete and not really useful, it goes as follows: ``` Character Dec Hex Octal HTML Function ^A 1 0x01 0001 ^A SOH start of header ``` But as you see, these characters were also called `Control Keys` I think because you did have to press Control+A to execute the `start of header` function. So what Terminals do here is they continue to use all these `Control+` ASCII characters as a way to send the keyboard event `Ctrl+`. But again, there is only a few of these (range 0 to 31). So if you press `Ctrl+A` the terminal maps it to ASCII 1. What's annoying is there isn't even enough for all `Ctrl+english letter` combination, because some of them are already used by TAB and Return: ``` Character Dec Hex Octal HTML Function ^I 9 0x09 0011 ^I HT horizontal tab [\t] ^M 13 0x0d 0015 ^M CR carriage return [\r] ``` You also get a few extras that allow for `Ctrl+` one of `@,\,],^,_` and you could have `Ctrl+[` but that's taken for `Escape` so it will collide. Alright, so now if you have been following, you can go to https://www.barcodefaq.com/ascii-chart-char-set/ to see the list of ASCII characters and you should have a good idea of what keypress will be sent to your shell or application by your terminal. Examples: ``` Ctrl+@ => ASCII DEC: 0, CHAR: ^@, INTERPRETED AS: Ctrl+@ Ctrl+B => ASCII DEC: 2, CHAR: ^B, INTERPRETED AS: Ctrl+B Ctrl+[ => ASCII DEC: 27, CHAR: ^[, INTERPRETED AS: ESC Shift+a => ASCII DEC: 65, CHAR: A, INTERPRETED AS: A a => ASCII DEC: 97, CHAR: a, INTERPRETED AS: a DEL => ASCII DEC: 127, CHAR: <invisible>, INTERPRETED AS: Delete ``` ### How terminals send keyboard and mouse events that don't fit the ASCII range? As we saw, there's not enough characters to send all the keyboard and mouse events, especially those that don't have a logical character associated to them like `Ctrl+Alt+Home`. In order to support these, different terminals came up with their own scheme, no standard was established, and everything just got messy, but overtime some terminals have become the "most used" and their way of doing things is often the ones best supported by applications and shells. Generally, what terminals will do is that for keyboard or mouse events with no direct mapping to ASCII, they will make up a combination of ASCII characters that they use to represent more keyboard and mouse events. So for example, they might say that `Ctrl+Alt+Home` will be represented as the string of characters: `^[[1;7H` This is just ASCII once more, so a terminal could decide that: ``` Ctrl+Alt+Home => ASCII (in decimal): [27,91,49,59,55,72] ``` ### Back to iTerm2 Key Mappings What you see in iTerm2's Key Mapping are all those additional mappings for stuff that fall outside the ASCII range. Though I think you could also use it to remap how iTerm2 maps the normal keys even within the ASCII range if you wanted. You have two useful settings: 1. Send hex codes This lets you tell iTerm2 that a specific keyboard shortcut should send the following sequence of ASCII characters (where it takes the ASCII chars in their hexadecimal representation). So refer too: https://www.barcodefaq.com/ascii-chart-char-set/ to see the hex code for each ASCII character. With that you can tell iTerm2 to send any arbitrary sequence of ASCII characters for any arbitrary keyboard key press event. 2. Send escape sequence But generally, terminals like `xterm` have used a sequence of ASCII characters that always starts with the ASCII Escape character `^[` which is ASCII decimal 27 or ASCII hex 0x1b. Because that's so common, iTerm2 has a "Send escape sequence" where it lets you type the ASCII characters using your keyboard (so you can input them as text instead of hex or decimal) which it will automatically prepend with the ASCII Escape char or `^[` aka ASCII decimal 27 or hex 0x1b. ### How do I know what I should map those shortcuts outside the ASCII range so they work in most shells and terminal applications? This is a little tricky, because each shell or application running in the terminal might not understand the same ASCII sequence to mean the same key-presses. And like I said, there is no real standard for it either. But some older terminals had established some convention for some additional key-press combinations, that's where for example in iTerm2 you can load the `xterm defaults` preset. This will load the set of added key-presses for which the `xterm` terminal (an old popular terminal) had itself added by default. Because `xterm` is popular, most shells and terminal applications will understand those. Beyond that, it really depends on the terminal application in question, and you need to check their documentation and hopefully they document that stuff. ### There's really no standards? Like I said, each old popular terminal like `VT-102`, `xterm`, etc. will have had their own additional key-presses, and those are mostly "standard". But none of them offered a scheme that covered all possible mouse and keyboard events. But, since then, there are 2 conventions that emerged which attempt to systematically cover all keypresses: 1. Fixterm (aka libtickit or libvterm) The convention for this is: ``` ^[[<char-code>;<modifer-code>u ``` I'm not sure where the list of valid `<char-code>` and `<modifier-code>` comes from though. 2. xterm's modifyOtherKeys The convention for this is: ``` ^[27;<modifer-code>;<char-code>;~ ``` I'm also not sure where the list of valid `<char-code>` and `<modifier-code>` comes from though, but I believe they are the same as with fixterm. Please note the xterm convention predates fixterm convention by many years. Neither are yet very popular, and I would say they are trying to be a "standard", but don't expect this to work with all apps. ### If you really just care about Emacs? For me, most exotic keyboard shortcuts I care about are for use with Emacs. Other apps tend to have shortcuts within the ASCII range, which works as-is. What I found for Emacs is that if you inspect the emacs-lisp variable: `input-decode-map` it'll show you all the ASCII sequences that Emacs support, it uses ASCII decimals to do so. For each combinations of sequence it shows what EMACS interprets the sequence as. So you can use that to bind the shortcut in iTerm2 to the sequence Emacs is configured to interpret it as. Also you can use the function: `(read-key-sequence "?")` and press some keyboard combination and Emacs will show you what it interprets it too. ### Useful trick A useful trick is to run `cat -v` in your terminal and now it will show you the ASCII characters of all the key combos and everything you press to see what your terminal currently maps them too. It won't show invisible stuff like Delete though. ### What about Alt? I forgot to mention that a lot of terminals will also make it so that `Alt` or `Meta` are mapped to ASCII 27 (the Escape character). So when you press `Alt+key` it will send the sequence: `^[<key>` so it'll send ASCII 27 for Escape followed by the character or character sequence that maps to the key you typed along with it. That's why in terminal Emacs, ESC is used for almost all `M-` style shortcuts as well, so `M-x` can also be performed with `ESC x`. Emacs will thus interpret `ESC key` as `M-key`. ### What about shift? Shift is normally not sent by the terminal, instead it normally simply change the character to be sent, like `Shift+a` sends the upper-case `A` character. Or pressing `Shift+5` will send `%` (on a US layout\`. You can map a custom sequence for `Shift+5` instead which you could have Emacs recognize as `S-5` instead of `%`. ### Revisiting fixterm and xterm modifyOtherKeys I also didn't mention that newer Emacs by default have in `input-decode-map` most of the mappings necessary to interpret both fixterm and xterm modifyOtherKeys generic schemes. That said, the way Emacs does it is hard-coded, it misses some of them, so not all of them will work as-is. Also both conventions are not super well defined when there exist another way to send the same, as when will they use the convention versus try to be backwards compatible with some prior sequence or strategy that was used. Anyways, that means that for Emacs and iTerm2, you can tick the `Report modifiers using CSI u` in iTerm2 Keys config, and a lot of things will now "just work" in Emacs (though not all). # Answer > 1 votes I could post a thousand-word essay on how all of the various layers of software interact to provide both backwards-compatibility with hundreds of historical systems as well as customizability for dealing with new ones, but the truth is that it's really a waste of time. Just run Emacs as a normal gui application, and it'll all work much better. If you really insist on running Emacs inside a terminal emulator, know that the OS tells the terminal emulator directly what keys you pressed. then the terminal emulator then translates this into a sequence of bytes to send to the application running inside the terminal, and finally that application translates it back into some idea of what keys you pressed. The idea behind this configuration window in iTerm is to allow you to tell iTerm what the application you're running expects. Unfortunately, Emacs can be configured to work in a wide variety of environments, and you haven't given us enough information to figure all of that out. I would suggest using the Emacs help functions to tell you what Emacs thinks is going on. Specifically, if you type `C-h k`, followed by any keyboard shortcut, Emacs will tell you what keys Emacs thinks you pressed and what command they normally trigger, if any. This will tell you what Emacs thinks of the bytes or escape codes that iTerm is sending. --- Tags: key-bindings, term ---
thread-67939
https://emacs.stackexchange.com/questions/67939
How can I handle unfound ELPA packages?
2021-08-02T08:11:43.393
# Question Title: How can I handle unfound ELPA packages? Sometimes I encounter packages claiming to be on ELPA, yet neither `package-install` nor \[1\] or \[2\] list them. How do I know if the problem is on my or the contributor's side? Simply manually installing a package wouldn't satisfy my curiosity. Example: https://github.com/theanalyst/ix.el \[1\] https://elpa.gnu.org/packages/ \[2\] https://melpa.org/#/ix.el # Answer > 0 votes You could try the MELPA search interface or `M-x list-packages` to search from within Emacs. If you are searching the package collection in Emacs, ensure you have updated with `M-x package-refresh-contents` and have the relevant package sources listed. --- Tags: package, package-repositories ---
thread-67929
https://emacs.stackexchange.com/questions/67929
How can I prevent undo after redo?
2021-08-01T10:50:51.047
# Question Title: How can I prevent undo after redo? I already know that to redo a change, I need to type something like `C-g C-/`. Why does it start to undo after all of the possible redos are done? Here is what I mean: 1. Visit a new file. 2. Type ``` aa bb cc ``` 3. Type `C-/` five times to undo the text. 4. Type `C-g` (one time) and then `C-/` (five times) to redo the text. 5. Continue to type `C-/`. I expected that it wouldn't make any effect, since there are no more things to redo, but it started to delete the text, as in the third step. Why? And how can I prevent it from happening? # Answer > 8 votes The reason Emacs "starts to undo after all of the possible redos are done" is that, after you interrupted the original undo sequence with `C-g`, every change you had made up until that point became part of the tree to be undone. Those changes include not only the initial text you entered ("aa bb cc") but also the undoing of those changes. As the manual explains: "Any command other than an undo command breaks the sequence of undo commands. Starting from that moment, the entire sequence of undo commands that you have just performed are themselves placed into the undo record." This is not how `undo` works in most other text editors, and some people find this behavior counterintuitive. However, this type of `undo` is very powerful, since it allows you to recover any past state of a buffer. You may want to try the package undo-tree, which replaces the native `undo` Emacs feature with a more intuitive equivalent, without sacrificing its power. Its commands `undo-tree-undo` and `undo-tree-redo` will behave like the `undo` and `redo` you are used to, but you can also see a visualization of the undo tree branches (`undo-tree-visualize`), and switch branches if needed (`undo-tree-switch-branch`). ADDED: Check the comments to this answer by ideasman42 and Phil Hudson for some issues with `undo-tree`, and note that as ideasman42 mentions in another answer, Emacs 28 offers the command `undo-redo` out of the box. # Answer > 5 votes Emacs 28 adds a redo command (called `undo-redo`). If you want to have more typical undo/redo, the following commands can be used. ``` (global-set-key (kbd "C-z") 'undo-only) (global-set-key (kbd "C-S-z") 'undo-redo) ``` --- You can also check the package undo-fu which has this functionality, allowing to access the full non-linear undo history as well. --- Tags: undo ---
thread-67932
https://emacs.stackexchange.com/questions/67932
Org mode link to open xterm with arguments
2021-08-01T12:42:06.970
# Question Title: Org mode link to open xterm with arguments ``` * MyHeader My links: Working: [[elisp:(term "xterm")]] **Not working** [[elisp:(term "xterm visidata /tmp/foo.csv")]] ``` 1. \[X\] Open xterm from org mode link 2. \[ \] Open xterm from org mode link **with arguments** How can I append arguments to the terminal command? # Answer I don't think `term` does what you think it does: if you want to open an external `xterm` window running `visidata /tmp/foo.csv`, then you want to run the elisp expression: ``` (shell-command "xterm -e visidata /tmp/foo.csv &") ``` so your link should look like `[[elisp:(shell-command "xterm -e visidata /tmp/foo.csv &")]]`. EDIT: as the commenters indicate, the command needs to be run asynchronously, otherwise emacs waits for the command to finish and will not do anything else. That can be done, as the OP indicates in their comment, with `start-process`, but it can also be done, perhaps more simply, with `shell-command`, by adding an `&` at the end of the command (see the edited code above), which is how you run a shell command in the background. `C-h f shell-command` has all the details. > 1 votes --- Tags: org-mode ---
thread-66327
https://emacs.stackexchange.com/questions/66327
emacs startup says "Invalid face: highlight"
2021-06-16T05:32:19.563
# Question Title: emacs startup says "Invalid face: highlight" When I start up emacs, it prints `Invalid face: highlight` and then exits. This problem happened after I reinstalled Ubuntu 21.04 from scratch. Any suggestions on how to debug this? * I have tried 26.2 from ubuntu... same problem. * I have tried downloading and compiling 27.2. Same problem. * I have tried commenting out every line in my .emacs file. Same problem. * `emacs -q` has the same problem. * `emacs -q --debug-init` has the same problem. * `emacs -Q` brings up an emacs window. # Answer If the problem persists with `emacs -q`, and not for `emacs -Q`, then the source is most likely in `site-start.el`. `site-start.el` is sometimes provided by distributions, and you might find it in `/usr/local/share/emacs/site-lisp`, `/etc/emacs/`. On Ubuntu, running the command `locate site-start.el` from the command line might show you other locations. Any files in the directory`/etc/emacs/site-start.d/` may be involved too. > 1 votes # Answer I narrowed the problem down to a file in `/usr/local/share/emacs/site-lisp`: `subdirs.el`. It contains ``` (if (fboundp 'normal-top-level-add-subdirs-to-load-path) (normal-top-level-add-subdirs-to-load-path)) ``` instead of the following which is in the source for emacs 27.2: ``` ;; In load-path, after this directory should come ;; certain of its subdirectories. Here we specify them. (normal-top-level-add-to-load-path '("vc" "url" "textmodes" "progmodes" "play" "org" "nxml" "net" "mh-e" "mail" "leim" "language" "international" "gnus" "eshell" "erc" "emulation" "emacs-lisp" "cedet" "calendar" "calc" "obsolete")) ;; Local Variables: ;; version-control: never ;; no-byte-compile: t ;; no-update-autoloads: t ;; End: ``` > 0 votes --- Tags: init-file, faces ---
thread-54668
https://emacs.stackexchange.com/questions/54668
Display word count in modeline without lag
2020-01-04T13:40:44.797
# Question Title: Display word count in modeline without lag ## Problem Stopped using `wc-mode` as it is not snappy anymore (as text writing usually is) with text document of 10k words. It appears that it *counts the whole buffer after every change* which seems to make it slow as logged here. A recent change was made to speed it up, but still produces considerable lag. ## Partial Solution There is a "solution" here, but it is so hard for me to implement it as I am not familiar with Lisp and inner workings of Emacs. There are two functions `wc-buffer` and `wc-region`, which are empty in the answer (below), for which I have no clue what should be in the function. ``` ;; Function that counts words in buffer (defun wc-buffer () ...) ;; Function that counts words in a region (defun wc-region (rbeg rend) ...) (defvar-local a1 nil) (defvar-local a2 nil) (defvar-local curr-wc nil) (defun init-function () (interactive) (save-excursion (setq curr-wc (wc-buffer)))) (defun wc-update-before (change-beg change-end) (setq pos1 (max 1 (1- change-beg))) (setq pos2 (min (point-max) (1+ change-end))) (setq a1 (wc-region pos1 pos2))) (defun wc-update-after (change-beg change-end prev-len) (if (bound-and-true-p a1) (progn (setq pos1 (max 1 (1- change-beg))) (setq pos2 (min (point-max) (1+ change-end))) (setq a2 (wc-region pos1 pos2)) (setq curr-wc (+ curr-wc (- a2 a1)))) nil)) (init-function) (add-hook 'before-change-functions #'wc-update-before nil t) (add-hook 'after-change-functions #'wc-update-after nil t) (setq inhibit-modification-hooks nil) ``` ## Help I ask for someone either to tell me explicitly what goes in these functions or suggest alternatives for counting words and not having lag while displaying them in the mode-line. ## Reproducing You can reproduce this by: installing `wc-mode` and enabling it and then when you have more than 10k words, you can expect (depending on your PC) quite some lag while typing. It's not snappy. # Answer > 1 votes **Solution 1**, add `(setq wc-idle-wait 2)` into `~/.emacs` if you need get updated with the data in real time, Please note `wc-idle-wait` should be set **before** loading `wc-mode.el` because of below code in `wc-mode.el`, ``` (setq wc-timer-tracker (run-with-idle-timer wc-idle-wait t '(lambda () (when wc-mode (setq wc-buffer-stats (wc-mode-update)))))) ``` **Solution 2**, do the calculation only before saving current buffer. But you need set `wc-idle-wait` to a bigger value first. Here is sample setup (see my comment, you can do some further optimization inside `before-save-hook`), ``` (setq wc-idle-wait most-positive-fixnum) (add-hook 'before-save-hook (lambda () ;; you can check `buffer-file-name' or `major-mode' first (setq wc-buffer-stats (wc-mode-update)))) ``` # Answer > 0 votes I think you can use `count-words` to implement the `wc-buffer` function and `count-words-region` to implement the `wc-region` function. Like this: ``` (defun wc-buffer () (count-words (point-min) (point-max))) (defun wc-region (rbeg rend) (count-words-region rbeg rend)) ``` # Answer > 0 votes See mode-line-idle, the `readme` shows an example of showing a word count in a way that's not blocking. This allows you to add anything you like to your mode line in a way that doesn't block your workflow. --- Tags: init-file, mode-line, words, counter ---
thread-64935
https://emacs.stackexchange.com/questions/64935
mwheel-scroll bindings between GUI and terminal?
2021-05-20T23:13:06.143
# Question Title: mwheel-scroll bindings between GUI and terminal? Using an Emacs daemon (28, pgtk branch) switching between GUI and terminal, I can't get mouse scrolling to work on both. They work on each individually, but the issue is with the `mouse-wheel-{up,down}-event` var - it's `mouse-4/5` on terminal and `wheel-down/up` on GUI. This has been documented in bug-gnu-emacs as far back as 2009. I tried: ``` (global-set-key (kbd "<mouse-4>") (kbd "<mouse-down>")) (global-set-key (kbd "<mouse-5>") (kbd "<mouse-up>")) ``` as suggested, but that gave me `bad binding in mwheel-scroll`. Trying other things with kbd macros gave me `After 0 kbd macro iterations: undefined: Keyboard macro terminated by a command ringing the bell`. Any other ideas? # Answer > 0 votes I reported this bug to the feature/pgtk maintainer > https://github.com/masm11/emacs/issues/108 > https://debbugs.gnu.org/cgi/bugreport.cgi?bug=50321 and it has just been fixed in > https://git.savannah.gnu.org/cgit/emacs.git/commit/?h=feature/pgtk&id=b22323c3b66feb3c9c0f3086cc784fab9578ff7b --- **This is only a partial answer to the question.** I recently upgraded to Emacs 28.0.50 with `feature/pgtk` to have better Wayland integration. Just like you I am connecting with both GUI and terminal clients to the same daemon, but scrolling no longer worked in the terminal. I figured out that I need the following Elisp to restore scrolling in the terminal. ``` (unless window-system (defun track-mouse (e)) (xterm-mouse-mode t) (when (featurep 'pgtk) (setq mouse-wheel-down-event 'mouse-4) (setq mouse-wheel-up-event 'mouse-5) (global-set-key (kbd "<mouse-4>") 'mwheel-scroll) (global-set-key (kbd "<mouse-5>") 'mwheel-scroll) (global-set-key (kbd "<C-mouse-4>") 'mouse-wheel-text-scale) (global-set-key (kbd "<C-mouse-5>") 'mouse-wheel-text-scale) (global-set-key (kbd "<S-mouse-4>") 'mwheel-scroll) (global-set-key (kbd "<S-mouse-5>") 'mwheel-scroll))) ``` Unfortunately, this only fires once, so it breaks scrolling for GUI clients. I tried to work around this using `focus-in-hook` and `make-variable-frame-local` but the former crashed Emacs when switching between frames and the latter is deprecated. --- EDIT: I've managed to find something that seems to do what I want. Essentially I advise `mwheel-scroll` and `mouse-wheel-text-scale` to locally change the event type for scrolling when invoked through `mouse-4` and `mouse-5`. This is probably extremely inefficient but it seem to work. ``` (defun track-mouse (e)) (xterm-mouse-mode t) (when (featurep 'pgtk) (defun user/mwheel-scroll (&rest args) "Wraps `mwheel-scroll' for use with <mouse-4> and <mouse-5>." (interactive (advice-eval-interactive-spec (cadr (interactive-form 'mwheel-scroll)))) (let ((mouse-wheel-down-event 'mouse-4) (mouse-wheel-up-event 'mouse-5)) (apply 'mwheel-scroll args))) (defun user/mouse-wheel-text-scale (&rest args) "Wraps `mouse-wheel-text-scale' for use with <mouse-4> and <mouse-5>." (interactive (advice-eval-interactive-spec (cadr (interactive-form 'mouse-wheel-text-scale)))) (let ((mouse-wheel-down-event 'mouse-4) (mouse-wheel-up-event 'mouse-5)) (apply 'mouse-wheel-text-scale args))) (global-set-key (kbd "<mouse-4>") 'user/mwheel-scroll) (global-set-key (kbd "<mouse-5>") 'user/mwheel-scroll) (global-set-key (kbd "<C-mouse-4>") 'user/mouse-wheel-text-scale) (global-set-key (kbd "<C-mouse-5>") 'user/mouse-wheel-text-scale) (global-set-key (kbd "<S-mouse-4>") 'user/mwheel-scroll) (global-set-key (kbd "<S-mouse-5>") 'user/mwheel-scroll)) ``` --- Tags: key-bindings, emacsclient, terminal-emacs, scrolling, mouse ---
thread-67936
https://emacs.stackexchange.com/questions/67936
How to see only the local branches created by me on Magit?
2021-08-01T17:30:19.583
# Question Title: How to see only the local branches created by me on Magit? When I am working on the Command Line Interface, I can do: ``` $ git branch ``` Then, I can see all the local branches that *I have created*. On Magit, If I do `b l` (check out local branch), there is a prompt to answer. With the auto-complete, I can *find* all the local branches I created. However, when I press `tab` to see the suggestions, **Magit lists absolutely all branches**, the ones I created locally and the ones pulled from the upstream remote repository. Is there a way to limit the suggestions for the branch checkout only to the branches I have created? # Answer > 3 votes Here's a quick hack using `magit-read-local-branch`: ``` (defun my-checkout-local-branch () (interactive) (let ((branch (magit-read-local-branch "Branch: "))) (magit-checkout branch))) (transient-append-suffix 'magit-branch "w" '("L" "my branch" my-checkout-local-branch)) ``` Though it won't do stuff like filtering out the branch you're currently on. --- Tags: magit ---
thread-66530
https://emacs.stackexchange.com/questions/66530
Are all .el files inside ELPA compliant packages sharing the same namespace?
2021-06-30T15:06:10.583
# Question Title: Are all .el files inside ELPA compliant packages sharing the same namespace? Assuming that a ELPA directory contains only **one** version of each Elpa-compliant packages, are the names of all Emacs Lisp files sharing the same namespace? AFAIK Emacs Lisp does not support the concept of package scope for module name (as other languages like Python support). I would therefore have assumed that *all* Emacs Lisp files share the same name space. However, some file names in different packages that have the same name but different content, as in the following case: * `lispy-20210121.926/elpa.el` * `ivy-20210311.1638/elpa.el` How does Emacs deal with this? # Answer > 1 votes The two files you reference (`elpa.el`) are used only in installing those packages. If you check the package sources, you'll see that they are only referenced from the Makefile. After the packages are installed, Emacs doesn't need to find them again, so it doesn't matter that they have conflicting names. Usually, Emacs refers to the `load-path` to see which directories it should search for files. The `load` function is used to load files by name: ``` (load "my-file") ``` Will search through the `load-path` until it finds a file with the name `my-file.elc`, `my-file.el`, `my-file`, and possibly a few other variants depending on your system. As soon as it finds a file with a matching name, it loads it and stops looking. If there is a second file with the same name further down in the load path, it is ignored. You can use the command `M-x list-load-path-shadows` to get a list of all such ignored files. Consequently, files in a package will be generally be named in a way that is unique to that package (e.g., with a `lispy-` or `ivy-`) prefix, with a few exceptions like the one above. # Answer > 1 votes All packages share the same namespace as Elisp does not support separate namespaces. Packages usually deal with this by prefixing every symbol with a short, unique string. For example, every function in the ivy package is prefixed with "ivy-". --- Tags: package-repositories ---
thread-66852
https://emacs.stackexchange.com/questions/66852
Ivy version of mu4e-view-save-attachments
2021-07-26T14:01:36.410
# Question Title: Ivy version of mu4e-view-save-attachments I used to use helm and really liked mu4e-view-save-attachments as a quick way to save multiple attachments in an email at once. I recently switched to Ivy and learned this function is helm specific. Does anyone have an ivy version of this or an equally efficient method of saving multiple attachments at once? EDIT: This ugly hack almost works (just a slight modification of mu4e-view-save-attachments but I get an error `wrong-type-argument listp "whatever-attachment-filename-I-select"` the error is happening in the `(member f files)` function call. ``` (defun jds/mu4e-view-save-attachments (&optional arg) "Save mime parts from current mu4e gnus view buffer. When helm-mode is enabled provide completion on attachments and possibility to mark candidates to save, otherwise completion on attachments is done with `completing-read-multiple', in this case use \",\" to separate candidate, completion is provided after each \",\". Note, currently this does not work well with file names containing commas." (interactive "P") (cl-assert (and (eq major-mode 'mu4e-view-mode) (derived-mode-p 'gnus-article-mode))) (let* ((parts (mu4e~view-gather-mime-parts)) (handles '()) (files '()) (helm-comp-read-use-marked t) (compfn (if (and (boundp 'helm-mode) helm-mode) #'completing-read ;; Fallback to `completing-read-multiple' with poor ;; completion ;;#'completing-read-multiple #'ivy-completing-read)) dir) (dolist (part parts) (let ((fname (cdr (assoc 'filename (assoc "attachment" (cdr part)))))) (when fname (push `(,fname . ,(cdr part)) handles) (push fname files)))) (if files (progn (setq files (funcall compfn "Save part(s): " files) dir (if arg (read-directory-name "Save to directory: ") mu4e-attachment-dir)) (cl-loop for (f . h) in handles when (member f files) do (mm-save-part-to-file h (expand-file-name f dir)))) (mu4e-message "No attached files found")))) ``` # Answer > 1 votes As you've discovered, `mu4e` only accommodates `helm-mode` or Emacs' built-in `completing-read-multiple`. In order to use ivy for completions, you need to modify the code directly. In addition, to make use of Ivy's multiple selection features, you need to use `ivy-read` with an appropriate `:action` defines. The following accomplishes this (with much room for refinement!): ``` (defun jds/mu4e-view-save-attachments (&optional arg) "Save mime parts from current mu4e gnus view buffer. When helm-mode is enabled provide completion on attachments and possibility to mark candidates to save, otherwise completion on attachments is done with our custom `ivy-completing-read-mu4e-parts'. Note, currently this does not work well with file names containing commas." (interactive "P") (cl-assert (and (eq major-mode 'mu4e-view-mode) (derived-mode-p 'gnus-article-mode))) (let* ((parts (mu4e~view-gather-mime-parts)) (handles '()) (files '()) (helm-comp-read-use-marked t) (compfn (if (and (boundp 'helm-mode) helm-mode) #'completing-read ;; Use ivy completion: #'ivy-completing-read-mu4e-parts )) dir) (dolist (part parts) (let ((fname (cdr (assoc 'filename (assoc "attachment" (cdr part)))))) (when fname (push `(,fname . ,(cdr part)) handles) (push fname files)))) (if files (progn (setq files (funcall compfn "Save part(s): " files) dir (if arg (read-directory-name "Save to directory: ") mu4e-attachment-dir)) (cl-loop for (f . h) in handles when (member f files) do (mm-save-part-to-file h (expand-file-name f dir)))) (mu4e-message "No attached files found")))) (defun ivy-completing-read-mu4e-parts (PROMPT COLLECTION) (let (PARTS) (ivy-read PROMPT COLLECTION :action (lambda (x) (add-to-list 'PARTS x))) PARTS)) ``` --- Tags: mu4e, ivy ---
thread-8068
https://emacs.stackexchange.com/questions/8068
emacs on terminal does not recognise option as alt-key on mac
2015-02-08T10:52:14.117
# Question Title: emacs on terminal does not recognise option as alt-key on mac I am on a mac and I am running emacs 24.4.1, but I have the same problem also with 22.1.1. When I open mac on a terminal on the remote host, it does not recognise option key (alt) like the meta key. I have modified the `.emacs` in the following way ``` (setq mac-option-key-is-meta nil mac-command-key-is-meta t mac-command-modifier 'meta mac-option-modifier 'none) ``` so I have tried to change the meta key to command, but also in this case the meta key doest work . This only work on the X version of emacs (when I open emacs in a new window), both with the option as meta key that as command as meta key. This is a problem I have with emacs in the terminal-only. Now I don't know how to run commands in emacs! is there any keybinding I can use? # Answer This is a setting in Terminal. In Terminal 2.5.1 the option is set differently than in the above comments: In the main Terminal menu, choose "Preferences" to open a dialog. Click the "Profiles" icon in the top of the dialog. In the Profiles section, make sure there is a check in the checkbox called "Use Option as Meta key." > 27 votes # Answer I solve the problem with answer of ohruunuruus. Maybe post a snapshot will be more easy to understand. > 15 votes # Answer I'm using iTerm2 and find out that setting the `Option` key to `Esc+` helps. > 0 votes --- Tags: osx, terminal-emacs, input-method ---
thread-67958
https://emacs.stackexchange.com/questions/67958
Is it problematic to use simultaneously Helm and Ido-mode? What are the consequences?
2021-08-04T11:07:28.947
# Question Title: Is it problematic to use simultaneously Helm and Ido-mode? What are the consequences? I am new to Emacs. When I started using it 2 months ago, a co-worker suggested using `helm` which definitely improved my use of Emacs. In addition, I have been slowly reading the book *Mastering Emacs*, by Mickey Petersen. At the beginning of the book, the author emphatically endorses using `ido-mode`. So, I installed it and I have been using it for the last 2 weeks. Since I have **not** uninstalled `helm`, I have been using both packages `ido-mode`and `helm` simultaneously. 1 - Is there a feature/functionality overlap between those packages? What is it? Or are they perfectly complementary? 2 - Aside from subjective opinions, is there any technical reason to make this a bad "design" choice for one's configuration? # Answer Question 1: Helm provides all the functions that ido does. You can use helm to find files, switch buffers, or do anything else that ido is used for. In addition, Helm can do a lot more, both in the main package and with extensions that use the helm framework. Question 2: it's really up to you. I haven't used ido in a while, but I mix Ivy and Helm. I like Ivy for most things, but there are some functions in helm that I find superior. There's no objective technical reason not to mix and match. The only issue I have run into is getting a little confused myself when I try to use the ivy keybindings in helm or vice versa. But I don't think using one will break the other, or impact how ido works. You might need to put some time into your keyboard shortcuts, since ido and ivy both have global modes that take over the defaults for find-file. I don't think Helm does, but it's been a while since I used it. > 2 votes # Answer 1, `ido-compleing-read` can only select from string list. `helm` supports Emacs builtin API `completing-read`. Here is `completing-read` documentation. So helm is more powerful. 2. `ido` and `helm` are bit old. New users can start from `counsel/ivy/swiper` (https://github.com/abo-abo/swiper). These days many experienced Emacs users prefer more "modern" completion frameworks, See https://www.libhunt.com/r/icomplete-vertical for the list. Ivy and these new frameworks also support `completing-read`. > 2 votes --- Tags: helm, ido ---
thread-67962
https://emacs.stackexchange.com/questions/67962
provide optional parameter for magit
2021-08-04T14:12:12.877
# Question Title: provide optional parameter for magit I am tracking my dotfiles by using this approach. This is very useful method to track files which are in different locations. Short summary of the blog. ``` alias dotfiles='/usr/bin/git --git-dir=$HOME/.dotfiles/ --work-tree=$HOME' dotfiles add newfile dotfiles commit -am "add new file" etc.. ``` Since it's bash alias, I couldn't fınd the way to integrate this function with **magit**. **Question:** How I can use magit graphical interface like `dotfiles-magit-status` and look for changed files for this repository? Kind of function like `M-x dotfiles-magit-status` is accepted. **Links same approach:** **Maybe helps:** # Answer > 1 votes > ``` > alias dotfiles='/usr/bin/git --git-dir=$HOME/.dotfiles/ --work-tree=$HOME' > > ``` I am under the impression that the only "problem" that this solves is that you typically cannot do `git clone URL $HOME` because $HOME already exists. I recommend you do this instead: ``` git clone URL /tmp/home mv /tmp/home/.git $HOME/.git rm -rf /tmp/home cd $HOME ``` The cost of the "dotfiles approach" however is high: you now have to teach Magit and probably many tools to come about this complication. Anyway, if you still want to do it, at https://www.reddit.com/r/emacs/comments/ot92l3 someone else seems to have figured out how to make the pig fly. --- Tags: magit, git ---
thread-67966
https://emacs.stackexchange.com/questions/67966
In Magit, the command `magit-status` opens the buffer with the status buffer. Is there some similar command to do the same but with the Slime's REPL?
2021-08-04T20:17:03.007
# Question Title: In Magit, the command `magit-status` opens the buffer with the status buffer. Is there some similar command to do the same but with the Slime's REPL? I am using Emacs powered with Slime to write code on Common Lisp (SBCL). In addition, I am also using magit. Magit has a **handy** command called `magit-status` (`C-x g`). I use it a lot and I tend to have 2 windows split horizontally on my screen. I would like to have a similar user experience with the Slime REPL's buffer. Currently, what I do is: `C-x b`, then ido-mode shows the options in an augmented mini-buffer and, lastly, I start typing the REPL which is auto-completed. I wish there was some command and a keybinding just like `magit-status` but to show show Slime's REPL buffer in one of the windows and move the cursor there. Is this already available? What do I need to call? If not, what should I do in my init file to have this shortcut? # Answer > 2 votes You want `slime-switch-to-output-buffer`, bound to `C-c C-z` by default. The SLIME User Manual has the documentation for this and many other interesting commands. You can read it inside of Emacs (use `C-h i` to open the Info viewer, you’ll find the manuals there), or online. See specifically chapter 8.2 REPL: the “top level”. --- Tags: key-bindings, magit, window, slime ---
thread-67972
https://emacs.stackexchange.com/questions/67972
Org mode: How to escape the # character in a table formula
2021-08-05T10:37:25.397
# Question Title: Org mode: How to escape the # character in a table formula I am trying to rename a row inside a table using a formula in Org mode (don't ask why I'm doing this, I need to do it that way) but I'd like to call this row `#`. I'm doing this: ``` | #ERROR | B | C | |--------+---+---| | 1 | 2 | 3 | | 1 | 2 | 3 | #+TBLFM: @1$1=# ``` As you can see I'm getting an error. I guess that's because `#` is a special character reserved to indicate line numbers. So I'd like to know how to escape this character to interpret it as a normal string. # Answer The following works because you can write table formulas with elisp code. Notice the `'` (quote) before the s-exp. ``` | # | B | C | |---+---+---| | 1 | 2 | 3 | | 1 | 2 | 3 | #+TBLFM: @1$1='(format "#") ``` Evaluate `(info "(org) Formula syntax for Lisp")` for more information. > 3 votes --- Tags: org-mode, org-table, escape, formula ---
thread-67975
https://emacs.stackexchange.com/questions/67975
Load right version of Git while connecting to remote
2021-08-05T13:30:05.500
# Question Title: Load right version of Git while connecting to remote I am currently working on a remote using Lmod for handling modules. I want to use Magit with the repositories on this remote, but the default system version of Git is 1.x. However, Git 2.18 is available on the cluster as a module (accessible at `/software/git-2.18/bin/git`), which I already called in my `.bashrc` through `module add git-2.18`. When Magit connects to the remote through Tramp, though, it still calls Git 1.x, resulting in ``` Error (magit): Magit requires Git >= 2.2.0, but on /ssh:myremote: the version is 1.x.x. If multiple Git versions are installed on the host, then the problem might be that TRAMP uses the wrong executable. First check the value of `magit-git-executable'. Its value is used when running git locally as well as when running it on a remote host. The default value is "git", except on Windows where an absolute path is used for performance reasons. If the value already is just "git" but TRAMP never-the-less doesn't use the correct executable, then consult the info node `(tramp)Remote programs'. ``` (The default value was Git already) I currently fixed this temporarily by setting the custom variable `magit-remote-git-executable` to `"/software/git-2.18/bin/git"`, but it makes it impossible to work on other remotes without modifying the variable manually each time. Would you have any thoughts on how to fix this on either end? Thanks # Answer > 1 votes How about using `C-h``i``g` `(emacs)Connection Variables` to conditionally set `magit-remote-git-executable` on the hosts where you want that? You could alternatively try setting `tramp-remote-path` such that your preferred location (if it exists) will be examined first when looking for `git`; but you may get better performance with `magit-remote-git-executable` set explicitly, so I'd try that first. --- Tags: magit, tramp, git, remote ---
thread-67970
https://emacs.stackexchange.com/questions/67970
What does the `@` mean in key-shortcuts?
2021-08-05T09:41:48.243
# Question Title: What does the `@` mean in key-shortcuts? For beginners it is sometimes hard to understand the description of key-shortcuts. I found a `@` sign in this context; e.g. `C-c @ C-f` What does it mean? More examples here: https://elpy.readthedocs.io/en/latest/ide.html#folding **EDIT**: When I literally type this I got `C-c @ C-f is undefined` **EDIT2**: And I am quit sure that elpy itself is active because a `*.py` file is opened and all the other elpy magic (syntax checks etc) are working well. # Answer The `@` symbol doesn't have a special meaning in a keybinding, it represents the symbol `@` (i.e., Shift+2 on US keyboards). `C-c @ C-f` is a keybinding defined by `hs-minor-mode`, which `elpy` has apparently extended. You should be able to use it after calling `M-x hs-minor-mode`. > 2 votes --- Tags: key-bindings ---
thread-67981
https://emacs.stackexchange.com/questions/67981
Emacs is slow, intermittently hangs, freezes when I "come back to it", profiler says `savehist`
2021-08-05T16:22:56.827
# Question Title: Emacs is slow, intermittently hangs, freezes when I "come back to it", profiler says `savehist` When I use Emacs it seems fine mostly, but since recently every couple of minutes it becomes extremely slow for a while. When I change focus to another app, and come back after a while, it is invariably unresponsive for \>10 seconds. Emacs is also very slow to boot now. I ran the profiler and got this result: ``` 41175 94% - timer-event-handler 41174 94% - apply 41102 94% - savehist-autosave 41100 94% - savehist-save 23713 54% - savehist-printable 4 0% #<compiled -0x1c1d3aafa883aee7> 4 0% #<compiled -0x1c1d3ab2e57b90e7> 64 0% + auto-revert-buffers 8 0% + show-paren-function 1 0% + timer-activate-when-idle 1859 4% + ... 386 0% + command-execute 65 0% + redisplay_internal (C function) 3 0% + jit-lock--antiblink-post-command 2 0% + winner-save-old-configurations ``` But savehist doesn't seem to have changed recently and it never gave me problems prior. What is happening, where do I go from here? # Answer > 4 votes Check your history file: `~/.emacs.d/history`. If it is very large (\> 10 MB), quit Emacs, then delete it. Credit to https://reddit.com/r/emacs/comments/5krh9b/long\_emacs\_pauses\_how\_to\_troubleshoot\_from\_here/ (/u/UpInHarms) --- Tags: performance, profiler ---
thread-67984
https://emacs.stackexchange.com/questions/67984
How to change visual appearance of ANSI colors for *shell* buffers running on "GUI Emacs"?
2021-08-05T17:06:37.413
# Question Title: How to change visual appearance of ANSI colors for *shell* buffers running on "GUI Emacs"? **OS:** Linux 4.19.0-16-amd64 #1 SMP Debian 4.19.181-1 (2021-03-19) x86\_64 GNU/Linux **Emacs:** GNU Emacs 28.0.50, with a solarized theme from here **Terminal emulator:** terminator 1.91, with a solarized (dark) palette --- The displays below were done by running the following bash script within a `*shell*` buffer (i.e. a buffer started with `M-x shell`): ``` echo -e '\e[30m██\e[31m██\e[32m██\e[33m██\e[34m██\e[35m██\e[36m██\e[37m██\e[0m' ``` "No-window"/"non-GUI" (`-nw`) Emacs process, running on a terminator 1.91 terminal emulator: "GUI Emacs" process: How can I make ANSI colors in the GUI Emacs environment look like those in the "non-GUI" environment? **NB:** I do *not* want to modify my terminal emulator in any way. I am happy with it. I want to modify *GUI Emacs* so that it produces the same behavior as my terminal emulator does. --- For what it's worth, below are the first 8 colors in the output for `(list-colors-display`) running on "non-GUI" Emacs, which correspond to the colors I get from the ANSI color test shown above: The colors with the same names (as reported by `(list-colors-display)` in "GUI-Emacs" are shown below; again, they match the colors from the ANSI colors test shown earlier: In light of this, it occurs to me that maybe a way to achieve what I want is to redefine the colors `black`, `red`, ..., `white`? How would I do this? Is there a "better" ("higher-level", more robust, etc.) way to solve this problem? --- EDIT: The accepted answer in #000000 and true black in terminal Emacs colors shows that its OP's issue was due to his gnome-terminal configuration. My question, on the other hand, has nothing to do with gnome-terminal, or with terminal emulators in general. *It's about GUI Emacs.* The one other answer to https://emacs.stackexchange.com proposes to modify the `default` font. This will *not* solve my problem. Changing the `default` font would affect at most one foreground color. I have a problem with 8 colors. Also, the text that exhibits these various colors often have the same face (e.g. `comint-highlight-prompt`). EDIT: I changed the code for the ANSI color test to this: ``` echo -e '\e[30m██\e[31m██\e[32m██\e[33m██\e[34m██\e[35m██\e[36m██\e[37m██\e[0m' echo -e '\e[30mXX\e[31mXX\e[32mXX\e[33mXX\e[34mXX\e[35mXX\e[36mXX\e[37mXX\e[0m' ``` Now, the output (on "GUI Emacs") is this: **The key point is this:** According to `describe-face`, *all* those X's have the `default` face. These means that ***no solution based on modifying *faces* will solve this problem***. --- **EDIT:** First I ran this: ``` ;; just to get a response... (setq ansi-color-names-vector ["red3" "red3" "red3" "red3" "red3" "red3" "red3" "red3"]) (ansi-color-make-color-map) ;; is this necessary??? ``` Then I started a fresh `*shell*` buffer (`M-x shell`), and ran the ANSI color test shown above, namely: ``` echo -e '\e[30m██\e[31m██\e[32m██\e[33m██\e[34m██\e[35m██\e[36m██\e[37m██\e[0m' echo -e '\e[30mXX\e[31mXX\e[32mXX\e[33mXX\e[34mXX\e[35mXX\e[36mXX\e[37mXX\e[0m' ``` I got the same results I got earlier. In particular, the 8 colors were different, even though all 8 entries in `ansi-color-names-vector` are the same. --- # Answer > 2 votes After some exploring, we determined that @Gilles suggestion of modifying `ansi-color-names-vector` was the correct approach. It can't be set with a regular `setq`, it needs to be updated through the `Customize` interface (i.e., `M-x customize-variable ansi-color-names-vector`. Changing the value won't change existing text in the shell terminal, but new text added after the update will take the new colors. If you do want to set it from code, you need to do this: ``` (setq ansi-color-names-vector ["red3" "red3" "red3" "red3" "red3" "red3" "red3" "red3"]) (ansi-color-map-update 'ansi-color-names-vector ansi-color-names-vector) ``` --- Tags: colors, ansi ---
thread-60866
https://emacs.stackexchange.com/questions/60866
How do I display links in a mu4E message at the end of the text
2020-09-27T18:29:26.947
# Question Title: How do I display links in a mu4E message at the end of the text I prefer reading plain text messages in Mu4E. However, I do not like its interface of mixing links with text on the same line. Is it possible to have Mu4E collect all links and list them at the end of the message, and only put numbers pointing to such links inside? for example, instead of "The great conference to take place http://onlineconferences.com/?c=1002&t=1400 had been rescheduled." It can be "The great conference (1) had been rescheduled" then before the message ends, we have: (1) http://www.conferences.com/c=1002&t=1400 # Answer > 0 votes Use a Python package, html2text (for my distro on Slint 14.21, latest is version 2020.1.16. Its description in the Slackdesc file is: "html2text (turn HTML into equivalent Markdown-structured text)". Try checking it either in your distro's package repository or using Python3-pip and do `pip3 install html2text`. And to to do what you are asking for, just pass `--reference-links` option to it. So in your `.emacs` file, you do something like this: ``` (setq mu4e-html2text-command "html2text --reference-links) ``` You can tweak a lot of other options if you like to tailor the end result. In my opinion, it is a tool that seems to convert html to markdown. Good luck! --- Tags: mu4e ---
thread-61775
https://emacs.stackexchange.com/questions/61775
Is there a gccemacs (native-comp) build for MS-Windows?
2020-11-16T16:28:07.563
# Question Title: Is there a gccemacs (native-comp) build for MS-Windows? I use the official binaries (28.0.50 prerelease) for MS Windows. I am using gccemacs on my home Linux machines, and feel like native-comp on Windows would be really useful for me at work. However, I don't have a MingW toolchain installed. Is anyone providing gccemacs binaries for MS-Windows? # Answer > 6 votes Here are unofficial builds https://github.com/kiennq/emacs-build/releases via https://www.emacswiki.org/emacs/GccEmacs # Answer > 7 votes Thanks to many people and their work here, the emacs native-compilation feature is now available on windows 10. Still yet you have to compile it yourself (from the Emacs master branch). First install msys2/mingw64 and all the required development packages for emacs (see nt/INSTALL.W64 in emacs source). Then install gcc and, of course, libgccjit. This later is now available as a regular mingw64 package. Then, still following nt/INSTALL.W64 : ``` ./autogen.sh ./configure --without-dbus --without-pop --with-native-compilation --prefix=/your/install/path make -j$(nproc) # or make NATIVE_FULL_AOT=1 -j$(nproc) // longer make install ``` Then create a batch script with : ``` @ECHO OFF TITLE Emacs - native-compilation SET HOME=C:\Users\yourname C: CD %HOME% IF EXIST .emacs.d\server\server DEL .emacs.d\server\server SET PATH=C:\msys64\mingw64\local\bin;C:\msys64\mingw64\bin;%PATH% C:\msys64\mingw64\local\bin\emacsclientw.exe -n -a C:\msys64\mingw64\local\bin\runemacs.exe -e "(make-frame-visible)" ``` And then, you can run it by clicking on the batch script as any other windows 10 program. I assume your msys64 installation is at C:\msys64 and that emacs - nativecomp is installed at C:\msys64\mingw64\local so as to not interfere with the default emacs 27.1 mingw64 package. It is mandatory to add "C:\msys64\mingw64\bin" to the windows path because emacs needs some libraries at startup which are in there. # Answer > 2 votes There isn't an "official" one at the moment. The windows port is a little flaky right now. Once it has had a bit more time to mature, or once it merges to master there will be an "official" snapshot (if that is not a contradiction in terms) of it. # Answer > 2 votes I created a MINGW `PKGBUILD` file for native compilation Emacs. You can find it here. A MINGW package is also available as a pre-release version here. You can install the pre-release version by using: ``` # Open mingw shell (e.g. msys2) pacman -U mingw-w64-x86_64-emacs-native-compilation-*-any.pkg.tar.zst ``` The request for merging this into `MINGW-packages` main fork (thus making Emacs native comp available via MINGW's `pacman`) was not approved, because native compilation is still an experimental feature. So for now, I can only provide it on my fork of the `MINGW-packages` repository. --- Tags: microsoft-windows, gccemacs ---
thread-61687
https://emacs.stackexchange.com/questions/61687
How can I move/kill multiple chunks of text to the same place/marker, one after another?
2020-11-11T20:07:03.660
# Question Title: How can I move/kill multiple chunks of text to the same place/marker, one after another? The task: I have a large-ish file, from which I need to pick certain chunks of text and move them into a certain place so they go one after another, in the order in which I pick them. More specifically, it's an Org-mode file, and the chunks are headings (possibly with subtrees). The target file may be the same, or it might not. Question: is there a package/mode or something, that would let me specify the target place and then add chunks of text there while I roam around and point out the pieces to cut? My attempts at finding such a thing turned up nothing so far, however the search terms are rather generic so the results are messy. I've thrown together code that inserts multiple items from the kill ring—I kill the chunks then insert them; but this doesn't seem quite clean, especially if I ever manage to save the file with the cuts made and have Emacs or the machine crash before inserting the text. Plus, the workflow doesn't feel right. Double kudos if the solution handles Org-mode headings: e.g. adjusts the inserted ones to the level of the ones in the target place. Triple kudos if I can bind it in Evil right away, i.e. it works with text objects. # Answer > 3 votes I believe you're looking for `org-refile` (bound to `C-c C-w`). By default, `org-refile` will only consider the current file. To refile into another file add the target file with your desired headings to `org-refile-targets`: ``` ;; Add the current buffer as possible refile target ; only consider up to level 2 as target. (add-to-list 'org-refile-targets `(,buffer-file-name :maxlevel . 2)) ``` You can also use a regular expression to refile to a specific heading: ``` ;; Use path/to/file as refile target, and ONLY headings that fit "List of great quotes" (setq org-refile-targets '(("path/to/file" :regexp . "List of great quotes"))) ``` `org-refile-targets`'s customization interface (`M-x customize-option RET org-refile-targets RET`) might be a little bit easier than lisp-based modification, though. Even better, store the location yourself and then use the stored location repeatedly: ``` (defvar aaa/refile-location nil "Location used for `aaa/refile-to-saved-location'. Use `aaa/save-refile-location' to set it in an org-mode buffer.") (defun aaa/save-refile-location () "Save current position for later refiling via `aaa/refile-to-saved-location'." (interactive) (when (not (equal major-mode 'org-mode)) (user-error "Refile location can only get saved in org-mode buffers!")) (let ((heading (org-entry-get nil "ITEM")) (file (buffer-file-name)) (pos (point))) (setq aaa/refile-location (list heading file nil pos)) (message "Saved \"%s\" in \"%s\"" heading file))) (defun aaa/refile-to-saved-location () "Move the current item to the saved location." (interactive) (if aaa/refile-location (org-refile nil nil aaa/refile-location) (user-error "Refile location is unset!"))) (global-set-key (kbd "<f6>") 'aaa/refile-to-saved-location) (global-set-key (kbd "C-<f6>") 'aaa/save-refile-location) ``` This will enable you to use `C-F6` to store your target location and `F6` afterwards to move items (with their subtree). # Answer > 4 votes A basic option is to use `append-next-kill`. Rather than killing each region with just `C-w` (or similar), you instead use `C-M-w``C-w` (i.e. type `C-M-w` immediately prior to whichever kill command you're using) to append the new kill to the most recent kill ring item. Do that for every region in sequence, and then a single `C-y` will insert the whole thing. ``` C-M-w runs the command append-next-kill (found in global-map) Cause following command, if it kills, to add to previous kill. If the next command kills forward from point, the kill is appended to the previous killed text. If the command kills backward, the kill is prepended. Kill commands that act on the region, such as ‘kill-region’, are regarded as killing forward if point is after mark, and killing backward if point is before mark. If the next command is not a kill command, ‘append-next-kill’ has no effect. ``` # Answer > 0 votes By the way, it turns out that the Doom configuration has functionality very similar to what I wanted. After using `org-refile`, mapped to `SPC m r r`, I can invoke `+org/refile-to-last-location`, or `SPC m r l`. (It's not the same as first pointing out the target destination, from the comfort of browsing the outline itself as usual—instead, `org-refile` pops up an Ivy/Helm completion listing all existing nodes in the file. But it's quite tolerable, at least as long as I know what the target node is called. And these commands have the benefit of already having decent mappings, instead of me desperately trying to come up with new ones.) Doom also has `+org/refile-to-other-window` (`SPC m r o`) and `+org/refile-to-other-buffer` (`SPC m r O`), which sound like they should do the same `org-refile` thing, but offer nodes from all open Org windows/buffers—in fact, the latter function's source seems to do exactly that. However for some reason they fail at this, and again do regular old `org-refile` to the current buffer. If I figure out the problem and a fix, these functions should alleviate almost all of my org-refile needs. (I'm guessing the hiccup is with some var not being dynamically overridden when it should be.) Conceivably, I could also write a command that will store a location for `+org/refile-to-last-location` to use, just as I would do with my separate custom commands (e.g. `aaa/save-refile-location`)—and invoke it from the outline, as I originally wanted. --- Tags: org-mode, kill-text ---
thread-67994
https://emacs.stackexchange.com/questions/67994
How to export a table as a Markdown table when using org-md-export-to-markdown?
2021-08-06T21:43:41.417
# Question Title: How to export a table as a Markdown table when using org-md-export-to-markdown? The current behavior of `org-md-export-to-markdown` is to export Org Mode tables as HTML tables. I would like tables to be exported as Markdown tables (as explained here). # Answer > 3 votes # Use the ox-gfm package The `gfm` part in the package name stands for "Github Flavored Markdown". This package is available at MELPA. The source code can be found at this repository at Github. A minimal working example is shown below. Consider the following Org Mode file ``` * The first heading | word | number | |---------+--------| | one | 1 | | ten | 10 | | hundred | 100 | * The second heading #+begin_src bash echo "Hello World" #+end_src #+RESULTS: #+begin_example Hello World #+end_example ``` By using `org-gfm-export-as-markdown` (function defined in the `ox-gfm` package) in the Org Mode buffer, the newly created buffer would look like <pre><code># The first heading | word | number | |------- |------ | | one | 1 | | ten | 10 | | hundred | 100 | # The second heading ```bash echo "Hello World" ``` ``` Hello World ``` </code></pre> # System information ``` emacs --version ``` ``` GNU Emacs 27.2 Copyright (C) 2021 Free Software Foundation, Inc. GNU Emacs comes with ABSOLUTELY NO WARRANTY. You may redistribute copies of GNU Emacs under the terms of the GNU General Public License. For more information about these matters, see the file named COPYING. ``` ``` (org-version) ``` ``` 9.4.4 ``` --- Tags: org-export, markdown ---
thread-67988
https://emacs.stackexchange.com/questions/67988
undo-tree is not able to load the latest changes from previous emacs daemon session
2021-08-05T21:45:46.857
# Question Title: undo-tree is not able to load the latest changes from previous emacs daemon session I can access all the changes in the `undo-tree` during `emacs --daemon` session. But when it session is killed and new `emacs --daemon` is started `undo-tree-visualize` is shown clean. `minimal.el`: ``` (defun my-save-all () (interactive) (let ((message-log-max nil) (inhibit-message t)) (save-some-buffers t))) (defun save-all () (interactive) (my-save-all) (bk-kill-buffers "magit: ebloc-broker") (bk-kill-buffers "__init__.py") (bk-kill-buffers "*helm")) (define-key ctl-x-map "\C-s" 'save-all) (global-undo-tree-mode 1) (setq undo-tree-auto-save-history t) (setq undo-tree-history-directory-alist '(("." . "~/.emacs.d/undo"))) ``` I have observe that `undo-tree` history is saved under `~/.emacs.d/undo` as hidden files but they won't loaded when new `emacs ---daemon` is started. simple scenario: ``` $ (&>/dev/null emacs --daemon -nw &) $ command emacsclient -tqu doo.py # - make changes check `undo-tree-visualize` # - kill `emacs —daemon` # restart `emacs daemon` $ (&>/dev/null emacs --daemon -nw &) $ command emacsclient -tqu doo.py # apply: M-x undo-tree-visualize # The undo-tree is empty ``` \[Q\] Is there anyway to force `emacs` daemon to load the already saved `unto-tree` history for the opened file. # Answer > 1 votes I forget to add following piece of code `async-undo-tree-save-history ()` at below, which was the main cause of the error. Since I wrote my own `save ()` function `after-save-hook` hook `(add-hook 'after-save-hook #'async-undo-tree-save-history)` does not properly save the `undo-tree` history. I have **commented** following section: ``` (with-eval-after-load "undo-tree" (remove-hook 'write-file-functions #'undo-tree-save-history-from-hook) (add-hook 'after-save-hook #'async-undo-tree-save-history)) ``` and updated my init.el file as follows: ``` (defun save-all () (interactive) (my-save-all) (async-undo-tree-save-history) ;; <== added here ``` --- > <pre><code>((file-name (buffer-file-name))) > (async-start > `(lambda () > (if (stringp ,file-name) > (list 'ok > (list :output (with-output-to-string > (add-to-list > 'load-path > ,async-undo-tree-save-history-cached-load-path) > (require 'undo-tree) > (find-file ,file-name) > (undo-tree-save-history-from-hook)) > :messages (with-current-buffer "*Messages*" > (buffer-string)))) > (list 'err > (list :output "File name must be string" > :messages (with-current-buffer "*Messages*" > (buffer-string)))))) > `(lambda (result) > (let ((outcome (car result)) > (messages (plist-get (cadr result) :messages)) > (output (plist-get (cadr result) :output)) > (inhibit-message t)) > (message > (cond > ((eq 'ok outcome) > "undo-tree history saved asynchronously for %s%s%s") > ((eq 'err outcome) > "error saving undo-tree history asynchronously for %s%s%s") > (:else > "unexpected result from asynchronous undo-tree history save %s%s%s")) > ,file-name > (if (string= "" output) > "" > (format "\noutput:\n%s" output)) > (if (string= "" messages) > "" > (format "\nmessages:\n%s" messages)))))) > nil)) > > (with-eval-after-load "undo-tree" (remove-hook 'write-file-functions > #'undo-tree-save-history-from-hook) (add-hook 'after-save-hook #'async-undo-tree-save-history)) ``` > </code></pre> --- Tags: undo-tree-mode ---
thread-68001
https://emacs.stackexchange.com/questions/68001
Export as nested lists instead of (sub)sections with org mode
2021-08-07T10:57:54.510
# Question Title: Export as nested lists instead of (sub)sections with org mode If I export an org file, like ``` * Item ** Subitem *** Subsubitem ``` and export it to latex it is converted to something like ``` [...] \section{Item} \label{sec:org1a2bb17} \subsection{Subitem} \label{sec:org7bddadf} \subsubsection{Subsubitem} \label{sec:org29ffdb2} ``` I.e. it translates it to sections and subsections. How can I configure org mode to convert it to nested lists (using itemize or enumerate), e.g. as: ``` [...] \begin{itemize} \item Item \begin{itemize} \item Subitem \begin{itemize} \item Subsubitem \end{itemize} \end{itemize} \end{itemize} ``` # Answer Try ``` #+OPTIONS: H:0 ``` and see the `Export settings` section of the manual with `C-h i g(org)Export settings` which says > ‘H’ > > ``` > Set the number of headline levels for export > (‘org-export-headline-levels’). Below that level, headlines are > treated differently. In most back-ends, they become list items. > > ``` The default list export to LaTeX is using `itemize` environments. The option `num:t` changes that to `enumerate` environments: ``` #+OPTIONS: H:0 num:t ``` > 1 votes --- Tags: org-mode, org-export, latex ---
thread-67998
https://emacs.stackexchange.com/questions/67998
org-capture header nesting levels
2021-08-07T06:36:11.960
# Question Title: org-capture header nesting levels I am a relative emacs/org newcomer, and I am trying to get org-capture tuned to what I am looking for. I do spend a lot of time trying to search for answers, but sometimes I just get stuck. what is happening is org-capture seems to be adding to much "header level". I have stripped down my template to the minimum: ``` ("j" "Journal" entry (file+olp+datetree ,(concat my/org-dir "journal.org")) "* %U\n%?") ``` After capturing I end up with: ``` * 2021 *** 2021-08 August ***** 2021-08-07 Saturday ******* [2021-08-07 Sat 08:21] This is an entry. ``` You can see that it is adding `**` on each level where I would want it to just add `*`. Is there any way to configure this, or does anyone see what might be wrong with my template? I am a Windows, I get the same thing with Emacs on Windows, and on WSL (Ubuntu). # Answer > 2 votes You probably have the variable `org-odd-levels-only` set to `t`. The default is `nil`, so see if you have set it inadvertently in your init file or through a Customization. See its doc string with `C-h v org-odd-levels-only` which says: ``` Non-nil means skip even levels and only use odd levels for the outline. This has the effect that two stars are being added/taken away in promotion/demotion commands. It also influences how levels are handled by the exporters. Changing it requires restart of ‘font-lock-mode’ to become effective for fontification also in regions already fontified. You may also set this on a per-file basis by adding one of the following lines to the buffer: #+STARTUP: odd #+STARTUP: oddeven ``` BTW, you might also want to check the variable `org-hide-leading-stars`: if you set it to `t`, you see the initial start as indentation. --- Tags: org-mode, org-capture ---
thread-67999
https://emacs.stackexchange.com/questions/67999
refresh org agenda (org-agenda-redo) scrolls buffer by 1 line
2021-08-07T09:06:30.127
# Question Title: refresh org agenda (org-agenda-redo) scrolls buffer by 1 line Since recently, whenever I refresh `*ORG Agenda*` with the "r" key (`org-agenda-redo`), the buffer will scroll up by 1 line, even if the buffer has not changed (best shown by hitting "r" repeatedly). I'm not sure whether this is due to an org-mode update or some configuration modification on my side (notably visual-line-mode), but going back on those changes doesn't help. Could anybody give me some pointers to what I could investigate? Alternatively, is there a workaround to reposition the buffer after redo exactly as it was? # Answer How do you turn on `visual-line-mode`? If you turn it on globally, you might want to turn it off in `org-agenda` buffers, by using the mode hook: ``` (defun turn-off-visual-line-mode () (visual-line-mode -1)) (add-hook `org-agenda-mode-hook #'turn-off-visual-line-mode) ``` The idea is that if it is turned off before the agenda buffer is populated, then the incompatibility will not arise. Untested, so caveat emptor. > 1 votes --- Tags: org-mode ---