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-69070 | https://emacs.stackexchange.com/questions/69070 | Batch mode, read NUL-delimited list of file names from stdin | 2021-10-24T22:17:06.993 | # Question
Title: Batch mode, read NUL-delimited list of file names from stdin
I am writing a batch Emacs script and I would like it to read a *NUL-delimited* list of file names to process from stdin. (NUL-delimited lists of file names are what you get from the Unix command `find ... -print0` among other things.)
I understand from the manual that, in batch mode, `read-from-minibuffer` reads from Emacs' stdin, and that one can control where it stops reading by supplying a keymap as an argument. Based on this, it seems like
```
printf 'foo\000bar\000baz\nblurf\r\n\000' |
emacs -no-site-file -batch -eval '
(let ((kmap (make-sparse-keymap)))
(define-key kmap "\C-@" '\''exit-minibuffer)
(message "%S" (read-from-minibuffer "" nil kmap)))
'
```
should print `"foo"`, but it does not. It prints `"foo^@bar^@baz"` where the two occurrences of `^@` represent literal NUL bytes. I also tried
```
printf 'foo\000bar\000baz\nblurf\r\n\000' |
emacs -no-site-file -batch -eval '
(message "%S" (read-from-minibuffer "" nil (make-keymap)))
'
```
with the same result (here I expected to get all of the input as a single string).
What am I doing wrong?
# Answer
> 4 votes
As NickD analyzed, `read-from-minibuffer` reads one line at a time, and considers either CR or LF to end a line and doesn't distinguish between them. And I can't find another way to read from `standard-input`.
If your operating system has `/dev/stdin` (which in practice, nowadays, basically means not Windows), you can open that. The following snippet parses a list of null-terminated items from standard input.
```
printf 'Γ©foo\000bar\000baz\nblurf\r\n\000' |
emacs -no-site-file -batch -eval '
(let ((parts (with-temp-buffer
(insert-file-literally "/dev/stdin")
(if (eobp)
nil
(split-string (buffer-substring-no-properties (point-min) (1- (point-max))) "\000")))))
(print parts))'
```
The special case `(eobp)` is for the empty input: this way, an empty input results in an empty list, while any other input is assumed to end with a null byte which gets truncated.
# Answer
> 3 votes
Assuming I'm reading the code correctly, the keymap argument is ineffective when `-batch` is used. What happens is that `read-from-minibuffer` gets called and it, in turn, calls `read_minibuf` (Line 1318 in my version of `src/emacs/minibuf.c` \- this is probably somewhat out of date but not too far off). `read_minibuf` (defined starting on line 545 of the same file) does a bit of initialization and then checks its `noninteractive` flag (line 621): if it is true (as it is in this case since we are using `-batch`), then it calls `read_minibuf_noninteractive` and just returns the result of this call. But `read_minibuf_noninteractive` does not care a whit about the keymap: it does not take it as an argument, it does not use it, it completely ignores it. All it cares about is low-level stuff: it gets characters using `getchar()` and looks for `EOF`, `\n` and `\r`. If it gets one of these, it returns whatever it has accumulated so far.
E.g. if I run the following command (a slight modification of yours so that I can store all the lisp code in a file):
```
printf 'foo\000bar\000baz\n\rblurf\000' | emacs --batch -l /tmp/foo2.el
```
where `foo2.el` contains the following code:
```
(setq s (read-from-minibuffer ""))
(print s)
(setq s2 (read-from-minibuffer ""))
(print s2)
(setq s3 (read-from-minibuffer ""))
(print s3)
(setq s4 (read-from-minibuffer ""))
(print s4)
```
I get the following output:
```
"foo^@bar^@baz"
""
"blurf^@"
Debugger entered--Lisp error: (end-of-file "Error reading from stdin")
read-from-minibuffer("")
(setq s4 (read-from-minibuffer ""))
eval-buffer(#<buffer *load*> nil "/tmp/foo2.el" nil t) ; Reading at buffer position 235
load-with-code-conversion("/tmp/foo2.el" "/tmp/foo2.el" nil t)
load("/tmp/foo2.el" nil t)
command-line-1(("-l" "/tmp/foo2.el"))
command-line()
normal-top-level()
```
So the first read returned the string "foo^@bar^@baz" including the NUL bytes but stopping at `\n`. The second read returned an empty string (the string between `\n` and '\r\`), the third read returned "blurf^@" including the NUL and stopping at EOF and the fourth read got an error because it tried to read past the EOF.
So I think the strategy that you have to follow is:
* do not allow `\n` and `\r` if you expect to read everything in one read.
* forget about handling the NULs using the keymap.
* do one read to get the whole input stream as a single string (including all the NULs) and then parse the string, splitting it at the NULs.
Something like this (note that I am using the library which is a third-party library available from MELPA):
```
(load-file "/path/to/s.elc")
(setq s (read-from-minibuffer ""))
(setq l (s-split "\000" s))
(print l)
```
Assuming that this is in a file `/tmp/foo3.el`, invoking it with a slight modification of your command line to avoid the troublesome `\n` and `\r`, but allowing spaces and tabs, gives this:
```
$ printf 'foo\000bar\000baz\t blurf barf\000' | emacs --batch -l /tmp/foo3.el
Loading /path/to/s.elc...
("foo" "bar" "baz blurf barf" "")
```
giving you a list of strings, which can be used for further processing, by splitting the original string at the NULs.
If you *have* to have `\n` and/or `\r` in your input, you will not be able to get the whole input in one read: you will have to loop until EOF (probably by catching the error and ignoring it other than treating it as the end of the input) and you will not be able to tell the difference between `\n` and `\r` since they are not part of the returned string and they both cause the same behavior. As long as the difference is not important, you can concatenate all the strings you read into one string with newline separators and then split the resulting string on NULs as above.
---
Tags: minibuffer, batch-mode
--- |
thread-69049 | https://emacs.stackexchange.com/questions/69049 | Emacs 28 and python-mode the syntax font-lock-mode seems all off | 2021-10-23T02:11:58.330 | # Question
Title: Emacs 28 and python-mode the syntax font-lock-mode seems all off
I wanted to upgrade to emacs 28 to get f-strings support in python but the `font-lock....` seem to be all messed up.
Sometimes it works as in the past but sometimes it doesn't like why is `post_split_val_size` not orange but the line below it is. This is inconsistent across all files, so not sure what is going on but checking if it is my setup only or an emacs 28 issue (:
# Answer
Usually, this is because font-lock does not recognize the item as being in one of its categories. You can check this by putting point on the variable and going to *Options-\>Customize Emacs-\>Specific Face*. In the minibuffer, you'll be offered the name of the face under point and the option to customize it.
However, I just checked my own python code, and it has the same issue as yours. I'm using LSP-Jedi. Are you using something like that? The text under point is `lsp-face-highlight-textual`. I guess I'll have to disconnect the server and see what that does.
EDIT: In my implementation, after getting rid of LSP & friends, the errant elements are not font-locked, they are unidentified. The properly formatted elements are `font-lock-variable-name`. This does look like a bug.
> 1 votes
---
Tags: python, font-lock
--- |
thread-69031 | https://emacs.stackexchange.com/questions/69031 | elpa package autoloads | 2021-10-21T08:58:47.000 | # Question
Title: elpa package autoloads
I am having issues with autoloading of elpa packages under different versions of emacs (under macOS if that matters).
My ~/.emacs.d is a link to somewhere else.
Take as an example amx
The loading works under emacs 25 and 27 but not under 28. The error is like Cannot open load file: No such file or directory, ../../../../../../../.emacs.d/elpa/28/amx-20210305.118/amx.el The load-path is correct for each version
The packages are loaded into a different path for each version using this code in early-init.el
```
(setq package-user-dir
(expand-file-name
(format "elpa/%s" emacs-major-version) user-emacs-directory))
```
I think the issue is with the generated amx-autoloads.el file and is the last line
emacs 25 has no register-definition-prefixes
emacs 27
```
(if (fboundp 'register-definition-prefixes) (register-definition-prefixes "amx" '("amx-")))
```
emacs 28
```
(register-definition-prefixes "../../../../../../../.emacs.d/elpa/28/amx-20210305.118/amx" '("amx-"))
```
In this file the generated comments are
emacs 25 -
```
;;;### (autoloads nil "amx" "amx.el" (24783 47304 949021 880000))
;;; Generated autoloads from amx.el
```
emacs 27
```
;;;### (autoloads nil "amx" "../../../../../../../.emacs.d/elpa/27/amx-20210305.118/amx.el"
;;;;;; "a034ecc8682671a85a9465e1b8dcc78e")
;;; Generated autoloads from ../../../../../../../.emacs.d/elpa/27/amx-20210305.118/amx.el
```
emacs 28
```
;;;### (autoloads nil "../../../../../../../.emacs.d/elpa/28/amx-20210305.118/amx"
;;;;;; "../../../../../../../.emacs.d/elpa/28/amx-20210305.118/amx.el"
;;;;;; (0 0 0 0))
;;; Generated autoloads from ../../../../../../../.emacs.d/elpa/28/amx-20210305.118/amx.el
```
So I think the problem is that emacs uses the relative path to a directrory in some places and uses the realpath (ie expands the symbolic link) rather than the path under ~/.emacs.d
How can I control the generation of the -autoloads.el files so that the expanded path is ideally not used as in emacs 25 or at least as in emacs 27 not really used.
I suspect that this question is the same issue but it has no answers
# Answer
> -1 votes
It may be corrupted byte-compilation. Delete the `.elc` files and recompile with v28. Keep in mind that after you do, earlier versions will not work anymore. So you might want to use a test bed to see what the outcome is, without wrecking your current production config.
---
Tags: package-repositories
--- |
thread-68831 | https://emacs.stackexchange.com/questions/68831 | org-babel python output drawing and print text at the same time | 2021-10-07T15:47:05.733 | # Question
Title: org-babel python output drawing and print text at the same time
I like to use org-babel to write tiny python code and drawing with matplotlib. but I can only output drawing or text, I have to switch the org header from "file link" to "output" each time if I want to see print output.
How can I enable both then no need to swich header options?
# Answer
> 0 votes
I think you want the `#+CALL` macro. In this example, evaluate the second code block (*emacs-lisp*), it will first run the *R* block and then pass its value to the *emacs-lisp* block. I copied this from the manual, so you may want to read further there about it - chapter 14.
```
#+NAME: random
#+begin_src R :cache yes
runif(1)
#+end_src
#+NAME: caller
#+begin_src emacs-lisp :var x=random
x
#+end_src
#+RESULTS: caller
: 0.397210547933355
```
---
Tags: org-mode
--- |
thread-68812 | https://emacs.stackexchange.com/questions/68812 | Is possible to set which-key package minimum height? | 2021-10-05T17:40:50.257 | # Question
Title: Is possible to set which-key package minimum height?
I'm using the `which-key` package and I checked the docs and it seems you can set the max height for the buffer with `(setq which-key-frame-max-height 20)` , but I can't seem to find a way to set the minimum height. I want to leave at least and empty line if the which key buffer is just a line height.
```
;; --- Which Key Mode ---
(use-package which-key
:ensure t
:defer t
:config
(setq which-key-idle-delay 3.0)
(setq which-key-separator " β " )
(setq which-key-unicode-correction 3)
(setq which-key-prefix-prefix "+" )
(setq which-key-side-window-location 'bottom)
;; This line doesn't seem to do anything
(setq which-key-min-display-lines 13)
)
```
Shows just two lines:
# Answer
I have a set of key bindings that is one line. When I apply your minimum height of '13', the one line turns into 3 lines, justified left. Setting it to larger values seemed to have no further effect. Unclear to me what is meant by 'lines.'
It's 50-50 whether the lines would be above or below the listed key bindings. I opened an issue at GitHub. We'll see what happens.
> 0 votes
---
Tags: which-key
--- |
thread-69083 | https://emacs.stackexchange.com/questions/69083 | Can window-height be ignored in display-buffer-alist after initial creation? | 2021-10-25T21:33:01.727 | # Question
Title: Can window-height be ignored in display-buffer-alist after initial creation?
Currently I'm using the following `display-buffer-alist`, which works fine but resets the size on opening a new window.
Is there a way to only use the `window-height` when first creating the window? After this, any resizing I do should be kept instead of being reset (when viewing another commit in this example).
```
(push
(list
"\\`magit-revision: "
(list 'display-buffer-reuse-window 'display-buffer-below-selected)
(cons 'window-height 0.8)
(cons 'reusable-frames 'visible))
display-buffer-alist)
```
# Answer
> 2 votes
This can be done by wrapping `display-buffer-reuse-window' to filter out the window-height from the alist, so it's only used for other functions (in this case` display-buffer-below-selected').
```
(defun my-display-buffer-reuse-window-without-size (buffer alist)
"Wrap `display-buffer-reuse-window' ignoring window-height."
(let *((skip-params (list 'window-height 'window-width 'window-min-height))
(alist-filter
(delete nil (mapcar (lambda (x)
(if (and (consp x) (memq (car x) skip-params))
nil
x))
alist))))
(display-buffer-reuse-window buffer alist-filter)))
(push (list "\\`magit-revision: "
(list 'my-display-buffer-reuse-window-without-height
'display-buffer-below-selected)
(cons 'reusable-frames 'visible)
(cons 'window-height 0.9))
display-buffer-alist)
```
---
Tags: window, display-buffer-alist
--- |
thread-68818 | https://emacs.stackexchange.com/questions/68818 | Calling elisp functions from inside yasnippet | 2021-10-06T08:32:13.620 | # Question
Title: Calling elisp functions from inside yasnippet
I created a yasnippet that calls a function:
```
# -*- mode: snippet -*-
# name: print
# key: pr
# --
`(cperl-print)`
```
The function code:
```
(defun cperl-print ()
(interactive)
(let* ((current (point))
(end (line-end-position)))
(if (< current end)
(insert "print")
(progn
(insert "print ;")
(backward-char 1))
)))
```
Unfortunately, `backward-char` doesn't produce any effect when called from inside yasnippet. When the function is called directly, it works. Is there any way to fix this?
# Answer
According to the documentation, there is `type` directive:
> If the type directive is set to command, the body of the snippet is interpreted as lisp code to be evaluated when the snippet is triggered.
So, I just used it and it worked.
```
# -*- mode: snippet -*-
# name: print
# key: pr
# type: command
# --
(let* ((current (point))
(end (line-end-position)))
(if (< current end)
(insert "print")
(progn
(insert "print ;")
(backward-char 1))))
```
> 0 votes
---
Tags: yasnippet
--- |
thread-69093 | https://emacs.stackexchange.com/questions/69093 | How to make backward-kill-word and kill-word stop after it kills a newline character? | 2021-10-26T16:15:44.903 | # Question
Title: How to make backward-kill-word and kill-word stop after it kills a newline character?
`kill-word` and `backward-kill-word` deletes too much text:
```
foo(bar)
<point>
```
Now if I press `C-<backspace>`:
```
foo(<point>
```
What I want is:
```
foo(bar)<point>
```
after pressing `C-<backspace>`, just like how the other editors do.
**EDIT:** Based on the answer from @gigiair, I'm trying to implement the command sequency in elisp, but I'm getting "Wrong number of arguments" when executing the code:
```
(defun leo/backward-kill-word ()
"Better backward-kill-word."
(interactive)
(set-mark-command)
(backward-sexp)
(forward-sexp)
(backward-delete-char-untabify))
```
I'm new to elisp, know nothing about.
# Answer
This sequence does it :
```
C-SPC ;; set-mark-command
C-M-b ;; backward-sexp
C-M-f ;; forward-sexp
<backspace> ;; backward-delete-char-untabify
```
This function executes this code :
```
(defun leo/backward-kill-word ()
"Better backward-kill-word."
(interactive)
(let((beg (point)))
(backward-sexp)
(forward-sexp)
(delete-region beg (point))))
```
This function is probably better
```
(defun leo/backward-kill-word ()
"Better backward-kill-word."
(interactive)
(fixup-whitespace)
(backward-delete-char-untabify 1))
```
> 0 votes
---
Tags: text-editing, motion, newlines, kill-text
--- |
thread-69097 | https://emacs.stackexchange.com/questions/69097 | How can I prevent ` running timer: (void-function vc-git-root)` error | 2021-10-26T19:33:10.047 | # Question
Title: How can I prevent ` running timer: (void-function vc-git-root)` error
> `vc-git-root` walks up the tree until it finds the directory that contains the `.git` subdir and declares that to be the root of the repo.
But if there is not `.git` folder in the root directory, `(vc-git-root (buffer-file-name))` gives following error `Error running timer: (void-function vc-git-root)`.
How could I fix it?
config:
```
(defun my-find-files ()
(interactive)
(message "press t to toggle mark for all files found && Press Q for Query-Replace in Files...")
(find-dired (vc-git-root (buffer-file-name)) "-name \\*.py"))
```
Related:
# Answer
> But if there is not `.git` folder in the root directory ... `(void-function vc-git-root)`
That error means that the function hasn't been defined.
The problem is that you haven't loaded the `vc-git` library before trying to use one of its functions. That was only working in other cases because when you *are* in a git directory, `vc` figures that out and loads the library for you.
```
(require 'vc-git)
```
> 1 votes
---
Tags: dired, git, find-dired
--- |
thread-69092 | https://emacs.stackexchange.com/questions/69092 | How can I jump beginning of the buffer under import section in python-mode | 2021-10-26T14:22:35.620 | # Question
Title: How can I jump beginning of the buffer under import section in python-mode
I am using `beginning-of-buffer` to the jump beginning of a buffer.
Is it possible to achive same behavior but to the first line under the `import or` from\` section in the Python mode.
In this example I want to jump to 17th line. There could be multiple modules under `from ... import (` and there could be also a new-line in between `from ...` and `import...` lines.
```
1: #!/usr/bin/env python3
2:
3: import os
4: import sys
5: import textwrap
6: import time
7: from broker.utils.tools import log
8:
9: import zc.lockfile
10: from ipdb import launch_ipdb_on_exception
11:
12: from broker.utils import (
13: CacheType,
14: StorageID,
15: )
16:
17: # <== jump here
18:
19: def _main():
20: from my_module.utils.tools import work
21:
22: work()
```
# Answer
> 1 votes
I am not aware of some existing function that does this. But there are many simple ways to achieve this; two commands you could use are:
EDIT in response to your first comment
So I guess after finding the last "import", you could just continue to look for the first empty line.
SECOND EDIT in response to your second comment
To exclude 'searching for/from' "import"s in 'the body' of the file, we can just limit the range for the search to "import", e.g. as follows:
```
(defun my-alternative-jump-to-end-of-imports ()
(interactive)
(goto-char (point-min))
(let (end)
(save-excursion
(forward-line 3)
(setq end (point)))
(while (search-forward "import" end t)
(save-excursion
(forward-line 3)
(setq end (point))))
(while (and (not (eobp))
(not (member (thing-at-point 'line t) '("" "\n"))))
(forward-line))
(if (bolp)
(forward-line)
(insert "\n\n"))))
```
You can play a little with the number of lines for searching forward. It is not perfect, but I guess it works fine for 99% of the cases.
END EDITS
I would suggest that you take some time to read a few chapters of An Introduction to Programming in Emacs Lisp (or read it right inside of Emacs) and study the above functions; it is not so much work, and Emacs becomes so much more fun to use.
---
Tags: python, buffers
--- |
thread-69101 | https://emacs.stackexchange.com/questions/69101 | How to filter by author in magit-log? | 2021-10-27T05:22:10.943 | # Question
Title: How to filter by author in magit-log?
In `gitk` you can for example do:
`gitk --author="Some Name"`
Is there a way to show/hide commits by author in the log view?
# Answer
From from the `magit-status` buffer press `l` to open the `magit-log` prefix transient window. Then in the `magit-log` transient window press `-A` to 'limit the commits' to "Some Name". Finally, press `l` again to get the actual filtered log.
> 2 votes
---
Tags: magit
--- |
thread-69106 | https://emacs.stackexchange.com/questions/69106 | org-link-open fails with Wrong number of arguments: (1 . 1), 0 | 2021-10-27T15:50:53.230 | # Question
Title: org-link-open fails with Wrong number of arguments: (1 . 1), 0
I recently added a config entry to my `./doom.d/config.el` to enable Firefox as a default browser for opening links. Below is the entry I added based on this post.
```
;; Set specific browser to open links from emacs
(setq browse-url-browser-function 'browse-url-firefox)
```
But after this, when I try to open a new link, I get `Wrong number of arguments (1 . 1) 0` error. Here is the debugger stack trace after enabling `toggle-debug-on-error`.
```
Debugger entered--Lisp error: (wrong-number-of-arguments (1 . 1) 0)
link-hint--open-org-link()
link-hint--apply(link-hint--open-org-link "https://drive.google.com/drive/folders/1yyYFggM3vx..." nil :open)
link-hint--action(:open (:pos 205 :win #<window 3 on linkedin.org> :args "https://drive.google.com/drive/folders/1yyYFggM3vx..." :type link-hint-org-link))
link-hint--one(:open)
link-hint-open-link()
funcall-interactively(link-hint-open-link)
call-interactively(link-hint-open-link nil nil)
command-execute(link-hint-open-link)
```
Can anyone help figure this error out.
# Answer
> 1 votes
Nothing to do with `org-open-link`: the error comes from `link-hint--apply` which tries various things in sequence as long as they produce errors (see the code here):
```
(defun link-hint--apply (func args &optional parser action)
"Try to call FUNC with ARGS.
If PARSER is specified, first change ARGS by passing PARSER ARGS and ACTION.
First try `apply'. If there is an error (ARGS is the wrong number of arguments
for FUNC), `funcall' FUNC with ARGS. Finally, call FUNC alone."
(when parser
(setq args (funcall parser args action)))
;; TODO is there a way to know how many arguments a function takes?
(condition-case nil
(apply func args)
(error (condition-case nil
(funcall func args)
(error (funcall func))))))
```
The problem is that something failed *before* the last failure which tried to call the function `link-hint--open-org-link` without arguments: since that function takes a single argument, calling it without any causes the error you see.
But the real question is why the previous two calls failed. So go to your `*scratch*` buffer which should be in `lisp-interaction-mode` and type:
```
(apply #'link-hint--open-org-link "https://drive.google.com/drive/folders/1yyYFggM3vx...")
```
except that you should give it the *FULL* URL (the error output elides part of it and replaces it with the ellipses `...` so I don't know what it should really be). Then press `C-j` after the closing paren and see what error you get. Is the URL correct? Can you open it in Firefox directly?
Then open an issue at https://github.com/noctuid/link-hint.el and tell them about the wrong error. No matter what, they should be reporting *all* the errors they get, not just the last one, similar to what Python does when it encounters an exception and during the handling of the exception, *another* exception occurs: just showing the last exception would lose important information. That's what happened here.
---
Tags: emacsclient, org-link, doom
--- |
thread-62187 | https://emacs.stackexchange.com/questions/62187 | Jupyter notebook, matplotlib visualization not showing up | 2020-12-09T15:01:37.827 | # Question
Title: Jupyter notebook, matplotlib visualization not showing up
I am a new Emacs user and proceeded to the install following the tutorial at: https://realpython.com/emacs-the-best-python-editor/#integration-with-jupyter-and-ipython. Now I am running a Jupyter Notebook, again as described in the link above, but I am getting the following error:
```
ein:cel--append-mime-type no viewer found in mailcap
```
Do you have any idea what I should do? I tried to solve it using https://github.com/millejoh/emacs-ipython-notebook/issues/671 but couldn't find the recommended fix (customize-group-ein-image on) to run.
```
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
# Data for plotting
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)
fig, ax = plt.subplots()
ax.plot(t, s)
ax.set(xlabel='time (s)', ylabel='voltage (mV)',
title='About as simple as it gets, folks')
ax.grid()
plt.show()
```
For information, I am running Emacs on Windows 10
# Answer
* You should `M-x customize RET` and look for "mailcap mime".
* Navigate to "Mailcap User Mime Data".
* INS new entry.
* Clock in Choice:`Value Menu` and choose Shell command.
* type in *Choice Shell command:* sxiv %s
* type in *MIME Type:* image/\*
Save the customization. Now, when jupyter looks for how to visualize an image file it will use `sxiv`. As the procedure we would like to emulate is upon a string-directory, the format is `sxiv %s(tring)`. Just like we would type in a terminal to visualize an image with sxiv, e.g., sxiv ~/path/to/my/image. The path is provided by a temporary file created by jupyter as the output of the cell.
I hope it's clear.
**ALTERNATIVE (tested)**: in `$HOME/.mailcap` file, put the following text and save it:
```
image/*; magick display %s
```
In Emacs, `M-x customize RET`, look for `ein inline images`, and `Toggle` to `on (non-nil)` the `Ein Output Area Inlined Images:` area.
```
Ein Output Area Inlined Images: Toggle on (non-nil)
State : SET for current session only.
Turn on to insert images into buffer. Default spawns external viewer.
Groups: Ein
```
If you have imagemagick installed (an image viewer and manipulator), you should be able to go to an ein-jupyter session, in a jupyter notebook, and see images inlined:
**EDIT: include author MWE** Your example works fine here, after this setup.
**NOTES:**
* You can use whatever image viewer software you would like, `sxiv`,`imagemagick`, `gimp`, etc.
> 1 votes
---
Tags: python, microsoft-windows, jupyter
--- |
thread-69103 | https://emacs.stackexchange.com/questions/69103 | EXWM performance and resources compared to other window managers | 2021-10-27T10:31:20.940 | # Question
Title: EXWM performance and resources compared to other window managers
I think about using EXWM on a Rapsberry Pi4 as a light weight window manager.
But how light is it really? I do not understand the underlying technology (X, Lisp, ...) enough to make own assumptions about this.
# Answer
**My background**
I'm a EXWM user; also I have used DWM and I've some background in installing various Linux distributions etc and some theoretical knowledge regarding software performance.
**Introduction**
First things first, how an OS can impact software performance: various OSes have various strategies to memory-allocate data. So, software that utilizes different data flow/structures in the same computer, but different OS, will have different performances Sulaiman, Raffi (2021). It's not an easy task to say this or that OS is better because it depends on the task, software being used, and a bunch of other variables; also, there is a case of scarse literature benchmarking about the subject.
**Case in hand** After this prelude, understand that Emacs Lisp is poorly run on Windows, for example, because of Windows File-system.
But, in your case, if you want fast and light, you shouldn't go with EmacsLisp EXWM, but probably DWM written in C. For small applications, and not exceeding complex software architecture, you should always go with C/C++/Rust etc (imperative languages). They run very fast in almost any platform and OS.
**Side note not directly related to the topic**
Although, I'm a Functional Programming (FP) aficionado, FP in only in it's baby steps being performant-competitive to C/C++ in general programming tasks. It certainly is faster than JavaScript in the web, vide Common Lisp benchmarks and Elm (blaziling fast) but we live in a Object-Oriented-Program-paradigm age, so it's simply overlooked and not taken in consideration when hiring people and choosing technology staks to solve problems. And, therefore, there is little effort to realize all the FP potential in it's fitting domain in Industry. We (FP-inclined people) however should not overlook where imperative languages shine, also; and in your case you are probably facing that scenario.
> 1 votes
---
Tags: exwm
--- |
thread-69107 | https://emacs.stackexchange.com/questions/69107 | How can I do something only if the minibuffer exits normally? | 2021-10-27T16:58:06.333 | # Question
Title: How can I do something only if the minibuffer exits normally?
Simply attaching to `minibuffer-exit-hook` is not enough, because it also runs when the user presses `C-g`, so the command quits.
Is there a way to determine in the hook if the command is exiting normally?
# Answer
A minibuffer prompt is a recursive edit, which ends by either throwing `'exit` or signaling `'quit` or another error. I think all normal exits from the minibuffer run `exit-minibuffer`, so you could advise that function.
> 2 votes
---
Tags: hooks, minibuffer
--- |
thread-69112 | https://emacs.stackexchange.com/questions/69112 | I need to restore the *scratch* buffer from the last time I used emacs even though I killed it and had to restart | 2021-10-27T20:17:14.463 | # Question
Title: I need to restore the *scratch* buffer from the last time I used emacs even though I killed it and had to restart
I was using emacs (XEmacs actually) and using the *scratch* buffer to experiment with regular expressions for a regex-replace operation that was giving me trouble. That has nothing to do with the problem, just setting the context.
A power failure caused me to have to reboot my computer and restart emacs. Because *scratch* can't be saved without explicitly copying it to a file, it's gone.
Is there any way to recover the previous (before the power failure) contents of *scratch* and, if so, how do I do it?
I'm not looking for suggestions for how to prevent this from being a problem in the future---I've figured that out. I just want restore the *scratch* contents that I just lost, if possible.
# Answer
Buffers that are not saved to a file are just kept in memory. The contents of memory are lost on a rebootΒΉ, so these buffers are gone. If you had a core dump, or a copy of your memory (such as you might get if you suspended your computer to disk), then perhaps you could recover it. Otherwise, no.
ΒΉ Technically memory can remain readable for a few minutes without power if you freeze the ram using propellant from a can of compressed air, liquid nitrogen, or some other means. But youβre probably not set up for that on short notice.
> 3 votes
---
Tags: persistence, recover, scratch
--- |
thread-14013 | https://emacs.stackexchange.com/questions/14013 | Change the default mode used when opening a new buffer | 2015-07-16T09:35:16.380 | # Question
Title: Change the default mode used when opening a new buffer
For example, we can open a new buffer with `C-x b <new-buffer-name>`, and by default, this new buffer opens in `fundamental-mode`, which is not very useful to me. I would like to change this to open all new buffers in `org-mode`. How can I do this?
# Answer
You have to customize the `major-mode` variable (see also the emacs manual). `C-h v`:
> Symbol for current buffer's major mode.
>
> The default value (normally \`fundamental-mode') affects new buffers. A value of nil means to use the current buffer's major mode, provided it is not marked as "special".
You can do this with `M-x customize-variable major-mode` or with something like `(setq-default major-mode 'org-mode)` somewhere in your init file.
See also `initial-major-mode` for the `*scratch*` buffer.
> 8 votes
# Answer
Add to your `init.el` one string:
```
(setq initial-major-mode (quote <major mode name>))
```
For example, I use `markdown-mode` as primary mode on my job:
```
(setq initial-major-mode (quote markdown-mode))
```
> 0 votes
---
Tags: buffers, major-mode
--- |
thread-69119 | https://emacs.stackexchange.com/questions/69119 | How can I sort a list of buffers according to a buffer-local variable? | 2021-10-28T11:15:09.113 | # Question
Title: How can I sort a list of buffers according to a buffer-local variable?
I am setting a buffer-local variable called `my/tab-order` in (some) of my buffers.
I have written the following function to return a list of buffers only where my/tab-order has been set and is greater than 0.
```
(defun my/unsorted-buffer-list ()
(seq-filter (lambda (buf)
(and
(local-variable-p 'my/tab-order buf)
(> (buffer-local-value 'my/tab-order buf) 0))
)
(buffer-list)))
```
I would now like a new function that sorts this list, according to `my/tab-order` (which is an integer).
I can sort this list by name with this function:
```
(defun my/sorted-buffer-list ()
(sort (mapcar #'buffer-name (my/unsorted-buffer-list)) #'string<)))
```
But I can't figure out how to sort by the buffer-local-variable. How can I do this?
# Answer
> 1 votes
IIUC, you want a function that will return the value of `my/tab-order` in a given buffer. Then you can use that function the same way (well, almost) that you use `buffer-name` to sort the buffers by name.
Since you are applying the function *only* to a list of buffers where `my/tab-order` is defined, we'll dispense with checking whether the value exists and what to do if it does not: we'll assume it's there.
The function is simple:
```
(defun my/buffer-tab-order (buffer)
(with-buffer buffer
(list my/tab-order (buffer-name buffer))))
```
The function returns a two-element list consisting of the tab order of the buffer and its name (since ultimately, the buffer name is what you want).
We need a comparison function that can compare two such lists and tell us which one is smaller. It just needs to compare the tab order of each such list which is the first element:
```
(defun my/buffer-tab-order< (l1 l2)
(< (nth 0 l1) (nth 0 l2)))
```
Then we map it across the list of buffers of interest and sort the results, using our comparison function for the two-element list structure:
```
(defun my/sorted-buffer-list ()
(sort (mapcar #'my/buffer-tab-order (my-unsorted-buffer-list)) #'my/buffer-tab-order<))
```
This produces the sorted list of `(tab-order buffer-name)` two-element lists. If you just want the buffer names only, just map a `cadr` on the list:
```
(defun my/sorted-buffer-list ()
(mapcar #'cadr
(sort (mapcar #'my/buffer-tab-order (my-unsorted-buffer-list)) #'my/buffer-tab-order<)))
```
Untested. It should work modulo typos: let me know if you run into problems.
The idea of attaching a sort key to an object, sort by the key value and then strip the sort keys out, is a common (almost ubiquitous) one. Here's an example from "The AWK Programming Language" from 1988, but it certainly goes back much further.
---
Tags: buffers, sorting
--- |
thread-69121 | https://emacs.stackexchange.com/questions/69121 | Tramp ignores remote paths, no matter what | 2021-10-28T14:37:25.813 | # Question
Title: Tramp ignores remote paths, no matter what
I run Emacs 27.1 in a Windows 10 environment, and I use `tramp` via `plinkx` for remote editing. I don't have `diff` installed locally, and I don't have the privileges to do it, so I'd like to avail of the one installed in the linux server. I put into my init.el
```
(require 'tramp)
(add-to-list 'tramp-remote-path 'tramp-own-remote-path)
```
But when I try to compare two buffers I get:
```
(file-missing "Searching for program" #("No such file or directory" 0 25 (charset windows-1252)) "diff")
call-process("diff" nil #<buffer *ediff-diff*> nil "--binary" "c:/Users/giglida/AppData/Local/Temp/1/responsabile..." "c:/Users/giglida/AppData/Local/Temp/1/responsabile...")
[...]
command-execute(execute-extended-command)
```
Why does it insist in searching for `diff` locally?
# Answer
> 3 votes
`call-process` runs local processes. For remote processes, you must use `process-file` instead.
---
Tags: tramp, remote
--- |
thread-69118 | https://emacs.stackexchange.com/questions/69118 | Unexpected org-export text duplication of hyperlinks | 2021-10-28T09:54:22.063 | # Question
Title: Unexpected org-export text duplication of hyperlinks
Given the following in my org-mode:
```
**** heading
***** [[https://somewhere.com][somewhere.com]]
***** [[https://somewhereelse.com][somewhereelse.com]]
```
(which my editor displays as links)
and the following options:
```
#+OPTIONS: ::t f:nil toc:nil tags:t num:nil author:nil H:11
```
org-export to text produces:
```
heading
=======
[somewhere.com] <https://somewhere.com>
* [somewhere.com]
[somewhere.com] <https://somewhere.com>
* [somewhereelse.com]
[somewhereelse.com] <https://somewhereelse.com>
```
There's duplication here which is unexpected and odd because it only happens to the link under the first point. Can anyone explain this to me?
# Answer
> 1 votes
Try setting `org-ascii-links-to-notes` to `nil` \- it is `t` by default. The doc string of the variable says:
> org-ascii-links-to-notes is a variable defined in βox-ascii.elβ.
>
> Its value is t
>
> Non-nil means convert links to notes before the next headline. When nil, the link will be exported in place. If the line becomes long in this way, it will be wrapped.
I have to admit I don't really understand its purpose, but I rarely use `ascii` export and this setting is very much specific to that export engine.
You can use a file-local variable (`C-h i g(emacs)File variables`) to set it for this file only if you don't want to change it globally. Putting that in a a separate section at the end of the file (it has to be at the end of the file BTW), and marking the section with the `noexport` tag, is a convenient way to keep this stuff in the file but never see it in the exported document. Something like this:
```
#+OPTIONS: ::t f:nil toc:nil tags:t num:nil author:nil H:11
* heading
** [[https://somewhere.com][somewhere.com]]
** [[https://somewhereelse.com][somewhereelse.com]]
* Local variables :noexport:
# Local Variables:
# org-ascii-links-to-notes: nil
# End:
```
---
Tags: org-mode, org-export
--- |
thread-69133 | https://emacs.stackexchange.com/questions/69133 | How to write an elisp function to insert some text at the beginning and end of a selected region? | 2021-10-29T13:11:10.590 | # Question
Title: How to write an elisp function to insert some text at the beginning and end of a selected region?
More specifically, I want to do something like this:
Select some region,
```
<mark>
int foo(int bar)
{
bar = do_something(bar);
return bar + 1;
}
<point>
```
and then type a command to do like this:
```
#if 0
int foo(int bar)
{
bar = do_something(bar);
return bar + 1;
}
#endif
```
Write an `#if 0` at the beginning of the region, and an `#endif` at the end. But it could be any arbitrary string really, even `/*` and `*/` to comment out the region.
# Answer
Thanks to some nice guy at the Doom Emacs discord server, I got it working:
```
(defun leo/c-if-0-region (beg end)
(interactive "r")
(save-excursion
(narrow-to-region beg end)
(set-mark nil)
(goto-char (point-min))
(insert "\n#if 0\n")
(goto-char (point-max))
(insert "\n#endif\n")
(widen)))
```
> 0 votes
---
Tags: region
--- |
thread-69130 | https://emacs.stackexchange.com/questions/69130 | Key sequence to automatically make math-mode fragments in org-mode? | 2021-10-29T11:00:02.353 | # Question
Title: Key sequence to automatically make math-mode fragments in org-mode?
My hands are getting lazier every day. Is there a key sequence to automatically type `\(_\)`, where `_` just denotes the position of my cursor, when I'm in org-mode? (Or `\[_\]`, of course: same question.)
# Answer
> 1 votes
I have a yasnippet for this:
```
# -*- mode: snippet; require-final-newline: nil -*-
# name: math for Org
# key: $$
# binding: direct-keybinding
# --
\\($1\\) $0
```
I type `$$` and get what you want: `\(_\)`.
---
Tags: org-mode, key-bindings, latex, math
--- |
thread-69132 | https://emacs.stackexchange.com/questions/69132 | Org-mode: Hide link's URL ([[URL][TITLE]]) in specific file | 2021-10-29T13:07:20.970 | # Question
Title: Org-mode: Hide link's URL ([[URL][TITLE]]) in specific file
I'm seeking for a file-local options (`#+OPTIONS:`) or something similar to auto set link display (See `M-x org-toggle-link-display` or variable `org-link-descriptive`).
I've tried `M-x add-file-local-variable-prop-line` provided by Emacs itself but seems doesn't work for org-mode and it's ugly.
Only found this: https://orgmode.org/manual/In\_002dbuffer-Settings.html but seems nothing is what I want......
# Answer
> 1 votes
Indeed, what you reported in the comments, that Org does not seem to honor the file-local-variable setting of `org-link-descriptive` appears to be a bug, and I've reported it to Org (https://lists.gnu.org/archive/html/emacs-orgmode/2021-10/msg00924.html).
In the meantime, a workaround is to put the following in your init file:
```
(defun my/fix-org-link-descriptive-local ()
(if org-link-descriptive (remove-from-invisibility-spec '(org-link))
(add-to-invisibility-spec '(org-link)))
(org-restart-font-lock))
(add-hook 'org-mode-hook #'my/fix-org-link-descriptive-local)
```
And don't forget to follow up on the bug report to remove it, when it gets fixed upstream.
With that in hand, adding the variable with `M-x add-file-local-variable` should work as expected, and place the corresponding setup at the end of your file.
@NickD's tip to make a heading for local variables is a good one to, to which I myself resort when setting file local variables with Org: it helps the visuals, and also makes some structural editing cleaner/safer. So, after setting the variable, the end of your file could look like:
```
* Local Variables :noexport:
# Local Variables:
# org-link-descriptive: nil
# End:
```
And which, normally, would just get folded, so you just see the heading.
---
Tags: org-mode
--- |
thread-47074 | https://emacs.stackexchange.com/questions/47074 | How can I change external program to open org URLs for one org file only | 2019-01-12T18:04:58.177 | # Question
Title: How can I change external program to open org URLs for one org file only
In my Emacs config, I have set Firefox to be the browser to open URLs with,
```
(setq browse-url-browser-function 'browse-url-firefox)
```
Now, I have one org-mode file, in which I would like to open URLs with a different program (`mpv`, to be precise).
What I'm currently trying is a buffer-local variable, indicated by a mode line
```
# -*- browse-url-browser-function: 'browse-url-chromium -*-
```
at the top of my org file. However, whenever I click on an org-mode link pointing to a URL (or, just click on a URL, for that matter), I get an error
```
Debugger entered--Lisp error: (wrong-type-argument listp quote)
browse-url("https://www.google.com/")
(lambda (path) (browse-url (concat "https:" path)))("//www.google.com/")
org-open-at-point()
org-open-at-mouse((mouse-2 (#<window 1244 on testfile.org> 192 (163 . 95) 82295534 nil 192 (20 . 4) nil (3 . 9) (8 . 19))))
funcall-interactively(org-open-at-mouse (mouse-2 (#<window 1244 on yoga.org> 192 (163 . 95) 82295534 nil 192 (20 . 4) nil (3 . 9) (8 . 19))))
call-interactively(org-open-at-mouse nil nil)
command-execute(org-open-at-mouse)
```
I would appreciate any pointer towards how I can resolve this.
# Answer
> 3 votes
Error is caused by this quote:
```
# -*- browse-url-browser-function: 'browse-url-chromium -*-
___________________________________|
```
It shouldn't be there.
## Open video path in MPV on \*nix OS's
Add this line to the init file(*.emacs*), or evaluate in Scratch buffer
```
(org-add-link-type "mpv" (lambda (path) (browse-url-xdg-open path)))
```
`browse-url-xdg-open` uses `xdg-open` program that exists on all \*nix desktops("X Desktop Group"). It check file extension to decide which program on desktop should open that path.
## Custom link in org mode:
```
[[mpv:/somepath_to_a_file/some_filename.extension]]
```
**mpv:** prefix, or any other defined by `org-add-link-type`
Actually it would open any file according to MIME type known to *xdg-open*. It would be MPV video player for a video file if it's configured as a default player on a desktop.
# Answer
> 0 votes
Like you, I could not figure out how to directly assign a function to a file variable using mode lines. What I ended up having to do was define a function that set the local variables that I wanted, and use a `Local Variables:` section at the end of the file to call the function.
```
(defun set-mpv-local-variables ()
"Set local variables for using mpv"
(set (make-local-variable 'browse-url-browser-function) 'browse-url-chromium))
```
Then at the bottom of your org document add:
```
# Local Variables:
# eval: (set-mpv-local-variables)
# End:
```
https://www.gnu.org/software/emacs/manual/html\_node/emacs/Specifying-File-Variables.html
If you only want to set one variable, just inlining the `set` expression may be enough, but if you need to set more than one local variable, I'd split it out into a separate function as I did here.
# Answer
> 0 votes
A link abbreviation
```
#+LINK: mpv elisp:(browse-url-xdg-open "%s")
```
in the .org file is a neat way to add a custom link type such as mpv: just for the current .org file.
---
Tags: org-mode, org-link, buffer-local
--- |
thread-69142 | https://emacs.stackexchange.com/questions/69142 | Cycling through a list back and forth | 2021-10-30T01:22:09.927 | # Question
Title: Cycling through a list back and forth
I need an interactive function that works like a generator, whenever it is called it should return "next" or "previous" value from a list. Whenever it reaches the end of the list, it should start over from the beginning (and vice versa when going backwards).
It looks like elisp offers (at least) a couple of ways to iterate forward (generators, cl-loop), but how do I cycle back?
I need something like:
```
(defvar my-list '(:a :b :c))
(defun cycle-through (previous)
(interactive)
(if previous
;; get previous --
;; get next))
(cycle-through) => :a
(cycle-through) => :b
(cycle-through t) => :a
(cycle-through) => :b
(cycle-through) => :c
(cycle-through) => :a
```
What's the best and elegant way of achieving something like that?
*Mind that the list may have duplicate values, trying to store the current value and determine the current position based on that not desirable.*
# Answer
There are many ways to do it, as you guessed. One simple way is to use a *ring*, which is a list used cyclicly. Standard library `ring.el` defines what you need to create and use rings.
This is from the Commentary at the beginning of `ring.el`:
> This code defines a ring data structure. A **ring** is a `(hd-index length . vector)` list.
>
> You can insert to, remove from, and rotate a ring. When the ring fills up, insertions cause the oldest elts to be quietly dropped.
>
> In `ring-ref`, 0 is the index of the newest element. Higher indexes correspond to older elements. When the index equals the ring length, it wraps to the newest element again.
>
> * `hd-index` = vector index of the oldest ring item.
>
> Newer items follow this item. At the end of the vector, they wrap around to the start of the vector.
> * `length` = number of items currently in the ring.
>
> This never exceeds the length of the vector itself.
>
> These functions are used by the input history mechanism, but they can be used for other purposes as well.
You can convert an existing sequence (list, vector, etc.) to a ring using function `ring-convert-sequence-to-ring`.
You can create an empty new ring with function `make-ring`.
You can easily guess what these other functions do:
* `ring-insert`
* `ring-extend`
* `ring-insert+extend`
* `ring-remove`
* `ring-member`
* `ring-elements`
* `ring-next`
* `ring-previous`
* `ring-ref`
* `ring-size`
* `ring-copy`
> 2 votes
---
Tags: cycling, iteration, generators
--- |
thread-69074 | https://emacs.stackexchange.com/questions/69074 | How to make buffer order in tab-line persistent? | 2021-10-25T12:55:20.750 | # Question
Title: How to make buffer order in tab-line persistent?
I'm using `global-tab-line-mode`, and I would like the order of tabs to persist.
Say my buffer/tab order is:
| `a.el` | `b.el` | `c.el` |
and `b.el` is the current buffer.
If I call `(find-file "a.el")` the tab order will change to
| `b.el` | `c.el` | `a.el` |
I find this disorienting and would prefer if the tab/buffer order did not change. As well as the order being persistent, I would also very much like it if I could manually change the order (eg move a tab left or right).
Is this possible?
In my config `tab-line-tabs-function` is set to `tab-line-tabs-window-buffers`. I have looked in the `tab-line-tabs-window-buffers` function and think if I can just sort the list it returns at the end I may be able to get the behaviour I want, but have not been able to achieve this.
I also tried setting `tab-line-tabs-function` to `bs-buffer-list`, but the sorting in that was even more unpredictable.
Any help greatly appreciated.
# Answer
Ok - so I've come up with a solution. It's not too pretty, and it needs polishing, but it works. Keen to hear any suggestions anyone has.
I am declaring a list that is my list of tabs to display, and `tab-line-tabs-function` draws from this.
```
(global-tab-line-mode)
(setq my/current-tab-list (list (current-buffer)))
(setq tab-line-tabs-function 'tab-line-tabs-mode-buffers)
(defun tab-line-tabs-mode-buffers ()
my/current-tab-list)
```
The following function adds new buffers to this list. I add this as a hook to find-file and dired-mode to automatically add new buffers as I open them.
```
(defun my/add-current-buffer-to-tab ()
(interactive)
(setq my/current-tab-list (add-to-list 'my/current-tab-list (current-buffer)))
)
(add-hook 'find-file-hook 'my/add-current-buffer-to-tab)
(add-hook 'dired-mode-hook 'my/add-current-buffer-to-tab)
```
To remove a buffer from this list when I close it, I call this custom function.
```
(defun my/close-tab ()
(interactive)
(setq my/current-tab-list (delete (current-buffer) my/current-tab-list))
(kill-buffer)
)
```
The following functions allow me to manually change the order of the buffers.
```
(defun my/shift-tab-left ()
(interactive)
(let ((n (seq-position my/current-tab-list (current-buffer))))
(when
(> n 0)
(progn
(setq my/current-tab-list
(append
(seq-take my/current-tab-list (- n 1))
(list (elt my/current-tab-list n))
(list (elt my/current-tab-list (- n 1)))
(seq-drop my/current-tab-list (+ n 1))
))))))
(defun my/shift-tab-right ()
(interactive)
(let ((n (seq-position my/current-tab-list (current-buffer))))
(when
(< n (- (length my/current-tab-list) 1))
(progn
(setq my/current-tab-list
(append
(seq-take my/current-tab-list n)
(list (elt my/current-tab-list (+ n 1)))
(list (elt my/current-tab-list n ))
(seq-drop my/current-tab-list (+ n 2))
)))))))
```
Sometimes I want a buffer to be loaded, but not appear in the tab list. For that situation I run the following function:
```
(defun my/drop-tab ()
(interactive)
(setq my/current-tab-list (delete (current-buffer) my/current-tab-list))
(switch-to-buffer (nth 0 my/current-tab-list))
)
```
And I use `tab-line-switch-to-next-tab` and `tab-line-switch-to-prev-tab` to move forwards and backwards.
As I say, needs a bit more polishing, but so far seems to be meeting my needs very nicely and seems robust enough. Sometimes after reordering the tabs it takes a moment to refresh.
Keen for any feedback. Not a programmer, just bodged this together, so will be interested to hear any constructive feedback/elisp rules I have broken.
> 3 votes
---
Tags: buffers, persistence
--- |
thread-69147 | https://emacs.stackexchange.com/questions/69147 | Emacs displays different formatting than what actually is | 2021-10-30T11:25:19.923 | # Question
Title: Emacs displays different formatting than what actually is
I have been using emacs for a while now, I am relatively new to it but while editing i noticed that sometimes emacs will show the code correctly formatted, when i open it with another text editor however, the code blocks will be all messed up and incorrectly placed. It is most notable when i try to carry a function or expression arguments to the next line to make a given line shorter etc. As you can see below the text editor (in this case CLion shows insane amounts of misalignment, emacs however shows the code differently. For example:
I have the following configurations (setq-default indent-line-function 'insert-tab) (setq-default indent-tabs-mode t) (setq-default tab-width 1)
If i comment out those settings it gets even worse, here is the last block in CLion again, completely mangled. In emacs it looks EXACTLY the same as with the tabs settings above enables. I am confused and I really need some feedback here, as i said i am rather new to it.
# Answer
> 1 votes
> I have the following configurations
>
> ```
> (setq-default indent-tabs-mode t)
> (setq-default tab-width 1)
>
> ```
What you're seeing is 100% expected with such settings.
When you use tabs for indentation there's always a chance that other editors will not be configured with the same tab width and will therefore render differently; but I'm confident that there isn't a text editor in existence that will default to a tab width of 1 space. (That's a crazy setting.)
If a line of code was indented to column 4, your settings would use 4 tabs to achieve that, and an editor with a tab width of 8 (which is pretty standard) would therefore indent that line to column 32.
Configure the tab width in your other editor to match, however, and you should see the same thing in both editors.
I suggest that you set your `tab-width` to something sane and re-indent; however if you want to guarantee that code will look the same in any editor *regardless* of configuration, then don't use tabs at all.
---
Tags: formatting, c
--- |
thread-69149 | https://emacs.stackexchange.com/questions/69149 | Trouble with f90 major mode, maltreatment of highlighting in continuation lines | 2021-10-30T12:00:20.617 | # Question
Title: Trouble with f90 major mode, maltreatment of highlighting in continuation lines
My emacs (version 27.1 on a work computer where I do not have administrative privileges) seems strange. I am editing a \*.f90 file and the major mode is correctly identified as f90. But the highlighting in continuation lines is off. Example:
```
PROGRAM test
integer :: a, b, &
c
END PROGRAM test
```
Variables a and b are highlighted in a reddish brown (as expected), but variable c is plain black. Is this normal or might there be something wrong with my setup? I have not customized anything.
# Answer
> 1 votes
If you want to report a bug in Emacs, use `M-x report-emacs-bug`.
However, I recommend simply diving into the source and fixing it; it looks like continuation lines are fairly wellβsupported for indentation, but they donβt appear to be handled by the highlighting. If you look at `f90-font-lock-keywords-2`, for example, the first new item in this list is a regex matching variable declarations. It clearly matches everything up to an ampersand, exclamation, or newline character.
---
Tags: syntax-highlighting, fortran
--- |
thread-69150 | https://emacs.stackexchange.com/questions/69150 | How can I use some package after other some other packages loaded? | 2021-10-30T17:30:44.183 | # Question
Title: How can I use some package after other some other packages loaded?
I am trying to start `dap-mode` in my golang project. I already have `lsp-mode` config set.
for example:
```
(use-package lsp-mode
:hook
((go-mode . lsp-deferred)
(rust-mode . lsp-deferred)
)
)
```
What I want is let `dap-mode` in `use-package` block, but only load the configs when it is `go-mode`.
I have wrote
```
(use-package dap-mode
:if (member major-mode '(go-mode))
:custom
(dap-auto-configure-mode t)
(dap-auto-configure-features
'(sessions locals breakpoints expressions tooltip))
:config
(require 'dap-go)
)
```
Then I have the question that, I am using emacs server and client. So if I first in my golang project, `dap-mode` has loaded, then when I in my rust project, even I don't want `dap-mode`, it is still loaded.
So actually it is some question of emacs server-client and `use-package` mode. How can I make the mode in `use-package` load in special type mode and unload in other modes without restart emacs server?
# Answer
```
(with-eval-after-load 'lsp-mode (require 'dap-mode))
```
or
```
(eval-after-load 'lsp-mode '(require 'dap-mode))
```
`C-h f with-eval-after-load` says:
> **`with-eval-after-load`** is a Lisp macro in `subr.el`.
>
> `(with-eval-after-load FILE &rest BODY)`
>
> Execute `BODY` after `FILE` is loaded.
>
> `FILE` is normally a feature name, but it can also be a file name, in case that file does not provide any feature. See `eval-after-load` for more details about the different forms of FILE and their semantics.
You can add the other code you want after the `(require 'lsp-mode)`. You can put any code you like there: the Customize code you want, for options such as `dap-auto-configure-mode`, additional `require`s, and so on.
> 1 votes
---
Tags: use-package, lsp-mode, server, load, eval-after-load
--- |
thread-69146 | https://emacs.stackexchange.com/questions/69146 | How to export code outputs to HTML using org-export? | 2021-10-30T09:16:34.410 | # Question
Title: How to export code outputs to HTML using org-export?
I have an org file with the following contents:
```
#+begin_src python
from datetime import datetime
return datetime.now()
#+end_src
#+RESULTS:
: 2021-10-30 17:05:27.247133
```
I want to export this file to HTML, both code and output. This can be achieved if I just add `:exports both` to the code header. But the tricky part is:
1. The org-mode exporter just evaluates the code, gets the new result (instead of the result shown in my org file), and converts it to HTML. The new output is not what I want because it runs in a new context. I want the output shown in the HTML to be **exactly** the same as the shown in the file.
2. If the code doesn't have a `#+RESULTS:` part in the org file, don't show it in the generated HTML file as well.
3. I have a lot of such org files to be converted into HTML, so it would be really great if I can change the behavior by just modifying some variables instead of changing each code block one by one.
Is it possible?
# Answer
You can use the `eval` header to influence when/how to evaluate a code block (do `C-h i g(org)Evaluating Code Blocks` and scroll down to the `Limit code block evaluation` subsection to see the details). In your case you want `:eval never-export`, which is described as follows in the manual:
> Org does not evaluate the source code when exporting, yet the user can evaluate it interactively.
You can specify it per-code-block with:
```
#+begin_src python :eval never-export
...
#+end_src
```
You can specify it per-subtree with:
```
* Limit it to the current subtree
:PROPERTIES:
:header-args: :eval never-export
```
or you can specify it per-file with:
```
#+PROPERTY: header-args :eval never-export
```
You can also limit it to blocks for a specified language by using e.g. `header-args:python` instead of `header-args`.
I looked for an option that you can set globally, but I don't think one exists. The closest I found is `org-export-use-babel`: setting it to nil stops the evaluation of (all) source blocks, but unfortunately it's a bit too blunt for your purposes: it also ignores headers. So I think you'll have to be satisfied with the per-file method. If you can identify all the files of interest, you could do a batch edit of all of them to add the appropriate `#+PROPERTY:` line at the top of each. Better yet, you might want to add a `#+SETUPFILE:` line in the batch edit instead, e.g.:
```
#+SETUPFILE: ~/src/org/setup.org
```
and put the `#+PROPERTY:` line in the setup file. That would be a one-time operation and from then on *every* file that includes that line would get whatever settings you put in your setup file - and if at some point you wanted to get rid of these customizations, you could make the setup file empty - or even delete it altogether, although that generates complaints in the `*Messages*` buffer.
EDIT: Here's how I tested. I created an Org mode file like this:
```
#+SETUPFILE: ~/src/org/setup.org
* Test
#+begin_src elisp
(random)
#+end_src
#+begin_src python :results value
from random import random
return random()
#+end_src
#+RESULTS:
: 0.10363433247781972
```
with the setup file containing this:
```
#+PROPERTY: header-args :exports both :eval never-export
```
and exported it to HTML. The resulting HTML file shows this (cut and pasted directly from Firefox):
```
1. Test
(random)
from random import random
return random()
0.10363433247781972
```
so no result from the lisp code block and the same result from the python code block as in the Org mode file (i.e. the RNG was *not* exercised again, the code block was not evaluated on export). I then evaluated the lisp code block manually to get this buffer:
```
#+SETUPFILE: ~/src/org/setup.org
* Test
#+begin_src elisp
(random)
#+end_src
#+RESULTS:
: 1890415366607963977
#+begin_src python :results value
from random import random
return random()
#+end_src
#+RESULTS:
: 0.10363433247781972
```
I saved the buffer and exported again to get this in Firefox:
```
1. Test
(random)
1890415366607963977
from random import random
return random()
0.10363433247781972
```
The resulting HTML contains exactly the same results as the Org mode file does: the code blocks do not get reevaluated. It seems to me that that's exactly what you asked for.
And a couple of things that you might have missed:
* Make sure that the `:exports both` header is present.
* Make sure that you save the buffer in the file before exporting.
* Make sure that if you add `#+PROPERTY:` or `#+SETUPFILE:` lines in the buffer, you restart Org mode on the buffer by pressing `C-c C-c` on one of those lines (any keyword line will do, actually).
> 1 votes
---
Tags: org-mode
--- |
thread-37910 | https://emacs.stackexchange.com/questions/37910 | fix or workaround: "Terminal is not fully functional" | 2018-01-05T13:49:24.930 | # Question
Title: fix or workaround: "Terminal is not fully functional"
What can I do about this issue? I'm using
psql, inside a ssh tunnel to ubuntu, inside a `M-x shell`, inside a `emacsclient -nw`
# Answer
# Quick answer
That's not an issue, it's a statement of fact. `M-x shell` isn't a fully functional terminal - it simply can't do what you want it to do. If you want a full terminal emulator in emacs, you have to use `M-x ansi-term` instead.
# Explanation
This isn't an Emacs issue per se, but a consequence of how different kinds of terminals process input, and especially output. All terminals support printing raw text, and accept lines of input ending with a return (enter key).
Some terminals also support escape sequences (which allow for coloured text), clearing lines, and controlling cursor position. Xterm is an example of this, and using these features you can create a complex interface like the Mutt mail program, or formatting and scrolling support as found in the terminal Man page viewer.
Terminals without these features are called `dumb terminals`. Dumb terminals can only print single color text to the screen, and can't back up or overwrite lines, as is necessary for an interactive display like Mutt provides, or Man uses to scroll up and down through a manual.
When a program that requires these features is started, it usually checks to see if the terminal supports them. One way to do this is to check the value of the environmental variable `TERM`. If the value of that variable is `dumb`, the program knows it can't rely on all the features it expects, and will warn the user with the message reported here.
You can still use a program that requires a fully functional terminal in a dumb terminal. There's no guarantee it will function properly, or at all. That's why you get the warning. If you really want to use such programs in a dumb terminal, without the warning, you could manually set the value of `TERM` to `xterm`, i.e.,
```
export TERM=xterm
```
You will no longer get the warning message, and you won't have to press `enter` before you can see the program output. But after that, the program will still behave strangely, because you have tricked it into thinking it can use features that aren't there.
That might work for simple cases. It would not work at all for Mutt.
In the Emacs context, `M-x shell` is a dumb terminal, built from the `comint` library. It is Emacs, so it would be possible in theory to extend it to fully support all the features of a fully-functional shell. I expect that is non-trivial. In practice, `ansi-term` already exists to fulfill this function.
# Eshell
`eshell` is a different kind of entity, being a terminal and shell written completely in elisp, and making it a special case that I won't get into here. I will note that the people who developed `Eshell` anticipate that users will want to use programs that require fully-functional shell features from within Eshell. They provide facilities to integrate `ansi-term` with `eshell`, with a bit of configuration (Eshell manual):
> If you try to run programs from within Eshell that are not line-oriented, such as programs that use ncurses, you will just get garbage output, since the Eshell buffer is not a terminal emulator. Eshell solves this problem by running such programs in Emacsβs terminal emulator.
> Programs that need a terminal to display output properly are referred to in this manual as βvisual commands,β because they are not simply line-oriented. You must tell Eshell which commands are visual, by adding them to βeshell-visual-commandsβ; for commands that are visual for only certain *sub*-commands β e.g., βgit logβ but not βgit statusβ β use βeshell-visual-subcommandsβ; and for commands that are visual only when passed certain options, use βeshell-visual-optionsβ.
This should address most use cases. Note that the recommended solution of the `eshell` developers is not to change `eshell`, but to automatically switch to `ansi-term` when `eshell` is incapable of providing the necessary features. Which brings us back to the short answer above: use `ansi-term` when you need a fully-functional terminal.
# What about `M-x shell`?
Emacs' `shell` doesn't have built-in support for visual commands like `eshell` does. You can add support yourself with relatively little effort. For example, the command line program `man` doesn't work properly in a dumb terminal, but there is an Emacs mode for it. You can call it directly from `M-x shell` by including the following function in your `.emacs.d/init_bash.sh` file:
```
function man() {
emacsclient -e "(man \"$@\")"
}
```
This requires that you are running emacs in daemon/server mode. If you are, using the `man` command from the Emacs shell will pass the argument to the elisp function `man`, opening the file in a buffer and displaying it properly.
You could use the same principle to replace programs with functions that do the appropriate thing for other programs. For instance, creating a function named `mutt` that opens and `ansi-term` buffer and runs the command `mutt` in it.
> 14 votes
# Answer
If you don't care about whether Emacs is a "fully-functional" terminal or not and you just want it to work without making you press enter, then run the psql command `\pset pager off`. This will make psql skip running a pager program and just dump all the output at once. You can then scroll through the output using the Emacs scrollbar or scrolling commands. The pager that it runs is typically `less`, which is what prints this message. You could also use `\pset pager more` to run `more` as the pager instead. `more` doesn't need many terminal capabilities and so it doesn't bother to print this message.
You could also arrange for the `PAGER` environment variable to be unset or to have a different value such as `more`.
> 6 votes
# Answer
> What can I do about this issue? I'm using `psql`, inside a `ssh` tunnel to ubuntu, inside a `M-x shell`, inside a `emacsclient -nw`
In short, "don't do that".
Emacs has excellent comint-based support for `psql` via `M-x` `sql-postgres`, and the `sql-interactive-mode` buffer created by that can interact with `sql-mode` buffers so that you can write queries in the latter and send them to the former. In Emacs I wouldn't want to be running `psql` any other way.
> 1 votes
# Answer
I fixed this by adding the following line to my`~/.bashrc` file (note the whitespace around the square brackets matters)
```
[ "$TERM" = "dumb" ] && export PAGER=cat
```
Without this change, my `PAGER` environment variable was set to `less -R`, which is what gives the warning (i.e. try running `echo foo | less -R`). The nice thing about this fix is it should only apply to shells that need it because it only sets `PAGER` when `TERM=dumb`.
> 1 votes
# Answer
`export TERM=eterm ;` Inside your `M-x shell`
> 0 votes
---
Tags: shell, terminal-emacs, eshell, ssh
--- |
thread-45678 | https://emacs.stackexchange.com/questions/45678 | Spacemacs redefine main prefix `M-m` | 2018-10-31T18:21:24.340 | # Question
Title: Spacemacs redefine main prefix `M-m`
I am trying Spacemacs with emacs keybindings, so the commands starting with `SPC`, like `SPC f e d`, can be invoked by replacing `SPC` with `M-m`.
Since `M-m` is bound to `back-to-indentation` in stock emacs, I would like to remap the prefix `M-m` to `M-n`, so that I can then safely bind `M-m` to `back-to-indentation`.
How can I achieve this?
# Answer
> 2 votes
There are settings for the leader key in your `.spacemacs` file. I have remapped mine to Page Up, (which is represented as `<prior>` by emacs). Here's what I have in my `.spacemacs`:
```
;; The leader key
dotspacemacs-leader-key "<prior>"
;; The key used for Emacs commands (M-x) (after pressing on the leader key).
;; (default "SPC")
dotspacemacs-emacs-command-key "<prior>"
;; The key used for Vim Ex commands (default ":")
dotspacemacs-ex-command-key ":"
;; The leader key accessible in `emacs state' and `insert state'
;; (default "M-m")
dotspacemacs-emacs-leader-key "<prior>"
```
You may not need to set all three here as I have, start with just the leader key accessible in emacs state ("M-m") and see if that works.
# Answer
> 0 votes
I'm recovering the `back-to-indentation` functionality with `M-m M-m`. For now it seems to be a good compromise.
See my **dotspacemacs/user-config** configuration below:
```
(defun dotspacemacs/user-config ()
"Configuration for user code:
This function is called at the very end of Spacemacs startup, after layer
configuration.
Put your configuration code here, except for variables that should be set
before packages are loaded."
(spacemacs/set-leader-keys
"M-m" 'back-to-indentation))
```
---
Tags: spacemacs, prefix-keys
--- |
thread-69160 | https://emacs.stackexchange.com/questions/69160 | conf "language" in org-babel | 2021-10-31T17:06:37.220 | # Question
Title: conf "language" in org-babel
```
#+NAME: certfile
#+begin_src emacs-lisp
(cond
((eq system-type 'gnu/linux) "/etc/ssl/cert.pem")
((eq system-type 'darwin) "~/Mail/certificates/root-certificates.pem"))
#+end_src
#+begin_src conf :tangle .mbsyncrc :noweb yes
User user@domain.org
CertificateFile <<certfile()>>
#+end_src
```
I don't see `conf` language being listed at https://orgmode.org/worg/org-contrib/babel/languages/index.html
Is it functioning example or just pseudo-code org-babel snippet? How to install it?
# Answer
> 0 votes
My mistake was that I used `org-babel-execute` instead of `org-babel-tangle`.
Also, `conf-mode` package is nice to have installed for such blocks.
---
Tags: org-babel
--- |
thread-68753 | https://emacs.stackexchange.com/questions/68753 | grep contents of a set of files from find | 2021-10-01T12:42:10.943 | # Question
Title: grep contents of a set of files from find
I want to grep contents of all CMakeLists.txt files in a project (nested within a directory) so I can jump from each instance, like I would when running emacs grep function. In the examples below I'm looking for "Boost".
I can get the results I want with the following command in bash:
```
grep Boost $(find . -name CMakeLists.txt)
```
I tried:
* in eshell calling `$grep Boost $(find . -name CmakeLists.txt)`
* calling emacs-grep with `grep --color -nH --null -e Boost $(find . -name CMakeLists.txt)`
* noodling around with projectile.
So far with no success. Can someone enlighten me?
# Answer
> 0 votes
I'm not sure I understand the question, so maybe this won't help, but...
There's command `find-grep-dired`. Here's its doc from the version in `find-dired+.el`:
> **`find-grep-dired`** is an interactive compiled Lisp function in `find-dired+.el`.
>
> It is bound to `menu-bar search find find-grep-dired`, `menu-bar subdir find find-grep-dired`.
>
> `(find-grep-dired DIR REGEXP &optional DEPTH-LIMITS EXCLUDED-PATHS)`
>
> Use Dired on the list of files in `DIR` whose contents match `REGEXP`.
>
> The `find` command run (after changing into `DIR`) is essentially this, where `LS-SWITCHES` is `(car find-ls-option)`:
>
> ```
> find . \( -type f -exec grep grep-program find-grep-options \
> -e REGEXP {} \; \) LS-SWITCHES
>
> ```
>
> Thus `REGEXP` can also contain additional grep options.
>
> Optional arg `DEPTH-LIMITS` is a list `(MIN-DEPTH MAX-DEPTH)` of the minimum and maximum depths. If `nil`, search directory tree under `DIR`.
>
> Optional arg `EXCLUDED-PATHS` is a list of strings that match paths to exclude from the search. If `nil`, search all directories.
>
> When both optional args are non-`nil`, the `find` command run is this:
>
> ```
> find .
> -mindepth MIN-DEPTH -maxdepth MAX-DEPTH
> \( -path EXCLUDE1 -o -path EXCLUDE2 ... \)
> -prune -o -exec grep-program find-grep-options -e REGEXP {} \;
> LS-SWITCHES
>
> ```
>
> where `EXCLUDE1`, `EXCLUDE2`... are the `EXCLUDED-PATHS`, but shell-quoted.
---
There's also command `find-dired`, which is essentially a general `find` command:
> **`find-dired`** is an interactive compiled Lisp function in `find-dired+.el`.
>
> `(find-dired DIR ARGS &optional DEPTH-LIMITS EXCLUDED-PATHS)`
>
> Run `find` and put its output in a buffer in Dired Mode.
>
> Then run `find-dired-hook` and `dired-after-readin-hook`.
>
> The `find` command run (after changing into `DIR`) is essentially this, where `LS-SWITCHES` is `(car find-ls-option)`:
>
> ```
> find . \( ARGS \) LS-SWITCHES
>
> ```
>
> Optional args:
>
> * `DEPTH-LIMITS`: Minimum and maximum depths: `(MIN-DEPTH MAX-DEPTH)`.
> * `EXCLUDED-PATHS`: Strings matching paths to be excluded. Uses `find` switch `-path`.
>
> When both optional args are non-`nil`, the `find` command run is this:
>
> ```
> find . -mindepth MIN-DEPTH -maxdepth MAX-DEPTH
> \( -path EXCLUDE1 -o -path EXCLUDE2 ... \)
> -prune -o \( ARGS \) LS-SWITCHES
>
> ```
>
> where `EXCLUDE1`, `EXCLUDE2`... are the `EXCLUDED-PATHS`, but shell-quoted.
# Answer
> 0 votes
If I'm reading the question rightly, you want `M-x` `find-grep`
You would run that and then edit the template, adding the files names to search, and the pattern to grep. The before/after would be something like this:
```
find . -type f -exec grep --color -nH --null -e \{\} +
find . -type f -name CmakeLists.txt -exec grep --color -nH --null -e 'Boost' \{\} +
^^^^^^^^^^^^^^^^^^^^ ^^^^^^^
```
You would enter the grep pattern first, as Emacs puts the cursor at that position in the prompt (after the `-e`); but you can then edit the rest of the options as required. By default, if you enter only a grep pattern, the command will search all regular files.
---
Tags: projectile, find-file, grep
--- |
thread-69157 | https://emacs.stackexchange.com/questions/69157 | init-open-recentf with use-package | 2021-10-31T13:44:59.540 | # Question
Title: init-open-recentf with use-package
I want to use `use-package` for nearly everything in my `init.el`. I have set up `recentf`. And to make the recent-file buffer pop up when Emacs starts I also included the `init-open-recentf` package.
But I cannot make it work with `use-package`. The `recentf-list` does not pop up on start.
This question is not only about how to make it work but more about how to make it work the `use-package` way.
This is the problematic `init.el`
```
(use-package recentf
:bind
("C-x C-r" . recentf-open-files)
:config
(setq recentf-max-menu-items 15
recentf-max-saved-items 100
)
(recentf-mode 1))
(use-package init-open-recentf
:after recentf
:config (init-open-recentf))
```
Of course I can call `init-oopen-recentf` outside the `use-package` thing. But I assume there is a way to do this with `use-package`.
```
(use-package init-open-recentf
:after recentf)
;; works
(init-open-recentf)
```
# Answer
Your snippet isn't working because `recentf` won't load until you press the `C-x C-r` key combination, which in turn implies `init-open-recentf` will not be loaded. You can read more about lazy loading with `use-package`.
```
(use-package recentf
:bind ("C-x C-r" . recentf-open-files)
:config
(setq recentf-max-menu-items 15
recentf-max-saved-items 100
)
:hook (after-init . recentf-mode))
(use-package init-open-recentf
:after recentf
:config (init-open-recentf))
```
This works for me. The hook ensures that `recentf-mode` is loaded and configured after Emacs starts. It is possible to come up with alternate forms using `:init` sections.
You will need to add `:demand t` to the second `use-package` macro if you have set `use-package-always-defer` to a non-nil value.
> 2 votes
---
Tags: init-file, use-package, recentf
--- |
thread-69165 | https://emacs.stackexchange.com/questions/69165 | Cannot display full string in emacs | 2021-11-01T02:45:05.033 | # Question
Title: Cannot display full string in emacs
I have doomemacs installed freshly, without any customization, and I found my emacs hides part of the string from being displayed in `emacs-lisp-mode`. E.g., the following line:
```
(package! org-roam-ui :recipe (:host github :repo "org-roam/org-roam-ui" :files ("*.el" "out")))
```
is been displayed as:
```
(package! org-roam-ui :recipe (:host github :repo "org-roam/org..." :files ("*.el" "out")))
```
the `org-roam-ui` is displayed as `org...`, Why is that and how I bring the full string display back?
# Answer
> 0 votes
Youβve left out any information about what you did to arrive at this problem, so I will have to use my psychic debugging powers and guess. If you had just typed this into a source buffer then this probably wouldnβt have happened, so you must have evaluated some code and this is the result of that evaluation.
In that case, the variables `eval-expression-print-length` and `eval-expression-print-level` control how expressions are abbreviated. As chapter 27.9 Evaluating Emacs Lisp Expressions of the Emacs manual says:
```
The options βeval-expression-print-levelβ and
βeval-expression-print-lengthβ control the maximum depth and length of
lists to print in the result of the evaluation commands before
abbreviating them. Supplying a zero prefix argument to
βeval-expressionβ or βeval-last-sexpβ causes lists to be printed in
full.
```
You can read the manual inside of Emacs by typing `C-h i`, then selecting the Emacs manual from the list.
---
Tags: doom
--- |
thread-69164 | https://emacs.stackexchange.com/questions/69164 | Skeleton for org source blocks causing issues | 2021-10-31T20:59:14.733 | # Question
Title: Skeleton for org source blocks causing issues
I've tried to setup a skeleton to speed up entering org source blocks
```
(define-skeleton skel-org-block
"Insert an org block, querying for type."
"Type: "
"#+begin_" str " " (setq v1 (skeleton-read "Language and headers?: ")) "\n"
_ - \n
"#+end_" str "\n")
(global-set-key (kbd "C-c b") 'skel-org-block)
```
This works fine in a fresh .org file. But problems occur when I try to add a new source block above an existing one:
* Doing `C-c b` above the block
```
#+begin_src python
blah
#+end_src
```
adds a comma before the first line of the old block:
```
#+begin_src python
#+end_src
,#+begin_src python
blah
#+end_src
```
* If I'm adding a new block via `C-c b` to the very end of an org file, I can leave the "Language and headers?: " prompt in the minibuffer blank, and I get a simple org block. If I repeat this above an existing org block, I get a message saying `org-edit-src-code: No such language mode: nil-mode`.
Something's clearly going wrong with the line `(setq v1 (skeleton-read "Language and headers?: "))`, but I'm not sure what.
Is there a fix? Is there a simpler skeleton to help me create an org block on the fly, with headers? (I could always remove the `setq` line, but I'd like to be able to specify language and switches.)
# Answer
> 1 votes
\[Making my comment into an answer, as suggested\]
I don't understand what the skeleton buys you: you still have to type the language and the headers which you might as well type in the source block instead. I personally use `C-c C-,` (bound to `org-insert-structure-template`) and Org tempo templates (`<s TAB`) as described in the manual: do `C-h i g(org)Structure Templates`.
For the Org tempo templates, you need to `(require 'org-tempo)`.
---
Tags: org-mode, org-babel, literate-programming, skeleton
--- |
thread-69173 | https://emacs.stackexchange.com/questions/69173 | Not correct show time (Daylight Saving Time) | 2021-11-01T18:12:27.893 | # Question
Title: Not correct show time (Daylight Saving Time)
Linux Mint 20.2
Emacs 27.2
Before 2 days (on 31 Oct) in our country **Daylight Saving Time Ended**.
```
When local daylight time was about to reach
Sunday, 31 October 2021, 03:00:00 clocks were turned backward 1 hour to
Sunday, 31 October 2021, 02:00:00 local standard time instead.
```
OS Linux Mint show current time 08:09 PM. OK. This is a correct.
But on Emacs (mode-line) the time is 09:09 PM - it's incorrect.
In my init.el
```
(setenv "TZ" "GMT-3")
(display-time-mode 1)
```
# Answer
You set the time zone to `GMT-3`. This means it's 3 hours later than GMT all year round. This can't be correct if the place where you live has DST. Use the correct time zone name, for example `TZ=Europe/Kiev`. On Linux Mint, the system time zone name is in `/etc/timezone`.
It's really weird to set a time zone specifically for Emacs. Since your operating system has the correct time, just remove the setting of `TZ` for Emacs. (And if your OS didn't have the correct time, my advice would be to fix that.)
> 3 votes
---
Tags: time-date
--- |
thread-69176 | https://emacs.stackexchange.com/questions/69176 | How do you find all macro calls in an elisp file? | 2021-11-01T20:04:08.797 | # Question
Title: How do you find all macro calls in an elisp file?
I am trying to make sure a package that is installed from Melpa (`org-ref`) byte compiles correctly, and a typical issue is related to the use of macros. For example, if I use `org-with-wide-buffer` which is a macro defined in `org-macs.el` I need to make sure to put
`(eval-and-compile (require 'org-macs))` in it so the package works as expected from Melpa.
The tricky thing is finding all the macro calls, so I know when to do this. I wondered if there is a way to find these in an elisp file. It seems like one just walks through all the s-exps and checks if the `(macrop (car sexp))` is non-nil, and print it or something so I can figure out what to put at the top. Does something like this already exist?
Or is there some way to test if there are uncompiled macro calls? I already can cleanly compile the package; the issues come up when using the functions.
# Answer
> 4 votes
I found a way to do it interactively with `el-search` (http://elpa.gnu.org/packages/el-search.html).
```
M-x el-search `(,(pred macrop) ,_)
```
finds them. Interestingly, it matches backticked s-exps like ``(:annotation-function ,type-annotation)` too.
Here is an interactive function version:
```
(defun find-macro-calls-1 ()
(interactive)
(goto-char (point-min))
(el-search (read "`(,(pred macrop) ,_)")))
```
---
Tags: elisp-macros, byte-compilation
--- |
thread-69178 | https://emacs.stackexchange.com/questions/69178 | SICSTus Emacs Interface - Installation | 2021-11-01T22:07:26.107 | # Question
Title: SICSTus Emacs Interface - Installation
I am currently trying to install the SICSTus Emacs Interface on Ubuntu to use Emacs to program in Prolog, but it seems that I am too stupid to do so. On https://sicstus.sics.se/sicstus/docs/4.3.5/html/relnotes/Emacs-Installation.html#Emacs-Installation it says I just need to load the file `sicstus_emacs-init.el`. I am totally new to Emacs. I suppose "load the file" means I should open it with Emacs. But how am I able to execute the code to configure the Interface?
# Answer
For reference, the documentation says this:
```
The easiest way to configure the Emacs interface is to load the file
sicstus_emacs_init.el from your .emacs file. It will find the SICStus
executable and do all initialization needed to use the SICStus Emacs
interface.
```
It means that you should put `(load "sicstus_emacs_init")` in your init file (which might be `~/.emacs` or `~/.emacs.d/init.el`).
Of course, Emacs still need to know where this file is. Emacs will look in every directory in the variable `load-path` for this file, so you might want to first add the SICSTus installation directory to that list. The documentation says:
```
The default installation location for the Emacs files is
<prefix>/lib/sicstus-4.3.5/emacs/ on UNIX platforms and
C:\Program Files\SICStus Prolog VC14 4.3.5\emacs\ under Windows.
```
Thus you would add something like this to your init file, making sure to adjust it for the location where you have actually installed the software:
```
(add-to-list 'load-path "<prefix>/lib/sicstus-4.3.5/emacs")
```
You might want to read chapter 27.8 Libraries of Lisp Code for Emacs of the Emacs manual for more information about how to load libraries. The manual can also be read inside of Emacs by typing `C-h i`, and choosing it from the list. You mentioned Ubuntu though, so be aware that Debian and Ubuntu and some related distributions donβt install the manual unless you install a separate package, which is stupid.
> 1 votes
---
Tags: shell, load
--- |
thread-69175 | https://emacs.stackexchange.com/questions/69175 | Hide siblings of first level on sparse tree | 2021-11-01T19:38:49.997 | # Question
Title: Hide siblings of first level on sparse tree
By pressing \[Enter\] on an entry in `org-agenda`, the sparse tree containing the entry shows up.
The variable `org-show-context-detail` controls how to see such a sparse tree (docs). Pairs "context -\> detail-level" are setup on it. As I understand from the docs, the context "agenda" is the one that controls the jump from the agenda view to the tree.
I tried setting all the detail-level values (minimal, local, ancestors, lineage, tree, canonical) and none of them seems to do what I need (`minimal` gets close, though):
Given a tree like this;
```
* A
** A.1
** A.2
* B
** B.1
** B.2
*** B.2.i
*** B.2.ii
* C
** C.1
*** C.1.i
```
Setting the detail-level to `minimal`, if I go from the agenda to the tree by pressing \[Enter\] or Tab in an entry that contains `B.2.ii`, I get:
```
* A...
* B
** B.2...
*** B.2.ii
* C...
```
I would like to **hide all siblings of first level headlines**, to get something like:
```
* B
** B.2
*** B.2.ii
```
Or maybe show just the immediate parent of the matched headline:
```
** B.2
*** B.2.ii
```
Is there a way to accomplish these two desired views?
I saw this entry Reveal entry's parents recursively, but not siblings here, but I couldn't make an analogy to my situation (which, as I understand, would be setting up "canonical" detail-level for the agenda context.)
# Answer
Pressing \[Enter\] on an item in the agenda does *not* show a sparse tree (do `C-h i g(org)Sparse trees` to see where sparse trees are used): what it does is it visits the file from which the item came, puts `point` on the item and then decides (depending on the agenda setting in `org-show-context-detail`) how much of the context to show *if `point` is not already visible*. If `point` is already visible, then Org mode assumes that everything is fine and does not do anything.
Try this: in the file, do `S-TAB` until everything is folded as much as possible. Then go to the agenda and press `[Enter]` on the item. That will reveal the context as specified in the `org-show-context-detail` variable. You can try all the different settings, but none of them do what you want, because the top level headings are always shown, even when the file has been folded as much as possible. The closest you can get I think is this:
```
#+STARTUP: overview
* A...
* B...
** B.2...
*** TODO B.2.ii
SCHEDULED: <2021-11-01 Mon>
* C...
```
by setting the agenda context to `ancestors`.
The only way to get what you want I believe is to modify `org-show-set-visibility` to interpret a new detail setting and then set the agenda context to that new detail setting. But I don't see a way to do it without code modifications. You might want to submit an enhancement request to the Org mode mailing list (although there is no guarantee that anybody will implement it).
> 2 votes
---
Tags: org-mode, org-agenda
--- |
thread-69181 | https://emacs.stackexchange.com/questions/69181 | How to evaluate Python code blocks with pipenv instead of system environment? | 2021-11-02T00:08:54.290 | # Question
Title: How to evaluate Python code blocks with pipenv instead of system environment?
I'm trying to use org-mode as an alternative to Jupyter. I'm able to evaluate code blocks with system environment by doing `C-c C-c` on blocks, but I don't know how to evaluate it through pipenv environment. I installed and configured pipenv.el but the documentation doesn't say how to evaluate code blocks with it.
# Answer
Here's how I configured `pipenv` package after installing it:
```
(use-package pipenv
:hook (python-mode . pipenv-mode)
:commands (pipenv-mode
pipenv-activate
pipenv-run))
```
When you open a buffer with python code, if you want the code to be ran by pipenv you have to activate pipenv first by doing `M-x pipenv-activate` once.
> 2 votes
---
Tags: org-mode, org-babel, python
--- |
thread-69172 | https://emacs.stackexchange.com/questions/69172 | How do you target the present directory, once in a while, with do-what-I-mean enabled? | 2021-11-01T13:59:32.113 | # Question
Title: How do you target the present directory, once in a while, with do-what-I-mean enabled?
After setting Dired do-what-I-mean
```
(setq dired-dwim-target t)
```
which, quoting the man pages
> If non-nil, Dired tries to guess a default target directory. This means: if there is a Dired buffer displayed in some window, use its current directory, instead of this Dired bufferβs current directory.
but you frequently want the target to be some other directory. In particular, you may want to copy (if copy is the operation at hand) to the same directory, not to the `C-x 3` (and hence `dwim`eant) directory.
How do you target the present directory, once in a while, with dwim enabled?
# Answer
> 3 votes
I think such exclusions cannot be pre-determined, but are simply decisions you make at the time you decide to copy the file.
In such cases I just use `M-n` at the prompt, which gives me the original directory as the first option.
> `M-n` runs the command `next-history-element`
>
> Puts next element of the minibuffer history in the minibuffer. With argument N, it uses the Nth following element. **The position in the history can go beyond the current position and invoke "future history."**
Where "future history" can be alternatively phrased as "educated guesses". This works at many prompts.
In this case, dired ensures that the original directory is first in that list.
---
Tags: dired, minibuffer, default
--- |
thread-69188 | https://emacs.stackexchange.com/questions/69188 | emacs 26.1 "Symbolβs function definition is void: bibtex-completion-candidates-formatter" | 2021-11-02T14:15:04.637 | # Question
Title: emacs 26.1 "Symbolβs function definition is void: bibtex-completion-candidates-formatter"
I have updated to Emacs 26.1. and reinstalled all packages. When running `helm-bibtex`, the bibliographies are loaded, but then the process terminates with the following error message:
`helm-bibtex-candidates-formatter: Symbolβs function definition is void: bibtex-completion-candidates-formatter`
Can anyone give me a hint what might cause this problem? I am using `helm-bibtex` 2.0.0 and `bibtex-completion` 20211019.1306, both from MELPA.
# Answer
> 0 votes
`helm-bibtex 2.0.0` is five years old. The variable`bibtex-completion-candidates-formatter` was removed in 2016. Updating to the current version on Melpa, 20210725.1510, should fix this problem.
---
Tags: debugging, helm-bibtex
--- |
thread-69185 | https://emacs.stackexchange.com/questions/69185 | Using `:scale` with org-mode's image links and include first and last page of pdf in latex export | 2021-11-02T09:39:42.007 | # Question
Title: Using `:scale` with org-mode's image links and include first and last page of pdf in latex export
I'm trying to include the first and last page of a PDF document in a new PDF document that I create via org-mode's Latex export engine. With this I have two issues:
1. I would like to include the first and last page of the external PDF document scaled to their real size and not scaled down to fit the margins of the new PDF. However, I have not found much information about the `:scale` parameter in org-mode's manual. If I run:
```
#+ATTR_LATEX: :scale 1.0
```
or
```
#+ATTR_LATEX: :scale 100.0
```
the external PDF is not included at all.
2. I would like to be able to choose which page of the external PDF to include. The default behavior when including a link to an external PDF as in:
```
[[/my/directory/my-external-document.pdf]]
```
is to include *only* the first page of the PDF linked. How could I include another page, such as the last one?
Thank you all!
# Answer
> 0 votes
I think you'll get somewhere faster if you can separate out the first and last pages of the external PDF file into their own PDF files.
On Linux, you can use `pdfseparate` (part of the `poppler-utils` package) to separate pages out of the external PDF file. Let's say the last page is page 42 (you can determine how many pages the PDF file file has with `pdfinfo` which is in the same package):
```
pdfseparate -l 1 external-file.pdf foo-first.pdf
pdfseparate -f 42 external-file.pdf foo-last.pdf
```
Then use links to the separate pages:
```
* Test
The first page of the external PDF file looks like this:
[[/my/directory/foo-first.pdf]]
* Another test
The last page, magnified by a factor of 1.2, of the external PDF file looks like this:
#+ATTR_LATEX: :scale 1.2
[[/my/directory/foo-last.pdf]]
```
If you look at the produced TeX file, you should see something like this:
```
\documentclass[11pt]{article}
...
...
\begin{document}
\tableofcontents
\section{Test}
\label{sec:org13d6711}
The first page of the external PDF file looks like this:
\begin{center}
\includegraphics[width=.9\linewidth]{/tmp/foo-first.pdf}
\end{center}
\section{Another test}
\label{sec:orgd2e453b}
The last page, magnified by a factor of 1.2, of the external PDF file looks like this:
\begin{center}
\includegraphics[scale=1.2]{/tmp/foo-last.pdf}
\end{center}
\end{document}
```
Other OSes should allow you to split pages out of a PDF file similarly, but you'll have to figure out what is available on them - I can't help with that.
---
Tags: org-mode, pdf, inline-image, scaling
--- |
thread-69191 | https://emacs.stackexchange.com/questions/69191 | Building custom theme based on another | 2021-11-02T16:34:20.903 | # Question
Title: Building custom theme based on another
Since the first time I set a custom theme in Emacs and then later attempted to modify some faces, I learned how to do it dynamically with the currently loaded and enabled theme.
Now, I am finally trying to build a set of my "own" themes. But of course, I want to base them on other popular themes. And I am a bit perplexed.
What does it mean for a theme to be loaded? What does this exactly do?
```
;; let's say my currently loaded theme is different
(load-theme 'zenburn :dont-ask :dont-enable)
```
And If I load a theme but don't enable it, can I still fetch all its faces and their attributes?
I want to do something like: `(custom-theme-set-faces 'my-dark-theme ...` but instead of listing all the faces and their attributes by hand, I want to get them from another theme (not currently enabled one), and only change selected faces.
# Answer
With the great help from amazing Henrik Lissner (Doom Emacs author) and others, I have found answers to my questions:
* About multiple enabled themes. Why is it possible to enable multiple themes?
> If you have multiple themes active at the same time, you have multiple groups of faces active at once. e.g. Theme 1 sets the background of emacs to red. Theme 2 sets the color of bold text to blue. Theme 3 makes comments dark grey.
> Activate them all and you have a red background, blue bold text, and dark grey comments. Though, generally, folks don't design their themes to be modular.
* How to get faces for a loaded yet not enabled theme?
> I think you'd need to look into (enable-theme)
I checked the code and found that `(enable-theme)` does: `(get theme 'theme-settings)`. That however returns a lot of data that I needed to streamline a bit; After a bit of bike-shedding, I wrote this:
```
(defun color-theme-get-faces (theme)
"Get list of faces with their attributes of a given THEME.
If theme is not loaded, it loads it first"
(let* ((theme (get theme 'theme-settings))
(theme-settings (if theme theme
(progn
(load-theme theme :no-ask :no-enable)
(get theme 'theme-settings))))
(extract-props (lambda (props)
"extracts face props based on display type"
(seq-reduce
(lambda (acc x)
(pcase-let ((`(((,disp-type ,disp-val)) ,face-props) x))
(if acc acc
;; prioritize graphic & color displays
(cond ((eq disp-val 'graphic) face-props)
((eq disp-val 'color) face-props)
((eq disp-type 'min-colors) face-props)
(t face-props)))))
props nil))))
(seq-remove
'null
(seq-map
(lambda (x)
(pcase-let* ((`(,prop-type ,face _ . (,props)) x))
(when (eq prop-type 'theme-face)
(list face (funcall extract-props props)))))
theme-settings))))
```
> 1 votes
---
Tags: themes, load
--- |
thread-69192 | https://emacs.stackexchange.com/questions/69192 | How to display file containing old extended-ASCII code-page characters? | 2021-11-02T18:24:18.953 | # Question
Title: How to display file containing old extended-ASCII code-page characters?
How can I setup Emacs to be able to display the content of an old file that contains non-ASCII 8-bit characters that we encoded using a code-page my system does not seem to support?
I have a file that has most probably been written in Germany in the days of 8-bit extended ASCII and Emacs does not display those characters properly. I was thinking I code tell Emacs to try various encoding and see if text would show up. Encoding like Windows 1250 code-page or some others.
Can this be done in Emacs?
# Answer
> 1 votes
`M-x set-buffer-file-coding-system` and select the desired coding system.
This is, by default, bound to `C-x RET f`.
Notice that `C-x RET` is a prefix map. For more info, `C-x RET C-h` (or equivalently `C-x C-m C-h`).
---
Tags: character-encoding
--- |
thread-69124 | https://emacs.stackexchange.com/questions/69124 | Show all prioritized items in sublistings | 2021-10-28T17:21:51.417 | # Question
Title: Show all prioritized items in sublistings
I have trees of tasks in org-mode. They are organized into several headings, and subheadings. I have prioritized items at every level.
Is there a way to show all the prioritized item from all subheading levels by priority. For example all the #A items, or all the #b items?
I have a bunch of things with priorities and some without. I want to have a way to just see the prioritized items.
# Answer
> 1 votes
This will give you an unsorted sparse tree of all lines (unfortunately not just headlines) containing a priority cookie within an individual Org file:
```
C-c / (or M-x org-sparse-tree)
r (to enter a pattern)
\[#[ABC]]\] RET
```
The pattern means: left square bracket, then `#`, then either `A` or `B` or `C` (the default set of priorities), then right square bracket.
Use the pattern `\[#B\]` for only priority B, etc.
See `(info "(org) Sparse Trees")`.
You might want to submit a bug report/request for enhancement asking to add an option for creating priority sparse trees to the existing set of options (TODO state, tags, properties etc). It seems like a good idea to me.
```
M-x org-submit-bug-report
```
---
Tags: org-mode
--- |
thread-69197 | https://emacs.stackexchange.com/questions/69197 | How can I add global (usable outside of Emacs) hotkeys? | 2021-11-03T06:01:26.437 | # Question
Title: How can I add global (usable outside of Emacs) hotkeys?
Several applications like Mumble allow the use of *global* hotkeys that even get intercepted if Mumble is not in focus at the time of the key press.
Is there a way within Emacs to create such shortcuts, for example to immediately invoke `org-capture` via `Super-C`? Or do I need to use an external application such as AutoHotkey?
(If the functionality requires a specific operating system or Desktop environment: I'm on Windows 10)
# Answer
> 2 votes
It generally requires listening to *all* keystrokes all the time, and swearing profusely that youβre not a keylogger. And naturally the way you implement it is quite different from OS to OS. It therefore cannot be done directly in Emacs lisp; it requires some level of C programming to integrate with the OS.
I donβt believe that anyone has implemented this integration, but I could be wrong. In any case, if you want to try it the source is readily available. If you donβt want to modify Emacs directly, know that Emacs does have the ability to load pluggable modules; you could write one of those instead. You should read chapter 16.11 Emacs Dynamic Modules from the Emacs Lisp Manual for more information.
---
Tags: key-bindings, microsoft-windows
--- |
thread-69201 | https://emacs.stackexchange.com/questions/69201 | BIND org-export-filter with multiple functions | 2021-11-03T09:57:24.053 | # Question
Title: BIND org-export-filter with multiple functions
I'd like to be able to pass more than one headline filter function to a `BIND` inside my org file:
```
#+BIND: org-export-filter-headline-functions (tmp-f-one tmp-f-two)
```
Although the pluralised name of the directive `headline-functionS` makes me think this function can accept more than one argument, in this case it seems to ignore `tmp-f-one` and only use the `tmp-f-two`.
How to I get this directive to filter using both functions?
# Answer
> 1 votes
What makes you think that `tmp-f-one` is ignored?
The following works fine for me:
```
#+BIND: org-export-filter-headline-functions (tmp-f-one tmp-f-two)
* Test one
One
* Test two
Two
* Code :noexport:
#+begin_src elisp
(defun tmp-f-one (data backend info)
(string-replace "one" "ONE" data))
#+end_src
#+RESULTS:
: tmp-f-one
#+begin_src elisp
(defun tmp-f-two (data backend info)
(string-replace "two" "TWO" data))
#+end_src
#+RESULTS:
: tmp-f-two
```
Both headlines are modified as expected.
---
Tags: org-mode, org-export
--- |
thread-69199 | https://emacs.stackexchange.com/questions/69199 | Is there indentation in org src blocks? | 2021-11-03T08:49:57.497 | # Question
Title: Is there indentation in org src blocks?
I'm going kinda crazy trying to understand what's going on here... Asked this question on the r/emacs subreddit so apologies if any of you are seeing this again.
Do org blocks allow `TAB` indentation without going into special editing mode via `C-c '` ?
I have the following relevant settings in my `custom-set-variables` block (i.e. edited via `customize-mode`.
```
'(org-edit-src-content-indentation 0)
'(org-src-preserve-indentation nil)
```
I used these settings because I was getting sick of editing code in the source block and having all the lines jump 2 spaces to the right.
`org-src-tab-acts-natively` is set to `t` as well.
But now when I write
```
#+begin_src python
def hello():
|
#+end_src
```
the cursor is stuck at the start of the line and I can't use `TAB` to indent to add a new line, i.e. to *make it look like*:
```
def hello( ):
print("hello)
```
`TAB` **used** to work -- or atleast, I thought it was working. This github comment suggests that this facility was never actually available, and we always had to use `C-c '` to edit code properly. But then this Stackoverflow post and answers, as well as this github issue seem to imply otherwise.
Now, I have also set `org-adapt-indentation` to `nil`, because I prefer org-headings, sub-headings and text to be aligned with the buffer edge. If I set it to `1`, it looks like there is some aligning going on when I hit `TAB`, but this is not perfect. Does this explain the "pseudo-indenting" that I had before, and there really is no inherent `TAB` indent in org blocks?
I have also been recommended `poly-mode` and `poly-org`, but I'd first like to understand what is going on here.
**EDIT**: I have neglected to say that the message `Canβt guess python-indent-offset, using defaults: 4` appears in the minibuffer after each failed `TAB` press. I wouldn't have thought that would be the difference, as long as it guessed a non-zero offset.
**EDIT:** `Org mode version 9.4.4 (release_9.4.4 @ /usr/share/emacs/27.2/lisp/org/)`
**EDIT:** Here is the tab-indentation behavior when running `emacs -Q` https://i.stack.imgur.com/Bm05v.jpg
# Answer
`TAB` is bound to `org-cycle` in Org mode buffers: that function generally cycles the element that the cursor is on (headlines, drawers, source blocks) between the folded and unfolded state. But Org mode makes use of context-dependent bindings very often and that confuses things. E.g. in this case, *if* the cursor is in a table, the table is realigned and the cursor moves to the next cell.
But when the cursor is not on anything that `org-cycle` considers "special" to do something interesting, then it just executes the global binding of `TAB` which re-indents lines, *assuming that `org-cycle-emulate-tab` is not `nil`*. In that case, `TAB` *in* your python source code block (as opposed on the `#+BEGIN_SRC` line which folds the code block) should indent using `indent-for-tab-command` (unless you have modified the global binding of `TAB`).
EDIT: for debugging, try adding and evaluating the following source block to an Org mode file:
```
#+begin_src elisp
(global-key-binding (kbd "TAB"))
#+end_src
#+RESULTS:
: indent-for-tab-command
```
Do you get `indent-for-tab-command` as the result? If so, go to your python source block and say `M-x indent-for-tab-command` \- do you get the indentation you expect?
~~EDIT 2: Note that you should not expect "real" python indentation. This is more like typing python code in a buffer that is in fundamental mode.~~
EDIT 3: I stand corrected: you *should* expect "real" python indentation: `indent-for-tab-command` calls the function which is the value of the variable `indent-line-function`. Now inside an Org mode buffer, the value of that variable is `org-indent-line`, which, in source code blocks, calls `org-babel-do-key-sequence-in-edit-buffer`; that in turn calls the macro `org-babel-do-in-edit-buffer`: that finally calls whatever function is bound to `TAB` in the context of an edit buffer created by `org-edit-src-code` and then does `org-edit-src-exit` \- phew! That's basically what would happen interactively, if you did `C-c '` in the source block, typed a `TAB` in the resulting source buffer (which is in python mode!) and then exited with another `C-c '`. But note that using two tabs to unindent, as would happen if you did it interactively, does not work: each tab is treated separately, so we go into the source buffer twice, do a single tab each time and exit. There are limitations to this approach.
> 3 votes
---
Tags: org-mode, org-babel, python, indentation
--- |
thread-55705 | https://emacs.stackexchange.com/questions/55705 | pdf-tools view bottom of one page and top of another page simulatenously | 2020-02-22T15:03:22.520 | # Question
Title: pdf-tools view bottom of one page and top of another page simulatenously
Does pdf-tools have scrolling where I can view the bottom half of one pdf page and the top of the next page? Right now, my installation simply jumps to the next page and I cannot view two pages simultaneously.
# Answer
The package pdf-continuous-scroll provides this functionality. It is hacky (and therefore it is not on (M)ELPA), but it does a reasonable job...
> 1 votes
---
Tags: pdf-tools
--- |
thread-69209 | https://emacs.stackexchange.com/questions/69209 | Avoid `\begin{center}` environment when including external PDF image | 2021-11-03T22:27:52.557 | # Question
Title: Avoid `\begin{center}` environment when including external PDF image
By default a code such as this in `org-mode`
```
[[foo.pdf]]
```
will produce the following code in the exported `.tex` document
```
\begin{center}
\includegraphics[width=.9\linewidth]{foo.pdf}
\end{center}
```
How can I stop `org-mode`'s exporter from adding the `\begin{center} \end{center}` environment. I am using the `memoir` class and I'd rather use `\centerfloat`.
# Answer
> 0 votes
Use
```
#+ATTR_LATEX: :center nil
...
```
Do `C-h i g(org)Images in LaTeX export` where you'll find this:
> The LaTeX export back-end centers all images by default. Setting β:centerβ to βnilβ disables centering. To disable centering globally, set βorg-latex-images-centeredβ to βnilβ.
as well as more information about other possible attributes.
---
Tags: org-mode, latex, images, pdf, graphics
--- |
thread-69208 | https://emacs.stackexchange.com/questions/69208 | How does Emacs select which thread to run? | 2021-11-03T22:03:03.097 | # Question
Title: How does Emacs select which thread to run?
If a thread does a `thread-yield` then how does Emacs select which thread to run next? Does it simply select the oldest one waiting?
# Answer
`thread-yield` simply unlocks a global lock, calls the pthread `sched_yield` function (or something similar on other platforms), and then relocks the global lock. All such threads will end up waiting for the global lock, trying to reacquire it. Whichever one happens to do so will be the one to run next. See the C function `yield_callback` in thread.c in the Emacs source.
> 1 votes
---
Tags: threading
--- |
thread-69215 | https://emacs.stackexchange.com/questions/69215 | Add bibliographic entry by DOI without using bib-files | 2021-11-04T13:42:02.710 | # Question
Title: Add bibliographic entry by DOI without using bib-files
This question is not about `org-bibtext`, `org-ref` or something like that which are all based on underlying existing `bib`-files.
I have a simple text-file (e.g. `*.org`) open in a buffer. I wan't to insert the full reference/bibliographic information of an article into it.
But I only have the DOI in my clipboard. I wan't to do something like this
`M-x` `insert-full-ref-by-doi 10.2147/CIA.S218367`
And then this should appear in the buffer of the text-file
> Buhtz, C., Paulicke, D., Schwarz, K., Jahn, P., Stoevesandt, D. & Frese, T. (2019). Receptiveness Of GPs In The South Of Saxony-Anhalt, Germany To Obtaining Training On Technical Assistance Systems For Caregiving. A Cross-Sectional Study. Clinical Interventions in Aging, 2019(14), 1649β1656. doi:10.2147/CIA.S218367
# Answer
> 2 votes
I haven't tested this extensively, but, using the citeproc-el library, the function for fetching BibTeX entries based on DOIs at https://www.anghyflawn.net/blog/2014/emacs-give-a-doi-get-a-bibtex-entry/ can be adapted to insert a full formatted reference along the following lines (you need to replace "/path/to/dir\_with\_csl\_locales" and "/path/to/a\_csl\_style.csl" with valid paths to a dir with CSL locales and to a CSL style):
```
(require 'citeproc)
(require 'bibtex)
(defun insert-full-ref-by-doi (doi)
"Insert a formatted reference of the item with DOI."
(interactive "MDOI: ")
(let* ((url-mime-accept-string "text/bibliography;style=bibtex")
(lg (citeproc-locale-getter-from-dir
"/path/to/dir_with_csl_locales"))
(csl-style
(citeproc-create-style "/path/to/a_csl_style.csl" lg))
bibtex-item)
(with-current-buffer
(url-retrieve-synchronously
(format "http://dx.doi.org/%s"
(replace-regexp-in-string "http://dx.doi.org/" "" doi)))
(set-buffer-multibyte t)
(goto-char (point-max))
(re-search-backward "@")
(beginning-of-line)
(setq bibtex-item (bibtex-parse-entry))
(kill-buffer (current-buffer)))
(let ((csl-item (citeproc-bt-entry-to-csl bibtex-item)))
(insert (citeproc-render-item csl-item csl-style 'bib 'plain t)))))
```
---
Tags: bibtex
--- |
thread-69219 | https://emacs.stackexchange.com/questions/69219 | xref-find-definitions, find next | 2021-11-04T18:48:47.923 | # Question
Title: xref-find-definitions, find next
In decades past when I used `find-tag`, I think there was a way to advance to the next tag definition if the first one found is not the one you were looking for. Is there a way to do this now that `find-tag` has been made obsolete by `xref-find-definitions`?
In my particular case I'd like to jump to a Java class definition of type XYZ, but am instead taken to a Java class that has an XYZ member declaration.
GNU Emacs 25.2.1
# Answer
* `M-x next-error`, or
* `M-g n` (same command), or
* Switch to Xref's window and press `n` (maybe several times). When you see the buffer you're looking for displayed, press `RET`.
> 0 votes
---
Tags: tags, xref
--- |
thread-69221 | https://emacs.stackexchange.com/questions/69221 | Emacs backups - why backup all files to a single directory? | 2021-11-04T22:05:30.027 | # Question
Title: Emacs backups - why backup all files to a single directory?
I was updating my emacs backup approach using ideas from answers to this question, but I'm left unsure by one aspect, namely: the fact that several of them arrange to have backups placed in a single backup directory. So they might have something like:
```
(setq backup-directory-alist `(("." . "~/.emacs.d/backups")))
```
That's in contrast to what I've been doing up until now, with each "actual" directory having it's own backup directory, using something like:
```
(setq backup-directory-alist `(("." . "backups")))
```
That has seemed sensible to me since it keeps any given file's backups close to it in the filesystem. As a result, if and when I need a copy of a backup, I just drop into `./backups` instead of having to climb out of whatever Mines of Moria-esque subdir I've been working in, drag my sorry a\*se all the way over to `~/.emacs.d/backups` or the like, and then dive into a haystack of mostly unrelated files with blindingly !-infested full pathnames, to find the needle that is my desired backup. Not to mention the fact that backing up to a single directory creates a risk that sensitive files may get backed up to a place with less than sensitive permissions.
Nevertheless, reading around the topic I now get the impression that the single directory approach may in fact be the norm, and that *I'm* the weirdo.
**So what am I missing?** Is there some gotcha to the per-directory approach? Or some really useful benefit with the single directory approach? Or both? Or what?
# Answer
> 5 votes
There is no accounting for taste.
---
Tags: backup
--- |
thread-69225 | https://emacs.stackexchange.com/questions/69225 | What's an easy way to do find file then fuzzy search by filename? | 2021-11-05T01:49:44.517 | # Question
Title: What's an easy way to do find file then fuzzy search by filename?
I am trying to learn emacs in order to use orgmode.
I came from vscode universe.
There's a Cmd+P in vscode that allows search by filename easily. Looks like this.
Then i can use cursor keys to go up and down and hit enter it will open as new tab.
Is there an equivalent of this in emacs and open in either new buffer or new window?
I have installed dired, but i think it forces me to type out the exact path
# Answer
> 1 votes
There are several alternatives, but I use projectile. It lets me open a file within a project by typing only a short portion of the name, and not necessarily just a prefix. You can adjust somewhat how fuzzy the search is with other libraries, such as ido-mode.
It has a few other related features, such as searching the whole project for text, compiling the project, and so on.
https://github.com/bbatsov/projectile
---
Tags: find-file
--- |
thread-63990 | https://emacs.stackexchange.com/questions/63990 | How can disable TAB to execute selected line in `counsel-M-x`? | 2021-03-20T09:25:47.227 | # Question
Title: How can disable TAB to execute selected line in `counsel-M-x`?
I am using `counsel-M-x`, it has little bit different behavior than `smex`, where `TAB` may execute the line.
Is it possible to use `TAB` only for toggling where I just want to disable feature to execute the found command if its solo match?
---
Basic example: Type `M-x list-packages` enter and pressing two TABs one after another will executute `list-packages`. I just don't want runnung the command to take place.
# Answer
> 2 votes
```
(ivy-define-key ivy-minibuffer-map (kbd "TAB") #'ivy-partial)
```
Originally `TAB` binds to `ivy-partial-or-done`. Note that in ivy terms, "done" means your term "execute", whereas "partial" means to try to complete in minibuffer. So switching from `ivy-partial-or-done` to `ivy-partial` will keep the tab-complete function but prevent execution.
---
Tags: key-bindings, counsel
--- |
thread-45797 | https://emacs.stackexchange.com/questions/45797 | Does ivy-occur have a follow mode? | 2018-11-06T19:30:21.460 | # Question
Title: Does ivy-occur have a follow mode?
In `org-agenda`, it is possible to enable a "follow mode" so that moving the point over an agenda item automatically displays the linked item in another window.
In `ivy-occur`, you need to press `f` to get this, it doesn't happen automatically.
Is there a way to make `j` and `k` behave like `j f` and `k f`?
# Answer
> 1 votes
From the doc:
```
c runs the command ivy-occur-toggle-calling (found in ivy-occur-grep-mode-map),
which is an interactive native compiled Lisp function in βivy.elβ.
It is bound to c.
(ivy-occur-toggle-calling)
Toggle βivy-callingβ.
```
---
Tags: ivy
--- |
thread-61657 | https://emacs.stackexchange.com/questions/61657 | Multi-directory tab completion for find-file? | 2020-11-09T18:28:39.990 | # Question
Title: Multi-directory tab completion for find-file?
I am frequently diving through many layers of directory hierarchies (thanks, Java) to find files named like thisβ¦
```
java/test/com/company/thing/test/testy/testier/testier/Tester.java
```
The main issue that I have is that `TAB`-completion in `find-file` only completes *one directory* at a time, meaning that I may have to press `TAB` 5 times to get through the first few layers of the hierarchy, where each directory contains only one subdirectory and nothing more (e.g. `com/` contains only `company/`, `company/` contains only `thing/`), etc.
Is there any package that modifies `TAB`-completion with standard Emacs commands, including `find-file`, so that multiple directories will be "greedily" autocompleted when they contain only one subdirectory?
I'm aware of Projectile, and know that it has a similar feature, but I'm hoping to find something standalone and minimal that *just* solves this one issue.
# Answer
I use ivy/counsel so I only have an `ivy` solution:
```
(defcustom dc4ever-cd-all-the-way t
"Whether to enable cd-all-the-way feature." :type 'boolean)
(defvar dc4ever--cd-all-the-way-flag nil "Internal flag for cd-all-the-way.")
(defun dc4ever//ivy-magic-slash-advice (func &rest r)
"Set `dc4ever--cd-all-the-way-flag' for `ivy--magic-file-slash'."
(let ((dc4ever--cd-all-the-way-flag dc4ever-cd-all-the-way))
(apply func r)))
(advice-add #'ivy--magic-file-slash :around #'dc4ever//ivy-magic-slash-advice)
(defun dc4ever//ivy--cd-advice (func &rest r)
"Advice `ivy--cd' to do cd-all-the-way."
(if (not dc4ever--cd-all-the-way-flag) (apply func r)
(cl-labels ((get-only-dir
(dir)
(let* ((entries (f-entries dir))
(onlyent (when (= 1 (length entries))
(concat (expand-file-name (car entries) dir)
"/"))))
(cond
((null onlyent) dir)
((f-dir? onlyent) (get-only-dir onlyent))
(t dir)))))
(funcall func (get-only-dir (car r))))))
(advice-add #'ivy--cd :around #'dc4ever//ivy--cd-advice)
```
NOTE:
This only works if you type `/` since I implemented that way, so that `TAB` would keep the original behavior.
> 0 votes
---
Tags: completion, find-file
--- |
thread-69232 | https://emacs.stackexchange.com/questions/69232 | Org Babel ignores `org-plantuml-executable-args` | 2021-11-05T10:56:16.440 | # Question
Title: Org Babel ignores `org-plantuml-executable-args`
I cannot make plantuml set the UTF-8 charset, I've set
```
'(org-plantuml-executable-args '("-headless -charset UTF-8"))
```
in the `init.el`, but when I check in the message buffer the command invoked, these options are missing
```
java -jar /path/to/plantuml.jar -tsvg -p < /path/to/org-babel-temp-file > /path/to/file.svg
```
Any clue?
Thanks in advance.
# Answer
> 3 votes
Do `C-h v org-plantuml-exec-mode` to see its doc string:
> org-plantuml-exec-mode is a variable defined in βob-plantuml.elβ.
>
> Its value is βjarβ
>
> Method to use for PlantUML diagram generation. βjarβ means to use java together with the JAR. The JAR can be configured via βorg-plantuml-jar-pathβ.
>
> βplantumlβ means to use the PlantUML executable. The executable can be configured via βorg-plantuml-executable-pathβ. You can also configure extra arguments via βorg-plantuml-executable-argsβ.
It is probably set to `jar`, the default, but `org-plantuml-executable-args` only applies when it is set to `plantuml`, i.e. when using the `plantuml` executable.
I looked around a bit to find a `plantuml` executable which must have existed at some point, but AFAICT no longer does. And the `jar` method in `ob-plantuml.el` does not allow for arguments (this is probably an omission that is worth a bug report).
SUGGESTION: I think the easiest thing to do is create your own `plantuml` executable as a shell script and change `org-plantuml-exec-mode` to `plantuml`. Something like this (but note it's *very lightly* tested):
```
#! /bin/bash
java -jar /path/to/plantuml.jar "${@}"
```
Put it into some directory, make it executable and then add something like this to your init file:
```
(setq org-plantuml-exec-mode 'plantuml)
(setq org-plantuml-executable-path "/path/to/script/above/plantuml")
(setq org-plantuml-executable-args '("-headless" "-charset UTF-8"))
```
Very lightly tested.
---
Tags: org-babel
--- |
thread-69228 | https://emacs.stackexchange.com/questions/69228 | ESS : Seeing vignettes for a package without attaching the corresponding package | 2021-11-05T07:21:26.653 | # Question
Title: ESS : Seeing vignettes for a package without attaching the corresponding package
Suppose I wish to see the vignettes for an R package via ESS. I can do it like this:-
```
# This in the R process
library(car)
# This in the minibuffer
M-x ess-display-vignettes
```
My question is this: Can I see the vignettes in a package *without* attaching it to the namespace via the library incantation?
# Answer
With a prefix argument (`C-u`), `ess-display-vignettes` will show vignettes from all installed packages.
From the help for this function (`C-h f ess-display-vignettes`):
> ess-display-vignettes is an interactive compiled Lisp function in βess-help.elβ.
>
> (ess-display-vignettes &optional ALL)
>
> Display vignettes if available for the current dialect.
> With (prefix) ALL non-nil, use βvignette(\*, all=TRUE)β, i.e., from all installed
> packages, which can be *very* slow.
So do `C-u M-x ess-display-vignettes` (and maybe wait a few seconds if you have a lot of installed packages).
> 1 votes
---
Tags: ess, r
--- |
thread-41343 | https://emacs.stackexchange.com/questions/41343 | Magit asks for passphrase for ssh key every time | 2018-05-05T10:34:25.013 | # Question
Title: Magit asks for passphrase for ssh key every time
Running emacs 25.2.2 magit 2.12.1 on Kubuntu 18.04.
I have set-up ssh keys for my bitbucket repository and I run ssh-agent on start.
When I fetch or pull or push, magit asks for the passphrase for ssh key.
How can I avoid keying this passphrase every time there is any remote operation?
# Answer
Running `ssh-agent` and hoping for the best is not enough. `ssh-agent` hands out the decrypted private key to everyone asking *on a specific socket*. The problem is that the socket is not always the same and therefore only those processes that know the currently used socket can benefit.
When `ssh-agent` is started it outputs the socket and its pid.
```
$ ssh-agent
SSH_AUTH_SOCK=/tmp/ssh-XX4LkMJS/agent.26916; export SSH_AUTH_SOCK;
SSH_AGENT_PID=26917; export SSH_AGENT_PID;
echo Agent pid 26917;
```
The intended use is
```
$ eval $(ssh-agent)
```
By evaluating the output some environment variables are set and exported so that all **subprocesses** can see them too.
The reason that a `git` process started by Magit inside Emacs doesn't know the socket is that the `emacs` instance is not a subprocess of any process whose environment contains values for the necessary variables.
You can confirm this by running `eval $(ssh-agent); ssh-add ~/.ssh/id_rsa` in a terminal, and then *in the same terminal* `emacs &`. From that `emacs` instance you will be able to push without being asked for the passphrase again.
Now you have to arrange for these variables to be always set in `emacs`'s environment, regardless of how it was started.
The way I do this is that I start the agent and add the keys using the `keychain` utility when starting an interactive shell. That causes the variables to be set in all shells, and if I did then type `emacs &` in a shell, then `emacs` would have access too. But that's not how I usually start Emacs, so I also use `keychain-environment.el`, which looks for a file created by `keychain` and then sets the environment variables it finds in there.
I recommend you read OpenSSH Key Management, Part 2 (the other parts too). It was written by the author of `keychain`. Also read the description of `keychain-environment.el` (In particular note that you still have enter the passphrase from outside Emacs once.)
> 13 votes
# Answer
Short answer: launch `emacs` directly from your shell ; chances are that both the latter and the former, in their current version, know how to handle ssh keyrings.
On Ubuntu 20.04.2 LTS / the latest ZSH and the latest Emacs, it works, Magit doesn't ask for the passphrase ; but if I use some menu system to launch Emacs, it then does.
When you defer the launching to the DE/WM, most probably via the `/usr/share/applications/emacs.desktop` file, I guess things get "lost in translation".
> 0 votes
# Answer
I'm using Win10 and the only thing I need to do is to open Git bash and then run
```
ssh-add <path/to/private/key>
```
provided the return values of `M-x getenv SSH_AUTH_SOCK` in Emacs and `echo $SSH_AUTH_SOCK` in Git Bash are the same. If not then you need to change that of Emacs to match what's shown in Git Bash. Then Emacs never asks for passphrase again.
> 0 votes
---
Tags: magit, ssh
--- |
thread-69236 | https://emacs.stackexchange.com/questions/69236 | How to force org-attach to create lowercase UUIDs | 2021-11-05T14:47:14.957 | # Question
Title: How to force org-attach to create lowercase UUIDs
When using the org-attach function on macOS the IDs are that are created are uppercase. It is possible to change the folder name to lowercase via `(advice-add #'org-attach-id-uuid-folder-format :filter-return #'downcase)` but the format in the ID property remains uppercase.
Example:
org attachment relative location (after adding the above advice): `data/3e/8bb725-3fb7-4f3f-80b2-baa4369a48ce/example.pdf`
snippet from org file:
```
** Example :ATTACH:
:PROPERTIES:
:ID: 3E8BB725-3FB7-4F3F-80B2-BAA4369A48CE
:End:
```
On macOS I can still open the attachment because of filesystem case-insensitivity. However on Linux if you try to open the attachment, no corresponding ID can be found. I would like all org-attach IDs to be lowercase in both the folder name and its reference. How can I accomplish this?
Edit: uuidgen is used on macOS and Linux for me, and `org-id-new`/ `org-id-get-create`/`uuidgen` always returns an uppercase ID on macOS and lowercase ID on Linux.
# Answer
> 2 votes
Are you wedded to using `uuidgen`? Org-mode has its own internal functions to generate uuid's, which will be used if you customize `org-id-method` to `org`. See `C-h v org-id-method RET`.
# Answer
> 1 votes
Alternatively, on MacOS write a `uuidgenlc` script that downcases the output of the "real" `uuidgen` and set
```
(setq org-id-uuid-program "/path/to/uuidgenlc")
```
`uuidgenlc` could be as simple as
```
#! /bin/bash
uuidgen | tr A-Z a-z
```
---
Tags: org-mode
--- |
thread-69214 | https://emacs.stackexchange.com/questions/69214 | Using shell-command-on-region with TRAMP | 2021-11-04T11:07:36.050 | # Question
Title: Using shell-command-on-region with TRAMP
I like to use `shell-command-on-region` for pretty printing a selected region of code with *prettier*.
After selecting a region, I type `C-u M-|` and then I use `prettier --parser ruby` as the shell command. This is working great. :)
Now, I also like to use TRAMP to open a ruby file on a remote system.
Unfortunately, `shell-command-on-region` does not seem to respect TRAMP. It attempts to execute a shell command on my local machine.
On the other hand, if I invoke `shell-command` unsing `M-!`, this executes a command on the remote machine.
Is there a way to make `shell-command-on-region` work together with TRAMP?
# Answer
`shell-command-on-region` uses `call-process-region`, which doesn't support remote execution.
> 1 votes
---
Tags: tramp, shell-command
--- |
thread-35775 | https://emacs.stackexchange.com/questions/35775 | How to kill magit-diff's buffers on quit? | 2017-09-26T23:25:02.807 | # Question
Title: How to kill magit-diff's buffers on quit?
After making a commit in magit, magit will leave around a `magit-diff` buffer containing just:
```
Staged changes
(empty)
[back]
```
This is pretty useless and clutters up my buffers, and I'd just like that buffer to be killed off not just after a commit but whenever magit is done with it and empties it out like this.
This question is similar to How to kill ediff's buffers on quit?, only the accepted answer there (to use the `ediff-quit-hook`) won't work here because there's no corresponding `magit-diff-quit-hook`, as far as I can see.
Any help is greatly appreciated.
# Answer
*This answer takes the other answers and the comments into account, offering better ways of doing the same things. Your original question was about deleting the diff buffer after committing, though the other answers concentrated on doing something when quitting the status buffer. So I will do that first too, but later also tell you how to do something when you are done committing.*
---
All that `magit-mode-bury-buffer` does is `(funcall magit-bury-buffer-function kill-buffer)`. So there is no need to bind another home-made command to replace it or to advice it - just use the existing option intended to tweak the quitting behavior: `magit-bury-buffer-function`. This is also documented in the manual.
This command's primary purpose is to make the previously current buffer "go away", but you can also use it to do something to other buffers.
Here is how to get to other relevant buffers:
* `magit-mode-get-buffers` lists the other Magit buffers belonging to the current repository.
* `magit-mode-get-buffer` returns a particular buffer belonging to the current repository, matching the provided arguments.
---
To do something when you press `C-c C-c` in a commit message buffer use `with-editor-post-finish-hook` (a `pre` variant also exists, as do two `cancel` variants). These hooks are primarily intended for package authors who use the `with-editor` library (like `git-commit.el` does), so they are a bit under-documented and odd to use. To add something to such a hook for the benefit of `git-commit-mode` do something like:
```
(add-hook 'git-commit-setup-hook
(lambda ()
(add-hook 'with-editor-post-finish-hook
(lambda ()
...) ; your stuff here
nil t))) ; the t is important
```
But use named functions instead of `lambda`s.
> 4 votes
# Answer
Here is the working solution I ultimately wound up using. It is based on tarsius' advice, who deserves all the credit.
```
(defun kill-magit-diff-buffer-in-current-repo (&rest _)
"Delete the magit-diff buffer related to the current repo"
(let ((magit-diff-buffer-in-current-repo
(magit-mode-get-buffer 'magit-diff-mode)))
(kill-buffer magit-diff-buffer-in-current-repo)))
;;
;; When 'C-c C-c' is pressed in the magit commit message buffer,
;; delete the magit-diff buffer related to the current repo.
;;
(add-hook 'git-commit-setup-hook
(lambda ()
(add-hook 'with-editor-post-finish-hook
#'kill-magit-diff-buffer-in-current-repo
nil t))) ; the t is important
```
> 1 votes
# Answer
I had the same problem and I fixed it changing the "q" keybinding in `magit-mode-map` to run `(magit-mode-bury-buffer t)`, which kills the buffer when burying it
To test it within the current session:
```
(define-key magit-mode-map
(kbd "q")
(lambda() (interactive) (magit-mode-bury-buffer t)))
```
You can add it to your startup config with `use-package`
```
(use-package magit
:ensure t
:config (define-key magit-mode-map
(kbd "q")
(lambda() (interactive) (magit-mode-bury-buffer t))))
```
> 0 votes
# Answer
I wonder if the messages below are still valid in the current version of magit... Do we have any new and simpler way to close all magit buffers when que `quit` magit-status buffer?
> 0 votes
# Answer
For general reference - extending izkon's solution to also work when canceling (`C-c C-k`):
```
(defun kill-magit-diff-buffer-in-current-repo (&rest _)
"Delete the magit-diff buffer related to the current repo"
(let ((magit-diff-buffer-in-current-repo (magit-mode-get-buffer 'magit-diff-mode)))
(kill-buffer magit-diff-buffer-in-current-repo)))
;;
;; When 'C-c C-c' or 'C-c C-l' are pressed in the magit commit message buffer,
;; delete the magit-diff buffer related to the current repo.
;;
(add-hook 'git-commit-setup-hook
(lambda ()
(add-hook 'with-editor-post-finish-hook #'kill-magit-diff-buffer-in-current-repo
nil t)
(add-hook 'with-editor-post-cancel-hook #'kill-magit-diff-buffer-in-current-repo
nil t)))
```
> 0 votes
---
Tags: magit, kill-buffer
--- |
thread-69237 | https://emacs.stackexchange.com/questions/69237 | How do I change the python layer test command | 2021-11-05T14:51:11.423 | # Question
Title: How do I change the python layer test command
I'm writing an app in python, which I will run in docker. Therefore I want to test it in docker as well. I'm working in spacemacs and want to use the tools available to test.
With projectile this is possible, I can call `projectile-test-project` and give the command: `docker-compose run --rm mycontainer pytest tests/`
However it would be nice if I could use some of the Python layer functions such as `python-test-one`. This doesn't work because it will call the command `py.test -x -s path/to/file...`
I would really like to be able to change that command to something that starts with `docker-compose`. I think this should be doable, but I don't know much about lisp. How can I do this?
# Answer
Alright, maybe no one cares, but I fixed it.
You call `M-x add-dir-local-variable` Choose the mode: `python-mode` choose the variable: `pytest-global-name` and the value: `docker-compose run --rm <<your_container>> pytest`
Now the function `pytest-test-one` will call the new command. It didn't work for me yet because the folder structure is different in the container. So I solved that by just adding the same directory's in the container.
```
RUN mkdir -p /home/<<user_name>>/projects/project
RUN ln -s /app /home/<<user_name>>/projects/project
```
I suppose this not an ideal solution, but for me since I work alone this is fine. I was also looking if its possible to change the path with some configuration as well. And you can only change the path of the project location, which you don't want to change because that's also where your docker-compose file should be.
> 2 votes
---
Tags: spacemacs, python, testing, docker
--- |
thread-69251 | https://emacs.stackexchange.com/questions/69251 | Server bash-ls starting exited with status exit | 2021-11-06T12:05:17.547 | # Question
Title: Server bash-ls starting exited with status exit
I keep seeing following error when I run `emacs daemon`.
```
Server bash-ls:7089/starting exited with status exit(check corresponding
stderr buffer for details). Do you want to restart it? (y or n)
```
When I press `y` the same message show up again.
my config file:
```
(define-derived-mode my-cfg-mode sh-mode "My CFg Mode"
"A mode for my CFg files."
(sh-set-shell "bash"))
```
=\> How could I prevent this message to show up or respond it `n` by default?
# Answer
You can customize the variable `lsp-restart`. According to the documentation, there are three choices: `interactive`, `auto-restart` and `ignore`. The default value is `interactive`, you can select `ignore`.
```
(with-eval-after-load "lsp-mode"
(setq lsp-restart 'ignore))
```
However, this page indicates that the server may have crashed. Did you check the logs in the `*bash-ls::stderr*` buffer?
> 2 votes
---
Tags: lsp-mode, bash
--- |
thread-69252 | https://emacs.stackexchange.com/questions/69252 | org-babel shell session not starting | 2021-11-06T14:58:58.447 | # Question
Title: org-babel shell session not starting
I'm trying to write some shell code blocks in a session, but it seems no session has been started, and all the code blocks are run independently. Here is a simple example:
```
* org-babel
:PROPERTIES:
:header-args:shell :session babel
:END:
#+begin_src sh
pwd
#+end_src
#+RESULTS:
: /Users/olivier/git/mybrain
#+begin_src sh
cd ..
pwd
#+end_src
#+RESULTS:
: /Users/olivier/git
#+begin_src sh
pwd
#+end_src
#+RESULTS:
: /Users/olivier/git/mybrain
```
As can be see from above, I changed the working directory to the parent folder in the second block, but it went back to the original folder in the next block.
But I do know the session is not working, because there is a background buffer `babel` opened in the background, but it's an empty buffer with `:no process` written at the bottom.
Can someone tell me what's going on and how to fix this?
# Answer
> 2 votes
Two things:
1. the language name here is `sh`, not `shell`
2. the colon is missing after the language name
The following works:
```
* org-babel
:PROPERTIES:
:header-args:sh: :session babel
:END:
#+begin_src sh
pwd
#+end_src
#+RESULTS:
: /Users/olivier/git/mybrain
#+begin_src sh
cd ..
pwd
#+end_src
#+RESULTS:
: /Users/olivier/git
#+begin_src sh
pwd
#+end_src
#+RESULTS:
: /Users/olivier/git
```
---
Tags: org-babel
--- |
thread-69213 | https://emacs.stackexchange.com/questions/69213 | How to implement the native |> pipe in ESS mode | 2021-11-04T11:01:19.257 | # Question
Title: How to implement the native |> pipe in ESS mode
Using the code provided here I can use the `magrittr` package pipe `%>%`. I want to switch to the new native R pipe `|>`, but if I just substitute the old pipe with the new one the code is not recognized as continued and therefore is not indented. What it the best way to implement the new operator in ESS? This is the code in my `.emacs` file:
```
(defun then_R_operator ()
"R - |> operator or 'then' pipe operator"
(interactive)
(just-one-space 1)
(insert "|>")
(just-one-space 1)
(indent)
(reindent-then-newline-and-indent))
(define-key ess-mode-map (kbd "C-S-m") 'then_R_operator)
(define-key inferior-ess-mode-map (kbd "C-S-m") 'then_R_operator)
```
This is an example of what I get:
```
data |>
some_function()
```
This is the expected result:
```
data |>
some_function()
```
# Answer
I finally managed to get what I need, I will list all the steps so that someone may comment on why some of the problems have come up:
1. I tried to install `ess` from within Emacs, but I did not succeed because Emacs freezes;
2. I removed `melpa-ess` (`sudo apt remove --purge melpa-ess`) from my Ubuntu installation. After that, `ess` was no longer listed when I issued the `list-packages` command;
3. I downloaded and installed `ess` from MELPA;
4. I added this code to my `.emacs` file to create a keybind:
```
(require 'ess-site)
(use-package ess
:bind (:map ess-r-mode-map
("C-S-m" . " |> ")
:map inferior-ess-r-mode-map
("C-S-m" . " |> ")))
```
Hope this helps others who have the same problem.
> 1 votes
---
Tags: ess, r, pipe
--- |
thread-69249 | https://emacs.stackexchange.com/questions/69249 | Need search function to navigate to last line in continuous occurrence range | 2021-11-06T01:52:35.477 | # Question
Title: Need search function to navigate to last line in continuous occurrence range
I am looking for a way to improve searching by repeating pattern. Let's say some program prints lots of log messages with the same pattern:
```
copying path '/nix/store/lqfjx7x6imy5a9xab1ff5nhg90v089rq-postgresql-12.8' from 'https://cache.nixos.org'...
copying path '/nix/store/i80hgssxz2710ysawck5k9im6ccbic89-postgresql-13.4' from 'https://cache.nixos.org'...
copying path '/nix/store/qnq00zsw837kiyhvi3jxcizw0gim5g6f-util-linux-2.36.2-bin' from 'https://cache.nixos.org'...
copying path '/nix/store/kr4w1cjjcy4ml7wpb5x6i8dbivdx36rh-postgresql-libpq-0.9.4.3' from 'https://cache.nixos.org'...
```
Cursor is on a line starting with `copying path` and my goal is to jump to the nearest line above/below containing `copying path`; meanwhile neighbor line doesn't have matching pattern.
Such a function and shortcut would boost navigation performance across shell buffer. I hope the library I am interested in exists.
# Answer
I am not sure how you would like this function to work exactly, but it sounds like you can achieve it with only a few lines of code, e.g. the following:
```
(defun my-jump-to-non-matching-line (arg)
(interactive "P")
(let ((regexp (if arg
(thing-at-point 'word t)
(read-string "Jump to first line not matching regexp: "))))
(while (and (string-match regexp (thing-at-point 'line))
(not (eobp)))
(forward-line))))
```
You can simply do `M-x my-jump-to-non-matching-line` and enter some (part of the repeating) pattern that is not contained in the line where you would like to jump to. By doing `C-u M-x my-jump-to-non-matching-line`, the function automatically uses the word under the cursor as pattern (in your example, for example, place the cursor on 'copying' and press `C-u M-x my-jump-to-non-matching-line`).
Of course, you can also create a keybinding for this command.
Finally, you can make a `search-backward` version by changing `eobp` to `bobp` and adding a `-1` behind `forward-line`.
> 2 votes
---
Tags: search, motion, navigation
--- |
thread-69264 | https://emacs.stackexchange.com/questions/69264 | How to use "arrow-up" button to scroll in searched words history immediately after using isearch-forward | 2021-11-07T17:14:38.290 | # Question
Title: How to use "arrow-up" button to scroll in searched words history immediately after using isearch-forward
Is there any way to use "arrow-up" button to scroll in latest searched words **immediately** after using isearch-forward? For now, in order to use the "arrow-up" key for this purpose, I am first required to do either of the following things:
1. M-p (mapped to isearch-ring-retreat in this context). Unfortunately my brain has limited capacity for remembering keyboard shortcuts, so I don't like this solution, "arrow-up" is more intuitive for me and I tend to remember it. Maybe I can bind the "arrow-up" key to isearch-ring-retreat **only** inside isearch context?
2. By clicking the mouse on the isearch prompt that had opened. This is inconvenient as it requires to use the mouse. Maybe I can change some isearch properties so that this happens by default?
Thanks!
# Answer
OK, after further investigation I actually found a solution that seems to achieve what I was looking for. I added the following to my init.el:
```
(progn
(define-key isearch-mode-map (kbd "<up>") 'isearch-ring-retreat )
(define-key isearch-mode-map (kbd "<down>") 'isearch-ring-advance )
)
```
Credit goes to http://ergoemacs.org/emacs/emacs\_isearch\_by\_arrow\_keys.html
> 2 votes
---
Tags: isearch, history
--- |
thread-69258 | https://emacs.stackexchange.com/questions/69258 | How can I create block (multiline) comments in Lisp code? | 2021-11-07T09:36:07.973 | # Question
Title: How can I create block (multiline) comments in Lisp code?
How can I do multiline / block comments in Lisp code - e.g. in the `init.el`.
In Python I would do it like this
```
"""Block
comment
"""
```
In C/C++ like this
```
/*
Block
comment
*/
```
The use case is to out-comment some code blocks for debugging and error diagnosis.
# Answer
Emacs Lisp doesn't have multiline comments. Neither does Python, for that matter. `"""β¦"""` in Python delimit a multiline string. Emacs has multiline string literals, but they're delimited simply by `"β¦"`, so you can't use them to make a block of code inert if that block contains ordinary string literals.
You can just select the block and use `M-;` or `M-x comment-region`. This will comment out all the selected lines.
Assuming what you want to comment out is a syntactically correct block of code with balanced parentheses, you can put `(when nil` before it and `)` after it, or even shorter, `[` before and `]` after. `(when nil β¦)` doesn't execute any of the code in and evaluates to `nil`. `'(β¦)` doesn't evaluate any of the code in and evaluates to a list object. `[β¦]` doesn't evaluate any of the code in and evaluates to a vector object. This doesn't require any change to intermediate lines, and nests. This is similar to using `#if 0``#endif` in C or C++, although the requirement on having a syntactically well-formed block is higher since this Emacs Lisp equivalent requires the parentheses in the block to be balanced.
```
[
(some)
(code)
]
```
> 7 votes
# Answer
There is no syntax for multi-line comments (AFAIK). Just select the target code blocks and do `comment-dwim` which will comment/uncomment each line.
> 1 votes
# Answer
First, yes, it's true that Emacs Lisp does not have a real block-comment syntax. This is different from Common Lisp, which has **`#|`** ... **`|#`**.
That said, you can use `;`-style comments to get much of the effect of `#|`...`|#` commenting, if not quite the same flexibility or appearance.
---
My answer is to use **`comment-region`**, *not* `comment-dwim`. IMO, the former is much more useful when you want to, for example, nest blocks of comments and, in particular, unnest a given level of nesting. I use `comment-dwim` (`M-;`) only for single-semicolon comments after a line of code.
For `comment-region`:
* A plain `C-u` unnests a full level of comments, for the region.
* A negative prefix arg removes that many comment chars. E.g., `M- - 2` removes two `;` chars.
---
However, I actually prefer the following, **`comment-region-lines`** from library `misc-cmds.el`, because I typically want to comment/uncomment full **lines** as a block comment. I bind it to **`C-x C-;`**.
```
(defun comment-region-lines (beg end &optional arg)
"Like `comment-region' (which see), but comment or uncomment whole lines."
(interactive "*r\nP")
(when (> beg end) (setq beg (prog1 end (setq end beg))))
(let ((bol (save-excursion (goto-char beg) (line-beginning-position)))
(eol (save-excursion (goto-char end) (if (bolp) (point) (line-end-position)))))
(comment-region bol eol arg)))
```
Here's the doc string of `comment-region`, which the doc of `comment-region-lines` refers to:
> **`comment-region`** is an interactive compiled Lisp function in `newcomment.el`.
>
> `(comment-region BEG END &optional ARG)`
>
> Comment or uncomment each line in the region.
>
> With just **`C-u`** prefix arg, uncomment each line in region `BEG` .. `END`.
>
> *Numeric* prefix `ARG` means use `ARG` comment characters. If `ARG` is negative, delete that many comment characters instead.
>
> The strings used as comment starts are built from `comment-start` and `comment-padding`; the strings used as comment ends are built from `comment-end` and `comment-padding`.
>
> By default, the `comment-start` markers are inserted at the current indentation of the region, and comments are terminated on each line (even for syntaxes in which newline does not end the comment and blank lines do not get comments). This can be changed with `comment-style`.
> 1 votes
# Answer
If you mean commenting for functions/variables docs, then let's look at this example, taken at random:
```
(defun centaur-tabs-current-tabset (&optional update)
"Return the tab set currently displayed on the tab bar.
If optional argument UPDATE is non-nil, call the user defined function
`centaur-tabs-current-tabset-function' to obtain it. Otherwise return the
current cached copy."
(and update centaur-tabs-current-tabset-function
(setq centaur-tabs-current-tabset
(funcall centaur-tabs-current-tabset-function)))
centaur-tabs-current-tabset)
```
It is self-explaining: start with `"` and when finished close also with `"`.
> 0 votes
---
Tags: elisp, comment
--- |
thread-69265 | https://emacs.stackexchange.com/questions/69265 | After setting syntax-propertize-function, comment is not being fontified with comment face | 2021-11-07T18:40:20.680 | # Question
Title: After setting syntax-propertize-function, comment is not being fontified with comment face
I'm trying to build a major mode for xwiki, where I'm defining
```
{{{
verbatim
}}}
```
as a comment.
So far, I've done
```
(eval-when-compile
(defconst xwiki-syntax-propertize-rules
(syntax-propertize-precompile-rules
("{{{" (0 "< b"))
("}}}" (0 "> b")))))
(setq-local syntax-propertize-function (syntax-propertize-rules xwiki-syntax-propertize-rules))
```
When I do `describe-char`, on any of the characters in `{{{`, I see that it is identified as a comment style b. I also see `}}}` identified as comment style b.
However, under text properties, there's nothing set for `face`. Am I missing something?
# Answer
The above code will indeed set something for face. @Lindydancer helped me realize that I had set `font-lock-defaults` with the second parameter (`keywords-only`) of the list as `t`).
Unsetting `keywords-only` fixed the above and enabled highlighting.
Also, with
```
(eval-when-compile
(defconst xwiki-syntax-propertize-rules
(syntax-propertize-precompile-rules
("{{{" (0 "< b"))
("}}}" (0 "> b")))))
```
The last two `}}` did not get fontified with the comment face, but with
```
(eval-when-compile
(defconst xwiki-syntax-propertize-rules
(syntax-propertize-precompile-rules
("\\({\\){{" (1 "< b"))
("}}\\(}\\)" (1 "> b")))))
```
It gets fontified correctly - `{{{`, `}}}`, and everything between those get fontified as comments.
> 2 votes
---
Tags: font-lock, syntax-highlighting, text-properties, comment, syntax-table
--- |
thread-64279 | https://emacs.stackexchange.com/questions/64279 | `pop-to-buffer` in other frame if file is already visited | 2021-04-03T14:50:08.523 | # Question
Title: `pop-to-buffer` in other frame if file is already visited
Say I have two frames open. Frame A is visiting a file `foo.org`. Calling `(pop-to-buffer "foo.org")` in the other frame (B) opens `foo.org` in frame B instead of moving the focus to frame A where that buffer is already open. Can this be configured (and how) to "jump" to frame A?
I appreciate that there are other functions that allow me to jump "across frames" but I'd like to adapt the behaviour of `pop-to-buffer` specifically.
# Answer
`pop-to-buffer` is essentially `display-buffer` with selecting the chosen window afterwards.
You can influence the behavior of `display-buffer` with display actions specified in several variables. See the corresponding info page for a complete list of actions and variables.
I think you should configure `display-buffer-base-action` with your preferred display behavior.
`display-buffer-reuse-window` with the alist `(reusable-frames . 0)` avoids popping up the buffer in the already selected frame if it is shown on another frame.
Configure it with the following Elisp snippet in your config files or use `M-x` `customize-option` `RET` `display-buffer-base-action` `RET`.
```
(setq display-buffer-base-action '(display-buffer-reuse-window (reusable-frames . 0)))
```
The list of available options for the `reusable-frames` entry of the alist is:
* **nil:** the selected frame (actually the last non-minibuffer frame)
* **A frame :** just that frame
* **βvisibleβ:** all visible frames
* **0 :** all frames on the current terminal
* **t :** all frames.
> 1 votes
---
Tags: buffers, frames
--- |
thread-69272 | https://emacs.stackexchange.com/questions/69272 | How to open image-dired in a directory using a key binding? | 2021-11-08T11:41:19.003 | # Question
Title: How to open image-dired in a directory using a key binding?
The binding works, though I'm still required to input the directory `/home/foo/Pictures`.
What do I have to change?
init.el:
```
(spacemacs/set-leader-keys "jI"
(lambda ()
(interactive)
(call-interactively #'image-dired "/home/foo/Pictures")))
```
# Answer
> 1 votes
The signature of `call-interactively` is:
```
(call-interactively FUNCTION &optional RECORD-FLAG KEYS)
```
In particular, you can't pass arguments to the callee in the way you attempt.
This should work instead:
```
(spacemacs/set-leader-keys "jI"
(lambda ()
(interactive)
(image-dired "/home/foo/Pictures")))
```
---
Tags: spacemacs, image-dired
--- |
thread-69274 | https://emacs.stackexchange.com/questions/69274 | how do I match brackets and parentheses in lisp code? | 2021-11-08T15:13:18.807 | # Question
Title: how do I match brackets and parentheses in lisp code?
I started to write some elisp and have am having trouble with the brackets/parentheses. Often, I delete only one bracket/parenthesis and left the other dangling. I have trouble finding the matches.
How do I manage brackets/parentheses to keep them balanced?
# Answer
> 2 votes
`paredit-mode` is very popular. There are a few others; the key thing to search for is βstructural editingβ.
# Answer
> 3 votes
Before you start looking for extensions, you should read the documentation about what Emacs provides natively. In particular, parenthesis matching and editing is something you can read about in the manual: `C-h i g(emacs)parentheses` will take you to a section that describes commands that deal with moving past a "balanced expression" in various directions, commands that allow you to move "up, down and across in the structure of parentheses" and commands that allow you to see matching parentheses.
After that, as @db48x's answer points out,`paredit-mode` is one direction that you could go, but there are others as well. The EmacsWiki is a useful source of information on this and many other topics. Searching for `parentheses` on the main page brings you to a page with lots of information on the topic (including `paredit` BTW).
In summary, learning enough about Info so you can easily find things in the manuals is going to repay you a thousand-fold in the future. You can even use it to learn about Info itself: `C-h g(Info)`. The EmacsWiki is also very helpful, but as it is user-editable, the quality is more variable, so you have to be a bit more careful about what to try.
Above all, don't try everything at once or you will be overwhelmed. That's why I suggested to start by using what is in Emacs already.
---
Tags: balanced-parentheses
--- |
thread-69271 | https://emacs.stackexchange.com/questions/69271 | How to specify a different font for plain-text-files | 2021-11-08T10:54:40.683 | # Question
Title: How to specify a different font for plain-text-files
Let me say first my English is not so good and I'm totally new to Emacs.
In Org-Mode I can specify a monospace font in code-blocks while using a proportional font in normal text.
So I defined a proportional font as my default font.
But if I open now for example a shell script or `init.el`, I get syntax highlighting but no monospace font.
I can change each different item using `M-x describe-face` and set there a font.
Unfortunately this would force me to change the font for each item, for example (default βfont-lock-comment-faceβ) for comments but it would be more easy to set a proportional font for plain text (files) in general.
An other possibility would be as a workaround to apply a specific font for the current buffer using a keyboard shortcut.
How can I configure one or both possibilities?
---
No, I configured Org Mode that way having a proportional font as default (via Menu 'default font') and monospace font for code-blocks, what is ok for me. But when I open a shell-script for exemple, it will be opened in my default-font not monospace as I would expect.
The function shown above does work fine for Org-mode but it does not enable me changing the font for files which does need monospace. I'm *not* talking about code blocks here but opening for exemple a shell script in monospace font, a plain text 'file.txt' in proportional font.
---
Yes, but that's exact my question how to set in a general way. But I think I explained this before... didn't meant expectation that way - but how to reach this target in general. I would suppose most people who use Emacs in a more literary way use a monospace font for code files nevertheless... But how do they realize this without editing each single item (meaning by mime type or ending). This because Emacs recognize a shell script for exemple and does correct syntax highlighting but not changing to a monospace font?
# Answer
> 3 votes
You can use `buffer-face-mode` for this purpose. For example:
```
(defun my-buffer-face-org-mode ()
"Set a fixed width (monospace) font in `org-mode' buffers, with a
height of 11pt."
(interactive)
(setq buffer-face-mode-face '(:family "Fira Mono" :height 110))
(buffer-face-mode))
(add-hook 'org-mode-hook 'my-buffer-face-org-mode)
```
You can create a default value and then change it for particular buffer types. e.g., attach a hook to `text-mode-hook`, which is inherited by most text modes, such as XML. If you don't want the default in XML buffers, then change it with `nxml-mode-hook`.
---
Tags: fonts
--- |
thread-69257 | https://emacs.stackexchange.com/questions/69257 | Org-mode element API returns (slightly) incorrect results | 2021-11-07T09:08:42.950 | # Question
Title: Org-mode element API returns (slightly) incorrect results
I have a use case where I tag a particular node in my Org-mode document with a unique hash. I then want to be able to programmatically access that node and append something to it. To that effect I wrote an Elisp function that returns a list of nodes with matching tags (this list should contain a single element in the non-pathological case):
```
(cl-defun get-node-by-tag (tag)
"Given TAG, search the designated Org file and return a list
of nodes with matching tags."
(with-temp-buffer
(insert-file-contents *org-notes-file*)
(let ((contents (org-element-parse-buffer)))
(labels ((extract (el)
(let ((c (org-element-contents el)))
(append (when
(member tag (org-element-property :tags el))
(list el))
(mapcan #'extract (org-element-contents el))))))
(extract contents)))))
```
I then get the result, which is of the form:
```
((headline
(:raw-value "TODO Jake VanderPlas - Python Data Science Handbook" :begin 10089 :end 10343 :pre-blank 0 :contents-begin 10190 :contents-end 10343 :level 5 :priority nil :tags
...
```
and use its `:end` property to position myself at the end of that node.
Now here's the problem. I wrote the code on my work Emacs (27.2, running on Win 10), where it works fine. When I tried running it on my home machine (Emacs 27.1, running on PureOS), I found that the Org Element API returns results that are off by 2. The files on which I operate are different on both systems, but that shouldn't make a difference. One thing that came to my mind is the newline incompatibility (`LF` in Unix vs. `CRLF` in DOS/Windows), but I find it hard to believe the API would fail to take this into account. So I'm at a loss as to why the results are off. I'll appreciate any suggestions.
**EDIT:** As per @NickD's comment below, I'm attaching Org versions:
* Home system (erroneous): `9.3`
* Work system (correct): `9.3`
So the only difference here is the OS on which they run. And yes, the result is obviously wrong, i.e. I end up at the next node.
# Answer
> 0 votes
The question about line endings may be checked by running a test file through `unix2dos` and seeing if you get the correct results from it at home.
I also suggest upgrading Org to the current version, 9.5, and see if that makes a difference. `org-element-parse-buffer` does call `org-skip-whitespace`, which does as its name suggests.
This would be a bug, if you verify that it's the line endings, and should be reported. You can use `org-submit-bug-report`.
---
Tags: org-mode
--- |
thread-69260 | https://emacs.stackexchange.com/questions/69260 | How to use `initial-scratch-message` variable to display mutliple status informations after start | 2021-11-07T11:33:32.887 | # Question
Title: How to use `initial-scratch-message` variable to display mutliple status informations after start
I want to use the scratch buffer to display some status informations after starting emacs. I read I can use `initial-scratch-message` variable for this.
But I do not know how to set it up.
Here you see a function(?) that gives back the start-up-time as a string. And with `emacs-startup-hook` it is well displayed in the statusbar. But the same with `initial-scratch-message` it does not work. I tried \`display-graphic-p' too. And how would I append informations/values to that variable instead of just overwriting it?
```
;; === Print start-time after start
; from https://github.com/daviwil/emacs-from-scratch/blob/master/show-notes/Emacs-Scratch-12.org
(defun efs/display-startup-time ()
(message "Emacs loaded in %s with %d garbage collections."
(format "%.2f seconds"
(float-time
(time-subtract after-init-time before-init-time)))
gcs-done))
(add-hook 'emacs-startup-hook #'efs/display-startup-time)
(initial-scratch-message #'efs/display-startup-time)
; this does not work also (wront type argument stringp)
; (setq initial-scratch-message #'efs/display-startup-time)
(initial-scratch-message display-graphic-p)
; Would prefere this (Python-Lisp-Pseudo-Code)
;(initial-scratch-message 'display-graphic-p is "{}".format(display-graphic-p))
```
# Answer
This solve a part of the problem. Keep in mind that `efs/display-startup-time` is a function.
```
(setq initial-scratch-message (efs/display-startup-time))
```
But `display-graphic-p` (which is a "compiled function") doesn't work like that.
This is how strings can added (concated) to the variable. But I am unsure if this is the usual Lisp-way.
```
(setq initial-scratch-message (concat initial-scratch-message "\nfoo"))
(setq initial-scratch-message (concat initial-scratch-message "bar"))
```
> 0 votes
# Answer
Functions that end with 'p' are predicates, which in emacs-speak means they check for something. In this case, `display-graphic-p` checks to see if you're invoking emacs in a terminal or in a graphical display. "Return non-nil if DISPLAY is a graphic display." Have you looked at the Dashboard package? It may provide what you're looking for.
> 1 votes
---
Tags: start-up, scratch-buffer
--- |
thread-69235 | https://emacs.stackexchange.com/questions/69235 | How can a function be used as an alist value but be evaluated before its value is used? | 2021-11-05T13:08:00.400 | # Question
Title: How can a function be used as an alist value but be evaluated before its value is used?
I am using Chemacs2 and I want to set an environment variable in the `.emacs-profiles.el`, eg
To clarify the problem `.emacs-profiles.el` is not executed it is read and I have updated the post with a proper sample, ie a list of lists. It does not `provide` and is not `require`d
```
(
("vanilla" .((user-emacs-directory . "~/emacsen/vanilla/.emacs.d")))
("doom01" . ((user-emacs-directory . "~/emacsen/doom01/.emacs.d")
(env . (("DOOMDIR" . "~/emacsen/doom01/doomdir")
("PATH" . (concat "~/emacsen/doom01/.emacs.d/bin/doom" ":" (getenv "PATH")))
))))
)
```
The file that processes it is https://github.com/plexus/chemacs2/blob/master/chemacs.el.
The profile eg `vanilla` or `doom01` is passed on the command line and its values such as `user-emacs-directory` and `env` used for that Emacs session.
The function which sets the environment variables is
```
(mapcar (lambda (env)
(setenv (car env) (cdr env)))
(chemacs-profile-get 'env))
```
and it fails on the pair `("PATH" . (concat "~/emacsen/doom01/.emacs.d/bin/doom" ":" (getenv "PATH")))` because `(cdr env)` which is `(concat "~/emacsen/doom01/.emacs.d/bin/doom" ":" (getenv "PATH"))` gets passed to the `setenv` call as it is without being evaluated first.
I have tried some of the splicing techniques listed at Backquote to no avail.
If the expression in the `.emacs-profiles.el` can't be written in a better way then is there a way to rewrite `(cdr env)` in `(setenv (car env) (cdr env))` in such a way that it gets evaluated to a string before `setenv` tries to apply it?
# Answer
I suggest that what you need is a generator function that will run your code and generate a file in the proper format. One way to do this is with literate programming in Org mode. A simple org document can run your lisp and produce the proper output, and updating the document for new values can automatically create the new file for you. Essentially, you never touch the `.el` file itself.
> 1 votes
---
Tags: functions, doom
--- |
thread-69090 | https://emacs.stackexchange.com/questions/69090 | Trying to update emacs from the command line, but add-hook won't fire | 2021-10-26T12:20:01.793 | # Question
Title: Trying to update emacs from the command line, but add-hook won't fire
I want to update Emacs from the command line so I created the following function to help with this:
```
;;; update.el -- Update Emacs from the command line
(defun update-emacs ()
"Update Emacs without interaction, to be used from the command line."
(defun perform-emacs-update ()
(switch-to-buffer "*Packages*")
(declare-function package-menu-mark-upgrades "package.el.gz")
(declare-function package-menu-execute "package.el.gz")
(package-menu-mark-upgrades)
(package-menu-execute t))
(add-hook 'package--post-download-archives-hook 'perform-emacs-update)
(package-list-packages))
(provide 'update-emacs)
```
Then I run Emacs with these parameters:
```
$ emacs --batch --eval '(load "~/.emacs.d/update.el")' --eval '(update-emacs)'
```
However it doesn't run the hook for some reason. I get this output instead
> Loading ~/.emacs.d/update.el (source)... Setting βpackage-selected-packagesβ temporarily since "emacs -q" would overwrite customizations
This code works fine when I execute it from an already running Emacs. How can I get it to run in batch mode?
# Answer
> 1 votes
The documentation gives the answer.
> Don't run this hook directly. It is meant to be run as part of package--update-downloads-in-progress.
As a rule, `--` in the name is an indication that it's a private unit not intended to be used by us mere mortals.
If you collect your packages to upgrade into a list, then a function like this should work.
```
(dolist (p my-packages)
(when (not (package-installed-p p))
(package-install p)))
```
---
Tags: hooks, batch-mode
--- |
thread-69292 | https://emacs.stackexchange.com/questions/69292 | org-agenda-prefix based on timestamp | 2021-11-09T21:30:18.963 | # Question
Title: org-agenda-prefix based on timestamp
While I understand the `DEADLINE` and `SCHEDULED` timestamp keywords are all that org mode support natively, I am wondering if it is possible to have something like this:
```
*** TODO [#1] Assignment
DEADLINE: <2021-11-07 Sun 10:00> (Time I want to finish the assignment)
Actual Deadline: <2021-11-08 Mon 10:00> (Time the assignment is actually due)
```
The idea is that I can have the `DEADLINE` keyword act normally, but have the second item show up in a special way (not just as a timestamp) on the Org Agenda. e.g. When the assignment shows up at `<2021-11-08 Mon 10:00>` on the agenda, a prefix denotes its purpose:
```
...
Monday 8 November 2021 W45
Math 4130: 10:00...... Actual Deadline: DONE [#1] Assignment
...
```
The `Actual Deadline` doesn't need any special `DEADLINE` behavior. For my purpose this functionality would be more helpful than the deadline "warning days" functionality Org Mode provides. I have functionality for other `org-agenda-prefix` information, but unsure how I might achieve this.
How might I do this?
EDIT: Just to be perfectly clear, `Actual Deadline` is just an example. Ideally any timestamp label could be displayed in the org-agenda-prefix.
# Answer
> 1 votes
Here's a possible implementation. It is based on the idea of adding the actual deadline time stamp as a property to the heading (do `C-h i g(org)properties and columns` to read about properties in Org mode). So the Org mode file would look like this:
```
#+CATEGORY: Math 1234
* TODO Assignment
DEADLINE: <2021-11-14 Sun 10:00> (Time I want to finish the assignment)
:PROPERTIES:
:ActualDeadline: <2021-11-15 Mon 10:00>
:END:
```
Adding it as a property allows easy retrieval of it later using the Propery API (see `C-h i g(org)Using the Property API`). With `point` anywhere in a heading, all you have to do is:
```
(org-entry-get nil "ActualDeadline")
```
In the heading above, you get the string `"<2021-11-15 Mon 10:00>"` as the value. If there is no such property, you get `nil`.
The next step is to define a function that looks for an `ActualDeadline` property in the current heading and if it finds one, it compares the date from the timestamp with the agenda date: if the dates are equal, then the function returns the string "Actual Deadline ", otherwise it returns an empty string:
```
(defun actual-deadline ()
(let ((ts (org-entry-get nil "ActualDeadline"))
tsdate)
(setq tsdate (if ts
(calendar-gregorian-from-absolute
(time-to-days (org-read-date nil t ts nil)))
nil))
(if (and tsdate (equal org-agenda-current-date tsdate))
;; there was an ActualDeadline property and the dates agree
"Actual Deadline: "
""))
```
The hardest part here is to convert the date from the timestamp into the `(month day year)` format that the calendar uses. That is necessary because `org-agenda-current-date`, the variable that remembers the current date while processing each day's items in the agenda, uses that format. Note that if there is no `ActualDeadline` property or if the dates do not agree, the function returns the empty string.
Now all you have to do is redefine the agenda entry in `org-agenda-prefix-format` to use the above function. There is a `%(expr)` format that allows you to evaluate an arbitrary lisp expression: the format is replaced by the (string) value of the expression - see the doc string of the variable with `C-h v org-agenda-prefix-format` for the details. In particular, we can have it call the function above:
```
(setf (cdr (assq 'agenda org-agenda-prefix-format))
" %i %-12:c%?-12t%(actual-deadline)% s")
```
That's the default value of the format for the agenda, except that I've interpolated the call to the function: `%(actual-deadline)`.
You can add the function to your init file, but you have to be careful when you add the setting of `org-agenda-prefix-format`: the code above assumes that the variable is already defined, but the variable is only defined after `org-agenda` is loaded, so the safest thing to do is to use `with-eval-after-load`:
```
(with eval-after-load 'org-agenda
(setf (cdr (assq 'agenda org-agenda-prefix-format))
" %i %-12:c%?-12t%(actual-deadline)% s")
```
Here's how it looks:
```
Sunday 14 November 2021
Weather: 6:30...... Sunrise
Math 1234: 10:00...... Deadline: TODO Assignment
Weather: 16:26...... Sunset
Monday 15 November 2021 W46
Weather: 6:32...... Sunrise
Math 1234: 10:00...... Actual Deadline: TODO Assignment
Weather: 16:26...... Sunset
```
EDIT: Adding a property to an Org mode heading is easy. There is a convenient keybinding for it: `C-c C-x p` bound to `org-set-property`. It asks you for the name of the property and it allows for completion, so that is easy to do. It then asks for the value of the property and that's a problem: you would like the value of the `ActualDeadline` problem to be an active timestamp, but the keybinding `C-c .` that is normally used for that is only available in an Org mode buffer, not in the minibuffer where `org-set-property` is asking you to enter it. You can enter it by hand of course, but it might be convenient to make `org-time-stamp` available through a keybinding in the minibuffer. Fortunately, the `C-c .` key is generally not defined in the minibuffer, so you can add it for yourself:
```
(define-key minibuffer-mode-map (kbd "C-c .") #'org-time-stamp)
```
That gives you the standard Org mode method of adding a time stamp in the minibuffer, so adding an ActualDeadline property with a time stamp value becomes pretty easy:
```
C-c C-x p Ac TAB RET C-c . ... RET
```
i.e. call org-set-property, start giving it the name of the property, TAB for completion, RET to accept (assuming there is no other property starting with `Ac`) then `C-c .` to start the dialog for a time stamp, then RET when you are done. That's easier done than said.
---
Tags: org-mode
--- |
thread-69290 | https://emacs.stackexchange.com/questions/69290 | Project specific customization: where to put font-latex-match-reference-keywords? | 2021-11-09T17:51:57.863 | # Question
Title: Project specific customization: where to put font-latex-match-reference-keywords?
In a project of mine I defined a new LaTeX command `\emphix{...}`, similar to `\emph{...}` and I want its argument to be similarly italicized in my AUCTeX/emacs buffer. To this purpose I defined
```
(setq font-latex-match-italic-command-keywords
'(("emphix" "{")))
```
This all works when the definition is put in my init file (`.emacs`), but it doesn't work if I put it e.g. in the file `xxxxx.el` which is supposed to contain project specific definition (and, as far as I can understand, is loaded when AUCTeX recognises the style `xxxxx.sty` in my main `.tex` file).
I realised that only when I put the definition in my main init file the variable `font-latex-match-italic-command` is correctly redefined to include it.
Where should I put my definition so that I do not burden my main init file with project specific definitions?
# Answer
> 1 votes
If you look at the docstring of `font-latex-match-italic-command-keywords`, you see:
> `font-latex-match-italic-command-keywords` is a variable defined in βfont-latex.elβ.
>
> Its value is nil
>
> List of keywords and formats for italic-command face.
> Each element has to be a list consisting of the name of a macro omitting the leading backslash and a format specifier as described in the doc string of `font-latex-user-keyword-classes`.
>
> Setting this variable directly does not take effect; restart Emacs.
Last sentence says: This variable must be set before `font-latex.el` is loaded, otherwise it won't work. This is the reason why setting it in your init file works and not in `xxxxx.el` which will be loaded after `latex.el` and `font-latex.el`.
The usual practice is to write an AUCTeX `xxxxx.el` and use the function `font-latex-add-keywords`:
```
;;; xxxxx.el --- AUCTeX style for `xxxxx.sty'
(TeX-add-style-hook
"xxxxx"
(lambda ()
(TeX-add-symbols
'("emphix" t))
;; Fontification
(when (and (featurep 'font-latex)
(eq TeX-install-font-lock 'font-latex-setup))
(font-latex-add-keywords '(("emphix" "{"))
'italic-command)))
TeX-dialect)
;;; xxxxx.el ends here
```
---
Tags: auctex, customization
--- |
thread-52066 | https://emacs.stackexchange.com/questions/52066 | How can I set color for listing executable files in Dired Mode? | 2019-08-08T13:18:54.740 | # Question
Title: How can I set color for listing executable files in Dired Mode?
Trying here to set color for executable files, as it is for ls command!
How can I do that?
I've already managed to set color for certains file extensions, using Diredful package, but couldn't do it according to it's mode!
# Answer
Define "executable file" and a file's "mode".
If you mean something that `ls` recognizes as executable and flags as such, with an asterisk (`*`), when you use `ls` switch `F`, then Dired+ highlights that. It uses face \`\` for the asterisk.
```
;; For this to show up, you need `F' among the options in `dired-listing-switches'.
;; For example, I use "-alF" for `dired-listing-switches'.
(defface diredp-executable-tag
'((t (:foreground "Red")))
"Face used for executable tag (*) on file names in Dired buffers."
:group 'Dired-Plus :group 'font-lock-highlighting-faces)
```
> 0 votes
# Answer
For a non-dired-plus version, I use this code to highlight executable files in `dired-mode` by using the face `helm-ff-executable` (it can be changed to any other face up to preference):
```
(add-to-list
'dired-font-lock-keywords
(list dired-re-exe
'(".+" (dired-move-to-filename) nil (0 'helm-ff-executable)))
'append)
```
> 0 votes
---
Tags: dired, colors
--- |
thread-68177 | https://emacs.stackexchange.com/questions/68177 | evil/elpy: Auto-fold when opening a file | 2021-08-19T07:30:47.857 | # Question
Title: evil/elpy: Auto-fold when opening a file
I am using `Emacs 27.1 (build 1, x86_64-pc-linux-gnu, GTK+ Version 3.24.24, cairo version 1.16.0) of 2021-03-28, modified by Debian` with `elpy` and `evil-mode`.
When I open a `py`-file I want everything folded in there by default.
It is still unclear for me how to search for an answer to this wish because I do not know which of the components (elpy, evil, emacs itself, ...) is responsible for that.
# Answer
> 2 votes
With EVil, you can use
```
(add-hook 'python-mode-hook
(lambda ()
(evil-close-folds)
))
```
to close all folds upon entering a file.
---
Tags: evil, elpy, code-folding
--- |
thread-69296 | https://emacs.stackexchange.com/questions/69296 | How to directly display "Class" in imenu? | 2021-11-10T05:58:07.167 | # Question
Title: How to directly display "Class" in imenu?
imenu only displays "function" by default, "Class" is hidden by default.
As shown below:
When I need to view "Class", I have to type "Class" and press Enter, which is troublesome, I hope there is a way to display "Class" directly
# Answer
> 1 votes
As far as I can find `imenu` is not designed to make this configurable for the user. However, by looking a little into the code, we find that we can achieve it using the following code:
```
(defun my-imenu-class ()
(interactive)
(imenu (imenu-choose-buffer-index "Jump to class: "
(alist-get "Class"
(imenu--make-index-alist)
nil
nil
'string=))))
```
You can use it via `M-x my-imenu-class`
Of course, you can also create a keybinding for the command.
---
Tags: imenu
--- |
thread-69305 | https://emacs.stackexchange.com/questions/69305 | What is meant by "variable expansion"? | 2021-11-10T13:58:44.950 | # Question
Title: What is meant by "variable expansion"?
I'm looking at the ob-core.el source and see docstrings like:
> Expand variables in PARAMS...
The Emacs manual talks about macro expansion, which is when a macro is converted to executable source code (i.e. "the value returned by the macro body is an alternate Lisp expression"). It also talks about expanding an abbrev wherein a word (an abbrev) is replaced by something else (an expansion). I don't see what variable expansion is, though.
What does it mean to expand a variable?
# Answer
That refers to headers that have `:var name=thing` in them, where thing may be the name of another block, table, or function. `thing` gets "expanded" and assigned to `name` so you can use `name` inside the src block.
For example:
```
#+name: tbl
| 1 | 2 |
| 3 | 4 |
#+BEGIN_SRC python :var data=tbl
return data
#+END_SRC
#+RESULTS:
| 1 | 2 |
| 3 | 4 |
```
> 3 votes
---
Tags: org-mode, variables
--- |
thread-69319 | https://emacs.stackexchange.com/questions/69319 | Shift+Ctrl+arrow to enlarge and shrink windows does not work in org-mode | 2021-11-12T08:50:20.930 | # Question
Title: Shift+Ctrl+arrow to enlarge and shrink windows does not work in org-mode
Similarly to what is described here, org-mode overrides `C-S-<arrow>` key-binds which, in order to control the size of the windows, I have defined as follows:
```
(global-set-key (kbd "S-C-<right>") 'enlarge-window-horizontally)
(global-set-key (kbd "S-C-<left>") 'shrink-window-horizontally)
(global-set-key (kbd "S-C-<up>") 'enlarge-window)
(global-set-key (kbd "S-C-<down>") 'shrink-window)
```
I would expect an identical solution to work, i.e.:
```
(add-hook 'org-ctrl-shiftright-final-hook 'enlarge-window-horizontally)
(add-hook 'org-ctrl-shiftleft-final-hook 'shrink-window-horizontally)
(add-hook 'org-ctrl-shiftup-final-hook 'enlarge-window)
(add-hook 'org-ctrl-shiftdown-final-hook 'shrink-window)
```
However the above has no effect at all. In `org-mode` those keys are still bind to setting and clearing marks (up/down combinations) and to work with the clock log (right/left combinations). In particular, they are bound to `org-shiftcontrolup` (and similar for the remaining three).
Does someone know how can one successfully override these key-binds in `org-mode`?
# Answer
You can override the `org-mode-map` like this:
```
(define-key org-mode-map (kbd "S-C-<left>") 'shrink-window-horizontally)
(define-key org-mode-map (kbd "S-C-<right>") 'enlarge-window-horizontally)
(define-key org-mode-map (kbd "S-C-<down>") 'shrink-window)
(define-key org-mode-map (kbd "S-C-<up>") 'enlarge-window)
```
> 2 votes
---
Tags: org-mode, key-bindings, window
--- |
thread-69321 | https://emacs.stackexchange.com/questions/69321 | Change indent for function calls in Emacs Lisp? | 2021-11-12T11:37:48.593 | # Question
Title: Change indent for function calls in Emacs Lisp?
*While writing the question I found a viable workaround solution for myself, so I am posting it as Q&A. I am leaving the question open, because my workaround does not allow to set the* amount *by which things are indented.*
By default Emacs indents function calls as
```
(function-name (first-argument)
(second-argument))
```
This is mostly fine, unless nesting gets very deep or if `function-name` is on the long side. Then it becomes preferable to put all arguments on a separate line, which Emacs indents as
```
(function-name
(first-argument)
(second-argument))
```
This I find extremely ugly, because it makes code hard to read, when arguments are barely indented *at all*.
I `could` add a file local variable `-*- lisp-indent-offset: 4 -*-` to get more readable
```
(function-name
(first-argument)
(second-argument))
```
but this then would not affect only functions but would also produce the very much *not* well-readable
```
(let ((a (first-argument))
(b (second-argument)))
(function-name a b))
```
or for quoted data, equally bad,
```
(setq data '(data1
data2
data3))
```
This part is probably the most tricky, since Emacs has no fully reliable way to distinguish it from a quoted expression
```
(setq expression '(function-name
(first-argument)
(second-argument)))
```
which I assume is the reason for the default behavior.
Is there any option, short of writing my own indent function, that would allow Emacs Lisp functions to be indented more deeply, *without* overriding the explicitly declared behavior for macros?
# Answer
## Workaround
The best I can currently think of is
```
(advice-add #'function-get :around #'my--get-lisp-indent-function)
(defun my--get-lisp-indent-function (oldfun symbol propname &rest r)
(let ((value (apply oldfun symbol propname r)))
(cond ((not (eq propname 'lisp-indent-function))
value)
((and (null value)
(functionp symbol))
0)
(t value))))
```
Which *mostly* fulfills the requirement.
I also like to add some customizations, like
```
(put 'format 'lisp-indent-function 1)
(put 'cl-loop 'lisp-indent-function 0)
```
## Remarks
#### function-get
Cannot advise 'get, because 'get has its own opcode in compiled code and thus isn't affected by advice.
#### (functionp symbol)
If always returning the modified value, it would cause incorrect indentation of quoted data lists and binding forms
```
(setq data '(data1
data2))
(let ((var1 val1)
(var2 val2))
...)
```
#### lisp-indent-function -\> 0
Only viable value is 0. For comparison:
```
;; 0 -> correct, but slightly low indent
(function-name (arg1)
(arg2))
(function-name
(arg1)
(arg2)
;; defun -> incorrect
(function-name (arg1)
(arg2))
;; most-positive-fixnum -> weird, but acceptable?
(function-name
(arg1)
(arg2)) ;; Nice!
(function-name (arg1)
(arg2)) ;; Decidedly not nice.
```
> 1 votes
---
Tags: indentation, emacs-lisp-mode
--- |
thread-69324 | https://emacs.stackexchange.com/questions/69324 | Two functions run on the same org-export filter; first has no effect | 2021-11-12T13:04:03.207 | # Question
Title: Two functions run on the same org-export filter; first has no effect
I'm passing more than one headline filter function to a `BIND` inside my org file, and I can't see why only the second seems to have an impact:
```
#+BEGIN_SRC emacs-lisp :exports results :results none
(defun tmp-f-list-singlebreak (s backend info)
(message "list singlebreak!")
(when (eq backend 'ascii)
(when (string-match-p "^* " s)
(message "match * in singlebreak")
(replace-regexp-in-string "\n\n" "\n" s))
(when (string-match-p "^β " s)
(message "match β in singlebreak")
(replace-regexp-in-string "\n\n" "\n" s))))
(defun tmp-f-list-item-better-bullet (s backend info)
(message "bullet!")
(when (eq backend 'ascii)
(replace-regexp-in-string "^β " "β’ " s)
))
#+END_SRC
#+BIND: org-export-filter-headline-functions (tmp-f-list-singlebreak tmp-f-list-item-better-bullet)
```
The messages printed are:
```
list singlebreak!
match β in singlebreak
bullet!
list singlebreak!
match β in singlebreak
bullet!
list singlebreak!
bullet!
```
From which it is clear that both functions are running. However the results on these exported items make it seem like `tmp-f-list-singlebreak` is not working:
```
** Heading
*** item one
*** item two
```
is exported as:
```
Heading
βββββββ
β’ item one
β’ item two
```
... when I expect there to not be a line break between `item one` and `item two`.
# Answer
> 1 votes
Try this simplified function:
```
(defun tmp-f-list-singlebreak (s backend info)
(message s)
(when (eq backend 'ascii)
(replace-regexp-in-string "\n\n" "\n" s)))
```
The filters are applied *after* the headline is "transcoded", i.e. after the exporter is done with it: at that point, there are not stars left to match, so I doubt you are doing the `replace-regexp-in-string` at all.
Note also that the above prints the incoming string for debugging. That allows you to check that indeed there is no asterisk left, so the `string-match-p` calls prevent the function from doing anything.
If you want better debugging messages, you can use `format`:
```
...
(message (format "In singlebreak: %s" s))
...
```
EDIT: The OP must have some setting to "beautify" the asterisks in the headline, which is probably why characters appear in the export output. When I run the exporter `text->UTF8` on his example Org mode file (with the "better debugging messages" method above), I get the following debugging output in `*Messages*`:
```
singlebreak: 1.1 item one
ββββββββββββ
[2 times]
bullet: 1.1 item one
ββββββββββββ
[2 times]
singlebreak: 1.2 item two
ββββββββββββ
[2 times]
bullet: 1.2 item two
ββββββββββββ
[2 times]
singlebreak: 1 Heading
βββββββββ
1.1 item one
ββββββββββββ
1.2 item two
ββββββββββββ
[2 times]
bullet: 1 Heading
βββββββββ
1.1 item one
ββββββββββββ
1.2 item two
ββββββββββββ
[2 times]
```
No asterisks and no diamonds.
---
Tags: org-mode, org-export
--- |
thread-69115 | https://emacs.stackexchange.com/questions/69115 | i have a regex that i want to apply only to the lines immediately following a \item line in a latex list. how do i do it? | 2021-10-27T23:36:03.853 | # Question
Title: i have a regex that i want to apply only to the lines immediately following a \item line in a latex list. how do i do it?
I should mention that I want to do this in emacs with its version of regex.
Here's an example. I would like to change
```
- \item
- Property Agreement
- Your agreement changing Joint Tenancy
- property into Community property.
```
to
```
- \item
- \textbf{Property Agreement}\\
- Your agreement changing Joint Tenancy
- property into Community property.
```
The regex to change the "Property Agreement" line is no problem. The problem I'm having is making it happen to lines immediately following the `\item` lines in the list and only those lines. The `\\` is the new-line code in LaTeX; not an emacs-regex code for a single slash.
# Answer
This worked:
regex = ^\\(\\item.\*C-qC-j\\)\\(.\*\\)
replacement = \1\\textbf{\2}\\\\
Thanks for your help.
Before
```
\item
Property Agreement
Your agreement changing Joint Tenancy
property into Community property.
\item
Funding Instructions
Instructions for the proper transfer of your
assets into the name of your Living Trust.
\item
Certificate of Trust
Selected Living Trust provisions that will
be helpful in funding and administering
your Living Trust.
```
After
```
\item
\textbf{Property Agreement}\\
Your agreement changing Joint Tenancy
property into Community property.
\item
\textbf{Funding Instructions}\\
Instructions for the proper transfer of your
assets into the name of your Living Trust.
\item
\textbf{Certificate of Trust}\\
Selected Living Trust provisions that will
be helpful in funding and administering
your Living Trust.
```
> 0 votes
# Answer
How about this? I left out the slashes and other details for simplicity, but it still demonstrates a solution:
```
\(item.*\n.+\)Property Agreement -> \1{Property Agreement}
```
Note that if you do this interactively then type `C-q C-j` instead of `\n`.
> 5 votes
---
Tags: regular-expressions, query-replace-regexp
--- |
thread-69326 | https://emacs.stackexchange.com/questions/69326 | Δ°mage caption problem | 2021-11-12T19:25:15.620 | # Question
Title: Δ°mage caption problem
I use org-mode publish, and it all works great but I have this small problem. I use this format to insert images:
```
#+CAPTION: Cavendish deneyinin ΓΆzgΓΌn analizi
#+ATTR_HTML: :alt cavendish deneyi :title cavendish deneyi :align center
#+ATTR_HTML: :width 50% :height 50%
http://cavendish-deneyi.com/img/cavendish-memoirs-88.jpeg
```
But for some reason, "Figure 1" is added to the caption of every image I insert. Do you know why? How can I get rid of it? Thanks.
# Answer
This question solved the problem.
I added this
```
.figure-number {
display: none;
}
```
to my css file.
**Edit:** More info about how I figured this:
I opened the page with the image that displayed "Figure 1." and in *Chrome DevTools*, I selected the caption and I saw that there was a class called "figure-number":
```
<span class="figure-number">Figure 1: </span>
```
So this class was adding the "Figure 1." In my CSS file I added
```
.figure-number {
display: none;
}
```
and that solved the problem.
> 2 votes
---
Tags: images, org-publish
--- |
thread-69329 | https://emacs.stackexchange.com/questions/69329 | How to multi-word search | 2021-11-13T08:58:21.110 | # Question
Title: How to multi-word search
When I use `swiper` to search inside a buffer I can use multiple search words separated by a blank space. This works.
But I also want that behaviour when search for a file (`C-x f`), a variable or function (`C-h f` or `C-h v`) or via `M-x` (what is this?) or finding a `org-roam` node.
I have `cousel` and `ivy` here and not sure which one of that packages is relevant for a the needed feature.
# Answer
If you use Icicles then you can:
1. Match any number of search patterns (e.g. words, literal strings, regexps) during completion. So you can use that to match file names with `C-x C-f`, function names with `C-h f`, etc.
2. Match not only file names this way (i.e., with multiple search patterns) but also, or instead, file contents. In Icicle minor mode `C-x C-f` is bound to the multi-completion command `icicle-file`, which lets you match either file name or file contents, or both, any number of times (e.g. with different patterns). `C-h f icicle-file` tells you this:
> **`C-x C-f`** runs the command **`icicle-file`** (found in `icicle-mode-map`), which is an interactive compiled Lisp function in `icicles-cmd1.el`.
>
> It is bound to `menu-bar file icicles icicle-file`, `open`, `C-x C-f`, `menu-bar file new-file`.
>
> `(icicle-file ARG)`
>
> Visit a file or directory.
>
> * With *no* prefix argument, use relative file names (`icicle-find-file`).
> * With a prefix argument, use absolute file names (`icicle-find-file-absolute`).
> * With a *negative* prefix arg, you can choose also by **date**: Completion candidates include the last modification date.
>
> All of these commands let you **search file content**, as well as file **names** (unless you use an Emacs version prior to 23). See `icicle-find-file` and `icicle-find-file-absolute` for more information.
>
> Note that when you use a prefix arg, completion matches candidates as ordinary strings. It knows nothing of file names per se. In particular, you cannot use remote file-name syntax if you use a prefix argument.
>
> If you use a prefix arg when you act on a completion candidate, then you visit the file or dir in *read-only* mode. This includes when you act on all candidates using **`C-!`**: precede the `C-!` with a prefix arg. This does not apply to the final candidate chosen (using `RET` or `mouse-2`) - a prefix arg has no effect for that.
>
> During completion (***** means this requires library Bookmark+), you can use the following keys:
>
> * `C-c C-d` \- change the \`default-directory' (with a prefix arg)
> * `C-c +` \- create a new directory
> * `C-backspace` \- go up one directory level
> * `M-|` \- open Dired on the currently matching file names
> * `S-delete` \- delete candidate file or (empty) dir
> * ***** `C-x C-t *` \- narrow to files with all of the tags you specify
> * ***** `C-x C-t +` \- narrow to files with some of the tags you specify
> * ***** `C-x C-t % *` \- narrow to files with all tags matching a regexp
> * ***** `C-x C-t % +` \- narrow to files with some tags matching a regexp
> * ***** `C-x a +` \- add tags to current candidate
> * ***** `C-x a -` \- remove tags from current candidate
> * ***** `C-x m` \- access file bookmarks (not just autofiles)
>
> By default, Icicle mode remaps all key sequences that are normally bound to `find-file` to `icicle-file`. If you do not want this remapping, then customize option `icicle-top-level-key-bindings`.
For more info about `icicle-file` and other file-accessing commands see Icicles - File-Name Input.
> 0 votes
---
Tags: search, find-file
--- |
thread-69330 | https://emacs.stackexchange.com/questions/69330 | defcustom not appearing in Customize UI | 2021-11-13T09:34:54.090 | # Question
Title: defcustom not appearing in Customize UI
I have a problem that variables defined with `defcustom` in elisp files under `~/.elisp` do not appear in the Customize UI.
In particular, I use word-count-mode from https://github.com/tomaszskutnik/word-count-mode/blob/master/word-count.el. Since it contains
```
(defcustom word-count-word-regexp "[a-z0-9_-]+"
"Regexp what is counted as words.")
```
I would have thought that I should then be able to do `M-x customize-apropos word-count-word-regexp`, for example, and be able to customize this variable. But nothing appears as "word-" at all.
The manual at https://www.gnu.org/software/emacs/manual/html\_node/elisp/Variable-Definitions.html seems to indicate that they should?
# Answer
> 1 votes
Just because something is defined in an Elisp file, that doesn't mean that that file ever gets *loaded*. And if it doesn't get loaded then its contents are unknown to Emacs.
To use `M-x customize-option` to customize an option, *you must load the file* that contains the `defcustom` that defines that option.
To load a file, put it in your `load-path`, then `require` it in your init file. Putting it in your `load-path` means adding its directory to the value of variable `load-path`, which you can do with \`add-to-list.
For example, this will make all files in directory `~/.elisp` (but not in subdirectories) loadable using `require`:
```
(add-to-list 'load-path "~/.elisp")
```
If the `defcustom` is autoloaded (it has an autoload cookie (`;;;###autoload` or other autoload declaration), and if an autoloads file that has been generated to include it has been loaded, then you don't need to explicitly load the file with the `defcustom` \- it will be loaded automatically. But that doesn't seem to be the case for your \`defcustom.
---
Tags: customize, autoload, require, load
--- |
thread-69334 | https://emacs.stackexchange.com/questions/69334 | Setting new values in `org-refile-target` not working | 2021-11-13T15:38:05.973 | # Question
Title: Setting new values in `org-refile-target` not working
I'm trying to add a new file `foo.org` and delete an old `bar.org` from the `org-refile-target` variable. So doing
```
(setq org-refile-targets (quote (("~/foo.org" :maxlevel . 2))
```
should work by replacing the former
```
(setq org-refile-targets (quote (("~/bar.org" :maxlevel . 2))
```
However, if I run the new code (i.e., the first line above), then the fix only works in the current session. Upon re-start changes are lost.
And even in the current session, if I do `C-h v org-refile-target` I see the changes under the `Value` heading. But the old settings are under the headings `saved-value` and `theme-value`. How come?
By the way, previously I was using
```
(custom-set-variables
'(org-refile-targets '(("~/foo.org" :maxlevel . 2)
```
with the same result. Plus I don't have a `custom` file that loads on Emacs's startup.
I've tried `org-refile-cache-clear` to no avail... so where on earth are the old settings stored and how can I override them?? Is `setq-default` the answer? (just tested and it is not the answer)
# Answer
Use `M-x customize-option` to change the value to whatever you want - and save it. *Customize **persists** your settings; `setq` does not.*
If you don't use a separate `custom-file` (I recommend you do use one), which you then load from your init file, then Customize saves your settings in your init file.
If you don't want to use the Customize UI then you can use function `customize-set-variable` or `custom-set-variables`, instead. They don't persist the settings they make, but you can use them in your init file to set things when it's loaded. (You can also use `customize-save-variable` or `custom-save-variables`.)
> -1 votes
---
Tags: customize, setq, persistence
--- |
thread-69335 | https://emacs.stackexchange.com/questions/69335 | How to switch windows to specific visible buffer? | 2021-11-13T16:30:05.863 | # Question
Title: How to switch windows to specific visible buffer?
Is there a command that allows me to have my cursor switch windows to a specified buffer? Something that looks like
```
(switch-to-specific-window-command "buffer-name")
```
# Answer
> 2 votes
Command `switch-to-buffer`, bound to `C-x b`, does what you're looking for. Likewise, `switch-to-buffer-other-window`, bound to `C-x 4 b`, and `switch-to-buffer-other-frame`, bound to `C-x 5 b`.
Command `pop-to-buffer` also does what you request, slightly differently.
---
From your comments, it's not clear what you want. The goalposts seem to be moving...
Now you seem to say you want to do *nothing* if the buffer is already in the `selected-window`? In that case, `pop-to-buffer` does just what you want, I think. Have you tried it?
Or if you don't want to use `pop-to-buffer`, but that is anyway what you want (do nothing if already visiting the buffer in the selected window), then this does that also:
```
(defun foo (buffer)
(interactive "b")
(unless (equal (get-buffer buffer) (window-buffer (selected-window)))
(switch-to-buffer-other-window buffer)))
```
---
Tags: buffers, window, selected-window
--- |
thread-69323 | https://emacs.stackexchange.com/questions/69323 | Failed to download βmelpa-stableβ archive. GnuTLS : Contacting host: 443 | 2021-11-12T12:59:50.383 | # Question
Title: Failed to download βmelpa-stableβ archive. GnuTLS : Contacting host: 443
I am trying to install packages/modes from melpa on my emacs27.1, but I am unable to do so. If I run `M-x package-refresh-contents` , I get the following error :
```
Importing package-keyring.gpg...done
Contacting host: elpa.gnu.org:443
gnutls.el: (err=[-50] The request is invalid.) boot: (:priority NORMAL:-VERS-TLS1.3 :hostname elpa.gnu.org :loglevel 0 :min-prime-bits nil :trustfiles (/etc/ssl/certs/ca-certificates.crt) :crlfiles nil :keylist nil :verify-flags nil :verify-error nil :callbacks nil)
Failed to download βgnuβ archive.
gnutls.el: (err=[-50] The request is invalid.) boot: (:priority NORMAL:-VERS-TLS1.3 :hostname stable.melpa.org :loglevel 0 :min-prime-bits nil :trustfiles (/etc/ssl/certs/ca-certificates.crt) :crlfiles nil :keylist nil :verify-flags nil :verify-error nil :callbacks nil)
Package refresh done
Failed to download βmelpa-stableβ archive.
You can run the command βpackage-refresh-contentsβ with M-x pa-r- RET
Failed to download βmelpa-stableβ archive.
```
My emacs init file has the following commands corresponding to this function:
```
(setq gnutls-algorithm-priority "NORMAL:-VERS-TLS1.3")
(package-initialize)
(require 'package)
(add-to-list 'package-archives
'("melpa-stable" . "https://stable.melpa.org/packages/") t)
```
By tracing a little I thought the error might be due to GnuTLS and it could not connect to the internet. So I tried `M-x eww RET https://www.wikipedia.org/ RET`, it stops at `Contacting host: www.wikipedia.org:443` and does not load anything.
Prior to this, I was running on emacs25 (updated to 27.1 thinking this error would go away), and when I ran `M-x eww RET https://www.wikipedia.org/ RET` on emacs25, I would get
```
Contacting host: www.wikipedia.org:443
gnutls.el: (err=[-50] The request is invalid.) boot: (:priority NORMAL:-VERS-TLS1.3 :hostname www.wikipedia.org :loglevel 0 :min-prime-bits 256 :trustfiles (/etc/ssl/certs/ca-certificates.crt) :crlfiles nil :keylist nil :verify-flags nil :verify-error nil :callbacks nil)
gnutls-negotiate: GnuTLS error: #<process www.wikipedia.org>, -50
```
Though I am running on Ubuntu 18.04LTS I tried the answer mentioned here hoping it would work, but unfortunately it did not. Please let me know if I need to add something more to my init file, or download some certificate or anything else.
# Answer
Not much of an answer but too long for a comment...
Among the various Emacs that I'm using, I use the default `emacs-nox` package from Ubuntu 18.04 (v25.2.2), and the default `emacs-nox` package from Ubuntu 21.04 (v27.1). I βhave the following for my package+use-package config. Connections to elpa/melpa, and https websites via `eww` are working fine for me. This is basically universal to all my Emacs configs.
If it wasn't for your errors with `eww` I'd have just blamed your issue on elpa being elpa...
Maybe the addition to `gnutls-trustfiles` βwill make a difference for you?
```
(require 'package)
(when (>= emacs-major-version 27)
β(setq gnutls-algorithm-priority "NORMAL:-VERS-TLS1.3"))
(add-to-list 'package-archives
β'("melpa" . "https://melpa.org/packages/") t)
(package-initialize)
;; Bootstrap 'use-package'
(eval-after-load 'gnutls
β'(add-to-list 'gnutls-trustfiles "/etc/ssl/cert.pem"))
(unless (package-installed-p 'use-package)
β(package-refresh-contents)
β(package-install 'use-package))
(eval-when-compile
β(require 'use-package))
(require 'bind-key)
```
> 0 votes
---
Tags: package-repositories, error-handling, gnutls, ssl
--- |
thread-31572 | https://emacs.stackexchange.com/questions/31572 | Detect language in buffer | 2017-03-20T12:39:40.453 | # Question
Title: Detect language in buffer
Is it possible to detect and set the correct ispell language based on the contents of the buffer?
And beyond that: A markdown file can contain multiple human languages at the same time, perhaps Swedish in paragraphs but english in code sections, is it possible to use different dictionaries for different parts of the buffer?
# Answer
> 3 votes
As for the first question, there is a package `guess-language` that you can use. See also this post by Manuel Uberti http://manuel-uberti.github.io/emacs/2017/02/04/guess-language/
# Answer
> 1 votes
For multiple languages in the same buffer an option would be to use `hunspell`.
Based on rom Spell check with multiple dictionaries :
```
(eval-after-load "ispell"
(defun myflyspell-multilingual-setup ()
;; POSSIBLE FIXES FOR MISSING DICTIONARIES FOR HUNSPELL:
;; - zypper install myspell-de_DE
;; COULD NOT GET IT TO WORK ON WINDOWS
(unless (eq system-type 'windows-nt)
(condition-case err
(progn
(setq ispell-program-name "hunspell")
(setq ispell-dictionary "en_US,de_DE")
(let ((null-device (make-temp-file "nuldevice")))
(ispell-set-spellchecker-params))
(ispell-hunspell-add-multi-dic ispell-dictionary))
('error (warn "In myflyspell-multilingual-setup: %S" err))))))
```
Fun fact: The only other spell-checker that I've seen to be able to check multiple languages without explicitly switching is the one built into Chrome. No Office suite or offline Email client I know of has this ability, which is extremely annoying for a non-native English speaker regularly writing with international contacts.
---
Tags: ispell
--- |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.