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-68803 | https://emacs.stackexchange.com/questions/68803 | Flycheck: Reenable automatically disabled checker? | 2021-10-04T15:19:16.807 | # Question
Title: Flycheck: Reenable automatically disabled checker?
I have slightly tweaked checkers in flycheck so that I can run my code in docker containers. I've tweaked how these settings work, which has temporarily broken my flycheck setup and flycheck has disabled checkers.
I think I've fixed the bug I want to check how it works. If I remember correctly, to get this working before I would repeatedly close and reopen files to clear flychecks automatic disabled checkers... but this time this feels like a stupid approach.
**How do I clear flychecks automatically disabled checkers?**
# Reading
# Answer
> 1 votes
The warning flycheck shows when a checker is automatically disabled explains how to re-enable it:
> Warning (flycheck): Syntax checker ... reported too many errors (...) and is disabled. Use ‘M-x customize-variable RET flycheck-checker-error-threshold’ to change the threshold or ‘C-u C-c ! x’ to re-enable the checker.
This can also be found in the documentation:
```
To enable a disabled checker again, remove it from flycheck-disabled-checkers or use C-u C-c ! x:
C-u C-c ! x
C-u M-x flycheck-disable-checker
Prompt for a disabled syntax checker to enable again in the current buffer.
```
(https://www.flycheck.org/en/latest/user/syntax-checkers.html#key-C-c%20!%20x)
---
Tags: flycheck
--- |
thread-68806 | https://emacs.stackexchange.com/questions/68806 | Why can't I boot Emacs succesfully with this EXWM configuration in my init file? | 2021-10-04T23:21:36.853 | # Question
Title: Why can't I boot Emacs succesfully with this EXWM configuration in my init file?
I have been using Emacs for the last 5 months. However, tiling window managers is totally a new topic for me. This includes EXWM.
Since I am already somewhat familiar with Emacs, I have been trying some tutorials about EXWM. After logging out on Ubuntu and toggling EXWM for the new log, I am able to see a new environment with only emacs being loaded.
Ok. The problem starts when I try inserting this tiny tweak in my `.emacs`:
```
(use-package exwm
:ensure t
:config
(require 'exwm-config)
(exwm-config-default))
```
After the new edition being saved, logging out again, and choosing EXWM for the new log, Emacs now has an odd behavior showing the following error message:
```
Debugger entered--Lisp error: (void-function use-package)
(use-package exwm :ensure t :config (require (quote exwm-config)) (exwm-config-default))
eval-buffer(#<buffer *load*> nil "/home/pedro/.emacs" nil t) ; Reading at buffer position 9029
load-with-code-conversion("/home/pedro/.emacs" "/home/pedro/.emacs" t t)
load("~/.emacs" t t)
#f(compiled-function () #<bytecode 0x1e0f4d>)()
command-line()
normal-top-level()
```
Why is this happening? How can I fix this?
My whole `.emacs` file can be seen here.
# Answer
You’re using `use-package`, but you didn’t set it up correctly. See the Getting Started instructions in the README.
For completeness, I will mirror the first step of those instructions here:
```
;; This is only needed once, near the top of the file
(eval-when-compile
;; Following line is not needed if use-package.el is in ~/.emacs.d
(add-to-list 'load-path "<path where use-package is installed>")
(require 'use-package))
(use-package foo)
```
You can see how it first loads the `use-package` package, and only then uses it.
> 2 votes
---
Tags: use-package, exwm
--- |
thread-68808 | https://emacs.stackexchange.com/questions/68808 | Import thousands of text files into org-mode | 2021-10-05T08:49:29.287 | # Question
Title: Import thousands of text files into org-mode
I have a folder with 3000+ txt files (made in nvALT originally) that I would like to import into an org-mode file.
Preferrably I would like each file name to become a header in the org-file.
The order of the files/headers are not really important, but if possible I would like to add them based on creation date.
Ps. I know about deft, but it really slows down when I have so many files, and I cannot use all the powers of org there.
# Answer
Here's an elisp function that prompts you for a directory name, and then inserts all the `txt` files in that directory into the current buffer. It sorts by last modified time too. If you want to change the file names that it matches, you can modify the string `"txt"` to suit your needs. Or add it as an additional interactive argument.
```
(defun orgify-directory (DIR)
(interactive "DDirectory: ")
(mapc (lambda (elt)
(insert (concat "\n* " ;; insert headline
(file-name-nondirectory (car elt))
"\n\n"))
(insert-file-contents (car elt)) ;; insert file contents
(goto-char (point-max))) ;; jump to end of buffer
(seq-sort-by ;; sort by last modified time
(lambda (elt) (time-to-seconds (nth 6 elt))) #'<
(directory-files-and-attributes DIR t "txt$"))))
```
> 5 votes
---
Tags: org-mode, files, text
--- |
thread-68810 | https://emacs.stackexchange.com/questions/68810 | How to replace ascii codes with characters in custom settings or buffer? | 2021-10-05T14:06:53.757 | # Question
Title: How to replace ascii codes with characters in custom settings or buffer?
I customized `org-tag-alist` using the built-in customization interface. This stored the values in `("tag") . <ascii key value>)` pairs like this:
```
("ez" . 90)
("pin" . 73)
("per" . 61)
("inprog" . 78)
("maybe" . 66)
```
Is there any way to view this data with the ascii codes converted to characters, like this?
```
("ez" . ?Z)
("pin" . ?I)
("per" . ?=)
("inprog" . ?N)
("maybe" . ?B)
```
# Answer
> 2 votes
Just a replace regexp :
```
M-x query-replace-regexp \([[:digit:]]\{2\}\) → \,(format "?%c" (string-to-number \1))
```
instead of `(string-to-number \1)`you could prefer `\#1` .
---
Tags: org-mode, init-file, customize, org-tags, ascii
--- |
thread-66754 | https://emacs.stackexchange.com/questions/66754 | How to prevent org-tags-view from creating latex previews? | 2021-07-19T15:02:09.573 | # Question
Title: How to prevent org-tags-view from creating latex previews?
When running `org-tags-view`, I see a message "Creating Latex previews in buffer..." for 10+ seconds. It appears all files in my org directory are recursively parsed for latex fragments. Is this expected behavior? How would I prevent it?
# Answer
Have you found a solution?
I had a similar problem while using another package (helpful). When I called `helpful-callable`, I got the same message ("Creating Latex previews in buffer...") for a long time.
This is what was happening apparently:
1. I had made org-mode the default major mode for new buffers: my .emacs file had
```
(setq-default major-mode 'org-mode)
```
2. When the `helpful-callable` function created a new buffer, org-mode ran a hook to build latex preview images, showing the message and causing the delay.
3. Everything got back to normal when I commented out that line in my .emacs file.
> 0 votes
---
Tags: org-mode
--- |
thread-68814 | https://emacs.stackexchange.com/questions/68814 | Escape all square brackets with replace-regexp-in-string | 2021-10-05T19:35:25.540 | # Question
Title: Escape all square brackets with replace-regexp-in-string
So I was writing a function that would convert one type of a link (e.g. Org-mode link) to another type (e.g. Markdown), and then I realized that Org-mode doesn't require you to escape square brackets, i.e.,
if you have a link like this:
`[[https://github.com/foo/bar/issues/42][Major issue in [Bar] project]]`
Org mode would have no issues with displaying it (whereas Markdown would). And if you try to convert it to Markdown, you have to escape those square brackets.
Of course, I could do something like the following:
```
(let ((str "Major issue in [Bar] project"))
(replace-regexp-in-string "\\]" "\\\\]"
(replace-regexp-in-string "\\[" "\\\\[" str)))
;; => "Major issue in \\[Bar\\] project"
```
But I think it's possible to achieve the same result by calling the function only once and using optional arguments. Can someone show me how does it work?
# Answer
I have figured it out. It looks like the second argument can be either regexp or a function. So this worked for me:
```
(replace-regexp-in-string
"\\[\\|\\]"
(lambda (x) (format "\\\\%s" x))
"Major issue in [Bar] project")
;; => "Major issue in \\[Bar\\] project"
```
But ultimately, I still don't understand how other parameters, like I have figured it out. It looks like the second argument can be either regexp or a function. So this worked for me:
```
(replace-regexp-in-string
"\\[\\|\\]"
(lambda (x) (format "\\\\%s" x))
"Major issue in [Bar] project")
;; => "Major issue in \\[Bar\\] project"
```
But ultimately, I still don't understand how other parameters, like `SUBEXP` work with this function
**Update:** I popped the question in Doom Emacs Discord and got help from amazing Henrik Lissner himself. Here are the examples he provided, they do help understanding the mechanics better:
<pre><code>(replace-regexp-in-string "^\\(foo\\)bar$" "bar\\1" "foobar")
;; #=> "barfoo"
(replace-regexp-in-string "^\\(foo\\)bar$" "baz\\&" "foobar")
;; #=> "bazfoobar"
(replace-regexp-in-string "^\\(foo\\)bar$" "bar\\1\\&" "foobar" nil t) ; literal = t
;; #=> "bar\\1\\&"
(replace-regexp-in-string "^\\(foo\\)bar$" "bar\\\\1\\\\&" "foobar") ; equivalent to literal = t
;; #=> "bar\\1\\&"
``` work with this function
</code></pre>
> 0 votes
---
Tags: regular-expressions
--- |
thread-68816 | https://emacs.stackexchange.com/questions/68816 | Why emacs opens a menu with the keybinding bound to another command? | 2021-10-05T21:56:37.523 | # Question
Title: Why emacs opens a menu with the keybinding bound to another command?
I want to use the command `just-one-space` which is bound to `M-SPC`, see the describe key associated with it:
Unfortunately, if I press `M-SPC` a menu opens up in Emacs:
I was expecting to execute `just-one-space`.
Why does this happen? Is there a way to fix this?
# Answer
> 1 votes
Emacs didn’t open that menu, your operating system or window manager did. Note that the same thing happens to other key combinations, like `M-Tab` (better known as Alt-Tab).
`M-SPC` opens that same menu for all applications in Windows. Linux computers running Gnome have a similar menu bound to the same keyboard shortcut.
---
Tags: key-bindings, menu-bar
--- |
thread-68819 | https://emacs.stackexchange.com/questions/68819 | How to view single maildir in mu4e-headers? | 2021-10-06T09:02:38.130 | # Question
Title: How to view single maildir in mu4e-headers?
Is there any variable in mu4e setup which allows to view messages from a single maildir in mu4e-headers buffer instead of multiple maildirs?
I am using mu4e and mbsync to read emails from multiple e-mail accounts, say ac1 and ac2. I followed the instructions from the documentation (and some other sources on the web) to set up contexts. There are multiple emails where the multiple email accounts are in Cc or Bcc (e.g. email "To" ac1 with "Cc" to ac2).
My problem is that the mu4e-headers for a specific maildir (say for ac1) shows emails from other maildirs as well (say ac2), if these maildirs contain emails in the same thread.
# Answer
> 1 votes
By default, the key 'W' is bound to `mu4e-headers-toggle-include-related`. Pressing this will toggle between showing all the related messages in every maildir, and showing only the messages in the current maildir.
---
Tags: mu4e
--- |
thread-68826 | https://emacs.stackexchange.com/questions/68826 | Why do I have missing keybindings for magit in spacemacs? | 2021-10-07T07:23:27.017 | # Question
Title: Why do I have missing keybindings for magit in spacemacs?
I am trying to use magit in spacemacs. When I read instructions to use magit, I am instructed to hit `spc` \+ `g` \+ `s`. However, when I push `spc` \+ `g` I see only one shortcut which is `spc` \+ `g` \+ `f` \+ `s`, which is "helm-ls-git-ls". Why do I not have any of the other keybindings? I have checked to make sure magit is installed, and also I have reinstalled the package, but I still not get any of the keybindings. I am at a loss. Any ideas on how to troubleshoot this?
# Answer
I figured out the problem. In my spacemacs dotfile, under my layers function, I had the line git commented out. I have since enabled the git layer and I now have all the associated magit commands.
> 1 votes
---
Tags: key-bindings, spacemacs
--- |
thread-21188 | https://emacs.stackexchange.com/questions/21188 | How to associate more than one file extension with a given mode in `use-package` | 2016-03-23T17:44:35.310 | # Question
Title: How to associate more than one file extension with a given mode in `use-package`
When using `use-package`, is there a way to associate more than one file extension with a particular mode in one place instead of multiple locations?
Case in point is that I would like to associate both `js` and `jsx` files with js2-mode. Currently what I have is:
```
(use-package js2-mode
:mode "\\.js\\'"
:init
(setq js2-highlight-level 3)
(add-hook 'js2-mode-hook (lambda () (auto-revert-mode)
(setq auto-revert-interval 0.1)))
:ensure t)
(add-to-list 'auto-mode-alist '("\\.jsx\\'" . js2-mode))
```
... which I don't like as the extensions are specified in two different places.
# Answer
Use
```
:mode "\\.jsx?\\'"
```
Remember: all those backslashes are there because it's a regexp, so you really want to take advantage of it when you can, otherwise you're just suffering through those backslashes for nothing.
You could also write it
```
:mode "\\.\\(js\\|jsx\\)\\'"
```
or many other ways, of course.
> 10 votes
# Answer
The following should work:
```
(use-package js2-mode
:mode (("\\.js\\'" . js2-mode)
("\\.jsx\\'" . js2-mode))
...
:ensure t)
```
> 15 votes
# Answer
In addition to scatotonic's way you can use this shorter equivalent expression:
```
(use-package js2-mode
:mode
"\\.js\\'"
"\\.jsx\\'")
```
It's not as useful when only doing the two entries, (especially since they can be merged with the regex `"\\.jsx?\\'"`), yet it's really helpful for more generic stuff like `web-mode`.
> 0 votes
# Answer
It's pretty dang flexible... This works, and is my preferred method when the mode name is the same as the package name:
```
(use-package js2-mode
:mode ("\\.js\\'"
"\\.jsx\\'"))
```
I do see why a regex like in Stephan's answer would be nice for the js/jsx case. Here's an example where a single regex may be too complicated and a list of regexs may be preferred:
```
(use-package groovy-mode
:mode ("\\.groovy\\'"
"^Jenkinsfile$"))
```
scatotonic's answer would be my choice if the mode name is different from the package name.
> 0 votes
---
Tags: major-mode, use-package
--- |
thread-68830 | https://emacs.stackexchange.com/questions/68830 | How to run elisp checking utilities from the command line? | 2021-10-07T10:55:48.143 | # Question
Title: How to run elisp checking utilities from the command line?
There are a number of emacs-lisp checking utilities - for example:
* checkdoc.
* package-lint.
* relint.
* byte-code-compilation.
Are there existing ways to quickly run this on an entire project without having to access each individually (for every file)?
for example:
`emacs-check-code *.el`
... would run all the checkers on my elisp files in the current directly, reporting warnings to the console.
---
*Note: I have my own WIP solution, but wanted to avoid reinventing the wheel.*
# Answer
> 3 votes
See the function `batch-byte-compile` which implements the last of your asks. It is invoked as
```
emacs --batch -f batch-byte-compile *.el
```
to compile all the `*.el` files in the current directory. If you want to byte-compile all the the `.el` files under the current directory, you can use `find` and shell facilities:
```
emacs --batch -f batch-byte-compile $(find . -type f -name '*.el')
```
If you have thousands of files, this might not work: you might have to split the invocation in order to keep the length of the command line under the maximum allowed, but in most cases it is fine.
The code of `batch-byte-compile` can serve as an example of how to implement the rest. Basically, it consumes every element of the command line and applies `byte-compile-file` to each `.el` file it finds. As long as each of your tools provides such a function, then you can build the same scaffolding around it to consume every element of the command line. Then you can use utilities like `find` and shell facilities for command line substitution like `$(...)` to build the command line that will be consumed.
---
Tags: batch-mode, script
--- |
thread-68804 | https://emacs.stackexchange.com/questions/68804 | lsp-rust-analyzer ignores edition value in Cargo.toml | 2021-10-04T17:00:31.140 | # Question
Title: lsp-rust-analyzer ignores edition value in Cargo.toml
When talking about Emacs configuration, the rust-analyzer manual mentions
> \[...\] this excellent guide from @rksm.
Which I followed to good effect, in particular:
```
(use-package lsp-mode
:commands lsp
:custom
;; what to use when checking on-save. "check" is default,
;; I prefer clippy.
(lsp-rust-analyzer-cargo-watch-command "clippy")
(lsp-eldoc-render-all t)
(lsp-idle-delay 0.6)
(lsp-rust-analyzer-server-display-inlay-hints t)
:custom-face
(lsp-rust-analyzer-inlay-face ((t (:foreground "dim gray"))))
:config
(add-hook 'lsp-mode-hook 'lsp-ui-mode))
(use-package lsp-ui
:commands lsp-ui-mode
:custom
(lsp-ui-peek-always-show t)
(lsp-ui-sideline-show-hover nil) ; I found this confusing
(lsp-ui-doc-enable nil))
```
However when having an `async fn` in my code, for example as suggested by the rocket.rs guide,
Rust analyzer is complaining about:
```
error[E0670]: `async fn` is not permitted in Rust 2015
--> .../hello-rocket/src/main.rs:16:28
|
16 | #[get("/delay/<seconds>")] async fn delay(seconds: u64) -> String {
| ^^^^^ to use `async fn`, switch to Rust 2018 or later
|
= help: set `edition = "2018"` in `Cargo.toml`
= note: for more on editions, read https://doc.rust-lang.org/edition-guide
```
despite the fact that I already have in my `Cargo.toml`:
```
edition = "2018"
```
My code compiles just fine, and `rust-analyzer diagnostics $PWD` seems to complete without errors.
So I guess my question is: **How should I tell rust-analyzer via `lsp-rust-analyzer` to consider my `Cargo.toml` for the value of `edition`?**
# Answer
It took me some time to realize that `rust-analyzer` was not the one to complain, but the buffer with the error message mentioned above was `*rustfmt*`, and indeed running `rustfmt` on my source file gave me the same error.
As suggested in this (inexplicably closed) issue, one can convince `rustfmt` to behave by adding `edition = "2018"` to `.rustfmt.toml`.
Since I am not expecting to hack on 2015 edition code any time soon, I chosen a different (and more Emacsy) workaround:
```
(use-package rustic
;; ...
:custom
(rustic-rustfmt-config-alist '((edition . "2018")))
;; ...
)
```
Hopefully, I will find a better solution by the time the 2021 edition will come to fruition.
> 1 votes
---
Tags: lsp, rust
--- |
thread-68841 | https://emacs.stackexchange.com/questions/68841 | Different versions of bookmarks for home and office computer | 2021-10-08T14:01:33.583 | # Question
Title: Different versions of bookmarks for home and office computer
Linux Mint 20.2
Emacs 27.2
I installed Emacs 27.2 on my home and office computer. Both computers on LInux Mint 20.2
I has the same `init.el` for both computers. And its very convenient. I push my `init.el` to GitHub. And just use `git pull` to get the latest version of the **SAME** `init.el` for both computers. Nice.
But on my home computer and office computer I has **different** favorites dirs and files. As result I need to store **two versions** of file `bookmarks`. One for home and another for office. I can't push it to Github because the content of this 2 bookmarks's files are different.
So the questions are
1. Is it possible in Emacs to load different version of bookmarks depend on environment - home or office ?
2. Maybe has better solution for this kind of problem?
# Answer
> 3 votes
I can think of at least two ways to handle multiple `bookmarks` files. Firstly, according to the Introduction bookmarks page on the EmacsWiki
> (Bookmark+ makes it easy to have multiple bookmark files – different sets of bookmarks for different uses.)
The second, and more generic option is to just test for your hostname in your init file. This is of course, just one of many ways to do it.
```
;; set bookmark file location
(cond ((eq (system-name) "work.local")
(setq bookmark-default-file "~/.emacs.d/boomarks-work"))
((eq (system-name) "home.local")
(setq bookmark-default-file "~/.emacs.d/boomarks-home"))
(t (setq bookmark-default-file "~/.emacs.d/bookmarks")))
;; load bookmarks package
(require 'bookmark)
```
(NB. Prior to Emacs 25.1 you'd test the *variable* `system-name`, not the *function* `system-name`.)
Elisp's `cond` is akin to a "case statement" in other languages. In `bash` the above would look like:
```
# set bookmark file location
case "$HOSTNAME" in
"work.local") BOOKMARK-DEFAULT-FILE="~/.emacs.d/bookmarks-work" ;;
"home.local") BOOKMARK-DEFAULT-FILE="~/.emacs.d/bookmarks-home" ;;
*) BOOKMARK-DEFAULT-FILE="~/.emacs.d/bookmarks"
esac
# load bookmarks package
source bookmark.sh
```
If you have just a simple test, and don't need a bunch of "elses", then maybe try Elisp's `when`. Let's pretend you want one bookmark file everywhere except at work, which gets its own bookmark file.
```
;; when at work use a special bookmark file. use the default everywhere else
(when (eq (system-name) "work.local")
(setq bookmark-default-file (expand-file "~/.emacs.d/bookmarks-work")))
;; load bookmarks package
(require 'bookmark)
```
Check the Elisp manual page on conditionals for other conditional forms. Remember that your init file isn't "just a config file". It's elisp code, and you can do just about anything with it.
# Answer
> 2 votes
Here my solution:
In init.el file:
```
;; Load host specific files (e.g bookmarks)
(cond ((string-match "laptop" (system-name))
(setq bookmark-default-file "~/.emacs.d/bookmarks-laptop"))
((string-match "workstation" (system-name))
(setq bookmark-default-file "~/.emacs.d/bookmarks-workstation"))
(t (setq bookmark-default-file "~/.emacs.d/bookmarks")))
```
---
Tags: init-file, bookmarks
--- |
thread-68430 | https://emacs.stackexchange.com/questions/68430 | When compiling Emacs on RHEL8 should I better bind to GTK3 or GTK2? | 2021-09-08T01:44:06.947 | # Question
Title: When compiling Emacs on RHEL8 should I better bind to GTK3 or GTK2?
I am compiling Emacs 27.1 on a RHEL8 Linux box. This RHEL system is a remote system I log in from my Windows machine using MobaXterm (Personal Edition V12.1) on the Windows machine as X server.
On this new-ish RHEL system GTk2 and GTK3 is installed. On other Unix machines with older OSes I use GTK2 for Emacs. **Is it better to use GTK3** which is available to me on the RHEL8 system?
# Answer
> 0 votes
Just as a follow-up:
I did install Emacs on the RHEL8 system with GTK3 - and under MobaXterm as X server it does not look as "normal" as the GTK2 build from another machine (the scrollbars have strangely thin handles).
---
Tags: x11, gtk3, widget
--- |
thread-68846 | https://emacs.stackexchange.com/questions/68846 | How change name of file "projects" and set it in init.el? | 2021-10-08T18:05:05.237 | # Question
Title: How change name of file "projects" and set it in init.el?
Emacs 27.2
In `~/.emacs.d/projects`
This file content all my projects.
press `d` But I need to change file name. E.g. `projects-laptop`.
Is it possible and and set it name on `init.el` file?
P.S. For bookmarks has variable: `bookmark-default-file`
But I need same for file `projects`
# Answer
You can customize the variable `project-list-file`. For example, try `(setq project-list-file "~/.emacs.d/projects-laptop")`. The variable docstring says "File in which to save the list of known projects."
I am using Emacs 27.1 and the `project` v0.8 is installed from GNU Elpa.
> 2 votes
---
Tags: init-file, project
--- |
thread-68853 | https://emacs.stackexchange.com/questions/68853 | company-mode popups and magit current region are dark while current theme is light | 2021-10-09T09:30:23.687 | # Question
Title: company-mode popups and magit current region are dark while current theme is light
I've been successfully using `lsp-mode` and `magit` for a while with a **light theme** (leuven).
Today I was messing with something seemingly unrelated (`company-mode` and `auto-complete` settings in my `~/.emacs` file) and all of a sudden popups in `lsp-mode` \+ `company-mode` appear as if in a dark theme:
The same goes now in `magit` for the area where the cursor is:
Needless to say, it's all unreadable now!
How can I get the light colours back?
My `~/.emacs` contents are here, if it helps: https://pastebin.com/Hph4VXvH
Thanks!
# Answer
The problem was this from my `~/.emacs` file:
```
'(frame-background-mode 'dark)
'(hl-sexp-background-color "#1c1f26")
```
I'm not really sure how it got there, but setting `frame-background-mode` to nil (so that it will be set according to theme) and commenting the second line did the trick:
```
'(frame-background-mode 'nil)
;; '(hl-sexp-background-color "#1c1f26")
```
> 3 votes
---
Tags: magit, company-mode, themes, colors, popup
--- |
thread-68840 | https://emacs.stackexchange.com/questions/68840 | Is there a way to include heading in link from org-outlook | 2021-10-08T12:49:41.703 | # Question
Title: Is there a way to include heading in link from org-outlook
'New to OrgMode'
I am using org-outlook to capture email from outlook as task. I have a file ToDo.org with different multi-level headings. Looking for a way to put task under a specific heading.
Right now I am using file+function in capture template:
```
("u" "mycv" entry (file+function "~/Private/OrgMode/ToDo.org"
(lambda () (let ((org-goto-interface 'outline-path-completion))
(org-goto))))
```
This gives me an option to select heading/sub-heading from file but but I want to automate this step as well, if I can read Heading info from the link coming from outlook. I can customize VBA to include any info...
# Answer
If you know the filename and the sequence of headlines under which you want to capture the new item, then you just need a `file+olp` target as described in the doc string of `org-capture-templates`. The entry would look like this:
```
("u" "mycv" entry (file+olp "~/Private/OrgMode/ToDo.org" "Level 1 Headline" "Level 2 Headline" ...) <some template>)
```
If the headline under which you want the new item is unique in the file, you can get away with a simpler target: `(file+headline <file> <headline>)`, but the full-path specification of `file+olp` is safer in the long term.
See the doc string of `org-capture-templates` with `C-h v org-capture-templates`:
> ```
> ...
> (file+headline "path/to/file" "node headline")
> Fast configuration if the target heading is unique in the file
>
> (file+olp "path/to/file" "Level 1 heading" "Level 2" ...)
> For non-unique headings, the full outline path is safer
> ...
>
> ```
*EDIT*: if you want the outline path to be dynamically constructed, then you'll have to construct the `org-capture-templates` entry at runtime, and let-bind `org-capture-templates` around a call to `org-capture` in a function of your own. Since you don't provide an interface, I'm going to make some assumptions and write a function based on those assumptions, but I hope what you have to do will be clear enough so that you can tweak the function to your requirements.
The basic assumption is that somebody constructs a list of headlines under which the new item is to be inserted. The list is sorted by headline level, so that if you want the new entry to go into a file `my.org` under the following headlines:
```
* foo
** bar
*** baz
<new item goes here>
```
the required list will be `("foo" "bar" "baz")` in that order.
Based on that assumption, you can write a function that takes the path of the file, an olp list and the text of your new entry as arguments and does what it needs to have the new entry inserted in the specified place:
```
(defun my/insert-item-in-olp-hierarchy (path olp entry)
(let ((org-capture-templates
`(("u" "mycv" entry
(file+olp ,path ,@olp)
,(format "* This is my new entry: %s" entry)
:immediate-finish t))))
(org-capture nil "u")))
```
You call it with something like this: `(my/insert-item-in-olp-hierarchy "~/org/foo.org" '("foo" "bar" "baz") "My new entry")`
The first level `foo` heading, second level `bar` heading and third level `baz` heading *MUST* already exist in the file or else you'll get an error. The new entry is inserted at the fourth level as specified by the template in the let-bound `org-capture-templates`. The function uses the `backquote` mechanism (read about it in the elisp manual: `C-h i g(elisp)Backquote`) to substitute in the path of the file and splice in the outline path list, as the `file+olp` entry type expects. And we specify `:immediate-finish t`, so that the new entry is entered directly in the file, without popping up a buffer to edit it before submitting it, since it's supposed to be self contained. For these details, careful study of the `org-capture-templates` doc string is warranted: see above for how to get the doc string.
This is just an example and you'll have to adapt it to your circumstances, but I think it contains all of the important elements you are looking for. Good luck!
> 0 votes
---
Tags: org-mode, org-capture
--- |
thread-68837 | https://emacs.stackexchange.com/questions/68837 | Use basename of the file | 2021-10-08T10:46:46.903 | # Question
Title: Use basename of the file
When I am done editing myfile.tex, I `M-x shell-command RET`. At the prompt, I manually enter `pandoc -s myfile.tex -o myfile.org`.
What command will save me the trouble of having to type out the myfile part everytime? So, a command like:
`pandoc -s takethebasename.tex -o takethebasename.org`
Then I can use it on `myfile.tex`, `yourfile.tex` and `hisfile.tex`. :)
# Answer
To expanding on @NickD's answer, I like to do these kind of shell operations with `compile` so I can take advantage of the instantly visible window with the "compile" command's output. Taking the original example I'd do `M-x``compile``Return``C-a``C-k``pandoc -s myfile.tex -o myfile.org``Return`. On subsequent runs I'd just do `M-x``Up``Return``Return` to run the same command again.
But, we want something more dynamic because we're editing multiple `.tex` files. Continuing our ad-hoc theme, we can use `eval-expression`. `M-:``(compile (format "pandoc -s %s.tex -o %s.org" (file-name-base buffer-file-name) (file-name-base buffer-file-name)))``Return`. Now, we only have to enter this once in our session because we cause use the minibuffer history again to get back to it and run it on a new buffer with `M-:``Up``Return`. This method also "feeds" `compile`. Say I'm editing `foo.tex`, and I want to "compile" it for the first time. I'll do the previous `eval-expression`. The second time I want to "compile" I could use `eval-expression`'s minibuffer history, or I could do `M-x``compile``Return`, and be greeted with `compile`'s prompt: `Compile command: pandoc -s foo.tex -o foo.org`. If you've run the `eval-expression` on `bar.tex` and `baz.tex`, then you could search `compile`'s minibuffer history for their constructed statements too.
Is it a better way? No, probably not. @NickD's would be the way to go. But, it's different and it shows off `eval-expression`.
> 3 votes
# Answer
Write your own function to prepare the command string as you want it and then pass it to `shell-command` for execution:
```
(defun pandoc-it ()
(interactive)
(let* ((basename (file-name-base (buffer-name)))
(cmd (format "pandoc -s %s.tex -o %s.org" basename basename)))
(shell-command cmd)))
```
and execute it with `M-x pandoc-it RET`. You can also bind it to a key.
> 4 votes
# Answer
Write a file called `Makefile` containing:
```
all: takethebasename.org otherfile.org more-space-separated-file-names.org
%.org: %.tex
⇥pandoc -s $< -o $@
```
Replace ⇥ by a tab character (press `Tab`: when editing a makefile, this will insert a tab character instead of indenting).
Then running `make` will run pandoc to generate the `.org` file(s). And that's the default command for `M-x compile`.
Explanation of the make features used here:
* `foo: bar` instructs make that to *build* the file `foo`, it needs the file `bar`. Make calls `foo` a *target* and calls `bar` a *dependency*.
* If you run `make`, it builds the first target. If you run `make target-name other-target-name`, it builds the listed targets.
* In `%.org: %.tex`, the `%` sign is a wildcard, so this allows building any `.org` file from the corresponding `.tex` file.
* Lines beginning with tab are commands to build the files. The `all` target has no commands, so `make all` only requires building the listed `.org` files and not running extra commands. Building each `.org` file requires running pandoc.
* In the command, `$<` stands for the first dependency and `$@` stands for the target.
* `make` won't run the commands if the target already exists and is more recent than the dependencies (it considers the target *up-to-date*).
`make` is usually installed by default on Unix-like systems (if not, install the `make` package). On Windows you'll need some port of Unix tools.
> 0 votes
---
Tags: shell, shell-command
--- |
thread-68860 | https://emacs.stackexchange.com/questions/68860 | How to ask for confirmation before killing any new modified buffer? | 2021-10-09T16:41:12.637 | # Question
Title: How to ask for confirmation before killing any new modified buffer?
What's the best way to prompt for confirmation before killing any modified buffer, including **new** buffers created by `evil-buffer-new`, which creates a buffer without an associated filename. Modified file buffers already have confirmation, but modified new buffers without an associated filename don't. I'd like to ask for confirmation on these buffers too, whether the kill is by `kill-this-buffer`, `restart-emacs` or any other means.
# Answer
Use `kill-buffer-hook`. But you probably don't want to force confirmation when a temporary buffer ( `*...`) gets killed.
Add this or similar to your init file:
```
(defun foo ()
(unless (or (string-match-p "^ [*]" (buffer-name))
(y-or-n-p
(format "Are you sure you want to kill buffer `%s'? "
(current-buffer))))
(error "OK, buffer `%s' not killed" (current-buffer))))
(add-hook 'kill-buffer-hook 'foo)
```
> 0 votes
# Answer
Instead of erroring out from the hook, you apparently can use the variable `kill-buffer-query-functions`, which seems to be made specially for that.
```
(defun my/confirm-closing-buffer ()
(or (string-match-p "^ [*]" (buffer-name))
(y-or-n-p (format "Are you sure you want to kill buffer `%s'? " (buffer-name)))))
(add-to-list 'kill-buffer-query-functions #'my/confirm-closing-buffer t)
```
> 0 votes
---
Tags: buffers, evil, hooks, kill-buffer, confirmation
--- |
thread-68856 | https://emacs.stackexchange.com/questions/68856 | How to read the shell environment variables? | 2021-10-09T10:05:46.670 | # Question
Title: How to read the shell environment variables?
I have the following command in my `.emacs`
```
(setq org-roam-directory
(concat (getenv "BASEDIR") "/data/org-roam/"))
```
The purpose is to the set the directory for `org-roam` (but really it could be any other package) on different systems where the variable `$BASEDIR` has different paths. `$BASEDIR` is defined in `.bashrc`. This works well if I start emacs from the command line, but fails if emacs is started from, e.g., the file manager. Is there a way to have emacs read the shell environment variables at startup, regardless on how it is launched?
**EDIT**: I am running Ubuntu and Arch with GNOME. The file manager is graphical (nautilus or double commander) but of course this also happens if emacs is launched from the apps menu.
# Answer
aaa is right. You might try setting `$BASEDIR` in `~/.profile`. That file is read when you log in to Gnome, while `~/.bashrc` is read when you open up a terminal, basically. (Note that Bash as a login shell doesn't parse `~/.profile` if either `~/.bash_profile` or `~/.bash_login` exists.)
Alternatively you could try is using `(shell-command-to-string "$SHELL --login -c 'echo $BASEDIR'")` instead of `(getenv "BASEDIR")`. See How to get the PATH from the SHELL
> 2 votes
---
Tags: shell, variables, environment
--- |
thread-68869 | https://emacs.stackexchange.com/questions/68869 | Find out where "Text is read only" coming from | 2021-10-10T13:58:41.167 | # Question
Title: Find out where "Text is read only" coming from
My workflow involves converting a huge generated org-mode document that is created in a read only buffer and is automatically put together. When trying to export it to latex, sporadically I get the "Text is read only" error which is apparently hidden behind some `unwind-protect` somewhere because `toggle-debug-on-error` does not catch it. I have no good way of debugging this because I can't reproduce it for small documents so finding out the stacktrace of the error feels like the right way to go.
So my question is: is it possible to tell `toggle-debug-on-error` to also collect errors that are behind `unwind-protect`? I assume there are many such errors that are thrown and siletly handled during the process of export so I assume the feature I am looking for would *collect* rather than *immediately show me* the stack traces of the errors it encounters.
Note that while my problem is specific to org-mode and I would accept an answer that solves the particular one, I would appreciate an answer that helps me find the actual stacktrace.
# Answer
While writing the question the answer occured to me but I finished writing it for posterity: `unwind-protect` does not inhibit errors caught by `debug-on-error`, only `condition-case` does, which I don't know how to override but fortunately this was not the case for me, the error is ignored due to the value of `debug-ignored-errors` containing the symbol `buffer-read-only`. Removing that from the variable allowed the error handler to show me the stack trace.
As for the actual problem, the issue was that org babel was trying to evaluate my code blocks.
> 2 votes
---
Tags: debugging, error-handling
--- |
thread-68845 | https://emacs.stackexchange.com/questions/68845 | How to programmatically mark files in dired based on file modification time? | 2021-10-08T17:04:49.550 | # Question
Title: How to programmatically mark files in dired based on file modification time?
I'd like to write a bit of elisp to mark all files in a dired buffer that are "old": the files were last modified more than 10 days ago, say.
What would be a good way to do that? It seems there are functions to mark files in a dired buffer based on their name, using a regexp or whatever, but I don't see anything that handles file metadata other than the name.
# Answer
> I don't see anything that handles file metadata other than the name.
That's exactly the purpose of command **`dired-mark-sexp`**. Use a Lisp sexp to match files, where the sexp can use (pseudo-)variables whose values are file metadata values.
You can use the command interactively or use it or some of its code from Lisp.
You can use (pseudo-)variable **`time`** in the sexp you use for marking -- compare some given time with the value of `time` for each file.
Here's the doc string. (This is the doc for the version from Dired+, which enhances the vanilla version in relatively minor ways -- you can use the vanilla version for what you want just as easily.)
> **`dired-mark-sexp`** is an interactive compiled Lisp function in `dired+.el`.
>
> It is bound to `M-(`, `* (`, `menu-bar mark marks-mark marks-mark-sexp`.
>
> `(dired-mark-sexp PREDICATE &optional UNMARK-P)`
>
> Mark files for which PREDICATE returns non-`nil`.
>
> With a prefix arg, unmark or unflag those files instead.
>
> `PREDICATE` is a lisp sexp that can refer to the following symbols as variables:
>
> * `mode` \[string\] file permission bits, e.g. `"-rw-r--r--"`
> * `nlink` \[integer\] number of links to file
> * `size` \[integer\] file size in bytes
> * `uid` \[string\] owner
> * `gid` \[string\] group (If the `gid` is not displayed by `ls`, this will still be set (to the same as `uid`))
> * `time` \[string\] the time that `ls` displays, e.g. `"Feb 12 14:17"`
> * `name` \[string\] the name of the file
> * `sym` \[string\] if file is a symbolic link, the linked-to name, else `""`
> * `inode` \[integer\] the inode of the file (only for `ls -i` output)
> * `blks` \[integer\] the size of the file for `ls -s` output (ususally in blocks or, with `-k`, in Kbytes)
>
> Examples:
>
> * Mark zero-length files: \`(equal 0 size)'
> * Mark files last modified on Feb 2: \`(string-match "Feb 2" time)'
> * Mark uncompiled Emacs Lisp files (`.el' file without a` .elc' file):
>
> First, Dired just the source files: `dired *.el`.
>
> Then, use `M-(` with this sexp:
>
> ```
> `(not (file-exists-p (concat name "c")))`
>
> ```
>
> There's an ambiguity when a single integer not followed by a unit prefix precedes the file mode: It is then parsed as inode number and not as block size (this always works for GNU coreutils `ls`).
>
> Another limitation is that the `uid` field is needed for the function to work correctly. In particular, the field is not present for some values of `ls-lisp-emulation`.
>
> This function operates only on the Dired buffer content. It does not refer at all to the underlying file system. Contrast this with `find-dired`, which might be preferable for the task at hand.
> 2 votes
# Answer
If you use library`find-dired+.el` then you can use command **`find-time-dired`**. (You can also call it from Lisp or use part of its code, if you prefer.)
It puts only the selected files in a Dired buffer. You can then mark them all (or some subset).
Here's the doc string:
> **`find-time-dired`** is an interactive Lisp function in `find-dired+.el`().
>
> ```
> (find-time-dired DIR MIN-TIME MAX-TIME
> &optional DEPTH-LIMITS EXCLUDED-PATHS)
>
> ```
>
> **Find files in directory `DIR` newer or older than a timestamp**.
>
> The output is shown in a Dired buffer.
>
> * `MIN-TIME` is a `format-time` string parsable by `parse-time-string`, such as `"2014-12-25 23:59:00"`. Only files newer than this are shown. If `MIN-TIME` is `nil` or a string matching regexp `"^\s-*$"`, there is no lower time limit.
> * `MAX-TIME` is also a `format-time` string parsable by `parse-time-string`. Only files older than this time are shown. If `MAX-TIME` is `nil` or a string matching regexp `"^\s-*$"`, the upper time limit is the current system time.
>
> Optional arg `DEPTH-LIMITS` is a list `(MIN-DEPTH MAX-DEPTH)` of the minimum and maximum depths. If `nil`, search directory tree under `DIR`.
>
> Optional arg `EXCLUDED-PATHS` is a list of strings that match paths to exclude from the search. If `nil`, search all directories.
>
> If args `DEPTH-LIMITS` and `EXCLUDED-PATHS` are both non-`nil` then the command run is essentially the following:
>
> ```
> find . -mindepth MIN-DEPTH -maxdepth MAX-DEPTH
> \( -path EXCLUDE1 -o -path EXCLUDE2 ... \)
> -prune -o \( -TIME-SWITCH -SINCE-MIN -TIME-SWITCH +SINCE-MAX \)
> LS-SWITCHES
>
> ```
>
> where:
>
> * `EXCLUDE1`, `EXCLUDE2`... are the `EXCLUDED-PATHS`, but shell-quoted.
> * `TIME-SWITCH` is `find-diredp-time-prefix' concatenated with` "min"\`.
> * `SINCE-MIN` is the elapsed time since `MIN-TIME` in minutes.
> * `SINCE-MAX` is the elapsed time since `MAX-TIME` in minutes.
> * `LS-SWITCHES` is `(car find-ls-option)`.
> 1 votes
# Answer
Working off of Drew's answer with the vanilla `dired-mark-sexp`, something that works in full generality is pretty tricky, since the `time` variable is the formatted date/time string, and I'd need to parse all the different display formats into something structured: seconds since the epoch, or some other easily-parseable data structure.
There's probably a pretty good library or example code out there for that, but my use-case has a pretty simple heuristic that will work: look for times that don't have a colon in them.
The default `dired` / `ls` format appears to switch from showing the time to just showing a date for files that are six months old. That's good enough for me, so one answer to my question is: if your definition of "old" is "six months ago / whenever `ls` stops displaying times", then this will work:
Call `dired-mark-sexp` and for the predicate, use `(not (string-match-p ":" time)`.
> 0 votes
# Answer
Another option, and probably the most direct and best answer to my specific question, is `find-dired` with an argument of `-ctime +NDAYS`. Then in the resulting dired buffer, do `* t` to mark all the files (presuming you haven't marked any yet; `* t` toggles the marked state of all the files in the dired buffer.)
The only problem for me is that I'm using emacs on Windows and I'm not sure if I have a working version of `find`.
> 0 votes
---
Tags: dired
--- |
thread-68745 | https://emacs.stackexchange.com/questions/68745 | web dev environment setup | 2021-09-30T19:16:04.200 | # Question
Title: web dev environment setup
I wish to setup a web dev environment with emacs, I search it and some post looks like a little bit old. I do not want it very professional but basic web dev is enough such as edit javascript and update output to browser, and see debug console from browser etc.
Any simple setup for basic web dev?
# Answer
Install **skewer-mode** and **js2-mode**, then following below work flow:
1. Add below config into `init.el`:
```
(add-hook 'js2-mode-hook 'skewer-mode)
(add-hook 'css-mode-hook 'skewer-css-mode)
(add-hook 'html-mode-hook 'skewer-html-mode)
(require 'simple-httpd)
;; set root folder for httpd server
(setq httpd-root default-directory)
```
2. Start Emacs from one directory, say `/home/user/demo`.
3. Create `index.html` and `script.js`. `index.html` must include below line to communicate with Chrome: `<script src="/skewer"></script>`
4. Open Emacs with `script.js`, then run `M-x httpd-start` to start HTTP server
5. Open Chrome with URL `http://localhost:8080/index.html`, then open debug console.
6. In Emacs Javascript, press `C-c C-k` to send current buffer to Chrome browser.
> 2 votes
---
Tags: web-mode
--- |
thread-68877 | https://emacs.stackexchange.com/questions/68877 | What is the difference between C-x and C-c and the concept behind it? | 2021-10-11T09:43:43.143 | # Question
Title: What is the difference between C-x and C-c and the concept behind it?
I was asking a similar question about the main concept behind default emacs key bindings. But this one is more specific to `C-c` and `C-x`.
I know and use some commands/functions/features bind to `C-c` or `C-x` by default. I also have my own cheat sheet for that.
The **problem** ist that I often got the two mixed up. It would help my brain to understand the concept (if there is one) behind that two major keys. Most of time I remember the key-binding for a special command but did not remember if I need to start it with `C-c` or `C-x`.
Are there a special type of function always going to `C-c` and another type that always (or most) goes to `C-x`.
# Answer
The normal `C-x` keymap is for global bindings which are expected to do something regardless of the active modes. Conversely:
> Sequences consisting of ‘C-c’ followed by a control character or a digit are reserved for major modes.
>
> Sequences consisting of ‘C-c’ followed by ‘{’, ‘}’, ‘\<’, ‘\>’, ‘:’ or ‘;’ are also reserved for major modes.
>
> Sequences consisting of ‘C-c’ followed by any other ASCII punctuation or symbol character are allocated for minor modes.
-- `C-h``i``g` `(elisp)Key Binding Conventions`
Also:
> Sequences consisting of ‘C-c’ and a letter (either upper or lower case) are reserved for users.
Although those would commonly be global bindings.
> 9 votes
---
Tags: key-bindings, prefix-keys
--- |
thread-68881 | https://emacs.stackexchange.com/questions/68881 | Search and replace in multiples files at once by having them all open as a buffer? | 2021-10-11T12:51:31.027 | # Question
Title: Search and replace in multiples files at once by having them all open as a buffer?
I've done this before in emacs but I can't remember how or which plugins were involved.
Basically you marked a bunch of files according to a file extension, and then you got asked for a search string, and finally it **opened all files that matched the string as a long list of buffers/windows.**
This entire list of buffers/windows was easy to modify as ordinary text after which you could save them all to save the changes.
I've searched for "search replace multiple files in emacs" but all the results seem to point to a replace behaviour that is static rather than having all the files as actual buffers.
So the question is, which plugin or command may this have been?
# Answer
This is `helm-ag`.
More info here: https://yamadapc.github.io/posts/emacs/workflow/2015/03/11/using-helm-ag.html
> 1 votes
---
Tags: search, replace
--- |
thread-68886 | https://emacs.stackexchange.com/questions/68886 | Ediff in one frame | 2021-10-11T18:27:56.203 | # Question
Title: Ediff in one frame
I want to start Ediff in a single frame the way `pacfiles` does:
Right now it opens the control panel in a separate frame.
# Answer
You're looking for `ediff-setup-windows-plain`, which does everything in one frame.
`M-x customize-variable` `RET` `ediff-window-setup-function` and set the value to `ediff-setup-windows-plain`.
> 1 votes
---
Tags: ediff
--- |
thread-68879 | https://emacs.stackexchange.com/questions/68879 | How can I recursively find and replace in the current git repository | 2021-10-11T12:29:43.267 | # Question
Title: How can I recursively find and replace in the current git repository
I am working inside a git-repo. Here I want to apply my search operation based on the root directory of the git repo that current buffer is open.
Here I do: `find-dired "~/my_project" ...` in order to replace all Python files.
```
(defun my-find-files ()
(interactive)
(message "press t to toggle mark for all files found && Press Q for Query-Replace in Files...")
(find-dired "~/my_project" "-name \\*.py ! -name flycheck_\\*.py ! -name __init__.py"))
(global-set-key (kbd "M-z") 'my-find-files)
```
Instead how can I set `"~/my_project"` folder path dynamically based on the current buffer's root git repo.
`git rev-parse --show-toplevel` returns the root of the git repository where the file lives. I was wondering would it be possible to pass its return value instead of `"~/my_project"`?
Related: Using Emacs to recursively find and replace in text files not already open
# Answer
> 2 votes
You can use `(vc-git-root (buffer-file-name))` in place of "~/my\_project". It walks up the tree until it finds the directory that contains the `.git` subdir and declares that to be the root of the repo.
# Answer
> 3 votes
You can use `project-find-regexp` (`C-x p g`), from `project.el`, to find the regexp you are looking for and in the resulting buffer you can hit `r` (`xref-query-replace-in-results`) to replace what you need.
If your Emacs version does not come with `project.el` already built-in, you can get it from ELPA: https://elpa.gnu.org/packages/project.html
# Answer
> 0 votes
* Install counsel (https://elpa.gnu.org/packages/counsel.html)
* `M-x counsel-git-grep`
* Press `C-c C-o` or `M-x ivy-occur` to export result to a buffer in `ivy-occur-grep-mode`
* Press `C-x C-q` or `M-x ivy-grep-change-to-wgrep-mode` to switch to `wgrep-mode` and make the buffer editable
* Edit the buffer and press `C-c C-c` or `M-x wgrep-finish-edit` to commit the changes of the buffer. Then corresponding files will be updated
I use counsel&ivy because it provides the integration of `wgrep-mode`. Other completion/filter frameworks (helm, eg) could do the same thing.
Or you could integrate `wgrep-mode` into your own grep command.
Here is an example I grep my "emacs.d" and export the result of the buffer in `wgrep-mode`,
The key technology is `wgrep-mode`. You can edit one text buffer and change multiple files in one shot. Many techniques could be applied the text buffer first. For example, if I don't want to touch `README.org`, I just delete the line containing `README.org`.
---
Tags: dired, git, replace, find-dired
--- |
thread-68893 | https://emacs.stackexchange.com/questions/68893 | Change the case of slide headings generated by org-reveal | 2021-10-12T09:34:06.727 | # Question
Title: Change the case of slide headings generated by org-reveal
I'm using org-reveal to make a slide presentation. Several of the reveal themes appear to force headings to be shown on the html slides with all letters in uppercase.
Instead, I'd like the case in the html slide to be the same as in the .org file. Is there a straightforward way to do this (ideally as a configuration option rather than a custom css file)?
# Answer
Since the exporter does not change the case (at least in my simple experiments, there is no difference in the headings when I look at the HTML file), then it must be the JS or CSS that does that, so I suspect you will indeed have to modify the theme: I don't think you can do it with options on the Org mode side.
When I look into e.g. `moon.css`, I see this:
```
.reveal h1,
.reveal h2,
.reveal h3,
.reveal h4,
.reveal h5,
.reveal h6 {
margin: 0 0 20px 0;
color: #eee8d5;
font-family: "League Gothic", Impact, sans-serif;
line-height: 0.9em;
letter-spacing: 0.02em;
text-transform: uppercase;
text-shadow: none; }
```
I would try getting rid of that `text-transform` in the CSS file.
> 0 votes
---
Tags: org-mode, org-reveal
--- |
thread-68894 | https://emacs.stackexchange.com/questions/68894 | How to avoid the prompt in `revert-buffer` | 2021-10-12T13:21:39.193 | # Question
Title: How to avoid the prompt in `revert-buffer`
I'm trying to get rid of the annoying prompt at the end of `revert-buffer`. This prompt would make sense in a lesser text editor where reverting the buffer is an irreversible action (pardon the pun). However, most of the time when I want to revert buffer I actually want it to do that, and do it right away.
One solution I've come up with was to call the non-interactive counterpart of the `revert-buffer` function
```
(global-set-key (kbd "C-r") (lambda () (revert-buffer nil t t))
```
but this for some reason ignores the second optional argument and still prompts me.
# Answer
> 1 votes
I use this (and in keeping with the MS Windows key for reverting I bind it to `<f5>`). It's similar to what you're using, but not quite the same. I've been using it for a ***l o n g** *t i m e** .
```
(defun revert-buffer-no-confirm ()
"Revert buffer without confirmation."
(interactive) (revert-buffer t t))
```
# Answer
> 1 votes
I believe you can set "revert-without-query" to t.
---
Tags: interactive, revert-buffer
--- |
thread-60063 | https://emacs.stackexchange.com/questions/60063 | Remove multiple blank lines in a buffer, leave one | 2020-08-11T17:47:18.083 | # Question
Title: Remove multiple blank lines in a buffer, leave one
I'd like to take a buffer which looks like this:
```
one
two
three
four
five
```
And turn it into this
```
one
two
three
four
five
```
I've tried using `delete-blank-line`, however, it will only effect the area around the cursor, and I'd like to do the whole buffer (or at least the whole region). I've also tried various permutation of `replace-regexp` but I have not been able to find a regexp that works.
# Answer
> 1 votes
Have you tried
```
(replace-regexp "^\n+" "\n")
```
Replace any number of blank lines with one blank line. This works regardless of the end-of-line style (Unix,DOS,Mac).
Interactively, you can do the same by entering the newlines as literal newline characters, i.e.
```
M-x query-replace-regexp ^C-qC-jC-qC-jRETC-jRET
```
# Answer
> 0 votes
Tried lots of solutions and none worked for me. After much trials and errors this is what worked for me (GNU Emacs 27.1 (build 1, x86\_64-w64-mingw32) of 2020-08-22).
The idea is to match all blank lines that may or may not contain spaces at once (many solutions only match one blank line for each match), and then replace them with just one blank line. To match these blank lines use the pattern `\(^ *^J\)+` where `^J` is the newline character and it should be entered with `quoted-insert`, i.e., `C-q C-j`. The actual input sequence would be this:
```
M-x query-replace-regex RET ^ \ ( ^ SPC * C-q C-j \ ) + RET C-q C-j
```
---
Tags: regular-expressions, replace, newlines
--- |
thread-68899 | https://emacs.stackexchange.com/questions/68899 | Recalculate All Org-Mode Tables at Once Ending with Summary Table | 2021-10-12T19:11:23.380 | # Question
Title: Recalculate All Org-Mode Tables at Once Ending with Summary Table
Suppose I'm creating a Christmas list and tracking the gifts I am getting for people using `org-tables`. I have a named table for each group of people I am getting gifts for. These tables contains product & price info. I also have a summary table that gathers the totals for each table and puts them in their own table with a final total.
Is there a way that I can recalculate the summary table and it will go through each named table and perform a recalculation of each sub-group?
Below is a reproducible example of what I am talking about:
```
#+TBLNAME: Summary
| ! | Group | Total |
|---+----------+-------|
| # | Kids | 208 |
| # | Spouse | 350 |
| # | Parents | 155 |
| # | Siblings | 205 |
|---+----------+-------|
| # | Total: | 918 |
| ^ | | tot |
#+TBLFM: $3=remote($Group,$tot)::$tot=vsum(@-I..@-II)
#+TBLNAME: Kids
| | Product | Price |
|---+------------+-------|
| | Video Game | 60 |
| | Doll House | 38 |
| | Skateboard | 60 |
| | Books | 50 |
|---+------------+-------|
| | Total: | 208 |
| ^ | | tot |
#+TBLFM: $tot=vsum(@-I..@-II)
#+TBLNAME: Spouse
| | Product | Price |
|---+---------+-------|
| | Jewlery | 120 |
| | Clothes | 60 |
| | Pottery | 80 |
| | Books | 90 |
|---+---------+-------|
| | Total: | 350 |
| ^ | | tot |
#+TBLFM: $tot=vsum(@-I..@-II)
#+TBLNAME: Parents
| | Product | Price |
|---+---------------+-------|
| | Picture Frame | 45 |
| | Books | 50 |
| | Records | 60 |
|---+---------------+-------|
| | Total: | 155 |
| ^ | | tot |
#+TBLFM: $tot=vsum(@-I..@-II)
#+TBLNAME: Siblings
| | Product | Price |
|---+----------------+-------|
| | Sewing Machine | 145 |
| | Flannel | 60 |
|---+----------------+-------|
| | Total: | 205 |
| ^ | | tot |
#+TBLFM: $tot=vsum(@-I..@-II)
```
I don't mind have to perform the recalculation for each row in the summary table, but suppose I edit the `Kids` table. If I don't manually recalculate the `Kids` table, the `Summary` table will not update either.
# Answer
> 2 votes
The easiest, but not necessarily the most efficient way to do that, is to use `org-table-iterate-buffer-tables`: that will try updating all the tables until there is no change in the buffer.
I would add an elisp src block to run that:
```
#+name: recalc
#+begin_src elisp
(org-table-iterate-buffer-tables)
#+end_src
```
Pressing `C-c C-c` on the source block will evaluate it and that in turn will iterate the recalculation of every table in the buffer, until it converges - or after 10 iterations when it decides it is not going to converge. Naming the source block allows you to sprinkle calls to it in the file:
```
#+call: recalc()
```
so that you don't have to go far to find a place where you can trigger recalculation: `C-c C-c` on one of the `#+call:` lines will do that.
---
Tags: org-mode, org-table, formula
--- |
thread-68901 | https://emacs.stackexchange.com/questions/68901 | Passing variable to a function consisting of multiple components | 2021-10-12T21:05:06.470 | # Question
Title: Passing variable to a function consisting of multiple components
Consider the following example:
```
(defun glue (str1 str2)
(format "%s%s" str1 str2))
(setq str1 "Hello, ")
(setq str2 "World!")
(insert (glue str1 str2))
```
This inserts `Hello, World!` into a buffer.
I want to let the user define the format set in `(format "%s%s" str1 str2)`.
For example:
```
(defun glue (str1 str2)
(format "%s%s" hw))
(setq str1 "Hello, ")
(setq str2 "World!")
(insert (hw))
(setq hw (str2 str1))
```
This should return `World!Hello,`
However this returns `Symbol’s function definition is void: hw`
How can I set `hw` so it can be passed to `(format "%s%s" hw)`?
# Answer
I assume your starting point is
```
(defun glue (arg)
(format "%s%s" arg))
(setq str1 "Hello, ")
(setq str2 "World!")
(setq hw (list str2 str1))
(insert (glue hw))
```
You'll have to change `glue`. You need to pass two arguments to `format` after the format string, and `(format "%s%s" arg)` only passes one, no matter what `arg` is.
One possibility is to call `format` via the `apply` function. `apply` takes a list argument and calls the function with the arguments in the list (in addition to the ones that come before the list).
```
(defun glue (arg)
(apply #'format "%s%s" arg))
(setq str1 "Hello, ")
(setq str2 "World!")
(setq hw (list str2 str1))
(insert (glue hw))
```
Another possibility is to make `glue` take an arbitrary number of arguments and pass the whole list forward to `format`. This again involves `apply`.
```
(defun glue (&rest args)
(apply #'format "%s%s" args))
(setq str1 "Hello, ")
(setq str2 "World!")
(setq hw (list str2 str1))
(insert (apply #'glue hw))
```
> 1 votes
---
Tags: arguments
--- |
thread-68904 | https://emacs.stackexchange.com/questions/68904 | How can I write holiday list to a file? | 2021-10-13T03:50:28.163 | # Question
Title: How can I write holiday list to a file?
In Emacs I can evaluate the following to get a list of holidays:
```
(list-holidays 2020 2021)
```
But I need to have the list written to a file. I have tried this:
```
(progn (list-holidays 2020 2021) (write-file \"myholidays.txt\"))
```
But no luck. How can I write the holiday list to a file?
# Answer
> 1 votes
`list-holidays` opens a new buffer called `*Holidays*` and makes it visible, but leaves the current buffer unchanged. Meanwhile `write-file` writes the contents of the current buffer to a file. Thus your code writes the wrong thing to the file. You can call `switch-to-buffer` to change which buffer is current, but you probably also want to restore the window configuration afterwards.
You probably want to do something like this:
```
(save-window-excursion
(list-holidays 2020 2021)
(switch-to-buffer "*Holidays*")
(write-file "~/temp/myholidays.txt"))
```
`save-window-excursion` saves the current window configuration, runs the code you give it just like progn would, then restores the window configuration. It also saves the state of the buffer you are in as well (point and mark and suchlike).
The code inside opens the holidays window, switches to it, and then writes it to a file.
Edit: Incidentally, I took a peek at the `list-holidays` function before writing my answer, because as lawlist says there could be a better function to use. Ideally there would be one that returns a string, or just puts the text in the current buffer. Sadly no such function exists, though it wouldn’t be terribly hard to split the current `list-holidays` in half if you wanted.
# Answer
> 0 votes
I do not know if there is a built-in function similar to `list-holidays` that returns the list as a string. If no such function exists, then I would be inclined to take the function `list-holidays` and modify it to suit my needs ... beginning by typing `M-x find-function RET list-holidays RET` and copying the function to a `*scratch*` buffer and modifying it accordingly. However, I saw what makes it tick and see that the output is to a buffer defined as the `holiday-buffer` -- as such, the following may suffice to meet the needs of the O.P. without further ado:
```
(save-window-excursion
(require 'holidays) ;; just in case it is not already loaded
(when (get-buffer holiday-buffer)
(with-current-buffer holiday-buffer
(let ((inhibit-read-only t))
(erase-buffer))))
(list-holidays 2020 2021)
(with-temp-file "/Users/HOME/Desktop/myholidays.txt"
(insert-buffer holiday-buffer))
(kill-buffer holiday-buffer))
```
---
Tags: files
--- |
thread-64532 | https://emacs.stackexchange.com/questions/64532 | EMMS and MPD configuration | 2021-04-21T09:38:56.797 | # Question
Title: EMMS and MPD configuration
I've setup EMMS to use with MPD according to the manual with :
```
(use-package emms
:config
(require 'emms-setup)
(require 'emms-player-mpd)
(emms-all) ; don't change this to values you see on stackoverflow questions if you expect emms to work
(setq emms-player-list '(emms-player-mpd))
(add-to-list 'emms-info-functions 'emms-info-mpd)
(add-to-list 'emms-player-list 'emms-player-mpd)
;; Socket is not supported
(setq emms-player-mpd-server-name "localhost")
(setq emms-player-mpd-server-port "6600")
(setq emms-player-mpd-music-directory "/data/music")
)
```
I can see the current playlist in MPD, play and pause. But I cannot add new files to it . More precisely :
* `emms-cache-set-from-mpd-directory` displays `Dumping MusicPD data to cache...processing` but never finishes (even for a small folder).
* `emms-smart-browse` is never updated
* I can modify the playlist outside emacs with `ncmpcpp`.
* the previous thread was not helpful : mingus seems not maintained and broken
I'm using Doom emacs. Thanks !
# Answer
You have to run M-x `emms-cache-set-from-mpd-all` instead of `M-x emms-cache-set-from-mpd-directory`
You should add `(emms-player-mpd-connect)` to your Emms configuration if you want Emms to connect to mpd on startup.
Late answer, but might be useful to someone.
> 2 votes
---
Tags: emms
--- |
thread-68909 | https://emacs.stackexchange.com/questions/68909 | POVray mode minor change sought | 2021-10-13T13:32:30.583 | # Question
Title: POVray mode minor change sought
POVray is a scripting language used to define 3-dimensional graphics.
POVray mode for emacs provides text coloring, automatic indenting, etc. when developing a script on emacs.
For the most part, this works very well despite the fact that the last change to the mode was 5 years ago. POVray itself doesn't change very much either. But it does change. Specifically, a new keyword elseif has been added, and I would like this mode to incorporate this change.
I looked at the above linked GitHub page, and could not find a place to comment, or even a way to message the author. So maybe I am asking my question in the wrong place, and I just need a clue about GitHub.
I looked at the pov-mode.el file, to see if I could do this myself. My idea was to add in an #elseif directive, possibly within a parenthesized or clause, everywhere I saw the #else directive. But I am not familiar with Lisp and I am not sure whether the desired consequences would result. I would probably also have to search through instances of the #if directive as well.
Advice on how to either contact the author (melmothx on GitHub) or learn more about Lisp would be welcome.
# Answer
> 2 votes
You should file an “issue” on GitHub. Technically this is more of a feature request than a bug report, but GitHub lumps all such things together.
You could also just try adding the “elseif” to the regex in the `pov-all-keyword-matcher` variable at https://github.com/melmothx/pov-mode/blob/master/pov-mode.el#L916. This seems to be what it uses to find keywords.
---
Tags: major-mode
--- |
thread-68889 | https://emacs.stackexchange.com/questions/68889 | org-mode input M with shift-m doesn't work | 2021-10-12T02:00:22.657 | # Question
Title: org-mode input M with shift-m doesn't work
When I try to input a capital M in org-mode with ubuntu, I always got a M- in minibuffer, so M letter can never being input to my document.
How to fix it?
# Answer
> 1 votes
Thanks for @NickD's help.
Finally I found below line make the trouble:
```
(defun samplefunction()
(interactive)
(let ((fill-paragraph-function nil)
(adaptive-fill-function nil))
(fill-paragraph)))
(define-key org-mode-map "M-q" 'samplefunction)
```
This is define Meta-q, but not sure why it impackt on Shift-m.
---
Tags: org-mode
--- |
thread-68915 | https://emacs.stackexchange.com/questions/68915 | How to diagnose invalid slot name in Magit Forge | 2021-10-13T22:21:45.523 | # Question
Title: How to diagnose invalid slot name in Magit Forge
I thought I had found a minor issue in Magit forge, and before reporting a bug I wished to update to the latest version. In the process I seem to have borked my installation.
The value of my `package-archives` variable is
```
(("gnu" . "https://elpa.gnu.org/packages/")
("melpa-stable" . "http://stable.melpa.org/packages/")
("melpa" . "http://melpa.org/packages/"))
```
and the value of my `package-archive-priorities` variable is
```
(("melpa-stable" . 10) ("melpa" . 0))
```
To reach my current state I ran
1. `M-x package-refresh-packages`
2. `M-x package-list-packages`
3. `U` (mark packages to be updated to the latest version)
4. `x` (execute the update)
5. `M-x exit-emacs` and start a new one
In trying to get Magit and Forge to work again, I've tried three scenarios:
1. If I start Emacs with my usual `.emacs` loaded, and I try to run `magit-status`, it fails with this message:
```
slot-missing: Invalid slot name: "#<forge-database forge-database-1589f0c0434c>", :file
```
2. If I disable a good chunk of my `.emacs`, I can start Emacs and can run `magit-status` in a buffer, getting a display. But when I hit the `'` key to start a Forge command, it fails with these two messages:
```
Cannot insert ("'" "Forge" forge-dispatch) into magit-dispatch; % not found
transient-setup: Invalid slot name: "#<forge-database forge-database-158b9206ce84>", :file
```
3. If I run the command given by `M-x magit-emacs-Q-command`, I can load and use Magit just fine, but I cannot get `forge` to load. (It has a ton of additional dependencies.)
My question: **How can I get Forge commands working again?**
I found two questions that look related, but did not glean any answers there:
# Answer
Look at the error message you are given:
```
slot-missing: Invalid slot name: "#<forge-database forge-database-1589f0c0434c>", :file
```
It says that some code was operating on an object, which you can see is of type `forge-database`, and it failed when looking for the slot accessed by the key `:file`. Apparently `forge-database`s don’t have a slot called `:file`, so the question you must ask is “What slots does a `forge-database` actually have?”
Answering this question is pretty easy in Emacs Lisp. Just go to your `*scratch*` buffer and run `(eieio--class-slots (find-class 'forge-database))`. You’ll get a list that looks something like this:
```
[#s(cl-slot-descriptor process unbound process nil)
#s(cl-slot-descriptor log-buffer nil (or null buffer) ((:documentation . "Output log (debug).")))
#s(cl-slot-descriptor finalizer unbound t ((:documentation . "Object returned from `make-finalizer'.")))
#s(cl-slot-descriptor file unbound (or null string) ((:documentation . "Database file name.")))]
```
I’ve formatted it for easier reading, which has the effect of lining up the names into a column, but you don’t have to do that manually. You can get a list of the slot names by running:
```
(mapcar #'cl--slot-descriptor-name
(eieio--class-slots (find-class 'forge-database)))
```
This gives me a simple list of slot names: `(process log-buffer finalizer file)`, but notice that none of these exactly match the keyword in the error message, which was `:file`. I expect that this will match the slot named `file`, but the author of the `forge-database` class might have had the bad taste to choose confusing initargs for their class, so we should check:
```
(eieio--class-initarg-tuples (find-class 'forge-database))
```
Running this gives me a short list:
```
((:process . process)
(:log-buffer . log-buffer)
(:file . file))
```
It’s pretty clear that when we initialize an instance of class `forge-database` using the initarg `:file`, it is supposed to store the value in the slot named `file`. This is where you are getting the error. You should run the same diagnostic steps in your own Emacs, to see where the difference is. It sounds to me like your version of the Forge library has a different name for the slot, and your version of Magit has not been updated to match. I happen to know that `forge-database` does not define the `file` slot directly; it gets it from a base class of a base class. That grandbase class comes from a library for accessing sqlite databases.
It is very probable that you have installed an incompatible version of that sqlite library, either too new or too old. It has a different author than Forge and Magit, so there is no reason to expect them to update in sync with each other. If this proves to be the case, then you could ask the author of either the sqlite or Forge packages which version you should install, or you could examine their history to find when they changed and how, and use that information to pick the correct versions.
> 9 votes
---
Tags: magit, forge
--- |
thread-68918 | https://emacs.stackexchange.com/questions/68918 | Hiding metadata at the beginning of an org-mode file | 2021-10-14T13:27:31.910 | # Question
Title: Hiding metadata at the beginning of an org-mode file
I have a quite a bit of file-specific settings at the beggining for my org files. It looks as follows but there is many more lines:
```
#+STARTUP: overview
#+LINK: coderepo x:/my/repo/%s
#+LINK: scriptsrepo x:/mysrcript/repo/
```
Is there a way to hide or fold them ?
# Answer
> 4 votes
I think you can put them at the end, maybe even in a heading that can be collapsed.
You might try a drawer:
```
:setup:
#+STARTUP: overview
#+LINK: coderepo x:/my/repo/%s
#+LINK: scriptsrepo x:/mysrcript/repo/
:end:
```
For me, that is folded when I open the file.
Alternatively, I think you could put them in a separate setup.org file, and then include it as:
`#+include: setup.org`
---
Tags: org-mode
--- |
thread-68900 | https://emacs.stackexchange.com/questions/68900 | How do I set path for ag for helm-do-grep-ag | 2021-10-12T20:10:23.847 | # Question
Title: How do I set path for ag for helm-do-grep-ag
I am on MacOS (darwin) and when I attempt `helm-do-grep-ag` I get a zsh error `zsh:1: command not found: ag`. What is the proper way to address this?
My ag is homebrewed and so is in /usr/local/bin
I verified the setting of PATH in both bash and zsh startup, and if I open a shell inside emacs I see /usr/local/bin there. (pasted from emacs shell session:)
```
echo $PATH
/Users/cgrandi/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
```
I then also tried adding it to the `exec-path` variable:
```
Its value is
("/usr/local/bin" "/usr/bin" "/bin" "/usr/sbin" "/sbin" "/Applications/Emacs.app/Contents/MacOS/libexec" "/Applications/Emacs.app/Contents/MacOS/bin")
```
I note that variable is defined in 'C source code' and so I suspect it does not influence commands executed from 'helm-grep.el'
As a workaround I customize the variable `helm-grep-ag-command` to include the explicit full path
```
Its value is
"/usr/local/bin/ag --line-numbers -S --color --nogroup %s %s %s"
Original value was
"ag --line-numbers -S --color --nogroup %s %s %s"
```
But I suspect that is not the proper way to do it. Is this in fact the best way to address that? Or is there a more proper way?
# Answer
> 1 votes
This looks like a standard case for exec-path-from-shell.
Essentially, the emacs environment is dependent on where it was started from (e.g. GUI app vs terminal vs daemon, etc.) This package loads your real shell and copies the values into emacs.
---
Tags: exec-path, ag, helm-grep, mac
--- |
thread-68921 | https://emacs.stackexchange.com/questions/68921 | redefine a function as wrapper for the old definition | 2021-10-14T17:38:52.963 | # Question
Title: redefine a function as wrapper for the old definition
I am trying to modify a package by redefining a function in it. However, I would like to call the original definition in the new definition. (kind of like extending a constructor in a subclass now that I think of it)
let's say we have this defined
```
(defun hello ()
"hello")
```
I want to define something like this
```
(defun hello-world ()
(concat (hello) " world"))
```
except... I want to name the second function `hello` instead of hello world, and just redefine it so that it says " world" at the end, and does that by calling the old function.
Is there a way to give the old function a new name, and then call the old function by its new name, in the new function, which uses the old name?
```
;; first rename hello to _hello somehow
(defun hello ()
(concat (_hello) " world"))
```
or is there an even better way to accomplish the same thing?
# Answer
You apparently want to *advise* the function `hello`, so that it does what you want instead.
See the Elisp manual, node Advising Functions.
This code advises function `hello`, *replacing* its definition. The resulting function invokes the original function (`hello`), concatenates the result of that invocation to `" world"`, and returns that resulting string.
```
(advice-add 'hello :around #'my-hello)
(defun my-hello (original-function)
"..."
(concat (funcall original-function) " world")
```
(If the original function itself accepted arguments then you would add them to the list of args to `my-hello` and to the `funcall` sexp.)
> 2 votes
---
Tags: functions, advice, nadvice
--- |
thread-68916 | https://emacs.stackexchange.com/questions/68916 | How to export the current buffer with it's syntax highlighting to a WYSIWYG output? | 2021-10-13T23:41:19.543 | # Question
Title: How to export the current buffer with it's syntax highlighting to a WYSIWYG output?
I would like to use emacs to "render" text to an output file.
Is there a way to export the buffer with all font-locking to a file?
*(The exact format may not matter HTML or terminal-escaped colors would both be fine).*
Some options I'm aware of but aren't quite what I'm after.
---
* Cairo SVG screenshot...
+ Being a screenshot makes this less useful for writing a whole text buffer, although in theory and off screen buffer could be made very tall I suppose.
+ SVG isn't so easy to manipulate (search, convert into other text format).
* Terminal screenshot...
+ Again, it's limited to a "screen", not so convenient to dump an entire buffer.
.. Of course it's possible to do tricks like capturing regions and joining them together, this can work but isn't trivial and seems like a last resort.
---
Are there any solutions that export the entire buffer as it's displayed on-screen?
# Answer
> 3 votes
There are several packages for this, including:
* `ps-print` -- Renders a buffer as postscript for printing (standard package)
* `htmlfontify` -- Convert a buffer to html (standard package)
* `htmlize` -- Another package for converting a buffer to html. Even though this is not included in the standard Emacs distribution, it is widely used.
* `e2ansi` -- Renders a buffer using ANSI sequences for display in a terminal (useful in batch mode, e.g. as highlighter for `more`).
If you plan to write your own package that export it to another format you can base it on `face-explorer` (which was developed as part of the `e2ansi` project). It handles all the hairy low-level details, and works in batch mode.
*Note*: I'm the author of `e2ansi` and `face-explorer`.
---
Tags: font-lock, rendering, exporting
--- |
thread-68926 | https://emacs.stackexchange.com/questions/68926 | Validating Arguments to a Function | 2021-10-14T23:12:28.947 | # Question
Title: Validating Arguments to a Function
I would like to validate the argument to a function before its action is executed. The main concern is the passing of a void variable. How can I trap this?
```
(defun is-it-bound(item)
(if (boundp 'item)
(message "bound")
(message "not bound")))
```
This doesn't work if I pass in a non-existent/undefined variable. Instead of getting "not bound", I get the "void-variable" explosion immediately. I want something like exception handling, so that I can trap the error.
I tried `condition-case` but the results are the same.
```
(defun is-it-bound(item)
(condition-case nil
(boundp 'item)
(void-variable "%s" "void variable!" )
))
```
It looks like the argument is evaluated before being passed into the function. Is that correct?
In other languages, this is a no-brainer. But here, I need help getting it sorted. It's a brainer for me.
# Answer
> 0 votes
Yes, in Emacs Lisp, as in Common Lisp and most other Lisps, arguments are evaluated before evaluating the body of the function.
This is called *"applicative"* order evaluation. The opposite (passing the args unevaluated to the body, which evaluates them only as needed) is called *"normal"* order evaluation. (Well, there are actually multiple kinds of evaluation "as needed", but that's a detail here.)
Among other things, this means that you can end up with "wrong" (that is, perhaps unexpected) answers or infinite evaluation with Lisp. As one example, you can't define **`if`** as a function (you can define it as a macro, as Lisp macros don't evaluate their args before evaluating the body): each of the "consequence" args gets evaluated before the body of the function.
---
But I sense that you might have another question behind this one. That is, I suspect this is an X-Y question. Instead of trying to figure out how to do what you think you need to do, try asking how to do what you really want to do. ;-)
You say that your *"main concern is the passing of a void variable."* As you've seen, that's impossible - the function itself binds the arguments as local variables. Try to express your concern as a (separate) question.
---
Note that if what you want to do is *"pass a variable"*, and not pass the variable's value, then you can do that in either of these ways. The first (use a function) is almost always preferable.
1. Have callers of the function pass `'the-variable`, not just `the-variable` to it. Quoting means that when the function is called it's passed the result of evaluating the quoted symbol, which is the symbol (`the-variable`). Note that the function can do whatever it wants with the symbol, including, but not limited to, treating it as a variable.
2. Define a macro instead of a function. The macro body need not evaluate the variable passed to it as argument. (The macro body can do whatever else you want, to produce code that then gets evaluated.)
---
Tags: elisp, functions, variables, arguments, lisp
--- |
thread-68927 | https://emacs.stackexchange.com/questions/68927 | Evenly spaced table-cells | 2021-10-14T23:32:31.710 | # Question
Title: Evenly spaced table-cells
I would like to change the following spacing behavior so that ideally all begin and end of columns are lined up (evenly spaced).
All rows should stretch as much as the largest of them.
# Answer
If you use a mono-space font, the columns should align. There is no clear way to align columns in emacs using a variable-spaced font.
> 1 votes
---
Tags: org-mode, org-table, align
--- |
thread-68925 | https://emacs.stackexchange.com/questions/68925 | How do I set a restclient variable by calling a function? | 2021-10-14T22:32:48.703 | # Question
Title: How do I set a restclient variable by calling a function?
This is probably just a reflection of my weak elisp skills but when I try to create a restclient variable via a function call:
```
:uid := (shell-command "uuidgen" t)
```
It does not assign the output of the function call to the variable `:uid` but rather just outputs the result of the call into the buffer.
Is there some other elisp function I should be wrapping around that `shell-command` call?
# Answer
You should read the built–in help for the `shell-command` function. Type `C-h f shell-command` and hit enter to pull it up. Specifically, it says this:
```
The optional second argument OUTPUT-BUFFER, if non-nil,
says to put the output in some other buffer.
If OUTPUT-BUFFER is a buffer or buffer name, erase that buffer
and insert the output there; a non-nil value of
shell-command-dont-erase-buffer prevents the buffer from being
erased. If OUTPUT-BUFFER is not a buffer and not nil (which happens
interactively when the prefix argument is given), insert the
output in current buffer after point leaving mark after it. This
cannot be done asynchronously.
```
Your choices for this argument are to leave it unspecified, to specify nil, t, a string containing a buffer name, or an actual buffer object. When you specify t you are telling it to write the output to the current buffer. You want to put the result into a string instead, so you should make a temporary buffer, change to that new buffer, call `shell-command`, and then get the contents of the buffer as a string and delete the temporary buffer. Thankfully this kind of situation is fairly common, so in practice you don’t have to do all of that work yourself.
The function `buffer-string` gets the contents of the current buffer, and `with-temporary-buffer` runs any code in a new empty buffer that will vanish as soon as the code finishes running. Here’s how to put them together:
```
(with-temp-buffer
(shell-command "uuidgen" t)
(buffer-string))
```
However, one way of doing things is not enough, so there is also a slightly different way:
```
(with-output-to-string
(shell-command "uuidgen" standard-output))
```
The difference here is that `with-output-to-string` expects the commands you run to put their output in the buffer stored in the standard-output variable. `shell-command` doesn’t have a short way of doing that, so we have to specify it ourselves. On the other hand, it calls `buffer-string` for us. Pick whichever you prefer.
Also, I should point out that you could also use the `call-process` function in place of `shell-command`. `call-process` doesn’t start a shell to run your command in. Since you’re not using any shell features like pipelines, loops, or variables, this is an efficiency gain. Whether that gain is minor or major depends on your exact use case. The arguments are slightly different though:
```
(with-output-to-string
(call-process "uuidgen" nil standard-output))
```
> 1 votes
---
Tags: shell-command, restclient
--- |
thread-68932 | https://emacs.stackexchange.com/questions/68932 | Backup a variable and store it back | 2021-10-15T08:14:59.593 | # Question
Title: Backup a variable and store it back
I have problems to get into Lisp. I assume I miss the correct terms to search for. So I try to "speak in Python".
```
#!/usr/bin/env python3
foo = 7
backuped_foo = foo
# temporary change the value of foo
foo = 323
# restore the original foo value
foo = backuped_foo
```
So I would I do this in Emacs Lisp?
*EDIT*: I am not interested in lexial scoping or other concepts for a solution. I am only interested in an nearly exact technical copy of that python code into Lisp.
This is inspired by another answer:
```
(setq foo 7) ;; original value
(setq backuped_foo foo) ;; remember it for later restore
(setq foo 4373) ;; temporary value
;; ...
;; do a lot of stuff where a lexical scoope does not help
;; ...
(setq foo backuped_foo) ;; restore the original value
```
At the end `foo==7` (do not know how to express this in Lisp) so everything is fine. But I am not sure if this is a good and Lisp-like way.
In real I need this to modify a global variable (`gc-cons-threshold`) while a script (`init.el`) is running. When the script is finished I need to restore the original value.
# Answer
> 3 votes
Just use `let`. Write something like this:
```
(let ((foo 323))
…)
```
Where the ellipsis is, place whatever code you wanted to run with foo set to 323. Once that code finishes, foo will go back to having whatever old value it had; there is no need to manually save it and restore it.
This is called “lexical scope”. Python actually has lexically–scoped variables as well, though perhaps it is not quite as succinct. Consider this code:
```
foo = 7
def do_something:
foo = 323
…
do_something()
```
When you enter `do_something`, `foo` takes on a new value, and that value is restored automatically when `do_something` returns. In Emacs Lisp, `let` allows you to do the same thing but without defining a function every time you want to use it.
If you want to learn more about the Emacs Lisp language, I recommend reading the manual that is included with Emacs. The keyboard shortcut `C-h i` will open the Info viewer. It should open to a list of manuals, unless you have recently viewed a specific manual in which case it opens to whatever you were reading before. In the Info viewer, `d` will take you back to the index, where you can find the manual for Emacs Lisp. The whole manual is worth reading, but you should specifically take a look at chapter 12 Variables, which covers the topic quite thoroughly. chapter 12.10 Scoping Rules for Variable Bindings goes into the details of both dynamic and lexical scoping for variables.
---
Tags: variables, let-binding, setq
--- |
thread-12701 | https://emacs.stackexchange.com/questions/12701 | Kill a line deletes the line but leaves a blank newline character | 2015-05-26T09:18:27.513 | # Question
Title: Kill a line deletes the line but leaves a blank newline character
On deleting a line in Emacs using `C-k`, Emacs removes the line contents but it leaves a blank newline character. To remove this, I again press `C-k`.
How can I delete the complete line with no traces left behind in one shot?
# Answer
> 6 votes
From documentation:
> kill-whole-line is an interactive compiled Lisp function.
>
> It is bound to `<C-S-backspace>`.
>
> (kill-whole-line &optional ARG)
>
> Kill current line. With prefix ARG, kill that many lines starting from the current line. If ARG is negative, kill backward. Also kill the preceding newline. (This is meant to make C-x z work well with negative arguments.) If ARG is zero, kill current line but exclude the trailing newline.
# Answer
> 2 votes
Consider adding `(setq kill-whole-line t)` to your configuration in case you'd want it to be default behavior.
# Answer
> 1 votes
Use 1 as argument, for example `C-1 C-k` or bind to a function that calls `(kill-whole-line 1)`.
---
Tags: editing, kill-ring
--- |
thread-68945 | https://emacs.stackexchange.com/questions/68945 | How does eldoc (>= 1.1.0) display arguments in the mode-line during eval-expression | 2021-10-15T22:47:02.793 | # Question
Title: How does eldoc (>= 1.1.0) display arguments in the mode-line during eval-expression
I am unable to determine how eldoc is displaying arguments (or other information) in the mode-line while `eval-expression` is reading user input in the minibuffer. I could not find a relevant element in the default value of `mode-line-format` and I also did not find any code where eldoc is prepending an element temporarily to the (local?) value of `mode-line-format`.
I need this so that I can change the visual appearance, such as its background color.
Note that I did find the complex machinery that determines *what* information to display; that's not what I am looking for, I only wonder *how* that information is displayed, whatever it may be.
# Answer
Isn't it:
```
(defun eldoc-minibuffer-message (format-string &rest args)
"Display messages in the mode-line when in the minibuffer.
Otherwise work like `message'."
```
?
It seems that it prepends `eldoc-mode-line-string` to `mode-line-format` and clears it on a `minibuffer-exit-hook`:
```
(add-hook 'minibuffer-exit-hook
(lambda () (setq eldoc-mode-line-string nil
;; https://debbugs.gnu.org/16920
eldoc-last-message nil))
nil t)
...
(setq mode-line-format
(list "" '(eldoc-mode-line-string
(" " eldoc-mode-line-string " "))
mode-line-format)))
```
It also does a `(force-mode-line-update)`. Not a very polite way to do it, it could just have written to the `global-mode-string` or added its own lighter...
See how it looks with doom-modeline :(
The heading bar is displaced to the right. Fortunately moody-modeline won't be affected like this, although I don't know how well it plays with ribbons and tabs.
NOTE: all of the above is from emacs-28 branch.
> 2 votes
---
Tags: mode-line, minibuffer, eldoc
--- |
thread-68942 | https://emacs.stackexchange.com/questions/68942 | org-export-filter-final-output-function appears not to fire | 2021-10-15T17:20:46.683 | # Question
Title: org-export-filter-final-output-function appears not to fire
I'm trying to filter my org-export output in one file because every heading in the ascii output seems to have two line breaks after it:
```
first heading
=============
second heading
==============
```
And I want it to be:
```
first heading
=============
second heading
==============
```
So I added this function to my org file:
```
#+BIND: org-export-filter-final-output-functions (tmp-f-singlebreak)
#+BEGIN_SRC emacs-lisp :exports results :results none
(defun tmp-f-singlebreak (s backend info)
(message "inside singlebreak function")
(replace-regexp-in-string "\\n\\n" "\\n" s))
#+END_SRC
```
I added the `message` call so that I could debug whether the function was ever actually running. There is nothing in the messages buffer when I export using `org-export-dispatch` so I can only guess that the function is not being called.
What am I missing?
# Answer
Did you enable the `BIND` keyword by setting `org-export-allow-bind-keywords` to `t`? See the last paragraph of the `Export Settings` section of the manual (`C-h i g(org)Export settings` will get you there). Also, did you refresh the setup by pressing `C-c C-c` on the `#+BIND:` line or by killing the buffer and reopening the file?
FWIW, it fires for me - in the sense that I get the message that the function is indeed called.
But there is also a problem with the function. If you want a single empty line between the headings, you can't forget that there is also a newline at the end of each heading. So what you want to do is replace three or more newlines with exactly *two* newlines: one to end the heading line and the other to produce the empty line:
```
#+BEGIN_SRC emacs-lisp :exports results :results none
(defun tmp-f-singlebreak (s backend info)
(message "inside singlebreak function")
(replace-regexp-in-string "\n\n\n+" "\n\n" s))
#+END_SRC
```
The regexp matches three or more newlines and replaces them with two newlines. Note also that `\n` matches a newline; `\\n` matches an `n`. You can experiment with `re-builder` to see what a particular regexp matches.
You also probably want to limit the function to backends that make sense (the `ascii` backend in this case):
```
#+BEGIN_SRC emacs-lisp :exports results :results none
(defun tmp-f-singlebreak (s backend info)
(when (eq backend 'ascii)
(replace-regexp-in-string "\n\n\n+" "\n\n" s)))
#+END_SRC
```
> 1 votes
---
Tags: org-mode, org-export
--- |
thread-68891 | https://emacs.stackexchange.com/questions/68891 | Disabling lsp-mode's autocomplete only for some languages | 2021-10-12T05:48:27.943 | # Question
Title: Disabling lsp-mode's autocomplete only for some languages
I am on Emacs 27.2 configured with the latest commit of Spacemacs, `develop` branch.
I have both `ocaml` and `lsp` layer enabled. Sadly, I find `lsp-mode`'s auto-completion with the `ocaml-lsp` too slow to use, so I want to disable this feature only for `tuareg-mode`.
So far, I only found global solutions like this, but I want a buffer-local, major-mode sensitive behavior. So, building on the previous solution, I have tried:
```
(add-hook 'tuareg-mode-hook 'spacemacs/toggle-auto-completion-off)
```
However, this fails to disable autocompletion on buffers of `tuareg-mode`, maybe because `lsp` mode enables it back.
So, I concluded that I have to tackle `lsp`, not `tuareg`. What settings should I set in order to achieve my goal?
# Answer
You may try something like:
```
(add-hook 'tuareg-mode-hook (lambda ()
(setq-local lsp-completion-enable nil)))
```
but make sure that this runs before `lsp` itself.
> 1 votes
---
Tags: lsp-mode, lsp
--- |
thread-68053 | https://emacs.stackexchange.com/questions/68053 | How can I identify this popup face? | 2021-08-10T21:16:11.257 | # Question
Title: How can I identify this popup face?
I'm trying to find the face that applies to this tooltip in LSP in rust-mode with rust-analyzer, but I'm not seeing anything when I search on:
* tooltip
* lsp
* popup
* posframe
* lsp-rust-analyze
* faces
* lsp-ui
If there's a general method that works to identify faces you can't put the cursor on, or if someone knows what that annoyingly light background face is, I would love the help.
# Answer
> 1 votes
It seems like this is lsp-ui-doc-background.
---
Tags: faces, lsp-mode, lsp-ui
--- |
thread-66526 | https://emacs.stackexchange.com/questions/66526 | Auto-saving after lsp refactor | 2021-06-30T11:20:23.347 | # Question
Title: Auto-saving after lsp refactor
When I use `lsp-rename` function, the edited files are not saved automatically and I have to manually save them. Is this an expected behavior and, is it possible to change this?
(I use emacs 27.2, with doom configuration. I use pyright as the lsp backend for python projects.)
edit: in lsp-mode changelog for version 7.1 (which isn't released yet), I've found this:
> * Add lsp-auto-save-changed-buffers which save the changed buffers after any text edit operation by lsp-mode.
But I'm pretty sure it was working correctly before.
# Answer
> 2 votes
That CL line is stale, I will remove it. To achieve what you want use:
```
(add-hook 'lsp-after-apply-edits-hook
(lambda (operation)
(when (eq operation 'rename)
(save-buffer))))
```
In general, I use `projectile-save-project-buffers` for this usecase.
---
Tags: python, doom, lsp-mode
--- |
thread-68943 | https://emacs.stackexchange.com/questions/68943 | Run elisp function in html encoded part of mime handle | 2021-10-15T19:18:58.487 | # Question
Title: Run elisp function in html encoded part of mime handle
I am a newbie at handling MIME lists in emacs. I want to edit the `mu4e-action-view-in-browser` function so that before an email is displayed on a web browser all of its Microsoft Safelinks urls are filtered. I have developed an elisp function called unsafelinks to do this operation (both functions written below). Find here an edited raw email with a link for testing purposes. Here is another example of a message which cannot be decoded by a simple hook of the `unsafelinks` function to the `gnus-article-decode-hook` (as suggested by @db48x). I am currently reading the documentation on how to bypass the "=" linebreak format of this last message.
```
(defun mu4e-action-view-in-browser (msg)
"Show current MSG in browser if it includes an HTML-part.
The variables `browse-url-browser-function',
`browse-url-handlers', and `browse-url-default-handlers'
determine which browser function to use."
(with-temp-buffer
(insert-file-contents-literally
(mu4e-message-field msg :path) nil nil nil t)
(run-hooks 'gnus-article-decode-hook)
(let ((header (cl-loop for field in '("from" "to" "cc" "date" "subject")
when (message-fetch-field field)
concat (format "%s: %s\n" (capitalize field) it)))
(parts (mm-dissect-buffer t t)))
;; If singlepart, enforce a list.
(when (and (bufferp (car parts))
(stringp (car (mm-handle-type parts))))
(setq parts (list parts)))
;; Process the list
(unless (gnus-article-browse-html-parts parts header)
(mu4e-warn "Message does not contain a \"text/html\" part"))
(mm-destroy-parts parts))))
```
```
(defun unsafelinks ()
"This function filters MS safelinks from a message buffer"
(interactive)
(beginning-of-buffer)
(let ((simple-url-regexp "https?://") urls)
(save-excursion
;; edit text URLs
(while (search-forward-regexp simple-url-regexp nil t)
(when-let ((url (thing-at-point 'url))
(bounds (thing-at-point-bounds-of-url-at-point)))
(delete-region (car bounds) (cdr bounds))
(insert (my-decode-safelink url)))))))
(require 'url-parse)
(defun my-decode-safelink (url)
;; (print url)
"Given a url string this function returns the corresponding decoded url"
(if (string-match-p (regexp-quote "safelinks.protection") url)
(let* ((query (url-filename (url-generic-parse-url url)))
(url (cadr (assoc ".*/?url" (url-parse-query-string query) (lambda (pat x) (string-match-p x pat)))))
(path (replace-regexp-in-string "3Dhttps" "https" (url-unhex-string url))))
(url-encode-url (replace-regexp-in-string (rx "/" (>= 20 (any "#$%&*^@"))) "" path)))
url))
```
# Answer
> 1 votes
I don’t think you need to edit this function at all. It calls the hook functions stored in `gnus-article-decode-hook`. You could add `unsafelinks` to that list with `(add-hook 'gnus-article-decode-hook 'unsafelinks)`.
# Answer
> 0 votes
This is a long and ugly solution which does work. Instead of messing around with `mu4e-action-view-in-browser` the `unsafelinks` function can be inserted into `gnus-article-browse-html-parts` and redefined like so
```
(defun gnus-article-browse-html-parts (list &optional header)
"View all \"text/html\" parts from LIST.
Recurse into multiparts. The optional HEADER that should be a decoded
message header will be added to the bodies of the \"text/html\" parts."
;; Internal function used by `gnus-article-browse-html-article'.
(let (type file charset content cid-dir tmp-file showed)
;; Find and show the html-parts.
(dolist (handle list)
;; If HTML, show it:
(cond ((not (listp handle)))
((or (equal (car (setq type (mm-handle-type handle))) "text/html")
(and (equal (car type) "message/external-body")
(or header
(setq file (mm-handle-filename handle)))
(or (mm-handle-cache handle)
(condition-case code
(progn (mm-extern-cache-contents handle) t)
(error
(gnus-message 3 "%s" (error-message-string code))
(when (>= gnus-verbose 3) (sit-for 2))
nil)))
(progn
(setq handle (mm-handle-cache handle)
type (mm-handle-type handle))
(equal (car type) "text/html"))))
(setq charset (mail-content-type-get type 'charset)
content (mm-get-part handle))
(with-temp-buffer
(if (eq charset 'gnus-decoded)
(mm-enable-multibyte)
(mm-disable-multibyte))
(insert content)
(unsafelinks) ; <<<<insert this
;; resolve cid contents
(let ((case-fold-search t)
st base regexp cid-file)
(goto-char (point-min))
(when (and (re-search-forward "<head[\t\n >]" nil t)
(progn
(setq st (match-end 0))
(re-search-forward "</head[\t\n >]" nil t))
(re-search-backward "<base\
\\(?:[\t\n ]+[^\t\n >]+\\)*[\t\n ]+href=\"\\([^\"]+\\)\"[^>]*>" st t))
(setq base (match-string 1))
(replace-match "<!--\\&-->")
(setq st (point))
(dolist (tag '(("a" . "href") ("form" . "action")
("img" . "src")))
(setq regexp (concat "<" (car tag)
"\\(?:[\t\n ]+[^\t\n >]+\\)*[\t\n ]+"
(cdr tag) "=\"\\([^\"]+\\)"))
(while (re-search-forward regexp nil t)
(insert (prog1
(condition-case nil
(save-match-data
(url-expand-file-name (match-string 1)
base))
(error (match-string 1)))
(delete-region (match-beginning 1)
(match-end 1)))))
(goto-char st)))
(while (re-search-forward "\
<img[\t\n ]+\\(?:[^\t\n >]+[\t\n ]+\\)*src=\"\\(cid:\\([^\"]+\\)\\)\""
nil t)
(unless cid-dir
(setq cid-dir (make-temp-file "cid" t))
(add-to-list 'gnus-article-browse-html-temp-list cid-dir))
(setq file nil
content nil)
(when (setq cid-file
(gnus-article-browse-html-save-cid-content
(match-string 2)
(with-current-buffer gnus-article-buffer
gnus-article-mime-handles)
cid-dir))
(replace-match cid-file nil nil nil 1))))
(unless content (setq content (buffer-string))))
(when (or charset header (not file))
(setq tmp-file (make-temp-file
;; Do we need to care for 8.3 filenames?
"mm-" nil ".html")))
;; Add a meta html tag to specify charset and a header.
(cond
(header
(let (title eheader body hcharset coding)
(with-temp-buffer
(mm-enable-multibyte)
(setq case-fold-search t)
(insert header "\n")
(setq title (message-fetch-field "subject"))
(unsafelinks) ; <<<<insert this
(goto-char (point-min))
(while (re-search-forward "\\(<\\)\\|\\(>\\)\\|\\(&\\)\\|\n"
nil t)
(replace-match (cond ((match-beginning 1) "<")
((match-beginning 2) ">")
((match-beginning 3) "&")
(t "<br>\n"))))
(goto-char (point-min))
(while (re-search-forward "^[\t ]+" nil t)
(dotimes (i (prog1
(current-column)
(delete-region (match-beginning 0)
(match-end 0))))
(insert " ")))
(goto-char (point-min))
(insert "<div align=\"left\">\n")
(goto-char (point-max))
(insert "</div>\n<hr>\n")
;; We have to examine charset one by one since
;; charset specified in parts might be different.
(if (eq charset 'gnus-decoded)
(setq charset 'utf-8
eheader (encode-coding-string (buffer-string)
charset)
title (when title
(encode-coding-string title charset))
body (encode-coding-string content charset))
(setq hcharset (mm-find-mime-charset-region (point-min)
(point-max)))
(cond ((= (length hcharset) 1)
(setq hcharset (car hcharset)
coding (mm-charset-to-coding-system
hcharset nil t)))
((> (length hcharset) 1)
(setq hcharset 'utf-8
coding hcharset)))
(if coding
(if charset
(progn
(setq body
(mm-charset-to-coding-system charset
nil t))
(if (eq coding body)
(setq eheader (encode-coding-string
(buffer-string) coding)
title (when title
(encode-coding-string
title coding))
body content)
(setq charset 'utf-8
eheader (encode-coding-string
(buffer-string) charset)
title (when title
(encode-coding-string
title charset))
body (encode-coding-string
(decode-coding-string
content body)
charset))))
(setq charset hcharset
eheader (encode-coding-string
(buffer-string) coding)
title (when title
(encode-coding-string
title coding))
body content))
(setq eheader (encode-coding-string
(buffer-string) 'utf-8)
body content)))
(erase-buffer)
(mm-disable-multibyte)
(insert body)
(unsafelinks) ; <<<<insert this
(when charset
(mm-add-meta-html-tag handle charset t))
(when title
(goto-char (point-min))
(unless (search-forward "<title>" nil t)
(re-search-forward "<head>\\s-*" nil t)
(insert "<title>" title "</title>\n")))
(goto-char (point-min))
(or (re-search-forward
"<body\\(?:\\s-+[^>]+\\|\\s-*\\)>\\s-*" nil t)
(re-search-forward
"</head\\(?:\\s-+[^>]+\\|\\s-*\\)>\\s-*" nil t))
(insert eheader)
(mm-write-region (point-min) (point-max)
tmp-file nil nil nil 'binary t))))
(charset
(mm-with-unibyte-buffer
(insert (if (eq charset 'gnus-decoded)
(encode-coding-string content
(setq charset 'utf-8))
content))
(if (or (mm-add-meta-html-tag handle charset)
(not file))
(mm-write-region (point-min) (point-max)
tmp-file nil nil nil 'binary t)
(setq tmp-file nil))))
(tmp-file
(mm-save-part-to-file handle tmp-file)))
(when tmp-file
(add-to-list 'gnus-article-browse-html-temp-list tmp-file))
(add-hook 'gnus-summary-prepare-exit-hook
'gnus-article-browse-delete-temp-files)
(add-hook 'gnus-exit-gnus-hook
(lambda ()
(gnus-article-browse-delete-temp-files t)))
;; FIXME: Warn if there's an <img> tag?
(browse-url-of-file (or tmp-file (expand-file-name file)))
(setq showed t))
;; If multipart, recurse
((equal (mm-handle-media-supertype handle) "multipart")
(when (gnus-article-browse-html-parts handle header)
(setq showed t)))
((equal (mm-handle-media-type handle) "message/rfc822")
(mm-with-multibyte-buffer
(mm-insert-part handle)
(setq handle (mm-dissect-buffer t t))
(when (and (bufferp (car handle))
(stringp (car (mm-handle-type handle))))
(setq handle (list handle)))
(when header
(article-decode-encoded-words)
(let ((gnus-visible-headers
(or (get 'gnus-visible-headers 'standard-value)
gnus-visible-headers)))
(article-hide-headers))
(goto-char (point-min))
(search-forward "\n\n" nil 'move)
(skip-chars-backward "\t\n ")
(setq header (buffer-substring (point-min) (point)))))
(when (prog1
(gnus-article-browse-html-parts handle header)
(mm-destroy-parts handle))
(setq showed t)))))
showed))
```
---
Tags: mu4e, email, gnus, url
--- |
thread-68954 | https://emacs.stackexchange.com/questions/68954 | Can't change keybinding in prolog-mode | 2021-10-16T15:40:09.260 | # Question
Title: Can't change keybinding in prolog-mode
I have the following code that is launched on Emacs startup:
```
(defun my-prolog-mode ()
(define-key prolog-mode-map (kbd "M-a") 'pop-tag-mark))
(eval-after-load "prolog-mode" '(my-prolog-mode))
```
I expect `pop-tag-mark` function to be launched when M-a is clicked. But for some reason `M-a` is bound to another function:
```
M-a runs the command prolog-beginning-of-clause, which is an
interactive compiled Lisp function in ‘prolog.el’.
```
What is it?
# Answer
> 2 votes
`eval-after-load` expects the first argument to be the name of a file, with or without an extension. `prolog-mode` is defined in the file `"prolog.el"`, not `"prolog-mode.el"`. This should work:
```
(eval-after-load "prolog" '(my-prolog-mode))
```
---
Tags: key-bindings
--- |
thread-68958 | https://emacs.stackexchange.com/questions/68958 | `while` is hanging | 2021-10-16T19:13:46.200 | # Question
Title: `while` is hanging
```
(defun test (n)
(let ((list1 ()))
(while (< (length list1) 10))
(push (random n) list1)
list1))
```
I'm trying to add `(random n)` to `list1` while the `length` of `list1` is less than 10. When I evaluate this function, it hangs. What am I doing wrong?
# Answer
> 3 votes
You closed your `while` loop before doing the `push`. So the list length stayed less than 10.
```
(defun test (n)
(let ((list1 ()))
(while (< (length list1) 10)
(push (random n) list1))
list1))
```
**Moral:** Indent your code properly. `C-M-q` is your friend, as is `TAB`. See the Emacs manual, node Indenting Several Lines.
Hanging should have been your clue that the `while` loop was infinite. That would tell you that the list length wasn't increasing.
---
Tags: debugging
--- |
thread-68963 | https://emacs.stackexchange.com/questions/68963 | How to replace the diff output shown by magit? | 2021-10-17T06:16:56.947 | # Question
Title: How to replace the diff output shown by magit?
Is there a way to switch out magit's diff display with a 3rd party output?
I would like to use delta which has syntax highlighting & word-level diffs.
Is there a way of integrating 3rd party packages? Or would I be better off writing my own package that launches a different kind of diff view from magit?
This is a comparison with vdiff & delta.
---
Note: I'm awaer of ediff, however it doesn't seem to have a way to produce a small/concise summary of the diff (the whole buffer is shown and each file needs to be handled one-by-one).
# Answer
> 1 votes
There is a package magit-delta that does exactly this.
---
Tags: magit, diff
--- |
thread-44431 | https://emacs.stackexchange.com/questions/44431 | How to suppress a minor mode's key binding in only certain major modes? | 2018-08-30T18:48:50.187 | # Question
Title: How to suppress a minor mode's key binding in only certain major modes?
Suppose that I use minor mode MIN with a whole bunch of major modes. In one of those major modes, call it MAJ1, MIN's binding for a specific key K is undesirable; I would therefore like to suppress that definition and get Emacs to fall back to either the major mode's definition, if any, or the default in global-map. However, I don't want to change how MIN handles that key when it's used with any other major mode, and I want to preserve MIN's other effects in MAJ1. What's the best way to accomplish that?
The specific combination I'm concerned with is Typo minor mode + Markdown major mode (these are both installed as ELPA packages) and the printable character ``` (ASCII backtick), which is syntactically significant in Markdown. typo-mode defines ``` to insert (left single quote) and then replace that with a backtick if pressed again. 99% of the time when I type ``` in a markdown file I want the ASCII backtick, so I want to get rid of the typo-mode binding, but only when the major mode is markdown-mode.
Typo mode is activated from text-mode-hook:
```
(add-hook 'text-mode-hook
#'(lambda ()
(auto-fill-mode 1)
(typo-mode 1)))
```
The obvious place to put a markdown-specific override is markdown-mode-hook, so I tried
```
(add-hook 'markdown-mode-hook
#'(lambda ()
(local-set-key (kbd "`") 'self-insert-command)))
```
but that seems to have no effect at all; I'm guessing that the typo-mode keymap only gets applied *after* markdown-mode-hook finishes.
Complicating matters, markdown-mode has optional electric behavior for ```, so *ideally* what I would be doing is punching a markdown-specific hole in the typo-mode keymap to allow the markdown-mode-map binding to take effect for this key, but if there's no good way to do that, I could live with a solution that just gets it bound to self-insert-command.
# Answer
> 5 votes
I don't think there's an easy way out for this one. You might do something like:
```
(add-hook 'typo-mode-hook
(lambda ()
(when (and typo-mode (derived-mode-p 'markdown-mode))
(let ((map (make-sparse-keymap)))
(set-keymap-parent map typo-mode-map)
(define-key map (kbd "`") 'self-insert-command)
(push `(typo-mode . ,map)
minor-mode-overriding-map-alist)))))
```
# Answer
> 0 votes
While this is not a general-purpose solution, future readers might like to know that typo-mode has a hook `typo-disable-electricity-functions` that can be used to solve the specific case of not wanting typo's behavior for some keys in some major modes. Here's what I have been using for a while now:
```
(defun zw-typo-inappropriate-electricity-for-markdown ()
"Hook for typo-disable-electricity-functions: Typographical
punctuation is desirable in Markdown mode, but should be disabled
if we are inside code (either inline or block), and the typo-mode
binding for ` should be disabled altogether."
(and (derived-mode-p 'markdown-mode)
(or (eq last-command-event ?`)
(markdown-inline-code-at-point-p)
(markdown-code-block-at-point-p))))
(add-hook 'typo-disable-electricity-functions
'zw-typo-inappropriate-electricity-for-markdown)
```
(The predicates `markdown-inline-code-at-point-p` and `markdown-code-block-at-point-p` are defined by current versions of markdown-mode.)
---
Tags: key-bindings, hooks, minor-mode
--- |
thread-68971 | https://emacs.stackexchange.com/questions/68971 | Changing the file name of the pdf generated by emacs in Latex/AUCTeX mode | 2021-10-17T22:13:11.880 | # Question
Title: Changing the file name of the pdf generated by emacs in Latex/AUCTeX mode
I'm using AUCTeX mode in emacs, and I want the generated pdf (after I run `C-c C-c`) to be in the parent directory instead of the current one.
In other words, I want to be able to change the filename of the generated file.
# Answer
Perhaps, this is what you're looking for.
> -- User Option: TeX-output-dir
>
> ```
> Set this option to the path of a directory where output files will
> be placed. The output files include those that are produced by
> applications running under AUCTeX, temporary files related to
> region processing and the preview-latex files. If a relative path
> is specified, it is interpreted as being relative to the master
> file in a multifile document.
>
> This is a buffer local variable and must be set separately for all
> documents and all files in a multifile document. For example,
> %%% Local Variables:
> %%% mode: latex
> %%% TeX-output-dir: "build"
> %%% End:
>
> ```
> 1 votes
---
Tags: latex, auctex
--- |
thread-68973 | https://emacs.stackexchange.com/questions/68973 | Emacs / Doom emacs taking a lot of memory | 2021-10-17T22:46:33.223 | # Question
Title: Emacs / Doom emacs taking a lot of memory
I'm using Doom Emacs, which is taking a lot of Memory if my browser is opened with 10 tabs. What can I do to reduce amount of memory being used, without sacrificing the packages?
My config.el is as
```
(add-to-list 'default-frame-alist
'(ns-transparent-titlebar . t))
(setq user-full-name ""
user-mail-address "")
(setq doom-theme 'doom-tomorrow-night)
(setq org-directory "~/org/")
(setq display-line-numbers-type t)
(setq ring-bell-function 1)
(require 'company-dict)
(setq company-dict-dir (concat user-emacs-directory "dict/"))
(add-to-list 'company-backends 'company-dict)
(define-key evil-insert-state-map (kbd "C-x C-k") 'company-dict)
(add-to-list 'default-frame-alist '(inhibit-double-buffering . t))
(setq fancy-splash-image (concat doom-private-dir "logo3.png"))
(remove-hook '+doom-dashboard-functions #'doom-dashboard-widget-shortmenu)
(remove-hook '+doom-dashboard-functions #'doom-dashboard-widget-footer)
(use-package! beacon)
(beacon-mode 1)
(setq beacon-color "red")
;; (setq beacon-blink-duration 0.1)
(setq beacon-blink-when-window-scrolls 1)
(setq beacon-blink-when-point-moves-vertically 1)
(defface custom-line-highlight '((t
(:foreground "#61dafb" :extend t)
)) "")
(add-hook
'treemacs-mode-hook
(defun channge-hl-line-mode ()
(setq-local hl-line-face 'custom-line-highlight)
(overlay-put hl-line-overlay 'face hl-line-face)
(treemacs--setup-icon-background-colors)))
(after! treemacs
(setq evil-treemacs-state-cursor 1
treemacs-show-cursor 1
))
(functionp 'json-serialize)
(setq gc-cons-threshold 100000000)
(setq read-process-output-max (* 1024 1024)) ;; 1mb
;; (setq lsp-idle-delay 0.500)
(setq byte-compile-warnings '(cl-functions))
;; Fonts
(setq doom-font (font-spec :family "JetBrainsMono" :size 12 :weight 'light)
doom-variable-pitch-font (font-spec :family "Noto Serif" :size 13)
ivy-posframe-font (font-spec :family "JetBrainsMono" :size 15))
(after! doom-themes
(setq doom-themes-enable-bold t
doom-themes-enable-italic t))
(custom-set-faces!
'(font-lock-comment-face :slant italic)
'(font-lock-keyword-face :slant italic))
```
my packages.el as
```
(package! prettier-js)
```
my init.el as
```
(doom! :input
;;chinese
;;japanese
;;layout ; auie,ctsrnm is the superior home row
:completion
company ; the ultimate code completion backend
;;helm ; the *other* search engine for love and life
;;ido ; the other *other* search engine...
;;ivy ; a search engine for love and life
vertico ; the search engine of the future
:ui
;; deft ; notational velocity for Emacs
doom ; what makes DOOM look the way it does
doom-dashboard ; a nifty splash screen for Emacs
;; doom-quit ; DOOM quit-message prompts when you quit Emacs
;;(emoji +unicode) ;
hl-todo ; highlight TODO/FIXME/NOTE/DEPRECATED/HACK/REVIEW
;;hydra
indent-guides ; highlighted indent columns
;;ligatures ; ligatures and symbols to make your code pretty again
minimap ; show a map of the code on the side
(modeline +light) ; snazzy, Atom-inspired modeline, plus API
;;nav-flash ; blink cursor line after big motions
;;neotree ; a project drawer, like NERDTree for vim
ophints ; highlight the region an operation acts on
(popup +defaults) ; tame sudden yet inevitable temporary windows
tabs ; a tab bar for Emacs
treemacs ; a project drawer, like neotree but cooler
;;unicode ; extended unicode support for various languages
vc-gutter ; vcs diff in the fringe
vi-tilde-fringe ; fringe tildes to mark beyond EOB
window-select ; visually switch windows
workspaces ; tab emulation, persistence & separate workspaces
zen ; distraction-free coding or writing
:editor
(evil +everywhere); come to the dark side, we have cookies
file-templates ; auto-snippets for empty files
fold ; (nigh) universal code folding
;;(format +onsave) ; automated prettiness
;;god ; run Emacs commands without modifier keys
;;lispy ; vim for lisp, for people who don't like vim
multiple-cursors ; editing in many places at once
;;objed ; text object editing for the innocent
;;parinfer ; turn lisp into python, sort of
rotate-text ; cycle region at point between text candidates
snippets ; my elves. They type so I don't have to
;;word-wrap ; soft wrapping with language-aware indent
:emacs
(dired +ranger +icons) ; making dired pretty [functional]
electric ; smarter, keyword-based electric-indent
ibuffer ; interactive buffer management
undo ; persistent, smarter undo for your inevitable mistakes
vc ; version-control and Emacs, sitting in a tree
:term
;;eshell ; the elisp shell that works everywhere
;;shell ; simple shell REPL for Emacs
;;term ; basic terminal emulator for Emacs
vterm ; the best terminal emulation in Emacs
:checkers
syntax ; tasing you for every semicolon you forget
;;(spell +flyspell) ; tasing you for misspelling mispelling
;;grammar ; tasing grammar mistake every you make
:tools
;;ansible
;;debugger ; FIXME stepping through code, to help you add bugs
;;direnv
;;docker
;;editorconfig ; let someone else argue about tabs vs spaces
;;ein ; tame Jupyter notebooks with emacs
(eval +overlay) ; run code, run (also, repls)
;;gist ; interacting with github gists
lookup ; navigate your code and its documentation
lsp ; M-x vscode
magit ; a git porcelain for Emacs
;;make ; run make tasks from Emacs
pass ; password manager for nerds
;;pdf ; pdf enhancements
;;prodigy ; FIXME managing external services & code builders
;;rgb ; creating color strings
;;taskrunner ; taskrunner for all your projects
terraform ; infrastructure as code
;;tmux ; an API for interacting with tmux
;;upload ; map local to remote projects via ssh/ftp
:os
(:if IS-MAC macos) ; improve compatibility with macOS
;;tty ; improve the terminal Emacs experience
:lang
;;agda ; types of types of types of types...
;;beancount ; mind the GAAP
(cc +lsp) ; C > C++ == 1
;;clojure ; java with a lisp
;;common-lisp ; if you've seen one lisp, you've seen them all
;;coq ; proofs-as-programs
;;crystal ; ruby at the speed of c
;;csharp ; unity, .NET, and mono shenanigans
;;data ; config/data formats
;;(dart +flutter) ; paint ui and not much else
;;dhall
;;elixir ; erlang done right
;;elm ; care for a cup of TEA?
emacs-lisp ; drown in parentheses
;;erlang ; an elegant language for a more civilized age
;;ess ; emacs speaks statistics
;;factor
;;faust ; dsp, but you get to keep your soul
;;fsharp ; ML stands for Microsoft's Language
;;fstar ; (dependent) types and (monadic) effects and Z3
;;gdscript ; the language you waited for
(go +lsp) ; the hipster dialect
;;(haskell +lsp) ; a language that's lazier than I am
;;hy ; readability of scheme w/ speed of python
;;idris ; a language you can depend on
json ; At least it ain't XML
(java +meghanada) ; the poster child for carpal tunnel syndrome
(javascript +lsp) ; all(hope(abandon(ye(who(enter(here))))))
;; julia ; a better, faster MATLAB
;;kotlin ; a better, slicker Java(Script)
;;latex ; writing papers in Emacs has never been so fun
;;lean ; for folks with too much to prove
;;ledger ; be audit you can be
;;lua ; one-based indices? one-based indices
markdown ; writing docs for people to ignore
;;nim ; python + lisp at the speed of c
;;nix ; I hereby declare "nix geht mehr!"
;;ocaml ; an objective camel
(org +brain +pomodoro +pretty) ; organize your plain life in plain text
php ; perl's insecure younger brother
;;plantuml ; diagrams for confusing people more
;;purescript ; javascript, but functional
(python +pyright) ; beautiful is better than ugly
;;qt ; the 'cutest' gui framework ever
;;racket ; a DSL for DSLs
;;raku ; the artist formerly known as perl6
;; rest ; Emacs as a REST client
;;rst ; ReST in peace
;;(ruby +rails) ; 1.step {|i| p "Ruby is #{i.even? ? 'love' : 'life'}"}
(rust +lsp) ; Fe2O3.unwrap().unwrap().unwrap().unwrap()
;;scala ; java, but good
;;(scheme +guile) ; a fully conniving family of lisps
sh ; she sells {ba,z,fi}sh shells on the C xor
;;sml
;;solidity ; do you need a blockchain? No.
;;swift ; who asked for emoji variables?
;;terra ; Earth and Moon in alignment for performance.
web ; the tubes
;;yaml ; JSON, but readable
;;zig ; C, but simpler
:email
;;(mu4e +org +gmail)
;;notmuch
;;(wanderlust +gmail)
:app
;;calendar
;;emms
;;everywhere ; *leave* Emacs!? You must be joking
;;irc ; how neckbeards socialize
;;(rss +org) ; emacs as an RSS reader
;;twitter ; twitter client https://twitter.com/vnought
:config
;;literate
(default +bindings +smartparens))
```
I've not installed much packages but still taking a lot of ram :(
# Answer
> 1 votes
Possibly a duplicate.
Find out module slowing down emacs
This may be what you're looking for.
Emacs Lisp Profiler
---
Tags: spacemacs, doom, performance
--- |
thread-52604 | https://emacs.stackexchange.com/questions/52604 | customized week label in org-mode agenda view | 2019-09-10T10:20:51.203 | # Question
Title: customized week label in org-mode agenda view
Is it possible for org-mode agenda view to display a customized label for the week, in addition to the week number included by default? For example, the agenda for the current week shows:
```
Week-agenda (W37):
Monday 9 September 2019 W37
```
Instead, I would like it to show one of the following options, or a similar one (no preference, other than ease of implementation):
```
Week-agenda (W37 | A W00):
Monday 9 September 2019 W37 | A W00
```
```
Week-agenda (W37):
Monday 9 September 2019 W37 | A W00
```
```
Week-agenda (W37 | A W00):
Monday 9 September 2019 W37
```
The custom label captures one of three periods in the year (A--C), each comprising 10 weeks (W00--W10). The start date for each period is arbitrary, so it has to be set manually.
# Answer
> 0 votes
I believe the answer is 'no'. However, you can create a property on the org files that contains the custom week number and then create a customized org agenda view based on a search for that property. This view can be saved as a custom command in `org-agenda-custom-commands`.
---
Tags: org-mode, org-agenda
--- |
thread-68962 | https://emacs.stackexchange.com/questions/68962 | clean weird characters from org source shell | 2021-10-17T03:23:00.057 | # Question
Title: clean weird characters from org source shell
When I run a shell command in Org I sometimes get back weird control characters:
```
#+begin_src sh :results output :session test
guix pull
#+end_src
#+RESULTS:
:
: Updating channel 'guix' from Git repository at 'https://git.savannah.gnu.org/git/guix.git'...
: Building from this channel:
: guix https://git.savannah.gnu.org/git/guix.git 258a27e
: Computing Guix derivation for 'x86_64-linux'... ^H-^H\^H|^H/^H-^H\^H|^H/^H-^H\^H|^H/^H-^H\^H|^H/^H-^H\^H|^H/^H-^H\^H|^H/^H-^H\^H|^H/^H-^H\^H|^H/^H-^H\^H|^H/^H-^H\^H|^H/^H-^H\^H|^H/^H-^H\^H|^H/^H-^H\^H|^H/^H-^H\
: nothing to be done
```
It's not just `^H`, but many others. I can replace them if I have them present. However, I can't store them in a regex within a clean-up function because it's not clear how to encode the file it's saved in.
Answers to similar questions have suggested to check locale. I would think this should be okay:
```
#+begin_src sh :results output :session test
export | grep LANG
#+end_src
#+RESULTS:
: export GDM_LANG="en_US.utf8"
: export LANG="en_US.utf8"
```
Others have suggested changing `PS1` in `.bashrc`. These made no difference. It seems the shell used by Org is already stripped down:
```
#+begin_src sh :results output :session test
echo $PS1
#+end_src
#+RESULTS:
:
: \s-\v\$
```
Still more have suggested bracketed paste mode may be a factor. It may be, but definitely not for the `guix pull` above. As far as I understand, bracketed paste mode is only for `ESC [ 2 0 0 ~ ,` and `ESC [ 2 0 1 ~ .`. I have not seen these or, at the very least can't reproduce them.
I'm at a loss for how to clean up these control characters or, better yet, not produce them in the first place. Any advice?
# Answer
> 1 votes
guix is making a spinner by printing a character, backspacing over it, and printing something else. Programs are only supposed to do these things if they have reason to believe that their output is going to a terminal. Since `org-mode` is not a terminal, guix shouldn’t be doing this. It might be a bug you should report to them at https://issues.guix.gnu.org/, but it could just be that it thinks that it is in a terminal.
What is `TERM` getting set to in the subprocess?
```
#+begin_src sh :results output
echo $TERM
#+end_src
#+RESULTS:
: dumb
```
If it is anything other than “dumb”, then you should check your shell startup files to see if you’re explicitly setting it to something else. This is quite common, but always a mistake. You should allow your terminal to set it for you, and then leave it alone.
---
Tags: org-babel, shell, control-characters
--- |
thread-68986 | https://emacs.stackexchange.com/questions/68986 | Ignore footnotes when exporting org texts to html | 2021-10-18T15:32:48.460 | # Question
Title: Ignore footnotes when exporting org texts to html
I want to export org texts to HTML. This is easy if I use `org-export-string-as`. The problem is, the org texts may contain unreferenced footnotes, I want the export function to ignore the footnotes. Here is my code:
```
(let ((org-text (concat "* Header\n" "Text[fn:1]."))
(my-backend (org-export-create-backend
:parent 'html
:transcoders '((footnote-reference . ignore)))))
(org-export-string-as org-text my-backend t nil))
```
As you can see, I set the transcoder of `footnote-reference` to `ignore`, but it doesn't work. I still got an error when running the above code:
```
Definition not found for footnote 1
```
Why? What should I do?
# Answer
Setting `org-export-with-footnotes` to `nil` seems to work fine:
```
(let ((org-text (concat "* Header\n" "Text[fn:1]."))
(my-backend (org-export-create-backend
:parent 'html
;;:transcoders '((footnote-reference . ignore))
))
(org-export-with-footnotes nil))
(org-export-string-as org-text my-backend t nil))
```
It produces:
```
"<div id=\"table-of-contents\" role=\"doc-toc\">
<h2>Table of Contents</h2>
<div id=\"text-table-of-contents\" role=\"doc-toc\">
<ul>
<li><a href=\"#org27ffc60\">1. Header</a></li>
</ul>
</div>
</div>
<div id=\"outline-container-org27ffc60\" class=\"outline-2\">
<h2 id=\"org27ffc60\"><span class=\"section-number-2\">1.</span> Header</h2>
<div class=\"outline-text-2\" id=\"text-1\">
<p>
Text.</p>
</div>
</div>
"
```
Of course, you don't need `my-backend` any longer, but I left that in just in case you have other things up your sleeve :-)
> 1 votes
---
Tags: org-mode, org-export
--- |
thread-68995 | https://emacs.stackexchange.com/questions/68995 | How to fill a string programmatically like fill-region in elisp? | 2021-10-18T23:02:55.393 | # Question
Title: How to fill a string programmatically like fill-region in elisp?
Here is what I want:
```
(fill-string ";; This is a long string to be inserted into a buffer somewhere. Okay that's it.")
```
This should insert line breaks according to the `fill-column`. Something like this should be returned,
```
;; This is a long string to
;; be inserted into a buffer
;; somewhere. Okay that's it.
```
This can be done interactively if the string is in the buffer and you select it and call `M-x fill-region` but I can't find a way of doing this programmatically.
# Answer
> 3 votes
You can insert the string into a temporary buffer, fill the region, and read the contents of the buffer as a string:
```
(defun fill-string (s)
(with-temp-buffer
(emacs-lisp-mode)
(insert s)
(fill-region (point-min) (point-max))
(buffer-substring (point-min) (point-max))))
```
We put the temp buffer in `emacs-lisp` mode so that the filling will add the comment characters at the beginning of each line.
You can use the function like this:
```
(setq my-filled-comment
(let ((fill-column 25))
(fill-string ";; This is a long string to be inserted into a buffer somewhere. Okay that's it.")))
```
That binds `fill-column` to 25 for the duration of the `fill-string` call and sets the variable `my-filled-comment` to the result. You can then insert it wherever you want. The result looks like this:
```
;; This is a long string
;; to be inserted into a
;; buffer somewhere. Okay
;; that's it.
```
---
Tags: string, fill-paragraph, fill-column
--- |
thread-64849 | https://emacs.stackexchange.com/questions/64849 | Emacs error cannot load file counsel | 2021-05-14T19:28:30.827 | # Question
Title: Emacs error cannot load file counsel
I'm getting this error whenever I try to open `Emacs`:
```
Debugger entered--Lisp error: (file-missing "Cannot open load file" "No such file or directory" "counsel")
require(counsel)
ivy-rich-set-display-transformer(backup)
ivy-rich-mode(1)
(condition-case err (ivy-rich-mode 1) ((debug error) (funcall use-package--warning13 :init err)))
(progn (condition-case err (ivy-rich-mode 1) ((debug error) (funcall use-package--warning13 :init err))) (if (not (require 'ivy-rich nil t)) (display-warning 'use-package (format "Cannot load %s" 'ivy-rich) :error)))
(lambda nil (progn (condition-case err (ivy-rich-mode 1) ((debug error) (funcall use-package--warning13 :init err))) (if (not (require 'ivy-rich nil t)) (display-warning 'use-package (format "Cannot load %s" 'ivy-rich) :error))))()
eval-after-load(ivy (lambda nil (progn (condition-case err (ivy-rich-mode 1) ((debug error) (funcall use-package--warning13 :init err))) (if (not (require 'ivy-rich nil t)) (display-warning 'use-package (format "Cannot load %s" 'ivy-rich) :error)))))
(condition-case err (eval-after-load 'ivy #'(lambda nil (progn (condition-case err (ivy-rich-mode 1) ((debug error) (funcall use-package--warning13 :init err))) (if (not (require ... nil t)) (display-warning 'use-package (format "Cannot load %s" ...) :error))))) ((debug error) (funcall use-package--warning13 :catch err)))
eval-buffer(#<buffer *load*> nil "/home/apoorv/.emacs.d/init.el" nil t) ; Reading at buffer position 10649
load-with-code-conversion("/home/apoorv/.emacs.d/init.el" "/home/apoorv/.emacs.d/init.el" t t)
load("/home/apoorv/.emacs.d/init" noerror nomessage)
startup--load-user-init-file(#f(compiled-function () #<bytecode 0x1579fa7368c5>) #f(compiled-function () #<bytecode 0x1579fa731b9d>) t)
command-line()
normal-top-level()
```
I have my configuration as a `org` document, this the block that installs `counsel`,
```
(use-package counsel
:init
:bind (("M-x" . counsel-M-x)
("C-x b" . counsel-ibuffer)
("C-x C-f" . counsel-find-file)
("C-M-j" . 'counsel-switch-buffer)
:map minibuffer-local-map
("C-r" . 'counsel-minibuffer-history))
:custom
(counsel-linux-app-format-function #'counsel-linux-app-format-function-name-only)
:config
(counsel-mode 1)
(setq ivy-initial-inputs-alist nil)) ;; Don't start searches with ^
```
I also tried installing `counsel` manually by `M-x package-install` but it didn't help either.
# Answer
I'd recommend purging your elpa directory, and then restarting emacs:
```
$ cd ~/.emacs.d/elpa
$ rm -rf *
$ emacs
```
> 1 votes
---
Tags: package, error
--- |
thread-68992 | https://emacs.stackexchange.com/questions/68992 | How to force exit man buffer preventing jumping into *Messages* buffer | 2021-10-18T21:24:36.197 | # Question
Title: How to force exit man buffer preventing jumping into *Messages* buffer
I am using `emacs` to read man pages.
```
macsman() {
emacsclient -nw -e "(let ((Man-notify-method 'bully)) (man \"$1\"))"
}
alias man=macsman
```
---
```
(define-key Man-mode-map "q" 'save-buffers-kill-emacs)
```
While man buffer is opened, when I press `q` it usually exits.
> It is bound to `If the current frame has no client, kill Emacs itself using ‘save-buffers-kill-emacs’.`
After running ex: `man ls` and pressing "`q`" in order to exit and get back to my shell, I find myself in `*Messages*` buffer, than pressing `q` again opens the man page again, and finally pressing `q` exits `emacs`. What may be the reason of this?
Would it be possible to exit right away by preventing opening `*Messages*` buffer?
# Answer
> 1 votes
If you're just popping in and out for the man page, you don't need the `save-buffers-kill-emacs` because there are no buffers to save. Just unconditionally kill Emacs.
```
Command: kill-emacs &optional exit-data
This command calls the hook kill-emacs-hook, then exits the Emacs
process and kills it.
If exit-data is an integer, that is used as the exit status of the
Emacs process. (This is useful primarily in batch operation; see Batch
Mode.)
If exit-data is a string, its contents are stuffed into the terminal
input buffer so that the shell (or whatever program next reads input)
can read them.
If exit-data is neither an integer nor a string, or is omitted, that
means to use the (system-specific) exit status which indicates
successful program termination.
```
---
Tags: exit, man
--- |
thread-68985 | https://emacs.stackexchange.com/questions/68985 | Customising org-mode link click behaviour | 2021-10-18T15:12:44.043 | # Question
Title: Customising org-mode link click behaviour
My current (default) behaviour when click a `[[link]]` in org-mode is for Emacs to search a matching heading.
However, I wanted to redefine this behaviour to open a file called `link.org`. That is, for every link I have `[[foo]]`, clicking it would be same as clicking `[[file:./foo.org]]`. How can I do this?
*Note*: I could write all my links as `[[file:./foo.org]]` but I wanted to leave them as `[[foo]]` for compatibility with external applications.
# Answer
Retask `C-c C-o` and/or add a modifier to the mouse click, like `M-<click>`. Essentially, instead of handling a normal click event, and following the link, they fire a function that opens the target document.
> 1 votes
---
Tags: org-mode, org-link
--- |
thread-69003 | https://emacs.stackexchange.com/questions/69003 | call windows batch from shell | 2021-10-19T18:17:27.990 | # Question
Title: call windows batch from shell
I'm trying to run QGIS from the command-line on Windows. QGIS provides a batch file for this, "C:\Program Files\QGIS 3.20.3\bin\qgis.bat". When I run this from within Emacs shell, the load hangs when QGIS tries to load it's Python interpreter.
To reproduce, start a new shell in Emacs with `M-x shell` and call `"C:\Program Files\QGIS 3.20.3\bin\qgis.bat"`. If instead you first call `start` (to load a new prompt) and then call `"C:\Program Files\QGIS 3.20.3\bin\qgis.bat"` in that, QGIS loads.
Looking at `qgis.bat`, it calls several other batch files and also sets many environment variables. My guess is that some necessary variables aren't set when called directly from shell.
Is there a way to call the batch directly from Emacs shell so that QGIS loads?
# Answer
This is a workaround to run, kill, and rerun QGIS:
```
(defun rerun-qgis ()
(interactive)
;; kill any running instance of QGIS
(shell-command "taskkill /f /fi \"IMAGENAME eq qgis-bin.exe\"")
;; kill any lingering command window
(shell-command "taskkill /f /t /fi \"WINDOWTITLE eq \\qgis\\ \"")
;; start QGIS; opens a command window which isn't needed beyond the
;; load. Retitle it "\qgis\" (because shell quoting is unfun and
;; that's what I got to work) so that we can kill it directly with
;; taskkill after load.
(let ((proc (start-process "cmd" nil "cmd.exe" "/C" "start" "\"qgis\"" "cmd.exe" "/K" "C:\\Program Files\\QGIS 3.20.3\\bin\\qgis.bat")))
(set-process-query-on-exit-flag proc nil))
;; assume qgis loads in 3 seconds and kill the lingering command
;; window; I couldn't get a sentinel to work
(run-at-time "3 sec" nil #'(lambda () (shell-command "taskkill /f /fi \"WINDOWTITLE eq \\qgis\\ \""))))
```
> 0 votes
---
Tags: microsoft-windows, shell
--- |
thread-68987 | https://emacs.stackexchange.com/questions/68987 | Spacemacs org-mode faces | 2021-10-18T15:38:22.853 | # Question
Title: Spacemacs org-mode faces
How do I turn off all of the custom faces used by Spacemacs `org-mode`? For example, the background colouring, the overlines, the bold faces etc.
I tried using the `Customize` sub-menu from the `Org` menu to set my own faces, and it added lines like:
```
'(org-level-1 ((t nil)))
```
to `custom-set-faces` in my `.dotspacemacs` file. However, this doesn't stop Spacemacs showing the top-level heading with a large bold font on a gray background. I find these visual decorations very distracting and just want to see the text that I type!
# Answer
> 0 votes
If you really want to disable all faces then you should deactivate `font-lock-mode` by doing `M-x font-lock-mode`.
You could configure it to happen automatically by adding an `org-mode-hook` as follows in the `user-config` section of your dotfile:
```
(defun my-disable-font-lock ()
(font-lock-mode 0))
(add-hook 'org-mode-hook 'my-disable-font-lock)
```
# Answer
> 0 votes
Put your cursor on the offending text, then in the top menu, *Options-\>Customize Emacs-\>Specific Face* and you will go directly to the one you want to change.
---
Tags: org-mode, spacemacs
--- |
thread-68936 | https://emacs.stackexchange.com/questions/68936 | bind-keys with a macro for lambda functions | 2021-10-15T09:58:34.773 | # Question
Title: bind-keys with a macro for lambda functions
I am trying to bind keys to a lambda function using `bind-key.el`. I have the following factor macro
```
;; taken from Emacs Doom
(defmacro cmd! (&rest body)
(declare (doc-string 1) (pure t) (side-effect-free t))
`(lambda (&rest _) (interactive) ,@body))
```
which creates a lambda interactive function. So at first, I tried using that to bind-keys with no success.
```
(use-package org
:bind (:map org-mode-map
("C-c C-f" . (cmd! (message "Test")))))
```
But then I get the error. `use-package: org-super-agenda wants arguments acceptable to the 'bind-keys' macro...`. I also tried
```
(bind-keys :map org-mode-map
("C-c C-f" . (cmd! (message "Test"))))
```
but then I get the error `command-execute: Wrong type argument: commandp, (cmd! (message "Test"))` when I press `C-c C-f`.
I then tried replacing `(cmd! ...` with `(lambda () (interactive) ...)`
```
(bind-keys :map org-mode-map
("C-c C-f" . (lambda () (interactive) (message "Test"))))
```
but then I get stuck in an infinite loop when executing the previous statement. When stopping with `C-g`, I find that I am stuck in a function called `prin1-to-string` with a seemingly infinite
```
(closure ((binding closure ((binding closure ((binding closure ... nil ... ...)
```
as an argument. I think the reason is that in my particular file with lexical binding, closing the lambda expression is expensive.
How am I supposed to do this efficiently?
# Answer
Here's the format.
```
(bind-key KEY-NAME COMMAND &optional KEYMAP PREDICATE)
(bind-key "M-h" #'some-interactive-function my-mode-map)
```
`(bind-key "C-c iv" (lambda()(interactive) (my-function-here my-func-parameter)) my-mode-map)`
Documentation is your friend. `C-h f bind-key`.
> 0 votes
---
Tags: key-bindings, bind-key.el, lambda
--- |
thread-68937 | https://emacs.stackexchange.com/questions/68937 | Org export visible headings only | 2021-10-15T11:48:31.737 | # Question
Title: Org export visible headings only
I'm customising my export settings for a particular file using `#+OPTIONS`. I want to be able to set the defaults for `org-export-dispatch` for this particular file too.
In particular I want `Visible only: On` by default (again, for this file only).
The notes that I want to export are not hugely structured, so I don't want to build a sparse tree using particular tags. I just want the currently visible items.
# Answer
When you're in the buffer, `C-c C-e` brings up the dispatch menu. `C-v` there toggles `Visible only` setting. This seems to do what you want. No special settings are required.
NB I'm using Org 9.5. I don't know if this is a new feature, or no.
> -1 votes
---
Tags: org-mode, org-export
--- |
thread-69009 | https://emacs.stackexchange.com/questions/69009 | How to get org-time-stamp to return timestamp rather than inserting? | 2021-10-20T01:14:36.497 | # Question
Title: How to get org-time-stamp to return timestamp rather than inserting?
I am writing a function that includes the formatted timestamp that is produced by the prompt from `org-time-stamp`. However, calling the function cause it to insert the timestamp into the buffer.
Is there any other similar function which produces the same calendar prompt as `org-time-stamp` that I can utilize for my function?
# Answer
There is no such function: `org-time-stamp` is "sui generis".
The best thing to do is to define a new function that calls `org-time-stamp` in the context of a temporary buffer and then returns the string that is inserted into that buffer:
```
(defun my/org-time-stamp-string ()
(with-temp-buffer
(org-mode)
(org-time-stamp nil nil)
(buffer-substring (point-min) (point-max))))
```
Then you can call it like this:
```
(setq ts (my/org-time-stamp-string))
```
to store the string in `ts` and then do whatever you want with it.
For a different example of the same technique, see another recent answer of mine.
> 2 votes
---
Tags: org-mode, time-date
--- |
thread-54581 | https://emacs.stackexchange.com/questions/54581 | How to make highlights persistent? | 2019-12-29T23:40:32.647 | # Question
Title: How to make highlights persistent?
I don't want themes. I use bold,italics, and highlights. I also use background colors per file, so the code as in for background need to be embedded inside file.
But when I `Edit->Text Properties->Face->other` And select `highlight` upon reopening the file it's gone as the encoding isn't embedded inside the file, but bold does in this format when I open `M-x find-file-literally` I see this encoding `<bold> BOLDED FONT <\bold>`.
> Background color is not changed even though foreground color of text changes! What's wrong with background color?
I save them in enriched mode.
# Answer
As far as I can see, the problem is that `enriched-face-ans` does not consider inherited face attributes when it queries attributes with function `face-attribute`.
It should call `face-attribute` with the `INHERIT` argument set to t.
I assume that failing to do so is a bug in `enriched-face-ans`. Maybe, you should file a bug report to `bug-gnu-emacs@gnu.org`.
There follows a bugfix. It is essentially the original version of `enriched-face-ans` with my small modifications marked by `Tobias`.
```
(defun ad-enriched-face-ans (face)
"Return annotations specifying FACE.
FACE may be a list of faces instead of a single face;
it can also be anything allowed as an element of a list
which can be the value of the `face' text property."
(cond ((and (consp face) (eq (car face) 'foreground-color))
(list (list "x-color" (cdr face))))
((and (consp face) (eq (car face) 'background-color))
(list (list "x-bg-color" (cdr face))))
((and (listp face) (eq (car face) :foreground))
(list (list "x-color" (cadr face))))
((and (listp face) (eq (car face) :background))
(list (list "x-bg-color" (cadr face))))
((listp face)
(apply 'append (mapcar 'enriched-face-ans face)))
((let* ((fg (face-attribute face :foreground nil t)) ;; Tobias: Set INHERIT argument to t
(bg (face-attribute face :background nil t)) ;; Tobias: Set INHERIT argument to t
(props (face-font face t))
(ans (cdr (format-annotate-single-property-change
'face nil props enriched-translations))))
(unless (eq fg 'unspecified)
(setq ans (cons (list "x-color" fg) ans)))
(unless (eq bg 'unspecified)
(setq ans (cons (list "x-bg-color" bg) ans)))
ans))))
(advice-add 'enriched-face-ans :override #'ad-enriched-face-ans)
```
Tested with `GNU Emacs 26.3 (build 2, i686-pc-linux-gnu, GTK+ Version 3.22.30) of 2019-09-16`
by loading built-in library `add-log.el` and setting the `change-log-function` face on a stretch of text through "Edit → Text Properties → Face → Other → `change-log-function`" in an enriched buffer, saving and killing the buffer, and re-opening the corresponding file in Emacs.
> 1 votes
# Answer
i use GNU Emacs 26.3.
I had issue to save persistent highlighted text, using Text Property Face, under Enriched mode. I wanted to highlight with different style. So looking around the web and see this thread, which i don't really understand.
I finally am able to save persistent highlighted text, by doing below.
Then, ex. for the newly added face "Company Scrollbar Bg", i go to customize the variable of "Company Scrollbar Bg"
where, i think it needs to check/define its Foreground, Background and Inherit from Default. Then Save and Apply.
Also, in file .emacs, i have... \[.... '(font-lock-global-modes t) '(global-font-lock-mode t) '(global-hi-lock-mode nil) ...\] since some posts says hi-lock mode would interfere Enriched mode's highlight.
That's all i did. Hope it helps for those who has similar issue.
> 0 votes
---
Tags: faces, fonts, highlighting, enriched-mode
--- |
thread-68998 | https://emacs.stackexchange.com/questions/68998 | Minibuffer completion frameworks and interfaces | 2021-10-19T08:13:10.637 | # Question
Title: Minibuffer completion frameworks and interfaces
Emacs has a lot of different packages for minibuffer UI, search, and completion. Some of the packages I am aware of are Icicles, Ido, Ivy, Counsel, Swiper, Consult, Vertico, Selectrum, Orderless, Embark, Helm.
Some of these packages provide UI, some completion, some key mappings. As far as I understand some of them are designed to work with each other, and others are incompatible. Some packages may be old and practically deprecated. I found it very difficult to navigate this diverse landscape. Is there any consolidated comparison of what these packages provide, description of their compatibility and features?
# Answer
I guess the most elaborate comparison is given in the Selectrum readme.
Next to that I think you should read about the philosophy behind the Vertico and Embark packages, which I find very appealing. However, I have tried them out, and I guess especially for a beginner, it is a little hard and quite some work to find out which packages to include in the ecosystem, and how to configure all of them.
So to first get a feeling of a great, and more or less fully configured, minibuffer completion ecosystem, I would suggest you start with Ivy or Helm. Personally I use Spacemacs, which provides (suggests to use) Helm by default. But I have switched to Ivy because I find it a little easier to configure (i.e. use it in my own packages) and I have read in multiple places that it is more lightweight. For sure its counsel package (see start of Ivy readme) provides everything I require.
While using Ivy, and if you like to tinker, you can slowly read about and 'investigate' how to setup Vertico or Selectrum (or some other preferred alternative) and friends.
Of course this is only my, very briefly stated, personal perspective, and I am open to any comments/corrections/expansions on it.
> 4 votes
# Answer
When comparing consider simple vs complex. One factor to consider is keep it simple by using something built into emacs.
As you move from one computing platform to the next over time and prefer to use emacs using something native has advantages.
Some of the very powerful completion engines need a package manager to be installed, and the completion engine files to be installed and configured. Just the configuration may be more complex that everything you need to know to use a more basic tool. Much of this generally requires a computer be connected to the internet (to fetch packages) which may not be possible.
You may not want to repeat this procedure on every computing platform encountered (home/office desktop, lab machines, windows, Linux, machines on air-gaped networks etc). You will find little differences in the customization needed on different platforms which is a complicating factor.
The more complex 3rd party packages are also more prone to bugs and if you are a user you will find them (they are changing more frequently than emacs). Maybe you have an open source developers "happy to help" attitude or maybe you just want to get your job done.
Most of what is needed from a completion engine is complete files for find-file and select buffers for switch-buffer. The built in mechanisms tend to do this well stand-alone or with a simple configuration.
If users enjoy or need the complexity/power/features or are a emacs-lisp hobbyist then the more complex approaches might be worth it to you (if you are using emacs to develop emacs).
I work with people who use several other editors and none of them spend much time writing code for the editor or changing it for the platform they are on. I do spend the time. The others are free to spend time developing in the primary domain of concern (not developing/maintaining emacs).
I use icicles most of the time, and have found it very useful but difficult to learn, and maintain over a variety of computing environments for the past 10 years or so.
I have also used Ido.
Another users comments on icicles. http://ergoemacs.org/misc/emacs\_power\_of\_icicles.html
> 2 votes
---
Tags: completion, minibuffer
--- |
thread-68941 | https://emacs.stackexchange.com/questions/68941 | Loading hi-lock patterns from .emacs or custom .el file | 2021-10-15T17:16:36.203 | # Question
Title: Loading hi-lock patterns from .emacs or custom .el file
I'm trying to add syntax highlighting to specific file extensions (for example .foo). I can't have the Hi-lock patterns in the source code because I shouldn't be committing them. Is there a way of loading my hi-lock patterns from my .emacs or from a custom .el file when I open a .foo file?
This is my code in my .emacs file:
```
(add-to-list 'auto-mode-alist '("\\.foo\\'" . hi-lock-mode))
(defun fooInit ()
(("!" (0 (quote all-the-icons-dgreen) prepend)))
(("! .*$" (0 (quote all-the-icons-dgreen) prepend)))
(("!\\*.*$" (0 (quote all-the-icons-dgreen) prepend)))
(("!-.*$" (0 (quote all-the-icons-dgreen) prepend)))
)
(add-hook 'hi-lock-mode-hook 'fooInit)
```
I also tried
```
(add-to-list 'auto-mode-alist '("\\.foo\\'" . hi-lock-mode))
(defun fooInit()
Hi-lock: (("!" (0 (quote all-the-icons-dgreen) prepend)))
Hi-lock: (("! .*$" (0 (quote all-the-icons-dgreen) prepend)))
Hi-lock: (("!\\*.*$" (0 (quote all-the-icons-dgreen) prepend)))
Hi-lock: (("!-.*$" (0 (quote all-the-icons-dgreen) prepend)))
)
(add-hook 'hi-lock-mode-hook 'fooInit)
```
How can I do this?
# Answer
Does this work for you?
```
(add-to-list 'auto-mode-alist '("\\.foo\\'" . hi-lock-mode))
(defun fooInit ()
(highlight-regexp "!" 'all-the-icons-dgreen)
(highlight-regexp "! .*$" 'all-the-icons-dgreen)
(highlight-regexp "!\\*.*$" 'all-the-icons-dgreen)
(highlight-regexp "!-.*$" 'all-the-icons-dgreen))
(add-hook 'hi-lock-mode-hook 'fooInit)
```
If it does, and you're interested in expanding your Elisp skillset, then to optimise this you might combine those four patterns into a single one using `"\\|"`, or you might put the four patterns in a list and call `highlight-regexp` in a loop. The really advanced approach is to use `mapc`, but don't bother with that until you're ready and curious; just be aware that something called `mapc` exists.
> 0 votes
---
Tags: init-file, hi-lock
--- |
thread-69016 | https://emacs.stackexchange.com/questions/69016 | Cannot define custom latex class in org-mode | 2021-10-20T12:22:46.163 | # Question
Title: Cannot define custom latex class in org-mode
This is the code I tried:
```
(after! ox-latex
(add-to-list
'org-latex-classes
'("deeparticle"
(concat
"\\documentclass[11pt]{article}\n"
"\\usepackage{enumitem}\n"
"\\newenvironment{deepsection}[1]{\\begin{enumerate}[label={}] \\item \\textbf{#1} \\newline}{\\end{enumerate}}")
("\\section{%s}" . "\\section*{%s}")
("\\subsection{%s}" . "\\subsection*{%s}")
("\\subsubsection{%s}" . "\\subsubsection*{%s}")
("\\paragraph{%s}" . "\\paragraph*{%s}")
("\\subparagraph{%s}" . "\\subparagraph*{%s}")
("\\begin{deepsection}{%s}" "\\end{deepsection}" "\\begin{deepsection}{%s}" "\\end{deepsection}")
("\\begin{deepsection}{%s}" "\\end{deepsection}" "\\begin{deepsection}{%s}" "\\end{deepsection}")
("\\begin{deepsection}{%s}" "\\end{deepsection}" "\\begin{deepsection}{%s}" "\\end{deepsection}")
("\\begin{deepsection}{%s}" "\\end{deepsection}" "\\begin{deepsection}{%s}" "\\end{deepsection}")
("\\begin{deepsection}{%s}" "\\end{deepsection}" "\\begin{deepsection}{%s}" "\\end{deepsection}")
("\\begin{deepsection}{%s}" "\\end{deepsection}" "\\begin{deepsection}{%s}" "\\end{deepsection}")
("\\begin{deepsection}{%s}" "\\end{deepsection}" "\\begin{deepsection}{%s}" "\\end{deepsection}")
("\\begin{deepsection}{%s}" "\\end{deepsection}" "\\begin{deepsection}{%s}" "\\end{deepsection}")
("\\begin{deepsection}{%s}" "\\end{deepsection}" "\\begin{deepsection}{%s}" "\\end{deepsection}")
("\\begin{deepsection}{%s}" "\\end{deepsection}" "\\begin{deepsection}{%s}" "\\end{deepsection}"))))
```
I get `user-error: Unknown LaTeX class ‘deeparticle’` when trying to export.
Related SE question: Defining custom latex class for org-mode export (my code should be OK according to this)
# Answer
Fixed, I didn't quite grasp how quoting in elisp works. Correct code:
```
(after! ox-latex
(add-to-list
'org-latex-classes
`("deeparticle"
,(concat
"\\documentclass[11pt]{article}\n"
"\\usepackage{enumitem}\n"
"\\newenvironment{deepsection}[1]{\\begin{enumerate}[label={}] \\item \\textbf{#1} \\newline}{\\end{enumerate}}")
("\\section{%s}" . "\\section*{%s}")
("\\subsection{%s}" . "\\subsection*{%s}")
("\\subsubsection{%s}" . "\\subsubsection*{%s}")
("\\paragraph{%s}" . "\\paragraph*{%s}")
("\\subparagraph{%s}" . "\\subparagraph*{%s}")
("\\begin{deepsection}{%s}" "\\end{deepsection}" "\\begin{deepsection}{%s}" "\\end{deepsection}")
("\\begin{deepsection}{%s}" "\\end{deepsection}" "\\begin{deepsection}{%s}" "\\end{deepsection}")
("\\begin{deepsection}{%s}" "\\end{deepsection}" "\\begin{deepsection}{%s}" "\\end{deepsection}")
("\\begin{deepsection}{%s}" "\\end{deepsection}" "\\begin{deepsection}{%s}" "\\end{deepsection}")
("\\begin{deepsection}{%s}" "\\end{deepsection}" "\\begin{deepsection}{%s}" "\\end{deepsection}")
("\\begin{deepsection}{%s}" "\\end{deepsection}" "\\begin{deepsection}{%s}" "\\end{deepsection}")
("\\begin{deepsection}{%s}" "\\end{deepsection}" "\\begin{deepsection}{%s}" "\\end{deepsection}")
("\\begin{deepsection}{%s}" "\\end{deepsection}" "\\begin{deepsection}{%s}" "\\end{deepsection}")
("\\begin{deepsection}{%s}" "\\end{deepsection}" "\\begin{deepsection}{%s}" "\\end{deepsection}")
("\\begin{deepsection}{%s}" "\\end{deepsection}" "\\begin{deepsection}{%s}" "\\end{deepsection}"))))
```
> 1 votes
---
Tags: org-mode, org-export, latex, latex-header
--- |
thread-69019 | https://emacs.stackexchange.com/questions/69019 | How to apply code sample inside a line using org mode | 2021-10-20T16:17:13.703 | # Question
Title: How to apply code sample inside a line using org mode
In `org-mode` when I type following example code:
```
#+begin_src python
def main(*args):
from brownie import network, project
#+end_src
```
it will be previewed as, equivalent for `Code Sample` in markdown:
---
Would it be possible to achieve this for a singe for word or line `LIKE_THIS` code sample inside of a line:
---
Test `Hello World Doo` Test.
On the other hand preview of org mode:
---
When I try following `LIKE_THIS` in the org mode I see following in the preview:
---
I have tried following which did not work:
`#+begin_src python LIKE_THIS #+end_src`
which printed just a new line inside a code piece:
# Answer
> 2 votes
Markup for generic code in Org is either `=code=` or `~code~`. If you want to execute that code, then `src_python{print("Hello, world")}`, and you can `C-c C-c` on that line, and it will evaluate and print the results within that sentence. See more at https://orgmode.org/manual/Structure-of-Code-Blocks.html
---
Tags: org-mode
--- |
thread-69020 | https://emacs.stackexchange.com/questions/69020 | How can I remove more libs to reduce loading at startup? | 2021-10-20T16:45:44.167 | # Question
Title: How can I remove more libs to reduce loading at startup?
When I view the number of commands or functions through `M-x` I notice so many that I never use. However I also didn't load them explicitly in my `init.el` either. I do use `use-package` and have attempted to keep my dotfiles small and light, but it occurred to me that I might have some defaults going on in my build of Emacs that includes a number of 'site' libs. I'm not sure if there might be a recommended minimum, or how to removed these unnecessary libs from startup. How can I do that?
# Answer
You don’t need to remove anything. Emacs has a system called Autoloading that has a list of functions and what file they are defined in, and only loads the file when the function is called. This means that most of the functions you see in that list are things that are not yet fully loaded. They will only be fully loaded the first time you use them.
> 1 votes
---
Tags: init-file, start-up, load, site-lisp
--- |
thread-69023 | https://emacs.stackexchange.com/questions/69023 | Why binding M-Z to a command in org-mode with (define-key org-mode-map (kbd "<M-Z>") 'my-command) fails? | 2021-10-20T20:16:52.210 | # Question
Title: Why binding M-Z to a command in org-mode with (define-key org-mode-map (kbd "<M-Z>") 'my-command) fails?
For Emacs 26.3 running in terminal mode, I am trying to map a `my-command` to `M-Z` in org-mode by using the following code:
```
(with-eval-after-load org
(define-key org-mode-map (kbd "<M-Z>") #'my-command))
```
But this does not work.
It works if I do this instead:
```
(with-eval-after-load org
(define-key esc-map "Z" #'my-command))
```
But the latter binds `my-command` in the global map making it available everywhere, and I do not want that.
This behaves as if the `esc-map` takes precedence over the `org-mode-map`. I looked in org.el and I don't see that code copying anything from the `esc-map` defined in subr.el.
I thought it could because the org mode function has not yet run, so I tried adding the code inside a `org-mode-hook` as well (in addition to the above code):
```
(defun pel--org-set-keys ()
"Set keys."
(if (boundp 'org-mode-map)
(progn
(define-key org-mode-map (kbd "<M-Z>") #'my-command))
(display-warning 'pel--org-set-keys
"org-mode-map not bound"
:error)))
(add-hook 'org-mode-hook (function pel--org-set-keys))
```
But that still does not work.
Why does the `(define-key org-mode-map (kbd "<M-Z>") #'my-command)` not work?
# Answer
> 2 votes
You don't want `(kbd "<M-Z>")`. You want `(kbd "M-Z")`.
`kbd` expects the same key-description (name) syntax as that used by Emacs itself in `*Help*`. If you use `C-h k` followed by `Meta` \+ `Shift` \+ `z` then Emacs tells you that this is key `M-z`, not key `<M-Z>`.
---
Tags: key-bindings
--- |
thread-68980 | https://emacs.stackexchange.com/questions/68980 | Search and Replace for a block on many lines in a dozen files | 2021-10-18T06:54:18.857 | # Question
Title: Search and Replace for a block on many lines in a dozen files
I have a a bunch of HTML files and in each of them I want to replace a fixed block of approx 30 lines with a one liner.
Is there an Emacs command or package which makes this easier? Using e.g. `dired-do-find-regexp-and-replace` is pretty unwieldy for long multi-line search or replacement terms.
# Answer
> 1 votes
It is generally easier to match smaller, specific patterns, and then replace the region between them (although in this case the regexp as suggested by NickD works fine (except for a possible extra required `.*` before `bar`). Here follows an example for using a 'start' and 'end' pattern and replacing the region in between in a list of files (single file for this example, but you can add more files to the list) on a unix-like system (on windows just adjust the path names):
First save the following text in a file named `~/test.txt`:
```
this is an example
of how to replace
text in some buffer/file
```
Then evaluate the following snippet of code:
```
(dolist (x '("~/test.txt"))
(with-temp-buffer
(insert-file-contents-literally x)
(print (point))
(search-forward "an")
(let ((start (match-beginning 0)))
(delete-region start (search-forward "replace"))
(goto-char start)
(insert "the result of replacing"))
(write-file x)))
```
Of course, like when using regexps, the start and end patterns must be specific enough to not also replace 'unwanted' other blocks.
B.t.w. if it is a fixed block (i.e. a fixed string), then you could probably also just use `replace-string`. You could bind the string to a variable for use in replace-string.
Here the original file gets overwritten (for which we could have used `with-temp-file` directly), but you can replace the final `x` with something like `(concat x ".awesome")` to write to new files. I've kept the `(print (point))` to show explicitly that the point stays at the start after inserting the file contents. In Emacs, usually editing text is done by inserting it to some buffer, also when doing it programmatically. I hope this answer will be useful for your case...
---
Tags: dired, search, query-replace-regexp
--- |
thread-69026 | https://emacs.stackexchange.com/questions/69026 | symbol's function definition is void | 2021-10-21T04:06:27.483 | # Question
Title: symbol's function definition is void
My dotemacsfile looks like the following.
```
(require 'package)
(add-to-list 'package-archives '("melpa" . "http://melpa.org/packages/") t)
(package-initialize) ;load and activate packages, including auto-complete
(ac-config-default)
(global-auto-complete-mode t)
```
But when I run the above in a scratch buffer using `M-x eval buffer`, I get `symbol's function definition is void : ac-config-default`.
(The error is different from the error I get when I do `emacs --init-debug test.R` where the init file is in my home directory. I won't show that error in order to not confuse things.)
# Answer
You probably just forgot to install the package that `ac-config-default` comes from. Run `M-x list-packages`, find the `auto-complete` package (use `C-s` to search), and install it.
From the extended discussion, it turns out that it wasn’t clear what the difference between installing and loading a package was. Installing a package means downloading it from the internet, decompressing it, and putting the files where Emacs can find them. Loading a package means that Emacs actually reads some or all of the files, so that you can use what’s in them.
Installing happens once, and is usually done by running `list-packages` and choosing which packages to install, while loading happens every time you start Emacs.
The information you added to your init file was setting up your desired package sources, so that you could install packages from the source you prefer, telling the package system to load any installed packages by calling `package-initialize`, followed by configuring the specific package you are interested in. These were all necessary, but you missed the important step of actually installing that package :).
> 2 votes
---
Tags: init-file, package
--- |
thread-32377 | https://emacs.stackexchange.com/questions/32377 | Selecting correct font weight variant (Linux) | 2017-04-25T19:59:36.490 | # Question
Title: Selecting correct font weight variant (Linux)
Here's a minimal example that does something on Linux (Ubuntu 16.04) that doesn't seem right to me:
`M-: (set-frame-font "Ubuntu")` `M-x describe-font <RET>`
The first couple of lines that Emacs 25.1 (-Q) reports are:
```
name (opened by): -DAMA-Ubuntu-normal-normal-normal-*-16-*-*-*-*-0-iso10646-1
full name: Ubuntu:pixelsize=16:foundry=DAMA:weight=normal:slant=normal:width=normal:scalable=true
file name: /usr/share/fonts/truetype/ubuntu-font-family/Ubuntu-M.ttf
```
It's the bottom line of this that's wrong (Ubuntu-M.ttf) - Emacs is selecting the "Medium" font weight variant, instead of the "Regular". Like many fonts, the Ubuntu font has weight variants beyond the well-known "Regular" and "Bold". Such additional weights can include "Light", "Book", "Demi-Bold", "Black", "Medium".
I would like to use the Ubuntu Regular font for `variable-pitch-mode`, but the Medium weight isn't suitable. I've tried various different Emacs ways of specifying a font, including `"Ubuntu"`, `"Ubuntu-11:weight=Regular"`, `"-DAMA-Ubuntu-normal-normal-normal-*-15-*-*-*-*-0-iso10646-1"`.
All of these display text in emacs in the wrong, medium weight. Some apps allow selecting font weight by numbers (e.g. 200=Bold), but not, I believe, Emacs. Still, the system's font selection appears to be correct, and I don't understand why Emacs isn't using this
```
alex@Lucifer:~$ fc-match "Ubuntu"
Ubuntu-R.ttf: "Ubuntu" "Regular"
alex@Lucifer:~$ fc-list "Ubuntu" file family style weight
[correct output]
```
Can anyone confirm that this problem exists on Linux (it works fine on my Windows machine)? And, even better, can anyone point me to how to get Emacs to pick the correct weight of font?
# Answer
Not being able to distinguish between "medium" and "regular" weights of fonts on Linux was reported as a bug on Emacs (not by me, although the discussion references this issue). On 21.10.2021 a fix was committed to Emacs git tree (again, not by me, open source ♥).
So the solutions are:
1. Use the latest release of Emacs (version \>= 28), or
2. Hide the "medium" weight of the font, either by not installing it or renaming the file extension. This means, of course, that the medium weight will not be available to any application.
> 1 votes
---
Tags: fonts, linux
--- |
thread-68596 | https://emacs.stackexchange.com/questions/68596 | Open the same file on a different commit | 2021-09-20T20:52:35.327 | # Question
Title: Open the same file on a different commit
I have a local git repository with a certain git commit checked out. A running emacs instance has an open file inside one of the buffers.
How do I quickly open the *same file* inside a new buffer, but on a *different commit*?
The use case is to have a clear view on the changes between the two commits on that file.
# Answer
> 3 votes
The VC package is built into Emacs and provides some basic support for browsing file versions, browsing logs, checking out, committing, etc. VC commands are bound to `C-x v` by default.
There are several commands to access other revisions. If you know what revision you want to open, press `C-x v ~` (`vc-revision-other-window`). To open the last revision that changed a given line, press `C-x v g` (`vc-annotate`), and press `f` (`vc-annotate-find-revision-at-line`) on the desired line. If you want to find and open a revision based on its log message, run `C-x v l` (`vc-print-log`) and press `f` (`log-view-find-revision`) when the cursor is on the desired commit.
If you're interested in the changes between two commits, you can directly show a diff with `C-u C-x v =` (`vc-diff` with a prefix argument — by default it compares the current content of the file with the committed version). To see the differences in Emacs's Ediff interface, run `M-1 M-x vc-ediff RET` (`vc-ediff` with a prefix argument). You can also view a diff with the current content quickly from the annotate or log buffer with `d`, but there's no convenient access to Ediff from there. A convenient way to reach Ediff is to arrange for both versions to be open, and run `ediff-buffers`, which prompts for the buffers to compare and defaults to the current buffer and the previously selected buffer.
The external package Magit has a much more complete interface to Git than VC. It's very useful for interfacing with Git, but not particularly helpful when you're focused on one file in particular and not checking out or committing.
# Answer
> -1 votes
Please see the following StackOverflow duplicate Q&A.
https://stackoverflow.com/questions/25420282
(I won't quote it to avoid splintering answers across two sites on the same network, which is counter-productive.)
---
Tags: git
--- |
thread-68981 | https://emacs.stackexchange.com/questions/68981 | Projectile: How to include files of a sub directory into the project of of it's parent directory? | 2021-10-18T10:09:54.047 | # Question
Title: Projectile: How to include files of a sub directory into the project of of it's parent directory?
Given a project directory `my-project` which projectile correctly identifies because it is a git project.
Inside `my-project` there is a `my-module` directory. It is a git submodule and therefor projectile identifies it as a project of it's own.
But I want all files inside of `my-project/my-module` to be considered as part of `my-project`.
What is the idiomatic way to configure this?
I would like a solution in `dir-locals.el` so it does not affect other projects.
# Answer
The solution was putting this into `my-project/my-module/.dir-locals.el`:
```
((nil . ((projectile-project-root . "/p/my-project/"))))
```
> 0 votes
# Answer
See the issues: https://github.com/bbatsov/projectile/issues/712 / https://github.com/bbatsov/projectile/issues/1449.
One of the options suggested there is to (edit: I've changed `projectile-project-root-files-functions` -\> `projectile-project-root-functions` which it was aliased to):
```
(setq projectile-project-root-functions '(projectile-root-local
projectile-root-top-down
projectile-root-top-down-recurring
projectile-root-bottom-up))
```
Edit: I see you want this to not to affect other projects so you'd want to put this in `.dir-locals.el` in the project root.
> 0 votes
---
Tags: projectile, config
--- |
thread-3358 | https://emacs.stackexchange.com/questions/3358 | How can I get undo behavior in Evil similar to Vim's? | 2014-11-10T18:17:11.803 | # Question
Title: How can I get undo behavior in Evil similar to Vim's?
The default undo behavior in Evil is too coarse-grained because it considers anything taking place between entering insert mode and leaving it as one edit operation. When you enter a whole paragraph of text during one insert and then execute undo, the whole paragraph is removed. In contrast to that, Vim starts a new undo unit whenever you move the cursor in insert mode by means other than entering text.
Evil has a customization variable that can be used to get a more fine-grained undo history:
```
(setq evil-want-fine-undo t)
```
With this setting, Evil starts a new undo unit when the cursor is moved in insert mode, just like Vim does. However, this setting also messes with how the replace operation is handled: if you replace a word using `cw`, you have to undo twice to restore the original word: once for removing the new word and once for reinserting the original word. This is inconsistent with Vim and doesn't make much sense because replace should be atomic.
The question: How can I configure Evil and undo-tree in order to get Vim's undo behavior?
# Answer
> 14 votes
Since @shosti pointed out that Evil considers deviation from Vim behavior as bugs, I filed a bug and one of the authors of Evil added a new possible value for `evil-want-fine-undo`:
```
(setq evil-want-fine-undo 'fine)
```
With this setting, you get new undo units when moving the cursor in insert mode, but replace operations are undone in one step. As far as I can tell this is consistent with Vim. See here for details.
# Answer
> 7 votes
According to the variable description (see `C-h v evil-want-fine-undo`) the value `fine` is not supported any more due to inconsistent behaviour.
As I use undo to undo typos or the mentioned setting helped my allot.
```
(setq evil-want-fine-undo t)
```
I had trouble undoing errors in org-table formula editing, since you don't have to leave the insert mode if you want to change to `*Edit Forumlas*` with `C-'`.
# Answer
> 2 votes
Setting simultaneously
```
(setq evil-want-fine-undo t)
```
and
```
(advice-add 'undo-auto--last-boundary-amalgamating-number
:override #'ignore)
```
as suggested in this answer, gives very fine granularity, that is, undoing each character entered in insert mode one by one.
---
Tags: init-file, customize, evil, undo-tree-mode
--- |
thread-69038 | https://emacs.stackexchange.com/questions/69038 | How to show all sections after cycling visibility? | 2021-10-21T22:52:58.277 | # Question
Title: How to show all sections after cycling visibility?
After cycling visibility for some sections, is there a single key combination that will restore visibility to all subsections?
I was trying to isearch for a tab, and, instead of inserting a tab character into the mini-buffer, ended up cycling various sections of a document.
# Answer
> 1 votes
Looking at the documentation page, shift-tab should be bound to a function that cycles visibility "globally between the table of contents view (headings only), outline view (top-level headings only), and the full document view."
---
Tags: markdown-mode
--- |
thread-68984 | https://emacs.stackexchange.com/questions/68984 | error when trying to use custom made dotemacs file | 2021-10-18T14:19:38.697 | # Question
Title: error when trying to use custom made dotemacs file
I was getting an error when I did a `(require 'auto-complete)` in my init file. A comment suggested I check my `load-path` or alternatively use the package manager if I didn't want to do that manually. So I put in the package manager call and now get another error. I have also included the whole dotemacs file code. The error is different but still not very helpful. Thanks for any ideas. Maybe I shouldn't have (package-initialize) anymore ?
ERROR WHEN I DO emacs --debug-init temp.R
```
Debugger entered--Lisp error: (invalid-read-syntax ")")
eval-buffer(#<buffer *load*> nil "/home/markleeds/.emacs" nil t) ; Reading at buffer position 526
load-with-code-conversion("/home/markleeds/.emacs" "/home/markleeds/.emacs" t t)
load("~/.emacs" t t)
#[0 "\205\262
```
My init file:
```
(require 'package)
(add-to-list 'package-archives '("melpa" . "http://melpa.org/packages/"))
(package-initialize)
(set-background-color "blue")
(set-foreground-color "white")
(add-hook 'inferior-ess-mode-hook 'my-ess-mode-hook)
(add-hook 'shell-mode-hook 'ansi-color-for-comint-mode-on)
(put 'downcase-region 'disabled nil)
(put 'upcase-region 'disabled nil)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; auto-completion
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(require 'auto-complete')
(require 'auto-complete-config)
(ac-config-default)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; ESS set
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(require 'ess-site)
(setq ess-use-auto-complete t)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;open hs-mode
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(add-hook 'ess mode-hook 'hs-minor mode)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;smart parens
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(require 'smartparens-config)
(show-smartparens-global-mode t)
(smartparens-global-mode t)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;rainbow mode
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(require 'rainbow-mode)
(dolist (hook '(ess-mode-hook inferior-ess-mode-hook))
(add-hook hook 'rainbow-turn-on))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;rainbow-delimiters
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(require 'rainbow-delimiters)
(add-hook 'prog-mode-hook 'rainbow-delimiters-mode)
(add-hook 'ess-mode-hook 'rainbow-delimiters-mode)
```
# Answer
If you look at your backtrace:
```
Debugger entered--Lisp error: (invalid-read-syntax ")")
eval-buffer(#<buffer *load*> nil "/home/markleeds/.emacs" nil t) ; reading at buffer position 526
load-with-code-conversion("/home/markleeds/.emacs" "/home/markleeds/.emacs" t t)
load("~/.emacs" t t)
#[0 "\205\262
```
You'll notice the comment on the second line `; reading at buffer position 526`. This *generally* indicates that `eval-buffer()` failed at position 526 in your `~/.emacs`. Open your `~/.emacs` and jump there with `M-x` `goto-char` `Return` `526` `Return`. When you do, your cursor will move to (as indicated by the `|` character):
```
(require 'auto-complete'|)
```
You've quoted `auto-complete` incorrectly. That line should read (notice the single single-quote):
```
(require 'auto-complete)
```
> 1 votes
---
Tags: init-file
--- |
thread-69043 | https://emacs.stackexchange.com/questions/69043 | With swiper counsel ivy installed I get a 4 digit number in front of M-x in the mini-buffer. What does this number relate to? | 2021-10-22T09:47:18.407 | # Question
Title: With swiper counsel ivy installed I get a 4 digit number in front of M-x in the mini-buffer. What does this number relate to?
It doesn’t seem to be related either to the line I am in nor to the number of chars in the document.
# Answer
> 1 votes
I think you are referring to `ivy-count-format`. From the manual:
> A string that specifies display of number of candidates and current candidate, if one exists.
You can customize it if the default value does not suit your needs.
---
Tags: ivy, counsel, swiper
--- |
thread-69045 | https://emacs.stackexchange.com/questions/69045 | How to get user entered refile location, and return information on the chosen heading? | 2021-10-22T11:17:06.703 | # Question
Title: How to get user entered refile location, and return information on the chosen heading?
I would like to write a function that prompts the user to enter a refile location (with completion, like when you call `org-refile`). When the user chooses a refile location, I would like to return the filename and title of the chosen subheading (so I can do things with that data in the rest of the function).
Is this possible? Apologies if the question is unclear, I'm struggling to think of the right terminology.
I am using Ivy, in case this matters.
# Answer
Maybe you can use `org-refile-get-location`. The doc string says: " ...Prompt the user for a refile location, using PROMPT..." . The return value is not documented AFAICT, but an experiment shows that it returns a list, the first two elements of which are the headline to refile under and the pathname of the file to refile into:
```
("Misc (tabs.org)" "/home/nick/lib/org/tabs.org" "^\\(\\*+\\)\\(?: +\\(DONE\\|TODO\\)\\)?\\(?: +\\(\\[#.\\]\\)\\)?\\(?: +\\(?:\\[[0-9%/]+\\] *\\)*\\(Misc\\)\\(?: *\\[[0-9%/]+\\]\\)*\\)\\(?:[ ]+\\(:[[:alnum:]_@#%:]+:\\)\\)?[ ]*$" 3)
```
The reason it says "Misc (tabs.org)" above, is that in my case, I have two possible "Misc" headlines in two different files. I did not pursue it far enough to be able to tell you what the third and fourth elements of the list represent.
You can get the doc string of the function with `C-h f org-refile-get-location`. Note that it is *not* a command, so you can' use `M-x org-refile-get-location`: you can use `ESC ESC : (org-refile-get-location "My Prompt") RET` or you can wrap it in a command:
```
(defun my/org-refile-get-location-command ()
(interactive)
(org-refile-get-location "My Prompt"))
```
> 1 votes
---
Tags: org-mode
--- |
thread-69050 | https://emacs.stackexchange.com/questions/69050 | How to define a face that blends between two existing faces colors? | 2021-10-23T05:00:19.210 | # Question
Title: How to define a face that blends between two existing faces colors?
When defining a new face, how to blend/interpolate between two existing faces colors?
For example - mix the colors `foreground` of default and the `background` of the error face with a factor 0.0 being all of the first color, 1.0 returning all of the second.
# Answer
This macro blends colors between faces, example:
```
(defun my-face-color-blend (color-a color-b factor)
"Tint between COLOR-A and COLOR-B by FACTOR in (0..1).
Use for mixing face colors."
(let ((value-a (color-values color-a))
(value-b (color-values color-b))
(ifactor (- 1.0 factor)))
(apply 'format
(cons
"#%02x%02x%02x"
(mapcar
(lambda (n)
;; Shift by -8 to map the value returned by `color values':
;; 0..65535 to 0..255 for `#RRGGBB` string formatting.
(ash (truncate (+ (* (nth n value-a) ifactor)
(* (nth n value-b) factor))) -8))
(number-sequence 0 2))))))
(defface my-half-background-face
(list (list t (list :foreground
(my-face-color-blend
(face-attribute 'default :foreground)
(face-attribute 'error :background)
0.5))))
"Half the background and foreground of the default font.")
```
> 1 votes
---
Tags: faces, colors
--- |
thread-68888 | https://emacs.stackexchange.com/questions/68888 | What's this `slot-missing: Invalid slot name: "#<forge-database forge-database-156f3376b4d8>", :file` | 2021-10-11T21:06:58.500 | # Question
Title: What's this `slot-missing: Invalid slot name: "#<forge-database forge-database-156f3376b4d8>", :file`
I somehow messed up my magit/forge db, and now emacs won't forgive me. Now I can't open magit's status buffer, and sometimes not even a file buffer opens.
This is all I can gather from the Messages buffer:
```
Cannot insert ("'" "Forge" forge-dispatch) into magit-dispatch; % not found
Turning on magit-auto-revert-mode...done
For information about GNU Emacs and the GNU system, type C-h C-a.
slot-missing: Invalid slot name: "#<forge-database forge-database-156f3376b4d8>", :file
```
I tried a full package refresh, and greped the whole .emacs dir for the hash `156f3376b4d8`, but no luck so far.
I have no idea where to begin. Halp? Does anyone know what this error means?
**EDIT**
This appears when I refresh packages (delete `~/.emacs.d/elpa/` and reinstall all packages) and run with `--debug-init`:
```
Debugger entered--Lisp error: (invalid-slot-name "#<forge-database forge-database-1579ce5eb718>" :file)
signal(invalid-slot-name ("#<forge-database forge-database-1579ce5eb718>" :file))
slot-missing(#<forge-database forge-database-1579ce5eb718> :file oset "/home/philsf/.emacs.d/forge-database.sqlite")
#f(compiled-function (obj slots) "Set slots of OBJ with SLOTS which is a list of name/value pairs.\nCalled from the constructor routine." #<bytecode 0x1579cdb1622d>)(#<forge-database forge-database-1579ce5eb718> (:file "/home/philsf/.emacs.d/forge-database.sqlite"))
apply(#f(compiled-function (obj slots) "Set slots of OBJ with SLOTS which is a list of name/value pairs.\nCalled from the constructor routine." #<bytecode 0x1579cdb1622d>) #<forge-database forge-database-1579ce5eb718> (:file "/home/philsf/.emacs.d/forge-database.sqlite"))
shared-initialize(#<forge-database forge-database-1579ce5eb718> (:file "/home/philsf/.emacs.d/forge-database.sqlite"))
#f(compiled-function (this &optional slots) "Construct the new object THIS based on SLOTS.\nSLOTS is a tagged list where odd numbered elements are tags, and\neven numbered elements are the values to store in the tagged slot.\nIf you overload the `initialize-instance', there you will need to\ncall `shared-initialize' yourself, or you can call `call-next-method'\nto have this constructor called automatically. If these steps are\nnot taken, then new objects of your class will not have their values\ndynamically set from SLOTS." #<bytecode 0x1579cdb16259>)(#<forge-database forge-database-1579ce5eb718> (:file "/home/philsf/.emacs.d/forge-database.sqlite"))
apply(#f(compiled-function (this &optional slots) "Construct the new object THIS based on SLOTS.\nSLOTS is a tagged list where odd numbered elements are tags, and\neven numbered elements are the values to store in the tagged slot.\nIf you overload the `initialize-instance', there you will need to\ncall `shared-initialize' yourself, or you can call `call-next-method'\nto have this constructor called automatically. If these steps are\nnot taken, then new objects of your class will not have their values\ndynamically set from SLOTS." #<bytecode 0x1579cdb16259>) #<forge-database forge-database-1579ce5eb718> (:file "/home/philsf/.emacs.d/forge-database.sqlite"))
initialize-instance(#<forge-database forge-database-1579ce5eb718> (:file "/home/philsf/.emacs.d/forge-database.sqlite"))
#f(compiled-function (class &rest slots) "Default constructor for CLASS `eieio-default-superclass'.\nSLOTS are the initialization slots used by `initialize-instance'.\nThis static method is called when an object is constructed.\nIt allocates the vector used to represent an EIEIO object, and then\ncalls `initialize-instance' on that object." #<bytecode 0x1579cdcbd371>)(forge-database :file "/home/philsf/.emacs.d/forge-database.sqlite")
apply(#f(compiled-function (class &rest slots) "Default constructor for CLASS `eieio-default-superclass'.\nSLOTS are the initialization slots used by `initialize-instance'.\nThis static method is called when an object is constructed.\nIt allocates the vector used to represent an EIEIO object, and then\ncalls `initialize-instance' on that object." #<bytecode 0x1579cdcbd371>) forge-database (:file "/home/philsf/.emacs.d/forge-database.sqlite"))
make-instance(forge-database :file "/home/philsf/.emacs.d/forge-database.sqlite")
#f(compiled-function (class &optional variable file debug) #<bytecode 0x1579ce62179d>)(forge-database forge--db-connection "/home/philsf/.emacs.d/forge-database.sqlite" t)
apply(#f(compiled-function (class &optional variable file debug) #<bytecode 0x1579ce62179d>) forge-database (forge--db-connection "/home/philsf/.emacs.d/forge-database.sqlite" t))
closql-db(forge-database forge--db-connection "/home/philsf/.emacs.d/forge-database.sqlite" t)
(if (and forge--db-connection (emacsql-live-p forge--db-connection)) nil (make-directory (file-name-directory forge-database-file) t) (closql-db 'forge-database 'forge--db-connection forge-database-file t) (let* ((db forge--db-connection) (version (closql--db-get-version db)) (version (forge--db-maybe-update forge--db-connection version))) (cond ((> version forge--db-version) (emacsql-close db) (user-error "The Forge database was created with a newer Forge ..." "You need to update the Forge package.")) ((< version forge--db-version) (emacsql-close db) (error "BUG: The Forge database scheme changed %s" "and there is no upgrade path")))))
forge-db()
(apply #'emacsql (forge-db) sql args)
(if (stringp sql) (emacsql (forge-db) (apply #'format sql args)) (apply #'emacsql (forge-db) sql args))
forge-sql([:select * :from repository :where (and (= forge $s1) (= owner $s2) (= name $s3))] "github.com" "philsf" "dotemacs")
(car (forge-sql [:select * :from repository :where (and (= forge $s1) (= owner $s2) (= name $s3))] forge owner name))
(let* ((row (car (forge-sql [:select * :from repository :where (and (= forge $s1) (= owner $s2) (= name $s3))] forge owner name))) (obj (and row (closql--remake-instance class (forge-db) row)))) (if obj (progn (eieio-oset obj 'apihost apihost) (eieio-oset obj 'githost githost) (eieio-oset obj 'remote remote))) (cond ((and (eq demand t) (or (not obj) (eieio-oref obj 'sparse-p))) (error "Cannot use `%s' in %S yet.\n%s" this-command (magit-toplevel) "Use `M-x forge-add-repository' before trying again...")) ((and (eq demand 'full) obj (eieio-oref obj 'sparse-p)) (setq obj nil))) (if (and (memq demand '(stub create)) (not obj)) (progn (let* ((val (forge--repository-ids class host owner name (eq demand ...))) (x1651 (car val)) (x1652 (cdr val))) (let ((forge-id x1652) (id x1651)) (if (setq obj (forge-get-repository ...)) nil (setq obj (funcall class :id id :forge-id forge-id :forge forge :owner owner :name name :apihost apihost :githost githost :remote remote)) (if (eq demand ...) (progn ...))))))) obj)
(let ((class x1649) (forge x1647) (apihost x1645) (githost x1643)) (let* ((row (car (forge-sql [:select * :from repository :where (and ... ... ...)] forge owner name))) (obj (and row (closql--remake-instance class (forge-db) row)))) (if obj (progn (eieio-oset obj 'apihost apihost) (eieio-oset obj 'githost githost) (eieio-oset obj 'remote remote))) (cond ((and (eq demand t) (or (not obj) (eieio-oref obj 'sparse-p))) (error "Cannot use `%s' in %S yet.\n%s" this-command (magit-toplevel) "Use `M-x forge-add-repository' before trying again...")) ((and (eq demand 'full) obj (eieio-oref obj 'sparse-p)) (setq obj nil))) (if (and (memq demand '(stub create)) (not obj)) (progn (let* ((val (forge--repository-ids class host owner name ...)) (x1651 (car val)) (x1652 (cdr val))) (let ((forge-id x1652) (id x1651)) (if (setq obj ...) nil (setq obj ...) (if ... ...)))))) obj))
(let* ((x1643 (car spec)) (x1644 (cdr spec)) (x1645 (car x1644)) (x1646 (cdr x1644)) (x1647 (car x1646)) (x1648 (cdr x1646)) (x1649 (car x1648)) (x1650 (cdr x1648))) (let ((class x1649) (forge x1647) (apihost x1645) (githost x1643)) (let* ((row (car (forge-sql [:select * :from repository :where ...] forge owner name))) (obj (and row (closql--remake-instance class (forge-db) row)))) (if obj (progn (eieio-oset obj 'apihost apihost) (eieio-oset obj 'githost githost) (eieio-oset obj 'remote remote))) (cond ((and (eq demand t) (or (not obj) (eieio-oref obj ...))) (error "Cannot use `%s' in %S yet.\n%s" this-command (magit-toplevel) "Use `M-x forge-add-repository' before trying again...")) ((and (eq demand 'full) obj (eieio-oref obj 'sparse-p)) (setq obj nil))) (if (and (memq demand '(stub create)) (not obj)) (progn (let* ((val ...) (x1651 ...) (x1652 ...)) (let (... ...) (if ... nil ... ...))))) obj)))
(if spec (let* ((x1643 (car spec)) (x1644 (cdr spec)) (x1645 (car x1644)) (x1646 (cdr x1644)) (x1647 (car x1646)) (x1648 (cdr x1646)) (x1649 (car x1648)) (x1650 (cdr x1648))) (let ((class x1649) (forge x1647) (apihost x1645) (githost x1643)) (let* ((row (car (forge-sql ... forge owner name))) (obj (and row (closql--remake-instance class ... row)))) (if obj (progn (eieio-oset obj 'apihost apihost) (eieio-oset obj 'githost githost) (eieio-oset obj 'remote remote))) (cond ((and (eq demand t) (or ... ...)) (error "Cannot use `%s' in %S yet.\n%s" this-command (magit-toplevel) "Use `M-x forge-add-repository' before trying again...")) ((and (eq demand ...) obj (eieio-oref obj ...)) (setq obj nil))) (if (and (memq demand '...) (not obj)) (progn (let* (... ... ...) (let ... ...)))) obj))) (if (memq demand forge--signal-no-entry) (progn (error "Cannot determine forge repository. No entry for %..." host 'forge-alist))))
(let* ((spec (and t (assoc host forge-alist)))) (if spec (let* ((x1643 (car spec)) (x1644 (cdr spec)) (x1645 (car x1644)) (x1646 (cdr x1644)) (x1647 (car x1646)) (x1648 (cdr x1646)) (x1649 (car x1648)) (x1650 (cdr x1648))) (let ((class x1649) (forge x1647) (apihost x1645) (githost x1643)) (let* ((row (car ...)) (obj (and row ...))) (if obj (progn (eieio-oset obj ... apihost) (eieio-oset obj ... githost) (eieio-oset obj ... remote))) (cond ((and ... ...) (error "Cannot use `%s' in %S yet.\n%s" this-command ... "Use `M-x forge-add-repository' before trying again...")) ((and ... obj ...) (setq obj nil))) (if (and (memq demand ...) (not obj)) (progn (let* ... ...))) obj))) (if (memq demand forge--signal-no-entry) (progn (error "Cannot determine forge repository. No entry for %..." host 'forge-alist)))))
(progn (if --cl-rest-- (signal 'wrong-number-of-arguments (list nil (+ 3 (length --cl-rest--))))) (let* ((spec (and t (assoc host forge-alist)))) (if spec (let* ((x1643 (car spec)) (x1644 (cdr spec)) (x1645 (car x1644)) (x1646 (cdr x1644)) (x1647 (car x1646)) (x1648 (cdr x1646)) (x1649 (car x1648)) (x1650 (cdr x1648))) (let ((class x1649) (forge x1647) (apihost x1645) (githost x1643)) (let* ((row ...) (obj ...)) (if obj (progn ... ... ...)) (cond (... ...) (... ...)) (if (and ... ...) (progn ...)) obj))) (if (memq demand forge--signal-no-entry) (progn (error "Cannot determine forge repository. No entry for %..." host 'forge-alist))))))
(let* ((--cl-rest-- (if --cl-rest-- (car-safe (prog1 --cl-rest-- (setq --cl-rest-- (cdr --cl-rest--)))) (signal 'wrong-number-of-arguments (list nil (length --cl-rest--))))) (host (if (= (length --cl-rest--) 3) (car-safe (prog1 --cl-rest-- (setq --cl-rest-- (cdr --cl-rest--)))) (signal 'wrong-number-of-arguments (list nil (length --cl-rest--))))) (owner (car-safe (prog1 --cl-rest-- (setq --cl-rest-- (cdr --cl-rest--))))) (name (car --cl-rest--)) (remote (car-safe (prog1 --cl-rest-- (setq --cl-rest-- (cdr --cl-rest--))))) (demand (car-safe (prog1 --cl-rest-- (setq --cl-rest-- (cdr --cl-rest--)))))) (progn (if --cl-rest-- (signal 'wrong-number-of-arguments (list nil (+ 3 (length --cl-rest--))))) (let* ((spec (and t (assoc host forge-alist)))) (if spec (let* ((x1643 (car spec)) (x1644 (cdr spec)) (x1645 (car x1644)) (x1646 (cdr x1644)) (x1647 (car x1646)) (x1648 (cdr x1646)) (x1649 (car x1648)) (x1650 (cdr x1648))) (let ((class x1649) (forge x1647) (apihost x1645) (githost x1643)) (let* (... ...) (if obj ...) (cond ... ...) (if ... ...) obj))) (if (memq demand forge--signal-no-entry) (progn (error "Cannot determine forge repository. No entry for %..." host 'forge-alist)))))))
(progn (let* ((--cl-rest-- (if --cl-rest-- (car-safe (prog1 --cl-rest-- (setq --cl-rest-- ...))) (signal 'wrong-number-of-arguments (list nil (length --cl-rest--))))) (host (if (= (length --cl-rest--) 3) (car-safe (prog1 --cl-rest-- (setq --cl-rest-- ...))) (signal 'wrong-number-of-arguments (list nil (length --cl-rest--))))) (owner (car-safe (prog1 --cl-rest-- (setq --cl-rest-- (cdr --cl-rest--))))) (name (car --cl-rest--)) (remote (car-safe (prog1 --cl-rest-- (setq --cl-rest-- (cdr --cl-rest--))))) (demand (car-safe (prog1 --cl-rest-- (setq --cl-rest-- (cdr --cl-rest--)))))) (progn (if --cl-rest-- (signal 'wrong-number-of-arguments (list nil (+ 3 (length --cl-rest--))))) (let* ((spec (and t (assoc host forge-alist)))) (if spec (let* ((x1643 ...) (x1644 ...) (x1645 ...) (x1646 ...) (x1647 ...) (x1648 ...) (x1649 ...) (x1650 ...)) (let (... ... ... ...) (let* ... ... ... ... obj))) (if (memq demand forge--signal-no-entry) (progn (error "Cannot determine forge repository. No entry for %..." host ...))))))))
(closure (t) (&rest --cl-rest--) "((host owner name) &optional remote demand)\n\nRetur..." (progn (let* ((--cl-rest-- (if --cl-rest-- (car-safe ...) (signal ... ...))) (host (if (= ... 3) (car-safe ...) (signal ... ...))) (owner (car-safe (prog1 --cl-rest-- ...))) (name (car --cl-rest--)) (remote (car-safe (prog1 --cl-rest-- ...))) (demand (car-safe (prog1 --cl-rest-- ...)))) (progn (if --cl-rest-- (signal 'wrong-number-of-arguments (list nil ...))) (let* ((spec ...)) (if spec (let* ... ...) (if ... ...)))))))(("github.com" "philsf" "dotemacs") "github" full)
apply((closure (t) (&rest --cl-rest--) "((host owner name) &optional remote demand)\n\nRetur..." (progn (let* ((--cl-rest-- (if --cl-rest-- (car-safe ...) (signal ... ...))) (host (if (= ... 3) (car-safe ...) (signal ... ...))) (owner (car-safe (prog1 --cl-rest-- ...))) (name (car --cl-rest--)) (remote (car-safe (prog1 --cl-rest-- ...))) (demand (car-safe (prog1 --cl-rest-- ...)))) (progn (if --cl-rest-- (signal 'wrong-number-of-arguments (list nil ...))) (let* ((spec ...)) (if spec (let* ... ...) (if ... ...))))))) ("github.com" "philsf" "dotemacs") ("github" full))
forge-get-repository(("github.com" "philsf" "dotemacs") "github" full)
(if parts (forge-get-repository parts remote demand) (if (memq demand forge--signal-no-entry) (progn (error "Cannot determine forge repository. %s isn't a for..." url))))
(let* ((parts (and t (forge--split-url url)))) (if parts (forge-get-repository parts remote demand) (if (memq demand forge--signal-no-entry) (progn (error "Cannot determine forge repository. %s isn't a for..." url)))))
(progn (let* ((parts (and t (forge--split-url url)))) (if parts (forge-get-repository parts remote demand) (if (memq demand forge--signal-no-entry) (progn (error "Cannot determine forge repository. %s isn't a for..." url))))))
(closure (t) (url &optional remote demand) "Return the repository at URL." (progn (let* ((parts (and t (forge--split-url url)))) (if parts (forge-get-repository parts remote demand) (if (memq demand forge--signal-no-entry) (progn (error "Cannot determine forge repository. %s isn't a for..." url)))))))("git@github.com:philsf/dotemacs.git" "github" full)
apply((closure (t) (url &optional remote demand) "Return the repository at URL." (progn (let* ((parts (and t (forge--split-url url)))) (if parts (forge-get-repository parts remote demand) (if (memq demand forge--signal-no-entry) (progn (error "Cannot determine forge repository. %s isn't a for..." url))))))) "git@github.com:philsf/dotemacs.git" ("github" full))
forge-get-repository("git@github.com:philsf/dotemacs.git" "github" full)
(and t (forge-get-repository url remote demand))
(let* ((repo (and t (forge-get-repository url remote demand)))) (if repo (progn (eieio-oset repo 'worktree (magit-toplevel)) repo) nil))
(if url (let* ((repo (and t (forge-get-repository url remote demand)))) (if repo (progn (eieio-oset repo 'worktree (magit-toplevel)) repo) nil)) (if (memq demand forge--signal-no-entry) (progn (error "Cannot determine forge repository. %s\n%s %s" (cond (remote (format "No url configured for %S." remote)) (remotes "Cannot decide on remote to use.") (t "No remote configured.")) "You might have to set `forge.remote'." "See https://magit.vc/manual/forge/Token-Creation.h..."))))
(let* ((url (and t (and remote (magit-git-string "remote" "get-url" remote))))) (if url (let* ((repo (and t (forge-get-repository url remote demand)))) (if repo (progn (eieio-oset repo 'worktree (magit-toplevel)) repo) nil)) (if (memq demand forge--signal-no-entry) (progn (error "Cannot determine forge repository. %s\n%s %s" (cond (remote (format "No url configured for %S." remote)) (remotes "Cannot decide on remote to use.") (t "No remote configured.")) "You might have to set `forge.remote'." "See https://magit.vc/manual/forge/Token-Creation.h...")))))
(let* ((remotes (magit-list-remotes)) (remote (or remote (if (cdr remotes) (car (member (forge--get-remote) remotes)) (car remotes))))) (let* ((url (and t (and remote (magit-git-string "remote" "get-url" remote))))) (if url (let* ((repo (and t (forge-get-repository url remote demand)))) (if repo (progn (eieio-oset repo 'worktree (magit-toplevel)) repo) nil)) (if (memq demand forge--signal-no-entry) (progn (error "Cannot determine forge repository. %s\n%s %s" (cond (remote ...) (remotes "Cannot decide on remote to use.") (t "No remote configured.")) "You might have to set `forge.remote'." "See https://magit.vc/manual/forge/Token-Creation.h..."))))))
(if magit--refresh-cache (let ((G616 (list default-directory 'forge-get-repository demand))) (let ((it (assoc G616 (cdr magit--refresh-cache)))) (if it (progn (let* ((v magit--refresh-cache)) (setcar (car v) (+ ... 1))) (cdr it)) (let* ((v magit--refresh-cache)) (setcdr (car v) (+ (cdr ...) 1))) (let ((value (let* ... ...))) (let* ((v ...) (v magit--refresh-cache)) (setcdr v (cons v ...))) value)))) (let* ((remotes (magit-list-remotes)) (remote (or remote (if (cdr remotes) (car (member ... remotes)) (car remotes))))) (let* ((url (and t (and remote (magit-git-string "remote" "get-url" remote))))) (if url (let* ((repo (and t ...))) (if repo (progn (eieio-oset repo ... ...) repo) nil)) (if (memq demand forge--signal-no-entry) (progn (error "Cannot determine forge repository. %s\n%s %s" (cond ... ... ...) "You might have to set `forge.remote'." "See https://magit.vc/manual/forge/Token-Creation.h...")))))))
(or forge-buffer-repository (and forge-buffer-topic (forge-get-repository forge-buffer-topic)) (if magit--refresh-cache (let ((G616 (list default-directory 'forge-get-repository demand))) (let ((it (assoc G616 (cdr magit--refresh-cache)))) (if it (progn (let* (...) (setcar ... ...)) (cdr it)) (let* ((v magit--refresh-cache)) (setcdr (car v) (+ ... 1))) (let ((value ...)) (let* (... ...) (setcdr v ...)) value)))) (let* ((remotes (magit-list-remotes)) (remote (or remote (if (cdr remotes) (car ...) (car remotes))))) (let* ((url (and t (and remote ...)))) (if url (let* ((repo ...)) (if repo (progn ... repo) nil)) (if (memq demand forge--signal-no-entry) (progn (error "Cannot determine forge repository. %s\n%s %s" ... "You might have to set `forge.remote'." "See https://magit.vc/manual/forge/Token-Creation.h..."))))))))
(progn (or forge-buffer-repository (and forge-buffer-topic (forge-get-repository forge-buffer-topic)) (if magit--refresh-cache (let ((G616 (list default-directory 'forge-get-repository demand))) (let ((it (assoc G616 ...))) (if it (progn (let* ... ...) (cdr it)) (let* (...) (setcdr ... ...)) (let (...) (let* ... ...) value)))) (let* ((remotes (magit-list-remotes)) (remote (or remote (if ... ... ...)))) (let* ((url (and t ...))) (if url (let* (...) (if repo ... nil)) (if (memq demand forge--signal-no-entry) (progn ...))))))))
(closure (t) (demand &optional remote) "Return the current forge repository.\n\nIf the `forg..." (progn (or forge-buffer-repository (and forge-buffer-topic (forge-get-repository forge-buffer-topic)) (if magit--refresh-cache (let ((G616 ...)) (let (...) (if it ... ... ...))) (let* ((remotes ...) (remote ...)) (let* (...) (if url ... ...)))))))(full)
apply((closure (t) (demand &optional remote) "Return the current forge repository.\n\nIf the `forg..." (progn (or forge-buffer-repository (and forge-buffer-topic (forge-get-repository forge-buffer-topic)) (if magit--refresh-cache (let ((G616 ...)) (let (...) (if it ... ... ...))) (let* ((remotes ...) (remote ...)) (let* (...) (if url ... ...))))))) full nil)
forge-get-repository(full)
(and t (forge-get-repository 'full))
(let* ((repo (and t (forge-get-repository 'full))) (format (and repo (eieio-oref repo 'issue-url-format)))) (if format (progn (if bug-reference-url-format nil (set (make-local-variable 'bug-reference-url-format) (if (and (fboundp ...) (forge-gitlab-repository--eieio-childp repo)) #'(lambda nil ...) (forge--format repo 'issue-url-format '...))) (set (make-local-variable 'bug-reference-bug-regexp) (if (and (fboundp ...) (forge-gitlab-repository--eieio-childp repo)) "\\(?3:[!#]\\)\\(?2:[0-9]+\\)" "#\\(?2:[0-9]+\\)"))) (if (derived-mode-p 'prog-mode) (bug-reference-prog-mode 1) (bug-reference-mode 1)) (add-hook 'completion-at-point-functions 'forge-topic-completion-at-point nil t)) nil))
(if default-directory (let* ((repo (and t (forge-get-repository 'full))) (format (and repo (eieio-oref repo 'issue-url-format)))) (if format (progn (if bug-reference-url-format nil (set (make-local-variable 'bug-reference-url-format) (if (and ... ...) #'... (forge--format repo ... ...))) (set (make-local-variable 'bug-reference-bug-regexp) (if (and ... ...) "\\(?3:[!#]\\)\\(?2:[0-9]+\\)" "#\\(?2:[0-9]+\\)"))) (if (derived-mode-p 'prog-mode) (bug-reference-prog-mode 1) (bug-reference-mode 1)) (add-hook 'completion-at-point-functions 'forge-topic-completion-at-point nil t)) nil)) nil)
(let* ((default-directory (and t (magit--safe-default-directory nil)))) (if default-directory (let* ((repo (and t (forge-get-repository 'full))) (format (and repo (eieio-oref repo 'issue-url-format)))) (if format (progn (if bug-reference-url-format nil (set (make-local-variable ...) (if ... ... ...)) (set (make-local-variable ...) (if ... "\\(?3:[!#]\\)\\(?2:[0-9]+\\)" "#\\(?2:[0-9]+\\)"))) (if (derived-mode-p 'prog-mode) (bug-reference-prog-mode 1) (bug-reference-mode 1)) (add-hook 'completion-at-point-functions 'forge-topic-completion-at-point nil t)) nil)) nil))
forge-bug-reference-setup()
run-hooks(find-file-hook)
after-find-file(nil t)
find-file-noselect-1(#<buffer hydra-autoloads.el> "~/.emacs.d/elpa/hydra-0.14.0/hydra-autoloads.el" nil nil "~/.emacs.d/elpa/hydra-0.14.0/hydra-autoloads.el" (25561513 63))
find-file-noselect("/home/philsf/.emacs.d/elpa/hydra-0.14.0/hydra-auto...")
autoload-find-generated-file()
update-directory-autoloads("/home/philsf/.emacs.d/elpa/hydra-0.14.0")
package-generate-autoloads(hydra "/home/philsf/.emacs.d/elpa/hydra-0.14.0")
package--make-autoloads-and-stuff(#s(package-desc :name hydra :version (0 14 0) :summary "Make bindings that stick around." :reqs ((cl-lib (0 5))) :kind tar :archive "gnu" :dir nil :extras ((:url . "https://github.com/abo-abo/hydra") (:maintainer "Oleh Krehel" . "ohwoeowho@gmail.com") (:authors ("Oleh Krehel" . "ohwoeowho@gmail.com")) (:keywords "bindings")) :signed nil) "/home/philsf/.emacs.d/elpa/hydra-0.14.0")
package-unpack(#s(package-desc :name hydra :version (0 14 0) :summary "Make bindings that stick around." :reqs ((cl-lib (0 5))) :kind tar :archive "gnu" :dir nil :extras ((:url . "https://github.com/abo-abo/hydra") (:maintainer "Oleh Krehel" . "ohwoeowho@gmail.com") (:authors ("Oleh Krehel" . "ohwoeowho@gmail.com")) (:keywords "bindings")) :signed nil))
#f(compiled-function (&optional good-sigs) #<bytecode 0x1579ce40c479>)((#s(epg-signature :status good :key-id "066DAFCB81E42C40" :validity undefined :fingerprint "C433554766D3DDC64221BFAA066DAFCB81E42C40" :creation-time 1569088634 :expiration-time nil :pubkey-algorithm 1 :digest-algorithm 10 :class 0 :version 4 :notations nil)))
#f(compiled-function () #<bytecode 0x1579ce83795d>)()
package--with-response-buffer-1("http://elpa.gnu.org/packages/" #f(compiled-function () #<bytecode 0x1579ce83795d>) :file "hydra-0.14.0.tar.sig" :async nil :error-function #f(compiled-function () #<bytecode 0x1579ce40ff59>) :noerror t)
package--check-signature("http://elpa.gnu.org/packages/" "hydra-0.14.0.tar" "hydra-0.14.0/\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0..." nil #f(compiled-function (&optional good-sigs) #<bytecode 0x1579ce40c479>))
#f(compiled-function () #<bytecode 0x1579cdd91529>)()
package--with-response-buffer-1("http://elpa.gnu.org/packages/" #f(compiled-function () #<bytecode 0x1579cdd91529>) :file "hydra-0.14.0.tar" :async nil :error-function #f(compiled-function () #<bytecode 0x1579cdda22d5>) :noerror nil)
package-install-from-archive(#s(package-desc :name hydra :version (0 14 0) :summary "Make bindings that stick around." :reqs ((cl-lib (0 5))) :kind tar :archive "gnu" :dir nil :extras ((:url . "https://github.com/abo-abo/hydra") (:maintainer "Oleh Krehel" . "ohwoeowho@gmail.com") (:authors ("Oleh Krehel" . "ohwoeowho@gmail.com")) (:keywords "bindings")) :signed nil))
mapc(package-install-from-archive (#s(package-desc :name hydra :version (0 14 0) :summary "Make bindings that stick around." :reqs ((cl-lib (0 5))) :kind tar :archive "gnu" :dir nil :extras ((:url . "https://github.com/abo-abo/hydra") (:maintainer "Oleh Krehel" . "ohwoeowho@gmail.com") (:authors ("Oleh Krehel" . "ohwoeowho@gmail.com")) (:keywords "bindings")) :signed nil) #s(package-desc :name pandoc-mode :version (2 31) :summary "Minor mode for interacting with Pandoc" :reqs ((hydra (0 10 0)) (dash (2 10 0))) :kind tar :archive "melpa-stable" :dir nil :extras ((:commit . "500e80666fb779457be8771c5613c177187ba0cc") (:authors ("Joost Kremers" . "joostkremers@fastmail.fm")) (:maintainer "Joost Kremers" . "joostkremers@fastmail.fm") (:keywords "text" "pandoc") (:url . "http://joostkremers.github.io/pandoc-mode/")) :signed nil)))
package-download-transaction((#s(package-desc :name hydra :version (0 14 0) :summary "Make bindings that stick around." :reqs ((cl-lib (0 5))) :kind tar :archive "gnu" :dir nil :extras ((:url . "https://github.com/abo-abo/hydra") (:maintainer "Oleh Krehel" . "ohwoeowho@gmail.com") (:authors ("Oleh Krehel" . "ohwoeowho@gmail.com")) (:keywords "bindings")) :signed nil) #s(package-desc :name pandoc-mode :version (2 31) :summary "Minor mode for interacting with Pandoc" :reqs ((hydra (0 10 0)) (dash (2 10 0))) :kind tar :archive "melpa-stable" :dir nil :extras ((:commit . "500e80666fb779457be8771c5613c177187ba0cc") (:authors ("Joost Kremers" . "joostkremers@fastmail.fm")) (:maintainer "Joost Kremers" . "joostkremers@fastmail.fm") (:keywords "text" "pandoc") (:url . "http://joostkremers.github.io/pandoc-mode/")) :signed nil)))
package-install(pandoc-mode dont-select)
#f(compiled-function (p) #<bytecode 0x1579cdd91755>)(pandoc-mode)
mapc(#f(compiled-function (p) #<bytecode 0x1579cdd91755>) (auctex ess forge magit markdown-mode pandoc-mode use-package zerodark-theme))
package-install-selected-packages()
eval-buffer(#<buffer *load*> nil "/home/philsf/.emacs.d/init.el" nil t) ; Reading at buffer position 1605
load-with-code-conversion("/home/philsf/.emacs.d/init.el" "/home/philsf/.emacs.d/init.el" t t)
load("/home/philsf/.emacs.d/init" noerror nomessage)
startup--load-user-init-file(#f(compiled-function () #<bytecode 0x1579cdb2fe41>) #f(compiled-function () #<bytecode 0x1579cdb2fefd>) t)
command-line()
normal-top-level()
```
# Answer
> 2 votes
`forge` was upgraded in melpa-stable (now 0.3.0) and the issue I encountered can no longer be reproduced. My guess is that there was some incompatibility with `closql` (which now appears in melpa-stable as 1.2.0).
I never got to write a proper bug report, since the upgrade came before that. Gladly the issue went away with the upgraded version, so I'm closing the question here.
---
Tags: magit, debugging, sqlite, forge
--- |
thread-69052 | https://emacs.stackexchange.com/questions/69052 | Setup Emacs TRAMP to use psftp for ftp connection | 2021-10-23T10:10:45.443 | # Question
Title: Setup Emacs TRAMP to use psftp for ftp connection
I recently need to edit remote files a lot. Now I'm using FileZilla to edit files on SFTP server, but I want to use Emacs to connect to the server.
I think it should work with PuTTY's `psftp.exe`, but I don't know how to setup Emacs correctly.
One important detail: SSH support is disabled on the server. I'm running on Windows.
# Answer
On MS Windows, Tramp offers the `psftp` method. However, it uses internally PuTTY's `plink` command, which means you need remote ssh support.
On GNU/Linux systems, Tramp offers the `sftp` method. But this won't work on MS Windows.
> 0 votes
---
Tags: tramp
--- |
thread-59189 | https://emacs.stackexchange.com/questions/59189 | How could I see the output of my Python code in the echo area? | 2020-06-21T19:07:50.063 | # Question
Title: How could I see the output of my Python code in the echo area?
When I press `C-c C-c`(`python-shell-send-buffer`), I get output shown below. Afterwards when I do the same operation (`C-c C-c`) I always see `Sent: #!/usr/bin/env python3...` in the echo area.
* I just want to see the output rather than seeing the send code.
=\> How can I instead see only the output of the code in the echo area (if possible)? or show it on the minibuffer compact as possible and close it when `C-g` is pressed.
##
The output in the `*Python*` buffer:
```
#!/usr/bin/env python3
...
... print("hello world")
import codecs, os;__pyfile = codecs.open('''/var/folders/mx/m3c2fd193h169gg6nd5x3p480000gn/T/pyK57xMh''', encoding='''utf-8''');__code = __pyfile.read().encode('''utf-8''');__pyfile.close();os.remove('''/var/folders/mx/m3c2fd193h169gg6nd5x3p480000gn/T/pyK57xMh''');exec(compile(__code, '''/Users/alper/code/doo.py''', 'exec'));
hello world
#!/usr/bin/env python3
...
... print("hello world")
import codecs, os;__pyfile = codecs.open('''/var/folders/mx/m3c2fd193h169gg6nd5x3p480000gn/T/pyK57xMh''', encoding='''utf-8''');__code = __pyfile.read().encode('''utf-8''');__pyfile.close();os.remove('''/var/folders/mx/m3c2fd193h169gg6nd5x3p480000gn/T/pyK57xMh''');exec(compile(__code, '''/Users/alper/code/doo.py''', 'exec'));
hello world
```
---
My setup in my init file:
```
(add-to-list 'auto-mode-alist '("\\.py\\'" . python-mode))
(setq python-shell-interpreter "python3"
python-shell-prompt-detect-failure-warning nil
flycheck-python-pycompile-executable "python3"
python-shell-completion-native-enable nil
python-shell-completion-native-disabled-interpreters '("python3")
elpy-shell-echo-output nil ; https://github.com/jorgenschaefer/elpy/issues/1550#issuecomment-574512892
)
```
# Answer
I encountered the same issue, and this is a solution I found that works for me:
```
pip3 install gnureadline
cd /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload/
mv readline.cpython-37m-darwin.so readline.cpython-37m-darwin.so.bak
```
Some information that might help:
OS: MacOS Catalina 10.15.7.
Emacs: 27.2.
python: 3.7.4.
And here is an unofficial explanation that I understood: the `gnureadline` is the readline package that should be used by default here, it naturally comes with some version of python but maybe not the one that comes naturally with MacOS, according to the gnureadline's website. Instead the MacOS uses another packages for readline module. And if emacs need to use that readline, it requires some code(the unwanted 'import codecs blablabla') to do so. So here the solution used the `gnureadline` and unables the default readline module because the one(default readline) in lib-dynload comes before the one in side-packages(gnureadline). So we need to get the default one out of the way.
> 0 votes
---
Tags: python, shell, echo-area
--- |
thread-68972 | https://emacs.stackexchange.com/questions/68972 | Keeping track of "read" commits in magit? | 2021-10-17T22:25:03.013 | # Question
Title: Keeping track of "read" commits in magit?
When viewing commits in magit's log view, is there a way to treat commits in magit in a similar way to email?
Where I can track their "read" status? (set unread, mark as read... etc).
Is this already implemented? Or is this something that should be implemented in a new package?
---
Note that any kind of commit-tagging mechanism would probably be sufficient.
# Answer
> 2 votes
This package: magit-commit-mark keeps track of read commits (as well as the ability to star and set commits as urgent).
If you have the melpa repository setup, the package can be setup as follows:
```
(use-package magit-commit-mark
:commands (magit-commit-mark-mode))
(eval-after-load 'magit
(add-hook 'magit-mode-hook 'magit-commit-mark-mode))
```
---
*Created this package after asking here.*
# Answer
> 2 votes
I don't think so. And also, I must add, what strange feature that would be :)
---
Tags: magit
--- |
thread-69059 | https://emacs.stackexchange.com/questions/69059 | How to stop ESS from asking for "R starting project directory"? | 2021-10-24T05:25:32.557 | # Question
Title: How to stop ESS from asking for "R starting project directory"?
Every time I execute all code blocks in an org mode file that contains an R code block (using `org-babel-execute-buffer` with `C-c C-v C-b`), ESS pauses to ask for `R starting project directory`, which seems to default to the current directory of the `.org` file. This prompt causes delays as there is often lengthy initialization process and other code blocks before encountering the first R block. So one has to come back after a minute or two to make it continue.
My question is:
*Is there a way to disable the prompt for R starting project directory and always have it defaulted to the current directory?*
# Answer
You want to set `ess-ask-for-ess-directory` to nil. And, maybe, also check the value of `ess-startup-directory`, which should also be nil to use current buffer's default directory.
> 5 votes
---
Tags: org-mode, ess
--- |
thread-69060 | https://emacs.stackexchange.com/questions/69060 | How to show the remaining disk space in the modeline? | 2021-10-24T08:56:11.900 | # Question
Title: How to show the remaining disk space in the modeline?
I might using the wrong search terms, thus I'm asking for this here:
How can I have modify my modeline to display my remaining disk space?
Currently I have to open a terminal in order to enter:
```
$ df -H --output=avail /dev/mapper/Arch-root | tail -n 1
```
results in `32G`
# Answer
There is the function `free-disk-space` since Emacs 27. Modify your modeline to insert `(get-free-disk-space default-directory)`.
There are many ways to add information to the mode line. Do `C-h i g(elisp)mode line format` for all the gory details. And be prepared for some head scratching.
Here's an example if you want to add this information at the end of the mode line:
```
(add-to-list 'global-mode-string (list " " '(:eval (get-free-disk-space default-directory))) t)
```
This works even on remote directories.
> 4 votes
---
Tags: mode-line
--- |
thread-69041 | https://emacs.stackexchange.com/questions/69041 | How to display the currently running function in the echo area? | 2021-10-22T08:00:18.900 | # Question
Title: How to display the currently running function in the echo area?
I have this function:
```
(defun foo ()
(interactive)
(call-interactively 'bar)
(call-interactively 'baz)
(call-interactively 'qux)
(call-interactively 'quux)
(call-interactively 'fred))
```
When I call `foo`, I would like to see in the echo area a message like `X is running` as long as the `X` function is running, where `X` is `bar`, `baz` and so on, but without hiding any messages that emacs might show when `foo` itself is running. I mean something like this:
```
bar is running
Query replacing regexp foo with bar: (? for help)
```
Just I have no idea how to do such a thing.
---
**Clarification**
db84x pointed out to me that my question is unclear, so I'm going to clarify it.
Suppose `bar` contains this line:
```
(query-replace-regexp "bar" "qwerty" nil (point-min) (point-max))
```
When emacs finds this line, the following will appear in your echo area:
```
--- Echo area ---
Query replacing regexp bar with qwerty: (? for help)
--- Echo area ---
```
When I call `bar`, I first want a message to appear in echo area:
```
--- Echo area ---
bar is running
--- Echo area ---
```
and this message must not disapper as long as `bar` is running. So, when emacs finds the `query-replace-regexp`above, the echo area should appear this way:
```
--- Echo area ---
bar is running
Query replacing regexp bar with qwerty: (? for help)
--- Echo area ---
```
I'm sorry if my question was unclear. Hope now it is.
---
**Attempt 1**
I picked up Drew's suggestion about `message` and I found `with-temp-message`:
> Macro: with-temp-message message &rest body
>
> This construct displays a message in the echo area temporarily, during the execution of body. It displays message, executes body, then returns the value of the last body form while restoring the previous echo area contents.
It seems this macro is just what I am looking for, so I defined this function:
```
(defun fred ()
(interactive)
(with-temp-message
(message "Time's up! Three bucks off!")
(query-replace-regexp "foo" "bar" nil (point-min) (point-max))))
```
When I call `fred`, my message is shown only at the end of its execution and not during. Where am I wrong?
# Answer
> 1 votes
Ok, now that we’ve discovered that you actually want to display *two* messages, your own message plus whatever the code you are running wants to display, we may be able to answer the question.
I think you could potentially do what you want by changing the `set-message-function` variable temporarily. I don’t have time to verify that this will work, but something like this might work:
```
(defun foo ()
(interactive)
(let* ((prefix "")
(set-message-function
(lambda (message)
(concat prefix "\n" message))))
(setq prefix "bar is running")
(call-interactively 'bar)
(setq prefix "baz is running")
(call-interactively 'baz)
(setq prefix "qux is running")
(call-interactively 'qux)
(setq prefix "quux is running")
(call-interactively 'quux)
(setq prefix "fred is running")
(call-interactively 'fred)))
```
Check out 39.4.1 Displaying Messages in the Echo Area in the Emacs Lisp manual for more information. You can also open the Emacs manuals inside of Emacs with `C-h i`.
---
Tags: echo-area, message
--- |
thread-63625 | https://emacs.stackexchange.com/questions/63625 | org-publish: publish exactly files in a given list | 2021-02-27T00:16:42.553 | # Question
Title: org-publish: publish exactly files in a given list
I have hundreds Org files under a directory hierarchy and would want to export *only* those recently modified in HTML to speed up the process. I have the following project alist that I feed up to `org-publish`:
```
`("html"
:base-directory "~/Org/wiki"
:base-extension "org"
:include ,(my/org-files-to-publish)
:with-broken-links t
:publishing-directory "~/Org/wiki"
:publishing-function org-html-publish-to-html)
```
where `(my/org-files-to-publish)` returns recent Org files to export.
It seems that `org-publish` considers not only files of `:include` but also unconditionally those immediately under the root directory (*e.g.* `~/Org/wiki` here).
**Question**: How to export exactly a list of Org files to HTML ?
As `:exclude` accepts only regex and not a files list, I can't find a reliable way to do what I want beside looping on `(my/org-files-to-publish)` using `org-publish-file` plus some extra stuff `org-publish-projects` does.
P.S. This theory is confirmed by checking the output of `set-difference :test 'equal` between `org-publish-get-base-files PROJECT` and `(my/org-files-to-publish)`.
# Answer
> 0 votes
According to `org-publish-project-alist` documentation (emphasis mine):
> The :include property may be used to include **extra** files.
This means that your project alist will match all org files in your directory plus any files included via `:include` property.
You can achieve desired result in somewhat hacky way by setting `:base-extension` to a dummy value that won't match any files:
```
`("html"
:base-directory "~/Org/wiki"
:base-extension "dummy"
:include ,(my/org-files-to-publish)
:with-broken-links t
:publishing-directory "~/Org/wiki"
:publishing-function org-html-publish-to-html)
```
---
Tags: org-mode, org-export, org-publish
--- |
thread-69067 | https://emacs.stackexchange.com/questions/69067 | How to replace (blah) with {blah} for a specific string | 2021-10-24T19:39:57.573 | # Question
Title: How to replace (blah) with {blah} for a specific string
In a latex document, I wish to replace \cost(blah) with \cost{blah} in the entire document, where blah is an arbitrary string. That is, I only want to change the round brackets to curly brackets for every expression involving \cost. I realize this involves regular expressions in emacs - but I don't know how to do this.
# Answer
> 4 votes
You can do this with `query-replace-regexp` (bound to `C-M-%` by default), which prompts for a regexp and a replacement, then asks for confirmation at each match (useful for preventing accidents).
The regex you want to type in is `\\cost(\(.*\))`, and the replacement should be `\\cost{\1}`.
The key is to understand the regexp syntax. Most characters in the regexp stand for themselves; a `c` in the regexp just matches a “c” in the buffer. Characters that have some special meaning are mostly prefixed with a backslash, so matching a backslash requires a double–backslash. Thus the regexp `\\cost()` simply matches the string “\cost()” in the buffer.
Inside the parens is going to be some text that can vary. We want to capture that text and use it in the replacement, so we will surround it with parens, but these must be parens with backslashes: `\(\)`. This makes a capturing group.
Inside the group we just want to match anything. A period (`.`) matches any single character, and an asterisk (`*`) modifies the previous item so that it matches zero or more of the same thing. Thus `.*` is a basic regexp trick to match any number of any thing of character.
When we put it all together we get `\\cost(\(.*\))`. Note that the capturing parens are inside the normal parens, so that the normal parens are not captured.
Finally, in the replacement we again use `\\` to mean a single backslash character, and `\1` to mean the contents of the first capturing group in the regexp.
I recommend practicing this in the regexp builder, which lets you see exactly what a regexp matches as you type it in; it also shows you what every capturing group matches. First, put some sample text in your scratch buffer, like this:
```
\cost{blah}
\cost{foo}
\stuff(blah)
\cost{bar}
\cost{123}
```
Then run the regexp builder by typing `M-x re-builder`. This opens a small buffer below the scratch buffer where you can type in a regexp. One thing to note is that you are typing this into an elisp string, as if you were writing a program. Elisp strings also use the backslash character for escaping, so every backslash has to be doubled. Type this in:
```
\\\\cost(\\(.*\\))
```
As you type it in, watch as the regex matches change in the scratch buffer. When you complete the group, you’ll see them highlighted in a different color. To exit the regexp builder, type `C-x C-q`.
I recommend reading chapter 15.6 Syntax of Regular Expressions in the Emacs manual, as it documents everything that can go in a regexp. You can open the Info viewer to read the manuals inside of Emacs by typing `C-h i`.
Then go practice some regexes!
---
Tags: regular-expressions, query-replace-regexp
--- |
thread-69057 | https://emacs.stackexchange.com/questions/69057 | Man-mode in Emacs 27 - how to display the manual page all in one page? | 2021-10-24T02:45:11.623 | # Question
Title: Man-mode in Emacs 27 - how to display the manual page all in one page?
Using Man-mode in Emacs 27 on Arch Linux, for reading the **zshall(1)** manual page, the manual page appears to have been formatted to display on 16 separate pages, with each page being displayed separately. I'm seeing this behavior for the **zshall(1)** manual page, using the Emacs+GTK build from Arch Linux, in X Windows and at the console.
I'm also seeing this page-splitting behavior for the **zshall(1)** manual page in Emacs 28 on FreeBSD.
Perhaps this page-splitting behavior may be unique to the **zshall(1)** manual page, or manual pages using a similar formatting convention? Comparatively, the **bash(1)** manual page is displayed all in one page, in both Emacs installations. To own opinion, this is the ideal presentation for the manual page. It's easy to search and page through.
Maybe this has been around in Emacs for a while? Personally, I've not seen this page-splitting behavior outside of the manual pages for ZSH.
Searching the Emacs Lisp source code for Man-mode in Emacs 27 on Arch, I've been unable to locate any option for disabling the page-splitting behavior. I've also searched for a function for searching the content of those 16 pages. Presently, I'm only able to search each of the 16 pages separately.
To my own opinion, this page-splitting behavior makes it considerably more difficult to navigate the content of the manual page. Perhaps there may be some way to join any separate pages in the variable `Man-page-list` under the `Man-mode` buffer and display those all at one time, in Emacs Lisp? May there be any known workaround outside of that, to display the content all in one page?
Health, all
# Answer
> 3 votes
If you look at the source of the zshall manpage (`/usr/share/man/man1/zshall.1` for me) you'll find a section towards the end that looks like
```
.so man1/zshroadmap.1
.so man1/zshmisc.1
.so man1/zshexpn.1
.so man1/zshparam.1
.so man1/zshoptions.1
.so man1/zshbuiltins.1
.so man1/zshzle.1
.so man1/zshcompwid.1
.so man1/zshcompsys.1
.so man1/zshcompctl.1
.so man1/zshmodules.1
.so man1/zshtcpsys.1
.so man1/zshzftpsys.1
.so man1/zshcontrib.1
```
`.so` is the `troff` request to include a file. Assuming your terminal manpage viewer (`man`) is not using pre-compiled manpages, it is effectively concatenating those files with `zshall.1` acting as a wrapper and sends the result to a pager. Emacs's "Man mode", being "smarter" than a just a pager treats this as something akin to a "collection" that you can navigate through. It doesn't even quite get that right. You'll notice that the first page of `zshall(1)` (when viewed in "Man mode") is missing its footer. Move to the last page (`zshcontrib(1)` for me), and you'll see the footer is concatenated there.
So, I think there are a couple of issues at play here. We have an outdated viewing paradigm<sup>1</sup> ("Man mode"), a manpage (`zshall.1`) source written from the perspective of a terminal viewer (`man`) and like with many other "old fashioned" things in Emacs, a lack of people annoyed enough about the situation to do anything about it.
A feature request for a flag to toggle concat-ing or "collecting" via `M-x` `report-emacs-bug` might get something moving. In the meantime you might want to try pre-compiling `zshall(1)`. If I were to do that on my system for `man`, I'd do
```
$ mkdir -p /usr/share/man/cat1
$ PAGER=/bin/cat man zshall > /usr/share/man/cat1/zshall.1
$ MANPATH=/usr/share/man: man zshall
```
I'm sure it's easy enough to set the MANPATH when using "Man mode".
---
1. Such a thing *was* handy when viewing large sets of documentation typeset in some flavor of `roff`. At least it was better than flipping through multiple three-ring binders.
---
Tags: man
--- |
thread-69068 | https://emacs.stackexchange.com/questions/69068 | why is a let binding is ignored in compiled function? | 2021-10-24T20:46:27.347 | # Question
Title: why is a let binding is ignored in compiled function?
I have this function which works perfectly in an uncompiled function. It should let-bind the variable `bibtex-completion-bibliography` to the result of `(org-ref-find-bibliography)`.
```
(defun org-ref-valid-keys ()
"Return a list of valid bibtex keys for this buffer.
This is used a lot in `org-ref-cite-activate' so it needs to be
fast, but also up to date."
;; this seems to be needed, but we don't want to do this every time
(unless bibtex-completion-display-formats-internal
(bibtex-completion-init))
;; I don't fully understand what is happening here.
(let ((bibtex-completion-bibliography (org-ref-find-bibliography)))
(cl-loop for entry in (bibtex-completion-candidates)
collect
(cdr (assoc "=key=" (cdr entry))))))
```
What should happen is (org-ref-find-bibliography) gets a list of bibliography files if they are defined in a buffer (it defaults to a variable setting if they are not), and then let-binds that list to bibtex-completion-bibliography, and the keys are extracted from (bibtex-completion-candidates) which uses bibtex-completion-bibliography to get keys from those files. This works fine when the function is not compiled.
When the function is compiled, the keys end up coming from the default list of bibtex files, and not from the list defined by (org-ref-find-bibliography) (which still does the right thing). It is as if the let binding does not work.
If I debug the function, or re-evaluate it, it works fine, it only does not work when called from the compiled function. It also works if I delete all the .elc files in the package.
All the bibtex-completion\* functions and variables are defined in the external library bibtex-completion.
I have `-*- lexical-binding: t; -*-` in the first line of that file.
What could be causing this?
extra details:
```
GNU Emacs 28.0.50 (build 1, x86_64-apple-darwin20.6.0, NS appkit-2022.60 Version 11.5 (Build 20G71)) of 2021-07-29
```
# Answer
> 5 votes
You're compiling the file using lexical binding, so I *suspect* the problem is that your file does neither of the following:
* `(defvar bibtex-completion-bibliography)`
* `(require 'bibtex-completion)`
either of which would tell the code in your file that `bibtex-completion-bibliography` is a dynamic variable.
Without that information, the following creates a *lexical* binding for `bibtex-completion-bibliography` (which is distinct from the symbol by that name):
```
(let ((bibtex-completion-bibliography (org-ref-find-bibliography)))
(cl-loop for entry in (bibtex-completion-candidates)
```
You then call `(bibtex-completion-candidates)` which is undoubtedly looking at the dynamic variable `bibtex-completion-bibliography` which was *not* set by your code.
When you're testing all of this interactively, I imagine that `bibtex-completion-bibliography` is getting declared as dynamic along the way, thus causing your code to do what you had intended.
In summary, when you're using lexical binding, it's crucial that *all* dynamic variables are declared as such, either by `require`ing the library which defines them, or else by explicitly declaring them with the `(defvar FOO)` syntax (with only a single parameter, defvar does not define a variable `FOO`, but rather says that references to `FOO` in the same file are to the *dynamic* variable by that name).
---
> When ‘require’ is used at top level in a file, it takes effect when you byte-compile that file as well as when you load it. This is in case the required package contains macros that the byte compiler must know about. It also avoids byte compiler warnings for functions and variables defined in the file loaded with ‘require’.
-- `C-h``i``g` `(elisp)Named Features`
> Effectively ‘require’ is automatically ‘eval-and-compile’, the package is loaded both when compiling and executing.
-- `C-h``i``g` `(elisp)Eval During Compile`
---
Tags: lexical-scoping, let-binding, dynamic-scoping, defvar
--- |
thread-69078 | https://emacs.stackexchange.com/questions/69078 | Why does a stray period cause an error I associate with mismatched parens? | 2021-10-25T14:55:52.987 | # Question
Title: Why does a stray period cause an error I associate with mismatched parens?
A typo that changed `(foo)` to `(foo . )` in my `.init` file caused an `Invalid read syntax: )` error.
**I get why it's a syntax error. But why *this* error?** I thought this error message reliably reflected mismatched parentheses, and I spent ages barking up the wrong tree. What am I misunderstanding? Is there something about the elisp parser that makes a stray `.` look like an extra `)` to it? What other kinds of syntax error show up this way?
# Answer
> 3 votes
The period is part of the read syntax for a cons. `(a b)` is a list, while `(a . b)` is a cons. The difference is that the list is made of two conses, so the first is equivalent to `(a . (b . nil))`. The error message is telling you that it saw a `)` that it did not expect. It expected to see anything other than a `)`, because it was expecting to read a new object rather than the end of an existing one.
---
Tags: list, syntax
--- |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.