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-64319
https://emacs.stackexchange.com/questions/64319
Refile to non-agenda files
2021-04-06T14:13:26.247
# Question Title: Refile to non-agenda files Running Doom Emacs 2.0.9 on Emacs 27.1. My current settings are: ``` (setq org-directory "~/Documents/organize/org-mode") (setq org-agenda-files (directory-files-recursively "~/Documents/organize/org-mode/agenda" "^[[:alnum:]].*\\.org\\'")) ``` `org-refile-targets` is set to: ``` ((nil :maxlevel . 3) (org-agenda-files :maxlevel . 3)) ``` Refile targets seem to come only from agenda files. I would like to be able to refile to any file in org directory. What changes do I need to make? # Answer The doc string for the variable `org-refile-targets` says: > * a specification of the files to be considered, either a list of files, or a symbol whose function or variable value will be used to retrieve a file name or a list of file names. If you use ‘org-agenda-files’ for that, all agenda files will be scanned for targets. Nil means consider headings in the current buffer. So you can define a variable whose value is a list of the filenames of interest or a function that returns that list and use it in defining a new entry for `org-refile-targets`. Take the case of an org directory that contains a bunch of `.org` files (in a single level) that you want to be targets for refiling. Here's a function that returns a list of them: ``` (defun ndk/org-refile-candidates () (directory-files "/path/to/some/directory/org" t ".*\\.org$")) ``` You'll have to tweak the path according to your circumstances. If the set of files is static, it might be easier to define a variable instead. If you want a recursive traversal, you'll need to modify the function accordingly. Then you can add this to `org-refile-targets` with something like this: ``` (add-to-list 'org-refile-targets '(ndk/org-refile-candidates :maxlevel . 3)) ``` I should note that this is mostly untested, but it *should* work (ahem). > 2 votes --- Tags: org-mode, org-agenda, org-refile ---
thread-64325
https://emacs.stackexchange.com/questions/64325
Prevent term from asking me which shell to use
2021-04-06T18:32:01.770
# Question Title: Prevent term from asking me which shell to use I want to use `/bin/bash` as default shell for `term` avoiding it to ask me every time. Is this possible? # Answer There doesn't appear to be a way to tell Emacs to use a default shell for `term`. However, when you call the `term` function from elisp code, you can specify the terminal program to use. To use this, add the following to your configuration: ``` (defun my-term () (interactive) (term "/bin/bash")) ``` This defines a new command, which you can call as `M-x my-term`. You can change it to any name you like, as long as it doesn't conflict with an existing command name. (You could also use advice to change the way `M-x term` behaves, but that requires a bit more care to make sure you don't make problems for yourself) > 3 votes --- Tags: ansi-term, term ---
thread-64327
https://emacs.stackexchange.com/questions/64327
Run grep (like this)
2021-04-06T21:44:54.570
# Question Title: Run grep (like this) I use the standard `grep` command a lot. When I execute it, the minibuffer is populated with the following the text, allowing me to complete the command: ``` Run grep (like this): grep --color -nH --null -e ``` I almost always prefer to use Perl regex and ignore casing, so I'm finding myself replacing the last argument very often like so: ``` Run grep (like this): grep --color -nH --null -Pi ``` I would like to change the behavior of `grep` so that it loads with the argument `-Pi` instead of `-e` by default. When I use `describe-function` and inspect `grep`, I can see the lines (in `/usr/share/emacs/26.3/lisp/progmodes/grep.el.gz`) that define this behavior. Beginning line 650, there is a codeblock like so: ``` (let ((grep-options (concat (if grep-use-null-device "-n" "-nH") (if grep-use-null-filename-separator " --null") (if (grep-probe grep-program `(nil nil nil "-e" "foo" ,null-device) nil 1) " -e")))) (... ``` How do I override these `grep-options` in my Emacs config? I cannot find a variable named `grep-probe` or `grep-options` which I could just overwrite, for example, so what's the best practice then? # Answer The needed variable to set is called `grep-command`, resulting in `(setq grep-command "grep --color -nH --null -Pi")` > 2 votes --- Tags: grep ---
thread-64312
https://emacs.stackexchange.com/questions/64312
How to change color of searched text in the minibuffer when M-x activated?
2021-04-05T20:55:54.693
# Question Title: How to change color of searched text in the minibuffer when M-x activated? When I type `M-x` along with some text, the found text's background and font color is hard to read (gray and bold white on top of dark blue). Is it possible to change it? Example screenshot: --- As theme I am using dracula along with `ivy`. ``` (add-to-list 'custom-theme-load-path "~/.emacs.d/themes") (load-theme 'dracula t) (ivy-mode) (setq ivy-use-virtual-buffers t) (setq ivy-initial-inputs-alist nil) (setq enable-recursive-minibuffers t) (global-set-key (kbd "M-x") 'counsel-M-x) (define-key minibuffer-local-map (kbd "C-r") 'counsel-minibuffer-history) ``` ivy faces (I believe all are default setup): ## I was not able to do proper test using `emacs -Q` but it makes the found substring as bold without changing its background. example: # Answer @46\_and\_2's comment help me to solve to problem I was facing. > If you are using ivy you can customize the minibuffer faces using C-h v -\> ivy-minibuffer-faces -\> customize – > > You can try M-x \[customize group\] -\> ivy-faces. There are all kinds of \> faces you can set here including ivy minibuffer match highlight etc --- It was all related to ivy color configuration. Its not perfect but I was able to come up with following coloring from here (https://github.com/abo-abo/swiper/issues/2717) ``` (require 'package) (package-initialize) (require 'swiper) (progn (set-face-attribute 'ivy-current-match nil :foreground "white") (set-face-attribute 'ivy-minibuffer-match-face-2 nil :foreground "white" :background "red") (set-face-attribute 'ivy-minibuffer-match-face-3 nil :foreground "white" :background "darkgreen") (set-face-attribute 'ivy-minibuffer-match-face-4 nil :foreground "white" :background "blue") ;; (set-face-attribute 'swiper-match-face-2 nil :foreground "white" :background "red") (set-face-attribute 'swiper-match-face-3 nil :foreground "white" :background "darkgreen") (set-face-attribute 'swiper-match-face-4 nil :foreground "white" :background "blue")) ``` Output: > 0 votes --- Tags: minibuffer, coloring ---
thread-64320
https://emacs.stackexchange.com/questions/64320
Emacs from an alias/function
2021-04-06T14:59:35.137
# Question Title: Emacs from an alias/function ``` uname -a Linux antixbox 4.9.235-antix.1-amd64-smp #1 SMP PREEMPT Mon Sep 14 19:26:52 EEST 2020 x86_64 GNU/Linux emacs --version GNU Emacs 27.1 echo $SHELL /usr/bin/zsh ``` I'm trying to get the following to work: ``` em() { emacs $1 -geometry "56x23" } ``` I want to use it as follows e.g. with an existing file: ``` em testfile.txt ``` Emacs does launch, but no file buffer. If I edit the function and replace `nano` for `emacs` (and get rid of the geometry stuff), the function works perfectly. # Answer > 1 votes Maybe run Emacs as a server and then edit files with *emacsclient*? I have an alias ``` e='emacsclient -nw' ``` And is using it like ``` $ e foobar.txt ``` --- Tags: start-up ---
thread-47971
https://emacs.stackexchange.com/questions/47971
CC mode: make Tab just insert one tab or complete, no auto-indenting
2019-02-21T22:40:25.163
# Question Title: CC mode: make Tab just insert one tab or complete, no auto-indenting I am dissatisfied with current behaviour of Emacs in CC Mode. I'm not sure if this applies to other major modes, but that's one I'm currently struggling with. Here are my problems: 1. When I press tab, instead of inserting just one tab, Emacs either inserts enough space to match last line indentation level. 2. I also can't insert tab when on empty line. I believe those are caused by `c-indent-line-or-region` function, according to `C-h l`, but I don't know what I can do with it. Neither of possible values for `c-tab-always-indent` change this situation. I found something about `tab-to-tab-stop`, and using it helped, however, it disabled expanding snippets from yasnippet or `<s` in org-mode. My setup consists of Evil-mode, Company-mode, LSP-mode, and following directives in `init.el`: ``` (setq-default indent-tabs-mode t) (setq tab-width 8) (defvaralias 'c-basic-offset 'tab-width) (setq-default c-default-style "linux" c-basic-offset 8 c-tab-always-indent nil indent-tabs-mode t) ``` `tab-to-tab-stop` has something related to expanding in it's source: ``` (and abbrev-mode (= (char-syntax (preceding-char)) ?w) (expand-abbrev)) ``` but it doesn't help. I thought I found solution in using `tab-to-tab-stop` with `c-tab-always-indent` to `'complete`, and it worked, for some time, but after I restarted emacs, it, again, has no effect. ``` (setq-default c-tab-always-indent 'complete) ... ;; in configuration for evil mode (define-key evil-insert-state-map (kbd "TAB") 'tab-to-tab-stop) ``` So is there a way for me to make tabs stupid, i.e. **having pressing Tab just insert `\t` (or N spaces if configured so)**, while **keeping the ability to expand snippets** using it? **EDIT:** After disabling tab-to-tab-stop and seeing with `C-h l` what exactly causes snippets to expand (`org-cycle` and `yas-expand`), I'm starting to suspect that there is some kind of function that tries to understand the context and apply specific action, and my evil-state map interferes with it, taking priority or something? Are my guesses wrong? # Answer > 0 votes ``` (setq-default c-tab-always-indent 'complete) ... ;; don't do this: ;; (define-key evil-insert-state-map (kbd "TAB") 'tab-to-tab-stop) ;; also don' this: ;; (global-set-key (kbd "TAB") 'tab-to-tab-stop) ;; (global-set-key [tab] 'tab-to-tab-stop) ;; do this (define-key c-mode-base-map (kbd "<tab>") 'tab-to-tab-stop) (define-key c-mode-base-map [tab] 'tab-to-tab-stop) ``` # Answer > 1 votes If your goal is to insert a tab character, you can use `C-q <tab>`, and let the default binding for tab key as is. With `C-q` you invoke `quoted-insert`, so the next key is not interpreted as a command, but inserted "verbatim" in the buffer. `C-q` is also useful in other contexts. For example, to search for tabs character you can type `C-s C-q <tab>`. --- Tags: key-bindings, indentation, tabs ---
thread-58844
https://emacs.stackexchange.com/questions/58844
Where is `personal dictionary` for `ispell` located?
2020-06-01T15:16:15.603
# Question Title: Where is `personal dictionary` for `ispell` located? `C-h v ispell-personal-dictionary` shows `nil`. Its docstring says: ``` Documentation: File name of your personal spelling dictionary, or nil. If nil, the default personal dictionary for your spelling checker is used. ``` My spellchecker is hunpsell, installed in `C:\Hunspell`, Windows 10. Emacs finds it and performs spellcheck without issues. Can't find any personal dic in its folder and subfolders. Edit: the first comment gives a link, which explains where the default location is. # Answer The link in the first comment answered the question. From the man page: ``` -p dict Set path of personal dictionary. Default is $HOME/.hunspell_default. Setting -d or the DICTIONARY environmental variable, personal dictionary will be $HOME/.hunspell_dicname ``` This answers where hunspell stores personal dics. ‘ispell’ works with other backends (‘aspell’, ‘enchant’) and things are different there. > 2 votes # Answer You can find it at C:\users\username\hunspell\_default > 0 votes --- Tags: microsoft-windows, hunspell ---
thread-64322
https://emacs.stackexchange.com/questions/64322
Elpher loads for Gopher but not Gemini using Doom Emacs
2021-04-06T15:35:57.610
# Question Title: Elpher loads for Gopher but not Gemini using Doom Emacs I am using the most up to date version of Doom Emacs, and I am trying to use Elpher to access Gemini pages. While it loads up Gopher pages just fine, any time I try to pull up a Gemini page I get a "Connection time-out message." Other users have suggested that it may be a TLS related issue, but I can't confirm that. They have stated that when they try the package with vanilla Emacs it works fine. Any suggestions on how I might go about fixing this? # Answer So after comparing the TLS related variables between vanilla Emacs and Doomemacs, and playing around with some of the settings, the following allows me access to gemini websites: ``` (setq gnutls-verify-error 'nil) ``` I have no idea what security implications that has, but that gets things working at least. > 2 votes --- Tags: package, doom ---
thread-64342
https://emacs.stackexchange.com/questions/64342
Emacs: DiredSort : can't sort by size
2021-04-07T20:59:44.413
# Question Title: Emacs: DiredSort : can't sort by size Linux Mint 20.1 Emacs 26.1 Install dired+ package. Also install DiredSort from here https://www.emacswiki.org/emacs/DiredSort I try to sort by size. ``` dired-sort-size ``` But I get error on empty screen: Error: ``` insert-directory: Listing directory failed but ‘access-file’ worked ``` # Answer > 1 votes I think that your problem has nothing to do with Dired+. I think you'll have the same problem if you don't load Dired+. I can't speak for library `dired-sort.el`, which defines the command you're using. It may have a bug. Maybe contact the maintainer. Emacs-Wiki page DiredSorting lists other libraries that offer sorting possibilities. I use Dired Sort Menu (libraries dired-sort-menu+.el and dired-sort-menu.el), and they work fine for sorting by file size. You can also just customize your `dired-listing-switches` string to include the character `S` (uppercase). Or just use `C-u` when you invoke Dired, and add `S` to the listing switches when prompted for them. --- Tags: dired ---
thread-64348
https://emacs.stackexchange.com/questions/64348
Omit files in a certain directory
2021-04-08T05:15:15.687
# Question Title: Omit files in a certain directory I'm trying to omit html files from a certain directory when using dired. For all directories I could do it like so; ``` (setq dired-omit-files "\\.html$") ``` I only want to hide html files from my org directory Here is what didn't work ``` (setq dired-omit-files "\\/home/map7/org/\\.html$") ``` Is there a way to do this? # Answer > 3 votes Create a `.dir-locals.el` file in the directory of interest, with the following contents: ``` ((dired-mode . ((dired-omit-files . "\\.html\\'")))) ``` If you want to omit the usual suspects as well, then use this regexp (which is the OR of the standard value with the `html` value above): ``` "\\`[.]?#\\|\\`[.][.]?\\'\\|\\.html\\'" ``` Visiting the directory will ask about allowing the local variable which you can accept and enable for future visits with `!`. Assuming that one way or another, you have enabled `dired-omit-mode` (e.g. with `M-x dired-omit-mode RET`), then any `.html` files are omitted. To enable `dired-omit-mode` always, see the doc string for the function: `C-h f dired-omit-mode`, which says: > To enable omitting in every Dired buffer, you can put this in your init file: > > (add-hook 'dired-mode-hook (lambda () (dired-omit-mode))) This applies to the directory of interest *and its subdirectories*. I don't know of a way to limit it to just the directory of interest using `.dir-locals.el`. It might be possible to do it using the more advanced mechanisms that are mentioned in the "Per-directory local variables" section of the manual (which you can get to with `C-h i g (emacs)directory variables RET`), but I have not gone down that route at all. --- Tags: dired, dired-omit-mode ---
thread-64353
https://emacs.stackexchange.com/questions/64353
Change vertical characters to horizontal
2021-04-08T16:58:18.793
# Question Title: Change vertical characters to horizontal I have the following data and want to change from Code 1 to Code 2. Is there any useful method to do that? Code 1 ``` 11130101 11130102 11130201 ``` Code 2 ``` 11130101, 11130102, 11130201 ``` # Answer You want to replace a newline with a comma and a space. You can use `query-replace` for that if you know how to type a newline character: `C-q C-j`. So all together, you can mark the region where you want to make the change and then type `M-% C-q C-j RET , SPC RET !`. > 2 votes --- Tags: text-editing, keyboard-macros ---
thread-64359
https://emacs.stackexchange.com/questions/64359
Why can't I use rg (ripgrep) in an Org mode source block?
2021-04-08T19:15:28.977
# Question Title: Why can't I use rg (ripgrep) in an Org mode source block? I have the following source block in my Org mode file: ``` #+begin_src sh :results output exec 2>&1 mkdir -p /tmp/example && cd /tmp/example echo "hello" > world rg --color=never 'hello' : #+end_src ``` However, I never see any output in Org mode. The same code works fine in my shell. I've also compared the `env`ironment of both the `org-babel-execute:shell` results and my shell and they seem to differ only in `TERM`. Why doesn't `rg` output anything when I execute my block? # Answer > 4 votes This is likely related to this issue in ripgrep. As you didn't specify any file pattern, `rg` also reads from `STDIN`. For some reason, this yields to no result at all in your example, probably because Org uses your script as input into a shell (`sh < your-sh-scode`). However, if you use `/dev/null` or an explicit file pattern as input for `rg`, it works fine: ``` #+begin_src sh :results output exec 2>&1 mkdir -p /tmp/example && cd /tmp/example echo "hello" > world rg --color=never 'hello' </dev/null : #+end_src ``` --- Tags: org-mode, org-babel, ripgrep ---
thread-26203
https://emacs.stackexchange.com/questions/26203
Convert between numbered and unordered lists in org-mode
2016-08-11T15:05:13.157
# Question Title: Convert between numbered and unordered lists in org-mode Is there a function to convert between numbered and unordered lists in org-mode? The lists may or may not be nested. # Answer > 33 votes You can use the function `org-ctrl-c-minus`, bound by default to (you guessed it) `Control`-`c`-`-`, to cycle through the bullet types. The doctstring reads: > Insert separator line in table or modify bullet status of line. Also turns a plain line or a region of lines into list items. Calls `org-table-insert-hline`, `org-toggle-item`, or `org-cycle-list-bullet`, depending on context. `org-cycle-list-bullet`, in turn, does the following according to the docstring: > `(org-cycle-list-bullet &optional WHICH)` > > Cycle through the different itemize/enumerate bullets. This cycle the entire list level through the sequence: > > `-` -\> `+` -\> `*` -\> `1.` -\> `1)` > > If WHICH is a valid string, use that as the new bullet. If WHICH is an integer, 0 means `-`, 1 means `+` etc. If WHICH is `previous`, cycle backwards. See the `org` manual node on plain lists for more details. # Answer > 26 votes In my org-mode environment, for example, the first state is as followings: unordered list. ``` - a - b - c ``` Modify the first line as "1. a" as numbered list. ``` 1. a - b - c ``` Now, hit `C-c C-c` at the first line "1. a". Unordered list becomes numbered list. ``` 1. a 2. b 3. c ``` Modify the first line as "- a" as unordered list. ``` - a 2. b 3. c ``` Now Hit `C-c C-c` at the first line "- a". Numbered list becomes unordered list. ``` - a - b - c ``` I hope it works. # Answer > 3 votes You can use `shift` (that is `S-<right>` in Emacs notation.) This is bound to `org-shiftright`, which will automatically do the right thing for your entire list if you're on any of the items. Press it multiple times to cycle through all possible list styles. And `S-<left>` goes the other way :) (Source: reddit) --- Tags: org-mode ---
thread-64358
https://emacs.stackexchange.com/questions/64358
Org-mode: changing temporarily font size for LaTeX export
2021-04-08T18:45:29.510
# Question Title: Org-mode: changing temporarily font size for LaTeX export I need to change the font size of part of my text (actually mostly to fit a table, which might be an extra-step). Following a org-mode discussion somewhere, I have tried the following, which does not work for me in spacemacs 0.3 with Emacs 27: ``` #+title: Test changing font size * Text Nemo enim ipsam voluptatem, quia voluptas sit, aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos #+begin_latex {\scriptsize #+end_latex | Table | Column | |-------+---------| | Row | Content | #+begin_latex } #+end_latex #+begin_latex {\ssmall #+end_latex qui ratione voluptatem sequi nesciunt, neque porro quisquam est #+begin_latex } #+end_latex ``` Regards, Trad # Answer > 4 votes There *used* to be a `#+begin_latex` (or `#_begin_html` or ...) block, but it no longer exists. Try this instead: ``` * Text Nemo enim ipsam voluptatem, quia voluptas sit, aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos #+latex: {\scriptsize | Table | Column | |-------+---------| | Row | Content | #+latex: } ``` which is simpler and works through all Org mode releases (AFAIK). Alternatively, this should also work: ``` #+begin_export latex {\scriptsize #+end_export | Table | Column | |-------+---------| | Row | Content | #+begin_export latex } #+end_export ``` but it is longer and the markup obscures things (but it is more convenient for large, multi-line LaTeX code insertions). --- Tags: org-mode, latex ---
thread-53763
https://emacs.stackexchange.com/questions/53763
Semantic linefeeds (one sentence per line) in Emacs
2019-11-15T16:34:04.750
# Question Title: Semantic linefeeds (one sentence per line) in Emacs I'm trying to get Emacs to insert a line break at the end of each sentence as I type. (Why? Makes for easier version control of `tex` files.) Looking around I found a few places with some suggestions for how to do something similar. * This question's answers are mostly suggestions for how to take a document and insert line breaks after each sentence after the fact. * This question is asking for a slightly different feature, viz. having Emacs insert two spaces after each sentence. In an answer to the second question, abo-abo suggests something like this: ``` (defun electric-space () (interactive) (if (looking-back "\\w\\.") (insert " ")) (self-insert-command 1)) (defvar electric-space-on-p nil) (defun toggle-electric-space () (interactive) (global-set-key " " (if (setq electric-space-on-p (not electric-space-on-p)) 'electric-space 'self-insert-command))) ``` A small change to this almost allows me to do what I want: replace `insert " "` with `insert "%\n"`. One downside of this is that the point always ends up on the second column of the following line. Thus, this is what results if I call `toggle-electric-space`: ``` Hello world. % This is another line. ``` Is there an obvious way around this? Another problem with this approach is that there are cases where `.` does not come at the end of a sentence (though that's easy to fix by writing, e.g. `p.~23` instead of `p. 23`, which is good practice anyway) as well as cases where a sentence ends with something other than a period (`?`, `!`, `.)`, etc.). Now, it seems to me that these problems should be easy to get around in Emacs, since we have something like `forward-sentence` around, which is smart enough as far as I can tell to recognize that `(This sentence.)` ends after the closing parenthesis. But I don't know how to make use of `forward-sentence` in combination with the definition of `electric-space` above. This package manages to do something similar to what I want. The difference is that it makes `.` electric, so it requires explicitly listing all the possible exceptions, i.e. all cases where a period does not end a new line. And in order to allow for sentences that do not end with a period, the package makes `?` and `!` electric, but I see no easy way of allowing for `.)` and `?)`, etc., to be recognized as ending sentences. I suppose adding a condition like `if (looking-back ".")` in making the closing parenthesis electric might work... I'll need to study that package more careful and see how I could modify it to suit my purposes. But being effectively a `lisp` illiterate, I'd appreciate any pointers you may have. # Update The way to implement abo-abo's suggestion should instead be this: ``` (defun electric-space () ; Trying to get Emacs to do semantic linefeeds (interactive) (if (looking-back (sentence-end)) (insert " %\n") (self-insert-command 1)) ) (defvar electric-space-on-p nil) (defun toggle-electric-space () (interactive) (global-set-key " " (if (setq electric-space-on-p (not electric-space-on-p)) 'electric-space 'self-insert-command))) ``` I don't know if there's a more elegant way to do this, but for now it seems to work. # Answer > 1 votes (Posting the 'update' to my question here as an answer.) The way to implement abo-abo's suggestion should instead be this: ``` (defun electric-space () ; Trying to get Emacs to do semantic linefeeds (interactive) (if (looking-back (sentence-end)) (insert " %\n") (self-insert-command 1)) ) (defvar electric-space-on-p nil) (defun toggle-electric-space () (interactive) (global-set-key " " (if (setq electric-space-on-p (not electric-space-on-p)) 'electric-space 'self-insert-command))) ``` I don't know if there's a more elegant way to do this, but for now it seems to work. That said, since asking this question, the package twauctex has changed and now uses and makes `SPC` electric rather than `.`. I've been happily using this package for a while now and highly recommend it to other `auctex` users. --- Tags: latex, auctex, version-control ---
thread-64272
https://emacs.stackexchange.com/questions/64272
"#+STARTUP: hideblocks" won't work. Can't find offending package/setting
2021-04-02T17:24:25.987
# Question Title: "#+STARTUP: hideblocks" won't work. Can't find offending package/setting After I upgraded to Org Mode 9.4.5, I learned about the startup option `hideblocks`, but it won't work as advertised for me. OK, when I start emacs with the flag `-Q`, it did, so I went hunting for culprits in my `.emacs`. All suspicious-looking settings and packages have been removed, but `hideblocks` still doesn't work. Oddly enough, when I visit a test file with `#+STARTUP: hideblocks`, the variable `org-hide-block-startup` do indeed change from `nil`, which is default, to `t`. Despite this, the block remains unfolded! I can make all blocks fold on start-up, if I set `org-hide-block-startup` with a local variables section at the end of the file, but I consider that to be an ugly, last resort solution. Is there a smart way of tracking down when and where the hideblock setting is reversed, intercepted, toggled, or whatever happens? --- *Addendum April 4:* Since writing the above, I stumbled upon one additional interesting symptom. When I was led astray with the theory that my Org Mode installation was somehow faulty, I took a look at the installation instructions in the info documentation. Among other things, it says the following about an org mode installation with elpa: > Important: You need to do this in a session where no ‘.org’ file has been visited, i.e., where no Org built-in function have been loaded. Otherwise autoload Org functions will mess up the installation. So I did `M-x list-packages`, threw out org mode, restarted Emacs, installed org mode anew, and visited my test file. Lo and behold, my block was folded at start-up. However, the effect was short-lasting, and trying to open the same file later did not work as expected. # Answer > 2 votes The solution is much simpler than suggested by my own theories (see above). It turns out that the intended effect of `#+STARTUP: hideblocks` is overruled by the initial visibility setting `#+STARTUP: showeverything`, which is now default. So, by combining `#+STARTUP: hideblocks` with `#+STARTUP: showall` or (equivalently) `#+STARTUP: nohide`, the desired effect can be obtained. N.B. "nohide" is hiding pretty well in the info documentation, but can be found if one looks at the documentation for the variable `org-startup-folded`. --- Tags: org-mode, debugging ---
thread-64361
https://emacs.stackexchange.com/questions/64361
How to check if erc is running
2021-04-08T19:34:47.347
# Question Title: How to check if erc is running I want to write a function that does one thing if erc is running and starts erc (using command `erc`) if not. I tried to write it myself, but I couldn't find out how to check if erc is running. How can I do this in elisp? # Answer > 1 votes There are two aspects: is there an `erc` process running in the buffer? and if there is such a process, is there an established network connection to the server? If you look in `erc.el`, you will see how `erc` itself determines the process status to add to the mode line (line 6438 in the file): ``` ... (let ( ... (process-status (cond ((and (erc-server-process-alive) (not erc-server-connected)) ":connecting") ((erc-server-process-alive) "") (t ": CLOSED"))) ``` IOW, it uses the function `erc-server-process-alive` to check whether the process is alive and the value of the variable `erc-server-connected` to see if it is connected to the server: if it is alive but not connected to the server, it reports "connecting"; else if it is alive, it reports nothing (i.e. everything is good); else it reports "CLOSED". You should check the doc strings of the function above (`C-h f erc-server-process-alive`) and the variable (`C-h v erc-server-connected`) and read them carefully, but this should allow you to determine the state of `erc`. --- Tags: erc, irc ---
thread-63824
https://emacs.stackexchange.com/questions/63824
Add `tikzpicture` environment to the list of choices for AUCTex's environment insertion shortcut?
2021-03-10T13:42:32.937
# Question Title: Add `tikzpicture` environment to the list of choices for AUCTex's environment insertion shortcut? I use AUCTex for all my Latex needs, and it works great. However, I wanted to insert a `tikzpicture` environment in my document, and I pushed the key `C-c C-e` for environments, but `tikzpicture` is not listed amongst the choices. Is there a way to include the `\begin{tikzpicture} ... \end{tikzpicture}` environment in the list of AUCTex environments? I am not sure what variable I would need to change or how in my dotfile. I use Spacemacs, so I would probably need to append something to the list of environments,right? # Answer Okay, I figured it out. A user might need to check the final 3 parenthesis, but this code worked to add the environment. I added the following lines to my `.spacemacs` file. ``` ;; Add latex environments to list of environments. (add-hook 'LaTeX-mode-hook 'add-my-latex-environments) (defun add-my-latex-environments () (LaTeX-add-environments '("tikzpicture" LaTeX-env-label))) ``` > 1 votes # Answer AucTeX automatically provides a list of environments for you to insert. This includes a set of 'default' environments, based on a hard-coded set of environments commonly associated with the `documentclass` of your file. Additionally, AucTeX parses the header of your file, and if it detects any packages that provide additional environments, these are added to the list. This functionality depends on you telling AUCTeX to parse your file automatically: ``` (setq TeX-parse-self t) ; Enable parse on load. (setq TeX-auto-save t) ; Enable parse on save. ``` You can also manually tell AUCTeX to reparse your file, if you don't want it done automatically. The command `TeX-normal-mode`, bound to `C-c C-n` by default, serves this purpose. There may be exceptions where you need to manually add an environment. However, I have just tested this with Emacs 28.0.50 and AUCTeX 13.0.5, and the `tikzpicture` environment is properly detected when your file contains the `\usepackage{tikz}` macro. > 1 votes --- Tags: latex, auctex ---
thread-64334
https://emacs.stackexchange.com/questions/64334
Define setupfile in emacs init for org file
2021-04-07T07:48:30.873
# Question Title: Define setupfile in emacs init for org file I use setupfile to export org file to pdf. It basically define latex header and footer (my letterhead template). I include it in every org document like this ``` #+SETUPFILE: c:/SETUPFILE ``` Though there is not much issue with this practice, but is it possible to define it in init to be automatically included in all org files for export # Answer You could turn your SETUPFILE into a LaTeX class .sty file, and install that .sty file where LaTeX will find it. Then you can add your new package to the list of packages org automatically includes everytime you export to pdf by customizing the variable `org-latex-packages-alist`. > 1 votes --- Tags: org-mode, org-export, latex, latex-header ---
thread-64354
https://emacs.stackexchange.com/questions/64354
How to calculate time durations in tables?
2021-04-08T17:15:42.483
# Question Title: How to calculate time durations in tables? *How to calculate time durations in tables?* Subtraction of numerical vectors works directly: ``` | day | t1 | t2 | differences | |------------------+----------+----------+-------------| | [2021-04-08 Thu] | [10, 13] | [16, 18] | [6, 5] | #+TBLFM: $4=$3-$2 ``` Using this with time vectors to compute durations doesn't work. It computes only the first item: ``` | day | time 1 | time 2 | durations | |------------------+----------------+----------------+-----------| | [2021-04-08 Thu] | [10:45, 14:00] | [12:00, 15:00] | 01:15 | #+TBLFM: $4=$3-$2;U ``` I would expect this: ``` | day | time 1 | time 2 | durations | |------------------+----------------+----------------+---------------| | [2021-04-08 Thu] | [10:45, 14:00] | [12:00, 15:00] | [01:15, 1:00] | ``` I hope there is an (easy) solution (?) --- EDIT: The n-th item of 'time 2' would be always larger than the n-th item of 'time1'. I don't know if this makes it simpler. --- EDIT2: I've tried it with elisp. My idea was to convert the time into minutes, so 10:45 should be converted to 10x60+45=645. I've found an org function for it, the evaluation of the following line is "645.0". ``` (org-duration-to-minutes "10:45") ``` Then I can make the "vector subtraction" with the numbers, then I just have to reconvert the results. There is the function `org-duration-from-minutes` for this purpose. That was the idea but I wasn't able to let it work in the table. I'm not familiar at all with it. Even this simple formula doesn't work -- "ERROR": ``` | day | time 1 | time 2 | time2 in minutes | durations | |------------------+----------------+----------------+------------------+-----------| | [2021-04-08 Thu] | [10:45, 14:00] | [12:00, 14:00] | #ERROR | | #+TBLFM: $4='(mapcar 'org-duration-to-minutes $3) ``` I would expect "\[720.0, 840.0\]". (This would be an intermediate step.) I also tried to change the format into "10:45 14:00" or "(10:45 14:00)" or "(10:45, 14:00)".. It didn't work. --- EDIT 3: *I've found a solution. See below.* # Answer I've found a solution. It's acceptable for me. I don't know if it's useful for you. Anyway I'm sharing it. I changed the format a bit (one column for the times, not two), I think it is more practical. Example: Workflow for a day: ``` | work | workflow | single durations | sum | |------+------------------------------------+------------------+------| | w1 | 9:15-10:16 13:00-13:05 16:08-17:19 | (1:01 0:05 1:11) | 2:17 | | w2 | 11:13-12:00 | (0:47) | 0:47 | | w3 | 14:05-15:03 17:34-19:03 | (0:58 1:29) | 2:27 | #+TBLFM: $3='(format "%s" (durations-HHMM $2))::$4='(sum-durations $2) ``` I use these small functions: ``` (defun single-duration-minutes (s) (let ( (l (split-string s "-")) ) (- (org-duration-to-minutes (nth 1 l)) (org-duration-to-minutes (nth 0 l))))) (defun durations-HHMM (s) (mapcar 'org-duration-from-minutes (mapcar 'single-duration-minutes (split-string s)))) (defun sum-durations (l) (org-duration-from-minutes (apply '+ (mapcar 'single-duration-minutes (split-string l))))) ``` Examples for the functions: ``` (single-duration-minutes "10:15-11:45") ; 90.0 (durations-HHMM "10:15-11:45 13:00-13:05 14:10-14:14") ; ("1:30" "0:05" "0:04") (sum-durations "10:15-11:45 13:00-13:05 14:10-14:14") ; "1:39" ``` If you see an error or have any suggestions for improvement, please let me know. > 2 votes --- Tags: org-mode, org-table, time-date ---
thread-64374
https://emacs.stackexchange.com/questions/64374
How to prevent some files from showing up on the Ibuffer list?
2021-04-10T09:56:06.690
# Question Title: How to prevent some files from showing up on the Ibuffer list? On my IBuffer I keep seeing `*lsp-log*` and `*pyls::stderr*` files. ``` [ Default ] *% *lsp-log* 516 Fundamental *% *pyls::stderr* 264 Special (pyls stderr open) ``` --- Is it possible to prevent these file to be hidden in the `Ibuffer` or basically hide or remove them. My approach does not make any change: ``` (recentf-mode 1) (setq recentf-max-saved-items 50) (setq recentf-max-menu-items 50) (setq recentf-exclude '("*lsp-log*" "pyls::stderr" )) ``` More general question should be as: how can I prevent some files show up on the `Ibuffer list`. # Answer > 1 votes > Is it possible to prevent these file to be hidden in the `Ibuffer` or basically hide or remove them. Yes, have a look at the user option `ibuffer-never-show-predicates`: ``` ibuffer-never-show-predicates is a variable defined in ‘ibuf-ext.el’. Its value is nil This variable may be risky if used as a file-local variable. You can customize this variable. A list of predicates (a regexp or function) for buffers not to display. If a regexp, then it will be matched against the buffer’s name. If a function, it will be called with the buffer as an argument, and should return non-nil if this buffer should not be shown. ``` So, you could either customise this user option to include the buffer names `*lsp-log*` and `*pyls::stderr*` (using regexp syntax), or you could write something like the following yourself: ``` (setq ibuffer-never-show-predicates (mapcar #'regexp-quote '("*lsp-log*" "*pyls::stderr*"))) ``` > My approach does not make any change: That's to be expected, as `recentf` and `ibuffer` are different packages that don't share any common functionality. --- Tags: ibuffer ---
thread-64371
https://emacs.stackexchange.com/questions/64371
org mode open link in browser directly
2021-04-09T18:31:50.890
# Question Title: org mode open link in browser directly Suppose, we have a link `[[https://www.google.com/][Google]]`. When I put the cursor at the link and run `org-open-at-point`, instead of opening https://www.google.com/ in browser it downloads the page to `/var/tmp` and opens the file in browser: file:///var/tmp/kdecache-user/krun/20635\_0\_. All the css and js are broken of course. Can I make it open the direct link in browser? Or maybe, it's not Emacs, but KDE. # Answer \[This answer is meant as a tutorial introduction to how one would debug problems like the OP's, so it is more detailed than the "answer" which is just the setting of `browse-url-browser-function` below. But I have always found answers of the sort "Do `this` \- problem solved" unsatisfactory: I like to understand what's going on. YMMV, in which case skip the long-winded explanations.\] `org-open-at-point` calls `org-link-open` which uses the variable `org-link-parameters` to look up the `:follow` property for the type of the link. In this case the type is `https` and the `:follow` property turns out to be an anonymous function that is set when the file `ol.el[c]` (l.1349 in my version of the file) is loaded: ``` ... ;;;; "http", "https", "mailto", "ftp", and "news" link types (dolist (scheme '("ftp" "http" "https" "mailto" "news")) (org-link-set-parameters scheme :follow (lambda (url arg) (browse-url (concat scheme ":" url) arg)))) ... ``` The upshot is that this anonymous (`lambda`) function calls `browse-url`. It is unlikely that the problem as described is caused by any of the above, so we concentrate on `browse-url`. Reading the doc string of `browse-url` (`C-h f browse-url`) uncovers the fact that it calls the function that is specified as the value of the variable `browse-url-browser-function`. After prodding the OP with a question, we find out that the OP's setting of that variable was `browse-url-default-browser`. Unfortunately for debugging purposes (*remote* debugging purposes, no less), that function pokes around all over the place until it finds something that it can use and then calls that something. So at that point, it was more expedient to suggest that the OP bypass that and set the `browse-url-browser-function` variable directly to the function corresponding to the desired browser: ``` (setq browse-url-browser-function #'browse-url-firefox) ``` Setting that in the init file did the trick for the OP. Other "direct to external browser" function available include `browse-url-chrome` and `browse-url-mozilla`. The only remaining mystery is why the default browser function did what the OP described. From the description, it seems that the culprit is `browse-url-kde`. I have no way to test that, but a KDE user can confirm (or refute) that claim by evaluating the following (e.g. in the `*scratch*` buffer - paste the expression and type `C-j` after the closing paren): ``` (browse-url-kde "https://www.google.com") ``` If that does what the OP describes, it's arguably a bug in the `browse-url-kde` function and should probably be reported (`M-x report-emacs-bug`). > 10 votes --- Tags: org-mode, org-link, hyperlinks ---
thread-61173
https://emacs.stackexchange.com/questions/61173
How to time org-mode code block execution?
2020-10-13T19:14:37.410
# Question Title: How to time org-mode code block execution? Is there an easy way to time how long it takes to execute source code blocks in org-mode (maybe with header arguments or similar), if so, how? Or do I have to implement it in the code itself? I'm using python3 btw. # Answer > 2 votes This can be handled by *advising* the code that handles source code block execution in Org Mode. The function in question is `org-babel-execute-src-block` \- it runs a hook after it executes, but not before, so the advice feature is required - and probably preferred for this use. ``` (defun gjg/time-call (time-call &rest args) (message "Ohai %s" args) (let ((start-time (float-time))) (apply time-call args) (message "Function call took %f seconds" (- (float-time) start-time))) ) (advice-add 'org-babel-execute-src-block :around #'gjg/time-call) ``` You will now get a message with the elapsed time for the code block execution printed in the \*Messages\* buffer. To remove the advice, execute ``` (advice-remove 'org-babel-execute-src-block #'gjg/time-call) ``` # Answer > 1 votes There is a mistake: the result of function "time-call" must be passed forward. ``` (defun gjg/time-call (time-call &rest args) (message "Ohai %s" args) (let ((start-time (float-time)) (result (apply time-call args))) (message "Function call took %f seconds" (- (float-time) start-time)) result)) (advice-add 'org-babel-execute-src-block :around #'gjg/time-call) ``` --- Tags: org-mode, timers ---
thread-64380
https://emacs.stackexchange.com/questions/64380
`doc-view-mode` for PDFs not working
2021-04-11T02:31:36.790
# Question Title: `doc-view-mode` for PDFs not working For some reason I cannot view PDF files in `doc-view-mode`. Supposedly if I open a PDF file in Emacs, it should automatically open in the `doc-view` major mode. If it can't be opened in `doc-view`, then there will at least be some error message. But for me, opening a PDF file opens it in fundamental mode. If I use `M-x doc-view-mode` then the mode-line shows `(fundamental docview)` which indicates that the `docview` *minor mode* is used, as I understand it. That minor mode claims I can use `C-c C-c` to view the document, but that does nothing, and leaves me in the "editor mode." I've checked the `*Messages*` buffer, and there are no error messages. Here is a screenshot: Here's what I'm working with: * Emacs 27.1 * macOS 11.2.3 (Big Sur) * auctex 13.0.4 * latex-preview-pane-20181008.1822 The only discussion I've managed to find about this is specifically for Windows, such as here. # Answer > 1 votes `M-x` `find-library` `RET` `doc-view` tells us: > Requirements: > > doc-view.el requires GNU Emacs 22.1 or newer. You also need Ghostscript, `dvipdf` (comes with Ghostscript) or `dvipdfm` (comes with teTeX or TeXLive) and `pdftotext`, which comes with xpdf (http://www.foolabs.com/xpdf/) or poppler (http://poppler.freedesktop.org/). So check that you have those dependencies installed. If they are installed, check that Emacs can see them -- `C-h``v` `exec-path` is the list of directories where Emacs will look for executables on the local machine. --- You may wish to take a look at https://github.com/vedang/pdf-tools as well. There are some notes about OSX in the readme, so it might work for you if you follow those instructions. If you *can* get it working, it's much, much nicer than `doc-view`. --- Tags: pdf, docview ---
thread-435
https://emacs.stackexchange.com/questions/435
How do I delete duplicate messages in mu4e?
2014-09-29T06:09:56.100
# Question Title: How do I delete duplicate messages in mu4e? mu4e has the ability to hide duplicates, with the "V" key, but I see no way to delete the messages. I've tried tricks with marking messages in and out of the hide state, but nothing seems to work well. Searching the documentation and googling has turned up nothing. # Answer As far as I know mu and by extension mu4e does not support this and I don't think it ever will because it does not match its design principles. Instead of providing tools to make it easier to *organize* your inboxes more easily it replaces *organizing* with *searching*. There is some support for explicitly organizing mail and by *saving searches* you are effectively doing something similar. But the idea is that we receive so much mail that it has become inefficient to manually organize and vet our inboxes. Its not considered an issue that there might be duplicates, boring mail isn't deleted etc. Mu/mu4e is supposed to let us forget about these issues by providing good search. There are duplicates in your sea of messages but that isn't considered an issue. Only that duplicates might be *displayed* is considered an issue. And for that there is `(setq mu4e-headers-skip-duplicates t)`. > 3 votes # Answer I needed this too, after having accidentally deleted my `~/Maildir/<provider>/INBOX/.mbsyncstate`. That file seems to be a key piece for `mbsync`: because it was missing, `mbsync` started redownloading all the messages from the IMAP server, even though they were all still proper files in the `INBOX/cur` and `INBOX/new` folders... One solution proposed by the author of mu/mu4e is to do ``` mu find-dups ``` and some shell tweaking or the `--delete` option, but that didn't work for me (installation of `mu-guile` failed). I ended up writing a program in that would list all duplicate messages in a maildir folder (thousands for me), and **remove one of the duplicates using some custom rules**. Below are the main steps. The most important thing to know is that you only need to remove a message file from the file system so that `mu` detects it as a deleted message, and so that this deletion gets propagated to the IMAP server. Deleting a message from within `mu4e` does exactly that: it deletes the message file and nothing else. There is no need to touch `.mbsyncstate`, this file is automatically updated by `mbsync` subsequently. 1. Best is to work offline and to **backup your maildir directory** first, e.g. using `cp -pR` (put the backup somewhere where `mu` will not index it, i.e., most likely not in `~/Maildir`) 2. Scan all the message files in your maildir, and determine their `Message-ID` (this field is what is used to detect duplicates in `mu4e`). For this, I used a regular expression: ``` // #!/usr/bin/env rdmd import std.stdio; import std.file; import std.path; import std.algorithm; import std.array; import std.regex; import std.conv; string[string] msgid_db; // key = msgid, value = filename string[] duplicates; /** extract Message-ID from msg_file (message file in maildir format) */ string get_msgid(string msg_file) { assert(absolutePath(msg_file).isFile); string msg_text = to!string(read(msg_file)); auto c = matchFirst(msg_text, regex(`^Message-ID: <(?P<msgid>[^>]+>)`, "im")); // Some tags are 'Message-Id' => flag 'i'. Don't add $ to match end of line, some lines have an extra "(added by postmaster@smtp.xxx.com)" etc. Rarely, some don't have Message-ID and mu4e adds a fake-msgid. if(c.empty) { stderr.writeln("Warning: message ", msg_file, " has no Message-ID"); return ""; } else return c["msgid"]; } /** Scan dirname for message files, getting their message-ID, populating `msgid_db`, and filling `duplicates` */ void detect_duplicates(string dirname) { // scan the directory for msg files (filter out some non-msg files) foreach(msg; dirEntries(dirname, SpanMode.depth).filter!(msg => msg.isFile).filter!(msg => !canFind([".DS_Store", ".uidvalidity", ".mbsyncstate", ".mbsyncstate.journal", ".mbsyncstate.lock", ".mbsyncstate.new"],baseName(msg.name) ))) { // stderr.writeln(msg); string msgid = get_msgid(msg); if (msgid != "" && msgid !in msgid_db) msgid_db[msgid] = msg; else if (msgid != "") { duplicates ~= msgid_db[msgid]; duplicates ~= msg; } } assert(duplicates.length % 2 == 0); } ``` After running `detect_duplicates` above on a folder name (e.g. `~/Maildir/<provider>/INBOX`), the array `duplicates` contains an even number of message file names. Note that both message file names are returned sequentially when duplicates are found! When more than one copy is found, a pair of file names is returned for each copy detected. I.e. if the messages `'A'`, `'B'`, and `'C'` are duplicates, and `'A'` came first, `duplicates` will contain the sequence `[...,'A','B',...,'A','C',...]`. 3. The only remaining step is to do something with the detected duplicate messages. Anything is possible, but I chose to remove the duplicated message in a pair whose timestamp recorded in the filename would be older or (if timestamp is identical) whose UID is greater, which simply amounts to removing `'B'` if the names are such that `'A' < 'B'`, and removing `'A'` otherwise: ``` void main(string[] args) { if(args.length != 2 || !args[1].isDir) { stderr.writeln("Usage: ./duplicates.d dirname"); return; } stderr.writeln("*** Detecting duplicate messages in '", args[1], "' ***"); detect_duplicates(args[1]); foreach(i; 0 .. duplicates.length/2) if(duplicates[2*i] < duplicates[2*i+1]) writeln("rm ", duplicates[2*i+1]); else writeln("rm ", duplicates[2*i]); stderr.writeln("(There were ", duplicates.length, " messages in the duplicate list, i.e., ", duplicates.length/2, " pairs)"); } ``` I piped the output written to stdout to a file `to_delete.sh`, checked it, then added a first line `#!/bin/bash` before executing it. 4. I then ran `mu4e` offline first to check duplicates didn't appear anymore (using 'Q' to show all, then 'V' to toggle showing duplicates), then ran it again online and `mbsync` did its job removing duplicates on the server. > 1 votes # Answer I came up with this pure `mu4e` solution. `M-x my-mu4e-header-mark-duplicated` will mark the first of each duplication message set (defined by identical `:message-id` and `:flags`) in `*mu4e-headers*` for further actions. Set `(setq mu4e-headers-skip-duplicates nil)` as this requires duplicated messages to be visible in the `*mu4e-headers*` buffer. ``` (defvar *my-mu4e-headers-bol-positions* nil) (defun my-mu4e-headers-bol-positions () "Obtain a list of beginning of line positions for *mu4e-headers*. `*my-mu4e-headers-bol-positions*' is defined globally, as trying to use let binding and using add-to-list was unsuccessful." ;; list-bol is nil, equivalent to an empty list. (with-current-buffer (mu4e-get-headers-buffer) (setq *my-mu4e-headers-bol-positions* nil) (save-excursion (goto-char (point-min)) (while (search-forward mu4e~headers-docid-pre nil t) (add-to-list '*my-mu4e-headers-bol-positions* (line-beginning-position)) ;; Need to move to the end of the line to look for the next line (end-of-line)) (reverse *my-mu4e-headers-bol-positions*)))) ;; (defun my-mu4e-headers-sexps-with-bol () "Obtain the message s-expressions for the messages in *mu4e-headers* and extend with bol." (let ((list-bol (my-mu4e-headers-bol-positions))) (when list-bol (with-current-buffer (mu4e-get-headers-buffer) (seq-map (lambda (bol) (let ((msg (get-text-property bol 'msg))) (plist-put msg :bol bol))) list-bol))))) ;; (defun my-mu4e-headers-sexps-with-bol-dups () "Obtain the sexps for the messages in *mu4e-headers* with duplicated message-id." ;; https://emacs.stackexchange.com/questions/31448/report-duplicates-in-a-list (thread-last (my-mu4e-headers-sexps-with-bol) ;; Group by :message-id and :flags (to avoid marking messaged handled differently). (seq-group-by (lambda (sexp) (list (plist-get sexp :message-id) (plist-get sexp :flags)))) (seq-filter (lambda (al) (> (length al) 2))))) ;; (defun my-mu4e-headers-bol-dups () "Obtain the beginning of line positions for duplicated messages in *mu4e-headers*. The beginning of line position for the first of each duplicated messages set is retained." (thread-last (my-mu4e-headers-sexps-with-bol-dups) ;; First of each duplicated messages set. (seq-map (lambda (al) (cadr al))) (seq-map (lambda (sexp) (plist-get sexp :bol))) (seq-sort #'<))) ;; (defun my-mu4e-header-mark-duplicated () "Mark the first of each duplicate messages set in *mu4e-headers* for an action." (interactive) (save-excursion (mapc (lambda (bol) (goto-char bol) (mu4e-headers-mark-for-something)) (my-mu4e-headers-bol-dups)))) ``` > 0 votes --- Tags: mu4e ---
thread-63716
https://emacs.stackexchange.com/questions/63716
Add CC and BCC when composing an email with mu4e
2021-03-03T21:17:31.030
# Question Title: Add CC and BCC when composing an email with mu4e If I compose an email with mu4e I can only enter a recipient in the `TO:` field. But there are no fields for `CC` (carbon copy) and `BCC` (blind carbon copy). How can I use those fields? # Answer > 6 votes Look in the Field Menu and select those fields. For me, the key shortcuts are `C-c C-f C-c` (`message-goto-cc`) for CC and `C-c C-f C-b` (`message-goto-bcc`) for BCC. These will add those fields. Alternatively, I think you can just type them in yourself in the header, e.g. after the To: line, press enter, type Cc: and a space then add the email address you want. # Answer > 1 votes You can automate like this (based on http://www.djcbsoftware.nl/code/mu/mu4e/Compose-hooks.html). ``` ;; Always BCC myself ;; http://www.djcbsoftware.nl/code/mu/mu4e/Compose-hooks.html (defun my-add-header () "Add CC: and Bcc: to myself header." (save-excursion (message-add-header (concat "CC: " "\n") ;; pre hook above changes user-mail-address. (concat "Bcc: " user-mail-address "\n")))) (add-hook 'mu4e-compose-mode-hook 'my-add-header) ``` --- Tags: mu4e, message-mode ---
thread-63304
https://emacs.stackexchange.com/questions/63304
How can i activate emacs-binding in doom emacs?
2021-02-10T03:33:03.300
# Question Title: How can i activate emacs-binding in doom emacs? I am using doom emacs. But I want traditional emacs key binding. I've heard several people that emacs key binding becomes way of life and if somebody takes my key binding away, I cant express myself. Please give me way to use emacs binding in doom. Also after adding emacs binding, please tell me how can i add it to home like showing all binding instead of evil ones. # Answer > 1 votes In doom.d/init.el disable loading of evil and do the usual "doom sync". This way the evil module is not loaded and keybindings are "back to normal". --- Tags: spacemacs, doom ---
thread-63857
https://emacs.stackexchange.com/questions/63857
emacs windows bullet face change
2021-03-11T19:33:31.363
# Question Title: emacs windows bullet face change I am running emacs on Windows. I am trying to change the bullet face of `org-bullet`. Now it looks like this: I did several search and changed my default font to several different types but the problem persists. Now I have changed my emacs font to: ``` (set-frame-font "Inconsolata Regular" nil t) ``` Basically, `"◉"` gets displayed to the one showing on my screenshot. Any suggestions on how to fix it? Ideally I just to want to display better bullet without change my gloabal font. # Answer There’s no way to change the font for just the bullets, but you can change the font for the whole heading without changing the default font. Put your cursor on the heading and type `C-u C-x =`. This runs `what-cursor-position`, which gives you all the details about the character under the cursor. Scroll down to the text properties until you find the “face” being used for this text. It will likely be `org-level-1`, unless you were on a heading at a different level. Click on the face name (or move your cursor to it and hit enter), and it will take you to a description of the face and its attributes. You can use the customize button in this view to edit the face; changing the “Family” attribute will allow you to select a different font. You can also change the height, weight, color, and so on if you like. It’s a little bit annoying that there are eight of these faces, and that they don’t inherit from a useful common face. If you want to use the same font for all of them, you’ll probably want to customize them all. > 1 votes # Answer The problem is the font's unicode support. I installed DejaVu Sans and was able to display all the unicode symbols. The unicode font pacakge is very helpful. > 0 votes --- Tags: org-mode, faces ---
thread-64388
https://emacs.stackexchange.com/questions/64388
How to use a delayed evaluation function where a string is expected?
2021-04-11T19:48:06.303
# Question Title: How to use a delayed evaluation function where a string is expected? I have a variable that expects a string, and I want to set it to a function that will return a string whenever the variable is used. Right now, I have ``` (setq bibtex-autokey-prefix-string (format-time-string "%Y_%m%d-")) ``` This is close to what I want, but it sets the prefix string once when my variable customizations are evaluated at startup. So the variable holds not the current date but the date when Emacs was started. When I try ``` (setq bibtex-autokey-prefix-string '(format-time-string "%Y_%m%d-")) ``` I get the error: ``` Wrong type argument: characterp, format-time-string ``` Is it possible to do what I'm trying to do? p.s. something else I tried resulted in a `stringp` wrong type argument error (I think?), but I can't reproduce that any more. # Answer > 2 votes > How to use a delayed evaluation function where a string is expected? Submit a feature request for `bibtex.el` via `M-x report-emacs-bug RET`. > Is it possible to do what I'm trying to do? In the meantime, you can use function advice to temporarily modify `bibtex-autokey-prefix-string` around the place where it's used, e.g.: ``` (define-advice bibtex-generate-autokey (:around (&rest args) my-date) "Bind `bibtex-autokey-prefix-string' to desired date format." (let ((bibtex-autokey-prefix-string (format-time-string "%Y_%m%d-"))) (apply args))) ``` Along the same lines, you could permanently update `bibtex-autokey-prefix-string` just before it's used each time: ``` (define-advice bibtex-generate-autokey (:before (&rest _) my-date) "Set `bibtex-autokey-prefix-string' to desired date format." (setq bibtex-autokey-prefix-string (format-time-string "%Y_%m%d-"))) ``` \[Disclaimer: these examples are guaranteed 100% untested.\] ### Edit Based on the examples above, the OP ended up using the following: ``` (defun my-bibtex-autokey-wrapper (orig-fun &rest args) "Dynamically bind `bibtex-autokey-prefix-string' to current date." (let ((bibtex-autokey-prefix-string (format-time-string "%Y_%m%d-"))) (apply orig-fun args))) (advice-add 'bibtex-generate-autokey :around #'my-bibtex-autokey-wrapper) ``` ### Note In the first and last example, `bibtex-autokey-prefix-string` needs to be declared as a special variable in order for the advice to always have the intended effect, regardless of `lexical-binding` and byte-compilation. If `bibtex.el` is already loaded, then happy days: the user option has already been declared. Otherwise, an explicit `defvar` is needed so that the `let`-binding doesn't create a local variable with lexical scope: ``` (def... "..." (defvar bibtex-autokey-prefix-string) (let ((bibtex-autokey-prefix-string ...)) ...)) ``` --- Tags: variables, bibtex ---
thread-64119
https://emacs.stackexchange.com/questions/64119
mapcar but return non-nil element only
2021-03-25T21:46:23.033
# Question Title: mapcar but return non-nil element only Is there a function that applies a transformation to a sequence and returns only the non-nil values? Right now I am using the following (as an example): ``` (seq-filter #'identity (mapcar (lambda (x) (when (< x 3) (+ x 5))) '(1 2 3 4 5 6))) ``` Or through `dolist` ``` (defun mapcar-true (func list) (let (value) (dolist (elt list value) (when-let ((trans (funcall func elt))) (setq value (append value (list trans))))))) ``` But I feel there must be a more straightforward way. # Answer Use `remq` or `delq` to remove `nil` elements from a list (to remove more complex structures, consider `remove` and `delete`, too). ``` (remq nil (mapcar (lambda (x) (when (< x 3) (+ x 5))) '(1 2 3 4 5 6))) ``` The first example can be also simplified using `flatten-tree` as it will remove empty lists, i.e. `nil`s. ``` (flatten-tree (mapcar (lambda (x) (when (< x 3) (+ x 5))) '(1 2 3 4 5 6))) ``` > 6 votes # Answer > Is there a function that applies a transformation to a sequence and returns only the non-nil values? Since Emacs 26, you can use `mapcan`: ``` (mapcan (lambda (n) (and (< n 3) (list (+ n 5)))) (number-sequence 1 6)) ``` Alternatively, there's the age-old `mapcar+delq` approach like in choroba's answer (`delq` is more commonly used than `remq`, since `mapcar` already returns a fresh list, so there's no need to copy it first). Which of the two approaches to use usually boils down to personal preference and/or performance profiling. Personally, I'd submit a feature request via `M-x report-emacs-bug` for such a function to be added to `seq.el`. > 1 votes --- Tags: mapping, filtering, sequences ---
thread-32058
https://emacs.stackexchange.com/questions/32058
Why does GNU Emacs use ksi(ξ) as its logo?
2017-04-10T13:51:13.587
# Question Title: Why does GNU Emacs use ksi(ξ) as its logo? Why does GNU Emacs use ksi(ξ) as its logo, while most Lisp dialects use lambda(λ) as their logos? not mean this one: # Answer > 11 votes It doesn't. It uses just an `E` that is suggestive of a gnu's horns. # Answer > 2 votes See also https://www.emacswiki.org/emacs/EmacsIcons It is the letters "E" and "M" stylized to look like the horns of a Gnu. Any resemblance to the Greek alphabet is coincidental. Emacs version 22 put this symbol over an icon of a notepad. Later versions put it in a circle, overlaid with a pen. --- Tags: help ---
thread-64395
https://emacs.stackexchange.com/questions/64395
How to override the :hook section of a use-package declaration
2021-04-12T15:59:25.373
# Question Title: How to override the :hook section of a use-package declaration I am attempting to change the `:hook` section of a `use-package` declaration that I cannot directly modify. In my case, I want to remove hooks that are getting set, not just add more hooks. Is there a way to do this similar to how the `:init` and `:config` sections can be modified via `use-package-inject-hooks`? Reference points: 1. The `use-package` library provides a `use-package-inject-hooks` variable that can be enabled in order to activate hooks for the `:init` and `:config` sections: ``` [use-package-inject-hooks] If non-nil, add hooks to the `:init' and `:config' sections. In particular, for a given package `foo', the following hooks become available: `use-package--foo--pre-init-hook' `use-package--foo--post-init-hook' `use-package--foo--pre-config-hook' `use-package--foo--post-config-hook' This way, you can add to these hooks before evaluation of a `use-package` declaration, and exercise some control over what happens. NOTE: These hooks are run even if the user does not specify an `:init' or `:config' block, and they will happen at the regular time when initialization and configuration would have been performed. NOTE: If the `pre-init' hook return a nil value, that block's user-supplied configuration is not evaluated, so be certain to return t if you only wish to add behavior to what the user had specified. ``` 2. The `:hook` section provides an alternate interface for special-case usage of the `:init` section (see documentation): > The `:hook` keyword allows adding functions onto package hooks. Thus, all of the following are equivalent: > > ``` > (use-package ace-jump-mode > :hook prog-mode) > > (use-package ace-jump-mode > :hook (prog-mode . ace-jump-mode)) > > (use-package ace-jump-mode > :commands ace-jump-mode > :init > (add-hook 'prog-mode-hook #'ace-jump-mode)) > > ``` Given the above two points, I thought that maybe hooking into the `:init` section using `use-package-inject-hooks` would allow me to override the `:hook` section, but that was not the case. Looking at the source code for `use-package`, I can see that `:hook` and `:init` are implemented differently (`:hook` is not a special wrapper for `:init`) so I can see why that would not work. Any advice would be much appreciated. (On that note... I suppose a clever use of the *advice* mechanism in Emacs could provide a workaround, which I hadn't considered until I wrote that last sentence. That said, I would like to avoid such a kludge if possible.) # Answer > 1 votes I think something has gone wrong if you can't modify the use-package form -- AFAIK that macro is intended for use by end-users only. That said, the documentation you've quoted: > all of the following are equivalent: > > ``` > (use-package ace-jump-mode > :hook prog-mode) > > (use-package ace-jump-mode > :hook (prog-mode . ace-jump-mode)) > > (use-package ace-jump-mode > :commands ace-jump-mode > :init > (add-hook 'prog-mode-hook #'ace-jump-mode)) > > ``` suggests to me that you can probably just do the following (subsequent to loading the above code): ``` (with-eval-after-load 'ace-jump-mode (remove-hook 'prog-mode-hook #'ace-jump-mode)) ``` --- Tags: hooks, use-package, doom ---
thread-64387
https://emacs.stackexchange.com/questions/64387
How to debug an Emacs that stops taking input and needs to be restarted every few hours, but doesn't throw any errors
2021-04-11T17:11:48.477
# Question Title: How to debug an Emacs that stops taking input and needs to be restarted every few hours, but doesn't throw any errors I've been having a problem lately where every few hours of use, for some reason I don't understand, Emacs stops responding to input without throwing an error. `C-g` and `Esc-Esc-Esc` do nothing, so I'm forced to kill Emacs and restart it. Presumably, this has something to do with a change I recently made to my `.emacs`, but I've made a lot of changes, and I don't see any good way to debug it. Recursively bisecting could entail spending weeks or months with a semi-functional editor, since the problem takes hours to show up and I don't know how to reliably reproduce it. Emacs isn't throwing an error, so debug on error doesn't help. Is there some way I can start Emacs such that I can manually debug it on the fly, or so that it will give me a log of what Emacs was doing and I can look at the end to see what was going on when it stopped responding? # Answer Sending the `SIGUSR2` signal to Emacs should cause it to enter the debugger, interrupting whatever it was doing. See the help for the variable `debug-on-event` for more information. Try running `pkill -USR2 emacs` in a shell. > 5 votes --- Tags: debugging ---
thread-64393
https://emacs.stackexchange.com/questions/64393
How to scroll to the beginning of the line in Emacs
2021-04-12T11:15:39.900
# Question Title: How to scroll to the beginning of the line in Emacs I have buffer and I end up at 1616 column (I have one very long line, bug string). Is there a way to scroll the beginning of the line with a single commands. Is there a way to reset the buffer without killing it and opening again? **EDIT:** If fixed itself when I opened help screen and then close it. But from time to time I end up with state like this. To reproduce the state, press CTRL+X \< when truncate-lines is set to nil. # Answer The window has been scrolled left (`scroll-left`) for some reason. `C-x <` or `C-<next>` can get you into this state. `C-x >` or `C-<prior>` can get you out of this state. Note those commands are blocked by default. When using them the first time, you will be asked, whether or not to enable them, in the minibuffer. Note: if you press two times `C-x <` then you need to press two times `C-x >` to get back to your initial view. > 6 votes # Answer Just adding to answer by @jue above. The `C-x <` ("scroll-left") command horizontally scrolls all text lines to the left, which means that the window's view "pans" to the right. The emacs doc section on Horizontal-Scrolling does a pretty good job of explaining. The way to get out of this pickle is as follows: 1. Get back to start-of-line view. One of these will work, depending on emacs version: `C-u 0 M-x toggle-truncate-lines` to make long lines fold and undo any horizontal left scrolling. Press `C-x >` (or `Ctrl-PageUp`) as many times needed to get back to the start-of-line. 2. Disable the `scroll-left` command in the current emacs process: Do: `M-x eval-expression RET` and enter the elisp expression: `(put 'scroll-left 'disabled t)` 3. Make sure that scroll-left isn't enabled by default. Check your .emacs init file and delete line that has: `(put 'scroll-left 'disabled nil)` Hope this helps. > 2 votes --- Tags: motion, scrolling ---
thread-64400
https://emacs.stackexchange.com/questions/64400
Can I use org-latex-export-to-pdf to convert headlines to nested bullets?
2021-04-13T20:20:04.760
# Question Title: Can I use org-latex-export-to-pdf to convert headlines to nested bullets? I've been using headline levels in org-mode as essentially bullets. When I convert to PDF, I get a numbered list. Is there a way I can export those as nested bullets instead? Thanks. # Answer Try this: ``` #+OPTIONS: H:0 num:nil toc:nil * foo ** bar *** baz * fu ``` but consider changing your habits: headlines are for sections with perhaps somewhat extensive text under the headline. If you want bullets, consider using a list (do `C-h i g (org) plain lists` for more information): ``` - foo - bar - baz - fu ``` > 1 votes --- Tags: org-mode, org-export ---
thread-64402
https://emacs.stackexchange.com/questions/64402
Can a defmacro generate a string with the name of the .el file where it is expanded?
2021-04-13T20:43:20.100
# Question Title: Can a defmacro generate a string with the name of the .el file where it is expanded? I'd like to create a Emacs Lisp macro that is able to generate a string literal that contains the name of the .el file into which the macro is expanded. Is this possible? **Background**: I am writing a Elisp macro that generate one or several defun forms. Some may be inside conditional forms (if or conditions or whatever) and the macro being expanded may also be inside a conditional block form. Assuming I have the following code inside a file called `my-file.el`: ``` (when some-condition (my-macro lisp arg1 arg2)) ``` I'd like to be able to write a defmacro form that would be able to determine that it is being expanded inside `my-file.el` and would be able to generate the string literal "my-file". Something like: ``` (when some-condition (defun my-lisp-function (some-arg arg1) (some-code-here arg1 whatever)) (declare-function my-lisp-function "my-file") ;; (some-other-code etc etc) ;; (my-lisp-function arg2)) ``` In the example above I'm using the file name string literal inside a declare-function form to prevent the byte-compiler from complaining about the generated my-lisp-function not being defined. And at the same time allow the check-declare package to verify the existence of the function. I tried to use the variable `byte-compile-current-file` from bytecomp.el by accessing it in the non-generated portion of the macro, but that did not work. # Answer > 3 votes > I'd like to create a Emacs Lisp macro that is able to generate a string literal that contains the name of the .el file into which the macro is expanded. Is this possible? If I understood correctly, Emacs 28 adds a function which does this: ``` (defun macroexp-file-name () "Return the name of the file from which the code comes. Returns nil when we do not know. A non-nil result is expected to be reliable when called from a macro in order to find the file in which the macro's call was found, and it should be reliable as well when used at the top-level of a file. Other uses risk returning non-nil value that point to the wrong file." ;; `eval-buffer' binds `current-load-list' but not `load-file-name', ;; so prefer using it over using `load-file-name'. (let ((file (car (last current-load-list)))) (or (if (stringp file) file) (bound-and-true-p byte-compile-current-file)))) ``` It follows that some key variables of interest are: * `current-load-list` * `load-file-name` * `byte-compile-current-file` * `buffer-file-name` Sample usage: ``` (defmacro my-foo () "Echo name of file where this macro is expanded or nil." `(message "%s" ,(macroexp-file-name))) ``` --- Tags: elisp-macros ---
thread-64407
https://emacs.stackexchange.com/questions/64407
How to distinguish input from the return value of body in while-no-input?
2021-04-14T03:45:29.077
# Question Title: How to distinguish input from the return value of body in while-no-input? > `(while-no-input &rest BODY)` > > Execute BODY only as long as there's no pending input. > > If input arrives, that ends the execution of BODY, and while-no-input returns t. Quitting makes it return nil. If BODY finishes, while-no-input returns whatever value BODY produced. If the BODY returns `t` then there is no way to distinguish it from the input interruption. One way could be to check if the return value is `t` in the BODY itself and then return certain value like `293851932832985`. Is there a cleaner way? # Answer > 4 votes The Elisp manual (do `C-h i g (elisp) RET i while-no-input RET` for more details - learning to use Info and the Info manuals is a good investment of your time) suggests the following: > If you want to be able to distinguish all possible values computed by BODY from both kinds of abort conditions, write the code like this: > > ``` > (while-no-input > (list > (progn . BODY))) > > ``` The rest of the description in the manual is also worth reading because there are a couple of wrinkles that are not covered by the doc string of `while-no-input`. --- Tags: iteration ---
thread-2884
https://emacs.stackexchange.com/questions/2884
The old "how to fold XML" question
2014-10-31T02:02:30.047
# Question Title: The old "how to fold XML" question I'm doing quite a bit of manual XML editing (the source definition of some code generation I'm doing is a custom XML format) and of course prefer to use Emacs over any special purpose (usually ugly) XML editors. nXml mode has stood me well in the past, but I cannot get my head around its "outline" support. Various internet and SO posts effectively say nothing - I'm wondering if anyone has any practical experience with outlining/folding XML in Emacs (any mode) whether or not that requires altering the XML structure itself. # Answer I found this SO post: https://stackoverflow.com/questions/944614/emacs-does-hideshow-work-with-xml-mode-sgml-mode ``` (require 'hideshow) (require 'sgml-mode) (require 'nxml-mode) (add-to-list 'hs-special-modes-alist '(nxml-mode "<!--\\|<[^/>]*[^/]>" "-->\\|</[^/>]*[^/]>" "<!--" sgml-skip-tag-forward nil)) (add-hook 'nxml-mode-hook 'hs-minor-mode) ;; optional key bindings, easier than hs defaults (define-key nxml-mode-map (kbd "C-c h") 'hs-toggle-hiding) ``` You can use the code from there, slightly modified, for nxml-mode easily. This will allow you to toggle hiding/unhiding of xml elements with `C-c``h` and will support underscores in the names. > 47 votes # Answer `web-mode` has element folding built in and bound to `C-c C-f`. But you will lose some of the features of using `nxml-mode` obviously. > 13 votes # Answer There is a quite wonderful gem called `noxml-fold-mode` that exactly helps with that. https://github.com/paddymcall/noxml-fold It can do folding and it also has visibility cycling. > 1 votes # Answer ``` (add-to-list 'hs-special-modes-alist '(nxml-mode "<!--\\|<[^/>][^>]*>" "-->\\|</[^/>]+>" "<!--" #'nxml-forward-element nil)) (add-hook 'nxml-mode-hook #'hs-minor-mode) ;; (setcdr (assoc 'nxml-mode hs-special-modes-alist) (list "<!--\\|<[^/>][^>]*>" "-->\\|</[^/>]+>" "<!--" #'nxml-forward-element nil)) ``` > -1 votes --- Tags: xml, nxml, outline ---
thread-64418
https://emacs.stackexchange.com/questions/64418
What is Emacs' "Hyper?" key?
2021-04-14T16:21:15.850
# Question Title: What is Emacs' "Hyper?" key? QMK defines Hyper as Ctrl+Shift+Alt+GUI. XFCE4 is treating my Left super as Hyper, which also happens to be the key that was configured as Hyper in `xmodmap` when the shortcut was defined. Emacs doesn't treat QMK's Hyper as equivalent to the Hyper that can be generated in Emacs. Is there a "hardware definition" for the Hyper that Emacs uses? # Answer > 1 votes Looks like it isn't defined. https://github.com/qmk/qmk\_firmware/issues/288 > Hyper is all on the OS's side - I don't think there's any way to map it natively, but you can stick in KC\_MENU or something similar to be redefined in xmodmap or the equivalent for your distro. > http://www.usb.org/developers/hidpage/Hut1\_12v2.pdf Page ~58. No reference to hyper in here. > > I've had a look through the file /usr/include/linux/input.h and it's include, and it doesn't look like there is any reference to hyper in there. > > XFree86 keycode: > > ``` > // Other codes never generated. The XFree86 ddx never generates > // these codes. > // Thus we can use them as fake keys > <HYPR> = 128; // <U80> > > ``` > > So I guess it's a fake key implemented at one of the keyboard layers after the fact. I think it's xfree86 (X.org) layer, but I'm not sure. https://old.reddit.com/r/emacs/comments/mfgjr8/different\_meanings\_for\_hyper/ > it's not part of the USB HID, so it's impossible to generate directly. Regardless, this can be closed. --- Tags: key-bindings, keystrokes, modifier-key ---
thread-64417
https://emacs.stackexchange.com/questions/64417
How to compare date strings?
2021-04-14T16:10:02.813
# Question Title: How to compare date strings? I have a LaTeX package declared with a date: ``` \usepackage{foo}[=2021-04-01] ``` and I need to check if this date is before or after "2021-03-01". Is there a way to compare dates, like `(if (< date1 date0) ... )`? **Raw solution** Thanks to @Drew's answer I have found this solution: ``` (defun myfunc () (interactive) (goto-char (point-min)) (when (re-search-forward "\\\\usepackage{foo}\\[=\\([0-9]+\\)-\\([0-9]+\\)-\\([0-9]+\\)\\]" nil t) (let* ((year (match-string 1)) (month-num (match-string 2)) (day (match-string 3)) (month) (t0) (t1)) (if (string-equal month-num "01") (setq month "jan") (if (string-equal month-num "02") (setq month "feb") (if (string-equal month-num "03") (setq month "mar") (if (string-equal month-num "04") (setq month "apr") (if (string-equal month-num "05") (setq month "may") (if (string-equal month-num "06") (setq month "jun") (if (string-equal month-num "07") (setq month "jul") (if (string-equal month-num "08") (setq month "aug") (if (string-equal month-num "09") (setq month "sep") (if (string-equal month-num "10") (setq month "oct") (if (string-equal month-num "11") (setq month "nov") (if (string-equal month-num "12") (setq month "dec"))))))))))))) (setq t0 (date-to-time "01 mar 2021 00.00.00")) (setq t1 (date-to-time (concat day " " month " " year " 00.00.00"))) (if (time-less-p t1 t0) (insert "foo") (if (time-less-p t0 t1) (insert "bar"))) ))) ``` I can't figure out how to manipulate `date-to-time` argument: how can I simply use "2021-01-01" as date format? I have read about `(format-time-string "%Y-%m-%d")`, but I don't understand how to use it. **Raw Solution Update** For the sake of completeness: ``` (cond ((string= month-num "01") (setq month "jan")) ((string= month-num "02") (setq month "feb")) ((string= month-num "03") (setq month "mar")) ((string= month-num "04") (setq month "apr")) ((string= month-num "05") (setq month "may")) ((string= month-num "06") (setq month "jun")) ((string= month-num "07") (setq month "jul")) ((string= month-num "08") (setq month "aug")) ((string= month-num "09") (setq month "sep")) ((string= month-num "10") (setq month "oct")) ((string= month-num "11") (setq month "nov")) ((string= month-num "12") (setq month "dec"))) ``` (I don't know about `pcase`.) **Final Solution** Putting together all your suggestions, I got the following solution: ``` (defun myfunc () (interactive) (goto-char (point-min)) (when (re-search-forward "\\\\usepackage{foo}\\[=\\([0-9]+\\)-\\([0-9]+\\)-\\([0-9]+\\)\\]" nil t) (let* ((release (concat (match-string 1) "-" (match-string 2) "-" (match-string 3) " 00:00:00")) (t0) (t1)) (setq t0 (date-to-time "2021-03-01 00:00:00")) (setq t1 (date-to-time release)) (if (time-less-p t1 t0) (insert "foo") (if (time-less-p t0 t1) (insert "bar"))) ))) ``` # Answer Convert the date strings to time values, then use `time-less-p` to compare the time values. `C-h f time-less-p`: > `time-less-p` is a built-in function in ‘C source code’. > > `(time-less-p T1 T2)` > > Return non-nil if time value `T1` is earlier than time value `T2`. > > A `nil` value for either argument stands for the current time. See `current-time-string` for the various forms of a time value. See also function `date-to-time`: > `date-to-time` is an autoloaded compiled Lisp function in `time-date.el`. > > `(date-to-time DATE)` > > Parse a string `DATE` that represents a date-time and return a time value. > > `DATE` should be in one of the forms recognized by `parse-time-string`. If `DATE` lacks timezone information, GMT is assumed. For example, this returns `t`, and with the args in the opposite order it returns `nil`. ``` (time-less-p (date-to-time "2021-04-15 13:00:00") (date-to-time "2021-04-16 12:00:00")) ``` See the Elisp manual, nodes Time Calculations and Time Parsing. > 5 votes --- Tags: time-date, parse-time, format-time-string ---
thread-64414
https://emacs.stackexchange.com/questions/64414
Can't use soap-client. Package cl is deprecated
2021-04-14T14:00:56.947
# Question Title: Can't use soap-client. Package cl is deprecated Emacs 26.3 CentOS 7.0 Install packages **soap-client 3.2.0** and **cl-lib 0.6** https://github.com/alex-hhh/emacs-soap-client https://elpa.gnu.org/packages/cl-lib.html In my `init.el` I add ``` (require 'soap-client) ``` But after restart Emacs I get error: ``` Warning (package): Unnecessary call to ‘package-initialize’ in init file Package cl is deprecated ``` # Answer > 5 votes 1. Something that is deprecated is not unsupported. So it's not true that you cannot use it. 2. A warning is not, at least in Emacs, an error. It's just a message to let you know something you might not otherwise be aware of. And many, *many* Emacs warnings are benign in actual use, for various reasons. You need to understand a warning, and do so in the context of what you're doing, in order to know whether you need to do something about it or not. # Answer > 1 votes You're using Emacs 26, and the cl-lib version you're referring to is for Emacs 24. Use the built-in package manager: `M-x list-packages`. * Emacs 26 will probably have cl-lib 1.0 already installed. * The soap-client you're referring to in github is old (ie. not v3.2.0). * If you have older versions installed, un-install them. --- Tags: warning, cl ---
thread-64421
https://emacs.stackexchange.com/questions/64421
HTTP Error 400 returned when accessing MELPA package archive
2021-04-14T17:43:52.927
# Question Title: HTTP Error 400 returned when accessing MELPA package archive I'm working on a VM running Centos 7 which ships with emacs 24.3. I wanted to install, use some newer packages requiring \> 25.1 so I downloaded the source for emacs 25.2 and built it. When I try to load packages from MELPA it fails. If I run `M-x eww https://melpa.org/packages/` I see the following: ``` 400 Bad Request The plain HTTP request was sent to HTTPS port. ``` My understanding was that Emacs 25.2 included TLS functionality. When I evaluate the below it prints `tls IS NOT available`. IS TLS support not included in Emacs 25.2? The Emacs GnuTLS manual states that it is an optional optional add-on. Did I miss something when I built it? Was I supposed to specify that I wanted the TLS library included? ``` (let (tlsAvailable (gnutls-available-p)) (if (eq tlsAvailable nil) (message "tls IS NOT available") (message "tls IS available"))) ``` # Answer This might be a start: Your let-binding is probably not what you want. It just binds two variables to `nil`: `tlsAvailable` and `gnutls-available-p`. I expect you really wanted this, which binds variable `tlsAvailable` to the result of calling nullary function `gnutls-available-p`. ``` (let ((tlsAvailable (gnutls-available-p))) ...) ``` > 0 votes # Answer I also had problems using the emacs 25 package manager (on CentOS 7), which went away when I built the latest. Try building 27.2. > 0 votes --- Tags: package-repositories, let-binding ---
thread-64429
https://emacs.stackexchange.com/questions/64429
What type of variable binding is setq creating?
2021-04-15T08:09:26.910
# Question Title: What type of variable binding is setq creating? What type of variable binding or variable or symbol is `setq` creating, when the variable hasn't been declared prior `setq`? Given following source code: ``` ;; -*- lexical-binding: t; -*- (defun setq-x () (setq x 10)) (defvar y 20) (setq-x) (message " variable values: x: %i, y %i\n special-var status: x: %s, y: %s" x y (special-variable-p 'x) (special-variable-p 'y)) ``` The source code above outputs: ``` variable values: x: 10, y 20 special-var status: x: nil, y: t ``` I did not expect this output, and I could not find an explanation in the documentation\[1\]. Since `setq` is used so often in Elisp without prior declaration of a variable, I regard this question as somewhat important. \[1\] *mentioned documentation*: https://www.gnu.org/software/emacs/manual/html\_node/elisp/Setting-Variables.html#index-setq https://www.gnu.org/software/emacs/manual/html\_node/elisp/Variable-Scoping.html https://www.emacswiki.org/emacs/DynamicBindingVsLexicalBinding # Answer Quoth the docstring of `special-variable-p`: ``` special-variable-p is a built-in function in `src/eval.c'. (special-variable-p SYMBOL) Probably introduced at or before Emacs version 24.1. Return non-nil if SYMBOL's global binding has been declared special. A special variable is one that will be bound dynamically, even in a context where binding is lexical by default. ``` Note the subtlety in the last sentence, about how a special variable would be treated in a lexical context (such as your `lexical-binding` buffer). Quoth the manual entry for `special-variable-p`: ``` -- Function: special-variable-p symbol This function returns non-‘nil’ if SYMBOL is a special variable (i.e., it has a ‘defvar’, ‘defcustom’, or ‘defconst’ variable definition). Otherwise, the return value is ‘nil’. Note that since this is a function, it can only return non-‘nil’ for variables which are permanently special, but not for those that are only special in the current lexical scope. ``` This tells us that only variables which have been declared as special count as special. So, while `setq` will change the global value of `x` so long as it is a free variable, `special-variable-p` will return non-`nil` only after `x` is declared special. Modifying your example a bit may help to highlight why this distinction is important: ``` ;; -*- lexical-binding: t -*- (defun setq-x () (setq x 10)) (defvar y 20) (setq-x) (let ((x 20)) (setq-x) (message "values x: %s, y: %s\nspecial x: %s, y: %s" x y (special-variable-p 'x) (special-variable-p 'y))) ``` When byte-compiled, this gives: ``` values x: 20, y: 20 special x: nil, y: t ``` If the first `setq-x` made `x` special, then `x` would have to be 10 after the second call to `setq-x`. Instead, `x` is `let`-bound like a local lexical variable that's in a different scope to that of `setq-x`. --- The conclusion is that it's fine for users to set undeclared variables (usually user options defined in packages that are yet to be loaded). But Elisp libraries ought to declare their variables or those from other libraries appropriately. --- > What type of variable binding or variable or symbol is `setq` creating, when the variable hasn't been declared prior `setq`? `setq` considers variables without a local lexical value as effectively being dynamic. So in your example, `(setq x 10)` is the same as `(set 'x 10)` (which wouldn't be the case if `x` were a lexical variable). You can see this towards the end of the definition of `setq`: ``` DEFUN ("setq", Fsetq, Ssetq, 0, UNEVALLED, 0, doc: /* Set each SYM to the value of its VAL. The symbols SYM are variables; they are literal (not evaluated). The values VAL are expressions; they are evaluated. Thus, (setq x (1+ y)) sets `x' to the value of `(1+ y)'. The second VAL is not computed until after the first SYM is set, and so on; each VAL can use the new value of variables set earlier in the `setq'. The return value of the `setq' form is the value of the last VAL. usage: (setq [SYM VAL]...) */) (Lisp_Object args) { Lisp_Object val = args, tail = args; for (EMACS_INT nargs = 0; CONSP (tail); nargs += 2) { Lisp_Object sym = XCAR (tail); tail = XCDR (tail); if (!CONSP (tail)) xsignal2 (Qwrong_number_of_arguments, Qsetq, make_fixnum (nargs + 1)); Lisp_Object arg = XCAR (tail); tail = XCDR (tail); val = eval_sub (arg); /* Like for eval_sub, we do not check declared_special here since it's been done when let-binding. */ Lisp_Object lex_binding = ((!NILP (Vinternal_interpreter_environment) /* Mere optimization! */ && SYMBOLP (sym)) ? Fassq (sym, Vinternal_interpreter_environment) : Qnil); if (!NILP (lex_binding)) XSETCDR (lex_binding, val); /* SYM is lexically bound. */ else Fset (sym, val); /* SYM is dynamically bound. */ } return val; } ``` > 6 votes --- Tags: variables, lexical-binding, setq ---
thread-64432
https://emacs.stackexchange.com/questions/64432
Org-mode unexpected LaTeX conversion: package and spacing issues
2021-04-15T10:35:28.423
# Question Title: Org-mode unexpected LaTeX conversion: package and spacing issues I am writing a paper in Org-mode and I will need a PDF output through LaTeX. Though, I had issues with spacing (had too large gaps), so I checked the .tex file generated by Org-mode. Apparently, it added `\\` at the end of every line, which made the gaps huge (probably making it think a new paragraph is created). Plus, it loaded a number of the packages I employed twice. I am sharing both the .org and the .tex files here (a simplified version of the original document). .tex file that I manually fixed .org file produced .pdf .tex file generated by Org-mode # Answer > 1 votes I couldn't export your org file since I had a lot of LaTeX errors, but I think your questions can be answered without your (not so minimal :-)) working example. > Apparently, it added \ at the end of every line, which made the gaps huge (probably making it think a new paragraph is created). That's just because you explicitly requested this behaviour with `#+OPTIONS: \n:t`. Set it to `nil` to avoid that. > Plus, it loaded a number of the packages I employed twice The packages added by default by the org exporter can be customized thanks to the variable `org-latex-default-packages-alist`. It is not recommended to remove them, however (instead, it's probably better not to call them manually in your header, unless you want to specify some options, or you have some package conflicts). --- Tags: org-mode, org-export, latex ---
thread-64430
https://emacs.stackexchange.com/questions/64430
Org Mode export bullets instead of numbers
2021-04-15T08:58:23.680
# Question Title: Org Mode export bullets instead of numbers When exporting an Org-mode buffer to Text or ODT, I'm getting the following: ``` 1. Lorem 1.1. Ipsum 1.1.1. Dolor 1.1.2. Sit ``` I'd like to change it to a bulleted list rather than numbered (closer to Org Mode view itself): ``` * Lorem + Ipsum - Dolor - Sit ``` (the specific bullets chosen are just an example). How can I do that? # Answer For the text/ascii exporter, I would say: 1. Add `#+OPTIONS: num:0 H:0` in your org document 2. Customize the variable `org-ascii-bullets` to choose the character used for each level, for instance: ``` (setq org-ascii-bullets '((ascii ?* ?+ ?-) (latin1 ?* ?+ ?-) (utf-8 ?* ?+ ?-))) ``` The following org document: ``` #+OPTIONS: num:0 H:0 author:nil toc:nil * Toto ** Tata *** Titi ``` will be exported in text/utf-8 as: ``` * Toto + Tata x Titi ``` The export to odt format should (I suppose) work in a similar fashion. > 2 votes --- Tags: org-mode, org-export, spacemacs ---
thread-27698
https://emacs.stackexchange.com/questions/27698
How can I scroll a half page on C-v and M-v?
2016-10-10T16:56:15.250
# Question Title: How can I scroll a half page on C-v and M-v? I use Spacemacs, and for some time I've rebound `C-v` and `M-v` to `spacemacs/scroll-half-page-down` and `spacemacs/scroll-half-page-up`, respectively, to aid my understanding of the buffer as I move through it. After a recent update, though, these functions seem to no longer be defined. How can I get them back, or something reasonably similar? # Answer I actually managed to find the equivalent functions. They are * `View-scroll-half-page-forward` * `View-scroll-half-page-backward` So, I've updated my dotfile's user-config section to contain ``` (global-set-key (kbd "C-v") 'View-scroll-half-page-forward) (global-set-key (kbd "M-v") 'View-scroll-half-page-backward) ``` and this seems to work fine! > 9 votes # Answer I personally recommend you to use a package named `golden-ratio-scroll-screen`. You can add melpa to your package-list if you have not. > (add-to-list 'package-archives '("melpa" . "https://melpa.org/packages/")) and then `M-x package-list-packages`, search for `golden-ratio-`, or go to https://github.com/jixiuf/golden-ratio-scroll-screen to get it. It will do the following two things, which are to me excellent, maybe also what you want: 1. Scroll half screen down or up, and 2. highlight current line before or after scrolling. > 3 votes # Answer You can also write pretty simple elisp code to achieve this :- ``` (defun scroll-half-page-down () "scroll down half the page" (interactive) (scroll-down (/ (window-body-height) 2))) (defun scroll-half-page-up () "scroll up half the page" (interactive) (scroll-up (/ (window-body-height) 2))) ``` > 2 votes # Answer I use ``` (defun advice/scroll-context (proc &rest r) (let ((next-screen-context-lines (/ (window-text-height) 2))) (apply proc r))) (mapc (lambda (sym) (advice-add sym :around #'advice/scroll-context)) '(scroll-up scroll-down image-scroll-up image-scroll-down)) ``` in my emacs.el profile to achive this. > 0 votes --- Tags: spacemacs, scrolling ---
thread-64410
https://emacs.stackexchange.com/questions/64410
Ignore all buffer's local variables
2021-04-14T09:30:17.917
# Question Title: Ignore all buffer's local variables Is there any way to open an emacs file so that all local variables definitions are ignored? I often use local variables into `tex` documents to fix root documents, dictionaries, etc. Sometimes I need to compile some document ignoring these variables. For example, in a TeX document, I have ``` %% Local Variables: %% TeX-master: t %% End: ``` Sometimes I'd like to ignore that because, for example, I don't want to treat the file as a master file. # Answer > 3 votes The doc string of `enable-local-variables` says: > A value of nil means always ignore the file local variables. You can customize the value of this variable to *Ignore*, open your file and revert the customization. Then there is also the variable `local-enable-local-variables` which you can use itself as file variable. If you set this variable to `nil` all other file variables are ignored with the exception of a mode specification in a leading `-*- ... -*-` comment at the beginning of the file. --- Tags: file-local-variables ---
thread-50117
https://emacs.stackexchange.com/questions/50117
How to disable commented date in org mode html export
2019-04-24T04:54:05.363
# Question Title: How to disable commented date in org mode html export When you export an org file to html, a date will appear in the html source though commented. Example, line 5 of https://i.stack.imgur.com/Bqhn1.jpg . # Answer You need to set the appropriate export option, which is `timestamp`. It's described at Export Settings, but I always find that section ridiculously confusing, so here are some examples: Either globally using a variable: ``` (setq org-export-with-timestamps nil) ``` or globally using a keyword: ``` #+options: timestamp:nil * headline one two three ``` or on an individual headline: ``` * headline #+options: timestamp:nil one two three ``` > 3 votes # Answer To disable that globally, you can use `(setq org-export-time-stamp-file nil)`. > 6 votes --- Tags: org-export, html ---
thread-64437
https://emacs.stackexchange.com/questions/64437
setq require-final-newline not working when setq-default does
2021-04-15T14:59:07.690
# Question Title: setq require-final-newline not working when setq-default does I want all my files to end with only one newline, while trimming trailing whitespaces on regular lines. Like so : ($ is newline face) ``` text$ $ last_line$ ``` I use `whitespace-cleanup` in my init file, like so : ``` (add-hook 'before-save-hook 'whitespace-cleanup) ``` With whitespace-style : ``` (face tabs spaces trailing lines space-before-tab newline indentation empty space-after-tab space-mark tab-mark newline-mark) ``` To keep newlines I add : ``` (setq require-final-newline t) ``` Then `eval-buffer` my init file. But Emacs does not take my setting unless I use `setq-default`. There is no mention in `require-final-newline` documentation that it is buffer local. # Answer > 5 votes You need to either set the default value of the variable, if you want it for every file: ``` (setq-default require-final-newline t) ;; or ... (customize-set-variable 'require-final-newline t) ``` or to set it in the mode hook, if you only want it for files of that mode: ``` (add-hook 'some-mode-hook (lambda () (setq-local require-final-newline t))) ``` --- The reason that a bare `(setq require-final-newline t)` does not work is that `require-final-newline` is buffer-local in certain cases. A number of modes (most prominently `prog-mode` and `text-mode`) do this: ``` (setq-local require-final-newline mode-require-final-newline) ``` That also affects their derived modes (e.g. `emacs-lisp-mode` in the first case and `org-mode` in the second). So in those modes, `require-final-newline` is indeed buffer-local. I don't know exactly how the loading and evaluation of the init file happens, but if it happens in such a buffer (e.g. in an `emacs-lisp-mode` buffer), `require-final-newline` is indeed a buffer-local, so the `setq` does not change the global default and your (future) buffer does not see the changed value. I suspect (but I don't know for sure) that this is the underlying cause of the failure of the bare `setq` in your init file and why you need `setq-default`. EDIT: In answer to your question in the comment, I don't think there is a way to ask whether the variable is buffer-local in any buffer that exists in the current session, except by checking *every* buffer. The problem is that *any* variable can be made buffer-local in a particular buffer, and nobody would know about that except that particular buffer: if you try to`setq` from that buffer, you would only change the local value. So if you ask about the variable anywhere except in that buffer, it would say "not local". There are two functions `local-variable-p` and `local-variable-is-set-p` that do this kind of asking and they both say `nil` for a buffer in e.g. `fundamental-mode` for the variable `require-final-newline`. You can check for local-ness in other buffers so you could write something like this to check *every* buffer: ``` (defun is-local (sym) (catch 'found (dolist (buf (buffer-list)) (when (local-variable-p sym buf) (throw 'found t))) nil)) ``` If you evaluate `(is-local 'require-final-newline)` in *any* buffer, it says `t`, because it *is* local in the `*scratch*` buffer e.g. But even this is not completely reliable: if during initialization a buffer is created and makes `require-final-newline` buffer-local but then gets deleted, the loop above will not find it afterwards. If there is no other buffer with a buffer-local `require-final-newline`, the function says `nil`. You can check that by setting `initial-major-mode` to `fundamental`, in a small init file that also contains the function above and the `setq` of `require-final-newline`, and invoking emacs with `emacs -Q -l /path/to/minimal.init.el`. The `*scratch* buffer is now in fundamental mode and no other existing buffer (minibuffer, the` *Messages* buffer etc) makes the variable buffer-local, so the function happily says `nil` \- but the `setq` still does not work. To me, that indicates that the scenario I've been describing here is correct (but I can easily imagine being Horatio to someone's Hamlet :-) ). --- Tags: init-file, whitespace, newlines ---
thread-64441
https://emacs.stackexchange.com/questions/64441
How to pass the buffer being save to after save hook?
2021-04-16T02:01:18.397
# Question Title: How to pass the buffer being save to after save hook? This question How to run an \`after-save-hook\` only when the buffer has been saved manually provides a way to have after-save hook run after pressing Ctrl-x Ctrl-s, in the answer Here's an alternative solution. However the hook cannot take a argument. I understand a -function is needed and `add-function` is to be used instead. The argument I wish to pass to the function is the file path of the buffer being saved as I wish to rsync it to a remote compile server. # Answer You don’t need to pass any arguments to anything. The new hook that you have created, `after-save-interactively-hook`, is called just after saving the current buffer. Any hook functions you add to that list can simply call `buffer-file-name` to get the name of the file visited by the current buffer. For more information, use `C-h f buffer-file-name` to view the documentation of this function. > 1 votes --- Tags: hooks ---
thread-64443
https://emacs.stackexchange.com/questions/64443
How to memorise the cursor position and return to it?
2021-04-16T03:25:07.590
# Question Title: How to memorise the cursor position and return to it? Say I was working in a big file somewhere in the middle and all of the sudden I realise that I need to edit the top of the file. I do a `M-<` to go to the top and make my edits. Now I want to move back to the exact point where I was working before. Is it possible to call a function before moving to the top, memorising the current point then going somewhere and calling the same function again but this time the cursor is moved to the point which was previously memorised and the memory is erased; ready to memorise a new point. **Edit:** Here is what I ended up with, ``` (defconst POINT-REGISTER 0 "Register to save the current point in.") (defcustom saved-point nil "Whether a point is saved in `POINT-REGISTER`." :type 'boolean) (defun save-or-goto-saved-point () "Interactively memorise a point and return to it." (interactive) (if saved-point (progn (register-to-point POINT-REGISTER) (setq saved-point nil)) (progn (point-to-register POINT-REGISTER) (message "[<Your Name>] Point saved!") (setq saved-point t)))) ``` # Answer > 1 votes C-x r SPC (M-x point-to-register) to register the position and C-x r j (M-x register-to-point) to return to it. This last operation does not erase the contents of the register, but if you use this register for a new point, its contents will be overwritten. ## Improved for more comfort Notice that this function uses the register 0. I do not know wether this register is used or not, if so, you can change it to any unused register. ``` (defun my-point-excursion-toggle () "Saves the position of the point or return to the previous saved position. " (interactive) (cond ((get-register 0) (jump-to-register 0) (set-register 0 nil)) (t(point-to-register 0) (message "Save point %d"(point))) )) ``` You can bind this function to any key sequence for instance: ``` (global-set-key (kbd "C-c t") #'my-point-excursion-toggle) ``` # Answer > 2 votes Yes, `C-SPC` calls `set-mark-command`, which pushes the current location of point onto a stack. If called with a prefix argument (`C-u C-SPC`) it pops the stack and returns point to the popped location. A number of other commands also push point onto the stack. For example, a search with `C-s` pushes point onto the stack so that you can return to where you started the search easily. # Answer > 0 votes You talk about *calling a function*. Do you want to do what you describe in Elisp or interactively? @db48x essentially interprets your question as asking how to get back to a previous position interactively, and that answer is fine for that. For Elisp, however, there's typically no reason to set the mark and then use it to get back to it - and that's generally avoided. Instead, just bind a local variable to the original position, then `goto-char` to that position later. Or use `copy-marker` for the original position, and then return to that marker position later. Please clarify your question, to say whether you want to go to a previous position by program or interactively. --- Tags: motion, cursor, point ---
thread-64384
https://emacs.stackexchange.com/questions/64384
"Read error Is a directory /home/ngaroe/.emacs-mail-crash-box"
2021-04-11T14:02:04.413
# Question Title: "Read error Is a directory /home/ngaroe/.emacs-mail-crash-box" The version of emacs I'm using is 27.1-r4 (Gentoo description). My .gnus file is ``` (setq gnus-select-method '(nnmaildir ".maildir" (directory "~/.nnmaildir")) mail-sources '((maildir :path "~/.nnmaildir/" :subdirs ("cur" "new"))) ;;; mail-source-delete-incoming t ) (setq gnus-secondary-select-methods nil) (setq gnus-message-archive-group "nnmaildir+.maildir:archive") (setq gnus-inhibit-user-auto-expire t) ``` The .maildir directory is `~/.nnmaildir/.maildir/` On running `emacs -f gnus` I get ``` Reading incoming mail from maildir... Processing mail from ~/.emacs-mail-crash-box... Mail source (maildir :path ~/.nnmaildir/ :subdirs (cur new)) failed: (file-error Read error Is a directory /home/ngaroe/.emacs-mail-crash-box) ``` and `.emacs-mail-crash-box` is ``` ngaroe@lenovo ~ $ l .emacs-mail-crash-box/ total 24 4 drwx------ 5 ngaroe ngaroe 4096 Dec 1 2019 ./ 4 drwx------ 55 ngaroe ngaroe 4096 Apr 11 14:34 ../ 4 drwx------ 2 ngaroe ngaroe 4096 Dec 1 2019 cur/ 4 -rw------- 1 ngaroe ngaroe 17 Dec 1 2019 .mu-prop 4 drwx------ 2 ngaroe ngaroe 4096 Dec 1 2019 new/ 4 drwx------ 2 ngaroe ngaroe 4096 Dec 1 2019 tmp/ ``` There was no `.emacs-mail-crash-box` before running emacs/gnus so it seems to have been an own goal... What on earth is going on? # Answer > 0 votes The answer is ... delete the directory .emacs-mail-crash-box (saving a copy just in case), create a new empty file .emacs-mail-crash-box and rerun `emacs -f gnus` ... --- Tags: gnus ---
thread-59424
https://emacs.stackexchange.com/questions/59424
org-set-effort fast effort selection?
2020-07-03T12:57:24.390
# Question Title: org-set-effort fast effort selection? I wonder if there is any easy way to configure effort selection dialogue to allow selecting effort value from the list using single key. Currently I have configured `Effort_ALL` in the following way: ``` (add-to-list 'org-global-properties '("Effort_ALL". "0:05 0:15 0:30 1:00 2:00")) ``` and am using `org-set-effort` to pop up the dialogue. However the dialogue that it shows is just a regular narrow-list-of-candidates dialogue which takes multiple keystrokes (either arrows or partial string followed by return) to select the option I need. What I would rather have instead is a `org-fast-tag-selection-single-key`-style dialogue that allows to select an entry from the list by just pressing a single button (e.g. `1`, `2`, `3`, etc). I've tried to look at the code for the `org-set-effort` and google for the ivy-like list-narrowing modules, but so far wasn't able to find much. # Answer > 3 votes I'm just getting into using effort properties myself and stumbled on your question. Here is a function modified from `org-fast-todo-selection` which maps the index of the effort value to that number key (e.q. 0 -\> 0:05 and 1 -\> 0:15 per your provided EFFORT\_ALL property). ``` (defun org-fast-effort-selection () "Modification of `org-fast-todo-selection' for use with org-set-effert. Select an effort value with single keys. Returns the new effort value, or nil if no state change should occur. Motivated by https://emacs.stackexchange.com/questions/59424/org-set-effort-fast-effort-selection" ;; Format effort values into an alist keyed by index (let* ((fulltable (seq-map-indexed (lambda (e i) (cons (car e) (string-to-char (int-to-string i)))) (org-property-get-allowed-values nil org-effort-property t))) (maxlen (apply 'max (mapcar (lambda (x) (if (stringp (car x)) (string-width (car x)) 0)) fulltable))) (expert (equal org-use-fast-todo-selection 'expert)) (prompt "") (fwidth (+ maxlen 3 1 3)) (ncol (/ (- (window-width) 4) fwidth)) tg cnt e c tbl subtable) (save-excursion (save-window-excursion (if expert (set-buffer (get-buffer-create " *Org effort")) (delete-other-windows) (set-window-buffer (split-window-vertically) (get-buffer-create " *Org effort*")) (org-switch-to-buffer-other-window " *Org effort*")) (erase-buffer) (setq tbl fulltable cnt 0) (while (setq e (pop tbl)) (setq tg (car e) c (cdr e)) (print (char-to-string c)) (when (and (= cnt 0)) (insert " ")) (setq prompt (concat prompt "[" (char-to-string c) "] " tg " ")) (insert "[" c "] " tg (make-string (- fwidth 4 (length tg)) ?\ )) (when (and (= (setq cnt (1+ cnt)) ncol) ;; Avoid lines with just a closing delimiter. (not (equal (car tbl) '(:endgroup)))) (insert "\n") (setq cnt 0))) (insert "\n") (goto-char (point-min)) (unless expert (org-fit-window-to-buffer)) (message (concat "[1-9..]:Set [SPC]:clear" (if expert (concat "\n" prompt) ""))) (setq c (let ((inhibit-quit t)) (read-char-exclusive))) (setq subtable (nreverse subtable)) (cond ((or (= c ?\C-g) (and (= c ?q) (not (rassoc c fulltable)))) (setq quit-flag t)) ((= c ?\ ) nil) ((setq e (or (rassoc c subtable) (rassoc c fulltable)) tg (car e)) tg) (t (setq quit-flag t))))))) ``` Using with `org-set-effort` and binding to a key: ``` (define-key org-mode-map (kbd "C-M-e") (lambda () (interactive) (org-set-effort nil (org-fast-set-effort)))) ``` # Update 07/27/2020 A possibly less intrusive solution is to add a case to `org-set-effort` where, if `org-use-fast-todo-selection` is set to `'expert`, use `org-fast-effort-selection` as defined above. The advantages are that you won't have to bind it to a specific key, and it will also work with `org-agenda-set-effort` out of the box. I made a commit in my fork of org-mode showing how this can be done. After I use it a bit to make sure there's no edge cases that are being missed, I may submit it to the org-mode maintainers. # Answer > 1 votes based on tuh8888's answer https://emacs.stackexchange.com/a/59475/33499 i have an enhanced version to contribute: I patched his solution using el-patch.el to: * number the choices from 1..0 (use 0 for the 10th choice) + using dash.el because of readability (feel free to change this) * only include the first 10 choices (`-zip-with` limits to shortest argument-list) * provide the current effort-value via `SPC` (or abort like `q` when current is `nil`) + current value is an optional argument, can be provided from the calling function ``` (el-patch-defun org-fast-effort-selection ((el-patch-add &optional current)) "Modification of `org-fast-todo-selection' for use with org-set-effert. Select an effort value with single keys. Returns the new effort value, or nil if no state change should occur. Motivated by https://emacs.stackexchange.com/questions/59424/org-set-effort-fast-effort-selection" ;; Format effort values into an alist keyed by index (let* ((fulltable (el-patch-swap (seq-map-indexed (lambda (e i) (cons (car e) (string-to-char (int-to-string i)))) (org-property-get-allowed-values nil org-effort-property t)) (-zip-with (lambda (e i) (cons (car e) (string-to-char (int-to-string i)))) (org-property-get-allowed-values nil org-effort-property t) '(1 2 3 4 5 6 7 8 9 0)))) (maxlen (apply 'max (mapcar (lambda (x) (if (stringp (car x)) (string-width (car x)) 0)) fulltable))) (expert (equal org-use-fast-todo-selection 'expert)) (prompt "") (fwidth (+ maxlen 3 1 3)) (ncol (/ (- (window-width) 4) fwidth)) tg cnt e c tbl subtable) (save-excursion (save-window-excursion (if expert (set-buffer (get-buffer-create " *Org effort")) (delete-other-windows) (set-window-buffer (split-window-vertically) (get-buffer-create " *Org effort*")) (org-switch-to-buffer-other-window " *Org effort*")) (erase-buffer) (setq tbl fulltable cnt 0) (while (setq e (pop tbl)) (setq tg (car e) c (cdr e)) (print (char-to-string c)) (when (and (= cnt 0)) (insert " ")) (setq prompt (concat prompt "[" (char-to-string c) "] " tg " ")) (insert "[" c "] " tg (make-string (- fwidth 4 (length tg)) ?\ )) (when (and (= (setq cnt (1+ cnt)) ncol) ;; Avoid lines with just a closing delimiter. (not (equal (car tbl) '(:endgroup)))) (insert "\n") (setq cnt 0))) (insert "\n") (goto-char (point-min)) (unless expert (org-fit-window-to-buffer)) (message (concat (el-patch-swap "[1-9..]:Set [SPC]:clear" (format "[1-9..]:Set [SPC]: %s" (or current "abort"))) (if expert (concat "\n" prompt) ""))) (setq c (let ((inhibit-quit t)) (read-char-exclusive))) (setq subtable (nreverse subtable)) (cond ((or (= c ?\C-g) (and (= c ?q) (not (rassoc c fulltable)))) (setq quit-flag t)) ((= c ?\ ) (el-patch-swap nil (or current ; gebe alten wert zurück wenn non-nil sonst quit (setq quit-flag t)))) ((setq e (or (rassoc c subtable) (rassoc c fulltable)) tg (car e)) tg) (t (setq quit-flag t))))))) (el-patch-defun org-set-effort (&optional increment value) "Set the effort property of the current entry. If INCREMENT is non-nil, set the property to the next allowed value. Otherwise, if optional argument VALUE is provided, use it. Eventually, prompt for the new value if none of the previous variables is set." (interactive "P") (let* ((allowed (org-property-get-allowed-values nil org-effort-property t)) (current (org-entry-get nil org-effort-property)) (value (cond (increment (unless allowed (user-error "Allowed effort values are not set")) (or (cl-caadr (member (list current) allowed)) (user-error "Unknown value %S among allowed values" current))) (value (if (stringp value) value (error "Invalid effort value: %S" value))) (el-patch-add ((eq org-use-fast-todo-selection 'expert) (org-fast-effort-selection current))) (t (let ((must-match (and allowed (not (get-text-property 0 'org-unrestricted (caar allowed)))))) (completing-read "Effort: " allowed nil must-match)))))) ;; Test whether the value can be interpreted as a duration before ;; inserting it in the buffer: (org-duration-to-minutes value) ;; Maybe update the effort value: (unless (equal current value) (org-entry-put nil org-effort-property value)) (org-refresh-property '((effort . identity) (effort-minutes . org-duration-to-minutes)) value) (when (equal (org-get-heading t t t t) (bound-and-true-p org-clock-current-task)) (setq org-clock-effort value) (org-clock-update-mode-line)) (message "%s is now %s" org-effort-property value))) ``` --- Tags: org-mode ---
thread-64451
https://emacs.stackexchange.com/questions/64451
Emacs doesn't show the keymap of a key binding
2021-04-16T14:48:46.713
# Question Title: Emacs doesn't show the keymap of a key binding I want to unbind the key binding `C-k`, which runs the command `org-up-element` in org mode. To do it, I first need to find out which keymap this key binding is bound to. So I run `describe-key` and press `C-k`, here is the result: ``` C-k runs the command org-up-element, which is an interactive compiled Lisp function in ‘org.el’. It is bound to <motion-state> g h, C-c C-^. (org-up-element) Move to upper element. ``` It doesn't tell me which keymap `C-k` is bound to, but usually it should tell me. So my question is, why doesn't it tell me, and how can I know the keymap that `C-k` is bound to? # Answer > 2 votes `C-h b` lists all the keybindings currently in effect, and groups them by mode. Similarly, `C-h m` displays a short description of the current major mode, and all active minor modes. This includes the keys bound to the maps for each mode. It doesn't include keys bound in the global keymap, so if you don't find your key here, that might be why. The output from both of these commands is quite long, but you should be able to to search for the text `"C-k"` then back up to the previous heading to see what mode it is set in. Re: your actual situation: `C-k` is bound to `kill-line` by default in the global map. Unless you're using some kind of starter-kit configuration, you have almost certainly rebound this in your config somewhere if it is calling `org-up-element`. --- Tags: key-bindings, keymap ---
thread-64454
https://emacs.stackexchange.com/questions/64454
Inconsistency in emacs' rules of scope?
2021-04-16T16:06:57.913
# Question Title: Inconsistency in emacs' rules of scope? I have always felt that emacs' rules of scope are a bit strange and prone to contradictions. In fact I have even attempted to file bug reports just to be told that my interpretation of the rules of scope was wrong, which I always reluctantly accepted. This time I think I nailed a contradiction caused by such rules. In the emacs manual page for `setq` (https://www.gnu.org/software/emacs/manual/html\_node/eintr/Using-setq.html), it is stated that `setq` is **exactly** the same as using `set` followed by a quote, but the following two examples show that it isn't: ``` (progn (setq a "one") ;; Global variable (let ((a "two")) ;; Local variable (set 'a "three") ;; Using "set + quote" affected the GLOBAL variable "a" a)) ;; Return local variable a => "two" ;; The local variable "a" remained with its let-value "two" and was not affected by "set + quote" ``` Here is the second example: ``` (progn (setq a "one") ;; Global variable (let ((a "two")) ;; Local variable (setq a "three") ;; Using "setq" affected the LOCAL variable "a" a)) ;; Return local variable a => "three" ;; The local variable "a" was changed by setq ``` My question is thus: Am I once more misinterpreting the rules of scope or have I really found an inconsistency in these rules? Perhaps I should add that the above code was run with lexical binding enabled. Otherwise I believe there is no inconsistency --- My emacs version is: GNU Emacs 27.2 (build 1, x86\_64-pc-linux-gnu, GTK+ Version 3.24.20, cairo version 1.16.0) of 2021-03-26 # Answer > 4 votes Lexical scope (recently added to emacs) changes the rules, and some documentation is still out of date. The current documentation for setq is this manual page which says > When dynamic variable binding is in effect (the default), set has the same effect as setq, apart from the fact that set evaluates its symbol argument whereas setq does not. But when a variable is lexically bound, set affects its dynamic value, whereas setq affects its current (lexical) value. It looks like the page you are viewing was written for an earlier version of emacs and hasn't been updated; you might want to file a documentation bug. --- Tags: lexical-scoping, setq, dynamic-scoping ---
thread-64258
https://emacs.stackexchange.com/questions/64258
How reliable is it to OR multiple user defined regular expressions?
2021-04-02T03:54:50.097
# Question Title: How reliable is it to OR multiple user defined regular expressions? Given multiple regular expressions, how reliable is it to group these into a single regex, without knowing their contents ahead of time. e.g. ``` (re-search-forward (concat "\\(" "\\(" user-regex-1 "\\)" "\\|" "\\(" user-regex-2 "\\)" "\\|" "\\(" user-regex-3 "\\)" "\\)"), nil t 1) ``` Can this reliable enough to be used as an alternative to doing multiple searches? Or are there common regular expression features that won't work when grouped in this way. Said differently, if I write a package that uses this as a way to avoid many searches, will users fine some of their regular expressions fail because they are grouped with other expressions. From a simple test, this should work, including nested grouping. `(string-match "\\(\\(A\\)\\|\\(B\\|C\\)\\)" "C") ;; --> 0 (#o0, #x0, ?\C-@)` --- *Edit* to account for invalid regex causing unexpected behavior, each regex can first be tested before use, see How to check a regular expression is valid without using it for a search? # Answer > 2 votes For the most part, the syntax of regular expressions is defined compositionally: `\(?:*REGEXP1*\)\|\(?:*REGEXP2*\)` matches exactly what either `*REGEXP1*` or `*REGEXP2*` by definition of the `\|` operator. However, there is one exception: backreferences. Each use of parentheses declares a numbered group, and a backreference `\*DIGIT*` matches the group with the given (single-digit) number. Although numbered groups are primarily useful to know what some part of the regexp matched, the ability to use backreferences in regexps means that they influence what is matched. The use of groups on the left-hand side changes the meaning of backreferences on the right-hand side. For example, `\(.*\)\1` matches a fragment that is repeated, such as `aa` or `aaaa` or `foofoo`. But `\(a\)\|\(.*\)\1` does not, because `\1` now refers to the first group `\(a\)`, so it matches `fooa` and does not match `foofoo`. If you document that regexps may not include backreferences, then you can combine them with `\|` without changing their meaning. --- Tags: regular-expressions ---
thread-64461
https://emacs.stackexchange.com/questions/64461
Auctex change default comment style for latex-mode
2021-04-17T09:04:50.580
# Question Title: Auctex change default comment style for latex-mode I want a double `%%` to start my comments in latex documents. I'have found two solutions suggested ``` ;; solution 1 (add-hook 'latex-mode-hook '(lambda() (setq comment-start "%% "))) ;; solution 2 (add-hook 'latex-mode-hook (lambda () (setq-local comment-add 0))) ``` but both don't work. # Answer The Auctex LaTeX mode hook is `LaTeX-mode-hook` (note the capitalization). So try ``` (add-hook 'LaTeX-mode-hook (lambda() (setq comment-start "%% "))) ``` Note also that `lambda` expressions are self-evaluating so you don't need to quote them in this context. I am assuming you are using `M-;` to comment things, otherwise `comment-start` does not enter into the equation. > 2 votes --- Tags: init-file, auctex, comment ---
thread-64469
https://emacs.stackexchange.com/questions/64469
special form or macro? eval-when-compile, eval-and-compile
2021-04-18T02:11:48.353
# Question Title: special form or macro? eval-when-compile, eval-and-compile Is `eval-when-compile` a special form (primitive in C), or a macro? According to the elisp manual, `C-h S eval-when-compile RET`, > Special Form: eval-when-compile body... But according to `C-h f eval-when-compile RET`, > eval-when-compile is a Lisp macro in ‘byte-run.el’ I'm trying to understand the difference between `eval-when-compile` and `eval-and-compile`. They have identical macro definitions in byte-run.el, but since the manual says they're special forms, rather than macros, I suspect there's something I'm missing. # Answer It's a macro defined in `byte-run.el`: ``` (defmacro eval-when-compile (&rest body) "Like `progn', but evaluates the body at compile time if you're compiling. Thus, the result of the body appears to the compiler as a quoted constant. In interpreted code, this is entirely equivalent to `progn', except that the value of the expression may be (but is not necessarily) computed at load time if eager macro expansion is enabled." (declare (debug (&rest def-form)) (indent 0)) (list 'quote (eval (cons 'progn body) lexical-binding))) ``` I've submitted (doc) bug #47862 for this. > 1 votes --- Tags: help, elisp-macros, manual ---
thread-64329
https://emacs.stackexchange.com/questions/64329
How to prevent <RET> from triggering abbrev expansion?
2021-04-06T23:49:55.357
# Question Title: How to prevent <RET> from triggering abbrev expansion? I am trying to stop emacs from expanding abbrevs after I press the `return` key. If I press `return`, I simply want to create a new line without expanding any abbrev at point. I am relatively new at elisp. I’m assuming the answer involves `pre-abbrev-expand-hook`, but I haven’t found an answer in my research. # Answer > 1 votes It seems this has been addressed after all in similar post here that I found after the fact. The solution I settled on was as follows: ``` (defun my-self-insert-no-abbrev-RET () (interactive) (let ((abbrev-mode nil)) (newline nil t))) (global-set-key (kbd "RET") #'my-self-insert-no-abbrev-RET) ``` --- Tags: abbrev ---
thread-38428
https://emacs.stackexchange.com/questions/38428
How to make Geiser send the output to REPL buffer instead of echo area?
2018-01-29T12:14:44.010
# Question Title: How to make Geiser send the output to REPL buffer instead of echo area? I am running Emacs25 with Geiser (latest version from MELPA, 20180128.1821) and Guile (version 2.2, Debian package). So far it works fine, but when I evaluate a sexp, it will print the result to Emacs' echo area instead of in the REPL buffer. Is there a way to change this behavior? I'd like to be able to scroll through long output, copy parts of it, etc. I tried looking into the configuration menus, but found nothing that seemed to be related to that. I'd appreciate any help with this. # Answer I'm not sure if this is possible. Based on Geiser doc (https://www.nongnu.org/geiser/geiser\_4.html): > For all the commands above, the result of the evaluation is displayed in the minibuffer, unless it causes a (Scheme-side) error > 0 votes --- Tags: scheme ---
thread-5894
https://emacs.stackexchange.com/questions/5894
Why does the alt+enter combination only work sometimes in org mode?
2014-12-30T07:23:51.743
# Question Title: Why does the alt+enter combination only work sometimes in org mode? I used to be able to use alt+enter to create new entries in org mode. EMACS suddenly stopped responding to the combination and started to return "M-kp-enter is undefined". How can I get it to work again? Many thanks. PS I'm using EMACS on Windows 8. # Answer I know this is an old question but it suddenly happened to me too. squidly had the correct answer but his reply was hidden so I had to work it out for myself. I had accidentally pressed 'NumLock' (top-right-hand-corner, 4-keys to the left on my keyboard). I hadn't realised for at least a year that there are two 'Enter' keys on my keyboard and Emacs thinks they are different. > 1 votes --- Tags: org-mode ---
thread-64478
https://emacs.stackexchange.com/questions/64478
eval-when-compile and eval-and-compile identical definitions?
2021-04-18T13:16:54.153
# Question Title: eval-when-compile and eval-and-compile identical definitions? How can `eval-when-compile` and `eval-and-compile` have different behavior if their definitions are identical? From byte-run.el: ``` (defmacro eval-when-compile (&rest body) ;; ... documentation string omitted ... (declare (debug (&rest def-form)) (indent 0)) (list 'quote (eval (cons 'progn body) lexical-binding))) (defmacro eval-and-compile (&rest body) ;; ... documentation string omitted ... (declare (debug (&rest def-form)) (indent 0)) (list 'quote (eval (cons 'progn body) lexical-binding))) ``` # Answer > How can `eval-when-compile` and `eval-and-compile` have different behavior if their definitions are identical? The hint is in the commentary in the definition of `eval-and-compile`: ``` ;; When the byte-compiler expands code, this macro is not used, so we're ;; either about to run `body' (plain interpretation) or we're doing eager ;; macroexpansion. ``` Indeed, it's not the body of these macros that defines their semantics, but the environment in which they're expanded during byte-compilation. The two semantics are differentiated in `byte-compile-initial-macro-environment`: ``` byte-compile-initial-macro-environment is a variable defined in `bytecomp.el'. Its value is shown below. This variable may be risky if used as a file-local variable. The default macro-environment passed to macroexpand by the compiler. Placing a macro here will cause a macro to have different semantics when expanded by the compiler as when expanded by the interpreter. Value: ((declare-function . byte-compile-macroexpand-declare-function) (eval-when-compile . #f(compiled-function (&rest body) #<bytecode 0x914a391b97fc68e>)) (eval-and-compile . #f(compiled-function (&rest body) #<bytecode 0x1395261de4da407b>)) (with-suppressed-warnings . #f(compiled-function (warnings &rest body) #<bytecode -0xadad30c834fbff0>))) ``` Here's the current environment for `eval-when-compile`: ``` (lambda (&rest body) (let ((result nil)) (byte-compile-recurse-toplevel (macroexp-progn body) (lambda (form) ;; Insulate the following variables against changes made in the ;; subsidiary compilation. This prevents spurious warning ;; messages: "not defined at runtime" etc. (let ((byte-compile-unresolved-functions byte-compile-unresolved-functions) (byte-compile-new-defuns byte-compile-new-defuns)) (setf result (byte-compile-eval (byte-compile-top-level (byte-compile-preprocess form))))))) (list 'quote result))) ``` And that for `eval-and-compile`: ``` (lambda (&rest body) (byte-compile-recurse-toplevel (macroexp-progn body) (lambda (form) ;; Don't compile here, since we don't know whether to compile as ;; byte-compile-form or byte-compile-file-form. (let ((expanded (macroexpand-all form macroexpand-all-environment))) (eval expanded lexical-binding) expanded)))) ``` It is not entirely uncommon to have macros whose body does very little, but whose macroexpansion is treated specially. Another example in addition to the forms listed above is the `declare` form, whose body is `nil` but whose macroexpansion results in the setting of function properties. > 6 votes --- Tags: elisp-macros, byte-compilation ---
thread-64482
https://emacs.stackexchange.com/questions/64482
(symbol-name sym) vs. (format "%s" sym)
2021-04-18T15:35:51.793
# Question Title: (symbol-name sym) vs. (format "%s" sym) I noticed some code in use-package-core.el where `format` is used to get a keyword's name as a string, ``` (format "%s" keyword) ``` Is there a reason this is preferable to using `symbol-name`? ``` (symbol-name keyword) ``` I would've expected `symbol-name` to be better in terms of readability and performance. # Answer > 6 votes If `KEYWORD` is indeed always a *symbol* (in particular a keyword symbol) then IMO there's no special reason to use `format`. But there's no special reason not to, either: "better readability" is opinion-based, and performance difference is probably negligible. But if it's *not* sure to be a symbol then using `format` with `"%s"` ensures that the resulting value is a string and not raise an error. # Answer > 4 votes > Is there a reason this is preferable to using `symbol-name`? No, I think it just comes down to style and context. E.g. I can imagine someone preferring to consistently use `format` everywhere, because it can handle more than just symbols, and the format string can be easily changed. See also Drew's answer. > I would've expected `symbol-name` to be better in terms of readability That's entirely subjective and context-dependent, I'm afraid. > and performance. I'd expect the same. `symbol-name` just checks that it has a symbol, untags it, and returns the stored name: ``` DEFUN ("symbol-name", Fsymbol_name, Ssymbol_name, 1, 1, 0, doc: /* Return SYMBOL's name, a string. */) (register Lisp_Object symbol) { register Lisp_Object name; CHECK_SYMBOL (symbol); name = SYMBOL_NAME (symbol); return name; } ``` Although `format` essentially boils down to the same thing for symbols: ``` /* ... */ if (SYMBOLP (arg)) { spec->argument = arg = SYMBOL_NAME (arg); if (STRING_MULTIBYTE (arg) && ! multibyte) { multibyte = true; goto retry; } } /* ... */ ``` there is a lot more bookkeeping involved, and potentially a string allocation, so it is quite likely to run slower. Having said that, the time it takes to evaluate `(format "%s" keyword)` should be so miniscule that for all practical purposes there is no performance difference between that and `(symbol-name keyword)`. As always, it is better to profile your code for performance, rather than trying to reason about minor (and probably premature) optimisations like this. Another thing to consider when comparing seemingly identical definitions, is whether one or the other has a dedicated opcode (which tends to result in faster execution) or is marked as `pure` or `side-effect-free`. --- Tags: symbols ---
thread-61048
https://emacs.stackexchange.com/questions/61048
Whitespace-mode: highlight hidden indentation of empty lines
2020-10-07T16:25:04.783
# Question Title: Whitespace-mode: highlight hidden indentation of empty lines I use whitespace-mode, intend with tabs (colored pale yellow, which is what I want) and I am wondering about the situation where there is an empty line inside an indented block (see image below). I would like the empty line to also start with some pale yellow highlighting, of the same length of the surrounding indentation, in order to make it easier to understand which parts of the code belong to which block, but I do **not** want to add an actual tab in the file. Is there an easy way to do that? # Answer > 0 votes I couldn’t find a built-in way to do it, so I implemented it myself as a minor mode (see here). Feel free to try it out if you have the same issue. I have been using it full time at my day job for a few weeks/months now, and it works perfectly and makes my code look so much better! *Technical details:* The way it works is with text properties, which allow one to change the way certain characters are displayed (without actually changing the contents of the buffer). So basically whenever there are two consecutive new lines, I put a text property on the second one that displays it as a certain number of tabs followed by a new line, the number of tabs being taken from the first non-empty line that follows. Those text properties are automatically updated after any change, and they are also automatically removed from the region when the mark is active, as for some reason it was still showing through the `region` face. --- Tags: highlighting, newlines, whitespace-mode ---
thread-64473
https://emacs.stackexchange.com/questions/64473
Using tab-bar.el with automatic tab management
2021-04-18T06:57:51.297
# Question Title: Using tab-bar.el with automatic tab management I want to implement automatic tab management. Every file I open needs to go into a tab. The tab into which any given buffer goes is determined by root directory of the VC repo the file belongs to. The mechanism used by tabbar.el was `tabbar-buffer-groups-function` where I could use a function like ``` (defun my/find-vc-root () "Retuns the repository root as per [vc]." (vc-call-backend (vc-responsible-backend default-directory) 'root default-directory)) ``` I do see `tab-bar-new-tab-group` in the code but I can't wrap my head around how it is to be used. # Answer Tab groups don't create new tabs. You can implement automatic tab management at different levels, it depends on your needs. 1. If you want only `C-x C-f` to open a file in a new tab, then you can just rebind this key with `(define-key ctl-x-map "\C-f" 'find-file-other-tab)` 2. If you want every opened file to go to a new tab, this implies that you need to rely on the file-visiting hook: ``` (add-hook 'find-file-hook (lambda () (let ((tab-bar-new-tab-choice (buffer-name))) (tab-bar-new-tab)))) ``` 3. If you want that even displaying a visited file should switch to its tab, this is possible with: ``` (push '((lambda (b _a) (buffer-local-value 'buffer-file-name (get-buffer b))) . (display-buffer-in-tab (tab-name . (lambda (b _a) (buffer-name b))))) display-buffer-alist) ``` > 2 votes --- Tags: tabbar ---
thread-64488
https://emacs.stackexchange.com/questions/64488
Custom compilation command fails on Windows due to slashes in paths
2021-04-18T19:41:18.740
# Question Title: Custom compilation command fails on Windows due to slashes in paths when i type on "shell": > c:\Users\TR\Desktop\emacs-27.2-x86\_64\bin\GAMES\game3\>love . works fine but when i put ``` (defun insert-file-name () (interactive) (let ((compilation-ask-about-save nil)) (compile (concat (file-name-directory (buffer-file-name)) "love .")))) (global-set-key (kbd "C-c C-v") #'insert-file-name) ``` in my initialization file using "C-c C-v" gives me the error message: > -*\- mode: compilation; default-directory: "c:/Users/TR/Desktop/emacs-27.2-x86\_64/bin/GAMES/game3/" -*\- Compilation started at Sun Apr 18 23:30:16 c:/Users/TR/Desktop/emacs-27.2-x86\_64/bin/GAMES/game3/love . 'c:/Users/TR/Desktop/emacs-27.2-x86\_64/bin/GAMES/game3/love' is not recognized as an internal or external command, operable program or batch file. > > Compilation exited abnormally with code 1 at Sun Apr 18 23:30:16 a similar code worked on Ubuntu emacs, but on Windows 7 it does not work! How can i solve this problem? # Answer > 1 votes Learn about backslashes in strings. And learn about manipulating file names. The result of evaluating this is presumably the absolute file name that you want for your program: ``` (expand-file-name "love" "c:\\Users\\TR\\Desktop\\emacs-27.2-x86_64\\bin\\GAMES\\game3") ``` That is: ``` (expand-file-name "love" (file-name-directory (buffer-file-name))) ``` # Answer > 1 votes Short answer, pass the relative file path to the cli. See documentation of `file-relative-name`. Long answer, As I can see in first paragraph. The shell is *DOS* shell. When current work directory is "c:\Users\TR\Desktop\emacs-27.2-x86\_64\bin\GAMES\game3", you can run "love" (note it's relative path) without any problem. But when you run `M-x compile`, you pass the whole path "c:/Users/TR/Desktop/emacs-27.2-x86\_64/bin/GAMES/game3/love" to the *DOS* shell. The *DOS* shell can't recognise the path. You can convert the path by replacing the "/" with "" by `(replace-regexp-in-string "/" "\\\\" "c:/hello/world.txt")`. But it's better to use relative path which is portable on all environments (WSL, Cygwin, macOS, Linux ...) In your code, instead of using full path `(concat (file-name-directory (buffer-file-name)) "love .")`, you should use `(concat (file-name-relative (file-name-directory (buffer-file-name))) "love .")`. Here is the documentation of `file-relative-name`, ``` file-relative-name is a compiled Lisp function in ‘files.el’. (file-relative-name FILENAME &optional DIRECTORY) Convert FILENAME to be relative to DIRECTORY (default: ‘default-directory’). This function returns a relative file name that is equivalent to FILENAME when used with that default directory as the default. If FILENAME is a relative file name, it will be interpreted as existing in ‘default-directory’. ``` You might need set `default-directory` to the right working directory inside your function `insert-file-name` before calling `compile`. But looks it's correct according to the error message. --- Tags: microsoft-windows, shell, filenames ---
thread-64493
https://emacs.stackexchange.com/questions/64493
org mode — verbatim syntax for new type of block
2021-04-19T11:49:20.260
# Question Title: org mode — verbatim syntax for new type of block the following MWE shows how I have created a new type of environment called a `codebox` to store output in, so that I can format it inside a box with LaTeX. However, I don't know how to make Org Mode treat each `#+begin_codebox ... #+end_codebox` environment so that its contents are preserved verbatim. **This works:** *Source:* ``` #+TITLE: MWE #+LATEX_HEADER: \RequirePackage{fancyvrb} #+LATEX_HEADER: \DefineVerbatimEnvironment{verbatim}{Verbatim}{fontsize=\scriptsize} #+LATEX_HEADER: \usepackage{mdframed} #+LATEX_HEADER: \newenvironment{example}{\VerbatimEnvironment\begin{BVerbatim}[fontsize=\scriptsize]}{\end{BVerbatim}} #+LATEX_HEADER: \newenvironment{codebox}{\VerbatimEnvironment\begin{mdframed}\begin{example}}{\end{example}\end{mdframed}} #+begin_src R :session :results output org :wrap codebox # Sample from the vector 'a' 1 element. a<-c("a","b","c","d","e","f") sample(a, 3) #+end_src #+RESULTS: #+begin_codebox [1] "b" "e" "d" #+end_codebox ``` However, if I make a codebox that includes things like `~` or `_`, etc., those symbols are given a special interpretation by the org mode exporter. **This isn't what I want:** *Source (to add to file above):* ``` * Not so great #+begin_codebox This ~ is a test_of_the{codebox} #+end_codebox ``` # Answer Well, I found a solution, but it does seem excessively clever! **Based on this:** https://emacs.stackexchange.com/a/19941/8406 **Key idea:** wrap with `example` rather than `codebox`, then use built-in ability to alter the formatting of example blocks. Installing some adapted elisp code from the linked answer: ``` (defun my-latex-export-example-blocks (text backend info) "Export example blocks as custom results env." (when (org-export-derived-backend-p backend 'latex) (with-temp-buffer (insert text) ;; replace verbatim env by 'results' (goto-char (point-min)) (while (re-search-forward "\\\\\\(begin\\|end\\){verbatim}" nil t) (replace-match "\\\\\\1{results}")) (buffer-substring-no-properties (point-min) (point-max))))) (add-to-list 'org-export-filter-example-block-functions 'my-latex-export-example-blocks) ``` Updated MWE: ``` #+TITLE: MWE #+LATEX_HEADER: \RequirePackage{fancyvrb} #+LATEX_HEADER: \DefineVerbatimEnvironment{verbatim}{Verbatim}{fontsize=\scriptsize} #+LATEX_HEADER: \usepackage{mdframed} #+LATEX_HEADER: \newenvironment{contents}{\VerbatimEnvironment\begin{BVerbatim}[fontsize=\scriptsize]}{\end{BVerbatim}} #+LATEX_HEADER: \newenvironment{results}{\VerbatimEnvironment\begin{mdframed}\begin{contents}}{\end{contents}\end{mdframed}} * Example #+begin_src R :session :results output org :wrap example # Sample from the vector 'a' 1 element. a<-c("a","b","c","d","e","f") sample(a, 3) #+end_src #+RESULTS: #+begin_example [1] "c" "f" "e" #+end_example * This works now #+begin_example This ~ is a test_of_the{codebox} #+end_example ``` > 0 votes --- Tags: org-export, latex ---
thread-59791
https://emacs.stackexchange.com/questions/59791
Font and frame configuration in daemon mode
2020-07-23T12:00:25.997
# Question Title: Font and frame configuration in daemon mode In my `.emacs` I have ``` (set-frame-font "Source Code Pro") (set-face-attribute 'default nil :font "Source Code Pro" :height 140) (set-face-font 'default "Source Code Pro") ``` Which sets the fonts to source code pro. To do its job, this code apparently needs to run once after the first frame has been created. How can I achieve that? * I'm on MacOS and use emacs-plus. * Emacs Deamon is started on boot as a service, I only ever call emacsclient. * If I run this code once, all new frames have the right fonts. * If Emacs Daemon restarts, I need to run the code again, but after the first frame has been created. * Putting it in `.emacs` runs it too early so it's not working. * If I start emacs as emacs, not as the deamon, the code in `.emacs` works and the first frame uses Source Code Pro. How can I set the fonts or other frame parameters on deamon start? # Answer > 6 votes > To do its job, this code apparently needs to run once after the first frame has been created. How can I achieve that? The standard hooks for this are listed under `(info "(elisp) Standard Hooks")`: ``` ‘after-make-frame-functions’ ‘before-make-frame-hook’ ‘server-after-make-frame-hook’ see Creating Frames. ``` Following the link to `(info "(elisp) Creating Frames")`: ``` -- Variable: before-make-frame-hook A normal hook run by ‘make-frame’ before it creates the frame. -- Variable: after-make-frame-functions An abnormal hook run by ‘make-frame’ after it created the frame. Each function in ‘after-make-frame-functions’ receives one argument, the frame just created. Note that any functions added to these hooks by your initial file are usually not run for the initial frame, since Emacs reads the initial file only after creating that frame. However, if the initial frame is specified to use a separate minibuffer frame (see Minibuffers and Frames), the functions will be run for both, the minibuffer-less and the minibuffer frame. -- User Option: server-after-make-frame-hook A normal hook run when the Emacs server creates a client frame. When this hook is called, the created frame is the selected one. See (emacs)Emacs Server. ``` (Note that the last `server-` hook is new in Emacs 27.) To ensure a hook function is run only once, after the first non-daemon frame is created, just remove the function from the hook as its last step. For example: ``` (defun my-configure-font (frame) "Configure font given initial non-daemon FRAME. Intended for `after-make-frame-functions'." ;; Do stuff with FRAME... (remove-hook 'after-make-frame-functions #'my-configure-font)) (add-hook 'after-make-frame-functions #'my-configure-font) ``` Some things to consider: * Both `after-make-frame-functions` and `server-after-make-frame-hook` are called for non-graphical frames as well, so add appropriate checks for this as needed. * Neither of these hooks is run in a non-daemon Emacs session. To also support non-daemon sessions, add your function to `window-setup-hook` instead (or as well). To check whether the current session is a daemon or not, there's the predicate `daemonp`. # Answer > 0 votes It sounds like you would need a function to run once per server invocation. You can probably use the information in this post to help you set up a hook that would run a function to set the fonts, and then not run that function for subsequent frames until the next time the server is (re)started. --- Tags: frames, emacsclient, fonts ---
thread-64497
https://emacs.stackexchange.com/questions/64497
Mentions of people in org file?
2021-04-19T14:57:09.167
# Question Title: Mentions of people in org file? Is there some way in org-mode to keep track of people mentioned in an outline? Sometimes I use an `@` in front of a person's handle to keep a note of who was the source of a piece of information, or who to ask about a particular question, or even who is responsible for a delegated TODO. This personal syntax looks like this: ``` * Earth orbits Sun This was originally proposed by @copernicus. * TODO ask @galileo about this * TODO @newton works on an alternative formulation ``` I can then search for those specific strings in the file or the whole folder. I could use tags for the same, but then I could not use them in body text, only on headings, and only at the end of the sentence ... Also, I feel like a tag should represent a cross-hierarchy category for a heading, but not specifically a person. The things I am missing with my ad-hoc solution are: 1. org agenda functions to filter only tasks that mention specific people, or that mention people at all, 2. maybe some type of columnar view that shows all people mentioned in a larger body of text Does anyone know if there is an org-mode syntax for this that I may have overlooked, or else a package that provides this functionality? # Answer > 2 votes I use https://github.com/jkitchin/scimax/blob/master/org-db.el for something like this. It doesn't directly support your syntax. I have toyed with storing hashtags (which is pretty similar), with mixed success. There are a lot of false positives especially with org-mode and src-blocks. I added support for @labels, and if it goes well in the next few days, I will probably commit it to the link above. I have used a contact link as suggested in the comment above, and there is an org-db-links command for finding them. --- Tags: org-mode ---
thread-64501
https://emacs.stackexchange.com/questions/64501
Getting text input into ivy completing read
2021-04-19T18:50:26.113
# Question Title: Getting text input into ivy completing read I know that I can get previous selections of ivy with ivy-history. But is there any way to get what was actually input into the search before choosing a match? # Answer > 1 votes I think the variable `ivy-text` has what you are looking for in it. --- Tags: ivy, completing-read ---
thread-64495
https://emacs.stackexchange.com/questions/64495
Text editing with parentheses
2021-04-19T13:30:14.237
# Question Title: Text editing with parentheses I have a text like Code1. I want to convert from Code1 to Code2, including parentheses and removing some texts. How do I edit this efficiently? Code 1 ``` AAA & 0.076 & 0.053 & 0.053\\ AAA & 0.103 & 0.159 & 0.122\\ BBB & 0.036 & 0.037 & 0.037\\ BBB & 0.107 & 0.166 & 0.150\\ CCC & 0.033 & 0.062 & 0.062\\ CCC & 0.099 & 0.154 & 0.115\\ ``` Code2 ``` AAA & 0.076 & 0.053 & 0.053\\ & (0.103) & (0.159) & (0.122)\\ BBB & 0.036 & 0.037 & 0.037\\ & (0.107) & (0.166) & (0.150)\\ CCC & 0.033 & 0.062 & 0.062\\ & (0.099) & (0.154) & (0.115)\\ ``` # Answer There are a number of different tools/approaches that might be helpful for this kind of problem. Which ones work best for you will be a matter of personal preference. You could do all of this with the built in query-replace-regexp, bound to `C-M-%` by default. Searching for "(0.\[\[:digit:\]\]+)" and replacing it with "(\1)" will start an interactive search. You can then press 'y' for each number you want to wrap in parentheses, and 'n' for each number you want to skip. That's probably the quickest way to solve the problem you describe. For more general approaches, you might consider: Wrap region makes it easy to quickly "wrap" a region with delimiters, including `()`, `{}`, `""`, and extendable to include pretty much whatever you need. It can also be tweaked so that different modes will apply a different suite of wrappers. Expand region makes it easy to quickly select a region. With point on a word or number, expand region makes it easy to select that word, then the sentence, paragraph etc. This also works in code, where you can quickly select the object at point, then the expression, then the containing function etc. Expand-region combined with wrap-region is a good way to wrap individual numbers in your text. You could use keyboard macros to repeating this for multiple numbers. Keyboard macros let you 'record' a series of key presses, then 'replay' them. In this case, you could record the keypresses that mark your number, wrap it in parentheses, and then move to the next number. Stop recording, and then repeat the macro over and over until you've wrapped everything you want. > 1 votes # Answer If you have to do it once in a while only I would vote for keyboard macros. In your case I would start with the first two lines: ``` AAA & 0.076 & 0.053 & 0.053\\ AAA & 0.103 & 0.159 & 0.122\\ ``` record macro there and apply it to the following lines. So to say - place cursor at the first A and start recording (eg "C-x ("): * Move cursor down * delete AAA * move forward and insert parenthesis * move cursor to the first B stop recording (eg "C-x )") Select region to apply the macro to and do (apply-macro-to-region-lines). > 1 votes --- Tags: text-editing, parentheses ---
thread-64508
https://emacs.stackexchange.com/questions/64508
What is the difference between emacs -Q -u [my-user] and emacs -Q -l [my-init-file.el]
2021-04-20T07:27:00.247
# Question Title: What is the difference between emacs -Q -u [my-user] and emacs -Q -l [my-init-file.el] I have all my emacs config in `.emacs.d/init.el`. The first command in that file is: ``` (add-to-list 'package-archives '("melpa" . "https://melpa.org/packages/") t) ``` When I start emacs with `emacs -Q -u [my-user]` it works fine. But when I start it with `emacs -Q -l ~/.emacs.d/init.el` I get the error `Symbol’s value as variable is void: package-archives`. I know that I can add `(require 'package)` at the top of init.el to solve this problem. However, I'm trying to understand why I don't get that error with `emacs -Q -u [my-user]`. Besides I encounter other similar problems down the line with `-Q -l ~/.emacs.d/init.el` which are not present with `-Q -u [my-user]`. What could `-u [my-user]` load that is not in my `~/.emacs.d/init.el`? I had a look at The Emacs Initialization File and How Emacs Finds Your Init File. It lists several other possibilities for init files. None seems present on my system. Specifically, none of these files exist: * ~/.emacs.el * ~/.emacs * ~/.config/emacs/ I don't seem to have a site-wide `default.el`. Anyway the docs say that it would be loaded after my `init.el` so it would not explain why emacs chokes on the 1st line of that file. I don't have `site-start.el` either. Confirming this, it makes no difference whether I append `--no-site-file` to the above commands. In the Startup Summary I saw this: > 7. It calls the function package-activate-all to activate any optional Emacs Lisp package that has been installed. See Packaging Basics. However, Emacs doesn’t activate the packages when package-enable-at-startup is nil or when it’s started with one of the options ‘-q’, ‘-Q’, or ‘--batch’. I still don't understand why it works with `-Q -u [my-user]` and not with `-Q -l [my-init-file]`. I have GNU Emacs 27.1 built from source on Debian Buster. # Answer The weird thing is that `-Q -u [user]` loads an init file at all. I'd call that a bug, but it's probably been this way for decades. Given that it does, I suspect there's no difference between these: * `emacs` * `emacs -q -u "$USER"` I.e. you've *reverted* the `--no-init-file` (aka `-q`) behaviour by specifying an init file (although again, I find that surprising). If that's correct, then the only difference to `emacs -Q -u "$USER"` would be the difference between `-q` and `-Q`. As you can see from `emacs --help`: ``` --quick, -Q equivalent to: -q --no-site-file --no-site-lisp --no-splash --no-x-resources ``` Conversely `emacs -Q -l [my-init-file]` *isn't* overriding `--no-init-file` and so you can expect the behaviour you've quoted from the documentation to hold. Note also that `-l` isn't processed until later in the start-up sequence, and so even if the options you passed didn't have additional effects, loading a file with `-l` would not *necessarily* give the same outcome as Emacs loading it as an init file. > 0 votes --- Tags: init-file, start-up ---
thread-58315
https://emacs.stackexchange.com/questions/58315
Edit PDF page labels in pdf-tools?
2020-05-06T11:36:54.087
# Question Title: Edit PDF page labels in pdf-tools? **Q:** how can I change PDF page *labels* with `pdf-tools`? `pdf-tools` has the capacity to annotate PDFs, which is great. Can it also change the page *labels* as well? That is, not the raw page number, but the labeled page number? ### Use Case I scan a lot of books and articles. I would like to be able to jump to the page numbers as enumerated in the books/articles, not just the nominal page number of the PDF. Example: if I scan an article that ranges from pages 11-20, I want to be able to embed the pages 11-20 so that I can tell `pdf-tools` to jump to, say, page label 12, rather than have to use the nominal page numbers (in this case, PDF page 2 which would correspond to page label 12). ### What I Found A quick `apropos` search turns up `pdf-info-pagelabels`, `pdf-view-current-pagelabel`, and `pdf-view-goto-label`. None of these appear to allow me to edit the page labels. ### Alternatives Welcome In the event that `pdf-tools` does not have this capability, I'd be glad to know of (linux) command line tools that allow me to edit page labels, as I'm sure I could rig up something with the right tool. # Answer > 3 votes You can do this with the Java variant of pdftk, starting from version 3.1.0. First, create a file with the metadata you want, e.g.: ``` PageLabelBegin PageLabelNewIndex: 1 PageLabelStart: 1 PageLabelPrefix: Cover PageLabelNumStyle: NoNumber PageLabelBegin PageLabelNewIndex: 2 PageLabelStart: 1 PageLabelPrefix: Back Cover PageLabelNumStyle: NoNumber PageLabelBegin PageLabelNewIndex: 3 PageLabelStart: 1 PageLabelNumStyle: LowercaseRomanNumerals PageLabelBegin PageLabelNewIndex: 27 PageLabelStart: 1 PageLabelNumStyle: DecimalArabicNumerals ``` Then apply it to the PDF file: ``` pdftk book.pdf update_info metadata.txt output book-with-metadata.pdf ``` --- Tags: pdf, pdf-tools ---
thread-64506
https://emacs.stackexchange.com/questions/64506
Equivalent of query-replace-regexp for multiple regexps
2021-04-19T21:41:17.627
# Question Title: Equivalent of query-replace-regexp for multiple regexps How can I do the equivalent of `query-replace-regexp` for multiple regexps? For instance, if *regexp1* is matched, it should be replaced by *text1*, and if *regexp2* is matched, it should be replaced by *text2* (with interactive confirmation as with `query-replace-regexp`). The search and replace needs to be done in one pass for all the regexps (I don't want to use `query-replace-regexp` on the first regexp, then on the second regexp, and so on). While querying could be done with a single regexp like `regexp1\|regexp2`, I don't know how I could do the replacement depending on whether *regexp1* or *regexp2* is matched. When `query-replace-regexp` is called interactively, `\,` can be used to execute a Lisp expression, which could do the selection, but this is not possible for code put in my `.emacs`, for instance. # Answer Try this. Enter an empty regexp interactively to stop adding regexp/replacement pairs, and start replacements. ``` (defun query-multi-replace-regexp (&rest pairs) "Query replace for each regexp and replacement string in PAIRS." (interactive (let (pairs regexp replacement) (while (and (setq regexp (read-regexp "Query replace regexp")) (not (string= regexp ""))) (push regexp pairs) (push (read-string (format "Query replace regexp %s with: " regexp)) pairs)) (nreverse pairs))) (let ((pos pairs) patterns) (while pos (push (pop pos) patterns) (pop pos)) (perform-replace (concat "\\(?:" (mapconcat 'identity patterns "\\|") "\\)") (cons (lambda (pairs count) (catch 'replacement (while pairs (let ((regexp (pop pairs)) (string (pop pairs))) (when (string-match-p regexp (match-string 0)) (throw 'replacement string)))))) pairs) :query :regexp nil))) ``` See the definition of `query-replace-regexp` if you want to support things like replacement in a region. It shows how to obtain the arguments for `perform-replace`. > 2 votes --- Tags: replace, query-replace-regexp ---
thread-64511
https://emacs.stackexchange.com/questions/64511
Append some text to multiple files in a directory
2021-04-20T08:55:54.840
# Question Title: Append some text to multiple files in a directory I want to append some text to multiple files in a directory. So, I opened the directory in `dired` buffer and selected the files. After this, is there any shortcut/ command to append some text to these files? There is a command `append-to-file` but that does not seem to serve my purpose. Is there any other better way of doing this? # Answer You can execute shell commands from `dired`, so if you have your additional text in a file named `text`, you can mark all the files you want to append to with `m` and then do `! cat text >> ?` : the `?` gets replaced with each marked filename in turn. Do `C-h f dired-do-shell-command` for more information. > 2 votes # Answer > Is there any other better way of doing this? Programmatically, you could define custom functions: ``` (defun my/append-file (text file) "Append TEXT to the end of a given FILE." (save-excursion (with-temp-buffer (insert-file file) (goto-char (point-max)) (insert "\n" text) (write-file file)))) (defun my/append-multiple-files (text files) "Append TEXT of the end of multiple FILES." (dolist (file files) (my/append-file text file))) ``` Then you can simply execute: ``` (my/append-multiple-files "Emacs" '("~/foo.txt" "~/bar.txt")) ``` to add the text "Emacs" at the end of both files `~/foo.txt`, `~/bar.txt`. You can of course make this function interactive for a greater ease of use. As concerns dired: once some files are marked in the dired buffer, you could simply execute in the minibuffer with `M-:` the following instruction: ``` (my/append-multiple-files "My text" (dired-get-marked-files)) ``` There might be a more elegant way however... > 1 votes # Answer If you use Dired+ then you can act on the marked files in arbitrary ways. These keys/commands are available, for applying a function to the files, invoking a command in the files, or evaluating a sexp in the files. Each returns a list of the results. * **`@ @`** -- `diredp-do-apply-to-marked`: Apply `FUNCTION` to the absolute name of each marked file. * **`@ M-:`** -- `diredp-do-eval-in-marked`: Evaluate an Emacs-Lisp `SEXP` in each marked file. * **`@ M-x`** -- `diredp-do-command-in-marked`: Invoke Emacs `COMMAND` in each marked file. So if you wanted to, say, append `XXXXXXXXXXX` to the content of each of the marked files then you could do any of the following: * Use `@ @`, and at the prompt for the function to apply to each marked file enter `toto`, after defining a function `toto` such as this: ``` (defun toto (file) (with-current-buffer (find-file-noselect file) (goto-char (point-max)) (insert "XXXXXXXXXXX"))) ``` * Use `@ M-:`, and at the prompt for the sexp to evaluate at the beginning of each marked file, enter a sexp such as this: ``` (progn (goto-char (point-max)) (insert "XXXXXXXXXXX")) ``` * Use `@ M-x` and enter `foo` at the prompt for the command to invoke in each marked file, after defining a command `foo` such as this: ``` (defun foo () (interactive) (goto-char (point-max)) (insert "XXXXXXXXXXX")) ``` In addition, there are equivalent commands that act on a set of files determined **recursively**. These commands bound to the same keys but on prefix key `M-+` (e.g. `M-+ @ @`). They operate on all marked files in the current Dired buffer and on all those marked in any marked subdirs, and so on (recursively). That is, they act on all marked files *here and below*. --- Here are the doc strings, for more info. > **`diredp-do-apply-to-marked`** is an interactive compiled Lisp function in `dired+.el`. > > It is bound to `@ @`, `menu-bar operate diredp-do-apply-to-marked`, `menu-bar operate apply diredp-do-apply-to-marked`. > > `(diredp-do-apply-to-marked FUNCTION &optional ARG)` > > Apply `FUNCTION` to the absolute name of each marked file. Return a list of the results. You are prompted for `FUNCTION`. > > A prefix arg behaves according to the `ARG` argument of `dired-get-marked-files`. In particular, `C-u C-u` operates on *all* files in the Dired buffer. > > If you use multiple `C-u` as prefix arg then many files might be acted on, and some of them might already be visited in modified buffers. If the function you apply modifies file content, and you want to save any such buffers before using this command, then use `C-x s` first. > > The result returned for each file is logged by `dired-log`. Use `?` to see all such results and any error messages. If there are fewer marked files than `diredp-do-report-echo-limit` then each result is also echoed momentarily. --- > **`diredp-do-eval-in-marked`** is an interactive compiled Lisp function in `dired+.el`. > > It is bound to `@ M-:`, `menu-bar operate diredp-do-eval-in-marked`, `menu-bar operate apply diredp-do-eval-in-marked`. > > `(diredp-do-eval-in-marked SEXP &optional ARG)` > > Evaluate an Emacs-Lisp `SEXP` in each marked file. > > Visit each marked file at its beginning, then evaluate `SEXP`. Return a list of the results. You are prompted for the `SEXP`. > > The result returned for each file is logged by `dired-log`. Use `?` to see all such results and any error messages. If there are fewer marked files than `diredp-do-report-echo-limit` then each result is also echoed momentarily. > > A prefix argument behaves according to the `ARG` argument of `dired-get-marked-files`. In particular, `C-u C-u` operates on *all* files in the Dired buffer. --- > **`diredp-do-command-in-marked`** is an interactive compiled Lisp function in `dired+.el`. > > `(diredp-do-command-in-marked COMMAND &optional ARG)` > > Invoke Emacs `COMMAND` in each marked file. > > Visit each marked file at its beginning, then invoke `COMMAND`. You are prompted for the `COMMAND`. > > Only *explicitly* marked files are used. A prefix arg has no effect on which files are used. > > A prefix arg is passed to `COMMAND` as its prefix arg. For example, if `COMMAND` uses a numeric prefix arg `N` for repetition then the effect of `COMMAND` is repeated `N` times. > > Other than the prefix arg, no arguments are passed to `COMMAND`. > > If any of the marked files are already visited in modified buffers then you are prompted to save them first. > > If after invoking `COMMAND` in all of the marked files new buffers have been created to visit some of them then you are prompted to kill those buffers. > > An errors are logged by `dired-log`. Use `?` to see the error messages. > > Be aware that `COMMAND` could be invoked in a directory (Dired) buffer. You may not want to do this if `COMMAND` modifies the buffer text. (But generally this will have little lasting effect - you can just use `g` in that buffer to revert the listing.) > 1 votes --- Tags: dired ---
thread-64521
https://emacs.stackexchange.com/questions/64521
How to copy commit hash from Magit status buffer?
2021-04-20T17:55:13.690
# Question Title: How to copy commit hash from Magit status buffer? After I open a Magit status buffer and make a commit, I commonly also want to copy that commit's hash (the shortened version) to my clipboard to post somewhere else. I can't work out how this should be done, and the Magit documentation doesn't seem to describe this feature. This makes me suspect there's a general way one should do this on these sorts of buffers that I don't yet know about. I am using Doom Emacs, so I get to the Magit buffer via `SPC g g`. # Answer > After I open a Magit status buffer and make a commit, I commonly also want to copy that commit's hash With vanilla Emacs bindings in the Magit status buffer: `M-w` (`magit-copy-buffer-revision`) saves the latest commit hash to the `kill-ring`: ``` M-w runs the command magit-copy-buffer-revision (found in magit-status-mode-map), which is an interactive compiled Lisp function in `magit-extras.el'. It is bound to M-w. (magit-copy-buffer-revision) Save the revision of the current buffer for later use. Save the revision shown in the current buffer to the `kill-ring' and push it to the `magit-revision-stack'. This command is mainly intended for use in `magit-revision-mode' buffers, the only buffers where it is always unambiguous exactly which revision should be saved. Most other Magit buffers usually show more than one revision, in some way or another, so this command has to select one of them, and that choice might not always be the one you think would have been the best pick. In such buffers it is often more useful to save the value of the current section instead, using `magit-copy-section-value'. When the region is active, then save that to the `kill-ring', like `kill-ring-save' would, instead of behaving as described above. When `magit-copy-revision-abbreviated' is non-nil, save the abbreviated revision to the `kill-ring' and the `magit-revision-stack'. ``` `C-w` (`magit-copy-section-value`) saves the commit hash at point to the `kill-ring`: ``` C-w runs the command magit-copy-section-value (found in magit-status-mode-map), which is an interactive compiled Lisp function in `magit-extras.el'. It is bound to C-w. (magit-copy-section-value ARG) Save the value of the current section for later use. Save the section value to the `kill-ring', and, provided that the current section is a commit, branch, or tag section, push the (referenced) revision to the `magit-revision-stack' for use with `magit-pop-revision-stack'. When `magit-copy-revision-abbreviated' is non-nil, save the abbreviated revision to the `kill-ring' and the `magit-revision-stack'. When the current section is a branch or a tag, and a prefix argument is used, then save the revision at its tip to the `kill-ring' instead of the reference name. When the region is active, then save that to the `kill-ring', like `kill-ring-save' would, instead of behaving as described above. If a prefix argument is used and the region is within a hunk, then strip the diff marker column and keep only either the added or removed lines, depending on the sign of the prefix argument. ``` > (the shortened version) The user option `magit-copy-revision-abbreviated` controls whether the hash is shortened: ``` magit-copy-revision-abbreviated is a variable defined in `magit-extras.el'. Its value is nil You can customize this variable. This variable was introduced, or its default value was changed, in version 3.0.0 of the magit package. Whether to save abbreviated revision to `kill-ring' and `magit-revision-stack'. ``` > the Magit documentation doesn't seem to describe this feature. This makes me suspect there's a general way one should do this on these sorts of buffers that I don't yet know. These commands are documented under `(info "(magit) Common Commands")`: ``` ‘C-w’ (‘magit-copy-section-value’) This command saves the value of the current section to the ‘kill-ring’, and, provided that the current section is a commit, branch, or tag section, it also pushes the (referenced) revision to the ‘magit-revision-stack’. When the current section is a branch or a tag, and a prefix argument is used, then it saves the revision at its tip to the ‘kill-ring’ instead of the reference name. When the region is active, this command saves that to the ‘kill-ring’, like ‘kill-ring-save’ would, instead of behaving as described above. If a prefix argument is used and the region is within a hunk, then it strips the diff marker column and keeps only either the added or removed lines, depending on the sign of the prefix argument. ‘M-w’ (‘magit-copy-buffer-revision’) This command saves the revision being displayed in the current buffer to the ‘kill-ring’ and also pushes it to the ‘magit-revision-stack’. It is mainly intended for use in ‘magit-revision-mode’ buffers, the only buffers where it is always unambiguous exactly which revision should be saved. Most other Magit buffers usually show more than one revision, in some way or another, so this command has to select one of them, and that choice might not always be the one you think would have been the best pick. Outside of Magit ‘M-w’ and ‘C-w’ are usually bound to ‘kill-ring-save’ and ‘kill-region’, and these commands would also be useful in Magit buffers. Therefore when the region is active, then both of these commands behave like ‘kill-ring-save’ instead of as described above. ``` > 7 votes --- Tags: magit, copy-paste, doom, clipboard ---
thread-64522
https://emacs.stackexchange.com/questions/64522
How can I use `TAB` with `M-x` to cycle through commands matching minibuffer input
2021-04-20T18:21:27.823
# Question Title: How can I use `TAB` with `M-x` to cycle through commands matching minibuffer input I am finding completion in Emacs system to work similarly to `bash` completion, in the sense that upon pressing `TAB`, it presents the user with a list of possible options. However, I am looking for something more similar to `zsh`, where pressing `TAB` completes my input to the nearest match, and pressing `TAB` again subsequently cycles through remaining matches. Does something like this exist in Emacs? # Answer Such `TAB` completion is available in Emacs, and not just for `M-x` (completing command names). 1. With vanilla Emacs, that is, without any additional library, you can have `TAB` cycle among completions by customizing user option `completion-cycle-threshold` to a number or the value `t`. If a number `N` then `TAB` cycles only when there are fewer than `N` completions of your input. If `t` then `TAB` always cycles, no matter how many completions there are. See the Emacs manual, node Completion Options, for more info. (You can get to this doc in Emacs itself using `C-h r g completion options`.) 2. In addition, there are several 3rd-party libraries that offer very useful `TAB` completion, including these: > 2 votes --- Tags: completion, minibuffer, cycling ---
thread-64518
https://emacs.stackexchange.com/questions/64518
Open a new buffer on the right
2021-04-20T15:09:02.370
# Question Title: Open a new buffer on the right I just upgraded from Fedora Linux 32 to Fedora 33 and I think this updated emacs as well because I now see some new behaviours. I have set: `(global-set-key (kbd "<f6>") 'org-todo-list)` so that I can press F6 to open the TODO list and it used to open on the right, which is what I want. Now it opens below. I did some research and found: `(setq split-width-threshold 1)` Which does open the TODO list on the right. BUT when I middle-click on a TODO item in the list, in order to bring the cursor to my org file, in order to mark a TODO item as DONE, sometimes (this seems like a weird behaviour) emacs will open a new window/frame with the org file to the right of the TODO list. So now I have: | org file | todo list | same org file | side by side. I have been searching for other ways to fix this, but found nothing. Any help is much appreciated. # Answer > 1 votes I found using a higher value, eg `(setq split-width-threshold 100)` resolved the issue. --- Tags: org-mode, window-splitting ---
thread-64498
https://emacs.stackexchange.com/questions/64498
multi-line diary event?
2021-04-19T15:30:16.067
# Question Title: multi-line diary event? I'd like to have diary entries/events with multiple lines. The usual diary format interprets newlines as delimiting events: ``` Monday event A every monday event B every monday event C every monday ``` Something like `diary-list-entries` gives you three entries. I want to have, say, multiple lines for event A: ``` Monday event A every monday some more stuff about event A yet more stuff about event A event B every monday event C every monday ``` ...and to have `diary-list-entries` or similar make the event A string have newlines in it. Is there a way to do this that doesn't involve making up my own format and writing lisp to handle that? (The motivation here is to have org mode entries with a properties block, but this isn't strictly org-mode-specific.) # Answer > 0 votes Thanks to @NickD, I see that I should just repeat the date specification. For some reason that didn't occur to me. So in my example, I should just do: ``` Monday event A every monday some more stuff about event A yet more stuff about event A Monday event B every monday further lines about this event / diary entry for event B Monday event C every monday ``` --- Tags: diary ---
thread-37780
https://emacs.stackexchange.com/questions/37780
Increment days / months / dates, etc. within buffer
2017-12-29T05:12:21.477
# Question Title: Increment days / months / dates, etc. within buffer In a text document, while editing, I often need to increment/ decrement calendar data. So, Friday will need to become Monday, December will need to become March, etc. Or 28 Apr after adding 5 will become 03 May, and even 31 Dec 2017 after adding 15 will become 15 Jan 2018. Is there a way to achieve this by placing cursor on the desired word/ number and hitting some keys so that it increments or decrements? So, while on Friday, I hit something to say 'Add 3' and it becomes Monday, etc. While on 28 in 28 Apr, I hit something to say 'Add 5' and it becomes 03 May. But while on Apr in 28 Apr, I hit something to say 'Subtract 2', it becomes 28 Feb, etc. Just so that you get an idea, vim has a speeddating plugin that does exactly what I am aiming at. # Answer > 1 votes Here's an example of how you can increment/decrement all ISO 8601 date strings in the current buffer by N days. `M-x shift-dates` will prompt you to enter the number of days to shift (enter a negative value to decrement). BTW I know this doesn't quite answer your question, but I think it's close. ``` (defun shift-date (date days) (format-time-string "%F" (time-add (time-to-seconds (days-to-time days)) (time-to-seconds (org-time-string-to-time date))))) (defun shift-dates (days) (interactive "nDays: ") (save-excursion (goto-char (point-min)) (while (not (eobp)) (forward-char 1) (when (looking-at iso8601--full-date-match) (let ((date (shift-date (match-string 0) days))) (save-excursion (while (looking-at "[^\s\\|\n]") (delete-char 1)) (insert date))))))) ``` # Answer > 0 votes The answer uses `calendar-day-name-array` and `calendar-month-name-array` which are set by calendar.el and shipped with Emacs: ``` ;; calendar-day-name-array ==> ["Sunday" "Monday" "Tuesday" "Wednesday" "Thursday" "Friday" "Saturday"] ;; calendar-month-name-array ==> ["January" "February" "May" "April" "May" "June" "July" "August" "September" "October" "November" "December"] (require 'calendar) (defun ar-shift--intern (arg thisarray) (let* ((name (substring-no-properties (word-at-point))) (bounds (bounds-of-thing-at-point 'word)) (beg (car-safe bounds)) (end (cdr-safe bounds)) (counter 0) (laenge (length thisarray)) (orig (point)) idxr dlr (datelist (progn (while (< counter laenge) (push (aref thisarray counter) dlr) (setq counter (1+ counter))) (nreverse dlr))) (idx (progn (dolist (ele datelist) (unless idxr (when (string= ele name) (setq idxr counter)) (setq counter (1+ counter)))) idxr)) (replaceform (aref thisarray (if (< (+ arg idx) laenge) (+ arg idx) (% (+ arg idx) laenge))))) (if (and beg end) (progn (delete-region beg end) (insert replaceform) (goto-char orig)) (error "Don't see a date at point")))) (defun ar-shift-day-atpt (arg) "Raise name of day at point ARG times. Decrease with negative ARG" (interactive "p") (ar-shift--intern arg calendar-day-name-array)) (defun ar-shift-month-atpt (arg) "Raise name of month at point ARG times. Decrease with negative ARG" (interactive "p") (ar-shift--intern arg calendar-month-name-array)) ``` Also raise or decrease positive integers: https://github.com/andreas-roehler/numbers-at-point --- Tags: text-editing, time-date ---
thread-64537
https://emacs.stackexchange.com/questions/64537
Org mode python code block with session does not return a result
2021-04-21T15:59:25.960
# Question Title: Org mode python code block with session does not return a result I had been successfully using python code blocks with the `:session` header argument when I noticed that upon export no result was given. I then simplified my example to the following two: ``` #+begin_src python :python ~/anaconda3/bin/python3 :session :results output import random if random.randint(0,10) % 2 == 0: ret = "even" else: ret = "odd" print(ret) #+end_src #+RESULTS: ``` ``` #+name: session_init #+BEGIN_SRC python :results value :session example str='Hello, World' str #+END_SRC #+RESULTS: session_init ``` but found that neither yielded any results. I'm quiet confused about this since it had been working until suddenly it wasn't. I tried removing cache, tmp files and rebuilding my emacs packages (I'm using doom emacs) but all to no avail I'm using org-version 9.5 and my emacs version is as such ``` GNU Emacs 28.0.50 Copyright (C) 2021 Free Software Foundation, Inc. GNU Emacs comes with ABSOLUTELY NO WARRANTY. You may redistribute copies of GNU Emacs under the terms of the GNU General Public License. For more information about these matters, see the file named COPYING. ``` If anyone can help that'd be much appreciated. # Answer > 8 votes The python implementation in Org babel has a couple of long-standing problems: * If you specify `:results value`, then the body is *implicitly wrapped in a function* and *you* have to add a `return` statement to indicate the value of the block - but *only* if you are not using a session. * If you specify `:results value` but you use a session, *you* have to wrap the body in your own function and *call* the function as the last thing of the block. That makes it awkward to switch a block from session to no-session (and vice versa) and from `:results output` to `:results value` (and vice versa): you have to modify the code to switch. In addition to that, when using sessions and an error occurs in a code block, then subsequent evaluations of the same or a different code block can fail, not because of the code, but because the session output got out of sync and Org babel can no longer parse it. When that happens, I kill the session buffer and start anew; and for that reason, I always name my sessions. I deal with these problems in a couple of different ways: for a session, I use `:results output` exclusively and add `print(...)` statements in order to produce the output I want. For non-session evaluation, I usually use `:results value` and I try to remember to add a `return` statement with the result that the block is supposed to produce. --- **EDIT**: For your specific case, you seem to need a python interpreter from a non-standard place. In order not to have to specify it for every code block, I would add the header as a file property: ``` #+PROPERTY: header-args:python :python ~/anaconda3/bin/python3 ``` (Don't forget to refresh the buffer by pressing `C-c C-c` on the added line above). --- In accordance with the guidelines above, here's how I would write your blocks: ``` #+begin_src python :session foo :results output import random if random.randint(0,10) % 2 == 0: ret = "even" else: ret = "odd" print(ret) #+end_src #+RESULTS: : odd #+name: session_output #+BEGIN_SRC python :results output :session foo str='Hello, World' print(str) #+END_SRC #+RESULTS: session_output : Hello, World ``` If you *really* want to combine a session with `:results value`, use something like this, where you define a function and call it - that lets Org babel figure out what the result should be: ``` #+name: session_value #+BEGIN_SRC python :results value :session foo def hello(): str='Hello, World' return str hello() #+END_SRC ``` and finally for `:results value` outside a session, use something like this: ``` #+name: non-session_value #+BEGIN_SRC python :results value str='Hello, World' return str #+END_SRC #+RESULTS: non-session_value : Hello, World ``` Remember, in this last case, the body of the code block is implicitly wrapped in a function, the function is called and the return value of the function is the result of the block. --- Tags: org-mode, org-babel, python, session ---
thread-64543
https://emacs.stackexchange.com/questions/64543
Restore privileged folder access for previously working Emacs.app on Catalina (NOT system upgrade)
2021-04-22T15:04:12.417
# Question Title: Restore privileged folder access for previously working Emacs.app on Catalina (NOT system upgrade) This is similar to How to Restore File System Access in macOS Catalina but the problem is different. I did not upgrade my operating system, only the app, and none of the solutions there are valid fixes for this question. I am having a problem with my `Emacs.app` on Mac OS X 10.15 Catalina. The distribution i am using is from the emacs-app-devel port from MacPorts. I initially installed `Emacs.app` on Catalina. Everything worked as expected. When i tried to access privileged locations like `~/Documents`, i received an OS popup asking for permission, granted, and was able to use the app normally. I then upgraded my `Emacs.app` through macports. After the new install and relaunching, i could no longer access the files using the emacs find-file functionality (default `C-x C-f`). I can still access everything using `File->Open`. Opening a file in one of the protected directories like ~/Documents using `File -> Open` or `ns-open-file-using-panel` does NOT restore access and allow find-file to proceed. Permissions like `"Files and Folders"` `"Network Volumes"` are already granted and i can see them. `Full Disk Access` is not necessary to allow emacs to access these files in Catalina. # Answer Investigating this problem, i was able to see a Console.app error from process tccd, (i think this is the "Transparency Consent and Control System" daemon). The error was `Failed to copy signing info for 95201, responsible for file:///Applications/MacPorts/Emacs.app/Contents/MacOS/Emacs: #-67062: Error Domain=NSOSStatusErrorDomain Code=-67062 "(null)"`. I do not know if the old install of the app produced by macports was codesigned, but the new one definitely was not (i checked this using `codesign -vvv Emacs.app`). I do not yet know if there will be any unintended side effects, but ah-hoc codesigning the existing app (identity below is '-') did fix my problem. I used to following command in the app's parent directory: `sudo codesign --force --deep --sign - ./Emacs.app` The codesign ran sucessfully, and upon relaunch i was prompted by the OS when i tried to access ~/Documents using find-file. I granted access and was able to open files inside. The prompt for ~/Documents looked like this: > 1 votes --- Tags: osx, files, find-file, gui-emacs, permissions ---
thread-41539
https://emacs.stackexchange.com/questions/41539
Evil keybindings in reftex-toc
2018-05-19T06:18:30.430
# Question Title: Evil keybindings in reftex-toc I would like to bind `j` to `reftex-toc-next` and `k` to `reftex-toc-previous` whilst in a reftex-toc buffer. According to the documentation, the keymap active in `*toc*` buffers is `reftex-toc-map`. I'm using `use-package` to load reftex, so I've tried ``` (use-package reftex :ensure t :after (latex) :bind (:map reftex-toc-map ("j" . reftex-toc-next) ("k" . reftex-toc-previous)) :config (add-hook 'LaTeX-mode-hook 'turn-on-reftex) (setq reftex-plug-into-AUCTeX t)) ``` Which produces the following error ``` Error (use-package): reftex/:catch: Symbol's value as variable is void: reftex-toc-map ``` Any suggestions as to why this doesn't work and how I can resolve it? # Answer > 3 votes I faced this exact problem and solved it by using evil-collection just on refTeX. Installed it as an additional package in my `dotspacemacs/layers()` ``` (setq-default ... dotspacemacs-addtional-packages '(... evil-collection ...) ... ) ``` And initialised it only for refTeX in my `user-config()` through ``` (evil-collection-init 'reftex) ``` --- Tags: key-bindings, evil, reftex-mode ---
thread-64547
https://emacs.stackexchange.com/questions/64547
Switch to most recent buffer in a given mode
2021-04-22T21:21:04.253
# Question Title: Switch to most recent buffer in a given mode I am trying to create a function that switches to the most recent buffer in major mode `major-mode`. An answer to a related question supplies a function that should require the smallest of tweaks to serve my purpose, but I can't make it work. Here is the original function in that answer: ``` (defun switch-to-most-recent-org-buffer () (interactive) (let (found) (catch 'done (mapc (lambda (x) (when (with-current-buffer x (eq major-mode 'org-mode)) (switch-to-buffer x) (setq found t) (throw 'done nil))) (buffer-list)) (unless found (message "not found"))))) ``` I thought I could just replace the first and sixth lines, respectively, with ``` (defun switch-to-most-recent-buffer-in-mode (major-mode) ``` and ``` (when (with-current-buffer x (eq major-mode major-mode)) ``` Which gives me this: ``` (defun switch-to-most-recent-buffer-in-mode (major-mode) (interactive) (let (found) (catch 'done (mapc (lambda (x) (when (with-current-buffer x (eq major-mode major-mode)) (switch-to-buffer x) (setq found t) (throw 'done nil))) (buffer-list)) (unless found (message "not found"))))) ``` but it doesn't work: while the original function switches to my most recent org buffer, evaluating `(switch-to-most-recent-buffer-in-mode org-mode)` returns a "not found" message. It seems I am failing to grasp something very basic about Elisp, so please excuse my ignorance: I'm not a programmer and am new to Emacs. -- \[edited to add:\] The amended code below works (taken from phils's answer). ``` (defun switch-to-most-recent-buffer-in-mode (mode) (interactive "C") (let (found) (catch 'done (mapc (lambda (x) (when (with-current-buffer x (eq major-mode mode)) (switch-to-buffer x) (setq found t) (throw 'done nil))) (buffer-list)) (unless found (message "not found"))))) ``` # Answer Regarding your changes: > ``` > (defun switch-to-most-recent-buffer-in-mode (major-mode) > (interactive) > > ``` The first problem is that you used the name of a standard variable for your argument, which means that the real `major-mode` is shadowed by whatever you pass to your function. You should rename that to something else (`mode` would be safe). The second problem is with the `interactive` form, which tells Emacs how to obtain the function arguments interactively (e.g. if called with `M-x` or by a key binding). By adding a required argument, but not changing the `interactive` spec, this command now won't work interactively. You could make that `(interactive "C")` to read a command symbol (which will include all modes). Your next change is: > ``` > (when (with-current-buffer x (eq major-mode major-mode)) > > ``` That `(eq major-mode major-mode)` will hopefully look pretty dodgy to you upon review. It is guaranteed to be true. You have run headlong into the first problem here -- you are trying to compare the standard variable `major-mode` with the argument you added of the exact same name, which obviously can't work. Take note that even if the function wasn't *directly* using the standard variable, name clashes are often unsafe (whether and how depends on the specifics, though). It's best to stick to un-hyphenated single word names for function arguments, as the *vast* majority of global variables are hyphenated. Finally, you're not calling your function correctly. > ``` > (switch-to-most-recent-buffer-in-mode org-mode) > > ``` You are trying to evaluate the variable `org-mode` and pass its value to the function. The value of `major-mode` (the standard variable, with which you will later be comparing the argument you've passed) is a *symbol*, so you need to quote the argument to prevent it from being evaluated, so that you are passing the *symbol* `org-mode`: ``` (switch-to-most-recent-buffer-in-mode 'org-mode) ``` > returns a "not found" message. I would actually have expected either an error (because `org-mode` isn't normally a valid variable to evaluate in your call), or for it to unconditionally select the first buffer (because `(eq major-mode major-mode)` is always true), so I'm not sure whether you were testing what you've described; but hopefully these pointers are sufficient in any case. > 1 votes --- Tags: buffers, major-mode ---
thread-32150
https://emacs.stackexchange.com/questions/32150
How to add a timestamp to each entry in Emacs' *Messages* buffer?
2017-04-14T16:58:41.807
# Question Title: How to add a timestamp to each entry in Emacs' *Messages* buffer? I depend on the `*Messages*` buffer a lot, but entries are not timestamped. How can one add a timestamp to each entry in Emacs' *Messages* buffer? So that something like this: ``` Loading /Users/gsl/lisp.d/init.el (source)... No outline structure detected For information about GNU Emacs and the GNU system, type C-h C-a. Loading /Users/gsl/lisp.d/var/recentf...done Error running timer: (wrong-number-of-arguments (lambda nil (setq gc-cons-threshold (* 64 1024 1024)) (message "WARNING: gc-cons-threshold restored to %S")) 1) [yas] Prepared just-in-time loading of snippets successfully. M-] is undefined CHILDREN [2 times] ‘show-all’ is an obsolete command (as of 25.1); use ‘outline-show-all’ instead. Invalid face reference: nil [33 times] Auto-saving...done Saving file /Users/gsl/lisp.d/init.el... Wrote /Users/gsl/lisp.d/init.el mwheel-scroll: Beginning of buffer [5 times] Mark set previous-line: Beginning of buffer [10 times] Quit [4 times] ``` will become something like this: ``` 2017-02-14-18:50:01 Loading /Users/gsl/lisp.d/init.el (source)... 2017-02-14-18:50:02 No outline structure detected 2017-02-14-18:50:03 For information about GNU Emacs and the GNU system, type C-h C-a. 2017-02-14-18:50:05 Loading /Users/gsl/lisp.d/var/recentf...done 2017-02-14-18:50:10 Error running timer: (wrong-number-of-arguments (lambda nil (setq gc-cons-threshold (* 64 1024 1024)) (message "WARNING: gc-cons-threshold restored to %S")) 1) 2017-02-14-18:50:12 [yas] Prepared just-in-time loading of snippets successfully. 2017-02-14-18:50:40 M-] is undefined 2017-02-14-18:50:41 CHILDREN [2 times] 2017-02-14-18:50:00 ‘show-all’ is an obsolete command (as of 25.1); use ‘outline-show-all’ instead. 2017-02-14-18:50:01 Invalid face reference: nil [33 times] 2017-02-14-18:51:01 Auto-saving...done 2017-02-14-18:51:03 Saving file /Users/gsl/lisp.d/init.el... 2017-02-14-18:51:06 Wrote /Users/gsl/lisp.d/init.el 2017-02-14-18:51:09 mwheel-scroll: Beginning of buffer [5 times] 2017-02-14-18:51:11 Mark set 2017-02-14-18:51:21 previous-line: Beginning of buffer [10 times] ``` I searched on EmacsWiki, Reddit and emacs.sx of course, to no avail. I am aware of `command-log-mode`, which can be adjusted to log with timestamps, but it is useful only for interactive commands, not all messages, including Emacs' "system" ones. Instead, every message logged to the *Messages* buffer should be timestamped. How can one add a timestamp to each entry in Emacs' *Messages* buffer, no matter its source? # Answer I have the following snippet in my init.el, which was adapted from an original I found in the following Reddit thread: http://www.reddit.com/r/emacs/comments/16tzu9/anyone\_know\_of\_a\_reasonable\_way\_to\_timestamp/ (EDIT: modernised to advice-add and removed clumsy read-only buffer handling on advice of @blujay) ``` (defun sh/current-time-microseconds () "Return the current time formatted to include microseconds." (let* ((nowtime (current-time)) (now-ms (nth 2 nowtime))) (concat (format-time-string "[%Y-%m-%dT%T" nowtime) (format ".%d]" now-ms)))) (defun sh/ad-timestamp-message (FORMAT-STRING &rest args) "Advice to run before `message' that prepends a timestamp to each message. Activate this advice with: (advice-add 'message :before 'sh/ad-timestamp-message)" (unless (string-equal FORMAT-STRING "%s%s") (let ((deactivate-mark nil) (inhibit-read-only t)) (with-current-buffer "*Messages*" (goto-char (point-max)) (if (not (bolp)) (newline)) (insert (sh/current-time-microseconds) " "))))) (advice-add 'message :before 'sh/ad-timestamp-message) ``` This results in decoration of the \*Messages\* buffer as follows: ``` [2017-06-13T07:21:13.270070] Turning on magit-auto-revert-mode... [2017-06-13T07:21:13.467317] Turning on magit-auto-revert-mode...done [2017-06-13T07:21:13.557918] For information about GNU Emacs and the GNU system, type C-h C-a. ``` > 12 votes # Answer The translation of @xinfatang's simple solution to the new `advice-add` syntax as a wrapper around the `message` function is: ``` (defun my-message-with-timestamp (old-func fmt-string &rest args) "Prepend current timestamp (with microsecond precision) to a message" (apply old-func (concat (format-time-string "[%F %T.%3N %Z] ") fmt-string) args)) ``` Outputs `*Messages*` like: ``` [2018-02-25 10:13:45.442 PST] Mark set ``` To add: ``` (advice-add 'message :around #'my-message-with-timestamp) ``` To remove: ``` (advice-remove 'message #'my-message-with-timestamp) ``` > 8 votes # Answer Refer to https://www.emacswiki.org/emacs/DebugMessages: ``` (defadvice message (before when-was-that activate) "Add timestamps to `message' output." (ad-set-arg 0 (concat (format-time-string "[%Y-%m-%d %T %Z] ") (ad-get-arg 0)) )) ``` Finally, I still like **Stuart Hickinbottom** 's answer, because it avoids showing timestamp in the minibuffer. The following is a modified version which I use, it ignores messages only shown in the echo area(by `let`ting `message-log-max` to `nil` before message function call): ``` (defun my/ad-timestamp-message (FORMAT-STRING &rest args) "Advice to run before `message' that prepends a timestamp to each message. Activate this advice with: (advice-add 'message :before 'my/ad-timestamp-message) Deactivate this advice with: (advice-remove 'message 'my/ad-timestamp-message)" (if message-log-max (let ((deactivate-mark nil) (inhibit-read-only t)) (with-current-buffer "*Messages*" (goto-char (point-max)) (if (not (bolp)) (newline)) (insert (format-time-string "[%F %T.%3N] ")))))) (advice-add 'message :before 'my/ad-timestamp-message) ``` > 5 votes # Answer My solution expands on **Stuart Hickinbottom** 's and **xinfa tang** 's answers by NOT printing the timestamp of repeated messages: ``` (defvar my-package--last-message nil "Last message with timestamp appended to it.") (defun my-package-ad-timestamp-message (format-string &rest args) "Prepend timestamp to each message in message buffer. FORMAT-STRING and ARGS are used by `message' to print a formatted string. Enable with (add-hook 'find-file-hook 'my-package-ad-timestamp-message)" (when (and message-log-max (not (string-equal format-string "%s%s"))) (let ((formatted-message-string (if args (apply 'format `(,format-string ,@args)) format-string))) (unless (string= formatted-message-string my-package--last-message) (setq my-package--last-message formatted-message-string) (let ((deactivate-mark nil) (inhibit-read-only t)) (with-current-buffer "*Messages*" (goto-char (point-max)) (when (not (bolp)) (newline)) (insert (format-time-string "[%F %T.%3N] ")))))))) ``` It accomplishes this by comparing the current message to the last message printed with a timestamp. > 1 votes --- Tags: buffers, message, logging ---
thread-17144
https://emacs.stackexchange.com/questions/17144
How to install po-mode?
2015-10-05T10:01:21.817
# Question Title: How to install po-mode? I tried `M-x po-mode`, but it is not installed. I have tried to find a `gettext` or `po-mode` package under `M-x list-packages` as well as `M-x package-install`, but I couldn't find either. I have gettext and relevant libraries, as shown here: ``` [my-pc]/home/lucas$ whereis gettext gettext: /usr/bin/gettext /usr/bin/gettext.sh /usr/lib/gettext /usr/share/gettext /usr/share/man/man1/gettext.1.gz /usr/share/man/man3/gettext.3.gz /usr/share/info/gettext.info.gz [my-pc]/home/lucas$ whereis poedit poedit: /usr/bin/poedit /usr/lib/poedit /usr/share/poedit /usr/share/man/man1/poedit.1.gz ``` I have reviewed the emacs PO mode docs and relevant install instructions, but I still cannot find a way to install po-mode on emacs. Any suggestions? Here is more system info, if interested: ``` [my-pc]/home/lucas$ uname -a Linux my-pc 4.2.2-1-ARCH #1 SMP PREEMPT Tue Sep 29 22:21:33 CEST 2015 x86_64 GNU/Linux 'M-x version' GNU Emacs 24.5.1 (x86_64-unknown-linux-gnu, GTK+ Version 3.16.6) of 2015-09-09 on foutrelis ``` --- **Update** It looks like the elisp files should be installed with the gettext package on my OS, but I don't think my installation includes them. I searched `/usr/share/gettext` but did not find anything: ``` [my-pc]/home/lucas$ tree /usr/share/gettext/ | grep emacs ├── po-emacs-x.css ├── po-emacs-xterm16.css ├── po-emacs-xterm256.css ├── po-emacs-xterm.css [my-pc]/home/lucas$ tree /usr/share/gettext/ ├── ABOUT-NLS ├── archive.dir.tar.xz ├── config.rpath ├── gettext.h ├── intl │ ├── bindtextdom.c │ ├── config.charset │ ├── COPYING.LIB │ ├── dcgettext.c │ ├── dcigettext.c │ ├── dcngettext.c │ ├── dgettext.c │ ├── dngettext.c │ ├── eval-plural.h │ ├── explodename.c │ ├── export.h │ ├── finddomain.c │ ├── gettext.c │ ├── gettextP.h │ ├── gmo.h │ ├── hash-string.c │ ├── hash-string.h │ ├── intl-compat.c │ ├── intl-exports.c │ ├── l10nflist.c │ ├── langprefs.c │ ├── libgnuintl.in.h │ ├── libintl.rc │ ├── loadinfo.h │ ├── loadmsgcat.c │ ├── localcharset.c │ ├── localcharset.h │ ├── locale.alias │ ├── localealias.c │ ├── localename.c │ ├── lock.c │ ├── lock.h │ ├── log.c │ ├── Makefile.in │ ├── ngettext.c │ ├── os2compat.c │ ├── os2compat.h │ ├── osdep.c │ ├── plural.c │ ├── plural-exp.c │ ├── plural-exp.h │ ├── plural.y │ ├── printf-args.c │ ├── printf-args.h │ ├── printf.c │ ├── printf-parse.c │ ├── printf-parse.h │ ├── ref-add.sin │ ├── ref-del.sin │ ├── relocatable.c │ ├── relocatable.h │ ├── setlocale.c │ ├── textdomain.c │ ├── threadlib.c │ ├── tsearch.c │ ├── tsearch.h │ ├── vasnprintf.c │ ├── vasnprintf.h │ ├── vasnwprintf.h │ ├── verify.h │ ├── VERSION │ ├── version.c │ ├── wprintf-parse.h │ ├── xsize.c │ └── xsize.h ├── javaversion.class ├── msgunfmt.tcl ├── po │ ├── boldquot.sed │ ├── en@boldquot.header │ ├── en@quot.header │ ├── insert-header.sin │ ├── Makefile.in.in │ ├── Makevars.template │ ├── quot.sed │ ├── remove-potcdate.sin │ └── Rules-quot ├── projects │ ├── GNOME │ │ ├── team-address │ │ ├── teams.html │ │ ├── teams.url │ │ └── trigger │ ├── index │ ├── KDE │ │ ├── team-address │ │ ├── teams.html │ │ ├── teams.url │ │ └── trigger │ ├── team-address │ └── TP │ ├── team-address │ ├── teams.html │ ├── teams.url │ └── trigger └── styles ├── po-default.css ├── po-emacs-x.css ├── po-emacs-xterm16.css ├── po-emacs-xterm256.css ├── po-emacs-xterm.css └── po-vim.css 7 directories, 100 files ``` It also seems like the archlinux gettext package does not include any elisp files, shown here: https://www.archlinux.org/packages/core/x86\_64/gettext/ (file list is at the bottom) For the meantime, I may just manually install the source elsewhere. # Answer > 5 votes `po-mode` should come with your installed gettext lib. In `/path/to/gettext/share/emacs/site-lisp/` you should find the po-mode files. Add the location to your load path and autoload the `po-mode` command. Here is how I have mine setup for a specific gettext version installed from brew: ``` (add-to-list 'load-path "/usr/local/Cellar/gettext/0.19.5.1/share/emacs/site-lisp/") (autoload "po-mode" "po-mode") ``` Alternatively setup with `use-package`: ``` (use-package po-mode :load-path "/usr/local/Cellar/gettext/0.19.5.1/share/emacs/site-lisp/" :commands (po-mode)) ``` # Answer > 4 votes You can get the file here: https://github.com/andialbrecht/emacs-config/blob/master/vendor/po-mode.el Then put the file in your load-path (like ~/.emacs.d/) and add `(require 'po-mode)` in your .emacs. # Answer > 3 votes In emacs v28.0.5, the po-mode from melpa didn't work for me. It had an issue that stopped me from opening **.po** files. (*Error: function definition is void: po-with-temp-buffer*) I had installed `gettext` and `gettext-el` via `apt` which were suggested solutions but that didn't seem to switch on `po-mode` in emacs for me. (*Even `Mx po-mode` didn't work*) After installing `gettext` and `gettext-el`, adding the following lines to my **.emacs** file, made po-mode work for me. ``` (autoload 'po-mode "po-mode" "Major mode for translators to edit PO files" t) (setq auto-mode-alist (cons '("\\.po\\'\\|\\.po\\." . po-mode) auto-mode-alist)) ``` Solution got from here. # Answer > 2 votes For Ubuntu 16.04 Xenial, the package you need is: ``` apt install gettext-el ``` # Answer > 1 votes All answers here are correct, and they all helped me find the root of the problem. But the following solution is the only thing that solved my issue, which was actually caused by the Archlinux gettext package: It turns out, this was an issue with the gettext package in ArchLinux. With lots of help from Earnestly, I was able to resolve this issue with the following PKGBUILD file (written by Earnestly): ``` pkgdesc='po-mode for emacs from gettext' arch=('i686' 'x86_64') url="http://www.gnu.org/software/gettext/" license=('GPL') depends=('emacs') source=(ftp://ftp.gnu.org/pub/gnu/gettext/gettext-"$pkgver".tar.gz{,.sig}) validpgpkeys=('462225C3B46F34879FC8496CD605848ED7E69871') # Daiki Ueno sha1sums=('4d236852bd8d63e14d09eb6fc1f4da20a99f568b' 'SKIP') build() { cd gettext-"$pkgver"/gettext-tools/misc emacs -Q --batch -f batch-byte-compile *.el } package() { cd gettext-"$pkgver"/gettext-tools/misc install -Dm644 *.el *.elc -t "$pkgdir"/usr/share/emacs/site-lisp } ``` That should do the trick. Now I have an `emacs-po-mode` package! # Answer > 0 votes This also give me hint to solve my problem. There is a po-mode file: po-mode 20160827.857 available melpa major mode for GNU gettext PO files However, it causes me some trouble - emacs bug #26539. I need try po-mode.el from gettext 0.19.8.1 --- Tags: translation ---
thread-64557
https://emacs.stackexchange.com/questions/64557
How to efficiently insert citations into LaTeX document with helm-bibtex?
2021-04-23T18:10:32.840
# Question Title: How to efficiently insert citations into LaTeX document with helm-bibtex? I'm having a heck of a time optimizing my desired `\cite` behavior when writing LaTeX source in emacs using helm-bibtex. I made a `C-c [` key-binding to get helm-bibtex going when I want to insert a citation: ``` (autoload 'helm-bibtex "helm-bibtex" "" t) (global-set-key (kbd "C-c [") 'helm-bibtex-with-local-bibliography) ``` What I want then is once I press `C-c [`, I want to start typing the name of a bib key, and when the entry is highlighted, I want to press `Enter` and it should insert the block `\cite{mykey}` into the text. However the current process is so inefficient, I have to do `C-c [`, start typing until entry is highlighted, press `F3`, and then it asks me which kind of citation command I want where `cite` is the default, then it asks for "prenotes", then "postnotes", then FINALLY it inserts the cite block. How do I get the behavior described first where I just press enter and it inserts cite block, instead of having to press a function key and `Enter` 3 times? # Answer There doesn't appear to be a way to stop `helm-bibtex` from asking which kind of citation you want. You can stop it from asking you for prenotes and postnotes: ``` (setq bibtex-completion-cite-prompt-for-optional-arguments nil) ``` You can also make inserting a citation the default action: ``` (helm-delete-action-from-source "Insert Citation" helm-source-bibtex) (helm-add-action-to-source "Insert Citation" 'helm-bibtex-insert-citation helm-source-bibtex 0) ``` This will automatically insert a citation when you hit enter, so you don't need to select it with `f3`. With these values set, I can enter a new citation via: 1. `M-x helm-bibtex` (or your keybinding) 2. search for the entry 3. hit enter twice That saves you two keypresses. I agree it would be nice to have `helm-bibtex` default to adding `cite`, without having to select it. It seems like there should be a way to configure this, but I don't see it. > 2 votes --- Tags: latex, helm-bibtex ---
thread-64564
https://emacs.stackexchange.com/questions/64564
Can't disable font-lock-mode
2021-04-24T08:34:15.290
# Question Title: Can't disable font-lock-mode If I have font-lock on and I do `M-x find-library RET simple RET`, I have colours: If I then `M-x font-lock-mode` to disable the mode, the colours disappear in the currently-visible portion of the buffer: But the colours are still present everywhere else if I scroll the buffer: This does not happen with `emacs -Q`. Any ideas on how to debug it? ``` GNU Emacs 27.1 (build 1, x86_64-apple-darwin20.3.0, NS appkit-2022.30 Version 11.2.1 (Build 20D75)) of 2021-03-13 ``` Update: It happens with a fresh `Doom` emacs, so I am reporting it as anissue. # Answer > Can't disable font-lock-mode ... i have tried `(global-font-lock-mode -1)` and manually disabling `font-lock-mode` locally via `M-x`; The result (for all major modes) is that the visible lines are stripped of color You have successfully disabled `font-lock-mode`. > but the other lines in the buffer are still colored. Sure, but evidentially not via `font-lock-mode`. There are other ways to apply faces to text. Such cases will probably be using overlays or text properties. I suspect your real question is something like "How do I make Emacs use the default face for all text?" > 1 votes --- Tags: debugging, font-lock, themes, performance ---
thread-64563
https://emacs.stackexchange.com/questions/64563
`capitalize` capitalizes letters following an apostrophe
2021-04-24T03:32:34.967
# Question Title: `capitalize` capitalizes letters following an apostrophe I wrote an Elisp script to deal with some file names with English phrases. `capitalize` converts "I'm a cat" to "I'M A Cat". What's the right way to get the desired result? ("I'm A Cat") Should I use regex and write my own capitalization function? # Answer What mode is your file in? If I open `file.txt` (which according to my `auto-mode-alist` makes the major mode of the file `text`), then the `m` after the apostrophe is *not* capitalized either by `capitalize-region` or by `capitalize-word`. That follows from the fact that the syntax class of the apostrophe is `word` in text mode, so `I'm` is considered a single "word", and only the `I` gets capitalized. In other modes, the syntax class of the apostrophe may be different, leading to different capitalization behavior. For example, if you do the same thing with a file called `foo.py`, the file is opened in `python-mode` (at least with my settings in `auto-mode-alist`) and the syntax class of the apostrophe is `"` (i.e. it delimits quoted strings). That makes the `I` and the `m` separate "words", so each gets capitalized. To find out the syntax class of a character in your buffer, put the cursor on it and say `C-u C-x =`, then look for `Syntax` in the description. To find out more about syntax tables, do `C-h i g (elisp) Syntax tables`. > 2 votes --- Tags: capitalization ---
thread-64554
https://emacs.stackexchange.com/questions/64554
Defining a simple transient with a default value
2021-04-23T15:21:15.127
# Question Title: Defining a simple transient with a default value I'm trying to add a very simple transient thus: ``` (transient-define-prefix simple-transient () "A simple transient" ["Arguments" ("-a" "Address (default 127.0.0.1)" "--addresss=") ("-p" "Port (default 554)" "--port=") ("-v" "Use verbose logging" "--verbose") ["Actions" ("r" "Run" run-command)]) ``` All I want to do is have say "verbose" on by default, or set port to something else, but I can't fathom the docs - is there a simple way of doing this? # Answer I have since found a way to do this, by using: ``` :value '("--verbose" "--port="1234") ``` Which is hopefully the recommended way of doing things. In case it helps anyone else, this is the first time I'd tried to use transient and found the documentation fairly heavy going. I just wanted to launch a command via transient and have some default values plugged in. So here's what I did. First, create the command to launch the process: ``` (defun run-command (&optional args) (interactive (list (transient-args 'simple-transient))) (let ((input-file (read-file-name "Run with input: " "C:/Path/Somewhere" nil t))) (apply #'start-process "command" "*command*" "command" (cons input-file args)))) ``` Then define the transient: ``` (transient-define-prefix simple-transient () "A simple transient" :value '("--verbose") ; default to verbose on ["Arguments" ("-a" "Address (default 127.0.0.1)" "--addresss=") ("-p" "Port (default 554)" "--port=") ("-v" "Use verbose logging" "--verbose") ["Actions" ("r" "Run" run-command)]) ``` And finally, you can then bind this to a key: ``` (global-set-key [f8] 'simple-transient) ``` > 0 votes --- Tags: transient-library ---
thread-64566
https://emacs.stackexchange.com/questions/64566
How to use package-generate-autoloads
2021-04-24T13:08:59.010
# Question Title: How to use package-generate-autoloads I am teaching myself autoloads for "home-made" packages. Official Docs suggest to use `update-file-autoloads` or `update-directory-autoloads` on the related package file or directory, which will add the corresponding autoload calls into `loaddefs.el`. This does not seem to be the strategy followed by most packages, which instead create a distinct `*-autoloads.el` file for each source equipped with the *magic autoload comments* (perhaps to avoid cluttering `loaddefs.el`). I haven't found any tutorial on this, by the way a user suggested to use `package-generate-autoloads`. Indeed, it works up to a certain point, and this is my attempt. I created the file `...site-lisp/foo/foo.el`: ``` ;;;###autoload (defun foofunc () (message "I'm foo")) (provide 'foo) ``` Then, I executed on the `foo` folder: ``` (package-generate-autoloads "foo" "foo") ``` Much like for any package, it generates in `foo` the `foo-autoloads.el` file, where there is a line: ``` (autoload 'foofunc "foo" nil nil nil) ``` When restarting Emacs, by inspecting the value of the variable `load-path`, I see that the `foo` is automatically included, being under `site-lisp`. However, evaluating `foofunc`, gives: ``` Debugger entered--Lisp error: (void-function foofunc) ``` Not surprisingly, if I manually evaluate `(autoload 'foofunc "foo" nil nil nil)` or ``` (load "foo-autoloads.el") ``` `foofunc` works. However, there should be some way to have this done automatically by Emacs for all autoloads files in the path. Note that, while this question focuses on `package-generate-autoloads` function, if there is a better way to activate autoloads, your answer is welcomed. ### Side Question As a side note, I have seen that applying `package-generate-autoloads` to some ELPA packages adds to the corresponding `*-autoloads.el` files a convenient call to `register-definition-prefix`. As I understand, with this function you can add a custom prefix `mypref-`, such that, whenever you try to autocomplete `mypref-` in the minibuffer, you autoload the relevant lisp file. What (magic cookies) in the source files trigger(s) the insertion of these calls in the `*-autoloads.el` files? # Answer > 1 votes > This does not seem to be the strategy followed by most packages, which instead create a distinct `*-autoloads.el` file for each source equipped with the magic autoload comments It is not the package that is responsible for this, but the built-in package manager, `package.el`. > (perhaps to avoid cluttering `loaddefs.el`). I'm not familiar with the history behind `-autoloads.el` files, but I'd say they are distinct from `loaddefs.el` so that the former can be automatically detected and loaded by `package.el`. > However, there should be some way to have this done automatically by Emacs for all autoloads files in the path. AFAIK, only `package.el` has such a mechanism built-in; see `package-directory-list`: ``` ;;;###autoload (defcustom package-directory-list ;; Defaults are subdirs named "elpa" in the site-lisp dirs. (let (result) (dolist (f load-path) (and (stringp f) (equal (file-name-nondirectory f) "site-lisp") (push (expand-file-name "elpa" f) result))) (nreverse result)) "List of additional directories containing Emacs Lisp packages. Each directory name should be absolute. These directories contain packages intended for system-wide; in contrast, `package-user-dir' contains packages for personal use." :type '(repeat directory) :initialize #'custom-initialize-delay :risky t :version "24.1") ``` So if you put your `foo` package directory under `package-user-dir` or `site-lisp/elpa/` it should be picked up by `package.el` automatically (after calling `package-activate-all`, `package-initialize`, or similar). Otherwise, I think non-`package.el` loaddefs files need to be explicitly loaded. > What (magic cookies) in the source files trigger(s) the insertion of these calls in the `*-autoloads.el` files? The lack of a cookie ;). The following file: ``` ;;; -*- lexical-binding: t -*- ;;;###autoload (defun foo-bar ()) (provide 'foo) ``` will produce only the following autoload: ``` (autoload 'foo-bar "foo" nil nil nil) ``` There is no need to register a prefix in this case, because Emacs already knows where to find `foo-bar` by virtue of it being autoloaded from a specific file. OTOH the following file: ``` ;;; -*- lexical-binding: t -*- ;;;###autoload (defun foo-bar ()) (defun foo-baz ()) (provide 'foo) ``` results in: ``` (autoload 'foo-bar "foo" nil nil nil) (register-definition-prefixes "foo" '("foo-baz")) ``` --- Tags: package, autoload ---
thread-39116
https://emacs.stackexchange.com/questions/39116
Simple ways to copy/paste files and directories between dired buffers
2018-02-27T10:21:44.353
# Question Title: Simple ways to copy/paste files and directories between dired buffers Is there a simple `M-w` `C-y` approach to copy paste files and directories between two dired buffers? I mean marking some items (files and buffer) by `m` then copying them by `M-w` (or another shortcut), then going to another dired buffer (which is not necessarily in a window side-by-side by the window of previous dired buffer(s)) then `yanking` all copied file by `C-y` (or another shortcut) there? This is a simple task that many file explorers in different OS can do. The problem with the classical Copy option **C** in dired is that as soon as it is pressed, it asks for the destination. If the path of the destination buffer is very long or there are too many opened dired buffer, this approach is complicated. I am looking for a solution to first copy the items then to paste them at an appropriate dired buffer. There is a related question How to quickly copy/move file in Emacs Dired? which uses the classical approach of pressing **C** when two dired windows separated vertically using the option `(setq dired-dwim-target t)`. What are the ways to achieve this? # Answer You can do the following in vanilla Dired (no 3rd-party library needed): 1. Go first to a Dired buffer that lists the *target directory*. 2. With the cursor on the directory header line for a listing of the target directory, use **`w`** (command `dired-copy-filename-as-kill`). This copies the absolute name of that target directory. (You can copy a dir name from any Dired-listing subdir header line in the same way.) 3. Go to the Dired buffer that lists the *files you want to copy*. Mark those files. 4. Use **`C`** (command `dired-do-copy`) to *copy the marked files*. At the prompt, use `C-y` to *paste the (absolute) name of the target directory*. You can just paste it, without bothering to remove the default directory that is inserted in the minibuffer. (Pasting it after that default dir name dims that default name - it is ignored.) This is, I think, as simple as what you describe (`C-w` to copy marked file names followed by `C-y` in the target Dired listing), but the *order is opposite*: you copy the target directory name first, and then paste it to the `C` (`dired-do-copy`) command. (`dired-do-copy` checks for existing files of the same name in the target dir, etc.) --- **Tip:** (This is not needed if you use Dired+ \- see my other answer here.) If you intend to copy (or move) files from multiple directories to the same target directory, and you might be doing other things with the kill-ring in between, so that the copied target dir name might no longer be first in the kill-ring, then use the **secondary selection** to select the target dir name. The secondary selection doesn't depend on the region or the position of the cursor - you can paste it as many times as you want, regardless of changes to the kill-ring. You can paste it using the mouse, but it is handier to use `C-M-y` from library **`second-sel.el`**. > 15 votes # Answer I've added this feature now to Dired+. You can use **`C-y`** (command `diredp-yank-files`) to paste files, whose absolute names you have copied to the kill ring, to the current directory. The "current directory" here is what `dired-current-directory` returns: the inserted subdirectory where the cursor is located, or the Dired main directory if the cursor is not in a subdir listing. With a prefix arg, `C-y` instead prompts you for the target directory for the paste. So you do not need to be in a Dired buffer to paste files to a directory. You should have copied file names to the kill ring using `M-0 w` or `M-x diredp-copy-abs-filenames-as-kill`. In Dired+ those commands also set variable `diredp-last-copied-filenames` to the same string of file names. `C-y` uses the value of that variable, not whatever is currently at the head of the kill ring. This means that you need not paste immediately after you copy file names. And it means that you could, instead of copying file names to the kill ring, just put the names in that variable (e.g. programmatically). When you use `C-y`, you are prompted for confirmation (`y` or `n`). You can also hit **`l`** (for "list") when prompted, to display the list of files that will be pasted. --- You can also copy the marked files from the current Dired buffer *and any marked files in its marked subdirectories, defined recursively*. For that you use **`M-0 M-+ M-w`** (zero prefix arg with command `diredp-copy-filename-as-kill-recursive`) or use `M-x diredp-copy-abs-filenames-as-kill-recursive`. --- Note that with Dired+ you can also easily have a Dired buffer that lists any number of files and directories, from anywhere. That is, the entries listed need not be in the same directory or even in related directories. See **`C-x D F`** (command `diredp-dired-for-files`), which is on the **Dir** menu-bar menu as item **Dired Files Located Anywhere**. You can mark and then paste (copy) such arbitrary files from a Dired buffer to any directory. --- Update 2019-04-22: I also added the ability to *move* (not just paste) the files whose (absolute) names you copied to the kill ring to the current (or another) directory. This is bound to **`C-w`** in Dired. > **`diredp-move-files-named-in-kill-ring`** is an interactive Lisp function in `dired+.el`. > > `(diredp-move-files-named-in-kill-ring &optional DIR NO-CONFIRM-P DETAILS)` > > Move files, whose absolute names you copied, to the current directory. > > With a non-negative prefix arg you are instead prompted for the target directory. > > With a non-positive prefix arg you can see details about the files if you hit **`l`** when prompted to confirm pasting. Otherwise you see only the file names. The details you see are defined by option `diredp-list-file-attributes`. > > You should have copied the list of file names as a string to the kill ring using **`M-0 w`** or `M-x diredp-copy-abs-filenames-as-kill`. Those commands also set variable `diredp-last-copied-filenames` to the same string. `diredp-move-files-named-in-kill-ring` uses the value of that variable, not whatever is currently at the head of the kill ring. > > When called from Lisp: > > * Optional arg `NO-CONFIRM-P` means do not ask for confirmation to move. > * Optional arg `DETAILS` is passed to `diredp-y-or-n-files-p`. > 8 votes # Answer Your idea sounds straightforward, maybe you can try to implement it by yourself, you can also use the following to get started if you want to. ``` (defvar your-dired-copy-list nil) (defun your-dired-copy () (interactive) (setq your-dired-copy-list (dired-get-marked-files))) (defun your-dired-paste () (interactive) (when your-dired-copy-list (shell-command (mapconcat #'shell-quote-argument `("cp" "-r" ,@your-dired-copy-list ,default-directory) " ")) (setq your-dired-copy-list nil))) ``` > 4 votes # Answer Ranger file manager works the way you describe, but it is inspired by vim (thus vim keybindings `yy` to yank/copy `p` to paste etc). Emacs also has implementation of ranger. Try it, maybe it'll fit your need. I for myself use emacs sunrise-commander which kind of similar to Midnight Commander (mc), whenever I feel I need double-panes-files-managing. Upd: dired-ranger has that copy/paste you have described. At least in the docs. ``` ;; Multi-stage copy/pasting of files ;; --------------------------------- ;; A feature present in most orthodox file managers is a "two-stage" ;; copy/paste process. Roughly, the user first selects some files, ;; "copies" them into a clipboard and then pastes them to the target ;; location. This workflow is missing in dired. ;; In dired, user first marks the files, then issues the ;; `dired-do-copy' command which prompts for the destination. The ;; files are then copied there. The `dired-dwim-target' option makes ;; this a bit friendlier---if two dired windows are opened, the other ;; one is automatically the default target. ;; With the multi-stage operations, you can gather files from ;; *multiple* dired buffers into a single "clipboard", then copy or ;; move all of them to the target location. Another huge advantage is ;; that if the target dired buffer is already opened, switching to it ;; via ido or ibuffer is often faster than selecting the path. ;; Call `dired-ranger-copy' to add marked files (or the file under ;; point if no files are marked) to the "clipboard". With non-nil ;; prefix argument, add the marked files to the current clipboard. ;; Past clipboards are stored in `dired-ranger-copy-ring' so you can ;; repeat the past pastes. ;; ... ``` > 3 votes # Answer \[The OP posted an answer to his own question but then deleted it - I don't understand why, since it was a perfectly good answer to the question in the title, even though it does not implement what he asked in the body of the question. So for the benefit of future visitors to this question, I will provide his answer - if he decides to undelete his answer in the future, I will delete mine.\] The most convenient way I know to copy (or move) files/directories from one directory to another, is to customize the option `dired-dwim-target` to `t` and then open both the source and destination directories in `dired`: that is much easier than typing a long pathname since you can use completion on paths. Mark the files you want to copy (or move) and then execute the action: `C` for copy, `R` for rename. `dwim` stands for `do what I mean` and the fact that you have the destination open in `dired` shows that you mean to copy/move the files to that directory. One caveat is that if there is a third directory open in `dired` and shown in a window, `dired` might mistakenly pick that as the destination directory. But all you have to do is hide it (`C-x 0` in the errant directory's window) to tell `dired` exactly what you mean. > 2 votes # Answer I also would suggest to use `dired-ranger`. This is what I have in my `init.el`: ``` (use-package dired-ranger :ensure t :config (setq dired-ranger-copy-ring-size 1) (define-key dired-mode-map (kbd "C-w") (lambda () (interactive) (dired-ranger-copy nil) ; t adds item to dired-ranger-copy-ring (define-key dired-mode-map (kbd "C-y") 'dired-ranger-move))) (define-key dired-mode-map (kbd "M-w") (lambda () (interactive) (dired-ranger-copy nil) (define-key dired-mode-map (kbd "C-y") 'dired-ranger-paste))) ) ``` > 1 votes # Answer Dired ranger was the true solution for me: You can achieve common file explorer behavior as you describe, just with this simple config (assuming you use `use-package`): ``` (use-package dired-ranger :bind (:map dired-mode-map ("W" . dired-ranger-copy) ("X" . dired-ranger-move) ("Y" . dired-ranger-paste))) ``` > 0 votes --- Tags: dired, copy-paste ---
thread-64573
https://emacs.stackexchange.com/questions/64573
What's :eval (colon eval) in defcustom?
2021-04-25T01:38:16.057
# Question Title: What's :eval (colon eval) in defcustom? I am reading this Elisp library and can't figure out what `:eval` is. # Answer > 8 votes The doc string tells you this: > "Mode line lighter for Github Notifier." You couldn't otherwise know for sure what the code is about, or what `:eval` means in that context. That is, you couldn't know without checking where, and how, that user option (variable) is actually used in the surrounding code. Normally, you could use `i` in the Elisp manual, and type `:eval`, to see where that's indexed in the manual. But there are no index terms that start with `:` (because of the tools that build the manual), and trying `i eval` doesn't really help. However, you can search (`C-s`, repeating) the manual for `:eval`, and you will come to nodes in the manual having to do with the `mode-line` that tell you about this. In particular, you'll come to node Mode Line Data, where you find this: > `(:eval FORM)` A list whose first element is the symbol `:eval` says to evaluate `FORM`, and use the result as a string to display. Make sure this evaluation cannot load any files, as doing so could cause infinite recursion. Keep searching for `:eval` and you'll come to these nodes, which tell you more about the same use of `:eval`, that is, its use in a `mode-line` construct: Another way to find this information would be to use `i mode line` in the manual. That takes you to node Mode Line Format, which has the other nodes mentioned as subnodes (in the menu you see there). And after you try `i mode line`, and visit that node, a message in the echo area tells you that you're visiting the first of four matches for your input `mode line`, and that you can use `,` to visit the other matches, in turn. Doing that takes you to the other nodes mentioned above. All of this is without actually studying the code that uses the variable in question. Of course, searching that Elisp file for the variable name will show you just how it's used, and there you'll see that it's used as a mode-line construct. That will show you the *particular* use, in context. In sum: * Emacs doc strings are a great entry point. * `i` in the manuals is your friend. * But index entries can't start with `:`, and index entries for just `eval` unfortunately don't really cover this. (Consider filing a bug report: `M-x report-emacs-bug`, to add an index entry for `eval` that has to do with the `:eval` mode-line construct.) * You can search throughout a manual using `C-s`. --- (If you want to get to the web version of the manuals, you can use `G` (command `Info-goto-node-web`) when in the manual in Emacs, if you use library Info+. That's how I quickly got the URLS for the above links.) # Answer > 4 votes This has nothing to do with `defcustom`: if you look at the doc string of `defcustom` it says: > (defcustom SYMBOL STANDARD DOC &rest ARGS) In this case, the SYMBOL is `github-notifier-mode-line`, the DOC is "Mode line lighter for Github Notifier.", the ARGS are `:type 'sexp :risky t :group 'github-notifier)`. The whole quoted expression is the STANDARD value of this variable. In fact, if you evaluate the `defcustom` in an emacs session, you can then ask about `github-notifier-mode-line` with `C-h v github-notifier-mode-line`: it will tell you its value and its value is exactly that quoted expression. That's as far as `defcustom` goes. You have to dig a bit deeper to find out what exactly that value is doing. The hint is that the name of the variable indicates that it has something to do with the mode line. If you look further in the file you linked, that suspicion is confirmed: e.g. the first line of the file says: > Displays your GitHub notifications unread count in mode-line and the keywords line says: > Keywords: github, mode-line The clincher however is one of the last lines in the file that says: ``` (add-to-list 'global-mode-string 'github-notifier-mode-line t) ``` Now if you ask emacs about `global-mode-string` with `C-h v global-mode-string`, it tells you: > String (or mode line construct) included (normally) in ‘mode-line-format’. In other words, you got to look at the `mode-line-format` documentation to see what that `:eval` is doing. `C-h v mode-line-format` then tells you: > A list of the form ‘(:eval FORM)’ is processed by evaluating FORM and using the result as a mode line construct. Be careful--FORM should not load any files, because that can cause an infinite recursion. IOW, whenever the mode line is updated, that code is evaluated and its value is plugged into the mode line as part of `global-mode-string`. For more details on the mode line, consult the Emacs Lisp manual with `C-h i g (elisp) mode line format`. In particular, the subsection "Mode line variables" explains how `global-mode-string` is used. # Answer > 3 votes Run `C-h f defcustom RET` to show the help information for defcustom. This will tell you what arguments it expects. In particular, is says that this is the expected signature: ``` (defcustom SYMBOL STANDARD DOC &rest ARGS) ``` So this `:eval` thing is in the position of the argument called STANDARD. A few lines down it says: ``` SYMBOL is the variable name; it should not be quoted. STANDARD is an expression specifying the variable's standard value. ``` So this is just the value that this variable will have by default, unless the user customizes it. But it is a pretty funny–looking value! The hint is in the name of the variable: `github-notifier-mode-line`. This is a value that will be put into a mode line definition at some point, so we can look in the Elisp manual for information about that. Chapter 23.4.2 The Data Structure of the Mode Line has all the information about what can go into a mode line definition, including what `:eval` means. Two other people just answered the question, so I’ll stop there and hope that between the three of us you get the information you need. --- Tags: help, mode-line-format, manual ---
thread-64579
https://emacs.stackexchange.com/questions/64579
After update to Emacs 27.2 ORG mode expands everything upon opening the file
2021-04-25T10:22:55.927
# Question Title: After update to Emacs 27.2 ORG mode expands everything upon opening the file After updating Emacs from 27.1 to 27.2 (current stable of Fedora 33 default repository), I found myself with the dilemma that once I open an ORG mode file, all subtrees and children thereafter are opened instead of neatly wrapped up and folded. Is this an expected change for ORG mode? If it is, can one revert to start with a folded tree globally without having to add headers in each and every file one works on? # Answer Ok. Found the culprit: `org-startup-folded` According to the built-in help: ``` This variable was introduced, or its default value was changed, in version 9.4 of the Org package that is part of Emacs 27.2. ``` While this answers the questions posed, it throws up another question as to why this was changed. However, since "why"-questions can be dug in indefinitely, I draw the line here after having changed the variable to the former reasonable state. It is even a built-in variable which can be customized through Emacs internal routines. For those not too familiar, call up its help `C-h` `v`, then type in the above variable and press `ENT`. In the help you find a link to "customize" this variable. > 2 votes --- Tags: org-mode ---
thread-59864
https://emacs.stackexchange.com/questions/59864
Starting a shell then cd to a specific directory
2020-07-29T03:55:35.870
# Question Title: Starting a shell then cd to a specific directory I want to go to a specific directory after I start a shell. So I put these lines in my .emacs file: ``` (shell) (shell-command "cd C:/MyStartUp/ThisDirectory") (setq default-directory "C:/MyStartUp/ThisDirectory") ``` However, whenever I start emacs, the shell ends up in this directory `c:\emacs-26.3\bin>` How do I fix this? # Answer > 2 votes First > ``` > (shell) > > ``` opens a `*shell*` buffer and starts a shell process in it. Then > ``` > (shell-command "cd C:/MyStartUp/ThisDirectory") > > ``` runs a non-interactive shell which executes the command `cd C:/MyStartUp/ThisDirectory` and exits. Then > ``` > (setq default-directory "C:/MyStartUp/ThisDirectory") > > ``` sets the current directory of the buffer where the shell process is running. This does not affect the running process. You need to either set the current directory of the `*shell*` buffer before starting the shell process, or send the `cd` command to the running shell. Setting the current directory of the `*shell*` process is a little complicated because the way to do it depends on whether the `*shell*` buffer already exists. You also need to decide whether you want to change the current directory if a shell is already running, which sending the `cd` command will always do. To set the current directory if a new `*shell*` buffer is created: ``` (let ((default-directory "C:/MyStartUp/ThisDirectory")) (shell)) ``` To set the current directory of an existing `*shell*` buffer if there is one: ``` (let ((buffer (get-buffer "*shell*"))) (if buffer (with-current-buffer buffer (shell-cd "C:/MyStartUp/ThisDirectory")))) ``` `shell-cd` runs the `cd` function, which is a bit fancier than directly setting `default-directory`: it honors `CDPATH` (which you may or may not care about). `shell-cd` also takes care to update the directory shown in buffer lists. You can run this before the previous snippet to cover both the case where no `*shell*` buffer exists and the case where a `*shell*` buffer exists without a running shell process. Note that this does not cover the case of an existing `*shell*` buffer with a running shell process. To change the directory of the running shell, send a `cd` command to it. (`cd` works for all common shells including Unix-like `*sh`, fish, Windows `cmd` and Plan 9 rc, but if you use a more exotic shell you'll need to use its own syntax.) This doesn't work if you want to change to a remote directory using Tramp: for that, you have to decide on the host before running the shell. ``` (shell) (with-current-buffer "*shell*" (shell-cd "C:/MyStartUp/ThisDirectory") (let ((cmd (concat "cd " (shell-quote-argument default-directory) "\n"))) (comint-send-string nil cmd)) ``` Note that this snippet assumes that your shell accepts the same quoting mechanism as your platform's default shell. Otherwise you may need to replace `shell-quote-argument` with a function that's suitable for your shell's syntax. Sending input to the shell assumes that the shell is listening to input. If the shell is running an interactive application, that application will receive the input. There's no easy way to detect that and no reliable way to work around it. # Answer > 1 votes In some circumstances, having the trailing forward slash for the `default-directory` is necessary. My recollection is that this may depend upon the OS. It is possible to pass commands to the `shell` buffer under-the-hood with `comint-send-string` and `comint-send-input`, but that appears to be unnecessary in this particular use-case. The beginning directory in the `shell` buffer will be inherited from the `default-directory`, which can be let-bound: ``` (let ((default-directory "C:/MyStartUp/ThisDirectory/")) (shell)) ``` --- Tags: shell, shell-mode ---
thread-64516
https://emacs.stackexchange.com/questions/64516
Using org-roam tags when org publishing
2021-04-20T13:15:37.467
# Question Title: Using org-roam tags when org publishing When publishing it's possible to get a list of filetags for an org note by doing something like `(org-export-data (plist-get info :filetags) info)` in `publish.el` and loop over them to create markup. I use org-roam and was wondering if there is a way to do something similar with the `+#roam_tags:` property. Just switching `:filetags` for `:roam_tags` doesn't work - no error, it's just empty I think. Could anyone offer some advice on how I might approach this? FYI I asked this question on the org-mode sub reddit as well but posting here as well. # Answer After experimenting with custom backends using `org-export-define-derived-backend`, I learned that we can define custom properties and reference their values in the way my question states. For example: We can derive a backend from the existing one and provide customizations. In this case, we can define a custom property mapped to the export property. ``` (org-export-define-derived-backend 'my-custom-backend 'slimhtml :options-alist '((:roam_tags "ROAM_TAGS" nil nil split))) ``` Now, with `my-custom-backend` defined, invoking `(plist-get info :roam_tags)` returns a list of the `#+roam_tags`. Also, we can access the roam tags with `(org-publish-find-property entry :roam_tags project 'my-custom-backend)` See https://orgmode.org/worg/dev/org-export-reference.html and http://doc.endlessparentheses.com/Var/org-export-options-alist.html for more details like the additional arguments. > 1 votes --- Tags: org-mode, org-publish, org-roam ---
thread-64584
https://emacs.stackexchange.com/questions/64584
Popping the mark in Emacs
2021-04-25T17:49:24.077
# Question Title: Popping the mark in Emacs I am interested to know more about the use of the phrase "pop" in relationship to the mark in Emacs. The command `pop-global-mark`, as I understand it, jumps to the buffer and position of the latest entry in the global ring and also rotates the ring. But why the use of the word "pop" and what exactly is popped? # Answer `global-mark-ring` is a list with marker objects. In programming and computer science "popping" something from a list simply means removing the first element of the list (and usually returning the first element). I.e if you have a list `(1 2 3)` and call something like `(pop '(1 2 3))` the new list would be `(2 3)`. While I do not know when the term was first used in computer science, the first element of a list is commonly called the "head" (and everything after the "tail"). So what you are doing is "popping the head" of the list. Edit: According to Wikipedia (thanks @NickD) it comes from the stack of plates popping up in a cafeteria. > Stacks are often described using the analogy of a spring-loaded stack of plates in a cafeteria. Clean plates are placed on top of the stack, pushing down any already there. When a plate is removed from the stack, the one below it pops up to become the new top plate. > 3 votes --- Tags: mark ---
thread-64583
https://emacs.stackexchange.com/questions/64583
How to use Org mode for i3/sway config files
2021-04-25T16:04:23.617
# Question Title: How to use Org mode for i3/sway config files I use the `swaywm`. It's similar to `i3`. The Emacs distribution I use is `doom-emacs` I recently learnt about literate config files. But how make literate configs for something like this. The text is not in any particular programming language. I tried to use `conf` for tangling code blocks. But that throws up errors and emacs crashes. Here's a sample of the code I'm talking about https://github.com/swaywm/sway/blob/master/config.in # Answer > 1 votes You could just type `in` where you'd mention the language of the source block. This should work: ``` #+begin_src in :tangle yes Code goes here #+end_src ``` If your file is named `config.org`, this will tangle to `config.in`. Not sure whether this is good practice, but you could also use something generic like `sh`, and then provide a filename to tangle to: ``` #+begin_src sh :tangle config.in Code goes here #+end_src ``` --- Tags: doom, literate-programming, tangle ---
thread-64588
https://emacs.stackexchange.com/questions/64588
How do I get all marked files from all Dired buffers?
2021-04-26T13:48:28.000
# Question Title: How do I get all marked files from all Dired buffers? I'm trying to write a function that opens all marked files externally in their default programs. I've tried using `(dired-get-marked-files)` to get the filepaths, but that only returns the marked files in the current buffer. Is it possible to get *all* marked files from *all* dired buffers? # Answer > 3 votes This should do it: ``` (defun foo () "Return a list of marked files from all Dired buffers." (let ((files ()) (here ())) (dolist (buf (mapcar #'cdr dired-buffers)) (when (buffer-live-p buf) (with-current-buffer buf (setq here (dired-get-marked-files nil nil nil t))) (when (or (null (cdr here)) (eq t (car here))) (setq here (cdr here))) (setq files (nconc here files)))) (setq files (delete-dups files)))) ``` The reason to use `(dired-get-marked-files nil nil nil t)`, instead of just `(dired-get-marked-files)`, is because the latter returns the file where the cursor is when no files are explicitly marked. Presumably you want to include only files that are explicitly marked. The reason for the code involving `here`, that is, what's returned for a given Dired buffer, is to take care of that nothing-marked case, i.e., to remove the case of a file that's returned because no files are marked. The reason to use `delete-dups` is that it's possible that you have more than one Dired buffer that has the same (marked) file (even the same absolute file name). For example, you might have a Dired buffer for directory `toto`, and one for directory `toto/titi`, and in the buffer for `toto` its subdir `titi` might be inserted, and the same file in directory `titi` might be marked in both Dired buffers. --- Tags: dired ---
thread-64595
https://emacs.stackexchange.com/questions/64595
How was the Emacs Manual typed?
2021-04-27T06:38:06.223
# Question Title: How was the Emacs Manual typed? I have a beautiful hardcopy of the Emacs Manual printed by the FSF. I was wondering if anyone knew how this document was created in Emacs and what mode was used for its creation? I would also be interested to know how the effect of the different fonts was achieved? I am assuming it was typed up in Emacs and that Richard Stallman was the person to have typed it. There does not appear to be specific information in the Manual itself on the process. # Answer It was typed in texinfo. See here: https://www.gnu.org/software/emacs/manual/html\_node/efaq/Getting-a-printed-manual.html > 6 votes --- Tags: documentation, manual ---