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-66439 | https://emacs.stackexchange.com/questions/66439 | In a large directory of org-mode files, is there a view that combines them? | 2021-06-22T16:24:15.347 | # Question
Title: In a large directory of org-mode files, is there a view that combines them?
I'm looking into better ways to organize my notes in org-mode. I have a directory full of org-mode files. Some in lower directories. I'd like to view them all and add cross references, but I don't really want to have a bunch of open files to have to navigate between.
I could use links and that would make jumping to a target fairly easy, but not then jumping back.
I could use includes, but I'm not really interested in exporting the files, just traversing and walking references.
Is there a feature to org-mode that I'm overlooking, or a tool for this kind of use? I admit I haven't really concentrated ever on how I organize my org mode files, I just use grep like tools as needed.
# Answer
You could use org-roam, which creates a database of links between org files. Specifically, it can create a graph of your notes (see below) which you can use to jump between them.
This also solves your issue of not being able to jump back to the file quickly, as org-roam provides a buffer with files linking to the current file (backlinks).
You can also use nroam to show them at the bottom of the buffer instead (I prefer this.)
It additionally allows you to create graphs of said links using `org-roam-graph` (but it's kind of clunky.)
or org-roam-server
\[
If you configure `org-protocol` you will be able to click the links in the graphs and have it open the corresponding org-file in emacs!
> 4 votes
---
Tags: org-mode
--- |
thread-66440 | https://emacs.stackexchange.com/questions/66440 | make compile-goto-error use view-mode when visiting source buffer | 2021-06-22T17:20:38.247 | # Question
Title: make compile-goto-error use view-mode when visiting source buffer
After using `M-x find-grep` I have a list of files with position information in a *compile* buffer. Now I want to **visit** the files to check, which can be done with `<RET>`, calling `compile-goto-error` to switch/open file into buffer at given position. Emphasize on visit, I want to quickly leave the visited buffer by typing `q`.
I looked into the source of `compile-goto-error` and added the view-mode line with `progn` around the `(setq compilation-current-error (point))` clueless as I am like this:
```
(defun my-compile-goto-error (&optional event)
"Visit the source for the error message at point.
Use this command in a compilation log buffer."
(interactive (list last-input-event))
(if event (posn-set-point (event-end event)))
(or (compilation-buffer-p (current-buffer))
(error "Not in a compilation buffer"))
(compilation--ensure-parse (point))
(if (get-text-property (point) 'compilation-directory)
(dired-other-window
(car (get-text-property (point) 'compilation-directory)))
(progn
(setq compilation-current-error (point))
(unless view-mode (view-mode t)))
(next-error-internal)))
```
However, this works only every second time, with or without the line `(unless view-mode (view-mode t))`
How can I force `compile-goto-error` to open source-file in `view-mode`?
# Answer
> 0 votes
You run `view-mode` before `next-error-internal`, which is the function that parses the error list, finds the next one, extracts the location information and visits the file. You need to run `view-mode` after `next-error-internal`, at the very end of the function.
Additionally, you need to ensure that `view-mode` runs in the correct buffer. This works out of the box in Emacs 27, but not in Emacs 26, where `next-error-internal` keeps the compilation output buffer as current. The source code buffer is displayed after `compile-goto-error` because `compilation-goto-locus` displays it in a window and selects this window, but that only causes the *buffer* to become current after the interactive function returns. So either run `view-mode` from a `next-error-hook` (but that would make it harder to not run `view-mode` all the time) or run it with the displayed buffer as current.
Since you don't need to change the way `compile-goto-error` works at all, just call it. The only thing you need to copy from the code of `compile-goto-error` is the argument specifications. (You could use the advice mechanism to avoid copying them but for what you're doing here that would be far more complicated.)
```
(defun compile-view-error (&optional event)
"Like `compile-goto-error', but visit the file in view mode."
(interactive (list last-input-event))
(compile-goto-error event)
(with-current-buffer (window-buffer)
(view-mode t)))
```
---
Tags: compile-mode, view-mode
--- |
thread-66444 | https://emacs.stackexchange.com/questions/66444 | Retrieve file from an earlier commit | 2021-06-23T03:54:17.927 | # Question
Title: Retrieve file from an earlier commit
I am using Doom Emacs 2.0.9 on Emacs 27.2.
I use magit to manage a local git repository.
In an earlier commit, there was a file. In the latest commit as well as the current working tree, the file no longer exists as it was deleted somewhere along the way.
I want to have that file from the earlier commit in the current working tree. How do I do that using magit?
# Answer
> 2 votes
You can use `magit-file-checkout` on the commit hash of your interest, or find the command (most likely `f file`) in `Reset` menu.
After selecting the commit hash, choose the file you wanna resurrect.
# Answer
> 0 votes
First you have to find the revision where the file was deleted. You can do that with `magit-log`, then advice the full file name in "Limit to files". You will get the commit where the file was removed at the top of the log buffer.
You can open file as it was just before deleted with `magit-find-file`, settings revision to `rev^` where `rev` is the commit that delete the file. Or checkout it (`magit-file-checkout`) at the revision `rev^`.
---
Tags: magit, git
--- |
thread-66413 | https://emacs.stackexchange.com/questions/66413 | Finding in certain projects only files with particular extensions when doing a project(ile) grep | 2021-06-21T07:49:57.393 | # Question
Title: Finding in certain projects only files with particular extensions when doing a project(ile) grep
I have projects where `*.nim` files are the source files and `*.js` files are the "compiled" files.
When I issue `projectile-grep` (or `project-find-regexp`) in these projects I get both source and compiled JavaScript files returned, but of course I do not want the JavaScript files.
How can I tell project(ile) *on a project-base* only to return the source files (here `*.nim` and `*.nims`)?
---
PS: I know I can give `projectile-grep` a glob with a prefix argument, but this is cumbersome to do for every search in this type of project.
# Answer
> 0 votes
On a per-project-base you can use the `.projectile` file to exclude JavaScript files. Create a `.projectile` file at the root of your project with a line like
```
-*.js
```
In Nim projects in particular you probably want to add all `nimcache` folders as well with
```
-nimcache
```
**Please note:** You need to switch to hybrid or native indexing in projectile. If you want to do this globally, just add for example
```
(setq projectile-indexing-method 'hybrid)
```
to your .emacs file or in your projectile use-package expression.
# Answer
> 1 votes
The help for `projectile-grep` mentions the setting `projectile-grep-default-files`. I believe that you could use directory–local variables to set this to the correct value on a per–project basis, but I’ve not tried it myself.
Personally I use Ripgrep instead of grep. Ripgrep honors the `.gitignore` files that my projects all have, so it already ignores compiled files and concentrates on the correct source files.
# Answer
> 1 votes
`C-u M-x project-find-regexp`.
See its documentation,
```
project-find-regexp is an interactive Lisp closure in ‘project.el.gz’.
(project-find-regexp REGEXP)
Probably introduced at or before Emacs version 25.1.
Find all matches for REGEXP in the current project’s roots.
With C-u prefix, you can specify the directory
to search in, and the file name pattern to search for. The
pattern may use abbreviations defined in ‘grep-files-aliases’,
e.g. entering ‘ch’ is equivalent to ‘*.[ch]’. As whitespace
triggers completion when entering a pattern, including it
requires quoting, e.g. ‘M-x quoted-insert<space>’.
```
---
Tags: projectile, project, source
--- |
thread-66452 | https://emacs.stackexchange.com/questions/66452 | Replacing with context information | 2021-06-23T09:42:56.893 | # Question
Title: Replacing with context information
When writing latex sometimes I reuse old documents that use the `siunitx` package and use the `\SI` command. Then I often want to include the calculations via `pythontex` and replace (in a region) `\SI` with a modified command (see `pythontex` doc) called `\pySI[Session]` where in most cases `Session` is the last session in the document.
Consider this example:
```
\begin{pycode}[SessionA]
from numpy import
a = 3
b = 4
c = sqrt(a**2 + b**2)
\end{pycode}
```
In this text I previously had `\(a = \SI{3}{\m}\)` and `\(b = \SI{4}{\m}\)` and `\(c = \SI{5}{\m}\)`. But then I decided to add the pycode snipped above and want to replace it by `\(a = \pySI[SessionA]{a}{\m}\)` and `\(b = \pySI[SessionA]{b}{\m}\)` as well as `\(c = \pySI[SessionA]{c}{\m}\)`. This should even work, if I only marked this text and not the pycode environment above.
I tried the following code, but it seems to replace only `\SI` by `\pySI` but skips the session information:
```
(defun my/latex-last-pycode-session ()
(or (and (re-search-backward "^\\\\begin{pycode}\\[\\(.+\\)\\]\\s-*$" nil t)
(format "[%s]" (match-string 1))
)
""))
(defun try-replace-SI-to-PySI (begin end)
(interactive "r")
(let ((session (my/latex-last-pycode-session)))
(save-excursion
(goto-char begin)
(while
(re-search-forward
"\\\\SI" end)
(replace-match (format "\\\\pySI" session) 1)))))
```
What did I do wrong and how can I make it work?
# Answer
> 1 votes
There are three problems:
* The `format` call is wrong: you need to say `(format "\\\\pySI%s" session)` to have the session info interpolated into the string.
* you need to tell `re-search-forward` to deal with errors more gracefully. You do that by adding a `t` as the last argument. Do `C-h f re-search-forward` and read the description of the `NOERROR` argument.
* your regexp is not capable of detecting the first argument of the `\SI` macro and changing it from the numeric value to the symbolic one (e.g. `3` to `a`). I'll leave that problem for you to worry about.
I should say: these are the problems that I can see - there may be more :-).
---
Tags: replace, forward-search
--- |
thread-66449 | https://emacs.stackexchange.com/questions/66449 | Trouble with gnus imap / outlook on windows 10 | 2021-06-23T07:02:28.097 | # Question
Title: Trouble with gnus imap / outlook on windows 10
I successfully installed gnus with imap backend to access the outlook messaging service.
I could not make gnus access directly the exchange server by imap so, I settled davmail which acts as a local imap server and forwards gnus imap commands to something understandable for the exchange server.
Then, in outlook, I moved some old messages from one directory to the INBOX. When I opened again the INBOX from gnus, these old messages now appear at the top of the group summary as if they were the most recent. In order to get the most recent ones, I have to scroll down until the last old message. This does not happen in the outlook client.
In outlook, I moved some most recent INBOX messages on a temporary directory and then, moved them back to the INBOX. These most recent messages now appears correctly from gnus.
I am not sure it is a gnus bug. It seems that, when I move some messages in outlook from one directory to another, gnus sees them as newer than previous messages, most recent by date, in destination directory.
I displayed the whole header of some moved messages ... nothing unexpected, the dates are correct. How can I make gnus display messages correctly in that case ?
Regards
# Answer
Gnus sorts the messages by their ID number as used by the IMAP protocol. Moving a message changes its ID number, so this behavior is expected. You can sort a summary buffer in a number of ways:
```
C-c C-s C-a gnus-summary-sort-by-author
C-c C-s C-c gnus-summary-sort-by-chars
C-c C-s C-d gnus-summary-sort-by-date
C-c C-s TAB gnus-summary-sort-by-score
C-c C-s C-l gnus-summary-sort-by-lines
C-c C-s C-n gnus-summary-sort-by-number
C-c C-s C-o gnus-summary-sort-by-original
C-c C-s C-r gnus-summary-sort-by-random
C-c C-s C-s gnus-summary-sort-by-subject
C-c C-s C-t gnus-summary-sort-by-recipient
```
> 0 votes
# Answer
Thanks for your answer.
Actually, I think the trouble happens before the summary display and how message are sorted. When I enter a group, I am asked how many messages I want to retrieve, because it is a large group. It seems gnus retrieves the first 200 messages according to their ID number, not the date.
Then, I can sort the summary buffer in any way I want, I still get the oldest messages because they were prefered, thanks to their ID number, upon retrieving them from the IMAP server (davmail/outlook exchange).
How can I modify the criteria according to which gnus retrieves messages from the server ? Setting this criteria to the most recent date would them solve my problem.
> 0 votes
---
Tags: gnus
--- |
thread-66451 | https://emacs.stackexchange.com/questions/66451 | How to access Erlang shell JCL Mode inside an Emacs inferior-erlang shell? | 2021-06-23T08:54:37.000 | # Question
Title: How to access Erlang shell JCL Mode inside an Emacs inferior-erlang shell?
Inside an Erlang shell one can access the Erlang shell User Switch Command menu (also called Erlang shell JCL Mode) by typing *Ctrl-G*.
When running the Erlang shell inside Emacs (as an inferior-erlang) typing `C-g` once or twice or any other number of times does not bring the menu. Inside a comint driven shell, one can type `C-c C-c` to generate a *Ctrl-C* for the Erlang shell process. I did not find something similar to generate a *Ctrl-G*. Is there something?
*Environment:* Running Erlang 24 on macOS Mojave. Running Emacs 26.3 or 27.2 either graphical app or in termcap mode on a macOS Terminal.
# Answer
After further research I found a way: type `C-q C-g RET`.
That opens the Erlang shell JCL Mode.
The `C-q` key is bound to `(quoted-insert ARG)` allowing to pass the *Ctrl-G* once a `RET` is typed.
> 1 votes
---
Tags: comint, erlang-mode
--- |
thread-66299 | https://emacs.stackexchange.com/questions/66299 | How to insert overlay every n visual/screen lines? | 2021-06-14T09:43:07.720 | # Question
Title: How to insert overlay every n visual/screen lines?
I want to insert an overlay at the beginning of every 40th or so **visual/screen**, to generate a WYSIWYG looking page-break overlay like so:
At the moment this is done by font-locking the line-feed character (with overlays), which works but it edits the text and makes the overlay too concrete. Ideally I would have a minor-mode running which inserts overlays at the start of every nth visual line to prevent this.
While I found how to move x number of screen lines or get x number of screen lines in a certain region, https://www.gnu.org/software/emacs/manual/html\_node/elisp/Screen-Lines.html, I have not been able to figure out how **get** that position so that I can use it in the declaration of the overlay. Maybe this is doable with some complicated `compute-motion`, but I am not exactly sure how that would work.
Any ideas?
This is a partial copy of Obtain points at beginning/ending of visual line without using vertical-motion, but that question specifically concerns obtaining the beginning/end of the current line, not any line. While I could iterate over the entire file and obtain those coordinates, that is obviously not very feasible.
# Answer
> 1 votes
I've figured it out! You can use `save-excursion` to get the position of the `n-th` visual line
```
(defun get-visual-line-start (n)
"Get the character position of the 'nth' visual line, serving as the visual line number."
(save-excursion
(goto-line 1)
(vertical-motion n)
; (end-of-visual-line) ; for the end of the line instead
(point)))
```
Then do something like
```
(let ((n 40))
(dotimes (line (round (/ (count-screen-lines) n))
(let* ((line-pos get-visual-line-start (* n (1+ line)))
(ov (make-overlay line-pos line-pos)))
;;; do something with the overlay
)))
```
Tada
---
Tags: motion, overlays, visual-line-mode
--- |
thread-64590 | https://emacs.stackexchange.com/questions/64590 | How to persist a transient to make a command repeatable? | 2021-04-26T14:20:21.797 | # Question
Title: How to persist a transient to make a command repeatable?
I am converting some of my Hydras to Transient. One of them includes a command with shrinks or enlarges one of my split windows, so I hit it repeatedly until I like my size. How to do this in Transient? The documentation makes it clear that it's possible, but I can't find a place where it explains how. It appears to be related to the `:transient-suffix 'transient--do-stay`, but I can't figure out where to place this to make some of my commands repeatable. Further, it would be nice to set this per-command or per-group, not just on the whole transient. Here is what I'm working with:
```
(transient-define-prefix tsa/transient-window ()
;; the following :transient-suffix causes the whole thing to fail at command invocation:
;;; command-execute: Wrong type argument: commandp, tsa/transient-window
;; :transient-suffix 'transient--do-stay
"Window navigation transient"
[["Resize"
("q" "X←" tsa/move-splitter-left)
("w" "X↓" tsa/move-splitter-down)
("e" "X↑" tsa/move-splitter-up)
("r" "X→" tsa/move-splitter-right)]])
```
# Answer
> 1 votes
`transient` provide a `transient-variable` abstract class. Inspired by magit `magit--git-variable` which store variables in git config file, I tried to use global elisp variable.
```
(setq-default my-variable "default")
(defclass my-transient-variable (transient-variable) ())
(cl-defmethod transient-init-value ((obj my-transient-variable))
(oset obj value (symbol-value (oref obj variable))))
(cl-defmethod transient-format-value ((obj my-transient-variable))
(let ((v (oref obj value)))
(if v
(propertize v 'face 'transient-value)
(propertize "unset" 'face 'transient-inactive-value))))
(cl-defmethod transient-infix-set ((obj my-transient-variable) user-value)
(oset obj value user-value)
(set (oref obj variable) user-value))
(transient-define-argument my-option-argument ()
:description "My Option"
:class 'my-transient-variable
:key "d"
:variable 'my-variable
:prompt "My option: "
)
(transient-define-prefix my-command-transiant ()
"Test"
["Arguments"
(my-option-argument)]
["Commands"
("c" "run" my-command-run)
("q" "Quit" transient-quit-one)])
(defun my-command-run (&optional args)
(interactive (transient-args 'my-command-transiant))
(message (format "My option value: %s" my-variable)))
```
---
Tags: transient-library, transients
--- |
thread-66448 | https://emacs.stackexchange.com/questions/66448 | How to provide a dynamic default value for option in magit transient? | 2021-06-23T06:40:27.990 | # Question
Title: How to provide a dynamic default value for option in magit transient?
I can define a custom option with:
```
(transient-define-infix my-option-infix ()
:description "My Option"
:class 'transient-option
:shortarg "-o"
:argument "--my-option=")
```
But how can I initialize the value depending of the current buffer ?
# Answer
SECOND EDIT
If you have saved the prefix its state using `C-x s` or `C-x C-s`, then the prefix value is taken from `transient-values` variable or from the `transient-values-file`. To set the value as explained in this answer, make sure that you clear the value for the prefix from this variable and/or file.
FIRST EDIT
In the original code, the value of the `:value` keyword gets evaluated when the prefix is defined, so it sets the value to a fixed buffer.
To set the value at the moment of running the prefix, replace the `:value` keyword (line) in the prefix definition with the following line:
```
:init-value 'my-prefix-init
```
and define the `my-prefix-init` function as follows:
```
(defun my-prefix-init (obj)
(oset obj value `(,(concat "--foo=" (buffer-name)))))
```
END EDIT
It is, not very clearly, described in this reddit post.
I guess this is best answered with an example. I have commented out the simple way of setting the value and replaced it by a backquote syntax method to show how to set the current buffer name:
```
(transient-define-prefix test ()
;; :value '("--foo=bar")
:value `(,(concat "--foo=" (buffer-name)))
[(test-option-infix)]
[("p" "print value" print-essentials)])
(transient-define-infix test-option-infix ()
:class 'transient-option
:key "-f"
:description "My option"
:argument "--foo="
:choices '("some-alt-value" "etc"))
```
You can retrieve the value directly from the infix-object as follows.
```
(defun print-essentials ()
(interactive)
(pp (transient-args 'test))
(pp (transient-arg-value "--foo=" (transient-args 'test))))
```
To read more about this solution I refer to the reddit post. And the documentation of EIEIO (as I am not very familiar with neither transient nor EIEIO).
> 4 votes
---
Tags: transients
--- |
thread-66466 | https://emacs.stackexchange.com/questions/66466 | Why I am unable to squash these commits on magit? | 2021-06-25T00:53:01.307 | # Question
Title: Why I am unable to squash these commits on magit?
I am trying to squash some commits using magit. I tried two different approaches choosing different commit ids to pick and squash. Despite the fact that none of them worked out, the error messages varied. Unfortunately, I cannot understand any of them.
I did a gif to show what happens and I put it on github.
How can I solve this? What should I try? Why is this happening?
Thanks.
# Answer
When you squash a commit, it is squashed *into the previous non-squashed* commit. You're marking the very first commit in the list as a commit to be squashed, so there's no prior non-squashed commit to squash it into. It's a bit like starting a new repository and using `git commit --amend` before you've made your first commit.
You need:
```
pick this commit
squash into ^
squash into ^
```
Note also that Git's rebase listing runs from top-to-bottom chronologically, as opposed to the log which is in reverse-chronological order.
---
Note that this isn't actually an Emacs/Magit question -- the point of confusion is no different in the standard Git UI.
> 3 votes
---
Tags: magit, git
--- |
thread-66469 | https://emacs.stackexchange.com/questions/66469 | Isearch-forward org-timestamp in german time format | 2021-06-25T11:11:53.657 | # Question
Title: Isearch-forward org-timestamp in german time format
In org mode I use a german time format for timestamps
```
(setq org-time-stamp-custom-formats '("<%a. %d.%m.%Y>" . "<%a. %d.%m.%Y %H:%M>"))
```
For example `<Fr. 25.06.2021>`. Internally this is represented as `<2021-06-25 Fr>`.
So, I can for example `isearch-forward` for `06-25` to find the time stamp, but searching for `25.06.` doesn't work.
Is there any way to configure emacs such that it works to use`isearch-forward` for a substring of the german time stamp representation?
# Answer
> 0 votes
`org-times-stamp-custom-formats` affects the *display* of time stamps: it does not affect how the time stamp is stored in the file. `isearch` on the other hand does not care about how the display looks; it only cares about what's in the buffer.
So I believe the answer to your question is "no".
The custom time stamp format is implemented using overlays (do `C-h i g (elisp) Overlays` to read about them). You might be able to cobble up something using the functions described there, but I think it is going to be a fairly fragile thing.
Org mode really only supports the ISO time stamp format, so you are probably better off remembering that and using ISO format (sub)expressions for searching.
---
Tags: org-mode, isearch, time-date
--- |
thread-66474 | https://emacs.stackexchange.com/questions/66474 | Populate table row with rate changes with one formula | 2021-06-25T22:14:50.480 | # Question
Title: Populate table row with rate changes with one formula
I've got this Exhibit A in brute force for a rate that is halved after 10 minutes
```
#+NAME: ratetable
| 0 min | 10 min | 20 min | 30 min | 40 min | 50 min |
| 20.0 | 10. | 5. | 2.5 | 1.25 | 0.625 |
#+TBLFM: @2$2=@2$1/2::@2$3=@2$2/2::@2$4=@2$3/2::@2$5=@2$4/2::@2$6=@2$5/2
```
What I'd really like is a way to put in just one starting value in the second row/first column and have the rest of the row populated without all the individual formulae per cell. Any ideas/docs talking about this sort of "amortize(?) the whole row/column" would be appreciated.
# Answer
You can use a range formula for cases like this. The relevant section in the manual, which you can get to with `C-h i g (org) Field and range formulas`, says:
> ‘@1$2..@4$3=’
>
> ```
> Range formula, applies to all fields in the given rectangular
> range. This can also be used to assign a formula to some but not
> all fields in a row.
>
> ```
That, combined with relative references (`C-h i g (org) References`) , allows to write the above set of formulas as a single formula:
```
#+TBLFM: @2$2..@2$> = @2$-1/2
```
In words: for every cell in the second row `@2`, starting with the second column `$2`, and ending with the last column `$>`, set its value to be the value of the cell in the second row but the previous column `$-1`, divided by 2.
> 1 votes
---
Tags: org-mode, org-table, calc
--- |
thread-55417 | https://emacs.stackexchange.com/questions/55417 | Change theme when OS dark mode changes? | 2020-02-10T20:50:59.103 | # Question
Title: Change theme when OS dark mode changes?
VS Code recently added the ability to switch themes when macOS's dark mode changes. Presumably they use the Electron API, which internally uses the Objective-C API of subscribing to the `AppleInterfaceThemeChangedNotification` event in `NSDistributedNotificationCenter`.
It would be nice if Emacs had this same ability. The pseudo-code would be:
```
(add-event 'os-dark-mode-changed
(lambda (on)
(set-theme (if on
some-dark-theme
some-light-theme))))
```
(In VS Code, the dark and light themes are configurable.)
Does Emacs have the ability to do something similar?
# Answer
> 2 votes
Using emacs-plus this is easy. See the docs, but here is the code in any case.
```
(defun my/apply-theme (appearance)
"Load theme, taking current system APPEARANCE into consideration."
(mapc #'disable-theme custom-enabled-themes)
(pcase appearance
('light (load-theme 'tango t))
('dark (load-theme 'tango-dark t))))
(add-hook 'ns-system-appearance-change-functions #'my/apply-theme)
```
# Answer
> 0 votes
A work-around, more so than an answer: you can change your theme from an external process, by starting your main editor instance in server mode, and using `emacsclient`. E.g.
```
(server-start)
```
And:
```
emacsclient --eval "(my/dark-mode)" --quiet -no-wait --suppress-output -a true
```
It turns out that iTerm2 allows you to execute an arbitrary Python script on OS theme changes. You can use this to change iTerm2's *own* theme, but nothing stops you from adding a cheeky call to `emacsclient` and controlling Emacs along, with it.
I've combined all of this here: https://gist.github.com/hraban/8eb4ab5c110828a9d1b8c16b4f78193e.
Upside: no polling, no Emacs UI blocking, etc
Downside: iTerm2 must be running.
---
Tags: osx, themes
--- |
thread-66478 | https://emacs.stackexchange.com/questions/66478 | How to use make-frame to bring up "maximized windows" like -mm does for the first window (using WSL 2)? | 2021-06-26T09:16:35.460 | # Question
Title: How to use make-frame to bring up "maximized windows" like -mm does for the first window (using WSL 2)?
I am running emacs under (Ubuntu under) WSL 2 and I can bring up the first frame maximized (i.e. almost full screen, leaving the Windows "task bar" exposed, the -mm option does that). I would like to bring up other frames the same way, so that by switching tasks on the task bar, I see only one Emacs frame. I can do this by creating a window and clicking on the maximize button, but I would like to do it within Emacs (using make-frame) because I layout the emacs windows/buffers based upon the frame real estate and doing it as two steps gets the internal windows slightly the wrong size.
In the old X days, I could do it with geometry frame-parameters, but WSL 2 doesn't seem to respect the top and left parameters and makes a frame where the maximize button is outside the display area so I cannot even click on it without first moving the window and then clicking. Moreover, I'm not certain that the geometry I am specifying is exactly the right size, which may be exacerbating the problem.
# Answer
> 4 votes
The variable `default-frame-alist` controls the frame dimensions. To have any new frame maximized write
```
(add-to-list 'default-frame-alist '(fullscreen . maximized))
```
in your init.el. See the official documentation for details.
# Answer
> 3 votes
@matteol tells you how to get the effect you want for all frames, by default.
To answer just your question about creating a frame with `make-frame`, either of these may help (they don't need to be interactive):
```
(defun my-make-frame ()
"..."
(interactive)
(let ((default-frame-alist '((fullscreen . maximized))))
(make-frame)))
(defun my-make-frame ()
"..."
(interactive)
(let ((default-frame-alist ()))
(make-frame '((fullscreen . maximized)))))
```
The value of `default-frame-alist` supplements whatever frame-parameters alist you pass to `make-frame`.
---
Tags: microsoft-windows, frames
--- |
thread-66482 | https://emacs.stackexchange.com/questions/66482 | Why is my keybinding not working? | 2021-06-26T22:16:32.933 | # Question
Title: Why is my keybinding not working?
I am trying to customize my settings on Paredit. Instead of using the default `C-right` and `C-left`, I would like to do `C-<` and `C->`. I tried with this code inside my init file:
```
(eval-after-load 'paredit
'(progn
(define-key paredit-mode-map (kbd "<C->>") 'paredit-forward-slurp-sexp)
(define-key paredit-mode-map (kbd "<C-<>") 'paredit-forward-barf-sexp)
(define-key paredit-mode-map (kbd "<C-right>") nil)
(define-key paredit-mode-map (kbd "<C-left>") nil)))
```
Apparently, it works with order bindings, such as "\<C-)\>". Unfortunately, it **does not** work with "C-\>\>". I guess the consecutive "\>\>" are causing problems.
How do I fix this?
Thanks.
# Answer
> 1 votes
Thanks to @NickD, I was able to reach the solution. Just to be clear for other users, I will post it here:
```
(eval-after-load 'paredit
'(progn
(define-key paredit-mode-map (kbd "C->") 'paredit-forward-slurp-sexp)
(define-key paredit-mode-map (kbd "C-<") 'paredit-forward-barf-sexp)
(define-key paredit-mode-map (kbd "C-M-<") 'paredit-backward-slurp-sexp)
(define-key paredit-mode-map (kbd "C-M->") 'paredit-backward-barf-sexp)
(define-key paredit-mode-map (kbd "<C-right>") nil)
(define-key paredit-mode-map (kbd "<C-left>") nil)))
```
---
Tags: key-bindings
--- |
thread-66454 | https://emacs.stackexchange.com/questions/66454 | Any sort of bridge between notion and org mode? | 2021-06-23T13:37:21.123 | # Question
Title: Any sort of bridge between notion and org mode?
Notion is a trendy new piece of software that seems to be following in slacks footprints. Slack was successful by taking `irc` and making it more corporate: easier to use, prettier, and adding useful features.
Notion is doing the same to wikipedia and to some degree org mode (structural editing, storing data in text files, code that can operate on the data structure, hyperlinks, multimedia settings). But it's no emacs ("clickity, click, click goes the mouse"). I was wondering if anyone had attempted to integrate this with `org-mode` and whether this was at all successful in doing so - I suspect many emaxers will be forced to use notion to communicate with other people, and notion will introduce many people to many of the ideas in org-mode.
I found this undocumented repo: https://github.com/RadekMolenda/org-notion I've seen suggestions that integrate other web services with org-mode. With things like org-jira, and org-mediawiki \- though suspect that these tools are at risk of "bit rot" that accompanies most screen scrapers.
*References*
# Answer
Notion famously took a while to release their api to the public. It entered open beta literally a month ago (see https://developers.notion.com/) so there's probably nothing thorough yet to bridge it with other software.
> 1 votes
---
Tags: org-mode
--- |
thread-66487 | https://emacs.stackexchange.com/questions/66487 | How can I get rid of `Loading /home/user/.emacs.d/package.el (source)...done` message after installing a package manually? | 2021-06-27T11:23:18.557 | # Question
Title: How can I get rid of `Loading /home/user/.emacs.d/package.el (source)...done` message after installing a package manually?
I'm trying to install this package manually, adding the `org-bullets.el` file to my emacs directory.
As suggested, I enabled it adding
```
(load-file "~/.emacs.d/org-bullets.el")
(require 'org-bullets)
(add-hook 'org-mode-hook #'org-bullets-mode)
```
to my `init.el`
The program works but now when I start Emacs the mini buffer always shows this message:
`Loading /home/user/.emacs.d/org-bullets.el (source)...done`
How can I get rid of it?
I'm running Emacs 27.2
# Answer
You can crib the `load-file` function and replace it with a silent version.
The `load-file` function looks like this (just do `C-h f load-file` and then click on the link of the file that contains it (`files.el`) to see the definition of the function):
```
(defun load-file (file)
"Load the Lisp file named FILE."
;; This is a case where .elc and .so/.dll make a lot of sense.
(interactive (list (let ((completion-ignored-extensions
(remove module-file-suffix
(remove ".elc"
completion-ignored-extensions))))
(read-file-name "Load file: " nil nil 'lambda))))
(load (expand-file-name file) nil nil t))
```
As you can see, it calls `load`. If you examine the doc string of `load` it says:
> (load FILE &optional NOERROR NOMESSAGE NOSUFFIX MUST-SUFFIX)
>
> ...
>
> Print messages at start and end of loading unless optional third arg NOMESSAGE is non-nil (but ‘force-load-messages’ overrides that).
`force-load-messages` is `nil` by default (but check your configuration with `C-h v force-load-messages` to make sure). Assuming that's the case, all you need to do is define your own `load-file` function early in your init file (before you use it to load `org-bullets`), but when your function calls `load`, change it so that the `nomessage` parameter is `t` instead of `nil`:
```
(defun load-file (file)
"Load the Lisp file named FILE."
;; This is a case where .elc and .so/.dll make a lot of sense.
(interactive (list (let ((completion-ignored-extensions
(remove module-file-suffix
(remove ".elc"
completion-ignored-extensions))))
(read-file-name "Load file: " nil nil 'lambda))))
(load (expand-file-name file) nil t t))
```
> 0 votes
---
Tags: init-file
--- |
thread-66492 | https://emacs.stackexchange.com/questions/66492 | Why Emacs creates multiples whitespaces after I create a comment and jump to a new line? | 2021-06-27T23:43:19.157 | # Question
Title: Why Emacs creates multiples whitespaces after I create a comment and jump to a new line?
I am using Emacs, Paredit, Slime to work on Common Lisp (SBCL). When I create a comment such as:
```
; test
```
It is placed as expected. But if I press `return` in order to create a new line below `;test` this happens:
```
; test
```
A bunch of whitespaces suddenly appear.
Why is this happening?
How can I avoid it?
Thanks
# Answer
> 3 votes
Lisp has a more complex convention for comments than most languages, and automatic formatting respects this convention. It is documented in appendix D.7 Tips on Writing Comments of the Elisp manual (which is also available inside of Emacs itself, use `C-h i` to open the Info viewer).
In a nutshell, comments that start with just a `;` are formatted like marginal notes in a book; they go at the ends of the lines where the right–hand margin would be. Use `;;` for comments that are meant to be indented in a way similar to code; this puts the comments at the left–hand margin when they’re not inside a function or other type of top–level item. You can use `;;;` and `;;;;` for headings to divide your documentation or code up into sections and chapters.
---
Tags: indentation, whitespace, comment
--- |
thread-66494 | https://emacs.stackexchange.com/questions/66494 | Using elisp code with table formula problem | 2021-06-28T04:06:43.357 | # Question
Title: Using elisp code with table formula problem
I've got these working
```
#+NAME: expogrowth1
| 1 | 2 |
| 2 | 4 |
| 3 | 8 |
| 4 | 16 |
| 5 | 32 |
| 6 | 64 |
| 7 | 128 |
| 8 | 256 |
#+TBLFM: @2$2..@$2> = @-1$2*2
```
and
```
#+NAME: expogrowth2
| 1 | 2 | 3 | 4 | 5 | 6 | 7 |
| 2 | 4 | 8 | 16 | 32 | 64 | 128 |
#+TBLFM: @2$2..@2$> = @2$-1*2
```
but this won't work
```
#+NAME: expogrowth4
| 1 | 2 | 3 | 4 | 5 | 6 | 7 |
| | | | | | | |
#+TBLFM: @2$1..@2$> = '(mapcar (lambda (arg) (expt arg 2)) (list @1$1..@1$>))
```
This is not exactly the same, but eventually I'd like to have a real exponential growth table working with the elisp version. I'm following this, and the code from it works, but my own code to simply square the numbers from the top row won't work, and I can't see why.
# Answer
You are overcomplicating things: yes, there is a string conversion problem as @db48x has pointed out in his answer, but assuming that the last table should produce the same results as the other two, the formula is much simpler:
```
#+TBLFM: @2$1..@2$> = '(expt 2 (string-to-number @1))
```
In words: for every cell in the second row, get the corresponding cell in the first row (a string), convert the string to a number and then raise 2 to that exponent.
What your formula would do (after fixing the string conversions) would be to assign a *list* of values to each cell in the LHS range.
> 2 votes
# Answer
Use the formula debugger; you can turn it on with `C-c {`. You’ll see something like this:
```
Substitution history of formula
Orig: '(mapcar (lambda (arg) (expt arg 2)) (list @1$1..@1$7))
$xyz-> '(mapcar (lambda (arg) (expt arg 2)) (list @1$1..@1$7))
@r$c-> '(mapcar (lambda (arg) (expt arg 2)) (list #("1" 0 1 (fontified t face org-table)) #("2" 0 1 (fontified t face org-table)) #("3" 0 1 (fontified t face org-table)) #("4" 0 1 (fontified t face org-table)) #("5" 0 1 (fontified t face org-table)) #("6" 0 1 (fontified t face org-table)) #("7" 0 1 (fontified t face org-table))))
$1-> '(mapcar (lambda (arg) (expt arg 2)) (list #("1" 0 1 (fontified t face org-table)) #("2" 0 1 (fontified t face org-table)) #("3" 0 1 (fontified t face org-table)) #("4" 0 1 (fontified t face org-table)) #("5" 0 1 (fontified t face org-table)) #("6" 0 1 (fontified t face org-table)) #("7" 0 1 (fontified t face org-table))))
Result: #ERROR
Format: NONE
Final: #ERROR
```
You can see that the arguments are substituted in as strings, and fontified strings at that. You’ll need to convert them to numbers before you can call `expt` on them. The document you’re reading gives several different ways to do that; which one is best for you depends on what you’re trying to do.
> 2 votes
---
Tags: org-table
--- |
thread-45604 | https://emacs.stackexchange.com/questions/45604 | Permanently display line numbers in emacs | 2018-10-26T20:49:03.573 | # Question
Title: Permanently display line numbers in emacs
I am asking this after having read this post:
How do I display line numbers in emacs (not in the mode line)?
I have tried using: `M-x linum-mode` and `display-line-numbers-mode`
After closing emacs and reopening, they are gone. Is there not a way to have emacs permanently display the line numbers?
# Answer
In order for your changes to persist, you need to add them to your init file. If you've used any customize functionality, it probably generated one for you, and it's saved in `~/.emacs`. If that isn't the case, you're better off putting it in `~/.emacs.d/init.el`.
In order to have line numbers in all buffers and have them persistently, you can put
```
(global-display-line-numbers-mode)
```
into your init file.
If you're using an older version of Emacs, you'll want to use `linum-mode`, in that case you should put this in your init file isntead:
```
(global-linum-mode)
```
> 21 votes
# Answer
1. Menu `Options` \> `Show/Hide` \> `Line Numbers for All Lines` \> **`Global Line Numbers Mode`**
2. Menu `Options` \> `Save Options`
Menus are your friends. They can be a good way to discover Emacs features.
You can also alternatively use Customize to set the equivalent option directly: `M-x customize-option global-display-line-numbers-mode`.
> 2 votes
# Answer
I had the same problem, and when I was looking for an unrelated issue, I found this in Stack Overflow:
> The problem for me was the Initial Start Up Screen of emacs. It seems that the default welcome screen of emacs (with the tutorial links) forces you to start in your $HOME path.
Since the Initial Start Up Screen has to be shown in a certain way, it seems like it disables line numbering and other things. Therefore, by adding
```
(setq inhibit-startup-message t)
```
to `.emacs` made some changes, such as line numbering, become persistent for me.
> -1 votes
---
Tags: line-numbers
--- |
thread-66499 | https://emacs.stackexchange.com/questions/66499 | Yank / copy / get into a buffer matching regex search results | 2021-06-28T16:26:57.050 | # Question
Title: Yank / copy / get into a buffer matching regex search results
I am trying to "extract" my search results into a new buffer, but only the matches - not the whole lines.
For example I am trying to get a list of HTML color codes used in a file. I can identify them (in this case) with a search for `"#.*?"`, which produces:
However, now I want all those matches copied into a new buffer to work on. I just can't seem to figure out how to do this?
# Answer
> 5 votes
`C-u M-x occur \"\(#[^\"]+\)\" <RETURN> \1`
(this strips the quotes)
or
`C-u M-x occur "#.+\" <RETURN>`
(this keeps the quotes)
`occur` finds all lines that match the provided regexp. Calling it with the prefix argument (`C-u`) returns *only* the matched text, not the complete lines. Using the capture group (`\(...\)`) lets you select the group, while ignoring the enclosing quotes. If you don't care about including the quotes, you can drop the capture group.
For example:
```
(let (
(base00 "#081724")
(base01 "#033340")
(base02 "#1d5483")
(base03 "#2872b2")
(base04 "#d3f9ee")
(base05 "#a6f3dd")
(base06 "#effffe")
(base07 "#fffed9")
(red "#ff694d")
(orange "#f5b55f")
(yellow "#fffe4e")
(magenta "#afc0fd")
(violet "#96a5d9")
(blue "#bad6e2")
(cyan "#d2f1ff")
(green "#68f6cb")
(twsblue "#0000ff"))
```
Calling `occur` as above produces:
```
#081724
#033340
#1d5483
#2872b2
#d3f9ee
#a6f3dd
#effffe
#fffed9
#ff694d
#f5b55f
#fffe4e
#afc0fd
#96a5d9
#bad6e2
#d2f1ff
#68f6cb
#0000ff
#002b36
```
---
Tags: search, occur
--- |
thread-66491 | https://emacs.stackexchange.com/questions/66491 | Viewing projects using `org-ql` | 2021-06-27T21:00:24.237 | # Question
Title: Viewing projects using `org-ql`
I use `org-ql` to view projects.
```
(defun my/view-projects ()
(interactive)
(require 'org-ql)
(org-ql-search
(org-agenda-files)
'(and (tags "project")
(not (todo "DONE"))
(not (todo "XXXX")))
:sort nil))
```
However, the outcome forgets the tree structure. For example, the following
```
* a :project:
** b
*** c
```
got represented as
```
a
b
c
```
Wishing the outcome to preserve the tree structures more, I added `:super-groups '((:auto-parent))` in the form of `org-ql-search`. However, it doesn't make it better.
**Question** How to customize `org-ql` in order to view projects with the tree structures preserved?
# Answer
> 1 votes
I think you need to add a `t` argument to the :super-groups.
```
(defun my/view-projects ()
(interactive)
(require 'org-ql)
(org-ql-search
(org-agenda-files)
'(and (tags "project")
(not (todo "DONE"))
(not (todo "XXXX")))
:sort nil
:super-groups '((:auto-parent t))))
```
This results in this for me. I also note that although this doesn't exactly preserve the tree structure, if you select an item, you an see the path to it in the minibuffer. E.G. with the point on the c item below, you can see that it the path is file/a/b to get to it.
---
Tags: org-mode, org-agenda, org-ql
--- |
thread-66504 | https://emacs.stackexchange.com/questions/66504 | How to correctly set the path? | 2021-06-28T22:31:46.137 | # Question
Title: How to correctly set the path?
I've been unable to run the elixir shell using `alchemist-iex-run` because the erlang executable `erl` is not found in my path. Here's the error:
```
/opt/homebrew/Cellar/elixir/1.12.1/bin/elixir: line 230: exec: erl: not found
Process Alchemist-IEx exited abnormally with code 127
```
In an attempt to fix this, in init.el I added:
```
(add-to-list 'exec-path "/opt/homebrew/bin")
(add-to-list 'exec-path "/opt/homebrew/sbin")
```
But this still doesn't work. Here's the result from...
vterm `echo $PATH`: Includes the added homebrew paths.
`(exec-path)`: Includes the added homebrew paths.
`(call-process "ENV" nil t)`: Does not include the added homebrew paths.
Erlang shell: `os:cmd("echo $PATH").`: Does not include the added homebrew paths, but includes path to erl at /opt/homebrew/Cellar/erlang/24.0.2\_1/lib/erlang/erts-12.0.2/bin.
How to correctly set the path so that the added homebrew paths always appear?
# Answer
> 1 votes
`exec-path` is where *Emacs* looks for executables. The `PATH` environment variable is... well, an environment variable.
If you want to change the environment that Emacs passes to sub-processes, see the `process-environment` variable and `setenv` function.
See also `C-h``i``g` `(elisp)System Environment`
I'm extremely surprised if `vterm` is adding `exec-path` to `PATH`. It's probably considered a feature rather than a bug, but it's not normal.
---
Tags: init-file, config
--- |
thread-66506 | https://emacs.stackexchange.com/questions/66506 | Alternative way to disambiguate "dangling else" in a cl-loop | 2021-06-28T23:26:11.577 | # Question
Title: Alternative way to disambiguate "dangling else" in a cl-loop
I need to achieve in a `cl-loop` the following conditional written in pseudocode.
```
if (flag1) {
if (flag2) {return ...}
} else {
return ...
}
```
Note that it is equivalent to
```
if (flag1 && flag2) {return ...}
if (!flag1) {return ...}
```
which undesirably repeats `flag1` twice.
What I have done is:
```
(cl-loop ...
if (flag) do 'nothing and
if (...) return ... end
else
return ...)
```
The `do 'nothing and` looks a bit hacky to me, but I cannot omit it as it's part of the nested if syntax. Are there alternative (and clearer) ways to do this ? Maybe using `cl-block` or by outsourcing the conditionals to another function ?
**EDIT** (*further clarification*):
The use of the keywords `and` and `end` could help to disambiguate dangling else (which is the conditional pattern given in this question).
Inspired from @John Kitchin's example, consider the following snippets and note the indentation:
```
(cl-loop
with flag1 = nil
with flag2 = t
if flag1 return 3
if flag2 return 1
else return 2)
```
returns `1`.
On the other hand,
```
(cl-loop
with flag1 = nil
with flag2 = t
if flag1 return 3 and
if flag2 return 1 end
else return 2)
```
returns `2`.
Thus, to accomplish the desired conditional, the keywords `and` and `end` are required.
Now, going back to the initial question: how to achieve the latter conditional, without a clause at the `return 3` position, ignoring potential infinite loops ?
It seems impossible *per se*: according to the documentation, the `<clause>` in `if <condition> <clause>` should be an accumulation, `do`, `return`, `if`, or `unless` clause.
My solution is replacing it with `do 'nothing` or `do (ignore)` to fulfill the documentation's requirement, or use the equivalent yet repetitive conditional (undesired, see above), but I'm looking for alternatives.
# Answer
I think this is what you want:
```
(let ((flag1 nil)
(flag2 nil))
(cl-loop
if flag1
if flag2 return 1
else return 0
else return 2))
```
if flag1 is nil, you get 2 if flag1 is t, and flag2 is nil you get 0 if flag1 is t, and flag2 is t you get 1
---
Or to replicate the original pseudo code (complete with its infinite loop scenario):
```
(cl-loop
if flag1
if flag2 return 1 end
else return 2)
```
> 2 votes
---
Tags: conditionals, cl-lib, iteration
--- |
thread-66296 | https://emacs.stackexchange.com/questions/66296 | Any mode for Modula 2? | 2021-06-14T02:48:36.283 | # Question
Title: Any mode for Modula 2?
I'm (after a hiatus of some 30 years) dabbling again in Modula 2 (yes, too much time cooped up). But neither ELPA nor MELPA knows anything about a mode for GNU Emacs. This site seems not to mention the language either. Any hints? Perhaps (ab)use a mode for a similar language, like Pascal?
# Answer
> 0 votes
To my surprise, after looking all over without getting any leads (and thus asking here), I just set to edit some Modula 2 source code. I was prepared to use plain text mode or a mode for say Pascal (somewhat similar). To my surprise, emacs went into Modula 2 mode.
So the short answer is: Modula 2 mode is build into the standard distribution.
---
Tags: major-mode
--- |
thread-66512 | https://emacs.stackexchange.com/questions/66512 | Emacs daemon. First emacslient frame loads reasonably fast. Subsequent emacsclient frames load almost instantaneously. Why? | 2021-06-29T11:31:29.630 | # Question
Title: Emacs daemon. First emacslient frame loads reasonably fast. Subsequent emacsclient frames load almost instantaneously. Why?
Emacs daemon greatly reduces time to load the first frame with emacsclient. However, when visiting a file with emacsclient, subsequent emacsclient frames load much faster than the first.
| | Command | Load time (seconds) |
| --- | --- | --- |
| Emacs daemon | emacs --daemon | 30 |
| 1. emacsclient frame - no file visited | emacsclient -c | \<1 |
| 2. emacsclient frame visiting a file | emacsclient -c "file1.org" | 8 |
| 3. All subsequent emacsclient frames visiting the same file as in (2) with different filename | emacsclient -c "file2.org" | 1 |
What is slowing down the first emacsclient frame but not subsequent frames? Apparently that first call to emacsclient still loads something that is not being loaded in subsequent calls to emacsclient. Perhaps mode hooks? I can inspect load times for the daemon, which shows load time for individual packages. But I do not know how to inspect load times for each emacsclient frame.
If possible it would be great if the daemon could also take on the loading that seems to be executed during that first call to emacsclient.
Specs: GNU Emacs 27.1, use-package, Windows Subsystem for Linux, X410 window manager.
Additional information: Test times above are for org files (with org packages successfully loaded by the daemon.) Similar differential load times observed for identical text files. The observed behavior is independent of the file order, that is, the first invocation is slow and the subsequent invocations fast regardless of whether opening filename1 then filename2 or vice versa. Overall slowness may be caused by the fact I am running a virtual machine (WSL)
**Update** Following phils suggestion, I compared the value of the `features` variable after each invocation of emacsclient.
After running emacs --daemon, invoking emacsclient -c without visiting a file loads an empty frame in less than one second. The value the `features` variable is quite large, so I defer quoting the full value in this thread. Next, invoking emacsclient -c "file1.org" loads the frame in 8 seconds. The *difference* between the value of `features` between the first invocation without visiting a file and the invocation visiting a file is:
```
rx org-eldoc face-remap flyspell ispell org-indent ol-eww eww mm-url ol-rmail ol-mhe ol-irc ol-info ol-gnus nnir gnus-sum shr svg dom gnus-group gnus-undo gnus-start gnus-cloud nnimap nnmail mail-source utf7 netrc nnoo gnus-spec gnus-int gnus-range gnus-win gnus nnheader ol-docview doc-view jka-compr image-mode exif ol-bbdb ol-w3m pp cl-print
```
The third invocation, emacsclient - c "file2.org" loads the frame in less than one second and the value of `features` is unchanged from the second invocation.
Based on the change in the value of the `features` variable, there appear to be several suspects for the one-time, eight second delay experienced when first visiting a file. The only one I recognize is flyspell, which is configured by use-package to load with hooks to text-mode and org-mode. Is there a way to load these features in the daemon rather than when opening files? The fact that subsequent invocations of emacsclient do not cause this delay suggests they need be loaded only once.
# Answer
> 3 votes
> `emacsclient -c "filename1"` \[...\] for org files \[...\] What is slowing down the first emacsclient frame but not subsequent frames?
The fact that you are visiting an org-mode file for the first time when you open that frame, which means that Emacs must load the org libraries (which are numerous and large).
> If possible it would be great if the daemon could also take on the loading that seems to be executed during that first call to emacsclient.
Simply put this in your init file:
```
(require 'org)
```
Depending on config (e.g. mode hooks, as you mentioned), there might be additional things being loaded once you actually trigger the major mode for the first time, so you might want to `require` anything additional.
The `features` variable will show you all the things which are currently loaded, and `after-load-functions` can be used to log which files are being loaded, but you might just try something like this as a shortcut:
```
(defun my-load-org-mode-more () (with-temp-buffer (org-mode)))
(add-hook 'emacs-startup-hook #'my-load-org-mode-more)
```
---
Tags: emacsclient, daemon
--- |
thread-66489 | https://emacs.stackexchange.com/questions/66489 | No effect when changing BEAMER_THEME | 2021-06-27T16:48:47.627 | # Question
Title: No effect when changing BEAMER_THEME
I don't get any effect if I put the following line at the start of my Org-mode file:
```
#+BEAMER_THEME: metropolis
```
Indeed, whatever theme name I write after `#+BEAMER_THEME:`, there's not mention of it in the resulting `.tex` file, and I always get the default theme.
I'm using Org mode 9.5 and Emacs 27.2. Am I missing something here? What's the correct way to change the Beamer theme?
EDIT: I'm using Doom Emacs v2.0.9
# Answer
> 1 votes
`beamer` export is *different* from `latex` export: for `latex`, you say `C-c C-e l l` (or similar - this produces a TeX file but does not process it to PDF); for `beamer`, you say `C-c C-e l b` (again this produces a TeX file but does not process it - there are other options specific to `beamer` export for processing to PDF).
If you don't have these entries in the menu, then `beamer` export is not enabled. To enable it, go to the `*scratch*` buffer and type `(require 'ox-beamer)` followed by `C-j`: that enables it for this session. To enable it permanently, add `(require 'ox-beamer)` to your init file (I'd add it towards the end, after the rest of Org mode initialization, but that's probably not necessary).
---
Tags: org-mode, beamer
--- |
thread-66516 | https://emacs.stackexchange.com/questions/66516 | How to resolve key-binding conflict between Icicles and `super-save-mode`? | 2021-06-29T17:08:48.043 | # Question
Title: How to resolve key-binding conflict between Icicles and `super-save-mode`?
I noticed that if Icicles is loaded then `super-save-mode` doesn't save a buffer when you switch to another buffer, though switching frames works.
Icicles seems so technically advanced, yet there is no bug tracker on the internet. All info sits on a wiki page. How/where can I report an Icicles problem?
I run Emacs 26.1
# Answer
> 1 votes
1. **`M-x icicle-send-bug-report`** to send an Icicles bug report or feature request.
And the doc, both on Emacs Wiki (page Icicles - Debugging and Reporting Bugs and in file `icicles-doc2.el`, tells you this clearly:
> You can report a problem you experience with Icicles at IciclesIssuesOpen –- please follow the formatting suggestion provided there.
>
> But the best way to report an Icicles issue or pass along a suggestion is by email. Do one of the following:
>
> * Choose item `Send Bug Report` from menu-bar menu Icicles.
> * Use `M-x icicle-send-bug-report`.
> * Use `M-?` from the minibuffer. Then click button `Icicles Options and Faces` in buffer `*Help*`. Then click the link `Send Bug Report` in buffer `*Customize Group: icicles*`.
2. The question/problem is unclear. You'll need to specify what `super-save-mode` is, and why you expect a buffer to be saved when you switch to another buffer. That probably means explaining how `super-save-mode` invokes buffer saving when another buffer is switched to.
For that, you'll need to provide a step-by-step recipe to reproduce your problem, starting with `emacs -Q` (no init file), or at least point to the code that `super-save-mode` uses or depends on to automatically initiate buffer saving.
For example, *if `super-save-mode` simply advises* particular commands, such as `switch-to-buffer` then it will have no effect (by default) in Icicle mode -- see #3, below -- because (by default) `C-x b` in Icicle mode is not bound to command `switch-to-buffer`.
3. In Icicle mode, by default `C-x b` is bound to `icicle-buffer`, and `C-x 4 b` is bound to `icicle-buffer-other-window`. But there's no requirement that anyone use those bindings. You can *customize option* **`icicle-top-level-key-bindings`** to remove them.
---
Tags: key-bindings, buffers, auto-save, icicles
--- |
thread-62317 | https://emacs.stackexchange.com/questions/62317 | How to open a file in other window in the middle of function run? | 2020-12-17T00:31:48.320 | # Question
Title: How to open a file in other window in the middle of function run?
I use notmuch to read emails.
I've configured `notmuch` to call `offlineimap` via `pre-new` hook.
When I press `G` to refresh my `notmuch` buffer, I want emacs to open my offlineimap log file in another window so I can see the sync process in real time. Here's is what I've done:
```
(use-package notmuch
:bind
(:map notmuch-hello-mode-map
("G" . (lambda ()
(interactive)
(find-file-other-window "~/Maildir/.notmuch/hooks/offlineimap.log")
(notmuch-poll-and-refresh-this-buffer)))))
```
Problem with this is, emacs would only open the log file **after** sync is done.
How do I make emacs open the log file **before** notmuch and offlineimap action?
# Answer
Thanks to lawlist's suggestion, I've ended up with this:
```
(use-package notmuch
:bind
(("G" . (lambda ()
(interactive)
(find-file-other-window "~/Maildir/.notmuch/hooks/offlineimap.log")
(start-process "notmuch" "notmuch" "notmuch" "new")))))
```
since `(notmuch-poll-and-refresh-this-buffer)` is essentially just calling the external `notmuch` program and updates the current buffer, I decided to call `notmuch` myself. The drawback of this is I'll need to press `g` to update the `notmuch` buffer once after the external program finishes.
> 1 votes
# Answer
Here is my function that logs into a buffer and also updates `notmuch` buffers:
```
(setq-default notmuch-new-buffer "*notmuch-new*")
(defun my/notmuch-new ()
"""Update mail."""
(interactive)
(my/notmuch-new-prepare-buffer)
(let ((process (my/notmuch-new-process)))
(set-process-sentinel process 'my/notmuch-new-sentinel)))
(defun my/notmuch-new-prepare-buffer ()
(switch-to-buffer notmuch-new-buffer)
(erase-buffer)
(insert "Updating mail...")
(newline))
(defun my/notmuch-new-process ()
(start-process "notmuch" notmuch-new-buffer "notmuch" "new"))
(defun my/notmuch-new-sentinel (process event)
(notmuch-refresh-all-buffers))
```
> 0 votes
---
Tags: find-file, async
--- |
thread-24597 | https://emacs.stackexchange.com/questions/24597 | Determine if any frame has input focus? | 2016-07-14T05:33:36.170 | # Question
Title: Determine if any frame has input focus?
I have a function that gets called when idle, but I would like it to run only when a frame has input focus.
My current work around is to use `focus-in-hook` and `focus-out-hook` to change the behavior when idle, but I'd like to simplify it by just having one function that would check whether or not it had focus. Here's the code I am working with:
```
(use-package zone
:ensure shut-up
:commands (zone-when-idle)
:bind ("C-c z" . zone)
:init
(setq zone-timeout 30)
(defun zone-when-idle-and-focused ()
"Use with `focus-in-hook' to only zone when our focus is back in Emacs."
(zone-when-idle (or zone-timeout 30)))
(defun zone-nodoze ()
"Use with `focus-out-hook' so we don't zone when our focus is elsewhere."
(let ((inhibit-message t)) (zone-leave-me-alone)))
(add-hook 'focus-in-hook #'zone-when-idle-and-focused)
(add-hook 'focus-out-hook #'zone-nodoze)
(zone-when-idle zone-timeout))
```
# Answer
> 1 votes
Old question but if anyone else has the same problem `(frame-focus-state)` is available in Emacs 27.1 (and possibly before).
From the manual:
```
(frame-focus-state &optional FRAME)
Return FRAME’s last known focus state.
If nil or omitted, FRAME defaults to the selected frame.
Return nil if the frame is definitely known not be focused, t if
the frame is known to be focused, and ‘unknown’ if we don’t know.
```
---
Tags: focus
--- |
thread-66460 | https://emacs.stackexchange.com/questions/66460 | frame-background-mode leads `Args out of range: #<buffer doo.py>, 0, 1` error | 2021-06-23T21:51:56.500 | # Question
Title: frame-background-mode leads `Args out of range: #<buffer doo.py>, 0, 1` error
I am using following answer to search and replace a word in the entire buffer:
```
(defun query-replace-region-or-from-top ()
"If marked, query-replace for the region, else for the whole buffer (start from the top)"
(interactive)
(progn
(let ((orig-point (point)))
(if (use-region-p)
(call-interactively 'query-replace)
(save-excursion
(goto-char (point-min))
(call-interactively 'query-replace)))
(message "Back to old point.")
(goto-char orig-point))))
```
In addition, when I add `(setq-default frame-background-mode 'dark)` line in my `.emacs` file, I have following error message when I use `query-replace-region-or-from-top` function:
```
`Args out of range: #<buffer doo.py>, 0, 1`
```
What my be the reason of this error and how can I resolve it?
---
Debuggin result:
```
Debugger entered--Lisp error: (args-out-of-range #<buffer Driver.py> 0 1)
buffer-substring-no-properties(0 1)
perform-replace("DataStorage" "DataStorage" t nil nil nil nil nil nil nil nil)
query-replace("DataStorage" "DataStorage" nil nil nil nil nil)
funcall-interactively(query-replace "DataStorage" "DataStorage" nil nil nil nil nil)
call-interactively(query-replace)
(save-excursion (goto-char (point-min)) (call-interactively (quote query-replace)))
(if (use-region-p) (call-interactively (quote query-replace)) (save-excursion (goto-char (point-min)) (call-interactively (quote query-replace))))
(let ((orig-point (point))) (if (use-region-p) (call-interactively (quote query-replace)) (save-excursion (goto-char (point-min)) (call-interactively (quote query-replace)))) (message "Back to old point.") (goto-char
orig-point))
(progn (let ((orig-point (point))) (if (use-region-p) (call-interactively (quote query-replace)) (save-excursion (goto-char (point-min)) (call-interactively (quote query-replace)))) (message "Back to old point.")
(goto-char orig-point)))
query-replace-region-or-from-top()
funcall-interactively(query-replace-region-or-from-top)
call-interactively(query-replace-region-or-from-top nil nil)
command-execute(query-replace-region-or-from-top)
```
# Answer
> 0 votes
I am using dracula-theme `(load-theme 'dracula t)`, which was the main cause of the error I was facing.
When I use `query-replace-region-or-from-top` function along with dracula-theme and `(setq-default frame-background-mode 'dark)` I was facing the error I mention on my question.
```
(defun query-replace-region-or-from-top () ... ;; function from my question
(load-theme 'dracula t)
(setq-default frame-background-mode 'dark)
```
First, I have removed `(setq-default frame-background-mode 'dark)` from my `.init` file. The reason, I wanted to use `(setq-default frame-background-mode 'dark)` was to make highlights clear to read. Due to dracula-theme it was so lights and during word seach font color gets white.
---
In order to achieve this, I have update settings for `Isearch` and `Lazy Highlight` using `M-x customize-face`.
Following lines are added into my `customize.el` file:
```
(custom-set-faces
'(isearch ((t :background "#f1fa8c" :foreground "#282a36" :weight bold)))
'(lazy-highlight ((t :background "#8be9fd" :foreground "#282a36" :weight bold)))))
```
---
Tags: frames, colors, replace
--- |
thread-66532 | https://emacs.stackexchange.com/questions/66532 | Why not store all .el/.elc Elpa files inside the same directory to speed up Emacs startup? | 2021-06-30T18:12:02.737 | # Question
Title: Why not store all .el/.elc Elpa files inside the same directory to speed up Emacs startup?
Would it not be possible to modify Emacs package system to store **all** Emacs Lisp files installed from Elpa-compliant packages inside the **same** directory?
That would dramatically reduce the number of entries inside Emacs load-path and would speed up Emacs startup time, would it not?
On my system I have:
* 208 directories in my `~/.emacs.d/elpa` directory,
* 182 directories out of these 208 have only files in them, no sub-directories.
I wrote the following Makefile rules in my build system:
```
.PHONY: timeit
timeit:
@printf "***** Running Emacs startup time measurement tests\n"
@printf "** Report Configuration settings.\n"
$(EMACS) --batch -L . -l $(EMACS_INIT) -l pel-package.el -f pel-package-info
@printf "\n"
@printf "** Time mesaurement:\n"
time -p $(EMACS) -nw -Q -e kill-emacs
time -p $(EMACS) -nw -q -e kill-emacs
time -p $(EMACS) -nw -e kill-emacs
```
My pel-package-info gathers information about the package I use and prints a report on the number used, the load-path, etc...
When I run it a couple of times (with Emacs 26.3) I get something like this:
```
> make timeit
***** Running Emacs startup time measurement tests
** Report Configuration settings.
emacs --batch -L . -l "~/.emacs.d/init.el" -l pel-package.el -f pel-package-info
Loading /Users/roup/.emacs.d/emacs-customization.el (source)...
Loading pel_keys...
Loading /Users/roup/.emacs.d/recentf...
Cleaning up the recentf list...
Cleaning up the recentf list...done (0 removed)
PEL loaded, PEL keys binding in effect.
size of load-path : 241 directories
Number of PEL user-options : 250 (198 are active)
PEL activated elpa packages: 167 ( 45 dependants, 5 imposed by restrictions)
PEL Activated utils files : 25 ( 0 dependants, 0 imposed by restrictions)
** Time mesaurement:
time -p emacs -nw -Q -e kill-emacs
real 0.13
user 0.02
sys 0.01
time -p emacs -nw -q -e kill-emacs
real 0.13
user 0.02
sys 0.01
time -p emacs -nw -e kill-emacs
real 1.66
user 0.98
sys 0.55
>
```
As a small (yet incomplete) experiment:
* I created another directory (`~/tmp/roup`).
+ Inside that directory I created symlinks for **all** .el and .elc files of elpa sub-directories that do not have subdirectories (the 182 directories described above).
* I placed that `~/tmp/roup` directory at the front of Emacs `load-path`.
* I left everything else unchanged.
Then I ran the same test a couple of times and I got something like this:
```
> make timeit
***** Running Emasc startup time measurement tests
** Report Configuration settings.
emacs --batch -L . -l "~/.emacs.d/init.el" -l pel-package.el -f pel-package-info
Loading /Users/roup/.emacs.d/emacs-customization.el (source)...
Loading pel_keys...
Loading /Users/roup/.emacs.d/recentf...
Cleaning up the recentf list...
Cleaning up the recentf list...done (0 removed)
PEL loaded, PEL keys binding in effect.
size of load-path : 242 directories
Number of PEL user-options : 250 (198 are active)
PEL activated elpa packages: 167 ( 45 dependants, 5 imposed by restrictions)
PEL Activated utils files : 25 ( 0 dependants, 0 imposed by restrictions)
** Time mesaurement:
time -p emacs -nw -Q -e kill-emacs
real 0.13
user 0.02
sys 0.01
time -p emacs -nw -q -e kill-emacs
real 0.13
user 0.02
sys 0.01
time -p emacs -nw -e kill-emacs
real 1.50
user 0.92
sys 0.46
>
```
The time measurement is not very accurate as it is affected by other system operations, but I ran them several times and got similar results.
So just by providing a directory with symlinks to several of the files that are used during startup I was able to shave about 0.16 second from startup.
That's a 10% reduction of the startup time.
With Emacs 27.2, with or without package-quickstart, I get similar results (yet Emacs 27.2 is a little faster.)
By removing the 182 directories from the `~/.emacs.d/elpa` directory and place the .el and .elc files into `~/.emacs.d/elpa-files` then put this in front of the load-path (replacing the directory with symlinks) I reduced the time back to 0.77 secs:
```
** Time measurement:
time -p emacs -nw -Q -e kill-emacs
real 0.13
user 0.02
sys 0.01
time -p emacs -nw -q -e kill-emacs
real 0.14
user 0.03
sys 0.01
time -p emacs -nw -e kill-emacs
real 0.77
user 0.58
sys 0.08
>
```
The `~/.emacs.d/elpa-files` holds 1612 files. This is a large number of files but the end result is that it reduces the startup time quite a bit.
**Question**: Would it not be possible to modify the design of Emacs package managing logic to store all the .el and .elc inside a same directory?
We would have to create some other files to remember the package version number that have been installed and their files. But that processing would only occur during a package install or removal, it would not affect Emacs startup time.
Is there something in package.el that makes this strategy difficult or impossible?
* Currently the package inter-dependency checking breaks when package directories identifying the dependents and package detection fail.s But I assume this could be overcome if the installed packages were identified in some form of local db/list.
# Answer
> 2 votes
Sure, that’s possible. However, note that you will somehow have to ensure that filenames from different packages remain distinct. Currently nothing prevents two unrelated packages from both having a `foo.el` file.
There are however two other techniques that can improve startup performance without needing to make radical changes to the package implementation.
The first is simply to avoid using `require` in your init files. If you’re going to use a package called `foo`, and you want to configure some of `foo`’s variables, you do not need to run `(require 'foo)` before doing so. Just set the variables to whatever values you want them to have. Emacs will note that these variables are not yet defined, but will still store your value for them. Later, the first time you call a function from the `foo` package, `foo.el` will be read in and the package will be fully useable.
The second is to configure and `require` all the packages you use frequently, then dump a new Emacs image. You can either use the old `unexec` dumper or the newer portable dumper; either way this ensures that Emacs need not run a complicated init file; most of your customizations are already available in the image. See the help for the functions `dump-emacs` and `dump-emacs-portable` for more information, as well as appendix E.1 Building Emacs of the Emacs manual (which is also available inside of Emacs; just run `C-h i` to open the Info viewer).
---
Tags: package, package-repositories, start-up
--- |
thread-63702 | https://emacs.stackexchange.com/questions/63702 | Equivalent of `continue' in `cl-loop'? | 2021-03-03T11:41:44.787 | # Question
Title: Equivalent of `continue' in `cl-loop'?
Does the `cl-loop` macro implement an equivalent to the `continue` keyword of other languages?
The behavior of `break` can be achieved by using `until` or `while` clauses by placing them in the middle of `cl-loop`, e.g.
```
(cl-loop item in '(1 2 3 4)
do (print item)
until (= 3 item)
do (print item))
```
will be roughly equivalent to Python code
```
for item in [1, 2, 3, 4]:
print(item)
if item == 3:
break
print(item)
```
However, I cannot identify any clause, that says "abort this iteration step, continue with the next", like the `continue` keyword would do. Is there such a clause?
## Usage example
Let's say I want to do something for every string in a list. From the string I want to derive a file-name, and if it exists, collect data about those files.
With a `continue` clause:
```
(defconst mylist '(1 2 "hello" 3 "world" 4))
(defconst mylist-file-data
(cl-loop for prefix in mylist
unless (stringp prefix) continue
for file-name = (concat prefix ".txt")
unless (file-exists-p file-name) continue
for attributes = (file-attributes file-name)
for mtime = (file-attribute-modification-time attributes)
for size = (file-attribute-size attributes)
collect (list file-name mtime size)))
```
By contrast, without a `continue` clause I cannot use `for` clauses to define variables, that can only be defined when the condition is fulfilled. Instead I need to reformulate the loop more awkwardly, e.g. as
```
(defconst mylist-file-data
(cl-loop for prefix in mylist
for file-name = (if (stringp prefix) (concat prefix ".txt"))
for attributes = (if (file-exists-p file-name) (file-attributes file-name))
for mtime = (if attributes (file-attribute-modification-time attributes))
for size = (if attributes (file-attribute-size attributes))
if attributes
collect (list file-name mtime size)))
```
Note how all `(if ...)`s are executed for each iteration step, even when the first already decides that the step could be skipped.
# Answer
If you are looking for short-circuiting logic, e.g. nothing proceeds after one condition fails, I think you need to use something like the and macro. I don't know a way to do this other than to let bind some variables, and use setq inside the loop like below. The attributes line will only be set when the file-name exists here.
```
#+BEGIN_SRC emacs-lisp
(defconst mylist '(1 2 "hello" 3 "world" 4))
(let (file-name attributes)
(cl-loop for prefix in mylist
when (and (setq file-name (and (stringp prefix) (concat prefix ".txt")))
(file-exists-p file-name)
(message "getting attributes for %s" file-name)
(setq attributes (file-attributes file-name)))
collect
(list file-name
(file-attribute-modification-time attributes)
(file-attribute-size attributes))))
#+END_SRC
```
It isn't quite continue like you want, but is functionally the same I think. The only benefit of this over your solution above is the short-circuiting logic though.
Building on the `dolist` example that @Drew suggested below, here is a version that uses `when-let*` which I think also short circuits itself and stops evaluating its arguments on the first nil value.
```
#+BEGIN_SRC emacs-lisp
(defconst mylist '(1 2 "hello" 3 "world" 4))
(setq result ())
(dolist (prefix mylist)
(when-let* ((p0 (stringp prefix))
(file-name (concat prefix ".txt"))
(p1 (file-exists-p file-name))
(attributes (file-attributes file-name))
(mtime (file-attribute-modification-time attributes))
(size (file-attribute-size attributes)))
(message "fn: %s" file-name)
(push (list file-name mtime size) result)))
result
#+END_SRC
```
> 1 votes
# Answer
This "answer" is not meant to be an the answer to the question because it is not "using cl-loop". But rather provide an alternative (as many other answers have done already).
I would recommend using loopy. According to its readme, Loopy is an (external) emacs package that provides a "a macro meant for iterating and looping \[that is\] similar in usage to ~cl-loop~ but uses symbolic expressions rather than keywords."
It already has a `continue` command (whose alias is "skip"). Here is the relevant section of it's manual:
```
2.2.4.2 Skipping an Iteration
.............................
‘(skip|continue)’
Go to next loop iteration.
;; => (2 4 6 8 12 14 16 18)
(loopy ((seq i (number-sequence 1 20))
(when (zerop (mod i 10))
(skip))
(when (cl-evenp i)
(push-into my-collection i)))
(finally-return (nreverse my-collection)))
```
For the specific loop you posed as an example, I think this is the equivalent as `loopy` loop. Pretty straightforward translation.
```
(loopy ((list prefix mylist)
(unless (stringp prefix) (continue))
(expr file-name (concat prefix ".txt"))
(unless (file-exists-p file-name) (continue))
(expr attributes (file-attributes file-name))
(expr mtime (file-attribute-modification-time attributes))
(expr size (file-attribute-size attributes))
(collect (list file-name mtime size))))
```
One Caveat: loopy is still in its infancy and is currently undergoing some change in its syntax (see #33). However, it is more than usable and these changes will make it even more similar to `cl-loop` and easier do nested loops with.
> 1 votes
# Answer
As @NickD pointed out, you can also use `cl-block` and `cl-return-from` to simulate `continue`.
```
(cl-loop for item in '(1 2 3 4)
with items ;; declare variable `items'
do (cl-block 'iteration ;; put the iteration body in a block
(when (= 3 item)
(cl-return-from 'iteration)) ;; jump out the whole iteration if item = 3
(push item items))
finally return (nreverse items)) ;; return '(1 2 4)
```
In the same spirit, your example could be implemented like this:
```
(defconst mylist-file-data
(cl-loop for prefix in mylist
with file-data-list
do (cl-block 'iteration
(let (file-name attributes mtime size)
(unless (stringp prefix)
(cl-return-from 'iteration))
(setq file-name (concat prefix ".txt"))
(unless (file-exists-p file-name)
(cl-return-from 'iteration))
(setq attributes (file-attributes file-name))
(setq mtime (file-attribute-modification-time attributes))
(setq size (file-attribute-size attributes))
(push (list file-name mtime size) file-data-list)))
finally return (nreverse file-data-list)))
```
Or, to get rid of those `setq`
```
(defconst mylist-file-data
(cl-loop for prefix in mylist
with file-data-list
do (cl-block 'iteration
(let* ((prefix-string? (unless (stringp prefix)
(cl-return-from 'iteration)))
(file-name (concat prefix ".txt"))
(file-name-exists? (unless (file-exists-p file-name)
(cl-return-from 'iteration)))
(attributes (file-attributes file-name))
(mtime (file-attribute-modification-time attributes))
(size (file-attribute-size attributes)))
(push (list file-name mtime size) file-data-list)))
finally return (nreverse file-data-list)))
```
But at this point, @John Kitchin's answer using `when-let*` looks similar but cleaner.
> 1 votes
# Answer
This doesn't answer your question about CL's `loop`. But it shows you another, simple way to do what you apparently want to do.
```
(let ((result ())
file-name attributes mtime size)
(dolist (prefix mylist)
(unless (stringp prefix)
(setq file-name (concat prefix ".txt")
attributes (file-attributes file-name)
mtime (file-attribute-modification-time attributes)
size (file-attribute-size attributes))
(push (list file-name mtime size)))))
```
And if you really do want to break out of the loop at any point (instead of `continue`ing), just wrap the `dolist` in a `catch`, and then `throw` to that catch, throwing it whatever value you like.
> 0 votes
---
Tags: elisp, cl-lib, iteration, loop-facility
--- |
thread-66535 | https://emacs.stackexchange.com/questions/66535 | Can't unbind mouse button from keymap | 2021-07-01T04:13:05.483 | # Question
Title: Can't unbind mouse button from keymap
This is more of an academic question than a practical one, as I've already worked around it. However, the curiosity / mystery is killing me. I'm about 10 days into emacs, so new to a lot of this.
As I've been experimenting and learning about keymaps, I've been trying to unbind \[mouse-2\] from dired without success. From the dired.el source, I see this:
```
(defvar dired-mode-map
;; This looks ugly when substitute-command-keys uses C-d instead d:
;; (define-key dired-mode-map "\C-d" 'dired-flag-file-deletion)
(let ((map (make-keymap)))
(set-keymap-parent map special-mode-map)
(define-key map [mouse-2] 'dired-mouse-find-file-other-window)
(define-key map [follow-link] 'mouse-face)
```
However, when I try to unbind it with:
```
(define-key dired-mode-map [mouse-2] nil)
```
It remains bound. I've tried every method I can think of to unbind this, without success. I'm curious if someone can point me to what might be going on.
# Answer
I don't see that. Did you start Emacs using `emacs -Q` (no init file)?
If I do that, and then I do what you tried:
```
(define-key dired-mode-map [mouse-2] nil)
```
Then `mouse-2` is no longer bound in `dired-mode-map`.
To see that, you can load library `help-fns+.el` and use `C-h M-k dired-mode-map` before and after evaluating that sexp.
Or you can just try `mouse-2` in a Dired buffer, or use `C-h k` and click `mouse-2` -- its global binding is in effect.
> 0 votes
---
Tags: key-bindings, dired, keymap, mouse
--- |
thread-66541 | https://emacs.stackexchange.com/questions/66541 | Git track flag in Dired | 2021-07-01T10:45:06.067 | # Question
Title: Git track flag in Dired
How can I show an additional column in Dired, where I can see if the file is tracked or not by git in the current branch?
# Answer
You might want to look at diff-hl and this answer on Stack Exchange. Basically, diff-hl puts the git status of files in a dir in the margin rather than in the column. Depending on what exactly you're looking for, this should suffice. Just add the `diff-hl` package, and use `(add-hook 'dired-mode-hook 'diff-hl-dired-mode)`
> 2 votes
---
Tags: magit, dired, git
--- |
thread-66558 | https://emacs.stackexchange.com/questions/66558 | How to match a single ')' with replace-regex? | 2021-07-02T17:57:56.080 | # Question
Title: How to match a single ')' with replace-regex?
I want to replace a list in the form of
```
1)
2)
3)
4)
```
with
```
*
*
*
```
I've tried using the regex `[0-9]*\)`, but it gives `Invalid regexp: "Unmatched ) or \\)"` and `[0-9]*\\)` replaces 0 matches. in `regex-builder`, `[0-9]*\)` matches the expected items.
I'm using `spacemacs 0.300.0` on `emacs 26.3`
# Answer
> 1 votes
On writing this question, I found the (very simple) answer, so I'll put it out there for anyone else who finds this confusing (considering I found no similar questions).
It seems that the default behaviour for `replace-regexp` is matching parenthesis literally, so the solution was just `[0-9]*)` and for the usual group capturing is instead `\(group\)`, maybe some configuration or variable changes this.
TL;DR: use `)` with `replace-regexp` for literal matches
---
Tags: spacemacs, regular-expressions, parentheses
--- |
thread-66560 | https://emacs.stackexchange.com/questions/66560 | For convenience, how should I load a package whenever a specific other package loads? | 2021-07-02T18:48:22.053 | # Question
Title: For convenience, how should I load a package whenever a specific other package loads?
I have a package that enhances the functionality of another package. To save the user the effort of any additional configurating, I would like my package to load automatically if the larger package loads.
(In my example, my package is a Flycheck checker, but I don’t think this situation will be specific to Flycheck checkers).
Is there a standard idiom for achieving this?
---
I find myself tempted to put the following at the end of my package:
```
;;;###autoload
(with-eval-after-load 'flycheck
(unless (featurep 'flycheck-mychecker)
(require 'flycheck-mychecker)))
```
Now, `package-lint` tells me:
> warning: \`with-eval-after-load' is for use in configurations, and should rarely be used in packages
However, I couldn’t find an explanation of why this is typically bad in packages, and in what circumstances the “rarely used” exception should apply.
# Answer
> 2 votes
1. Use `autoload` for specific commands etc.
2. Use `require` if your library depends on another. That's the main question to ask yourself: does your library need the other library? If so, `require` it.
You can also use a "soft-require" if you want to load another library whenever something is true. For example:
```
(when (fboundp 'foobar) (require 'foo nil t))
```
3. Use `with-eval-after-load` (or `eval-after-load`) if you want to do something after some other library is loaded:
```
(with-eval-after-load 'bar
;; ...
)
```
I imagine that the "rarely used" just means that most libraries explicitly use `require` or they autoload stuff. The doc of `with-eval-after-load` and `eval-after-load` describes their behavior, which in turn defines their use cases. Don't use them when you don't need them; that's all I think that "rarely used" intends.
On the other hand, presumably your package is intended to be optional. In that case, it's enough that a user explicitly loads it. And in that case all you need to do is `require` the larger package at the outset of your code. I imagine that this is also part of what the text you quote intends.
---
A final note. If you want to load a library again, or load a library with the same name as one that's already been loaded (e.g. to pick up some other variant of version of it), then use `load-library`, not `require`. And if you want to load the source file (`*.el`) then explicitly include the `.el` in the argument to `load-library`.
---
Tags: package, autoload, require, eval-after-load
--- |
thread-66549 | https://emacs.stackexchange.com/questions/66549 | How to handle autocapitalize for things like i.e., e.g.? | 2021-07-01T18:55:30.990 | # Question
Title: How to handle autocapitalize for things like i.e., e.g.?
In auto-capitalize mode, whenever Latin abbreviations such as `e.g.` or `i.e.` are entered, auto-capitalize mode seems to be too eager, and capitalizes the first letters `E` and `I` after the first period `.` is entered.
*Is it possible to configure the mode to trigger auto-capitalize only after the period **plus a whitespace** is entered?*
(This seems to be a more natural way to capitalize to me.)
# Answer
> 3 votes
Based on the related SO question@Frimin, there are at least two ways to disable things like `e.g.`, `i.e.`.
One is to use regular expressions and `auto-capitalize-predicate` to filter them out explicitly in `init.el`:
```
(setq auto-capitalize-predicate
(lambda () (not (looking-back
"\\([Ee]\\.g\\|[Ii]\\.e\\)\\.[^.]*" (- (point) 20)))))
```
The second is to manually replace the triggering whitespace or punctuation character with `M-x quoted-insert` (e.g. `gnu C-q .`).
---
Tags: capitalization, sentences, auto-capitalize-mode
--- |
thread-65137 | https://emacs.stackexchange.com/questions/65137 | How to convert org-mode section to html | 2021-06-02T17:39:57.133 | # Question
Title: How to convert org-mode section to html
There exists `(org-html-export-as-html nil nil t t)` which converts an entire org-mode buffer to another buffer, but is there a way to convert a string in org-mode format to a string in html?
I'm looking to replace the function `org-export-string-as` from ox-slimhtml, because the package appears to be going away.
# Answer
> 1 votes
`org-export-string-as` should be a built in function of ox.html
You can use it like this:
```
(org-export-string-as "*bold*" 'html)
```
# Answer
> 0 votes
You can always get the contents of a buffer as a string by making the buffer current and then using `buffer-substring`. Something like this:
```
(with-current-buffer "Org HTML buffer name whatever that is"
(buffer-substring (point-min) (point-max)))
```
You might want to use `buffer-substring-no-properties` instead if you don't care about text properties.
See the documentation of `with-current-buffer` and `buffer-substring` (or `buffer-substring-no-properties`) for more details: do `C-h f buffer-substring` and similarly for the others.
There are string functions in Emacs (and there is also `s.el`, the "missing" Emacs string library) but if you want to do heavy manipulations, then creating a buffer, putting whatever you want into it, doing all kinds of manipulations and then getting the resulting string out of the buffer with `buffer-substring` is a very general and common idiom (although you'd probably use a temporary buffer in most cases).
---
Tags: org-export, html
--- |
thread-66409 | https://emacs.stackexchange.com/questions/66409 | How can I use the current org-mode buffer as a Target in an org-capture template? | 2021-06-21T01:27:03.373 | # Question
Title: How can I use the current org-mode buffer as a Target in an org-capture template?
I want to design an org-capture definition that targets the current org file. Looking at the list of available targets it's not clear to me what I should use. Considering using (current-buffer) as the file name in the Target definition.
# Answer
> 2 votes
`(file buffer-name)` will set the target to the current buffer. Here's an example capture template:
```
("T" "test" plain (file buffer-name) "\n- %?")
```
Explanation: The doc string for `org-capture-templates` says:
> ... Most target specifications contain a file name. If that file name is the empty string, it defaults to ‘org-default-notes-file’. A file can also be given as a variable **or as a function called with no argument**.
Emphasis added.
In this case, the function is `buffer-name`, which gives the file name associated with the current buffer (when called with no argument).
---
Tags: org-capture
--- |
thread-66565 | https://emacs.stackexchange.com/questions/66565 | Count number of lines between two consecutive matches | 2021-07-03T00:12:34.727 | # Question
Title: Count number of lines between two consecutive matches
I have files such as these:
```
0000
0030
+ Something
+ Another thing
+ One more thing
0200
+ Something else
+ And one more thing
0230
```
In the above, the numbers represent time in `HHMM` format. I want to transform it to:
```
0010 + Something
0020 + Another thing
0030 + One more thing
0115 + Something else
0200 + And one more thing
```
I will explain the transformation in the above example:
* between `0030` and `0200` there are 3 lines. And time difference between `0000` and `0030` is 30 minutes. So each item below `0030` gets a 10 minutes increment starting from `0000`. And thus the 3 new timestamps are `0010`, `0020` and `0030` respectively.
* similarly between `0200` and `0230` there are 2 lines. And the time difference between `0030` and `0200` is 90 minutes. So each item below `0200` gets 45 minutes increment starting from `0030`. So the 2 new timestamps are `0115` and `0200` respectively.
I have made some progress in writing an elisp-macro for this transformation task:
1. I could modify the answer to this emacs.stackexchange post to compute the time difference between times.
2. I could write a function that takes in time and minutes elapsed to print new time after adding elapsed minutes to time.
3. Now the only thing that I need to complete my recipe is: the number of items between two consecutive `HHMM` patterns so that I can split the difference of time evenly over the items.
4. Lastly I plan to wrap up all the above inside a `(while (search-forward-regexp "pattern" nil :noerror)` to apply the above macros to everywhere applicable inside the file.
Here is the summary of my failed attempts so far:
I recorded a keyboard macro to mark the region between two consecutive `HHMM` pattern and then I am trying to use `(count-lines start end)`. However I get the error:
```
Symbol's value as a variable is void: start
```
Here is my code snippet for this attempt:
```
(defun timesheet-fill-times ()
(interactive)
(let (diff lines)
(setq diff (timesheet-time-diff))
(timesheet-mark-lines)
(setq lines (count-lines start end))
(message "%d diff %d lines" diff lines)
)
)
```
where `timesheet-time-diff` is my elisp macro to compute time difference between consecutive patterns and `timesheet-mark-lines` is my recorded keyboard macro to mark the relevant region. I tried to modify the function definition to: `(defun timesheet-fill-times (start end) ;; rest of code )`. Now the error becomes:
```
Wrong number of arguments
```
However, strangely, the following works alright: I have defined this function:
```
(defun my-count-lines-region (start end)
(interactive "r")
(message "%d"
(count-lines start end)))
```
So if I keep my cursor on `+` after `0030` and do `M-x timesheet-mark-lines RET M-x my-count-lines-region RET` I get 3 as expected. And similarly with the cursor on `+` after `0200` I get 2 as expected.
My other approach I thought of was that: I can match for the pattern `HHMM - some lines - HHMM` by using something like this:
```
(re-search-forward (concat "^\\([0-2][0-9]\\)\\([0-5][0-9]\\)"
"\\(\\(.\\|[\n]\\)*?\\)"
"\\([0-2][0-9]\\)\\([0-5][0-9]\\)"
) nil :noerror)
```
Is there someway I can count the number of newline characters in that match?
I have tried my best but I feel stuck. Please advice.
# Answer
THIRD EDIT (added after @Inspired\_Blue's answer)
@Inspired\_Blue I did not try to completely follow and understand your answer. But as a matter of feedback, I will post here my way of solving the problem. While incidentally it inserts the correct times, you should still add functions to get the correct times for the general case.
I strongly recommend you to get familiar with `edebug` as it is only a really tiny bit of reading, while it will greatly boost your productivity. Then practice how to use `edebug`, while using it for reading my solution.
In short, in my solution I first parse the buffer into the following list (call `se-answer` interactively on your original text to see a pretty printed version of the list), where the car of each element is a pair (cons) with the start and end times, and the cdr forms a list containing the lines (the length of this list, effectively counts the number of lines between consecutive matches, providing an answer to your question).
```
(((0 . 30))
((30 . 200) "+ Something\n" "+ Another thing\n" "+ One more thing\n")
((200 . 230) "+ Something else\n" "+ And one more thing\n"))
```
Subsequently I format the list 'back' to your transformed text using a "list-eater" (term used in the books "Land of lisp" and "Realm of racket")
```
;; define handy macro for pretty printing
(defmacro parse-print (data &optional stream mode)
"Return value but pretty print when called interactively.
Optionally set STREAM (see `pp'). If STREAM is a buffer then
optionally set MODE for buffer (for syntax highlight)."
`(if (not (called-interactively-p))
,data
(pp ,data ,stream)
(when (bufferp ,stream))
(pop-to-buffer ,stream)
(when ,mode
(funcall ,mode))))
(defun se-answer ()
(interactive)
;; to prevent infinite loop first delete all trailing blank lines and
;; whitespace, and if exist final newline
(delete-trailing-whitespace)
(goto-char (point-max))
(when (bolp)
(delete-backward-char 1))
(goto-char (point-min))
;; parse buffer
(let (blocks) ;; we designate blocks for each part between a start- and end-time
(while (not (eobp))
;; use only this while loops body for single block (e.g. for your keyboard
;; macro)
(let (lines ;; per block we collect (push) the text lines in (to) a list
(start-time (thing-at-point 'number))) ;; also we collect the start-time
(forward-line)
(while (not (thing-at-point 'number))
(push (thing-at-point 'line t) lines)
(forward-line))
(push (cons (cons start-time (thing-at-point 'number))
(nreverse lines)) ;; and collect (push) the start- and end-time plus
blocks) ;; the lines in the block in (to) the list of blocks
(end-of-line)))
(unless (called-interactively-p)
(erase-buffer))
;; NOTE that you can call this function/command interactively to see the
;; pretty printed list.
(parse-print (nreverse blocks) (get-buffer-create "parsed-list") 'emacs-lisp-mode)))
(defun insert-transformed-text (parsed-buffer)
(interactive (list (se-answer)))
;; First an exit condition for. A list eater 'eats' the elements of the list
;; so we exit when there is only one element left (which can optionally get
;; inserted to the buffer).
(if (not (cdr parsed-buffer))
(if (y-or-n-p "Include final time?")
(insert (format "%s" (cdaar parsed-buffer)))
nil)
(let* ((n (length (cdadr parsed-buffer)))
(int-size (/ (- (cdaar parsed-buffer) (caaar parsed-buffer)) n)))
(let ((time (+ (caaar parsed-buffer) int-size)))
(dolist (x (cdadr parsed-buffer))
(insert (format "%s %s" time x))
(setq time (+ time int-size)))))
;; By passing back the 'tail' of the list, the function 'slowly eats' the
;; list.
(insert-transformed-text (cdr parsed-buffer))))
```
Find a buffer with `C-x C-f` and give it some name ending with the `.el` (this opens a buffer in `emacs-lisp-mode`), paste and load the code in that buffer. Then open a scratch buffer in a split screen and paste your original text/list. Then instrumentalize the `insert-transformed-text` (or the `se-answer`) function/command (see edebug), and finally in the scratch buffer (with ONLY your original text) run the command `M-x insert-transformed-text`.
Have fun!
SECOND EDIT
I see now that you already found `count-lines` (I read over it). So the `(interactive "r")` provides your function with `region-beginning` and `region-end` as its arguments (see here and here).
I've added a comment to answer your question about lines in the regexp match. But I would strongly advise not to approach the problem in this way.
FIRST EDIT
Programmatically, `count-words-region` does not fulfil your needs directly. But by inspecting the function you will find the function `count-words--message`, from which you get another answer by inspecting its code (simpler than my provided solution).
END EDIT
As it seems you want to mark the region, I provided a simplest answer as a comment. Now I am not sure what you ask exactly, but more programmatically, I would propose something as follows:
```
(defun se-answer ()
(interactive)
(let ((start-time (thing-at-point 'number))
(start-line (string-to-number (cadr (split-string (what-line))))))
(forward-line)
(re-search-forward "^[0-9]+")
(let ((end-time (thing-at-point 'number))
(end-line (string-to-number (cadr (split-string (what-line))))))
(message "start-time %s\nstart-line %s\nend-time %s\nend-line %s\nnum lines: %s"
start-time
start-line
end-time
end-line
(- end-line start-line 1)))))
```
> 2 votes
# Answer
@dalanicolai's `se-answer` function (see here), I believe, is superior to my solution as mine uses regular expressions and hence is possibly slower. Hence I accept his solution as the answer to this question.
However I will share my solution here as well (for anyone who may learn something new from code snippets on stackexchange, like I do):
```
(defun my-count-occurences (regex string)
(my-recursive-count regex string 0))
(defun my-recursive-count (regex string start)
(if (string-match regex string start)
(+ 1 (my-recursive-count regex string (match-end 0)))
0))
(defun timesheet-count-items ()
(interactive)
(let (match diff lines)
(save-excursion
(if (re-search-forward (concat "^\\(\\(.\\|[\n]\\)*?\\)"
"\\([0-2][0-9][0-5][0-9]\\)"
) nil :noerror)
(my-count-occurences "\n" (match-string 1))
))))
(defun timesheet-time-diff ()
(interactive)
(let (begin-hh begin-mm end-hh end-mm diff)
(save-excursion
(if (re-search-backward (concat "^\\([0-2][0-9]\\)\\([0-5][0-9]\\)"
"\\(\\(.\\|[\n]\\)*?\\)"
"\\([0-2][0-9]\\)\\([0-5][0-9]\\)"
) nil :noerror)
(progn
(setq begin-hh (string-to-number (match-string 1)))
(setq begin-mm (string-to-number (match-string 2)))
(setq end-hh (string-to-number (match-string 5)))
(setq end-mm (string-to-number (match-string 6)))
(setq diff (- (+ end-mm
(* 60 end-hh))
(+ begin-mm
(* 60 begin-hh))))
(list begin-hh begin-mm diff)
)
)
)))
(defun timesheet-time-add (hh mm de)
(interactive)
(let (M h m O)
(save-excursion
(progn
(setq M (+ (* 60 hh) mm de))
(setq h (/ M 60))
(setq m (% M 60))
(setq O (concat (format "%02d" h)(format "%02d" m)))
))))
(defun timesheet-fill-time ()
(interactive)
(let (temp count diff step start-hh start-mm delta)
(save-excursion
(setq count (timesheet-count-items))
(setq temp (timesheet-time-diff))
(setq start-hh (nth 0 temp)
start-mm (nth 1 temp)
diff (nth 2 temp))
(setq step (/ diff count))
(while (> count 0)
(setq count (- count 1))
(setq delta (- diff (* count step)))
(beginning-of-line)
(insert (concat (timesheet-time-add start-hh start-mm delta)
" "))
(next-line)
)
)))
(defun timesheet-process ()
(interactive)
(goto-char (point-min))
(while (re-search-forward "
\\([^
0-9]\\)" nil t)
(backward-char 1)
(timesheet-fill-time))
(goto-char (point-min))
(while (search-forward-regexp "
\\([0-9]\\{4\\}\\)
" nil t) (replace-match "
" t nil))
)
```
So to compare my solution with @dalanicolai's solution:
1. I solve for the entire transformation as in the example of my question.
2. Clearly @dalanicolai's solution is more elegant and pithy.
3. I will have to adapt @dalanicolai's solution to my needs to carry out the entire transformation (which I plan to do sometime soon and add as an edit to my answer).
4. My files have about 400-600 lines. And even my solution runs almost instantaneously.
Lastly, if you happen to read my code and are kind enough to offer me feedback, please do. As I have just started learning `lisp`, I will value such things immensely!
> 1 votes
---
Tags: regular-expressions, elisp-macros
--- |
thread-66347 | https://emacs.stackexchange.com/questions/66347 | gdb input/output buffer not working | 2021-06-17T13:49:04.877 | # Question
Title: gdb input/output buffer not working
I start gdb (with many-windows) through `projectile-run-gdb` but stdin/out is not displayed in the input/output buffer.
And I have no clue where to look for the issue. Google search did not bring up any good answers. Can somebody give me a good starting point?
If I start gdb from the command line, printed output is showing up in the terminal as expected.
Emacs Version: 28.0.50
# Answer
> 1 votes
Apparently the target output stream is not redirected while debugging on a remote target, so you need to set this.
This snippet helped me solving the issue:
```
(defun private-gdbmi-bnf-target-stream-output (c-string)
"Change behavior for GDB/MI target the target-stream-output so that it is displayed to the console."
(gdb-console c-string)
)
(advice-add 'gdbmi-bnf-target-stream-output :override 'private-gdbmi-bnf-target-stream-output)
```
---
Tags: debugging, gdb
--- |
thread-66438 | https://emacs.stackexchange.com/questions/66438 | Emacs does not respoect custom-set-faces, loads wrong font | 2021-06-22T13:56:35.137 | # Question
Title: Emacs does not respoect custom-set-faces, loads wrong font
I have an issue setting fonts in `GNU Emacs 27.2 (build 1, x86_64-w64-mingw32) of 2021-03-26` which is under Windows 10. I set the font successfully, but when I reopen Emacs my setting is not respected and instead `NexusSansPro` which is *not* my font of choice is used.
I intentionally set the font via Emacs' `Options->Set Default Font` and `Opetions->Save Options` menus to make sure I'm not making any lisp mistakes.
The relevant part which is store by Emacs in `init.el` reads:
```
(custom-set-faces
;; custom-set-faces was added by Custom.
;; If you edit it by hand, you could mess it up, so be careful.
;; Your init file should contain only one such instance.
;; If there is more than one, they won't work right.
'(default ((t (:family "JetBrains Mono Light" :foundry "outline" :slant normal :weight light :height 143 :width normal)))))
```
I'm new to Windows and never had the issue in Linux. Not sure if this a Windows specific probelem or not...
# Answer
> 0 votes
Answering my own question:
The issue seems to be rooted in the "**Light**" word in the font name. Eventhough it was saved by Emacs' GUI, it was causing the issue replacing the line with following fix the issue, however, doesn't exactly give me the font I wanted
```
(custom-set-faces
;; custom-set-faces was added by Custom.
;; If you edit it by hand, you could mess it up, so be careful.
;; Your init file should contain only one such instance.
;; If there is more than one, they won't work right.
'(default ((t (:family "JetBrains Mono" :foundry "outline" :slant normal :weight light :height 143 :width normal)))))
```
---
Tags: init-file, fonts
--- |
thread-66562 | https://emacs.stackexchange.com/questions/66562 | how to only include bibliography once | 2021-07-02T19:56:20.607 | # Question
Title: how to only include bibliography once
How can I export these 2 files individually, but only include the bibliography **once** in the resulting `b.pdf`?
As shown, I get two copies of the References section in the `b.pdf` file.
I'm not sure if this is an `org-mode` only question, or if `org-ref` has the answer, so I included both tags.
a.org
```
cite:something
bibliographystyle:unsrt
bibliography:stuff.bib
```
b.org
```
#+INCLUDE: "a.org"
cite:anotherthing
bibliographystyle:unsrt
bibliography:stuff.bib
```
# Answer
> 0 votes
You can change the bibliography link to nobibliography I think.
---
Tags: org-export, org-ref
--- |
thread-66556 | https://emacs.stackexchange.com/questions/66556 | Accept default in ivy filename prompt | 2021-07-02T16:10:09.510 | # Question
Title: Accept default in ivy filename prompt
Using Doom Emacs, when I invoke a command (such as `diff`) that needs a filepath I get an `ivy` prompt that names a default value:
But I am unable to clear the line or somehow tell ivy to take that default. Does ivy even know about it? Can I force ivy to output an empty string?
I browsed the ivy docs but to no avail
# Answer
> 2 votes
Use `ivy-immediate-done` (defaults to `C-M-j`) without entering any text to use the default value.
---
Tags: minibuffer, ivy, doom, path, prompt
--- |
thread-66573 | https://emacs.stackexchange.com/questions/66573 | Looking for a better way to test whether the current Emacs process is running under GNU Screen | 2021-07-03T14:55:04.697 | # Question
Title: Looking for a better way to test whether the current Emacs process is running under GNU Screen
**NB:** For the sake of this question, please assume that the underlying OS is some flavor of Unix. If more specificity is required, then please assume that it is either Darwin or some flavor of Linux.
---
In my `.emacs` file, I would like to map a particular key combination *only when* the current `emacs` process is a descendant of a `screen` (GNU screen) process. I am looking for a *robust* way to test for this condition.
I know that `(emacs-pid)` will evaluate to an integer corresponding to the pid of the current emacs process.
Beyond this point, the only thing I can come up with is the following (very fragile, IMO) monstrosity:
```
(if (= 0
(shell-command
(format "pstree -pu $USER | grep -qP -- '-screen\\(\\d+\\)-.*-emacs\\(%d\\)'"
(emacs-pid))))
(global-set-key ...)
)
```
Basically, this code runs a `global-set-key` command if the following expression evaluates to 0:
```
(shell-command
(format "pstree -pu $USER | grep -qP -- '-screen\\(\\d+\\)-.*-emacs\\(%d\\)'"
(emacs-pid)))
```
To evaluate this expression, Emacs will run the command below<sup>1</sup> in a subshell, and will use its exit status as the expression's value:
```
pstree -pu $USER | grep -qP -- '-screen\(\d+\)-.*-emacs\(<EMACS_PID>\)'
```
This shell command, in turn, will have an exit status of 0 if and only if the line in the output of `pstree -pu $USER` that contains the substring `-emacs(<EMACS_PID>)` is preceded by a substring that matches the Perl regex `-screen\(\d+\)-`.
In my experience, Emacs extension code that relies on parsing the output of some shell command is always extremely fragile.
Therefore, I am looking for an alternative way to solve this problem that does not rely on `shell-command` or similar, but rather directly interrogates the ancestors of `(emacs-pid)` (using the underlying OS's `getppid` function *somehow*). This would entail traversing the sequence of `(emacs-pid)`'s ancestors until finding either one whose associated command is `screen`<sup>2</sup> or one whose `pid` is 1 (i.e. it's the root process).
---
<sup><sup>1</sup> Here and below, I use the expression `<EMACS_PID>` as a placeholder for the integer `(emacs-pid)`.</sup>
<sup><sup>2</sup> Admittedly, the problem of determining, *in a robust way*, that a particular PID corresponds to a GNU-screen process may already be pretty non-trivial.</sup>
# Answer
Skip all the pid stuff, and just check the `STY` environment variable. If it is set, then emacs is running inside screen.
> 4 votes
# Answer
@db48x's answer is undoubtedly the best answer to the question. But it depends on the good graces of `screen` which conveniently sets the `STY` variable that sub-processes can check (`tmux` sets a `TMUX` variable, so it's equally cooperative). What if you have a less cooperative process that does not set a variable? Doing the "pid stuff", i.e. walking up the tree of processes until you find either pid 1 or the process of interest can easily be done within emacs: you don't need to parse shell command output. Here is a simple implementation:
```
(defun ndk/walk-up-process-tree-up-to (name)
(catch 'found
(let ((pid (emacs-pid)))
(while t
(let* ((attrs (process-attributes pid))
(ppid (cdr (assoc 'ppid attrs)))
(comm (cdr (assoc 'comm attrs))))
(cond ((string= comm name)
(throw 'found pid))
((= pid 1)
(throw 'found nil))
(t (setq pid ppid))))))))
```
The function returns the pid of the (first) process it finds walking up the process trees with the given name, or nil if no such name is found.
I tested it with an emacs started from screen, which was started from an xterm, which was started from my GUI emacs. The process tree as viewed with `pstree` looked like this:
```
$ pstree -psl $$
systemd(1)───systemd(2728)───gnome-shell(2949)───emacs(622022)───bash(623167)───xterm(796197)───bash(796199)───screen(796203)───screen(796204)───bash(796205)───emacs(796207)───bash(796226)───pstree(796325)
```
Evaluating `(ndk/walk-up-process-tree-up-to "screen")` in the child `emacs` whose `pid` is 796207 returns 796204, the pid of the child `screen`, the closest ancestor of the child `emacs`.
A couple of weaknesses: 1) As noted above, it returns the pid of the closest ancestor, so if you want the top-level `screen` e.g. in the above example, the function needs modifications. 2) A more significant weakness might be that the `comm` string does not match naive expectations (although it did in this case): a substring check might be better than the equality check I used. 3) It probably does not work on non-Unixy systems, since I doubt that they have a pid 1.
> 1 votes
---
Tags: key-bindings, process, subprocess
--- |
thread-66580 | https://emacs.stackexchange.com/questions/66580 | How do I move the cursor to be just after the `>` character on the beggining of REPL evaluation? | 2021-07-03T21:29:45.970 | # Question
Title: How do I move the cursor to be just after the `>` character on the beggining of REPL evaluation?
I am using Emacs and Slime to work on Common Lisp code and I would like to know the most efficient way to move the cursor to the beginning of the `REPL>` assessment.
For instance, modelling the cursor as "I", which keys should I press to move the cursor from this position:
```
NIL
REPL> (defvar lista-history-entries (reverse (mapcar #'url (mapcar #'htree:data
(with-data-unsafe "I" (history (history-path (current-buffer)))
(alex:hash-table-keys (htree:entries history)))))))
```
Into this position:
```
NIL
REPL> "I"(defvar lista-history-entries (reverse (mapcar #'url (mapcar #'htree:data
(with-data-unsafe (history (history-path (current-buffer)))
(alex:hash-table-keys (htree:entries history)))))))
```
If I press `C-a` it brings me to the beginning of the line, which is only useful for my goal if the starting position is on the first line. If I press `M-a` it brings me to the NIL expression, just above the REPL. It is close and helpful. But I bet there is a way to be exactly at the beginning of the evaluation.
# Answer
The slime REPL buffer is is REPL mode. You can get information about the mode with `C-h m`. That is useful in that it shows you the keymap for the mode, and among other things, you will see that `C-c C-p` is bound to `slime-repl-previous-prompt`. Here is an excerpt from the description:
```
REPL mode defined in ‘slime-repl.el’:
Major mode for interacting with a superior Lisp.
key binding
--- -------
C-c Prefix Command
C-j slime-repl-newline-and-indent
RET slime-repl-return
C-x Prefix Command
ESC Prefix Command
SPC slime-space
(this binding is currently shadowed)
, slime-handle-repl-shortcut
DEL backward-delete-char-untabify
C-<down> slime-repl-forward-input
C-<return> slime-repl-closing-return
C-<up> slime-repl-backward-input
<return> slime-repl-return
C-x C-e slime-eval-last-expression
C-c C-c slime-interrupt
C-c C-n slime-repl-next-prompt
C-c C-o slime-repl-clear-output
C-c C-p slime-repl-previous-prompt
C-c C-s slime-complete-form
C-c C-u slime-repl-kill-input
C-c C-z slime-nop
C-c ESC Prefix Command
C-c I slime-repl-inspect
M-RET slime-repl-closing-return
M-n slime-repl-next-input
M-p slime-repl-previous-input
M-r slime-repl-previous-matching-input
M-s slime-repl-next-matching-input
```
`C-h m` is one of the first things I do when exploring an unfamiliar mode.
> 2 votes
# Answer
`backward-sexp`, bound to `C-M-b` by default\`, would do it. Of course, if you’re nested inside several s–expressions then you would need to press it multiple times.
So perhaps you want `beginning-of-defun`, bound to `C-M-a`, instead.
> 2 votes
---
Tags: motion, repl, slime
--- |
thread-66548 | https://emacs.stackexchange.com/questions/66548 | Practical emacs abbrev-mode | 2021-07-01T15:49:09.090 | # Question
Title: Practical emacs abbrev-mode
Following up on Different abbrevs for each major mode, which covers the *first step* that I found from here. And now, trying to cover to the *next step*.
In summary,
* the *first step*, i.e., Different abbrevs for each major mode, solves the problem of allowing abbreviations with leading "\`" for each different major mode
* the *next step*, is to allow moving cursor into the proper position after expansion, which explained clearly in the above wiki
Please take a look at the *code change* at https://www.diffchecker.com/7TPMxkzU. It has two sides, which are two cases that I tried for the *next step*. They are basically all of my config, apart from load-path setting. On the left, everything is working; whereas on the right, abbreviations with leading "\`" are not working any more. In details,
```
(define-abbrev-table 'python-mode-abbrev-table
'(
("fo" "bar")
("`foo" "bar")
("`p" "print()" ahf)
;;
))
```
The first two definitions:
```
("fo" "bar")
("`foo" "bar")
```
* with the config file on the left side, both are working.
* with the config file on the right side, only 1st working. 2nd is no longer working -- when I type "\`foo" and press space, nothing happens.
The difference is the following code are being added:
```
;; == adapted from http://ergoemacs.org/emacs/elisp_abbrev.html
;; the “ahf” stand for abbrev hook function.
(defun ahf ()
"Abbrev hook function, used for `define-abbrev'.
prevent inserting the char that triggered expansion."
(interactive)
t)
(put 'ahf 'no-self-insert t)
(setq abbrev-expand-function 'global-expand-abbrev)
;; (setq abbrev-expand-function 'abbrev--default-expand)
(defun global-expand-abbrev ()
"Function for value of `abbrev-expand-function'.
Expand the symbol before cursor.
Returns the abbrev symbol if there's a expansion, else nil."
(interactive)
(let ( $p1 $p2
$abrStr
$abrSymbol
)
(save-excursion
(forward-symbol -1)
(setq $p1 (point))
(forward-symbol 1)
(setq $p2 (point)))
(setq $abrStr (buffer-substring-no-properties $p1 $p2))
(setq $abrSymbol (abbrev-symbol $abrStr))
(if $abrSymbol
(progn
(abbrev-insert $abrSymbol $abrStr $p1 $p2 )
(global-abbrev-position-cursor $p1)
$abrSymbol)
nil)))
(defun global-abbrev-position-cursor (&optional @pos)
"Move cursor (from @POS) back to ▮ if exist, else put at end.
Return true if found, else false."
(interactive)
(let (($found-p (search-backward "▮" (if @pos @pos (max (point-min) (- (point) 100))) t )))
(when $found-p (delete-char 1))
$found-p
))
```
I've made the above code work for abbreviations without leading "\`", but now, when the two are put together, abbreviations with leading "\`", and the above code, things are not working any more.
I don't know how to fix it as I don't know elisp except copying from working code.
Somebody help please.
PS. while you're at it, I'm also getting the following warning for above code:
```
Argument `@pos' should appear (as @POS) in the doc string (emacs-lisp-checkdoc)
```
which I have no idea how to fix either.
**UPDATE:**
I've documented my changes at https://www.diffchecker.com/BjiDYyJP, and set it to never expire. But just in case anything happens, here are the code again:
Before
```
;; https://emacs.stackexchange.com/questions/66410/different-abbrevs-for-each-major-mode
(defvar my-abbrev-regexp
(rx (or bol (not (any "`" wordchar)))
(group (one-or-more (any "`" wordchar)))
(zero-or-more (not (any "`" wordchar))))
"Use as :regexp in abbrev tables to make \\=` a valid abbrev char.
If `words-include-escapes' is used then this regexp can fail.
Refer to the elisp comments in `abbrev--before-point' for details.")
(abbrev-table-put emacs-lisp-mode-abbrev-table :regexp my-abbrev-regexp)
(define-abbrev emacs-lisp-mode-abbrev-table "`foo" "bar")
(add-hook 'emacs-lisp-mode-hook #'abbrev-mode)
;; use it with a mode which is not loaded by default
(with-eval-after-load "sh-script"
(abbrev-table-put sh-mode-abbrev-table :regexp my-abbrev-regexp)
(define-abbrev sh-mode-abbrev-table "`foo" "bar")
(add-hook 'sh-mode-hook #'abbrev-mode))
(progn
;; python
(when (boundp 'python-mode-abbrev-table)
(clear-abbrev-table python-mode-abbrev-table))
(define-abbrev-table 'python-mode-abbrev-table
'(
("fo" "bar")
("p" "print(▮)" ahf)
("`foo" "bar")
("`p" "print()" ahf)
;;
))
(abbrev-table-put python-mode-abbrev-table :regexp my-abbrev-regexp)
(add-hook 'python-mode-hook #'abbrev-mode)
)
;; == adapted from http://ergoemacs.org/emacs/elisp_abbrev.html
;; the “ahf” stand for abbrev hook function.
(defun ahf ()
"Abbrev hook function, used for `define-abbrev'.
prevent inserting the char that triggered expansion."
(interactive)
t)
(put 'ahf 'no-self-insert t)
(setq abbrev-expand-function 'global-expand-abbrev)
;; (setq abbrev-expand-function 'abbrev--default-expand)
(defun global-expand-abbrev ()
"Function for value of `abbrev-expand-function'.
Expand the symbol before cursor.
Returns the abbrev symbol if there's a expansion, else nil."
(interactive)
(let ( $p1 $p2
$abrStr
$abrSymbol
)
(save-excursion
(forward-symbol -1)
(setq $p1 (point))
(forward-symbol 1)
(setq $p2 (point)))
(setq $abrStr (buffer-substring-no-properties $p1 $p2))
(setq $abrSymbol (abbrev-symbol $abrStr))
(if $abrSymbol
(progn
(abbrev-insert $abrSymbol $abrStr $p1 $p2 )
(global-abbrev-position-cursor $p1)
$abrSymbol)
nil)))
(defun global-abbrev-position-cursor (&optional @pos)
"Move cursor (from @POS) back to ▮ if exist, else put at end.
Return true if found, else false."
(interactive)
(let (($found-p (search-backward "▮" (if @pos @pos (max (point-min) (- (point) 100))) t )))
(when $found-p (delete-char 1))
$found-p
))
(setq save-abbrevs nil)
```
After
```
;; https://emacs.stackexchange.com/questions/66410/different-abbrevs-for-each-major-mode
(defvar my-abbrev-regexp
"\\(`[0-9A-Za-z._-]+\\)"
"Use as :regexp in abbrev tables to make \\=` a valid abbrev char.
If making \\=` optional (suffix it with ?), `re-search-backward' will
not be able to be that aggressive to match to it. Thus, making
the leading \\=` mandatory.
If `words-include-escapes' is used then this regexp can fail.
Refer to the elisp comments in `abbrev--before-point' for details.")
(abbrev-table-put emacs-lisp-mode-abbrev-table :regexp my-abbrev-regexp)
(define-abbrev emacs-lisp-mode-abbrev-table "`foo" "bar")
(add-hook 'emacs-lisp-mode-hook #'abbrev-mode)
;; use it with a mode which is not loaded by default
(with-eval-after-load "sh-script"
(abbrev-table-put sh-mode-abbrev-table :regexp my-abbrev-regexp)
(define-abbrev sh-mode-abbrev-table "`foo" "bar")
(add-hook 'sh-mode-hook #'abbrev-mode))
(progn
;; python
(when (boundp 'python-mode-abbrev-table)
(clear-abbrev-table python-mode-abbrev-table))
(define-abbrev-table 'python-mode-abbrev-table
'(
("`foo" "bar")
("`p" "print(▮)" ahf)
;;
))
(abbrev-table-put python-mode-abbrev-table :regexp my-abbrev-regexp)
(add-hook 'python-mode-hook #'abbrev-mode)
)
;; == adapted from http://ergoemacs.org/emacs/elisp_abbrev.html
;; the “ahf” stand for abbrev hook function.
(defun ahf ()
"Abbrev hook function, used for `define-abbrev'.
prevent inserting the char that triggered expansion."
(interactive)
t)
(put 'ahf 'no-self-insert t)
(setq abbrev-expand-function 'global-expand-abbrev)
;; (setq abbrev-expand-function 'abbrev--default-expand)
(defun global-expand-abbrev ()
"Function for value of `abbrev-expand-function'.
Expand the symbol before cursor.
Returns the abbrev symbol if there's a expansion, else nil."
(interactive)
(let ( $p1 $p2
$abrStr
$abrSymbol
)
(save-excursion
;; (forward-symbol -1)
(re-search-backward my-abbrev-regexp)
(setq $p1 (point))
(forward-symbol 1)
(setq $p2 (point)))
(setq $abrStr (buffer-substring-no-properties $p1 $p2))
(setq $abrSymbol (abbrev-symbol $abrStr))
(if $abrSymbol
(progn
(abbrev-insert $abrSymbol $abrStr $p1 $p2 )
(global-abbrev-position-cursor $p1)
$abrSymbol)
nil)))
(defun global-abbrev-position-cursor (&optional @pos)
"Move cursor (from @POS) back to ▮ if exist, else put at end.
Return true if found, else false."
(interactive)
(let (($found-p (search-backward "▮" (if @pos @pos (max (point-min) (- (point) 100))) t )))
(when $found-p (delete-char 1))
$found-p
))
(setq save-abbrevs nil)
```
NB my above solution is different from phils answer, which accepted as the correct answer, and it'll remain that way.
# Answer
The problem is probably the use of `forward-symbol` if ``` is not a symbol-constituent character (much as the problem in the prior question was that this character was not word-constituent).
A character is symbol-constituent if it has *either* word or symbol syntax (i.e. symbol syntax is for the additional chars that aren't already word-constituent).
As before you *could* give ``` word or symbol syntax, but it would have other side-effects, so I'm inclined to again resolve this by replacing syntax-based movement with a regexp-based movement.
Try this change to `global-expand-abbrev`:
```
;; (forward-symbol -1)
(re-search-backward my-abbrev-regexp)
(re-search-forward "^\\|.")
```
n.b. It ignores the subsequent call to `(forward-symbol 1)` only on the basis that I know you're only using ``` at the very start of the abbrev. If you were using it within an abbrev, then you'd need to account for that too.
> 2 votes
---
Tags: abbrev
--- |
thread-66553 | https://emacs.stackexchange.com/questions/66553 | Open the directory of currently opened file using the OS's file explorer | 2021-07-02T09:45:50.297 | # Question
Title: Open the directory of currently opened file using the OS's file explorer
This is essentially the same question as this one. But the accepted answer there opens Dired for me in Emacs 28 while previously it opened Caja. Could someone offer a fix? I tried commenting there but no one responded.
**Edit**: I adopted the accepted answering like this:
```
(defun caja (interactive)
(let ((process-connection-type nil))
(start-process "" nil "caja"
(url-file-directory buffer-file-name))))
```
# Answer
Probably a better alternative (for which I have defined a command in my dotfile) to the answer in the comments, because it does not open a process buffer, is:
```
(let ((process-connection-type nil))
(start-process ""
nil
"open"
(url-file-directory buffer-file-name))))
```
(I am not completely sure about "open" because I am on GNU/linux, but I found that solution for OS X in the answer here).
> 2 votes
---
Tags: files, directories
--- |
thread-61012 | https://emacs.stackexchange.com/questions/61012 | How can I paste a defvar into the minibuffer? | 2020-10-06T13:44:23.733 | # Question
Title: How can I paste a defvar into the minibuffer?
I've written a regular expression to transform Markdown links into Org Mode links and I've stored it into a variable.
```
(defvar markdown-link-to-org-regexp "s/\[\(.+\)\](\(.+\))/[[\2][\1]]")
```
I'm using Doom and Evil mode so next time I type `:` so I go to the minibuffer I'd like to bring that string into the minibuffer. Is there an easy way to do it?
# Answer
> 0 votes
Define an interactive function (aka command), which `insert`s this string. Then put this function on a key binding.
```
(defun my-insert-regex ()
(interactive)
(insert (format "%S" markdown-link-to-org-regexp)))
(define-key global-map (kbd "C-c i") #'my-insert-regex)
```
When doing `M-:` you then just have to press `C-c i` to insert this string at the prompt.
Note, that your regex is eventualy wrong and needs more escape characters. `re-builder` can help you construct this regex.
---
Second option:
This `M-:` promt normaly supports a history. You just need to type or paste it once, then you can retrieve former inputs with `<up>` and `<down>` keys. `C-r` searches backwards in the history. (`C-r` maybe has a different keybinding in Doom, Evil).
# Answer
> 0 votes
I don't understand your use case. You can copy text and paste (yank) text into the minibuffer, as @NickD pointed out in a comment. If the text isn't in the kill ring, but is actually stored in a file, then you don't need to invoke the minibuffer to run it. You can wrap it in a function and run it directly:
```
(defun my-regex-set ()
(interactive)
(defvar markdown-link-to-org-regexp "s/\[\(.+\)\](\(.+\))/[[\2][\1]]"))
```
With this function defined, you can call it with `M-x my-regex-set`, or you can bind it to a key combo.
---
Tags: org-mode, regular-expressions, query-replace, markdown
--- |
thread-66589 | https://emacs.stackexchange.com/questions/66589 | How to prevent `Text is read-only` when in minibuffer | 2021-07-04T14:27:28.640 | # Question
Title: How to prevent `Text is read-only` when in minibuffer
> It's about deleting minibuffer input without trying to also delete some of the minibuffer prompt (which is read-only).
When I do `C-x C-f` for `find-file` and delete all the way of the given path. Now, I keep seeing `Text is read-only` warning message in the minibuffer.
Is it possible to prevent this warning message and let minibuffer remain as `Find file:` text?
---
```
Find file: /home/alper/foder/ ;; Pressing C-h to remove all characters
Find file:
^ Here when I press C-h one last time
```
I am seeing `Text is read-only`.
# Answer
You can bind the following function `backward-delete-char-stop-at-read-only` to the key of your choice (maybe `C-h`, but that binding overrides the default help key-binding). The function is essentially `backward-delete-char` but stops before deleting read-only text. No indication is given if the function is ineffective (as you want it).
```
(defun backward-delete-char-stop-at-read-only (n &optional killflag)
"Do as `backward-delete-char' but stop at read-only text."
(interactive "p\nP")
(unless (or (get-text-property (point) 'read-only)
(eq (point) (point-min))
(get-text-property (1- (point)) 'read-only))
(setq n (min (- (point) (point-min)) n))
(setq n (- (point) (previous-single-property-change (point) 'read-only nil (- (point) n))))
(backward-delete-char n killflag)))
```
You can bind that function to `C-h` in the minibuffer by the following form:
```
(define-key minibuffer-local-map (kbd "C-h") #'backward-delete-char-stop-at-read-only)
```
> 2 votes
---
Tags: key-bindings, minibuffer
--- |
thread-66593 | https://emacs.stackexchange.com/questions/66593 | How to open a link to a folder/file in Finder, not Dired | 2021-07-05T09:56:00.343 | # Question
Title: How to open a link to a folder/file in Finder, not Dired
I used to be able to create links with `open-insert-link` pointing to folders or files. When I clicked on them, I would be redirected to Finder. Lately, they are shown within `Dired`. How to control this behaviour?
# Answer
> 0 votes
I think you mean `org-insert-link` (bound to key `C-c C-l` within an org-mode buffer). Which you would then enter the file name prepend with either `file:`, `file+emacs:` or `file+sys:`. Within an org-mode buffer `C-c C-o` (`org-open-at-point`) opens the link, or Mouse Click which results in `org-open-at-mouse`. In my testing only the `file+emacs:` link is opened within an emacs' `dired` buffer. What is the value of your link? For example:
`[[file:/users/Shared]]`
Also, take a look at `org-open-file` and `org-file-apps`.
Update: Check MacOS `System Preferences` -\> `Security and Privacy`:
* Under `General` tab it might be asking you to accept Emacs.
* Under `Privacy` tab check that `Automation` has *Emacs* listed with the various applications. I see `Finder`, `System Events.app`, `Safari`, `Mail.app`, etc.
---
Tags: org-mode, osx
--- |
thread-66392 | https://emacs.stackexchange.com/questions/66392 | Setting a default page margin for org latex export | 2021-06-19T20:50:28.687 | # Question
Title: Setting a default page margin for org latex export
So far, I have set `org-latex-packages-alist` to `'(("margin=2cm" "geometry"))`, but if the geometry-package is explicitly loaded in a document, I get a clash.
I can use `\newgeometry{margin=1cm}` in the document, but then latex produces errors on different configurations.
Is there a way to set the default margin (ideally through geometry) without clashing with existing configurations in documents?
# Answer
> 2 votes
Found a good solution for my case: The fullpage latex package.
> This package sets all 4 margins to be either 1 inch or 1.5 cm, and specifies the page style.
Which is exactly what I needed, while I can still load `geometry` within the document to override it.
So I added it to my `org-latex-packages-alist`:
```
(setq org-latex-packages-alist '(("" "fullpage") ("avoid-all" "widows-and-orphans") ("" "svg"))
```
# Answer
> 2 votes
Putting this in the document will set a margin regardless of whether the emacs configuration already loads `geometry`, but it is a bit clunky and not DRY.
```
#+LATEX_HEADER: \makeatletter \@ifpackageloaded{geometry}{\geometry{margin=2cm}}{\usepackage[margin=2cm]{geometry}} \makeatother
```
A solution that modifies my configuration rather than the document would be nicer.
---
Tags: org-mode, org-export, latex, margins
--- |
thread-39002 | https://emacs.stackexchange.com/questions/39002 | python "WORKON_HOME" not showing virtual environments in helm | 2018-02-22T04:22:30.853 | # Question
Title: python "WORKON_HOME" not showing virtual environments in helm
I've check to see my `WORKON_HOME` env is set to where I want it at `/home/user/anaconda3/envs` but in helm the only option i get is `..` if I select that option Emacs thinks my virtual environment is `anaconda3`.
If I use `M-x pyvenv-activate` I can navigate to my virtual environment and everything is fine. I just can't seem to get `pyvenv-workon` to point to my environment
For refence I'm using spacemacs with `(setenv "WORKON_HOME" "/home/user/anaconda3/envs")` in my `user-init` section and verified it is set with `M-x getenv WORKON_HOME`
# Answer
> 0 votes
I found myself with the same problem. The problem was that I started from a completely new miniconda3 install and although I had created a virtual environment, it was not initialized yet. So after installing a module `pvyenv-workon` worked as expected.
So, in your terminal, just `create` an environment, `activate` it and install a module e.g. `conda install wheel`
---
Tags: spacemacs, python, virtualenv
--- |
thread-66601 | https://emacs.stackexchange.com/questions/66601 | Which key prefix is left for user defined bindings? | 2021-07-06T10:48:13.413 | # Question
Title: Which key prefix is left for user defined bindings?
`C-h` `b` shows the key bindings. But I can not see, which prefix is left for my own functions. Is any prefix reserved for user bindings?
# Answer
As stated in the manual:
> A small number of keys are reserved for user-defined bindings, and should not be used by modes, so key bindings using those keys are safer in this regard. The reserved key sequences are those consisting of **`C-c` followed by a letter** (either upper or lower case), and function keys **`F5` through `F9` without modifiers**
In practice, **C-S-*letter*** is not officially reserved but I don't remember ever seeing a mode using it.
Additionally, some standard bindings on control-letter combinations tend not to be useful because you can use the arrow keys instead. This gives you `C-p`, `C-n`, `C-b` and `C-f`. Also `C-a` and `C-e` if you have `Home` and `End` keys. And all standard bindings only use the modifiers `Ctrl`, `Shift` and `Meta` (`C`, `S`, `M`) (or if there's any standard binding using another modifier, it duplicates another binding because those are the only three modifiers that everyone has), so if there's another modifier on your keyboard and it isn't reserved by your window manager, you can use that.
You can also free `Ctrl`+`H`, `Ctrl`+`I`, `Ctrl`+`J` and `Ctrl`+`[` by using `Tab`, `BackSpace`, `Return` and `Escape` instead, however those are trickier to use because the function keys are processed as the control-character combinations in Emacs. For example, `TAB` is the same thing as `C-i`, so if you want to give `Ctrl`+`I` its own binding, you have to re-route it to something that is not `C-i`. See How to bind C-i as different from TAB?
> 7 votes
# Answer
Just override any key that you don't use. Check what (if anything) is binded to a key with C-h k or install which-key-mode. You could also install something like worf or hydra make more room.
> 2 votes
# Answer
Not yet mentioned, I'd like to recommend re-binding one of `C--` or `M--`, since they both serve the same purpose. Then you have an entire key free to use.
> 2 votes
---
Tags: key-bindings, customization
--- |
thread-66606 | https://emacs.stackexchange.com/questions/66606 | How to make TRAMP aware of VPNs? | 2021-07-06T19:27:45.533 | # Question
Title: How to make TRAMP aware of VPNs?
For work I sometimes have to connect to our enterprise VPN.
When inside of the VPN, I can reach host `remote` per SSH, so the following TRAMP incantation works:
```
C-x C-f /ssh:remote:/path/filename RET
```
Whereby *remote*'s user and full hostname are specified in my .ssh config so TRAMP magically handles that.
When outside of the VPN, I can still reach host `remote` provided I hop through `entry`. So the following would work:
```
C-x C-f /ssh:entry|ssh:remote:/path/filename RET
```
My question is:
**Can I have TRAMP automatically convert "ssh:remote" to "ssh:entry|ssh:remote" *only* when I'm not connected to the VPN?** Ultimately I'd like existing connections to files to also be updated upon TRAMP cleanup connections. Currently disconnecting from the VPN is a real pain but I can't be connected all the time because the VPN lease resets every now and then.
# Answer
> 5 votes
The answer to any engineering question that starts with “Can I have…” is almost always yes. The real question is how much work it will take, and whether it is worth it.
You haven’t said what operating system you are using, which is absolutely vital information; everything else depends on it. So I will just assume that you made the most sane choice, and are using Linux.
NetworkManager knows whether you are connected and how, so you should be querying it for the status of the VPN. I can’t give you complete details about it, but if you just wanted to know if you are connected at all, you could use this function:
```
(defun nm-is-connected()
(equal 70 (dbus-get-property :system
"org.freedesktop.NetworkManager"
"/org/freedesktop/NetworkManager"
"org.freedesktop.NetworkManager"
"State")))
```
You can read the NetworkManager documentation for all the details about the dbus API it provides.
Emacs has a number of features that you can use in combination with Tramp so that you can type something short and Tramp will open a much longer filename. They are all briefly documented in the Tramp FAQ. Look for the question titled “How to shorten long file names when typing in TRAMP?”; it has no anchor so I cannot link to it directly.
So, pick a method for shortening your long and complex file name, and then combine it with the state of your VPN. Choose wisely: some of these methods are more amenable to this type of complex customization that others. For example, some of these methods only allow you to replace one string with another, while other methods may allow you to specify a function that will be called to generate the replacement. You will need to research each of these methods until you find the one which is most appropriate.
But the question remains; it may not be a good idea to do all of this work. If you can reach your jump host even while connected to the VPN, then it may just be easier to always use the jump host even when it isn’t necessary. It won’t be any less secure, and it will simplify your life.
In particular, this makes method #3 much more attractive. If you specify the ProxyJump configuration option in your ssh config file, then it will always be used for all ssh connections to the remote host:
```
Host remote
Hostname remote.example.com
ProxyJump entry.example.com
```
Then you can always just use the shorter form to connect using Tramp:
```
C-x C-f /ssh:remote:/path/filename RET
```
---
Tags: tramp, ssh
--- |
thread-66595 | https://emacs.stackexchange.com/questions/66595 | Using multiple keys in AUCTeX LaTeX-math-list | 2021-07-05T14:16:04.143 | # Question
Title: Using multiple keys in AUCTeX LaTeX-math-list
`LaTeX-math-mode` in AUCTeX is very convenient for shorcuts. For example, I define the following in my .emacs file:
```
(defconst LaTeX-math-list '(?f "frac")))
```
Then if I type ``f` the Emacs buffer displays `\frac{}` which saves a lot of typing.
My question is: is it possible to use multiple keys for shorcuts? I would like to type ``ba` so that the Emacs buffer displays
```
\begin{align}
\label{eq:}
\end{align}
```
Is this possible using `LaTeX-math-list`?
Similarly I would like to use ``bs` so that Emacs displays
```
\begin{equation}
\begin{split}
\end{split}
\label{eq:}
\end{equation}
```
# Answer
I think you're better off using `cdlatex` as a minor mode within AUCTeX. Form the README:
> **OVERVIEW**
>
> CDLaTeX is a minor mode supporting mainly mathematical and scientific text development with LaTeX. CDLaTeX is really about speed. AUCTeX (the major mode I recommend for editing LaTeX files) does have a hook based system for inserting environments and macros - but while this is useful and general, it is sometimes slow to use. CDLaTeX tries to be quick, with very few and easy to remember keys, and intelligent on-the-fly help.
Check the features from README and install it from MELPA if you want to give it a roll.
> 0 votes
---
Tags: auctex
--- |
thread-66616 | https://emacs.stackexchange.com/questions/66616 | How to create a structure instance out of a -pkg.el file? | 2021-07-08T03:24:58.653 | # Question
Title: How to create a structure instance out of a -pkg.el file?
Package `foo` description is stored inside a file `foo-VERSION/foo-pkg.el` with a cl-defstruct definition that complies to package.el `package-desc` structure type with a `package-desc-from-define` constructor. Something like this (for the package `ace-link`):
```
(define-package
"ace-link"
"20210121.923"
"Quickly follow links"
'((avy "0.4.0"))
:commit "e1b1c91b280d85fce2194fea861a9ae29e8b03dd"
:authors '(("Oleh Krehel" . "ohwoeowho@gmail.com"))
:maintainer '("Oleh Krehel" . "ohwoeowho@gmail.com")
:keywords '("convenience" "links" "avy")
:url "https://github.com/abo-abo/ace-link")
```
Inside package.el, the `define-package` function is not meant to be called. I'd like to dynamically extract the information from all the `-pkg.el` files and process them further.
What is the best way to create a structure instance of that?
To circumvent the package.el definition of `define-package` I temporary re-defined `define-package` to the constructor and then applied the code once manually like this:
```
(defalias 'define-package 'package-desc-from-define)
(setq instance-value (define-package
"ace-link"
"20210121.923"
"Quickly follow links"
'((avy "0.4.0"))
:commit "e1b1c91b280d85fce2194fea861a9ae29e8b03dd"
:authors '(("Oleh Krehel" . "ohwoeowho@gmail.com"))
:maintainer '("Oleh Krehel" . "ohwoeowho@gmail.com")
:keywords '("convenience" "links" "avy")
:url "https://github.com/abo-abo/ace-link"))
```
That works, but its I'd like to do the same thing just using the file name: being able to create an `instance-value` but processing the content of the `-pkg.el` file.
So I wrote another alias that creates a global variable instance `my-struct-instance`:
```
(defun my-def (n v &optional s r &rest pl)
"Replaces package-desc-from-define."
(setq my-struct-instance (apply 'package-desc-from-define n v s r pl)))
(defalias 'define-package 'my-def)
```
Then I load the file with something like:
```
(load "~/.emacs.d/elpa/ace-link-xxx/ace-link-pkg.el")
```
And that creates an instance of the structure inside the variable `my-struct-instance`.
I get the feeling it should be easy and I'm missing something in the handling of *cl-defstruct*. Is there a better, more obvious way to extract the structure information from these `-pkg.el` files?
# Answer
> 1 votes
`(package-load-descriptor DIRECTORY)` will read the `*-pkg.el` file in the given directory, create a new `package-desc` structure object, add it to `package-alist` and return the object.
That seems to cover what you need, with the possible exception of it modifying `package-alist` (which you may or may not want to happen). It's actually the call to `package-process-define-package` which does this. If you wanted to avoid that modification, you could use:
```
(let (package-alist)
(package-load-descriptor DIRECTORY))
```
---
Tags: package, cl-lib, defstruct
--- |
thread-66599 | https://emacs.stackexchange.com/questions/66599 | Hide / fold settings above an image | 2021-07-06T06:30:49.223 | # Question
Title: Hide / fold settings above an image
Is there way to "fold" settings, similar to how I can fold drawers? I have these properties associated with an image:
```
#+NAME: fig:figure name
#+CAPTION: figure name
#+ATTR_ORG: :width 200
#+ATTR_LATEX: :width 2.0in
#+ATTR_HTML: :width 200
[[file:homepage.org_imgs/20210706_002617_ok9v4c.png]]
```
I'd like it to be foldable / unfoldable with TAB similar to a drawer. However, if I actually create a drawer, the properties no longer take effect because the :END: acts as a space before the image link.
For example this is foldable (like I want) but the settings no longer associate with the image:
```
:IMAGE_INFO:
#+NAME: fig:figure name
#+CAPTION: figure name
#+ATTR_ORG: :width 200
#+ATTR_LATEX: :width 2.0in
#+ATTR_HTML: :width 200
:END:
[[file:homepage.org_imgs/20210706_002617_ok9v4c.png]]
```
# Answer
> 0 votes
Expanding on lessons learned from John Kitchin's answer, this will "unpack" drawers both before rendering on the screen and exporting:
```
(defun unpack-image-drawers (&rest r)
"Replace drawers named \"IMAGE_INFO\" with their contents."
(let* ((drawer-name "IMAGE_INFO")
(save-string "#+ATTR_SAVE: true\n")
(image-drawers (reverse (org-element-map (org-element-parse-buffer)
'drawer
(lambda (el)
(when (string= drawer-name (org-element-property :drawer-name el))
el))))))
(cl-loop for drawer in image-drawers do
(setf (buffer-substring (org-element-property :begin drawer)
(- (org-element-property :end drawer) 1))
(concat save-string
(buffer-substring (org-element-property :contents-begin drawer)
(- (org-element-property :contents-end drawer) 1)))))))
(defun repack-image-drawers (&rest r)
"Restore image drawers replaced using `unpack-image-drawers'."
(let* ((drawer-name "IMAGE_INFO")
(save-string "#+ATTR_SAVE: true\n")
(image-paragraphs (reverse (org-element-map (org-element-parse-buffer)
'paragraph
(lambda (el)
(when (string= "true" (nth 0 (org-element-property :attr_save el)))
el))))))
(cl-loop for paragraph in image-paragraphs do
(setf (buffer-substring (org-element-property :begin paragraph)
(- (org-element-property :contents-begin paragraph) 1))
(concat ":" drawer-name ":\n"
(buffer-substring (+ (length save-string) (org-element-property :begin paragraph))
(- (org-element-property :contents-begin paragraph) 1))
"\n:END:")))))
(defun apply-with-image-drawers-unpacked (f &rest r)
"Replace drawers named \"IMAGE_INFO\" with their contents, run the function,
finally restore the drawers as they were. Also collapses all drawers before returning."
(unpack-image-drawers)
(apply f r)
(repack-image-drawers)
(org-hide-drawer-all))
(advice-add #'org-display-inline-images :around #'apply-with-image-drawers-unpacked)
(add-hook 'org-export-before-processing-hook 'unpack-image-drawers)
```
# Answer
> 2 votes
I would stick with your image info drawers, and then use a preprocessing hook to remove the lines that cause a problem. Here is one example that just replaces the IMAGE\_INFO drawers with their contents. You can collapse them in your org file, and export as usual when you use the hook at the end.
```
(defun preprocess-rm-image-info-drawers (_)
(let ((img-drws (reverse (org-element-map (org-element-parse-buffer)
'drawer (lambda (drw)
(when
(string= "IMAGE_INFO" (org-element-property :drawer-name drw)) drw))))))
(cl-loop for drw in img-drws do
(setf (buffer-substring (org-element-property :begin drw) (org-element-property :end drw))
(buffer-substring (org-element-property :contents-begin drw) (org-element-property :contents-end drw))))))
(add-hook 'org-export-before-processing-hook 'preprocess-rm-image-info-drawers)
```
---
Tags: org-mode, code-folding
--- |
thread-65141 | https://emacs.stackexchange.com/questions/65141 | How to fix indentation for `dash.el` threading macros (e.g. `->>`) | 2021-06-03T02:31:22.990 | # Question
Title: How to fix indentation for `dash.el` threading macros (e.g. `->>`)
As I write more Elisp, I find myself using the threading macro increasingly often. However, since it is an imported, not a built-in one, the indentation is not like what I want it to be.
For example, I want the auto-indentation to be, not like this:
```
(->> '(1 2 3 4)
(mapcar #'1+)
(seq-filter #'evenp)
(reduce #'+))
```
but like this:
```
(->> '(1 2 3 4)
(mapcar #'1+)
(seq-filter #'evenp)
(reduce #'+))
```
...so that the inner expressions are aligned together vertically.
How can I specially designate the indent level, based on the expression's `car`?
# Answer
This is what I do:
```
(with-eval-after-load 'dash
(function-put '-> 'lisp-indent-function nil)
(function-put '->> 'lisp-indent-function nil))
```
Dash maintainers refused to keep `->`/`->>` indentation in sync with other Lisps. See https://github.com/magnars/dash.el/pull/375#issuecomment-817947545
See `(info "(elisp) Indenting Macros")` for more details.
> 3 votes
# Answer
The Dash project has gone back and forth on the indentation of these Clojure-inspired threading macros a couple of times in the past:
And, most recently:
This pull request (re)introduced the indentation that OP describes as undesirable for `->` and `->>` on 2021-03-08. However, this controversial change was never included as part of an official Dash release, and was present only for 4 months in the development version that can be installed from GNU-devel ELPA or MELPA.
The release of Dash 2.19.0 on 2021-07-08 restored Clojure-like indentation for the macros `->`, `->>`, and `-->` for both development and non-development versions of the Dash package:
```
(->> '(1 2 3 4)
(mapcar #'1+)
(seq-filter #'cl-evenp)
(reduce #'+))
```
Once upgraded to this version, no further steps are required to achieve the desirable indentation, but see Ivan's answer for a general mechanism to customise Elisp indentation.
> 2 votes
---
Tags: indentation, dash.el
--- |
thread-66625 | https://emacs.stackexchange.com/questions/66625 | Eval src block only for certain system? | 2021-07-09T00:23:30.630 | # Question
Title: Eval src block only for certain system?
Is there way to disable/enable source block on a certain system type?
I've tried this, it didn't work:
```
#+begin_src shell :eval (eq system-type 'gnu/linux)
echo "On gnu/linux"
#+begin_src
```
# Answer
> 2 votes
Try
```
#+begin_src shell :eval (if (eq system-type 'gnu/linux) "yes" "no")
echo "On gnu/linux"
#+end_src
```
The expression *is* evaluated, but the value has to be one of the values that the `:eval` header expects.
---
Tags: org-mode
--- |
thread-66624 | https://emacs.stackexchange.com/questions/66624 | Package needs to be reinstalled every time spacemacs is started | 2021-07-08T21:05:57.080 | # Question
Title: Package needs to be reinstalled every time spacemacs is started
I install a theme using M-x package-install \[return\] doom-themes. And it installs the themes and I use the themes. However, when I close spacemacs and start it again, this package is gone and needs to be reinstalled again. How can I make it so that the doom-themes package is installed between spacemacs sessions?
# Answer
> 1 votes
Search for `dotspacemacs-additional-packages` and put the package name inside that list. That way Spacemacs would know not to delete it on startup.
---
Tags: spacemacs, package
--- |
thread-61278 | https://emacs.stackexchange.com/questions/61278 | Tangle Org file containing #+INCLUDE directives and multiple tangle targets | 2020-10-18T00:40:31.123 | # Question
Title: Tangle Org file containing #+INCLUDE directives and multiple tangle targets
## Context
I'm using `org-babel-tangle` to generate my configuration from an Org file `config.org`. Recently, I did some clean-up by
1. dispatching `config.org` to multiple Org files `config/*.org`;
2. replace the content of `config.org` with multiple `#+INCLUDE: config/*.org` directives.
To illustrate a bit, the directory tree is as follows:
```
config/
|______ A.org
|______ B.org
|______ C.org
|
config.org
```
where
```
## config.org
#+INCLUDE: config/A.org
#+INCLUDE: config/B.org
#+INCLUDE: config/C.org
...
```
and
```
## [ABC].org
#+BEGIN_SRC emacs-lisp :tangle target1.el
;; elisp code
#+END_SRC
#+BEGIN_SRC emacs-lisp :tangle target2.el
;; elisp code
#+END_SRC
...
```
## Issue & attempt
However, I ran into the issue that `org-babel-tangle` doesn't handle `#+INCLUDE` directives. So, I follow the idea of this post which consists of
1. exporting `config.org` to an Org file `config-export.org` with `org-export-to-file`;
2. `org-babel-tangle` the exported Org file `config-export.org` to tangle targets.
This approach does replace the multiple `#+INCLUDE` directives of `config.org` by the content of `config/*.org`, but all tangle options are **erased**. Namely, the exported `config-export.org` looks like this (all emacs-lisp tangle target filename are lost):
```
## config-export.org
#+BEGIN_SRC emacs-lisp
;; elisp code for target1.el
#+END_SRC
#+BEGIN_SRC emacs-lisp
;; elisp code for target2.el
#+END_SRC
...
```
## Question
How to `org-babel-tangle` an Org file with `#+INCLUDE` directives as it is intended?
(*i.e.* (1) include all Org files (preserving `:tangle target.el`), then (2) `org-babel-tangle` the whole Org file.)
## Related question
A similar question has been raised in the Org mode mailing-list.
# Answer
> 3 votes
I don't know how to do this without changing the code (it might be possible with `org-babel-pre-tangle-hook` but it did not seem at all simple, so I didn't try that). But as soon as you accept code changes, it does not seem too bad.
The simplest possible way I could think of was to emulate in `org-babel-tangle` what `org-export-as` is doing WRT included files. A simple test (similar to what you describe above) succeeded easily (but see caveats at the end), so if you want to try replicating the change, I include the patch below.
The patch itself would look big, but that's only because I'm taking all of the code of `org-babel-tangle` and enclosing it in another layer, which changes the indentation and that's most of the change. Ignoring whitespace changes, the "real" change is much smaller: I got the patch below with `git diff -b` in order to ignore whitespace. You can then see that it is very small: we just enclose almost the whole body of `org-babel-tangle` in `(org-export-with-buffer-copy ...)`, so that we can do transformations to the text in a temp buffer and not disturb the original and then add one more transformation to process the `#+INCLUDE:` directives, before the resulting buffer is then tangled:
```
diff --git a/lisp/ob-tangle.el b/lisp/ob-tangle.el
index b74b3fa0c..5e6eebf63 100644
--- a/lisp/ob-tangle.el
+++ b/lisp/ob-tangle.el
@@ -206,6 +206,9 @@ export file for all source blocks. Optional argument LANG-RE can
be used to limit the exported source code blocks by languages
matching a regular expression."
(interactive "P")
+ (org-export-with-buffer-copy
+ (org-export-expand-include-keyword)
+
(run-hooks 'org-babel-pre-tangle-hook)
;; Possibly Restrict the buffer to the current code block
(save-restriction
@@ -306,7 +309,7 @@ matching a regular expression."
(mapc (lambda (pair)
(when (cdr pair) (set-file-modes (car pair) (cdr pair))))
path-collector)
- (mapcar #'car path-collector)))))
+ (mapcar #'car path-collector))))))
(defun org-babel-tangle-clean ()
"Remove comments inserted by `org-babel-tangle'.
```
That produces the expected results WRT the tangled files I think, but you should check to make sure that it does the right thing in your case: my tests are toy tests so they might miss tricky situations that might arise in your "real world" tests.
There is one problem which I don't understand yet: the `config.org` buffer itself is changed in my tests, despite the `org-export-with-copy-buffer`, so at the end of the tangle I have to undo the change with `C-x u` and save it. That's probably because I don't understand what `org-export-with-copy-buffer` is really doing, but I have not checked that code yet.
OTOH, if that is resolved and the tests all pass, we can propose this as an enhancement to the Org mode mailing list and put that problem (from 2010!) behind us.
EDIT: I don't see any problem with `org-babel-tangle-file` \- it calls `org-babel-tangle` underneath, so in theory it should do the (almost) right thing and testing it with a simple example works fine for me. Maybe you can post a (small) example that gives you problems by editing your question?
I'm also testing with the following workaround to get around the issue of `config.org` getting changed:
```
#+begin_src emacs-lisp
(copy-file "./config.org.orig" "./config.org")
(org-babel-tangle-file "./config.org")
(delete-file "./config.org")
#+end_src
```
Ugly, but it seems to work (except that I have to answer the "changed on disk" question).
# Answer
> 2 votes
## Method 1
Manual method using default org-mode keybindings
### Setup
1. Add `Org` to `Org Babel Load Languages` configuration and then apply and save new configuration.
2. Add `#+EXPORT_FILE_NAME:` keyword near top of `config.org`.
e.g.
```
#+EXPORT_FILE_NAME: temp.org
```
3. Add `#+PROPERTY: header-args:org :results drawer replace` keyword near top of `config.org`.
e.g.
```
#+PROPERTY: header-args:org :results drawer replace
```
4. Update `#+INCLUDE:` to include the `src org` syntax.
e.g.
```
#+INCLUDE: config/A.org src org
#+INCLUDE: config/B.org src org
#+INCLUDE: config/C.org src org
```
5. Add `:eval never` header to each of `SRC` blocks that will be tangled inside the included `config/*.org` files.
e.g.
```
#+BEGIN_SRC elisp :tangle tangle1.el :eval never
;; Code goes here
#+END_SRC
```
### Manual Execution Steps
1. Open `config.org` in emacs.
The `config.org` file should look similar to the example below:
```
#+EXPORT_FILE_NAME: temp.org
#+PROPERTY: header-args:org :results drawer replace
#+INCLUDE: config/A.org src org
#+INCLUDE: config/B.org src org
#+INCLUDE: config/C.org src org
```
2. Export `config.org` using `C-c` `C-e` `O` `v` key chord. This will create a new `temp.org` file and open in emacs.
The `temp.org` file should look similar to the example below:
```
#+export_file_name: temp.org
#+property: header-args:org :results drawer replace
#+begin_src org
,#+BEGIN_SRC elisp :tangle tangle1.el :eval never
;; Code goes here
,#+END_SRC
#+end_src
#+begin_src org
,#+BEGIN_SRC elisp :tangle tangle2.el :eval never
;; Code goes here
,#+END_SRC
#+end_src
#+begin_src org
,#+BEGIN_SRC elisp :tangle tangle3.el :eval never
;; Code goes here
,#+END_SRC
#+end_src
```
3. Execute all the blocks in the `temp.org` using `C-c` `C-v` `C-b` key chord.
The `temp.org` file should look similar to the example below:
```
#+export_file_name: temp.org
#+property: header-args:org :results drawer replace
#+begin_src org
,#+BEGIN_SRC elisp :tangle tangle1.el :eval never
;; Code goes here
,#+END_SRC
#+end_src
#+RESULTS:
:results:
#+BEGIN_SRC elisp :tangle tangle1.el :eval never
;; Code goes here
#+END_SRC
:end:
#+begin_src org
,#+BEGIN_SRC elisp :tangle tangle2.el :eval never
;; Code goes here
,#+END_SRC
#+end_src
#+RESULTS:
:results:
#+BEGIN_SRC elisp :tangle tangle2.el :eval never
;; Code goes here
#+END_SRC
:end:
#+begin_src org
,#+BEGIN_SRC elisp :tangle tangle3.el :eval never
;; Code goes here
,#+END_SRC
#+end_src
#+RESULTS:
:results:
#+BEGIN_SRC elisp :tangle tangle3.el :eval never
;; Code goes here
#+END_SRC
:end:
```
4. Execute the tangle in the `temp.org` using `C-c` `C-v` `C-t` key chord. This will tangle the imported `SRC` blocks from the `config/*.org` files.
This will create the tangled files similar to the files listing below:
```
config.org
tangle1.el
tangle2.el
tangle3.el
temp.org
./config:
A.org
B.org
C.org
```
---
> **This answer was tested using:**
> **emacs version:** GNU Emacs 27.1
> **org-mode version:** 9.3.7
# Answer
> 1 votes
I am not sure if it still helps and if it is exactly what you need... I am using something like within spacemacs:
```
;;-----------------------------------------------------------------------
(message "--- START : filemanage ----")
(let ((srcuf (concat dotspacemacs-directory "user_filemanage.org"))
(uf (concat dotspacemacs-directory "user-filemanage.el"))
)
(when (file-newer-than-file-p srcuf uf)
(message "--- File is adjusted : filemanage ----")
(call-process
(concat invocation-directory invocation-name)
nil nil t
"-q" "--batch" "--eval" "(require 'ob-tangle)"
"--eval" (format "(org-babel-tangle-file \"%s\")" srcuf)))
)
(message "--- DONE : filemanage ----")
;;-----------------------------------------------------------------------
(message "--- START : helm ----")
(let ((srcuh (concat dotspacemacs-directory "user_helm.org"))
(uh (concat dotspacemacs-directory "user-helm.el"))
)
(when (file-newer-than-file-p srcuh uh)
(message "--- File is adjusted : helm ----")
(call-process
(concat invocation-directory invocation-name)
nil nil t
"-q" "--batch" "--eval" "(require 'ob-tangle)"
"--eval" (format "(org-babel-tangle-file \"%s\")" srcuh)))
)
```
And for loading within the config section
```
(let ((uf (concat dotspacemacs-directory "user-filemanage.el")))
(load-file uf))
(let ((uh (concat dotspacemacs-directory "user-helm.el")))
(load-file uh))
```
and in `user_filemanage.el` I have something like
```
*** dired-open
#+BEGIN_SRC emacs-lisp :tangle user-filemanage.el
;; dired open.............................................................................
(require 'dired-open)
#+END_SRC
```
---
Tags: org-mode, org-export, org-babel
--- |
thread-66629 | https://emacs.stackexchange.com/questions/66629 | How to make `C-x 9` the same as `C-x 8 "` | 2021-07-09T09:27:39.257 | # Question
Title: How to make `C-x 9` the same as `C-x 8 "`
For typing german text with an english keyboard layout the binding `C-x 8 "` is very valuable. After typing it I can insert umlauts easily. Here is what which-key shows me after typing `C-x 8 "`
I use this so often that I would like to use `C-x 9` as an "alias" for this binding.
Unfortunatelly I can't figure out how. `C-x 8 "` is only a partial binding if I see it correctly. `describe-key` `C-x 8 "` doesn't show me anything and just waits for further input. It also doesn't seem to be
Ideally I would like something like
```
(set-global-key-alias-or-so "C-x 9" "C-x 8 \"")
```
or
```
(global-set-key (kbd "C-x 9") 'whatever-is-behind-C-x-8-\")
```
# Answer
I can think of a couple of ways to do this. The main practical difference is whether you see `C-x 8 "` or `C-x 9` in the minibuffer while waiting to read the next key.
Option 1 is to simulate the user actually typing `C-x``8``"`:
```
(global-set-key (kbd "C-x 9") #'my-ctl-x-8-double-quote)
(defun my-ctl-x-8-double-quote ()
"Simulate typing: C-x 8 \""
(interactive)
(dolist (event (nreverse (list ?\C-x ?8 ?\")))
(push (cons t event) unread-command-events)))
```
Option 2 is to bind `C-x``9` to the same keymap used by `C-x``8``"` (which is defined in `key-translation-map`):
```
(define-key key-translation-map (kbd "C-x 9")
(lookup-key key-translation-map (kbd "C-x 8 \"")))
```
Note that option 2 requires you to figure out where that prefix keymap lives (`C-h``b` helps with that), while option 1 can be used even if you don't know that information.
See also: `C-h``i``g` `(elisp)Translation Keymaps`
> 8 votes
---
Tags: key-bindings, keymap
--- |
thread-66579 | https://emacs.stackexchange.com/questions/66579 | How to dynamically replace certain text, by evaluating a function on change in current buffer | 2021-07-03T21:02:47.797 | # Question
Title: How to dynamically replace certain text, by evaluating a function on change in current buffer
I am trying to figure out how to use `window-change-functions` refer here for official documentation to be able to run a function to replace certain text within the current buffer at every change of the buffer.
I have the below code, but it does not seem to work:
```
(defun clean-single-digits (window)
(with-selected-window window
(save-excursion
(goto-char (point-min))
(while (re-search-forward "I-1" nil t)
(replace-match "I-01"))))
(add-hook 'window-change-functions #'clean-single-digits)
```
Much appreciate any help on this, I didn't find any answers online and think this is a useful question. The best example I found was this, which was on a related function.
I was able to get the below working correctly, so the issue is the hook / window-change-function:
```
(save-excursion
(goto-char (point-min))
(while (re-search-forward "I-1" nil t)
(replace-match "I-01")))
```
# Answer
> 2 votes
As discussed in the comments to my question, I was a bit confused when writing the question, but will keep the original text in case similarly inexperienced people approach it from the same way.
To answer the main question "How to dynamically replace certain text, by evaluating a function on change in current buffer", below is an example of how to do it.
In this example, we want to rename all instances of "01" to "1" when our mode is active. The function `clean-single-digits` achieves this. Note how we use `save-excursion` to save the current point, i.e. this function replaces all "01" to "1" and returns point to the point it was when the function was called.
The second expression, where we add `clean-single-digits` to `after-change-functions` (refer here to the official documentation) ensures this function is called every time Emacs modifies a buffer.
Now you can see why we have `(when (eq major-mode 'my-mode)...` in our main function - we want our function to only apply in the relevant mode (my-mode in this case) and not for ALL changes in Emacs buffers.
Finally note how our function takes three parameters, which we don't use. Functions that we add to hooks need to have the same number of parameters as per the definition of these hooks - its an important point to read in the documentation of each hook function / variable. You can see references to this detail in the comments to the question.
```
(defun clean-single-digits (change-beg change-end prev-len)
(when (eq major-mode 'my-mode)
(save-excursion
(goto-char (point-min))
(while (re-search-forward "01" nil t)
(replace-match "1")))))
(add-hook 'after-change-functions 'clean-single-digits)
```
Finally, the window-change-functions referred in the question relate to a different set of hooks that were not appropriate (at least for my approach) to this question. For example `window-buffer-change-functions` runs on when the actual buffer is changed to something else, not to changes within a buffer.
---
Tags: window, frames, hooks, replace
--- |
thread-66637 | https://emacs.stackexchange.com/questions/66637 | How can I install and enable this theme? | 2021-07-09T18:15:56.770 | # Question
Title: How can I install and enable this theme?
I have been using this solarized theme for many years now: https://github.com/sellout/emacs-color-theme-solarized. This theme used to be available in the MELPA repos, but it is no longer available there.
I always run emacs in my terminal with `emacs -nw` and I am currently using `GNU Emacs 27.2`.
My problem is that I am currently moving to a fresh linux install, and want to continue to use this theme. What is the "correct" way to install this package manually?
# Answer
(Assuming you want to install the theme in `~/.emacs.d/lisp/emacs-color-theme-solarized`.)
The first step would be to clone the repository:
```
$ cd ~/.emacs.d/lisp
$ git clone 'https://github.com/sellout/emacs-color-theme-solarized.git'
```
Then to add this path to `custom-theme-load-path` by modifying your `init.el` with something along the lines of:
```
(add-to-list 'custom-theme-load-path
(file-name-as-directory
(expand-file-name "~/.emacs.d/lisp/emacs-color-theme-solarized")))
```
And then it’s business as usual:
```
(load-theme 'solarized t)
```
> 1 votes
---
Tags: package, themes
--- |
thread-66643 | https://emacs.stackexchange.com/questions/66643 | How to automatically downscale an image to window width in org-mode? | 2021-07-10T10:52:54.073 | # Question
Title: How to automatically downscale an image to window width in org-mode?
I use `org-toggle-inline-images` to directly view linked images in org-mode files. Unfortunately, depending on resolution, format and size, images often are too wide for the window (especially in portrait mode) and thus only partly visible.
Is there a way to automatically downscale an image to fit the window width?
# Answer
> 2 votes
Try setting `org-image-actual-width` to the width you would like it, usually a number like 600 is a reasonable choice. I don’t know of an way way to make it dynamic so it adjusts to the actual window width.
To get something more dynamic that only resizes things bigger than the window width, you need to advise a function.
Here is one way to think about it. We try to get the width of the image, and when it is bigger than the current window we use the actual window size in the preview. When it is smaller than the window, we use the actual size. And if you use attr\_org to set the image size, we use that instead. We use an :around advice to basically replace the built in call to org--create-inline-image call. It is only lightly tested with file links.
```
(defun get-image-width (fname)
"Returns the min of image width and window width, unless :width
is defined in an attr_org line."
(let* ((link (save-match-data (org-element-context)))
(paragraph (let ((e link))
(while (and (setq e (org-element-property
:parent e))
(not (eq (org-element-type e)
'paragraph))))
e))
(attr_org (org-element-property :attr_org paragraph))
(pwidth (plist-get
(org-export-read-attribute :attr_org paragraph) :width))
(width (when pwidth (string-to-number pwidth)))
open
img-buf)
(unless width
(setq open (find-buffer-visiting fname)
img-buf (or open (find-file-noselect fname))
width (min (window-width nil :pixels)
(car (image-size (with-current-buffer img-buf (image-get-display-property)) :pixels))))
(unless open (kill-buffer img-buf)))
width))
(defun around-image-display (orig-fun file width)
(apply orig-fun (list file (get-image-width file))))
(advice-add 'org--create-inline-image :around #'around-image-display)
```
---
Tags: org-mode, window, images
--- |
thread-66644 | https://emacs.stackexchange.com/questions/66644 | How does company mode work? | 2021-07-10T11:07:11.650 | # Question
Title: How does company mode work?
I am trying to set up a quasi-IDE experience on Emacs for C/++, and I installed the `company` package. However, it seems it doesn't work. For what I undersood, `company` by itself is only the front-end. Freshly installed, it only does basic completion (i.e., the words you alredy typed), and it doesn't show completions without a back-end a, for example, `irony`. Is it right?
I have Emacs 26, and I have already installed `clang` (not `libclang`), but it seems it doesn't help. Can someone of you explain how does the company autocompletion works?
# Answer
> 2 votes
Look into lsp or eglot. They provide completion candidates for company.
Personally, I used eglot now with vertico completion and it "just works" since i plumbs iself into completion-at-point functions.
https://github.com/joaotavora/eglot
---
Tags: completion, company-mode, ide
--- |
thread-66646 | https://emacs.stackexchange.com/questions/66646 | How to disable `flycheck` while merging Git conflicts | 2021-07-10T15:18:04.410 | # Question
Title: How to disable `flycheck` while merging Git conflicts
I am using following solution for merge Git conflicts in Emacs, which is based on `smerge`. During merging `smerge-mode` creates `<<<<<<< HEAD` , `||||||||| parent` lines for conflict detection.
But flycheck catches them as `flycheck-error` and changes their colors, hence they may become unreadable.
Would it be possible to prevent `flycheck-mode` to be disabled during merging or just can it ignore specific patterns to detected as `flycheck-error' like:` \<\<\<\<\<\<\< HEAD\`.
# Answer
You can use `M-x flycheck-mode` to turn off flycheck in current buffer. Or alternatively, you can disable it for specific hooks (in this case `smerge-mode`):
```
(add-hook 'smerge-mode-hook (lambda () (flycheck-mode -1)))
```
**Note: I haven't tested this code yet. So, I don't know if this works or not.*
> 1 votes
---
Tags: flycheck, colors, smerge
--- |
thread-66648 | https://emacs.stackexchange.com/questions/66648 | How do I cut and paste raw bytes in emacs? | 2021-07-10T19:28:21.103 | # Question
Title: How do I cut and paste raw bytes in emacs?
Here are some raw bytes shown in emacs that are printing correctly:
I can see that those are the actual bytes with `od -bc` on the command line:
When I use control-space to mark, control-w to cut, and control-y to yank, it drops something different:
`od -bc` confirms it is different:
How do I faithfully cut and paste the first thing, which has the raw bytes I want?
I'm using Emacs 22.1.1 on OS X.
(This is a place name, Łódź.)
**EDIT**: I did not find how to edit raw bytes in general. However, for my bytes, it was sufficient to edit the file in the "cp1250" encoding. I did this with:
```
C-x C-m c cp1250-unix RET C-x C-f <filename>
```
described here. (The "unix" part means to leave line endings alone.)
# Answer
You can use `M-x` `find-file-literally` to:
> Visit file FILENAME with no conversion of any kind. Format conversion and character code conversion are both disabled, and multibyte characters are disabled in the resulting buffer.
For more details (including information about "format conversion" and "character code conversion"), see the description of this command in `C-h``i``g` `(elisp)Visiting Functions`.
> 1 votes
---
Tags: copy-paste
--- |
thread-66659 | https://emacs.stackexchange.com/questions/66659 | What is this gap, and how do I remove it? | 2021-07-11T18:55:40.517 | # Question
Title: What is this gap, and how do I remove it?
I'm changing the appearance of the `tab-bar`, and I have the following:
There's a gap present between tabs and between the left edge of the frame, despite setting the face attribute `:box` to `nil` on `tab-bar-tab` and `tab-bar`. What is this gap, what face does it belong to, and how can I remove it?
Edit: changing the backrgound color of the `tab-bar` face to match the background color of the `tab-bar-tab` face 'fixes' the issue in that I can no longer see the gap, but I'd still like to know how to fully remove the gap.
# Answer
> 3 votes
It's a separator. It separates tabs as well as the first tab from the window edge. You can either set `tab-bar-separator` to an empty string, thus losing the separator between tabs too. Or just remove the first separator with
```
(advice-add 'tab-bar-format-tabs :around
(lambda (orig-fun)
(cdr (funcall orig-fun))))
```
---
Tags: faces, tabbar
--- |
thread-66658 | https://emacs.stackexchange.com/questions/66658 | Filter Columnview Dblock on Properties or Tags | 2021-07-11T15:13:03.450 | # Question
Title: Filter Columnview Dblock on Properties or Tags
I have been unable to get the `:match` feature of columnview dblocks to work. I need it because I want to filter headlines by tags that I used to identify Scrum stories in a particular sprint. I have basically tried every conceivable version of `:match` such as `:match "Sprint4"`, `:match "Sprint4"`, `:match ":Sprint4:"`, `:match "TAG=\":Sprint4:\""`, and `match: "TAG=\"Sprint4\""`. Basically, nothing works.
Any ideas on how to get this to work? I am running Org Mode 9.4.5 on Mac OS X Emacs 27.1.
Here is the offending Org mode text
```
* Scrum Summary
#+BEGIN: columnview :hlines 3 :id "47B8AC9D-2556-4F6E-AAE1-775731314596" :indent t :maxlevel 4 :match "Sprint4"
#+TBLNAME: aTable
| Status | EPICID | STORYID | TASKID | Task | OWNER | Effort | CLOSED | Sprints |
|--------+--------+---------+---------+--------------------------+-------+--------+------------------------+-----------|
| | | | | Backlog | | 45 | | |
|--------+--------+---------+---------+--------------------------+-------+--------+------------------------+-----------|
| | Epic1 | | | \_ Epic on Build It ALL | | 27 | | |
|--------+--------+---------+---------+--------------------------+-------+--------+------------------------+-----------|
| TODO | Epic1 | Story1 | | \_ Story 1 | | 12 | | :Sprint4: |
| TODO | Epic1 | Story1 | Task1.1 | \_ Task 1.1 | pablo | 7 | | :Sprint4: |
| TODO | Epic1 | Story1 | Task1.2 | \_ Task 1.2 | john | 2 | | :Sprint4: |
| TODO | Epic1 | Story1 | Task1.3 | \_ Task 1.3 | pablo | 3 | | :Sprint4: |
|--------+--------+---------+---------+--------------------------+-------+--------+------------------------+-----------|
| TODO | Epic1 | Story2 | | \_ Story 2 | | 15 | | :Sprint3: |
| DONE | Epic1 | Story2 | Task2.1 | \_ Task 2.1 | pablo | 4 | [2020-12-25 Fri 21:20] | :Sprint3: |
| DONE | Epic1 | Story2 | Task2.2 | \_ Task 2.2 | pablo | 5 | [2020-12-22 Tue 01:00] | :Sprint3: |
| DONE | Epic1 | Story2 | Task2.3 | \_ Task 2.3 | john | 6 | [2020-12-25 Fri 21:21] | :Sprint3: |
|--------+--------+---------+---------+--------------------------+-------+--------+------------------------+-----------|
| | Epic1 | | | \_ Epic to Run | | 18 | | |
|--------+--------+---------+---------+--------------------------+-------+--------+------------------------+-----------|
| TODO | Epic1 | Story3 | | \_ Story 3 | | 18 | | |
| TODO | Epic1 | Story3 | Task3.1 | \_ Task 3.1 | pablo | 10 | | |
| TODO | Epic1 | Story3 | Task3.2 | \_ Task 3.2 | pablo | 8 | | |
#+END:
* Backlog
:PROPERTIES:
:COLUMNS: %TODO(Status) %EPICID %STORYID %TASKID %30ITEM(Task) %OWNER %Effort{+} %CLOSED %Alltags(Sprints)
:Owner_ALL: pablo john
:EPICID_ALL: Epic1 Epic2
:ID: 47B8AC9D-2556-4F6E-AAE1-775731314596
:END:
** Epic on Build It ALL
:PROPERTIES:
:EPICID: Epic1
:END:
*** TODO Story 1 :Sprint4:
:PROPERTIES:
:STORYID: Story1
:END:
**** TODO Task 1.1
:PROPERTIES:
:OWNER: pablo
:TASKID: Task1.1
:END:
***** [2021-05-08 Sat]
:PROPERTIES:
:EFFORT: 3
:END:
***** [2021-05-08 Sat]
:PROPERTIES:
:EFFORT: 4
:END:
**** TODO Task 1.2
:PROPERTIES:
:OWNER: john
:EFFORT: 2
:TASKID: Task1.2
:END:
**** TODO Task 1.3
:PROPERTIES:
:OWNER: pablo
:EFFORT: 3
:TASKID: Task1.3
:END:
*** TODO Story 2 :Sprint3:
:PROPERTIES:
:STORYID: Story2
:END:
**** DONE Task 2.1
CLOSED: [2020-12-25 Fri 21:20]
:PROPERTIES:
:OWNER: pablo
:EFFORT: 4
:TASKID: Task2.1
:END:
**** DONE Task 2.2
CLOSED: [2020-12-22 Tue 01:00]
:PROPERTIES:
:EFFORT: 5
:TASKID: Task2.2
:OWNER: pablo
:END:
:LOGBOOK:
- State "DONE" from "TODO" [2020-12-22 Tue 01:00]
- State "TODO" from [2020-12-20 Sun 19:46]
:END:
**** DONE Task 2.3
CLOSED: [2020-12-25 Fri 21:21]
:PROPERTIES:
:OWNER: john
:EFFORT: 6
:TASKID: Task2.3
:END:
** Epic to Run
:PROPERTIES:
:EPICID: Epic1
:END:
*** TODO Story 3
:PROPERTIES:
:STORYID: Story3
:END:
**** TODO Task 3.1
:PROPERTIES:
:OWNER: pablo
:EFFORT: 10
:TASKID: Task3.1
:END:
:LOGBOOK:
- State "TODO" from [2020-12-21 Mon 00:08]
:END:
**** TODO Task 3.2
:PROPERTIES:
:TASKID: Task3.2
:OWNER: pablo
:EFFORT: 8
:END:
```
# Answer
It's a bug: the code cannot deal with both `maxlevel` and `match` set. You get `maxlevel` if it's set (`match` is disregarded in that case); you'll only get `match` if it is set and `maxlevel` is *not* set.
Here's a workaround while waiting for the bug fix:
```
#+BEGIN: columnview :hlines 3 :id "47B8AC9D-2556-4F6E-AAE1-775731314596" :indent t :match "Sprint4+LEVEL<=4"
...
```
IOW, you just pass a `:match` argument that incorporates the `:maxlevel` restriction that you want, without using the `:maxlevel` argument.
In the meantime, I'll send a patch to the mailing list and we'll see how it goes. For the record, here's my proposed patch:
```
diff --git a/lisp/org-colview.el b/lisp/org-colview.el
index 2e1c29a99..7144308ff 100644
--- a/lisp/org-colview.el
+++ b/lisp/org-colview.el
@@ -1398,8 +1398,9 @@ other rows. Each row is a list of fields, as strings, or
(org-get-tags))))
(push (cons (org-reduced-level (org-current-level)) (nreverse row))
table)))))
- (or (and maxlevel (format "LEVEL<=%d" maxlevel))
- (and match match))
+ (if match
+ (concat match (and maxlevel (format "+LEVEL<=%d" maxlevel)))
+ (and maxlevel (format "LEVEL<=%d" maxlevel)))
(and local 'tree)
'archive 'comment)
(org-columns-quit)
```
EDIT: The bug report and patch is here
EDIT: The patch has been merged into the master branch (see this commit) but has not been merged into the `maint` branch, so it will not be available until the next major release of Org mode.
> 0 votes
---
Tags: org-mode
--- |
thread-48449 | https://emacs.stackexchange.com/questions/48449 | pdb within eshell up/down keys dont work | 2019-03-19T15:17:34.947 | # Question
Title: pdb within eshell up/down keys dont work
I am running python3 in eshell.
When I use `import pdb; pdb.set_trace()` in my code, pdb opens within eshell.
Everything works in pdb but the up/down keys don't work for running the previous command. I get `not found` as the message if I press the arrow keys. How can I make them work?
# Answer
> 3 votes
This isn't so much an answer, as a clue for someone else...
When I run `emacs -Q` followed by `M-x eshell` and do:
```
Welcome to the Emacs shell
~ $ python3
Python 3.7.2 (default, Jan 13 2019, 12:50:15)
[Clang 10.0.0 (clang-1000.11.45.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pdb
>>> pdb.set_trace()
--Return--
> <stdin>(1)<module>()->None
(Pdb)
```
At this point run `M-x toggle-debug-on-error` and hit `<up>`. This triggers a backtrace:
```
Debugger entered--Lisp error: (error "Not found")
signal(error ("Not found"))
error("Not found")
eshell-previous-matching-input("^(Pdb) " 1)
eshell-previous-matching-input-from-input(1)
funcall-interactively(eshell-previous-matching-input-from-input 1)
call-interactively(eshell-previous-matching-input-from-input nil nil)
command-execute(eshell-previous-matching-input-from-input)
```
Ok. Fine. I didn't *do* anything in PDB, so there's no history.
```
(Pdb) ?
Documented commands (type help <topic>):
========================================
EOF c d h list q rv undisplay
a cl debug help ll quit s unt
alias clear disable ignore longlist r source until
args commands display interact n restart step up
b condition down j next return tbreak w
break cont enable jump p retval u whatis
bt continue exit l pp run unalias where
Miscellaneous help topics:
==========================
exec pdb
(Pdb) up
*** Oldest frame
(Pdb) down
*** Newest frame
(Pdb)
```
At this point I hit up and `python3` is added to the `(Pdb)` input line, a la
```
[...]
(Pdb) down
*** Newest frame
(Pdb) python3
```
and `History: 1` is displayed in the mini-buffer. Deleting "python3", and adding more pdb acceptable input, and hitting `<up>` (or `<down>`) again triggers the same backtrace.
Quitting pdb, and returning to the python3 repl, we run a command and hit `<up>`
```
(Pdb)q
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/Cellar/python/3.7.2_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/bdb.py", line 92, in trace_dispatch
return self.dispatch_return(frame, arg)
File "/usr/local/Cellar/python/3.7.2_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/bdb.py", line 154, in dispatch_return
if self.quitting: raise BdbQuit
bdb.BdbQuit
>>> print("foo")
foo
>>>
```
Again, a similar backtrace
```
Debugger entered--Lisp error: (error "Not found")
signal(error ("Not found"))
error("Not found")
eshell-previous-matching-input("^>>> " 1)
eshell-previous-matching-input-from-input(1)
funcall-interactively(eshell-previous-matching-input-from-input 1)
call-interactively(eshell-previous-matching-input-from-input nil nil)
command-execute(eshell-previous-matching-input-from-input)
```
## tl;dr
It looks like `eshell` is getting confused by the subprocess. Either it understands it's in a sub-process and doesn't know how to record history, or it has no idea it's in a sub-process and is trying to count the prompt as part of the input and again getting confused. Either way, not being an `eshell` user, I'd chalk this up as a bug (or a missing feature).
Maybe using `M-x shell` and @LoremIpsum's suggestion to remap `<up>` you'll have better luck.
# Answer
> 1 votes
The following worked for me: setting variable `realgud-populate-common-fn-keys-function` to `nil`
# Answer
> 0 votes
As implied by the research @nega has done, it looks like `eshell` doesn't capture the input of the `pdb` subprocess. This can also be seen in how `eshell-previous-matching-input-from-input`, the function bound to `<up>`, behaves. It essentially pulls from the `eshell-history-ring`. If you look at the `eshell-list-history`, which parses the `eshell-history-ring`, it only shows the `eshell` history, not the history of the `pdb` subprocess.
Sad horn.
Fortunately, you have options. There is `shell`, `term`, and `ansi-term`<sup>1</sup>. Overall, I've found `shell` to be the best middle ground.
In `shell`, input history is accessed via `comint-previous-input` (`M-p`) and `comint-next-input` (`M-n`). Subprocesses, in my experience, are included in this history. You can rebind the history commands to the up/down arrows with something like
```
(define-key comint-mode-map (kbd "<up>") 'comint-previous-input)
```
I would like to give you more advice on using `shell` with Python, however, without knowing your specific use-case, I'd only be guessing. I recommend giving `shell` a try, see how it suits you, and ask specifically about anything you feel it lacks out-of-the-box.
Hopefully that gives you a path forward!
<sup>1.</sup> Of course, since Emacs is free software, the option to implement the feature yourself is always there.
---
Tags: key-bindings, python, osx, eshell
--- |
thread-66662 | https://emacs.stackexchange.com/questions/66662 | Elisp function to open file name with space? | 2021-07-12T02:40:11.933 | # Question
Title: Elisp function to open file name with space?
To open a file with default associated application, I have this function, which works as I expect, except with a file name that has space:
```
(defun open-a-file ()
(interactive)
(let ((process-connection-type nil))
(shell-command
(format "xdg-open %s" (read-file-name "Open: ")))))
```
This definition also doesn't work with a file name that contains a space char:
```
(defun open-a-file ()
(interactive)
(let ((process-connection-type nil))
(shell-command
(format "xdg-open %s" (shell-quote-argument (read-file-name "Open: "))))))
```
How can I fix the function?
# Answer
> 2 votes
I recommend using `call-process` instead of `shell-command`:
```
(defun open-a-file ()
(interactive)
(call-process "xdg-open" nil 0 nil (read-file-name "Open: ")))
```
One large difference between the two is that `call-process` does not invoke a shell, and thus does not accept shell syntax. It also takes all of the arguments separately; they do not need to be assembled into a valid command line. This eliminates all ambiguity resulting from the spaces in the filename.
# Answer
> 0 votes
Try this boss.
Works with input like `file name` or `/path/to/file name` or `path/to/file name`.
Most importantly, even with `~/file name`.
```
(defun open-a-file ()
(interactive)
(call-process "xdg-open" nil 0 nil (expand-file-name (read-file-name "Open: "))))
```
---
Tags: shell-command, filenames, call-process
--- |
thread-7375 | https://emacs.stackexchange.com/questions/7375 | Can I format cells in an org-mode table differently depending on a formula? | 2015-01-14T17:55:34.260 | # Question
Title: Can I format cells in an org-mode table differently depending on a formula?
I have a column in an org-mode table with numbers in each cell. I'd like to change the background color of the cell to red if the number is below 1 or above 2.
How can I do that?
# Answer
I got whole-table formatting to work with some Elisp:
A formula is evaluated for the cells' contents, and converted to a color using a gradient.
Org file including code:
```
#+name: item-prices
|-----------------------+--------+-------------+-------+------+------+--------+------+------+------+------+------|
| Item | Weight | Label Price | Ratio | CS-F | <-LR | <-WR | CS-N | Si-N | Si-2 | St-N | St-F |
|-----------------------+--------+-------------+-------+------+------+--------+------+------+------+------+------|
| Охотничье ружьё | 3.3 | 400 | 121 | 40 | 10 | 11.82 | | 40 | 40 | 50 | 60 |
| «Гадюка-5» | 2.88 | 3000 | 1042 | 300 | 10 | 103.82 | | 300 | 300 | 375 | 450 |
| Обрез | 1.90 | 200 | 105 | 20 | 10 | 10.00 | | 20 | 20 | 25 | 30 |
| ПМм | 0.73 | 300 | 411 | 30 | 10 | 39.73 | | 30 | 30 | 37 | 45 |
| АКМ-74/2 * | 3.07 | 4000 | 1303 | 637 | 16 | 207.49 | | 318 | 318 | 398 | 478 |
| АКМ-74/2У | 2.71 | 2100 | 775 | 420 | 20 | 154.61 | | 210 | 210 | 262 | 315 |
| ПБ-1с | 0.97 | 400 | 412 | 120 | 30 | 122.68 | 100 | 40 | 40 | 50 | 60 |
| «Чeйзер-13» | 3.00 | 1250 | 417 | | | | | 125 | | | |
| «Чeйзер-13» * | | 1250 | 417 | 200 | 16 | 66.33 | | 100 | 100 | 125 | 149 |
| ХПСС-1м | 0.94 | 600 | 682 | | | | | 60 | | | |
| ХПСС-1м * | 0.88 | 600 | 682 | 92 | 15 | 104.55 | | 46 | 46 | 57 | 69 |
| «Фора-12» | 0.83 | 600 | 723 | 120 | 20 | 143.37 | | 60 | 60 | 74 | 90 |
| «Кора-919» | 1.10 | 1500 | | | | | | 150 | 150 | | 225 |
|-----------------------+--------+-------------+-------+------+------+--------+------+------+------+------+------|
| Прицел ПСО-1 | 0.20 | 1000 | 5000 | 100 | 10 | 500.00 | | 150 | 150 | 150 | 200 |
| Детектор «Отклик» | 0.00 | 500 | inf | 50 | 10 | 50.00 | | 100 | 100 | 175 | 250 |
| Детектор «Медведь» | 0.00 | 1000 | inf | 100 | 10 | 100.00 | | | | | 500 |
|-----------------------+--------+-------------+-------+------+------+--------+------+------+------+------+------|
| Кожаная куртка | 3.00 | 500 | 167 | 250 | 50 | 83.33 | | - | - | 200 | |
| Бронежилет ЧН-1 | 4.00 | 5000 | 1250 | 2500 | 50 | 625.00 | | - | - | | |
|-----------------------+--------+-------------+-------+------+------+--------+------+------+------+------+------|
| Аптечка | 0.10 | 300 | 3000 | 30 | 10 | 300.00 | 16 | 45 | 45 | 105 | 150 |
| Бинт | 0.05 | 200 | 4000 | 20 | 10 | 400.00 | 11 | 30 | | 70 | 100 |
| Противорад. п. | 0.05 | 300 | 6000 | 30 | 10 | 600.00 | 16 | 45 | | 105 | 150 |
|-----------------------+--------+-------------+-------+------+------+--------+------+------+------+------+------|
| Водка «Казаки» | 0.60 | 100 | 167 | 100 | 100 | 166.67 | 100 | - | - | - | - |
| «Завтрак туриста» | 0.30 | 100 | 333 | 100 | 100 | 333.33 | | - | - | - | - |
| Колбаса «Диетическая» | 0.50 | 50 | 100 | 50 | 100 | 100.00 | | - | - | - | - |
| Хлеб | 0.30 | 20 | 67 | 20 | 100 | 66.67 | | - | - | - | - |
|-----------------------+--------+-------------+-------+------+------+--------+------+------+------+------+------|
| Патроны 9x18 мм | 0.20 | 50 | 250 | 5 | 10 | 25.00 | 3 | 7 | 7 | 5 | 5 |
| Патроны 9x19 мм РВР | 0.24 | 100 | 417 | 20 | 20 | 83.33 | 15 | | | | |
| Патроны 9x19 мм ЦМО | 0.24 | 100 | 417 | | 0 | 0.00 | | 15 | 15 | 15 | 20 |
| Патроны 12x70 дробь | 0.45 | 10 | 22 | 1 | 10 | 2.22 | 0 | 1 | | 1 | 1 |
| Патроны 12x76 жекан | 0.50 | 20 | 40 | 4 | 20 | 8.00 | 3 | 1 | | 3 | 4 |
|-----------------------+--------+-------------+-------+------+------+--------+------+------+------+------+------|
| Граната РГД-5 | 0.30 | 350 | | | | | | 52 | 52 | 70 | 70 |
|-----------------------+--------+-------------+-------+------+------+--------+------+------+------+------+------|
| «Медуза» | 0.5 | 4000 | 8000 | | 0 | 0.00 | | 2800 | 3600 | 2500 | 2800 |
|-----------------------+--------+-------------+-------+------+------+--------+------+------+------+------+------|
#+TBLFM: $4='(/ (string-to-number $3) (string-to-number $2));%1.f
#+TBLFM: $6='(/ (string-to-number $5) 0.01 (string-to-number $3));%1.f
#+TBLFM: $7=$5/$2;%1.2f
#+begin_src emacs-lisp :var table=item-prices
(defun cs/itpl (low high r rlow rhigh)
"Return the point between LOW and HIGH that corresponds to where R is between RLOW and RHIGH."
(+ low (/ (* (- high low) (- r rlow)) (- rhigh rlow))))
(defun cs/gradient (gradient p)
(if (< p (caar gradient))
(cdar gradient)
(while (and (cdr gradient) (> p (caadr gradient)))
(setq gradient (cdr gradient)))
(if (null (cdr gradient))
(cdar gradient)
(list
(cs/itpl (nth 1 (car gradient)) (nth 1 (cadr gradient)) p (caar gradient) (caadr gradient))
(cs/itpl (nth 2 (car gradient)) (nth 2 (cadr gradient)) p (caar gradient) (caadr gradient))
(cs/itpl (nth 3 (car gradient)) (nth 3 (cadr gradient)) p (caar gradient) (caadr gradient))))))
(defun cs/scs-table-color ()
(when (boundp 'cs/cell-color-overlays)
(mapc #'delete-overlay cs/cell-color-overlays))
(setq-local cs/cell-color-overlays nil)
(save-excursion
(org-table-map-tables
(lambda ()
(let* ((table (cl-remove-if-not #'listp (org-table-to-lisp))) ; remove 'hline
(heading (car table))
(element (org-element-at-point)))
(while (and element (not (eq (car element) 'table)))
(setq element (plist-get (cadr element) :parent)))
(cond
((equal (plist-get (cadr element) :name) "item-prices")
(org-table-analyze)
(cl-loop for row being the elements of (cdr table) using (index row-index)
do (cl-loop for col being the elements of row using (index col-index)
if (and
(string-match "^..-.$" (nth col-index heading))
(not (zerop (length col)))
(not (equal "0" col)))
do (progn
(org-table-goto-field (format "@%d$%d" (+ 2 row-index) (1+ col-index)))
(forward-char)
(let* ((base-price (string-to-number (nth 2 row)))
(vendor-price (string-to-number col))
(ratio (/ vendor-price 1.0 base-price))
(gradient '((0.10 #x40 #x00 #x00)
(0.20 #xC0 #x00 #x00)
(0.50 #x00 #x80 #x00)
(1.00 #x00 #xFF #x80)))
(color (cs/gradient gradient ratio))
(overlay (make-overlay
(progn (org-table-beginning-of-field 1) (backward-char) (point))
(progn (org-table-end-of-field 1) (forward-char) (point))))
(bg (apply #'message "#%02x%02x%02x" color))
(fg (if (< (apply #'+ color) 383) "#ffffff" "#000000"))
(face (list
:background bg
:foreground fg)))
(overlay-put overlay 'face face)
(push overlay cs/cell-color-overlays)))))))))
t)))
(add-hook 'org-ctrl-c-ctrl-c-hook 'cs/scs-table-color nil t)
nil
#+end_src
```
> 22 votes
# Answer
Using an overlay is how I'm going to want to do it. I can hook into org-ctrl-c-ctrl-c-hook. It means I can press C-c C-c to run the check.
I need to properly check that I'm inside a table and run this for all cells.
Then I probably need to hook into the alignment function to either redo the overlays or at least clear them.
This code will make the cell background red for the cell I'm in if the value is less than 1 or greater than 2 when I press C-c C-c ... But it is still buggy and will clear the overlays if one of them doesn't match the rules.
```
(defun staggering ()
(save-excursion
(let* ((ot-field-beginning (progn (org-table-beginning-of-field 1) (point)))
(ot-field-end (progn (org-table-end-of-field 1) (point)))
(cell-text (buffer-substring ot-field-beginning ot-field-end)))
(if (or (< (string-to-number cell-text) 1)
(> (string-to-number cell-text) 2))
(overlay-put (make-overlay
(progn (org-table-beginning-of-field 1) (point))
(progn (org-table-end-of-field 1) (point)))
'face '(:background "#FF0000"))))))
(add-hook 'org-ctrl-c-ctrl-c-hook 'staggering)
```
> 6 votes
# Answer
This is not yet an answer but I want to keep track of the things I discover here, as they may give someone else an idea.
It is possible to **conditionally modify the value of the cell itself**:
We can create a formatting function in elisp and then call it from the formula line:
```
#+BEGIN_SRC emacs-lisp :results silent
(defun danger (cell)
(if (or (< (string-to-number cell) 1)
(> (string-to-number cell) 2))
(concat (int-to-string (string-to-number cell)) "!")
cell))
#+END_SRC
```
And it can be used like so:
```
| String | Num |
|--------+-----|
| Foo | 2 |
| Bar | 1 |
| Baz | 3! |
|--------+-----|
#+TBLFM: $2='(danger @0$0)
```
I think what I want may require the creation of an overlay.
> 5 votes
# Answer
Emacs provides the function `hi-lock-face-buffer` `M-s h r`which highlights a regular expression in the buffer as you type.
All we need is a regular expression which matches any number which is not 1 or 2 and is within the cell of a table. Try this:
```
| *\(-[0-9]+\|[03-9]\|[0-9][0-9]+\) *|
```
(You can recall previous expressions with `M-n` and `M-p`.)
> 5 votes
# Answer
I created the following mechanism for highlighting positive and negative numbers in org tables similar to how a spreadsheet program might do it:
```
(defface positive-face
'((t :foreground "green"))
"Indicates something positive")
(defface negative-face
'((t (:foreground "red")))
"Indicates something negative")
(defun ek/match-positive-numbers (limit)
(let (result)
(while
(progn
(when (looking-back "|" 1)
(backward-char))
(setq result (re-search-forward "| *\\([0-9\\., ]+\\) *|" limit t))
(save-match-data
(and result (not (looking-back "^ *|.*"))))))
result))
(defun ek/match-negative-numbers (limit)
(let (result)
(while
(progn
(when (looking-back "|")
(backward-char))
(setq result (re-search-forward "| *\\(- *[0-9\\., ]+\\) *|" limit t))
(save-match-data
(and result (not (looking-back "^ *|.*"))))))
result))
(font-lock-add-keywords 'org-mode
'((ek/match-positive-numbers 1 'positive-face t))
'append)
(font-lock-add-keywords 'org-mode
'((ek/match-negative-numbers 1 'negative-face t))
'append)
```
This yields this nice looking tables:
By modifying the regular expressions and perhaps adding checks for \<1 or \>2 this could easily be adapted to your use case.
> 3 votes
---
Tags: org-table, formatting, formula
--- |
thread-55192 | https://emacs.stackexchange.com/questions/55192 | I got an error: Package 'tabbar-20160524' is a system package,not deleting | 2020-01-30T08:50:23.653 | # Question
Title: I got an error: Package 'tabbar-20160524' is a system package,not deleting
I installed spacemacs using "git clone https://github.com/syl20bnr/spacemacs.git ~/spacemacs/.emacs.d" but I got an error: Package 'tabbar-20160524' is a system package,not deleting....
When I started emacs with --debug-init I got this:
but I am not good at elisp, this error is difficult for me , can you help me solve it, thanks!
# Answer
> 0 votes
I got the same error for a lot of packages that I tried to remove. I'm not sure, but it might be because I had an older version of Emacs, so maybe the newer version had problems when trying to remove a bunch of packages installed from an older version.
The workaround I did (thanks to @dcorking's comment above) was to use `M-x package-delete` for each package, and then it told me that the package was a dependency for another package, so then I used `M-x package-delete` to delete the other package and was then able to delete the dependency package afteward.
UPDATE: that only worked for a few packages then stopped working. It looks like my actual problem was that I am using Windows with a unicode character in my HOME path, which causes a number of problems in Emacs, so to workaround the problem, I had to tell Emacs to use a different HOME directory (see this Emacs doc). I created a `C:\.emacs` that is a symlink to `%APPDATA%\.emacs.d\init.el` and also made a directory junction called `C:\.emacs.d` that points to `%APPDATA%\.emacs.d`.
---
Tags: spacemacs, debugging, tabbar
--- |
thread-66655 | https://emacs.stackexchange.com/questions/66655 | `racket-mode` REPL doesn't find packages | 2021-07-11T07:57:57.453 | # Question
Title: `racket-mode` REPL doesn't find packages
I recently installed Racket (using Guix) and installed a couple packages (`gregor-lib` and `pollen`). When launching from my terminal, it all works as intended. Inside Emacs however, both `racket-mode` REPL **and** Racket launched from the shell (`M-x shell`) fail to find the packages. For example:
```
> (require gregor)
; standard-module-name-resolver: collection not found
; for module path: gregor
; collection: "gregor"
; in collection directories:
; $HOME/.racket/8.0/collects
; /gnu/store/c4w9cviyaif57ssdrnw7phfjzd0asvlh-racket-8.0/share/racket/collects/
; ... [164 additional linked and package directories]
; -----
; Can't suggest packages to install, because pkg/db get-catalogs is '().
; To configure:
; 1. Start DrRacket.
; 2. Choose "File | Package Manager".
; 3. Click "Available from Catalog".
; 4. When prompted, click "Update".
; -----
```
I have checked and both the system terminal and Emacs find Racket at `$HOME/.guix-profile/bin/racket`, however the function `(find-user-pkgs-dir)` gives:
* From whithin Emacs: `$HOME/.racket/8.0/pkgs` (doesn't matter if it's a shell buffer or a REPL buffer).
* From my system terminal: `$HOME/.local/share/racket/8.0/pkgs` (this is where raco installed the packages).
The question thus is:
> How to tell Emacs/racket-mode to load Racket packages from `$HOME/.local/share/racket/8.0/pkgs/` rather than `$HOME/.racket/8.0/pkgs/`?
##### Edits
1. Launching emacs from the console gives the same problem.
2. plocate says the libraries are installed in `$HOME/.local/share/racket/8.0/pkgs/<package>/`, however for package `pollen` it also gives `$HOME/.racket/8.0/pkgs/pollen`, I suspect here's where Emacs is looking into (I ran `raco pkg install pollen` from a terminal within Emacs and it is importable now).
The question now I guess is:
> How to tell Emacs to load Racket packages from `$HOME/.local/share/racket/8.0/pkgs/` rather than `$HOME/.racket/8.0/pkgs/`?
# Answer
Well, this is not like it answers my **real** question (why Emacs loads a different path than my terminal) but at least this makes it work:
* The variable `PLTADDONDIR` controls what addon-dir racket loads. By setting it, both the terminal and Emacs load the same path.
> 1 votes
---
Tags: spacemacs
--- |
thread-66674 | https://emacs.stackexchange.com/questions/66674 | How to make set-input-method buffer-local | 2021-07-12T15:52:22.227 | # Question
Title: How to make set-input-method buffer-local
I'm using Emacs 26.3. How do I `set-input-method` to `latin-alt-postfix` at the top of the buffer using the `-*- ... -*-` local-variables method? There are only certain files that I want to do this for.
I looked in the manual and wiki, but the instructions are not clear to me.
# Answer
You can use the `eval` pseudo-variable to evaluate arbitrary code (which is dangerous, so be careful about accepting such files from others). See the description of specifying file variables in the manual: `C-h i g(emacs)Specifying file variables`.
Here's an example:
```
-*- eval: (set-input-method 'latin-alt-postfix) -*-
This is a test á á é ö etc.
```
> 0 votes
---
Tags: input-method, file-local-variables
--- |
thread-9344 | https://emacs.stackexchange.com/questions/9344 | Pasting in evil-mode when there's an active selection copies the selection | 2015-02-18T11:10:40.383 | # Question
Title: Pasting in evil-mode when there's an active selection copies the selection
Currently when I select a bit of text replacing another bit of text (eg "viwp" to paste over the current word) it copies the thing I just replaced into kill ring. So if I try to paste over another bit it has lost the original thing I copied and instead pastes the thing I previously replaced. Obviously I can cycle through the kill ring but that's fiddly and a total pain.
Any idea what variables to look at? I think this happened when I upgraded evil-mode.
# Answer
Came across this while Googling for a solution to this problem. What I found to work is part of the Spacemacs FAQ:
```
(fset 'evil-visual-update-x-selection 'ignore)
```
See also: https://emacs.stackexchange.com/a/15054/84
> 3 votes
# Answer
That is evil's default behaviour, parallel to VIM. The variable to change this behavior is: `evil-kill-on-visual-paste`.
To discard the overwritten text:
```
(setq evil-kill-on-visual-paste nil)
```
> 1 votes
---
Tags: evil
--- |
thread-66647 | https://emacs.stackexchange.com/questions/66647 | Create a function that deletes word on point and replace with the yank register on Evil-emacs | 2021-07-10T17:56:21.140 | # Question
Title: Create a function that deletes word on point and replace with the yank register on Evil-emacs
I want to emulate this vim remap in evil-emacs (doom emacs).
`nnoremap <leader>mpp ciw<C-r>0`
I want to change the word on point (I don't mind word or Word, just want the evil-change with evil-inner-word syntax). If possible I want it defined on an interactive function to remap it to leader mpp.
I want a remap that substitutes current word on point with yank/clipboard content.
Thanks in advance.
# Answer
> 0 votes
I think this works as you want. Non-evil mode that I originally wrote for reference, as I'm not a day-to-day evil-mode user.
```
(defun replace-word-at-point ()
(interactive)
(let ((bounds (bounds-of-thing-at-point 'word)))
(if bounds
(progn (delete-and-extract-region (car-safe bounds) (cdr-safe bounds))
(yank))
(message "No word at point"))))
(defun replace-evil-word-at-point ()
"Select the word at point, remove it, and yank the most recent killed text. "
(interactive)
(let ((bounds (evil-inner-word)))
(if bounds
(progn (delete-and-extract-region (pop bounds) (pop bounds))
(yank))
(message "No word at point"))))
```
For instance (bold = character at point in each example, just take my word that the space is a bold space in the last one):
| Original | Plain emacs | Evil version |
| --- | --- | --- |
| this is my test w**o**rd | this is my test Hello! | this is my test Hello! |
| this is my test **w**ord | this is my test Hello! | this is my test Hello! |
| this is my test word | this is my Hello! word | this is my testHello!word |
---
Tags: key-bindings, evil
--- |
thread-65051 | https://emacs.stackexchange.com/questions/65051 | Python formatting not working on Doom Emacs | 2021-05-28T10:42:28.353 | # Question
Title: Python formatting not working on Doom Emacs
I activated the formatting on save in the `init.el` file uncommenting the following line
```
(format +onsave) ; automated prettiness
```
But when I save a Python file, I get the following error message:
```
Error (before-save-hook): Error running hook "+format-buffer-h" because: (error You need the "black" command. You may be able to install it via "pip install black".)
```
I installed black with pip, as the message says, but I keep getting the same message.
I set the following settings for the Python black formatter (found it here):
```
;; package.el
(package! python-black)
```
```
;; config.el
(use-package! python-black
:demand t
:after python
:config
(add-hook! 'python-mode-hook #'python-black-on-save-mode)
;; Feel free to throw your own personal keybindings here
(map! :leader :desc "Blacken Buffer" "m b b" #'python-black-buffer)
(map! :leader :desc "Blacken Region" "m b r" #'python-black-region)
(map! :leader :desc "Blacken Statement" "m b s" #'python-black-statement)
)
```
I did run `doom sync` after changing the settings, and it installed some packages, but I still get the same error when saving Python files.
I'm using Fedora 34, and installed black for Python 3.9. I also tried to install black for Python 2.7, but it's not supported anymore, so I was guessing that maybe Emacs is expecting black to be installed for Python 2.7, That's only a conjecture because I'm new to Emacs and don't know much about it.
Is there a way to make Python formatting work?
# Answer
I just activated `python` and `(format +onsave)` only.
You must run `doom/reload` (SPC h r r) after `doom sync`.
Activate virtualenv with `SPC : pyvenv-activate`
Install black with `python -m pip install black`
Close open `Python` buffer and open again.
`SPC b s` to save buffer.
`SPC c f` to format buffer / region.
Run `doom doctor` to diagnose problems.
> 1 votes
---
Tags: python, formatting, doom
--- |
thread-66681 | https://emacs.stackexchange.com/questions/66681 | How to override org-mode-map key bindings? | 2021-07-13T06:43:57.360 | # Question
Title: How to override org-mode-map key bindings?
I would like to override the `C-c C-j` keybinding. I put this in my init file
```
(global-set-key (kbd "C-c C-j") 'counsel-org-goto)
```
However, it won't override the command `org-goto` (found in org-mode-map).
Thanks for your input!
# Answer
Try this expression:
```
(with-eval-after-load "org"
(define-key org-mode-map (kbd "C-c C-j") #'counsel-org-goto))
```
The Org mode keymap "shadows" the global map. In Emacs, the keymaps of major modes take precedence over keybindings in the global keymap.
See this excellent tutorial from Mickey Petersen for a thorough discussion of the "keymap lookup order": https://www.masteringemacs.org/article/mastering-key-bindings-emacs.
> 5 votes
---
Tags: key-bindings
--- |
thread-47933 | https://emacs.stackexchange.com/questions/47933 | Are there any tutorials/documentation for lsp-java? | 2019-02-20T13:45:02.057 | # Question
Title: Are there any tutorials/documentation for lsp-java?
I have managed to install lsp-java according to their git Readme (https://github.com/emacs-lsp/lsp-java) and created my workspace.
Is there a better way (eg. in form of a documentation or tutorial) to get to known with lsp-java or do I have to try out every single possible command and see what is going to happen?
# Answer
In the github page for lsp-java, there is a wordpress page that runs through an example workflow utilising lsp-java. This could be a good starting point.
> 1 votes
# Answer
I'm using configure of prelude and install lsp-java recently without much configures:
1. require lsp-mode, company-lsp, lsp-ui, lsp-java;
2. add code for hook:
```
(add-hook 'java-mode-hook #'lsp)
(add-hook 'java-mode-hook 'flycheck-mode)
(add-hook 'java-mode-hook 'company-mode)
```
3. create a test java project with git and HelloWorld.java;
4. restart emacs and open HelloWorld.java by step3, emacs will auto download jdt(you may download it manually);
5. when everything ready, you should see message like "LSP :: Connected to \[jdtls:12693 status:starting\]." when you open HelloWorld.java by step 3.
all my configure can find at: https://github.com/RezoChiang/prelude/tree/rezo-lsp/modules
> 1 votes
---
Tags: java
--- |
thread-66677 | https://emacs.stackexchange.com/questions/66677 | How to prevent `[size greater than: 0]` shown in the iBuffer buffer | 2021-07-12T18:10:52.347 | # Question
Title: How to prevent `[size greater than: 0]` shown in the iBuffer buffer
When I run `M-x ibuffer`, it keeps adding `[size greater than: 0]` into top `iBuffer` file, which increases its file size. Would it be possible to prevent it?
`minimal.el`:
```
(add-hook 'ibuffer-hook (lambda ()(ibuffer-filter-by-size-gt 0)))
(add-hook 'ibuffer-mode-hook
(lambda ()
(ibuffer-auto-mode 1)
(ibuffer-switch-to-saved-filter-groups "default")))
```
---
// Here first line in the `ibuffer` keeps appending
```
IBuffer by recency (Auto) [size greater than: 0] [size greater than: 0] [size greater than: 0] [size greater than: 0] [size greater than: 0] ....
[ project ]
MRL Name Size Mode Filename/Process
--- ---- ---- ---- ----------------
[ Default ]
*scratch* 145 Lisp Interaction
*% *Messages* [keep increases] Messages
```
Related questions: How can I prevent empty files from showing up on the Ibuffer list?
# Answer
> 2 votes
\[This is probably a bad answer, but I no longer know what the question is\]
* If you are getting the '\[size greater than 0:\]\` message repeatedly in the header-line and you want to investigate and remove the cause of that, then you need to debug your init file. I cannot reproduce that with a minimal init file containing *just* the following and I assume that you will find the same behavior if you use this minimal init file:
```
(add-hook 'ibuffer-hook (lambda ()
(ibuffer-filter-by-size-gt 0)))
(add-hook 'ibuffer-mode-hook
(lambda ()
(ibuffer-auto-mode 1)
(ibuffer-switch-to-saved-filter-groups "default")))
(define-key ctl-x-map (kbd "C-b") #'ibuffer)
```
* If you are worried about the fact that the `*Messages*` buffer is increasing, you should filter out that buffer from the ibuffer listing. Interactively, `/*/!` will get rid of all starred buffers; `/n \*Messages\* RET /!` will just filter out the `*Messages*` buffer.
* If you don't want to see the header line at all, you should customize the `ibuffer-use-header-line` option.
* If you want to save a set of filters for future use, you can use `/s <name>` and you can restore those filters later with `/r <name>` or add them to whatever filters you have already defined with `/a <name>`.
* Do `C-h m` in an ibuffer-mode buffer to find out more about what you can do.
---
Tags: ibuffer
--- |
thread-51137 | https://emacs.stackexchange.com/questions/51137 | How can I debug a hang when debug-on-quit doesn't work? | 2019-06-20T10:01:38.247 | # Question
Title: How can I debug a hang when debug-on-quit doesn't work?
I have a problem with haskell-mode where Emacs will hang every time I open up a Haskell file. Mashing Ctrl-g a few times will get the file opened.
So I would imagine setting `debug-on-quit` would allow me to debug the issue. But it doesn't. No debugger shows up. Likewise if I run this elisp code `(while 1)`. Emacs locks up, Ctrl-g will will break out of the hang, but no debugger.
I can sometimes bring up the debugger. Say if I run grep and then Ctrl-g whilst it is running, I will get a backtrace popping up.
So I'm not totally sure what is going on. Is there another way I should be debugging this hang with haskell-mode?
*GNU Emacs 26.2 (build 1, x86\_64-apple-darwin17.7.0, Carbon Version 158 AppKit 1561.6)*
# Answer
So it seems that I was able to bypass the problem from occuring whilst opening the file by disabling global-font-lock-mode (`M-x global-font-lock-mode`). (Thanks to @Lindydancers advice.)
For reasons currently unknown to me, if Emacs hangs whilst opening the file, pressing Ctrl-G doesn't bring up the debugger.
This did at least allow me to open the file. While editing the file Emacs would occasionally hang, and this time pressing Ctrl-G did bring up the debugger which did allow me to locate where the problem was. There is something going on in the Lexer of haskell mode.
So although I don't fully understand why the debugger didn't open during file load, if you have a similar hang whilst opening the file, it is probably well worth disabling font-lock-mode which should get you a few steps further to debugging the actual issue.
> 2 votes
# Answer
Try sending Emacs the `SIGUSR2` signal, or whatever signal is specified by the Emacs variable `debug-on-event`. The easiest way to do this is probably to run `killall -SIGUSR2 emacs`.
> 2 votes
---
Tags: debugging
--- |
thread-51214 | https://emacs.stackexchange.com/questions/51214 | How prevent `display-buffer` from opening a specific buffer in a new window if and only if it is shown in another frame | 2019-06-24T07:26:39.910 | # Question
Title: How prevent `display-buffer` from opening a specific buffer in a new window if and only if it is shown in another frame
I want the `*compilation*` buffer to *not* pop up in my main frame when I have it in another frame already open. However if the buffer is not shown anywhere, I do want it to pop up in a new window of the main frame.
I have set `special-display-regexps`:
```
(setq special-display-regexps (list "\\*compilation\\*.*"))
```
And this somewhat works: The compilation buffer does not open in a new window when it's displayed in another frame, so far so good, *but*, if it is not displayed anywhere it is opened in a brand new frame - and I do not want this.
Any idea how I can tweak this?
# Answer
> 1 votes
Not a real answer, but some info that might help.
You will likely need to fiddle with `display-buffer-alist` (good luck!). Someone here will no doubt help with that.
You cannot use `special-display-regexps` or `special-display-buffer-names` alone to do what you want - they're designed for the simple behavior you described: use (and reuse) an existing window, and if there is none then use a new frame.
A poor man's workaround would be to first create a `*compilation*` window on your "main" frame, and then do the `special-display-*` thing. If a window showing the buffer already exists somewhere (anywhere) then it will be reused. If such a window does not exist then the buffer will be displayed in a new frame.
# Answer
> 0 votes
Try this:
```
;; Prefer existing frames already displaying *compilation*.
(add-to-list 'display-buffer-alist
(cons "\\`\\*compilation\\*\\'"
(cons 'display-buffer-reuse-window
'((reusable-frames . visible)
(inhibit-switch-frame . nil)))))
```
For more information, refer to:
* `C-h``f` `display-buffer-reuse-window`
* `C-h``v` `display-buffer-alist`
* `C-h``i``g` `(elisp)Displaying Buffers`
---
Tags: frames, window-splitting
--- |
thread-66695 | https://emacs.stackexchange.com/questions/66695 | org-fill-paragraph doesn't comply with org-list-allow-alphabetical | 2021-07-14T12:39:26.293 | # Question
Title: org-fill-paragraph doesn't comply with org-list-allow-alphabetical
Given that `(setq org-list-allow-alphabetical t)`.
Consider the following example, where `|` stands for the point:
```
1. |Lorem Ipsum
1. Lorem Ipsum
```
```
1. |Lorem Ipsum
a. Lorem Ipsum
```
While `org-fill-paragraph` does nothing in the first Org snippet, it collapses the two lines in the second:
```
1. Lorem Ipsum a. Lorem Ipsum
```
I'm working on a specific case where `read-only-mode` is in use and don't need to export the Org buffer to pdf or other file types. However, I have to keep the alphabetical numbering at least visually as the content refer to them as such. Hence, I'm currently considering a workaround which consists of
1. replacing alphabetical bullets by numeral ones ;
2. then using overlays with the `'display` property to display them as they were alphabetical bullets.
As the underlying bullets are numeral, `org-fill-paragraph` would work as expected.
Are there better solutions for this issue ?
# Answer
> 1 votes
As @NickD pointed out and per the documentation:
```
This variable needs to be set before org.el is loaded. If you
need to make a change while Emacs is running, use the customize
interface or run the following code after updating it:
‘M-x org-element-update-syntax’
```
---
Tags: org-mode, fill-paragraph, overlays, read-only-mode
--- |
thread-66688 | https://emacs.stackexchange.com/questions/66688 | Unexpected Error: (void-function check-calendar-holidays) in Calendar mode | 2021-07-14T01:27:31.973 | # Question
Title: Unexpected Error: (void-function check-calendar-holidays) in Calendar mode
I am trying to adapt this code from https://www.emacswiki.org/emacs/DiaryMode for use in Emacs with calendar and diary.
```
(defun diary-schedule (m1 d1 y1 m2 d2 y2 dayname)
"Entry applies if date is between dates on DAYNAME.
Order of the parameters is M1, D1, Y1, M2, D2, Y2 if
`european-calendar-style' is nil, and D1, M1, Y1, D2, M2, Y2 if
`european-calendar-style' is t. Entry does not apply on a history."
(let ((date1 (calendar-absolute-from-gregorian
(if european-calendar-style
(list d1 m1 y1)
(list m1 d1 y1))))
(date2 (calendar-absolute-from-gregorian
(if european-calendar-style
(list d2 m2 y2)
(list m2 d2 y2))))
(d (calendar-absolute-from-gregorian date)))
(if (and
(<= date1 d)
(<= d date2)
(= (calendar-day-of-week date) dayname)
(not (check-calendar-holidays date))
)
entry)))
```
The above allows recurring items having entries like `&%%(diary-schedule 22 4 2003 1 8 2003 2) 18:00 History`.
I prefer ISO date format, so I would like to be able to enter in `~/.emacs.d/diary` entries like
```
%%(diary-schedule 2021 08 30 2021 12 10 1) 08:30 Recurring event
```
Accordingly, I have modified the aforementioned code thus:
```
(defun diary-schedule (y1 m1 d1 y2 m2 d2 weekday)
""
(let ((date1 (calendar-absolute-from-gregorian
(diary-make-date y1 m1 d1)))
(date2 (calendar-absolute-from-gregorian
(diary-make-date y2 m2 d2)))
(d (calendar-absolute-from-gregorian date)))
(if (and
(<= date1 d)
(<= d date2)
(= (calendar-day-of-week date) weekday)
(not (check-calendar-holidays date))
)
entry)))
```
and I set `calendar-date-style` to `'iso`. However, when in Calendar mode, and I try to view diary for a given date (by pressing "d"), if there is a diary entry using `diary-schedule`, I get an error
```
Error (diary): Bad diary sexp at line 36 in ~/.emacs.d/diary:
(diary-schedule 2021 08 31 2021 12 10 2)
Error: (void-function check-calendar-holidays)
```
If I comment out the one line
```
(not (check-calendar-holidays date))
```
everything works OK.
`.emacs` includes the lines
```
(require 'calendar)
(setq calendar-date-style 'iso)
```
before the code above.
It seems that `check-calendar-holidays` should return a list of holidays that match `date` or `nil` otherwise. It also seems that `check-calendar-holidays` gets its input from `date` and that date style shouldn't matter. Perhaps I'm mistaken.
I used `M-: (setq calendar-debug-sexp t) RET` and then tried, so here is stack trace:
```
Debugger entered--Lisp error: (void-function check-calendar-holidays)
(check-calendar-holidays date)
(not (check-calendar-holidays date))
(and (<= date1 d) (<= d date2) (= (calendar-day-of-week date) weekday) (not (check-calendar-holidays date)))
(if (and (<= date1 d) (<= d date2) (= (calendar-day-of-week date) weekday) (not (check-calendar-holidays date))) entry)
(let ((date1 (calendar-absolute-from-gregorian (diary-make-date y1 m1 d1))) (date2 (calendar-absolute-from-gregorian (diary-make-date y2 m2 d2))) (d (calendar-absolute-from-gregorian date))) (if (and (<= date1 d) (<= d date2) (= (calendar-day-of-week date) weekday) (not (check-calendar-holidays date))) entry))
diary-schedule(2021 8 31 2021 12 10 2)
eval((diary-schedule 2021 8 31 2021 12 10 2))
diary-sexp-entry("(diary-schedule 2021 08 31 2021 12 10 2)" "10:15 Recurring appointment" (9 7 2021))
diary-list-sexp-entries((9 7 2021))
diary-list-entries((9 7 2021) 1)
diary-view-entries(1)
funcall-interactively(diary-view-entries 1)
call-interactively(diary-view-entries nil nil)
command-execute(diary-view-entries)
```
`Symbol's function definition is void: check-calendar-holidays` appears in the minibuffer.
New to Emacs and not sure how to debug. Why do I get this error?
# Answer
> 0 votes
Pursuant to @NickD's most helpful comments, the issue was indeed that `check-calendar-holidays` is no more and `calendar-check-holidays` is now the correct function, hence:
```
(defun diary-schedule (y1 m1 d1 y2 m2 d2 weekday &optional mark)
"Assumes calendar-date-style = iso.
Entry applies if date is between date1 and date2
and on the specified weekday, e.g., monday = 1.
Note: Expected order of parameters passed to
diary-make-date depends on calendar-date-style."
(with-no-warnings (defvar date) (defvar entry))
(let ((date1 (calendar-absolute-from-gregorian
(diary-make-date y1 m1 d1)))
(date2 (calendar-absolute-from-gregorian
(diary-make-date y2 m2 d2)))
(d (calendar-absolute-from-gregorian date)))
(and
(<= date1 d)
(<= d date2)
(= (calendar-day-of-week date) weekday)
(not (calendar-check-holidays date))
(cons mark entry))))
```
---
Tags: calendar, diary
--- |
thread-66653 | https://emacs.stackexchange.com/questions/66653 | How to use org-tree-to-indirect-buffer and turn off org-indent-mode in the new indirect buffer, with a toggle to go back, all in a single key binding? | 2021-07-11T03:48:52.290 | # Question
Title: How to use org-tree-to-indirect-buffer and turn off org-indent-mode in the new indirect buffer, with a toggle to go back, all in a single key binding?
I like using org-mode as a distraction free text editor.
I also like using org-indent-mode when navigating my entire file.
I also like using `org-tree-to-indirect-buffer` to focus on a desired section of text. Doing this makes org-indent-mode rather unnecessary however, as I'm usually working at the lowest level and thus the indent is just empty space where I could have more text on the screen.
After turning off org-indent-mode manually for a while I tried to come up with a single shortcut to toggle both commands at once.
I tried:
```
;; custom org to indirect buffer, toggling off indent-mode for the new indirect buffer
(defun my-org-to-indirect-buffer ()
"Run `some-command' and `some-other-command' in sequence."
(interactive)
(org-tree-to-indirect-buffer)
(org-indent-mode)
)
(global-set-key (kbd "C-f") 'my-org-to-indirect-buffer)
```
Not only does this fail to toggle off org-indent-mode in the indirect buffer, it also messes with the original buffer, so I have to manually toggle org-indent-mode off and on before it works again. I get this happens because the second command triggers after killing the indirect buffer, yet it doesn't behave as I'd expect and just turn off the mode, as my mode-line still displays it running. Clearly there's something going on I'm missing.
How would I open an indirect buffer and toggle off org-indent-mode in a single keypress, with a second keypress undoing the changes, reverting back to my main buffer with org-indent-mode on?
# Answer
> 0 votes
Big thanks to NickD for setting me on the right path.
Indeed, the error message "Not enabling jit-lock: it does not work in indirect buffer" is key to this problem.
When looking up that error message in jit-lock.el, we find this comment:
```
;; We're in an indirect buffer, and we're turning the mode on.
;; This doesn't work because jit-lock relies on the `fontified'
;; text-property which is shared with the base buffer.
```
In essence, we can't alter the fontified state of the indirect buffer, just the main buffer. The same seems to hold true for org-indent-mode, or at least it does in my setup for whatever reason.
Thus, to create a toggle we need to turn off and on org-indent-mode via the original buffer, not the indirect copy.
```
;; custom org to indirect buffer
(defun my-org-to-indirect-buffer ()
(interactive)
(if (buffer-live-p org-last-indirect-buffer)
; if the org indirect buffer is active
(with-current-buffer (buffer-base-buffer) (org-indent-mode 1)
(message "Enabled org-indent-mode"))
; then turn back on indent mode, because we're closing the indirect buffer
(org-indent-mode -1) (message "Disabled org-indent-mode"))
; else turn indent mode off, because we're opening the indirect buffer
(org-tree-to-indirect-buffer)
)
(define-key org-mode-map (kbd "C-f") #'my-org-to-indirect-buffer)
; org-mode specific key binding for an org-mode specific function
```
Still, this isn't perfect, as it only allows for one indirect buffer at a time. Trying to use the command on any other buffer while the first indirect buffer is open doesn't work and gives the error `save-current-buffer: Wrong type argument: stringp, nil` which I don't really know what to do with. Yet it does what I set out to do, so I'll consider it a win. If someone feels like making a more universal function though I'll happily mark their answer as the best instead.
# Answer
> 0 votes
Two problems:
* `org-indent-mode` is a minor mode and like *all* minor modes is enabled by calling with a positive argument and disabled by calling it with a negative argument - see its doc string with `C-h f org-indent-mode`. So you have to call it like this: `(org-indent-mode -1)` to disable it.
* `org-to-tree-indirect-buffer` leaves the current buffer unchanged, i.e. that of the original Org mode file. However, you need to turn off `org-indent-mode` not in the original buffer but in the generated indirect buffer. Fortunately, it saves that indirect buffer in the global variable `org-last-indirect-buffer`, so you can use `with-current-buffer` to temporarily switch to the indirect buffer and disable `org-indent-mode` there.
The final form of the function would then look like this (EDIT: the fontification of the buffer was lost when executing the original form of the following function, so I added an explicit call to `font-lock-fontify-buffer` to restore it, although this is probably a workaround, not the real solution. However, I *still* cannot reproduce the OP's problem where he loses `org-indent-mode` in the original buffer) /EDIT):
```
(defun my-org-to-indirect-buffer ()
"Run `some-command' and `some-other-command' in sequence."
(interactive)
(org-tree-to-indirect-buffer)
;; turn off org-indent-mode in the indirect buffer
(with-current-buffer org-last-indirect-buffer (org-indent-mode -1))
;; the original buffer loses fontification for some reason, so we restore it explicitly
(font-lock-fontify-buffer))
```
One more problem might be the key binding: why do you bind it in the global map? Presumably you only need it in an Org mode buffer, so why not restrict it to the mode-specific keymap? Something like this:
```
(define-key org-mode-map (kbd "C-c f") #'my-org-to-indirect-buffer)
```
---
Tags: org-mode, customize, narrowing, indirect-buffers
--- |
thread-66676 | https://emacs.stackexchange.com/questions/66676 | org-babel multi-line header var | 2021-07-12T17:18:48.127 | # Question
Title: org-babel multi-line header var
I'm trying to find a way how to conveniently edit(and pass) multi-line arguments to org-babel block.
In the example below, ${name} variable is pretty convenient to edit as inline variable but for ${storyDescription} it becomes very annoying because it could contain dozens of lines(separated by \n) and I would like to manage it like a regular text.
```
#+BEGIN_SRC http :pretty :var projectId="123" :var name="Test story name"
POST https://www.pivotaltracker.com/services/v5/projects/${projectId}/stories
X-TrackerToken: ${token}
Content-Type: application/json
{
"name": ${name},
"description": ${storyDescription},
"current_state": "unstarted",
"estimate": 1
}
#+END_SRC
```
Any hints are greatly appreciated.
---
Update.
For now, I'm using the following(dirty) hack in Ruby:
```
#+name: storyDescription
#+BEGIN_SRC ruby :results value
<<-EOL.gsub("\n", "\\n")
first line
second line
EOL
#+END_SRC
#+RESULTS: storyDescription
: first line\nsecond line\n
```
it works but I'm happy to accept more clean and idiomatic solution to this.
I'm wondering why there isn't some kind of `BEGIN_SRC text`(org-babel "text" language that's used just for setting long content blocks of plain text).
# Answer
I think the given (Ruby) solution is fine: I don't consider it a dirty hack. The same thing can be done in just about any language of course. Particularly, as in my case, if one does not speak Ruby.
Here's a code block in emacs lisp (using the string library s.el, also available from MELPA):
```
#+name: desc-lisp
#+begin_src elisp :results drawer
(setq x "first line
second line
third line
")
(s-replace "\n" "\\n" x)
#+end_src
```
or in python (with `:results value`):
```
#+name: desc-python-value
#+begin_src python :results value
x="""first line
second line
third line
"""
return x.replace("\n", "\\n")
#+end_src
```
or in python with `:results output`:
```
#+name: desc-python-output
#+begin_src python :results output drawer
x="""first line
second line
third line
"""
print(x.replace("\n", "\\n"))
#+end_src
```
or even Ruby using a string to make it congruent to the ones above:
```
#+name: desc-ruby-value
#+begin_src ruby :results value drawer
x = "first line
second line
third line
"
x.gsub("\n", "\\n")
#+end_src
```
In all cases, we define a string and then apply some transformation to it before returning it (in this case, translating newlines to the two-byte sequence `<backslash>, <n>`). Any transformation could be applied (including the identity transformation). In all the above cases, the output is `first line\nsecond line\nthird line\n`.
An alternative organization that may be slightly more modular is to just return the string untransformed from the code block: any transformation could then be applied in another code block that uses the string, E.g.:
```
#+name: desc-lisp
#+begin_src elisp :results drawer
"first line
second line
third line
"
#+end_src
#+name: desc-transformed
#+begin_src elisp :results drawer :var story=desc-lisp
(s-replace "\n" "\\n" story)
#+end_src
#+name: post-story
#+begin_src shell :var story=desc-transformed
echo $story
#+end_src
```
But all of these are minor variations on the theme which you established in your question.
> 1 votes
---
Tags: org-mode, org-babel
--- |
thread-66701 | https://emacs.stackexchange.com/questions/66701 | Why I cannot find `Emacs Lisp Intro` inside info mode? | 2021-07-15T01:28:47.837 | # Question
Title: Why I cannot find `Emacs Lisp Intro` inside info mode?
I am trying to read the `Emacs Lisp Intro` inside Emacs. I am following the advice on Emacs wiki:
> Read the Emacs Lisp Introduction: EmacsLispIntro. Use ‘C-h i’ (‘info’), then choose ‘Emacs Lisp Intro’. You can also read this manual on the Web or as a portable epub book.
Unfortunately, after pressing `C-h i`, I can find options such as Magit and Slime. However, I cannot find anything about ‘Emacs Lisp Intro’. I know I can read the *Introduction to Programming in Emacs Lisp*, written by Robert J. Chassell, on the web. But I would like to read it inside Emacs.
Why I cannot find it? How can I fix this?
UPDATE: I am using Ubuntu 20.04. Surprisingly, this is relevant.
Thanks.
# Answer
In order to solve this, I used the least upvoted answer here. These are the *original* instructions:
1 - Download https://www.gnu.org/software/emacs/manual/info/elisp.info.gz to your `/usr/share/info` directory.
2 - From a terminal run `update-info-dir` command.
3 - From emacs `C-h i m Elisp` (**capital** E).
Obs.: I was **not** able to download it directly to /usr/share/info using just GUI. So, I downloaded it on Downloads folder and then on root I did:
```
/$ sudo mv home/pedro/Downloads/elisp.info.gz usr/share/info/emacs/
/$ sudo update-info-dir
```
Notice that I inserted the file on `usr/share/info/emacs/` instead of the original instruction which used just `usr/share/info/`
> 1 votes
---
Tags: help, info, manual
--- |
thread-66689 | https://emacs.stackexchange.com/questions/66689 | changing default emacs theme to downloaded theme | 2021-07-14T02:08:41.730 | # Question
Title: changing default emacs theme to downloaded theme
I have just downloaded a matrix theme name **matrix-theme-source-code.el** and I want to install it on my emacs, I have read that I should do the following thing in my **.emacs** :-
```
(add-to-list 'custom-theme-load-path "~/.emacs.d/themes/")
(load-file "~/.emacs.d/themes/matrix-theme-source-code.el")
```
After doing this, I tried to do `M-x` and `customize-themes Ret` It should display me my theme but there's is no theme, except the default themes provided by the emacs.
# Answer
> 0 votes
This is what I have to load my preferred theme (named "foo" in this example):
```
(setq custom-safe-themes t)
(load-theme 'foo 'noconfirm)
```
First check your logs with `C-h e`, it might say why your theme isn't being applied.
`custom-safe-themes` can be `t` or a list of themes. Since themes can contain arbitrary code, it's better to whitelist the ones you use, but for testing set it to `t`.
Check that you definitely installed the theme correctly. `load-theme` says the file should be named `foo-theme.el`. `load-theme` calls `enable-theme` at the end, so if you use `load-file` instead you might need to do `(enable-theme 'foo)`.
You might also like the theme `calmer-forest` in melpa.
---
Tags: themes
--- |
thread-66652 | https://emacs.stackexchange.com/questions/66652 | Wrap all emacs key-bindings ... override command loop? | 2021-07-11T02:42:41.193 | # Question
Title: Wrap all emacs key-bindings ... override command loop?
**---+ 1: BRIEF:**
How can I wrap all or almost all key-bindings? Both those already defined, and those that will be defined in the future? E.g. can you point me to code that overrides the command loop completely? Or is there a better way?
By "wrap" I mean leave all key-bindings in their keymaps, So that any existing keymap manipulation code continues to work. Possibly require a prefix to access all such key-bindings. And override the un-prefixed versions of such key bindings. Possibly dynamically
I will explain why I think I need this below.
**---+ 2: LESS BRIEF:**
How can I "wrap" ALL (or almost all) key-bindings? i.e. is there any existing code that I can be pointed to that wraps all key-bindings?
Not just those defined at the time I run or install my code, i.e. key-bindings defined in the past, but also those defined in the future, after the wrapping code has being run or started or installed.
By "wrap" I mean something like
- if the wrap code were not running or installed and there is a keybinding K1 ... Kn
- then if the wrap code is installed
* K1 ... Kn does NOT map to its original binding
* but SOME-PREFIX K1 ... Kn does
Well, actually, in the "wrapped" mode I might like behaviors such as the following:
(W0) none of the wrapped mode K1...Kn sequences map to the original non-wrapped mode key-binding.
(W-1) some but not all of the wrapped mode key sequences might map to the original non-wrapped mode key-binding, they might do nothing, or they might map to other commands
(W+1) possibly all wrapped mode key sequences K1...Kn map to the original non-wrapped mode key-binding. which would be exactly the same as if the key-binding wrapping package or command loop were not installed, except for one or a few commands to change between wrapping modes (W0), (W-1), and (W+1).
**=== TL; DR ===========**
If I have been clear enough above , it should be possible for you to **stop reading here**. I believe that I have described the questions in sufficient detail. The remaining stuff below is (a) to explain I want to this (speech recognition and better ergonomics), (b) will explain why some approaches are unsatisfactory, that have been suggested in answers and also tried by me years ago, (c) to mention that I have started investigating modal packages like ErgoEmacs, Evil, and Boon, but they seem overkill and in any case I seek advice as to which might be simplest to start with, etc.
---+ 3: Unsatisfactory Approaches
---+ 3.1: Sliding in new keymaps
Some have suggested sliding in new keymaps that refer to the old keymaps in the standard keymaps' names. E.g.
```
(let ((new-global-map (make-sparse-keymap)))
(define-key new-global-map (kbd "C-x") global-map)
(setq global-map new-global-map))
```
This is unsatisfactory for several reasons, including
1. It only applies to key-bindings that were created at the time this code was run. key-bindings created later will be made in the `new-global-map`
2. Although simple enough for `global-map`, it is more awkward for other maps such as `local-map`, `minor-mode-map-alist`, `overriding-local-map`, etc.
3. Things break if the map wrapping code must know about the maps is overriding. E.g. when I first wrote such code IIRC the `overriding-local-map` did not exist and the minor mode math being reworked. Maintenance hassle.
---++ 3.2 Overriding the Command - Good or Bad?
Therefore it seems to me that overriding the command loop might be better: reading the next key symbol, and performing lookups or not according to what that symbol is but leaving all of the existing all of the existing emacs search code modified.
Assuming that the existing emacs Emacs search code is as described in https://www.gnu.org/software/emacs/manual/html\_node/elisp/Searching-Keymaps.html
```
(or (if overriding-terminal-local-map
(find-in overriding-terminal-local-map))
(if overriding-local-map
(find-in overriding-local-map)
(or (find-in (get-char-property (point) 'keymap))
(find-in-any emulation-mode-map-alists)
(find-in-any minor-mode-overriding-map-alist)
(find-in-any minor-mode-map-alist)
(if (get-text-property (point) 'local-map)
(find-in (get-char-property (point) 'local-map))
(find-in (current-local-map)))))
(find-in (current-global-map)))
```
then wrapping that code within (non-elisp pseudocode)
```
e <-- read-event
IF (and (printable e) disable-key-sequences-starting-with-printable-characters)
THEN (self-insert e)
ELSE
unget e ;; Push it back so that the original lookup can be done
... the original lookup code above ...
```
This solves most of the problems with sliding in a new key map in place of an old.
However, overriding the EMACS command loop is considered undesirable, as is done by ErgoEmacs, discussed in "Start ergoemacs command loop" is blocking Emacs
On quick look the ErgoEmacs looks messy and fragile. Full of references to other packages such as `icicle` and `ispell`, with the command loop code intermixed with things like colors and blink-rate. Avoiding such dependencies is IMHO the bigger reason to consider overwriting the command loop. At the very least ErgoEmacs is doing much more that I want, and since I am lazy and would appreciate advice on how to spread things out.
In any case, what is the most elegant way to override the command loop?
---++ 3.3: Comparing Modal packages for EMACS
What I am asking for is a particular modal interface for EMACS. A particularly simple mobile interface for EMACS. Possibly similar to modal packages like `evil` and `boon`, and possibly `ergoemacs`.
But, again, these packages do a lot, whereas I think I am looking for something much simpler.
Also, I am not at all certain that these packages provide full access to legacy keybindings.
---++ 3.3: Is There a Better or Best Known Way (BKM) to Do This?
I therefore ask questions such as:
Q1: is there a better way to get the "wrapping" behavior that I describe? better than overwriting the command loop.
Q2: as always, real code appreciated?
Q3: is ErgoEmacs approach the BKM? even if it has problems such as question referred to
**---+ 4: WHY I THINK I WANT THIS**
Note: I say "I think I want this" because I am open to the possibility of some other solution. But I also expect the usual misunderstandings.
There are at least two reasons why I want this, the most recent reason probably being more acceptable, and a historic reason that I have wanted this since the 1980s. I've lived without it so far, but the new reason is harder to work around not having this wrapping mode for key-bindings.
Reasons:
(1) speech recognition, want to avoid accidental emacs command invocation on misrecognitions
(2) ... I'll explain this original reason later ...
---++ 4.1: SPEECH RECOGNITION
In the original post of this question I provided much too much detail, which I have moved to https://github.com/AndyGlew/manx-UI--Speech/wiki/Speech-Commands-for-EMACS
Briefly, I want to use speech recognition to control EMACS. Nuance Dragon speech recognition accuracy is IMHO good enough. The real problem is trying to control EMACS via keyboard and mouse events (so don't do that), and interference with existing emacs key-bindings.
The big problem with automating nearly any WIMP application is controlling it by sending key and mouse events. Especially when the key and mouse command bindings are highly context-sensitive, and when the speech system cannot determine what the present context is.
Fortunately, EMACS can be controlled by commands: `esc-X some-command [enter]`. Although many emacs commands are not convenient to say by voice, this problem can be solved.
The second problem is interference with existing emacs key-bindings. For the most part I do not want to completely disable all emacs key-bindings. I can still type; I just want to reduce my typing is more I type more I hurt. In Dragon I usually use "normal mode", where dictation and speech commands are intermixed.
Unfortunately speech recognition is imperfect, and occasionally "foo" is interpreted as "bar". This is not so bad if dictating text, ordinary printable characters. But in packages like the Gnus mailreader, if the user interface binds commands to unmodified keystrokes, bad things can happen.
This problem is not specific to EMACS. e.g. Thunderbird is a similar vendor, so much so that I actually disable unmodified letters in the main Thunderbird window. But it is a pain to turn such a letter chill mode on and off.
It should be possible to do better with EMACS. in the terms are used above:
A (W0') mode, adapted so that any key sequence that begins with an unmodified letter is restricted, But he sequences that begin with modifiers such as control or meta- are allowed. This is how I might normally work, intermixing dictation of ordinary text and modified key sequences, with the option of escaping to legacy key sequences that have been disabled to avoid interference with speech.
Plus the (W+1) mode that is essentially legacy EMACS key-bindings.
---++ 4.2: an older reason
I admit to an older reason to want to do this wrapping: I have had this computeritis for years. It got suddenly worse when I first started using EMACS, because as I'm sure you know emacs key-bindings use lots and lots of modifiers. Typing those is a really big cause of my computeritis/repetitive motion syndrome/Repetitive stress injury/... even RMS (Stallman) has had RMS/RSI.
Therefore many years ago I created my own set of key-bindings or emacs that are less stressful on my hands. In many ways they are much like VI's key-bindings, where the most frequent commands are often just the same letter pressed over again, possibly with slightly different modifiers. I did not completely reimplement VI, but I broke many of the rules for emacs key-bindings in much the same way that evil-mode now does.
Hence, the desire to completely wrap key-bindings defined by packages other than my own. I want to still access, with the prefix, or if I disable my mode. Yada yada yada
---+ 5: Mouse Bindings
Interestingly, I have much less need to override or wrap mouse findings. speech recognition errors usually do not emit mouse events by accident
---+ 6: pontificating: separate functionality from user interface
IMHO it is unfortunate that many emacs packages intermix the functions and the key-bindings. In my own packages I try to separate the code that does stuff from the user interface. I might have separate .EL files, or I might have a function that installs my normal bindings. If you don't want my bindings, you can still load my library, just not run my key-bindings function.
# Answer
partial solution
* not necessarily to the question of how to wrap all emacs key-bindings, whether by overriding the command loop or some other way
* but a solution to the 1st use case I listed in the original question --- which I subsequently removed because the 1st responder said it was too much detail, to discursive
One of my big problems with speech recognition and emacs is that for the most part Dragon controls target applications by sending keyboard and mouse events. Fortunately in emacs I can send commands via M-X, but there remain problems: In particular it causes a big problem when a Dragon speech command targeting emacs is misrecognized as dictation, emitting ordinary unmodified letters, in an emacs mode like the Gnus mailreader where many commands do not have modifiers.
also, certain Dragon ordinary dictation words are Unicode, and at the very least are interpreted as repeat counts on emacs commands and letters, but also occasionally as modifiers. similarly for some unknown reason certain keystrokes from Dragon have bit 8 set.
I wanted to wrap emacs key mappings to ignore keystrokes related to some of these errors. I have not yet found any satisfactory solution within emacs.
But in my original post I mentioned that in Thunderbird I have created an AutoHotKey script that disables all unmodified letters in the main Thundebird window, since Thunderbird has the same problem with unmodified keyboard shortcuts.
This solution was not working for GNU emacs, because Dragon has limited knowledge of application context, based mainly on the window title. I have already modified my .emacs to put the major mode in the window title, but that does distinguish between when I want to send dictation and when I do not.
Doh!
I just realized that I can have emacs code, perhaps a minor mode, that indicates whether emacs command/key-bindings other than M-X or the like are allowed by modifying the window title. And I can have an AutoHotKey command that does letter telling based on that window title context.
Doh! once again, the solution to a Dragon speech recognition problem and a target at is to do it in AutoHotKey.
---
This does not immediately solve the 2nd use case for such keystroke lookup ramping in emacs, where I want to completely override the standard mappings but still have them accessible, in such a way that subsequent legacy key-bindings still work.
... although I'm brainstorming about ways of using AutoHotKey to accomplish the 2nd use case as well.
---
I may let this Q&A into 2 parts, one with this partial answer, and the original question about wrapping keyboard mappings in emacs. even if it is possible to use AutoHotKey to solve the problem completely, I would prefer to have a purely emacs solution, not least because AutoHotKey is not available on Linux (and I would prefer not to have to create a TTY driver that does the same thing - although I have long wanted AutoHotKey functionality on Linux and Mac OS - and I wrote such a TTY driver a long time ago in a galaxy far far away).
for the moment, I am going to mark this question as answered, even though it is only partially answered -- since StackExchange has no way of indicating such a partial answer. When I have refactored the question, I will rearrange the checkmark status.
---
BTW, this was not a setup so that I could do a self answer question. I truly had not figured out how to do this AutoHotKey partial solution, until just a few minutes ago. Doh!
> 0 votes
# Answer
Your question seems discursive and poorly organized, but I think that I understand the gist of it. It also contains some errors that I presume result from using voice recognition.
I think that you want to add a prefix to all keys.
You should read chapter 22 Keymaps of the Emacs Lisp manual for all of the details, but perhaps you could do something like this:
```
(let ((new-global-map (make-sparse-keymap)))
(define-key new-global-map (kbd "C-x") global-map)
(setq global-map new-global-map))
```
This replaces the global key map with a new keymap containing only a prefix key which allows access to the original global map. However, this will not entirely work because `global-map` is not the only active keymap. See chapter 22.7 Active Keymaps for the details, but basically the major and minor modes all have keymaps too. You would need to modify them all in the same way.
You might also look into modifying how Emacs searches these maps; it may be easier to add your global prefix there than it is to modify every single keymap for every single minor mode. An overview of that process is given in chapter 22.8 Searching the Active Keymaps, but you will need to read the Emacs source for the full story.
Good luck!
> 0 votes
---
Tags: key-bindings, evil, ergoemacs
--- |
thread-61225 | https://emacs.stackexchange.com/questions/61225 | How to loop over keymaps and assign keys? | 2020-10-16T01:10:14.880 | # Question
Title: How to loop over keymaps and assign keys?
If I have a key binding I want to apply to multiple keymaps, for example.
```
(evil-define-key 'visual c-mode-map (kbd "C-M-?") 'c-comment-from-c++)
(evil-define-key 'visual c++-mode-map (kbd "C-M-?") 'c-comment-from-c++)
(evil-define-key 'visual glsl-mode-map (kbd "C-M-?") 'c-comment-from-c++)
```
I tried putting the keymaps into a list and calling `evil-define-key` with each but it didn't work.
eg:
```
(dolist (this-map (list c-mode-map c++-mode-map glsl-mode-map))
(evil-define-key 'visual this-map (kbd "C-M-?") 'c-comment-from-c++))
```
Is this possible?
# Answer
In this kind of situation it's useful to use the function equivalent of whatever macro you're wrestling with, `evil-define-key*`. Note that this evaluates the keymap argument instead of deferring it to a later point, so I've adjusted your code to be run after the maps have been defined for `c-mode` and `c++-mode`:
```
(with-eval-after-load 'cc-mode
(dolist (this-map (list c-mode-map c++-mode-map))
(evil-define-key* 'visual this-map (kbd "C-M-?") 'c-comment-from-c++)))
```
> 1 votes
# Answer
(You don't say what you mean by *"it didn't work"*. Error?)
I don't use Evil, and I don't have its source code. So this probably won't help. Anyway...
Googling a bit, this doc page says that `evil-define-key` is a *macro*, not a function, which means it doesn't necessarily evaluate all of its arguments, and it returns Lisp code (the macro expansion), which then gets evaluated.
Even though it's a macro, that doc page indicates that it does evaluate all of its args (*"The remaining arguments \[besides `STATE`\] are like those of define-key"*, which is a function), so it's not too clear why it's a macro. Presumably it does something else. (Or maybe that statement is just false.)
On the other hand, that page also kinda suggests that the `KEYMAP` argument is *not* evaluated, because it says *"Note that foo-mode-map is unquoted, and that this form is safe before foo-mode-map is loaded."*. So to me at least, that doc is not too clear.
A guess is that `KEYMAP` is not evaluated, which would mean that `evil-define-key` expects a keymap variable, that is, a *symbol*, for `KEYMAP`. That would explain why your code wouldn't work: because you're passing the *values* of those keymap variables, not the variables (symbols) themselves, to `evil-define-key`.
(Note that `define-key` does *not* accept a keymap variable as arg; it accepts only a keymap, that is, the value of a keymap variable, as arg.)
If this guess is correct, you could try quoting the keymap symbols: instead of `(list c-mode-map c++-mode-map glsl-mode-map)`, try `'(c-mode-map c++-mode-map glsl-mode-map)`.
Another thing that suggests this interpretation is the doc string mention that you can pass a quoted symbol instead of a keymap or keymap symbol, in which case the quoted symbol indicates a mode. This is no proof, but it does suggest that the arg isn't evaluated first.
Just a wild guess. No doubt some Evil user or someone with the definition of `evil-define-key` will give you a good answer.
(This answer might also help a bit. Dunno.)
---
OK, I found the source code and took a very quick peek at the definition of macro `evil-define-key`.
It seems you can pass either an (unquoted) keymap variable (symbol) or its value, and that evaluation is delayed in either case. My quick peek didn't tell me just what the problem is with your code, however...
> 0 votes
# Answer
Posting an answer since this is the final solution I came up with.
It uses macros to avoid duplication, defining a macro `evil-define-key-for-cc-modes` that handles the details.
```
(defmacro evil-define-key-with-modelist (state-arg mode-list-arg key-arg action-arg)
`
(let ((state ,state-arg)
(mode-list ,mode-list-arg)
(key ,key-arg)
(action ,action-arg))
(dolist (mode-item mode-list)
(evil-define-key* state mode-item key action))))
(defmacro evil-define-key-for-cc-modes (state-arg key-arg action-arg)
`
(progn
(with-eval-after-load 'cc-mode
(evil-define-key-with-modelist
,state-arg
(list c-mode-map c++-mode-map)
,key-arg
,action-arg))
(with-eval-after-load 'glsl-mode
(evil-define-key-with-modelist ,state-arg (list glsl-mode-map) ,key-arg ,action-arg))))
```
Example usage:
```
(evil-define-key-for-cc-modes 'visual (kbd "C-/") 'c-comment-from-cxx)
```
> 0 votes
---
Tags: key-bindings, evil
--- |
thread-64644 | https://emacs.stackexchange.com/questions/64644 | orgmode sync beamer with header in orgmode file | 2021-05-01T05:37:13.690 | # Question
Title: orgmode sync beamer with header in orgmode file
I am creating my beamer presentations with orgmode and convert the file to tex and pdf when saving. This works quite fine.
What I am looking for is that the pdf (seen inside emacs with pdfview/pdf-tools) file syncs the slide number which is shown with the corresponding header I am having my cursor on.
Does someone have a hint how to achieve this?
I am using spacemacs-develop (but Ithink that this is not so relevant here).
Thank you in advance!
# Answer
The org-noter package keeps your notes in sync with the PDF, so I'd start there.
You could also write a command that (1) moves the cursor to the next heading and (2) visits the PDF and skips to the next slide/page.
> 0 votes
---
Tags: org-mode, pdf-tools
--- |
thread-66719 | https://emacs.stackexchange.com/questions/66719 | org-capture template does not replace the date placeholder or use the correct level | 2021-07-16T17:15:50.277 | # Question
Title: org-capture template does not replace the date placeholder or use the correct level
I'm trying to create an org capture template that will just insert a second level point: `"** 2021/07/16"` (or whatever the current date is).
I expect this setq example to do that:
```
(setq org-capture-templates
'(
("d" "Daily" entry (file "~/notes/daily.org") "** %Y/%m/%d %?")))
```
However what it inserts instead is:
```
* %Y/%m/%d
```
(first level point instead of second level, and the literal %Y etc instead of the date)
This is based on (probably a poor) reading of org-capture examples with slight adjustment. I have at most a basic understanding of org mode and emacs so please feel free to explain any principles that I've missed.
I'm also using spacemacs, in case that is relevant. This `setq` command is inside my `defun dotspacemacs/user-config`.
# Answer
`org-capture-templates` probably has the densest doc-string of any variable. The way I deal with it is figure out what I need to do, do it once and then *never* change it :-) The downside is that when I need to change it, I find that I've forgotten everything so I need to start from scratch. But after doing it a dozen times or so, the relearning gets faster and easier. In short, hang in there!
For the time stamp, you can either use `%t` which provides the date in ISO format, or you can use `%<%Y/%m/%d>` as the doc string of `org-capture-templates` describes:
> %\<...\> The result of format-time-string on the ... format specification.
The level at which the capture is entered for an `entry` type is again described in the doc string:
> ... Will be filed as the child of the target entry or as a top-level entry.
Since you are not using a target entry, it is filed as a top-level entry, no matter how many stars you put in the template. See the `target` description in the doc string.
You could create a top-level headline, say `* My daily thoughts` in your file and then use
```
... (file+headline "~/notes/daily.org" "My daily thoughts") ...
```
instead of the plain `file` entry: the captures would end up under that headline.
There is plenty more in the doc string to keep you busy for a while. Start simple, experiment, ask questions: you'll get there.
BTW, to get the doc string of the variable, do
```
C-h v org-capture-templates
```
and if you don't know yet how to use the emacs help system, do `C-h ?` and learn how to use it ASAP!
> 3 votes
---
Tags: org-mode, spacemacs, org-capture
--- |
thread-66722 | https://emacs.stackexchange.com/questions/66722 | Is there a way to automatically indent a parenthesis in Slime REPL after pressing `C-m o`? | 2021-07-16T21:32:41.250 | # Question
Title: Is there a way to automatically indent a parenthesis in Slime REPL after pressing `C-m o`?
I am using Slime, Paredit, and SBCL to code in Common Lisp. While editing a `.lisp` file, suppose I have this code:
```
(dotimes (i 4))
```
I will represent the cursor (point) as -!-. Having the cursor in this position and pressing `return` key I get:
```
(dotimes (i 4) -!-)
;;; press `return`
(dotime (i 4)
-!-)
```
I would like to have the same in the SLIME Repl. There, if I have:
```
CL-USER> (dotimes (i 4)-!-)
;; after pressing `return` the expression is evalued
NIL
```
I can use `C-o`. However, `C-o` gives a new line but with no indentation, such as:
```
CL-USER> CL-USER> (dotimes (i 4)-!-)
;; after pressing `C-o`, I have:
CL-USER> CL-USER> (dotimes (i 4)
-!-)
```
Is there a way to get a new line but with a properly indented parenthesis? Another command maybe? Should I insert something on my init files?
Thanks
# Answer
`C-j` runs `slime-repl-newline-and-indent` which I think will work. Whenever I'm faced with an unfamiliar mode, I do `C-h m` which shows me mode information, including the keymaps: I can then zero in on the relevant function(s). That's how I found this.
The doc string of `slime-repl-newline-and-indent` says:
> Insert a newline, then indent the next line. Restrict the buffer from the prompt for indentation, to avoid being confused by strange characters (like unmatched quotes) appearing earlier in the buffer.
> 2 votes
---
Tags: indentation, newlines, repl, slime
--- |
thread-66716 | https://emacs.stackexchange.com/questions/66716 | Ignore file encoding in diff | 2021-07-16T15:19:28.473 | # Question
Title: Ignore file encoding in diff
My magit diff is full of "differences" where there is no visually discernible change.
I've adjusted every Magit Diff Option. Configuring magit to ignore line endings, tabs, whitespace, and indentation doesn't silence the noise, so I conclude those aren't the culprit.
My init forces UTF-8:
```
(prefer-coding-system 'utf-8)
(set-default-coding-systems 'utf-8)
(set-terminal-coding-system 'utf-8)
(set-keyboard-coding-system 'utf-8)
(set-language-environment "utf-8")
```
I should be good, right? Apparently not. The encoding of init.el on my Windows machine is UTF-8-**dos** whereas on my GNU machine is UTF-8-**unix**. I conclude that this is the source of the noise.
I understand the problem to be with how each Git repo/clone is configured per system. It looks like the filter option of `.gitattributes` might resolve future problems. However, that looks to only work for checkouts; I don't think it does anything for the immediate problem of "I want to commit some changes right now".
It's probably silly to ask how to "ignore encodings", but I'm not an expert in how encodings function. Frankly, I don't care beyond understanding, *"how can I silence the noise so that I can see the meaningful differences and just make the commit?"*
# Answer
Magit doesn’t generate these diffs. Instead Git creates the diffs and Magit only presents them. It looks like the diff you are seeing is happening because the line endings have changed, or possibly the other whitespace in the line has changed (tabs to spaces, for example).
You might be able to change how the diffs are presented (for example by turning on whitespace mode and configuring it to use visibly distinct glyphs for spaces and tabs, but there’s little that you can do about the line–ending problem. The diff format doesn’t even include the original line endings from the file; all the line endings are replaced with whatever Git thinks is correct for your platform.
There are two avenues you should explore. The first is to configure git to always checkout files using a consistent choice of line–ending character on all platforms. For example, you could configure it to always use LF or always use CRLF, whichever you prefer. You may have configured Emacs to prefer one line ending over the other, in which case changing the git config to match that preference would simplify the problem. Consult the Git documentation about the .gitattributes file for more information about how to do this.
The other alternative is to leave the Git configuration alone, and reconfigure Emacs. Git’s default behavior is to convert all line endings in text files to the default line–ending character for the current platform. So if you commit a file with LF as the line–ending character and then check it out on Windows, Git will write the file to disk with CRLF characters in their place. There are a number of ways to configure Emacs, so I recommend reading chapter 22.6 Recognizing Coding Systems in the Emacs manual (also available inside Emacs type `C-h i` to open the Info viewer).
Since the default Emacs behavior is to mimic the line endings already in the file, it may be the case that the file already had mixed line–ending characters and Emacs’ guessing is making the problem worse. If that is the case, I recommend making the file (or files) consistent before continuing. Go to your Linux computer and run `dos2unix` on all affected files, then commit any changes that result. (There are ways to do that same cleanup in Emacs, of course, but `dos2unix` is easier. Naturally you are unlikely to have it installed on your Windows machine.)
Of course this is all a lot more complex than it really needs to be. Honestly it’s a wonder that our computers even work.
> 2 votes
---
Tags: magit, git
--- |
thread-66708 | https://emacs.stackexchange.com/questions/66708 | How to format cells of Orgmode table with colors according to its string? | 2021-07-15T16:58:41.147 | # Question
Title: How to format cells of Orgmode table with colors according to its string?
I want to have one-page-calendar as orgmode table, but I can't figure out how to add background colors on cells (in orgmode buffer not exported files).
Here is the calendar, I want to at least make cells which have "Sat" and "Sun" has blue background color. Would be better if the background color could be formatted almost same as that website (light gray for days, light blue for Mon/Tue/Wed/Thu/Fri, Blue for Sat/Sun).
```
* One page calendar 2021
| | | | | | Feb | Jun | Sep | Apr | Jan | May | Aug |
| | | | | | Mar | | Dec | Jul | Oct | | |
| | | | | | Nov | | | | | | |
|---+----+----+----+----+-----+------+-----+------+-----+-----+-----|
| 1 | 8 | 15 | 22 | 29 | Mon | Tue | Wed | Thu | Fri | Sat | Sun |
| 2 | 9 | 16 | 23 | 30 | Tue | Wed | Thu | Fri | Sat | Sun | Mon |
| 3 | 10 | 17 | 24 | 31 | Wed | Thu | Fri | Sat | Sun | Mon | Tue |
| 4 | 11 | 18 | 25 | | Thu | Fri | Sat | Sun | Mon | Tue | Wed |
| 5 | 12 | 19 | 26 | | Fri | Sat | Sun | Mon | Tue | Wed | Thu |
| 6 | 13 | 20 | 27 | | Sat | Sun | Mon | Tue | Wed | Thu | Fri |
| 7 | 14 | 21 | 28 | | Sun | Mon | Tue | Wed | Thu | Fri | Sat |
```
It should be able to be done similar like this one by eval elisp codes, I can't figure it out how to format it for specified strings.
# Answer
> 3 votes
For this simple case, and if your table is the only text in your buffer, then you could just use the `search-forward` function e.g.:
```
(defun org-table-format-cells ()
(interactive)
(dolist (x '("Sat" "Sun"))
(goto-char (point-min))
(while (search-forward x nil t)
(let ((overlay (make-overlay (match-beginning 0)
(match-end 0))))
(overlay-put overlay 'face '(background-color . "blue"))))))
```
You can get a list of colors and their names with `list-colors-display`.
For the more general case (working in any org buffer), you could use the Org Element API:
```
* One page calendar 2021
#+name: item-prices
| | | | | | Feb | Jun | Sep | Apr | Jan | May | Aug |
| | | | | | Mar | | Dec | Jul | Oct | | |
| | | | | | Nov | | | | | | |
|---+----+----+----+----+-----+------+-----+------+-----+-----+-----|
| 1 | 8 | 15 | 22 | 29 | Mon | Tue | Wed | Thu | Fri | Sat | Sun |
| 2 | 9 | 16 | 23 | 30 | Tue | Wed | Thu | Fri | Sat | Sun | Mon |
| 3 | 10 | 17 | 24 | 31 | Wed | Thu | Fri | Sat | Sun | Mon | Tue |
| 4 | 11 | 18 | 25 | | Thu | Fri | Sat | Sun | Mon | Tue | Wed |
| 5 | 12 | 19 | 26 | | Fri | Sat | Sun | Mon | Tue | Wed | Thu |
| 6 | 13 | 20 | 27 | | Sat | Sun | Mon | Tue | Wed | Thu | Fri |
| 7 | 14 | 21 | 28 | | Sun | Mon | Tue | Wed | Thu | Fri | Sat |
#+begin_src emacs-lisp :results silent :var table=item-prices
(defun org-element-example ()
(interactive)
(let* ((tree (org-element-parse-buffer))
(tables (org-element-map tree 'table 'identity)))
(org-element-map (car tables) 'table-cell
(lambda (x)
(when (or (string= (car (org-element-contents x)) "Sat")
(string= (car (org-element-contents x)) "Sun"))
(let ((overlay (make-overlay (org-element-property :contents-begin x)
(org-element-property :contents-end x))))
(overlay-put overlay 'face '(background-color . "blue"))))))))
#+end_src
;; Local Variables:
;; eval: (org-babel-execute-buffer)
;; eval: (add-hook 'org-ctrl-c-ctrl-c-hook 'org-element-example nil t)
;; End:
```
After saving this code in a file, then after opening the file, and with the cursor on the table, you can format the table by pressing `C-c C-c` (this is just to copy the style of the answer you referred to).
But generally I assume you prefer to put the emacs-lisp code in your `.emacs.d` file and then define a file variable by adding the following line to the beginning of your org-file:
```
;; -*- eval: (org-element-example) -*-
```
Alternatively, you probably could use `org-table-map-tables` directly.
---
Tags: org-mode
--- |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.