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-66166 | https://emacs.stackexchange.com/questions/66166 | How to get immediate visual feedback of keys I type? | 2021-06-05T11:32:48.273 | # Question
Title: How to get immediate visual feedback of keys I type?
I would like to get some immediate strong visual feedback for the commands I enter in emacs. For example, I would be happy if any key sequence (beginning with a modifier key) that I type appeared in large red letters in the centre of the current frame. Is there any package that does this?
(Currently, the key sequences only appear in the minibuffer, and with some delay. My problem is that I sometimes involutarily insert random letters in my documents because I accidentally press just `s` instead `C-s` etc. I'm hoping that stronger visual feedback might make me aware of most instances of such mistakes. I know there are nameless other editors with safeguards against this kind of "typo", but that's a different question.)
**Clarification:**
* By **immediate**, I mean that I would ideally like to see something as soon as I press a control/meta key. If "C-x" shows up once I've pressed down "C" and hit "x", that's maybe also ok. But I don't want to wait until I've type out "C-x s".
* I only want a feedback signal for **command sequences**, not for every letter I type. Starting from Drew's answer below, I've now found a couple of packages for creating screen casts, e.g. keystroke or keypression. However, just as showkey, they show all keyboard strokes, including the trivial ones.
* By "frame", I meant active "**window**"/subframe. I would like to see a visual signal in the currently active "window"/subframe.
# Answer
Library **`showkey.el`** (code) gives you what you request, I think.
It defines two global minor modes, which give you two ways to show keys you type:
* **`showkey-tooltip-mode`** – Show only the last key used, in a *tooltip*. This is refreshed with each such event. By default, it uses large red characters, just as you request.
* **`showkey-log-mode`** – Show a *log* of such events, in a separate frame. It is refreshed with each new event, and it is kept on top of other frames without stealing the input focus.
Some user options control the behavior:
* `showkey-tooltip-ignored-events` and `showkey-log-ignored-events` are each a list of regexps to match against events that you *do not want to show*.
* `showkey-tooltip-sleep-time` is the number of seconds to pause while showing the tooltip (zero by default).
* `showkey-tooltip-timeout` is the number of seconds to show the tooltip, before hiding it. It's also hidden upon any user event, such as hitting another key, but it's always shown for at least `showkey-tooltip-sleep-time` seconds.
* `showkey-log-frame-alist` is an a list of frame parameters for the logging frame.
* `showkey-log-erase-keys` is a list of keys that restart logging (erase the log and start it over). For example, if you add `RET` key to it (`?\r`) then each time you press `Enter` the log is restarted from scratch.
> 3 votes
---
Tags: help, keystrokes, logging, tooltip
--- |
thread-65069 | https://emacs.stackexchange.com/questions/65069 | Helm installing issues | 2021-05-29T11:05:14.727 | # Question
Title: Helm installing issues
I am trying following a book (Mastering Emacs) and right now stuck on a section about working with Helm. I tried to install through various means, listed there, and found online, my last attempt was with "straight.el" package manager. My current init.el file has only 1 line related to the helm, which is
```
(straight-use-package 'helm)
```
After restarting and seeing that there were no issues on launch, I tried to call basic helm command, helm-M-x and i got an error.
> Symbol’s value as variable is void: while-no-input-ignore-events
Which I also had when trying to install the helm through regular "package-install". I went for helm wiki and found the trick after installing about opening the terminal, going to the helm folder inside .emacs.d, and trying to launch the terminal command 'emacs-helm.sh'. I tried so and got back
> emacs-helm.sh: command not found
in both Emacs and outside Ubuntu terminals. I tried also to sudo snap install helm --classic, but installing helm through it didn't help, the command was still not "found". From my understanding, if "emacs-helm.sh" doesn't work that's the starting point that should be attempted to be fixed. Can someone recommend how to deal with this issue and what should be my logic when I am trying to debug such problems with packages?
# Answer
This might be a workaround for an underlying bug, but adding this to my `.emacs` fixed this for me:
`(setq while-no-input-ignore-events '())`
> 2 votes
# Answer
If you are a new user of Helm, then you can find new set of manuals here https://emacs-helm.github.io/helm/doc/index.html.
I found the manuals to be bit dry, and little unorganized. However, they cover lots of ground.
If you would like to browse the manual from within Emacs, download the tar file located at https://emacs-helm.github.io/helm/doc/helm-static-pages.tar. Once you untar it, you will see a bunch of `info` files in the `doc/` directory. You can browse the info files with `C-u C-h i doc/helm.info`
These Helm manuals are very new, and they were announced in the Emacs Tangents mailing list a month or so ago. Here is the link to the announcement https://lists.gnu.org/archive/html/emacs-tangents/2021-05/msg00001.html.
Since the manuals are new, it is possible that Helm's github repo has an improved set of these.
> 0 votes
---
Tags: helm, package
--- |
thread-20187 | https://emacs.stackexchange.com/questions/20187 | Organize the buffer list? | 2016-02-09T22:08:14.277 | # Question
Title: Organize the buffer list?
When you have many buffers opened, they are all shown in the buffer list.
Are they shown in the order of visit, from the latest to the remotest?
Can we organize the buffers in the buffer list somehow? For example resort them by their pathnames?
# Answer
I assume you are referring to the list of buffers you get with the default key binding `C-x C-b`, which calls `list-buffers`. That command uses `Buffer-menu-mode` which provides some key bindings for working with the list but has limited options for sorting or filtering. For more detail on what you can do in the list, try `C-h f Buffer-menu-mode`.
Emacs includes a more powerful buffer list that you may prefer: `ibuffer`. This mode provides a similar list of open buffers, but with additional capabilities for sorting, filtering, grouping, and otherwise working with the list. You can try it out with `M-x ibuffer`, and if you like it you can add this to your Emacs init file to use ibuffer instead of the default list-buffers command:
```
(global-set-key (kbd "C-x C-b") 'ibuffer)
```
The easiest way to get started with ibuffer is to explore the menu. Look under 'View' for options to sort, filter, and mark buffers.
> 16 votes
# Answer
Use `C-h m` in the buffer-list buffer to get answers to these questions and more. You can click the header of a column to resort entries by that column. Click it again to reverse. To sort by pathname, click header `File`.
If you don't have a mouse then move the cursor under the column you want to sort and use `S` to sort it. Repeat to reverse the direction.
If you use `C-h m` then near the beginning of the description of the mode you see *See `buffer-menu` for a description of its contents.* Follow that link (using `RET`, aka *Enter*) to see more info about the mode.
Near the end of that page of information you see this: *See `Buffer-menu-mode` for the keybindings available the Buffer Menu.* If you follow that link then near the top of the next page of info (about `Buffer-menu-mode`) you see this: *Parent mode: `tabulated-list-mode`.* If you follow that link, to see info about the parent mode, there you will see additional keys that are available in `Buffer-menu-mode` \- keys that are not specific to it but are provided by its parent mode, `tabulated-list-mode`.
Among those key descriptions you see this:
```
S tabulated-list-sort
```
That tells you that the key `S` runs command `tabulated-list-sort`. If you follow that link then you see this:
```
tabulated-list-sort is an interactive compiled Lisp function in
`tabulated-list.el'.
(tabulated-list-sort &optional N)
Sort Tabulated List entries by the column at point.
With a numeric prefix argument N, sort the Nth column.
```
It's a bit roundabout, but this tells you that *if you put the cursor (* **point** *is the cursor position) in a given column and you hit `S` then you will sort the buffer according to that column*.
The main lesson is that `C-h m` gives you information about the current mode, whatever mode you are in. In that description, you can follow links to get more information.
> 6 votes
# Answer
With M-x ibuffer one can filter on pathname components. The commands I use are
```
/f filter using part of full pathname
// filter off
/g create named filter group and move group to top of ibuffer
C-k RET kill filter group (the one under the cursor)
C-y RET yank filter group
```
The above recipe does not completely answer the question, since it is not possible (AFAIK) to place the files/buffers of the latest filter group at the top of the ibuffer after killing the group.
> 0 votes
---
Tags: buffer-list
--- |
thread-66169 | https://emacs.stackexchange.com/questions/66169 | From an org item, launch a shell command with the item text as parameter | 2021-06-05T13:47:46.997 | # Question
Title: From an org item, launch a shell command with the item text as parameter
From an org list item, I want **a function that I can bind** to a *shortkey* or an *`org-speed` shortcut*, to be able to launch a shell command with the **org list item text as parameter**. Then I want to add tag to the item
```
* item one
* item I two ← caret is here
* item three
```
I want to launch a command shell like
```
./my_command "item two" ← this is returning a short uuid
```
then adding a tag
```
* item one
* item two :b7acda1e: ← the tag added from previous command line
* item three
```
I'm not a elisp developer, but they told me \`org-element could help here
# Answer
There are three things to do, so we write a function for each:
* get the headline text
* run the command with the headline text as argument
* add the result as a tag to the headline
```
(defun ndk/headline-text ()
(let* ((el (org-element-at-point))
(typ (org-element-type el)))
(when (eq typ 'headline)
(plist-get (cadr el) :raw-value))))
(defun ndk/run-my-command (arg)
(unless (null arg)
(shell-command (concat "/tmp/command" " " arg))
(with-current-buffer shell-command-buffer-name
(buffer-substring-no-properties (point-min) (point-max)))))
(defun ndk/insert-tag (tag)
(unless (null tag)
(let ((tags (org-get-tags)))
(unless (member tag tags)
(org-set-tags (cons tag tags))))))
(defun ndk/do-it ()
(interactive)
(ndk/insert-tag (ndk/run-my-command (ndk/headline-text))))
```
The `ndk/do-it` command then just composes the three functions. You can bind it to a key if you want:
```
(define-key org-mode-map "C-c t" #'ndk/do-it)
```
You will need to customize the path to your command (`/tmp/command` above).
The functions take some pains to act reasonably even under unreasonable usage: they all return `nil` on error and the functions `ndk/run-my-command` and `ndk/insert-tag` do nothing if their argument is `nil`. Moreover, `ndk/insert-tag` checks whether the tag exists already before adding it.
> 1 votes
---
Tags: org-mode, shell, shell-command
--- |
thread-64602 | https://emacs.stackexchange.com/questions/64602 | Buffer-name on separate "row" from toolbar icons? | 2021-04-27T20:46:45.180 | # Question
Title: Buffer-name on separate "row" from toolbar icons?
Using macOS (11.3, M1 Mac mini) and an older Intel build of Emacs 27.1, when I load a file/buffer into Emacs, the path to the file/buffer shows up at the top of the window, above the toolbar: But, using a newer "universal" build of Emacs 27.2, the file/buffer name shows up on the same row as the toolbar: As you can see, the end of the file/buffer name can get cut off if the path is long and the window isn't wide enough.
How can I revert to the path-above-the-toolbar behavior shown in the 1st pic?
# Answer
It looks like you can change the default setting for whether or not the title (for Emacs, it's the buffer name) is over the toolbar with
> defaults write -g NSWindowSupportsAutomaticInlineTitle -bool false
You can also do it just for Emacs with:
> defaults write org.gnu.Emacs NSWindowSupportsAutomaticInlineTitle -bool false
although it's possible that your build of Emacs uses a different "domain" than org.gnu.Emacs.
I think that something like the following code change to Emacs in the right place would change the default appearance always:
```
if ( [NSToolbar instancesRespondToSelector:@selector(setToolbarStyle:)])
[win setToolbarStyle: NSWindowToolbarStyleExpanded];
```
for an `NSWindow` object `win` at an appropriate time.
> 2 votes
---
Tags: osx, tool-bar
--- |
thread-64672 | https://emacs.stackexchange.com/questions/64672 | How to switch to `flycheck-list-errors` buffer/window/minibuffer? | 2021-05-03T04:54:59.640 | # Question
Title: How to switch to `flycheck-list-errors` buffer/window/minibuffer?
For starters I use Doom Emacs.
Here's the scenario:
I have a python/perl/js buffer and flycheck-mode activated. Flycheck does its job and tells me that there are some errors that need attention. I go and do \`M-x flycheck-list-errors (or SPC c x). I have 2 spaces now: One with my code (which I believe is a window) and another **something** (buffer/window/minibuffer?) with the list of errors.
Question is: How do I switch to that **something** without using the mouse?
I've tried `next-buffer`, `previous-buffer`, `C-x o`, and I simply don't know how to focus on it.
Appreciate your help as It's driving me crazy! It shouldn't be that hard, right?
# Answer
You can either use M-x `other-window` to switch to the other window or create a custom function to use instead of the default function `flycheck-list-error`. The following function opens the `flycheck-list-errors` buffer and switches to it.
```
(defun switch-flycheck-list-errors ()
(interactive)
(flycheck-list-errors)
(pop-to-buffer "*Flycheck errors*"))
```
> 1 votes
---
Tags: buffers, window, flycheck, cycling
--- |
thread-66178 | https://emacs.stackexchange.com/questions/66178 | how to execute shell command with piping in Elisp? | 2021-06-05T21:09:09.130 | # Question
Title: how to execute shell command with piping in Elisp?
I am trying to duplicate the following bash command in Elisp:
`curl https://google.com | readability https://google.com`
Here's what I have so far, but it doesn't capture the piping "| readability" part of it. How can I use Elisp to pass info that will be interpreted as "from stdin"?
```
(shell-command-to-string (format "readability %s \n%s" url htmls))
```
# Answer
> 2 votes
The shell handles the pipelines, so there's no reason why the command you give `shell-command-to-string` can't include pipes.
```
(shell-command-to-string "curl 'https://google.com' 2>/dev/null | wc")
```
---
Tags: shell-command, pipe
--- |
thread-66179 | https://emacs.stackexchange.com/questions/66179 | How to set my settings in my init file? | 2021-06-05T21:27:28.713 | # Question
Title: How to set my settings in my init file?
I'm working on a shell script to automate the way I install linux on my computers. I'd like to incorporate some emacs customizations into this script.
For example, as soon as emacs is installed, I'd like the following set:
* The init file should be in `~/.config/emacs/init.el`.
* `menu-bar-mode` and `tool-bar-mode` should both be set to `nil`
* `backup-by-copying`, `delete-old-versions`, `global-linum-mode`, `line-number-mode`, and `version-control` should be set to `t`
* `kept-new-versions` and `kept-old-versions` should both be set to `5`
* `backup-directory-alist` should be `'(("." , "~/.cache/emacs-saves"))`
Is there a way to automate this from a shell script?
I suppose that one way to do it would be to simply write these settings to the init file with something like
```
#!/bin/sh
mkdir -p ~/.config/emacs
cat > ~/.config/emacs/init.el <<EOF
'(menu-bar-mode nil)
'(tool-bar-mode nil)
'(kept-new-versions 5)
'(kept-old-versions 5)
'(backup-bycopying t)
'(delete-old-versions t)
'(global-linum-mode t)
'(line-number-mode t)
'(version-control t)
'(backup-directory-alist '(("." . "~/.cache/emacs-saves")))
EOF
```
# Answer
You’re over–thinking it. It really is just a text file, and you don’t need to do anything fancy here.
Customize is nice primarily because it groups all the settings into categories, gives the user an easy way to search for the settings they are interested in, and makes editing the values of complex settings easier. There’s really nothing that forces you to use it, nor does it sound like there is much for you to gain by using it. It doesn’t have any API either, though you can script it in the usual ways. However, because customize writes your settings back to your init file, you could use it to set up one copy of Emacs the way you want and then copy that init file to your other machines.
So all you have to do is to create a text file with the contents that you want, using any tools that you like in the process.
I will point out, however, that in your question you put a single–quote in the front of every line, which will break them. Putting a single–quote in front of a parenthesis turns it into a list literal, but you want to actually *execute* these instructions rather than collect them into a list. Also, some of them are function that you are calling, but others are variables that you need to set. For the latter you should use setf:
```
(setf backup-by-copying t)
```
However, none of that has anything to do with how you put this file into place. You’ll know that you have done it correctly when Emacs starts up with the configuration that you want.
> 1 votes
---
Tags: init-file
--- |
thread-66182 | https://emacs.stackexchange.com/questions/66182 | How to Use Stack's GHCI when in Haskell Interactive Mode | 2021-06-05T23:18:16.860 | # Question
Title: How to Use Stack's GHCI when in Haskell Interactive Mode
I'm trying to maintain all of my package dependencies through Stack. However, when trying to use Haskell's Interactive Mode in Emacs, through `haskell-mode`, it won't find GHCI anymore, since it is only exposed through Stack now. How do I go around this now?
# Answer
You can use this line in your Emacs configuration in order to use Stack's GHCI:
```
(custom-set-variables '(haskell-process-type 'stack-ghci))
```
Then use the `haskell-session-change` command to change the buffer mode and enter interactive Haskell.
You can find more info in this tutorial.
> 2 votes
---
Tags: haskell-mode
--- |
thread-66187 | https://emacs.stackexchange.com/questions/66187 | How to keep inactive timestamped items in agenda | 2021-06-06T06:20:12.853 | # Question
Title: How to keep inactive timestamped items in agenda
To view inactive stamps in my agenda, I press `v` and `[`. This displays the inactive stamps for the specific day I am in in the `org-agenda`. However, if I press `B` of `F` to move back or forward one day, the effect of `[` is no longer valid and I must press `[` again to keep seeing those inactive items. Is it possible to keep inactive items showing in agenda when browsing days? Thanks.
# Answer
```
(setq org-agenda-include-inactive-timestamps t)
```
in your init file (untested).
Its doc string (`C-h v org-agenda-include-inactive-timestamps`) says:
> org-agenda-include-inactive-timestamps is a variable defined in ‘org-agenda.el’.
>
> Its value is nil
>
> Non-nil means include inactive time stamps in agenda. Dynamically scoped.
The fact that it is dynamically scoped and is not customizable indicates that it is meant to be set using `v [` interactively in the agenda, but setting its value to `t` should enable it permanently. Note however that `v [` will be a no-op in that case.
> 0 votes
---
Tags: org-agenda, timestamped
--- |
thread-66193 | https://emacs.stackexchange.com/questions/66193 | Automatically save files after multi-file search/replace | 2021-06-06T19:14:50.763 | # Question
Title: Automatically save files after multi-file search/replace
How can I get GNU Emacs to automatically save all the files I've changed after doing a multi-file search/replace with query-replace-regexp? Right now I have to switch back to the buffer for every individual file and save by hand whenever I do multi-file search and replace, which is just plain annoying.
# Answer
You could trigger `save-buffer` after the replace. I believe the following should work:
`(add-hook 'replace-update-post-hook 'save-buffer)`
> 3 votes
---
Tags: query-replace, query-replace-regexp
--- |
thread-65011 | https://emacs.stackexchange.com/questions/65011 | How to forward localhost ports from remote server when using tramp? | 2021-05-26T06:35:15.867 | # Question
Title: How to forward localhost ports from remote server when using tramp?
How to forward localhost ports to the remote server when using tramp, like one can do with ssh as follows:
```
ssh -L <local port>:localhost:<remote port> <user_id>@<server_ip_addr>
```
# Answer
In your `~/.ssh/config` file, you could add an entry like
```
Host <server_ip_addr>
LocalForward <local port> localhost:<remote port>
```
> 1 votes
---
Tags: tramp
--- |
thread-64803 | https://emacs.stackexchange.com/questions/64803 | How to include specific lines from latex file for org-export | 2021-05-11T09:53:39.937 | # Question
Title: How to include specific lines from latex file for org-export
I am writing a text in orgmode that I want to export to pdf. I want to include specific lines from a latex file using `#+include:`. In fact, I want to include multiple text sections from a single latex file at specific locations in an org file.
Following the documentation I should be able to do so using the `:lines` argument with `export latex`. This, however, seems not to be working.
An org file with the following content:
```
#+TITLE: Some File
* Heading
#+include: "another-file.tex" export latex :lines 3-5
```
Does not include anything from the latex file.
I also tested whether the order of arguments had an effect, i.e., with `#+include: "another-file.tex" :lines 3-5 export latex`. This results in the whole .tex-file being included in the exported PDF.
What am I missing here?
# Answer
I've tested your code and when I add quotation marks to the line numbers (as described in the documentation), it works.
Here is the working code:
```
#+TITLE: Some File
* Heading
#+include: "another-file.tex" export latex :lines "3-5"
```
Hope this helps.
> 1 votes
---
Tags: org-mode, org-export, latex
--- |
thread-54405 | https://emacs.stackexchange.com/questions/54405 | How to restore windows registers from saved desktop | 2019-12-16T13:28:04.190 | # Question
Title: How to restore windows registers from saved desktop
I save a few different windows registers using `M-x r w` and then save the entire desktop with `M-x desktop-save`.
I then restart Emacs and load the desktop using `M-x desktop-read`. If I do `M-x r j` do jump to one of the previously saved windows registers in the saved desktop I get an error message saying `Register doesn't contain a buffer position or configuration`.
If I do `M-x list-registers` every registry is described as `Register X contains a rectangle starting with an Unprintable entity`.
I do not run Emacs in a terminal, it's a full GUI Emacs and desktop-restore-frames is set to 't'. How should I do to save frame configurations between desktop sessions?
# Answer
> 1 votes
Rather than use window registers, use frame registers. Namely, save the configuration of the frames with `frameset-to-register`. It appears that Desktop correctly handles frame registers, but not window registers, and they perform largely the same function.
---
Tags: desktop, registers
--- |
thread-66196 | https://emacs.stackexchange.com/questions/66196 | Getting the PID of process initiated with call-process | 2021-06-07T02:09:48.607 | # Question
Title: Getting the PID of process initiated with call-process
Is there a way to find out the pid of an emacs subprocess started with `call-process`?
I realize that the return value of `start-process` is precisely its pid but I would like to know the pid of a process created with `call-process` instead.
I know that, after a process has started, I can get information about it using the utility `ps`, but I'd like to avoid parsing the output of `ps` just to know the pid.
# Answer
> 1 votes
Here's a somewhat silly implementation of a function that does a `call-process` and returns its pid (sort-of):
```
(defun call-process-pid ()
(let (l1 l2)
(setq l1 (list-system-processes))
(call-process "sleep" nil 0 nil "60")
(setq l2 (list-system-processes))
(cl-set-difference l2 l1)))
```
It's a somewhat cleaner way of doing a `ps` before and after to find out what process(es) got added.
The limitation is that between the first and second calls to `list-system-processes`, a bunch of processes may have been created, so the set difference will have more than one entry: AFAIK, there is no way to know which one is "your" process without looking at each one (e.g. with `process-attributes` to find out the command that was run). It may also happen that your command runs to completion before the second `list-system-processes`, in which case it will not appear at all - but that's probably OK for your intended use.
There are ways to daemonize a subprocess: that can be easily done from a C program (Stevens' "Advanced Programming in the Unix environment" has examples, but googling "daemonize Unix" should provide plenty). I'm not sure whether you can do the equivalent from within Emacs, but you don't have to: you can use `nohup` to prevent the program from responding to `SIGHUP`, so instead of `(call-process "command" nil 0 nil args...)`, you can do `(call-process "nohup" nil 0 nil "command" args...)`. I have not tested that it actually works, but I can't see any reason why it shouldn't. Assuming that it works, adapting this idea to your previous question should be straightforward.
---
Tags: subprocess, call-process
--- |
thread-66202 | https://emacs.stackexchange.com/questions/66202 | date to time for french | 2021-06-07T14:14:05.503 | # Question
Title: date to time for french
I want to convert a lot of french dates in date to time
```
(date-to-time "june 7 2021 12:00:00" )
=>
(24765 60960)
(date-to-time "7 juin 2021 12:00:00" )
=>
Debugger entered--Lisp error: (error "Invalid date: 7 juin 2021 12:00:00")
```
Should I translate the french date in english ?
# Answer
You can override the global variables `parse-time-months` and `parse-time-weekdays`, which are alists from month/weekday names to their respective numbers. These variables are undocumented, but they've been around for over two decades.
```
(defvar parse-time-months-french
'(("jan" . 1) ("fév" . 2) ("mar" . 3)
("avr" . 4) ("mai" . 5) ("jun" . 6)
("jul" . 7) ("aoû" . 8) ("sep" . 9)
("oct" . 10) ("nov" . 11) ("déc" . 12)
("janvier" . 1) ("février" . 2)
("mars" . 3) ("avril" . 4) ("juin" . 6)
("juillet" . 7) ("août" . 8)
("septembre" . 9) ("octobre" . 10)
("novembre" . 11) ("décembre" . 12)))
(defvar parse-time-weekdays-french
'(("dim" . 0) ("lun" . 1) ("mar" . 2)
("mer" . 3) ("jeu" . 4) ("ven" . 5)
("sam" . 6) ("dimanche" . 0) ("lundi" . 1)
("mardi" . 2) ("mercredi" . 3)
("jeudi" . 4) ("vendredi" . 5)
("samedi" . 6)))
(defun date-to-time-french (date)
"Like `date-to-time', but require French names."
(let ((parse-time-months parse-time-months-french)
(parse-time-weekdays parse-time-weekdays-french))
(date-to-time date)))
(defun date-to-time-french-english (date)
"Like `date-to-time', but recognize French names as well as English names."
(let ((parse-time-months (append parse-time-months-french parse-time-months))
(parse-time-weekdays (append parse-time-weekdays-french parse-time-weekdays)))
(date-to-time date)))
```
> 2 votes
---
Tags: time-date, calendar, date-to-time
--- |
thread-62546 | https://emacs.stackexchange.com/questions/62546 | How do I open a window that will behave like a *Help* window? | 2020-12-31T20:58:48.723 | # Question
Title: How do I open a window that will behave like a *Help* window?
`*Help*` windows appear to have a special behavior. For example, if I open a help window using `C-h f butterfly`, the window will open in a separate half-page buffer. If I use the help feature again `C-h f tetris`, the same help-mode buffer will be reused to display the documentation for `tetris`. Is there a way to replicate this behavior for other windows? For example, I would like EWW windows to have a behavior similar to `*Help*`.
So far, I have this:
```
;; Reuse old *eww* windows.
;; Otherwise, pop up a new window.
(setq-default display-buffer-alist
(cons '("^\\*\\eww\\*$"
(display-buffer-reuse-window
display-buffer-pop-up-window))
display-buffer-alist))
```
Is this method correct? I feel uneasy about the use of the use of regex to drive the behavior. Perhaps there is some other way of achieving the same result (e.g. using `advice-add`)?
# Answer
As @Drew says, it's not clear what you're looking for. However, since I found your question while creating my own function to reuse an eww window, I thought you might find it helpful.
It looks for a buffer called "\*eww\*" (the default name for an eww buffer). If there's a live window, then use that. Otherwise, call eww in the current window.
I've tried to document it fully. You can use `C-h f`, `C-h v` and `C-h i d m elisp` to learn more.
```
(defun my-lookup ()
"Lookup symbol at point in PySide online documentation."
(interactive)
;; define function variables
;; let form defines variables, the * means you can use one definition within another
(let* ((sym (thing-at-point 'symbol)) ; get symbol at point
(url (concat
"https://doc-snapshots.qt.io/qtforpython-5.15/PySide2/QtWidgets/"
sym
".html"
)) ; define a web address using that symbol
(buff (get-buffer-window "*eww*"))) ; check if there exists an eww buffer, get its window
;; begin function behavior
(if buff
(with-selected-window buff
(eww url)) ; if eww buffer exists, call eww command in that window
(eww url)))) ; otherwise call it in the current window
```
> 3 votes
# Answer
> Is this method correct? I feel uneasy about the use of the use of regex to drive the behavior.
You can use any logic you want to recognise the buffer. Here's an example which tests the major mode of the buffer, instead of its name:
```
(add-to-list 'display-buffer-alist
(cons (lambda (buffer _alist)
(with-current-buffer buffer
(derived-mode-p 'eww-mode)))
(cons '(display-buffer-reuse-window
display-buffer-pop-up-window)
'((inhibit-same-window . nil)
(reusable-frames . visible)
(inhibit-switch-frame . nil)))))
```
You might also consider `display-buffer-reuse-mode-window` as one of your fallback display actions.
> Perhaps there is some other way of achieving the same result (e.g. using advice-add)?
Advice is powerful and useful, but also not something to use unnecessarily. When there's already a mechanism provided, you definitely want to prefer that mechanism.
> 0 votes
---
Tags: window, eww, popup, help-mode
--- |
thread-63916 | https://emacs.stackexchange.com/questions/63916 | Use golangci-lint with lsp-mode | 2021-03-16T01:52:45.930 | # Question
Title: Use golangci-lint with lsp-mode
How can I set up `golangci-lint` as the linter with my config? I've tried using `flycheck-golangci-lint` but it doesn't seem to be working. I'm testing my config by opening a .go file with an ineffectual assignment that trips `golangci-lint` when run from the CLI tool. My Go and LSP configs are:
```
;; lsp-mode configs
(use-package lsp-mode
:delight lsp-lens-mode ""
:ensure t
:init
;; set prefix for lsp-command-keymap (few alternatives - "C-l", "C-c l")
(setq lsp-keymap-prefix "C-c l")
:custom
(lsp-auto-guess-root +1)
:config
(lsp-enable-imenu)
(setq lsp-prefer-flymake nil)
(setq lsp-headerline-breadcrumb-enable t)
:hook (;; replace XXX-mode with concrete major-mode(e. g. python-mode)
(python-mode . lsp-deferred)
(scala-mode . lsp-deferred)
(sh-mode . lsp-deferred)
(go-mode . lsp-deferred)
;; if you want which-key integration
(lsp-mode . lsp-enable-which-key-integration)
(lsp-mode . lsp-lens-mode)
(lsp-after-open . 'lsp-enable-imenu)
)
:commands (lsp lsp-deferred))
;; go-mode
(use-package go-mode
:delight ""
:hook
(before-save . lsp-format-buffer)
(before-save . lsp-organize-imports)
)
;; flycheck-golang-ci-lint
(use-package flycheck-golangci-lint
:ensure t
:hook
(go-mode . flycheck-golangci-lint-setup)
)
```
Apologies for the wall of code - I want to make sure I don't miss anything that might be causing `flycheck-golang-ci-lint` to fail.
# Answer
It seems you want to chain `golangci-lint` after `lsp`, is it? The following snippet allows you to chain other linters after `lsp`. I have included the link where the original solution was posted for other linters. You can see that I use the snippet to chain linters for `Python` and `Shell`.
```
;; https://github.com/flycheck/flycheck/issues/1762
(progn
(with-eval-after-load 'flycheck
(defvar-local flycheck-local-checkers nil)
(defun flycheck-checker-get (fn checker property)
(or (alist-get property (alist-get checker flycheck-local-checkers))
(funcall fn checker property)))
(advice-add 'flycheck-checker-get :around 'flycheck-checker-get)
(add-hook 'lsp-managed-mode-hook
(lambda ()
(when (derived-mode-p 'python-mode)
(setq flycheck-local-checkers '((lsp . ((next-checkers . (python-pylint)))))))
(when (derived-mode-p 'sh-mode)
(setq flycheck-local-checkers '((lsp . ((next-checkers . (sh-shellcheck)))))))
(when (derived-mode-p 'go-mode)
(setq flycheck-local-checkers '((lsp . ((next-checkers . (golangci-lint)))))))
))
))
```
I do not use `go`, so unfortunately I cannot test the code.
> 1 votes
---
Tags: flycheck, lsp-mode, golang
--- |
thread-65125 | https://emacs.stackexchange.com/questions/65125 | Publish a book as HTML/website with org-mode that is similar to bookdown | 2021-06-01T19:53:47.530 | # Question
Title: Publish a book as HTML/website with org-mode that is similar to bookdown
I've written a book using org-mode and I'm trying to export as an HTML/website, similar to this example. That was written using R and Bookdown, but since it all ends up as CSS/HTML, I don't see why the same thing can't be replicated with org-mode.
I've been trying to use `org-publish` to do this, but I'm running into a few of issues.
**1.** I can't seem to replicate the book structure of the above example -- it all comes out as one single long HTML file. I'm using separate files for each chapter, and then a `main.org` file where each chapter is included via `#+INCLUDE` statements. What is the best way to achieve this? In other words, I want a front page with a TOC, and then each chapter to be a separate page and to have previous and next links for navigation.
**2.** I've been using the `org-ref` package to cross-reference figures/tables/sections in the book, but it doesn't seem to work across multiple files. E.g. if I am in chapter 4 and I want to reference something in chapter 2 (using the `label:` and `ref:` keywords respectively), `org-ref` doesn't seem to recognize it. Any way around this?
**3.** I suppose I could do it manually: publish each chapter separately as a HTML file and have each chapter include file links to the previous and next chapters. But this would be tedious and hard to edit afterwards. Essentially I'm looking to automate the whole process.
Any help is appreciated. Is this easily doable with org-mode, or should I just bite the bullet and learn R and Bookdown?
# Answer
**Option 1:**
Use a static website generator, such as Hugo, which is external software that natively understands Org-Mode syntax. You will have to build a template that replicates your ideal.
Natively, each Org file is an HTML file. With the `ox-hugo` package, you can work with one file.
Limitation: Org-Ref only works with LaTeX output.
**Option 2:**
Convert the Org-Mode files to markdown and use bookdown in Emacs. The ESS package lets you use R in Emacs.
> 2 votes
---
Tags: org-mode, org-publish
--- |
thread-66221 | https://emacs.stackexchange.com/questions/66221 | How to install transient package? | 2021-06-08T23:41:01.647 | # Question
Title: How to install transient package?
> ...Magit depends on the dash, **transient** and with-editor libraries which are available from Melpa and Melpa-Stable. Install them using M-x package-install RET RET. Of course you may also install them manually from their repository...
How to install transient package?
What I tried
```
M-x package-refresh-contents
M-x package-install transient <enter>
at this point emacs suggests "transient-" so the transient package is not available.
```
My init.el:
```
; Hide menu bar because I dont use it
(menu-bar-mode -1)
;; got this from github.com/solkaz/dot-files
;; /blob/7e11b52176685326b5b0c328f557be80cb3d64c2/emacs/dot-emacs.d/init.el
(require 'package)
(add-to-list 'package-archives '("melpa-stable" . "https://stable.melpa.org/packages/") t)
(add-to-list 'package-archives '("melpa" . "https://melpa.org/packages/") t)
(add-to-list 'package-archives '("gnu" . "https://elpa.gnu.org/packages/") t)
(add-to-list 'package-archives '("org" . "https://orgmode.org/elpa/") t)
(package-initialize)
(unless (package-installed-p 'use-package)
(package-refresh-contents)
(package-install 'use-package))
```
# Answer
The easiest way is just to run `M-x list-packages`, find `magit` (use `C-s` to search just like any other buffer). With the cursor on the Magit line, type `i` to mark the package for installation, then `x` to execute. It will install Magit plus all of its dependencies automatically.
Or you could search for transient and mark it for installation if you really wanted to.
> 2 votes
---
Tags: magit
--- |
thread-66220 | https://emacs.stackexchange.com/questions/66220 | Why does font-lock-mode work with various programming languages but it does not in text-mode? | 2021-06-08T23:20:25.920 | # Question
Title: Why does font-lock-mode work with various programming languages but it does not in text-mode?
The objective is to do text highlighting when `TODO` and `NOTE` tokens are found somewhere in a `txt` file. This is what I have in the `.emacs.el` file:
```
(add-hook 'text-mode-hook 'font-lock-mode)
(setq fixme-modes
'(text-mode c++-mode c-mode emacs-lisp-mode octave-mode python-mode))
(make-face 'font-lock-fixme-face)
(make-face 'font-lock-note-face)
(mapc (lambda (mode)
(font-lock-add-keywords
mode
'(("\\<\\(TODO\\)" 1 'font-lock-fixme-face t)
("\\<\\(NOTE\\)" 1 'font-lock-note-face t))))
fixme-modes)
(modify-face 'font-lock-fixme-face "Red" nil nil t nil t nil nil)
(modify-face 'font-lock-note-face "Dark Green" nil nil t nil t nil nil)
;;(global-font-lock-mode 1)
(add-hook 'text-mode-hook 'flyspell-mode)
(add-hook 'emacs-lisp-mode-hook 'eldoc-mode)
```
The final two lines were added for debugging purposes, to check if other features could work in `text-mode`.
While editing C++, Python, and Octave source files - it works perfectly.
PS: I'm new to writing Elisp code!
# Answer
> Why does font-lock-mode work with various programming languages but it does not in text-mode?
`font-lock-mode` works fine in `text-mode`, it's just that `text-mode` does not initialise `font-lock-mode` by setting `font-lock-defaults`. Quoth `(info "(elisp) Font Lock Basics")`:
```
There are several variables that control how Font Lock mode
highlights text. But major modes should not set any of these variables
directly. Instead, they should set ‘font-lock-defaults’ as a
buffer-local variable. The value assigned to this variable is used, if
and when Font Lock mode is enabled, to set all the other variables.
-- Variable: font-lock-defaults
This variable is set by modes to specify how to fontify text in
that mode. It automatically becomes buffer-local when set. If its
value is ‘nil’, Font Lock mode does no highlighting, and you can
use the ‘Faces’ menu (under ‘Edit’ and then ‘Text Properties’ in
the menu bar) to assign faces explicitly to text in the buffer.
```
and `(info "(elisp) Search-based Fontification")`:
```
The variable which directly controls search-based fontification is
‘font-lock-keywords’, which is typically specified via the KEYWORDS
element in ‘font-lock-defaults’.
-- Variable: font-lock-keywords
The value of this variable is a list of the keywords to highlight.
Lisp programs should not set this variable directly. Normally, the
value is automatically set by Font Lock mode, using the KEYWORDS
element in ‘font-lock-defaults’. The value can also be altered
using the functions ‘font-lock-add-keywords’ and
‘font-lock-remove-keywords’ (see Customizing Keywords).
```
So the problem here is that `c++-mode`, `c-mode`, `emacs-lisp-mode`, `octave-mode`, and `python-mode` all initialise `font-lock-defaults` to some non-`nil` value with their custom fontification rules, but `text-mode` doesn't (because it doesn't by itself have any fontifification rules).
Indeed, with the following your code should work (this is just for illustration, not recommended):
```
(add-hook 'text-mode-hook (lambda () (setq font-lock-defaults '(nil))))
```
So far so good. The real subtlety, though, lies in what `font-lock-add-keywords` does. With a non-`nil` argument, it actually modifies `font-lock-keywords-alist`, not the variables `font-lock-defaults` or `font-lock-keywords` which `font-lock-mode` uses to determine whether and how to do any fontification. This is because `font-lock-add-keywords` implicitly expects the mode in question to have already initialised `font-lock-defaults` appropriately.
By contrast, with a `nil` argument, `font-lock-add-keywords` forcefully initialises and reenables `font-lock-mode` if it has to:
```
;; ...
(when (and font-lock-mode
(not (or font-lock-keywords font-lock-defaults)))
;; The major mode has not set any keywords, so when we enabled
;; font-lock-mode it only enabled the font-core.el part, not the
;; font-lock-mode-internal. Try again.
(font-lock-mode -1)
(setq-local font-lock-defaults '(nil t))
(font-lock-mode 1))
;; ...
```
This is kind of hinted at in the docstring of `font-lock-keywords`:
```
A user-level keywords list is what a major mode or the user would
set up. Normally the list would come from `font-lock-defaults'.
through selection of a fontification level and evaluation of any
contained expressions. You can also alter it by calling
`font-lock-add-keywords' or `font-lock-remove-keywords' with MODE = nil.
```
So one simple workaround is to call `font-lock-add-keywords` with a `nil` argument, as shown in `(info "(emacs) Font Lock")`:
```
(defvar my-fixme-hooks
'(text-mode-hook prog-mode-hook)
"List of mode hooks in which to fontify \"FIXME\" keywords.")
(defface my-fixme-face
'((t :foreground "Red" :weight bold :underline t))
"Default face for \"FIXME\" keywords.")
(defface my-note-face
'((t :foreground "Dark Green" :inherit my-fixme-face))
"Face for \"NOTE\" keywords.")
(defun my-fixme-fontify ()
"Fontify \"FIXME\" keywords in the current buffer."
(font-lock-add-keywords
nil
'(("\\<\\(TODO\\)" 1 'my-fixme-face t)
("\\<\\(NOTE\\)" 1 'my-note-face t))))
(dolist (hook my-fixme-hooks)
(add-hook hook #'my-fixme-fontify))
```
The only problem with this is that it applies not only to the mode hooks in `my-fixme-hooks`, but also to all their derived modes. If this is undesirable, I think the simplest workaround is to set `font-lock-defaults` as I showed at the start (but only if it's `nil`).
Either way, I think the situation and documentation is confusing/subtle enough that I recommend reporting it upstream via `M-x report-emacs-bug RET`. Even if `font-lock-add-keywords` is behaving 100% as desired, it would be nice if the caveat in question were documented more clearly. TIA.
> 3 votes
---
Tags: font-lock, text-properties
--- |
thread-66224 | https://emacs.stackexchange.com/questions/66224 | What is the sequence/chord/key used to backspace an Emacs Command | 2021-06-09T04:02:40.883 | # Question
Title: What is the sequence/chord/key used to backspace an Emacs Command
In Doom Emacs, I pressed `SPC` then pressed `p` instead of `o`. If I press Backspace key then it becomes `DEL` instead of backspacing `p`. This means Backspace key is one of the chords. How am I supposed to do a Backspace for the commands? What is the key or step that I need to do for backspacing commands in Doom Emacs?
# Answer
I don't think there's a way to undo a key when entering a sequence of keys. Usually one would enter `C-g` to `(keyboard-quit)` and reenter the sequence because sequences are typically short.
Documentation for `keyboard-quit`:
> Signal a quit condition.
>
> During execution of Lisp code, this character causes a quit directly. At top-level, as an editor command, this simply beeps.
I'm a fan of Doom, but not a user. So I'm not sure what the idomatic way to do this is in Doom. However, after greping through their repo (in the develop branch), I found the following:
https://github.com/hlissner/doom-emacs/blob/2731685095d1e6101b3215aa689426e1834ce00f/core/core-keybinds.el#L61
```
;;
;;; Universal, non-nuclear escape
;; `keyboard-quit' is too much of a nuclear option. I wanted an ESC/C-g to
;; do-what-I-mean. It serves four purposes (in order):
;;
;; 1. Quit active states; e.g. highlights, searches, snippets, iedit,
;; multiple-cursors, recording macros, etc.
;; 2. Close popup windows remotely (if it is allowed to)
;; 3. Refresh buffer indicators, like git-gutter and flycheck
;; 4. Or fall back to `keyboard-quit'
;;
;; And it should do these things incrementally, rather than all at once. And it
;; shouldn't interfere with recording macros or the minibuffer. This may require
;; you press ESC/C-g two or three times on some occasions to reach
;; `keyboard-quit', but this is much more intuitive.
;; ... elided
(global-set-key [remap keyboard-quit] #'doom/escape)
```
I think maybe you can quit a sequence with `Esc`, but might have to press it more than once or `C-g` to nuke it.
Please try it and let me know!
> 0 votes
---
Tags: doom, backspace
--- |
thread-51202 | https://emacs.stackexchange.com/questions/51202 | Configuring web-mode for Vue.js (.vue) files | 2019-06-23T08:20:47.197 | # Question
Title: Configuring web-mode for Vue.js (.vue) files
It seems that `web-mode` has supported Vue.js since May 2017, the "Venora Release".
Configuring Emacs to handle Vue.js files (extension `.vue`) is as easy as writing
```
(add-to-list 'auto-mode-alist '("\\.vue\\'" . web-mode))
```
in one's `.emacs` file.
But `web-mode` does not like the `<template>` tag. What is the right `.emacs` setup/config?
# Answer
> 0 votes
I belive your configuration is right. And I think you meant this issue. It seems to be solved in Jan 31, 2019. Hope this helps.
---
Tags: web-mode
--- |
thread-66218 | https://emacs.stackexchange.com/questions/66218 | Possible to copy-paste without markup in Org-mode? | 2021-06-08T19:43:25.357 | # Question
Title: Possible to copy-paste without markup in Org-mode?
You can add inline code and verbatim text in Org-mode using this syntax:
```
~<code>cd ~~</code>~
=verbatim /text/=
```
This is expected to display:
> \<code\>cd ~\</code\>
>
> verbatim /text/
If you copy the content in the Org-mode buffer and paste it into any other program, the content is pasted with the full markup.
**Is it possible to copy and paste only what is displayed and not the markup?**
# Answer
> 2 votes
You can use the ASCII exporter if you customize the option `org-ascii-verbatim-format` to `%s`.
Export to a buffer and copy the code there.
The following command sets the options temporarily for you as needed and then exports directly into the kill-ring:
```
(defun org+-copy-code ()
"Export code silently to kill-ring."
(interactive)
(require 'ox-ascii)
(cl-letf (((symbol-function 'org-element-normalize-string) #'identity))
(save-excursion
(kill-new
(org-export-as 'ascii
nil nil t
'(:ascii-verbatim-format "%s" :ascii-paragraph-spacing auto :ascii-headline-spacing nil :preserve-breaks t))
))))
```
You can try that command after evaluating the code above by selecting the region you want to copy and `M-x` `org+-copy-code` `RET`.
If you like what you see you can copy the code to your init file and bind `org+-copy-code` to some key, e.g., `C-c c` by the following line in your init file.
```
(with-eval-after-load 'org
(define-key org-mode-map (kbd "C-c c") #'org+-copy-code))
```
---
Tags: org-mode, copy-paste, markup
--- |
thread-66204 | https://emacs.stackexchange.com/questions/66204 | How to remove or overwrite a `yasnippets`? | 2021-06-07T16:07:06.333 | # Question
Title: How to remove or overwrite a `yasnippets`?
I am using Python but some pre-defineted snippets are acting not as I wanted, hence I want to remove some, if possible.
In most cases, I am using `TAB` for indent alignment, hence `yasnippets` apply themselve, which is pretty annoying.
For example:
In a Python file writing `log` and press `TAB`, `emacs` write followings code piece, which I want to disable:
```
logger = logging.getLogger("name")
logger.setLevel(logging.level)
```
---
my setup:
```
(add-hook 'python-mode-hook 'lsp)
(add-hook 'python-mode-hook #'lsp-deferred)
# taken from: https://github.com/joaotavora/yasnippet
(add-to-list 'load-path
"~/.emacs.d/plugins/yasnippet")
(require 'yasnippet)
(yas-global-mode 1)
```
---
```
Hide Yas Snippet Dirs: [Value Menu] List of directories:
[INS] [DEL] Choice: [Value Menu] Directory: ~/.emacs.d/snippets
[INS] [DEL] Choice: [Value Menu] Variable: yasnippet-snippets-dir
[INS] [DEL] Choice: [Value Menu] Variable: yasnippet-classic-snippets-dir
```
---
Please note that when I try to create a new snippet it generates it under `/home/user/etc/yasnippet/snippets/python-mode/` instead of `~/.emacs.d/snippets`.
Default snippets are located under `/usr/share/yasnippet-snippets/python-mode`; but since they require permission would it be a good idea to remove the ones that I don't want to use?
---
For example I want to remove following snippet keys for:
`__str__`, `str`, `size`, `def`, `self`, `__`
---
Basically,I just want to remove all `key` snippets for the given key. For example, when I type `str` and press `TAB` emacs says:
```
Possible completions are:
__str__ str
. Choose a snippet:
```
where I don't want to see neither of it and completely remove all keys for the `str` key.
# Answer
> 2 votes
It is not a good idea to remove a snippet from their place - at first update of yasnippet-snippet package, it will be again present in your Emacs.
So, a simpler method is to create new or modify/rename/save to the default `yas-snippet-dir`, which is `~/.emacs.d/snippets` folder (if you did not modify it already). But to be organised, add here a new folder `python-mode` where the new python snippets will be placed.
To modify an existing snippet and to place it in the default folder created, visit it and then use the command `save-as`, bound to `C-x C-w` instead the usual save command `C-x C-s`. The “save-as” will allow you to choose destination folder.
The last thing to do is to take care to load all snippets (the original ones + yours) after python-mode is loaded - so add the line `(yas-reload-all)` after python mode is configured.
# Answer
> 2 votes
It might be easiest to remove the template in your init file after yasnippets is loaded. That way you don't have to modify the system directories. I think this should do it:
```
(yas--remove-template-by-uuid (yas--table-get-create 'python-mode) "logging")
```
---
Tags: yasnippet
--- |
thread-66230 | https://emacs.stackexchange.com/questions/66230 | use-package hook in to multiple modes | 2021-06-09T13:14:16.133 | # Question
Title: use-package hook in to multiple modes
How can I tell this config to also activate git-auto-commit-mode mode for the `js-mode` in addition to `fundamental-mode`
```
(use-package git-auto-commit-mode
:hook
(fundamental-mode . git-auto-commit-mode)
:custom
(gac-ask-for-summary-p t))
```
# Answer
> 4 votes
According to the manual (section 4.13), the car of the `:hook` form can be a list. So
```
(use-package git-auto-commit-mode
:hook
((fundamental-mode js-mode) . git-auto-commit-mode)
:custom
(gac-ask-for-summary-p t))
```
should do the job.
---
Tags: use-package
--- |
thread-66232 | https://emacs.stackexchange.com/questions/66232 | Use variable in reference with remote in Org-table | 2021-06-09T13:47:10.117 | # Question
Title: Use variable in reference with remote in Org-table
I have one table called GRADING containing names and points entered by hand, and another table (FOO) containing the grading scheme. Is there a simple formula which allows to lookup the number of points and assign the corresponding grade from FOO? I have tried many variation of the formula `$3=remote(FOO,@@#$2)`. If we could replace `@#` by `$2` I think it would do the trick, but everything gets messed up.
```
#+NAME: GRADING
| Name | Points | Grade |
|-------+--------+-------|
| Alice | 10 | |
| Rob | 20 | |
| Bob | 30 | |
| Jack | 35 | |
| Marc | 12 | |
| Marie | 65 | |
| Fanny | 12 | |
#+TBLFM: $3=remote(FOO,@@#$2)
#+NAME: FOO
| Number of points | Grade |
|------------------+-------|
| 0 | 1 |
| 1 | 1 |
| 2 | 1 |
| 3 | 1.5 |
| 4 | 1.5 |
| 5 | 1.5 |
| 6 | 1.5 |
| 7 | 1.5 |
| 8 | 1.5 |
| 9 | 1.5 |
| 10 | 2 |
| 11 | 2 |
| 12 | 2 |
| 13 | 2 |
| 14 | 2 |
| 15 | 2 |
| 16 | 2 |
| 17 | 2.5 |
| 18 | 2.5 |
| 19 | 2.5 |
| 20 | 2.5 |
| 21 | 2.5 |
| 22 | 2.5 |
| 23 | 2.5 |
| 24 | 3 |
| 25 | 3 |
| 26 | 3 |
| 27 | 3 |
| 28 | 3 |
| 29 | 3 |
| 30 | 3 |
| 31 | 3 |
| 32 | 3 |
| 33 | 3.5 |
| 34 | 3.5 |
| 35 | 3.5 |
| 36 | 3.5 |
| 37 | 3.5 |
| 38 | 3.5 |
| 39 | 3.5 |
| 40 | 3.5 |
| 41 | 3.5 |
| 42 | 4 |
| 43 | 4 |
| 44 | 4 |
| 45 | 4 |
| 46 | 4 |
| 47 | 4 |
| 48 | 4 |
| 49 | 4.5 |
| 50 | 4.5 |
| 51 | 4.5 |
| 52 | 4.5 |
| 53 | 4.5 |
| 54 | 4.5 |
| 55 | 4.5 |
| 56 | 5 |
| 57 | 5 |
| 58 | 5 |
| 59 | 5 |
| 60 | 5 |
| 61 | 5.5 |
| 62 | 5.5 |
| 63 | 5.5 |
| 64 | 5.5 |
| 65 | 5.5 |
| 66 | 6 |
| 67 | 6 |
| 68 | 6 |
| 69 | 6 |
| 70 | 6 |
```
# Answer
Hope this will be useful to someone (have been searching for the solution for hours!). The function to use is `#+TBLFM: $3='(org-lookup-first $2 '(remote(FOO,@2$1..@>$1)) '(remote(FOO,@2$2..@>$2)))`
Found it by reading this answer which links to the org lookup functions documentation, which in turn links to useful examples in Worg.
> 2 votes
---
Tags: org-mode, org-table, remote
--- |
thread-66236 | https://emacs.stackexchange.com/questions/66236 | How to enable a major + a minor mode on loading a file? | 2021-06-09T22:50:27.440 | # Question
Title: How to enable a major + a minor mode on loading a file?
Clojure files should open in Clojure-mode. I also have Clojure files that contain color info and are used to generate my styles; they live under a /styles path. For these files, I want them to have both clojure-mode (a major mode) and rainbow-mode (a minor mode). I can implement this on a file-by-file basis be starting such files with a line like this:
`;; -*- eval: (rainbow-mode) -*-`
But I make and use enough of these files, I tried the following:
```
(use-package rainbow-mode
:mode "css\\|style")
```
Which adds that line to the top of `auto-mode-alist`. But that causes the auto-mode to no longer match my clojure files if they dwell under a `style/*` directory; it enables the rainbow minor mode and stops there. Is there a simple solution for getting both of these modes to load on clj files without having to preface every such file with the eval line?
# Answer
To use `rainbow-mode` in `clojure-mode` only under a certain directory, add a `.dir-locals.el` file to the directory, containing:
```
((clojure-mode . ((eval . (rainbow-mode 1)))))
```
You can also use `M-x` `add-dir-local-variable` to create/edit the file.
Note that `eval` is a pseudo-variable used to evaluate elisp.
Alternatively, with the file in the project root:
```
(("path/to/subdirectory" . ((clojure-mode . ((eval . (rainbow-mode 1)))))))
```
Refer to `C-h``i``g` `(emacs)Directory Variables` for more details, as well as an equivalent way of specifying this in your init file rather than with a `.dir-locals.el` file.
---
To use `rainbow-mode` in `clojure-mode` whenever the buffer file name contains `/style/` or `/css/`:
```
(add-hook 'clojure-mode-hook #'my-clojure-mode-hook)
(defun my-clojure-mode-hook ()
"Custom `clojure-mode' behaviours."
(and buffer-file-name
(string-match "/\\(?:style\\|css\\)/" buffer-file-name)
(rainbow-mode 1)))
```
> 3 votes
---
Tags: eval-expression, auto-mode-alist
--- |
thread-66203 | https://emacs.stackexchange.com/questions/66203 | Limit counsel-locate to certain file type and directory | 2021-06-07T14:54:57.330 | # Question
Title: Limit counsel-locate to certain file type and directory
CentOS 7, Emacs 27.2, Ivy, Swiper, Counsel package.
In `Temp` folder I have different files. I want to find using `counsel-locate` all text files only in this folder and **all subfolders**.
I try this:
As you can see I use command `M-x counsel-locate .txt` but `counsel` finds ALL text files in whole HDD. But I need to find all text files ONLY in the folder `Temp`.
Is this possible with the `counsel` package?
P.S.
```
(defun adl/counsel-locate-in-the-current-folder-and-subfolders ()
(interactive)
(counsel-locate (concat (file-truename default-directory) " ")))
```
Work only for current folder. But I need to find also in all subfolders. Here screenshots
# Answer
`counsel-locate` essentially just calls the system `locate` command (see `man 1 locate`).
You can control which executable is called by customising the user option `locate-command` from the built-in package `locate.el`.
You can further control the exact command that `counsel-locate` issues by customising the user option `counsel-locate-cmd`.
On GNU/Linux, the default command issued by `counsel-locate` is:
```
locate -i --regex REGEXP
```
where `REGEXP` is the user input interpreted as a regular expression.
So, to find any `.txt` files under any directory called `Temp`, you need an input like `Temp \.txt\'` or `Temp.*\.txt\'` (note that the literal full stop `.` has to be escaped, that `\'` anchors the file extension at the end of the file name, and that Ivy translates the first pattern into something equivalent to the second pattern by default).
To find any `.txt` files under a specific directory called `Temp`, you need an input like
```
\`/home/alexeij/Temp \.txt\'
```
or
```
\`/home/alexeij/Temp.*\.txt\'
```
Where the
```
\`
```
anchors the search at the start of the file name.
Finally, to start every `counsel-locate` search in the current directory, you can write a custom command like the following based on adl's answer:
```
(defun my-counsel-locate-here ()
"Start `counsel-locate' anchored at `default-directory'."
(interactive)
(counsel-locate (rx bos (literal (file-truename default-directory)) ?\s)))
```
Then you can issue e.g. `M-x my-counsel-locate-here RET \.txt\'` to find all `.txt` files under the current directory.
A more direct (but sometimes slower) way of achieving the same thing is `M-x counsel-file-jump RET \.txt\'`.
For a fuzzy search analogue, there's also e.g. `M-x counsel-fzf RET .txt`.
---
**Update**
> P.S. \[`adl/counsel-locate-in-the-current-folder-and-subfolders`\] work only for current folder. But I need to find also in all subfolders.
The `locate` command usually depends on indexing your filesystem in order to answer queries efficiently. Are you sure the subfolders in question have been indexed already? Usually `locate` updates its database daily in the background, but you can force it via `updatedb`.
In any case I think `adl/counsel-locate-in-the-current-folder-and-subfolders` is working fine (except for the fact that it doesn't quote and anchor regular expressions properly, see the `my-counsel-locate-here` example), so the problem is most likely a pilot error/misunderstanding.
> 2 votes
# Answer
You can use the following function to start `counsel-locate` already with the current directory in it and an space. Then you could type whatever you want to search there.
```
(defun adl/counsel-locate-in-the-current-folder-and-subfolders ()
(interactive)
(counsel-locate (concat (file-truename default-directory) " ")))
```
> 0 votes
# Answer
I prefer this approach:
```
(defun my-insert-default-directory ()
"Insert `default-directory' at point."
(interactive)
(insert (file-truename default-directory)))
(global-set-key (kbd "C-c C-d") #'my-insert-default-directory) ;; custom function
```
During `M-x counsel-locate`, if I press `C-c C-d` I get the following result:
I do not need the current directory every time. So when I need it I use `C-c C-d`.
> 0 votes
---
Tags: ivy, counsel
--- |
thread-66235 | https://emacs.stackexchange.com/questions/66235 | Display LaTeX-Quotation marks as unicode characters | 2021-06-09T18:34:11.750 | # Question
Title: Display LaTeX-Quotation marks as unicode characters
When quoting in auctex, I use the strings `"`` and `"'` to typeset and , respectively. Now, I want emacs to display the corresponding unicode characters to these strings. I've tried it with `prettify-symbols` but as it seems it can only handle *single characters*, not strings of characters. So my question is: How can you display `"`` in emacs as and `"'` as ?
# Answer
Thanks to Tyler's comment, I now know that **it is possible to assign a single character to a string of characters with `prettify-symbols`**! I simply forgot to put a question mark in front of the unicode symbol. For anyone as lost as me, here is the code:
```
(setq TeX-symbols-list '(lambda ()
(mapc (lambda (pair) (push pair prettify-symbols-alist))
'(
("\"\`" . ?„)
("\"\'" . ?“)
))))
```
Additionally, you can tell LaTeX to print `"`` and `"'` if you press `"` at the beginning or end of a quote, respectively:
```
(setq TeX-open-quote "\"`")
(setq TeX-close-quote "\"'")
```
This way, you can use quotation marks the same way you would use them in Word.
> 3 votes
---
Tags: latex, auctex, font-lock, unicode
--- |
thread-66241 | https://emacs.stackexchange.com/questions/66241 | How can I make 'git diff' aware of Emacs Lisp functions? | 2021-06-10T09:29:25.637 | # Question
Title: How can I make 'git diff' aware of Emacs Lisp functions?
When diffing with Git, for most languages, it provides a function name in the chunk header, allowing to get a better grasp on the context, e.g.,
```
@@ -7,5 +7,6 @@ int main() {
if(condition()) {
task4();
task5();
+ task6();
}
}
```
For Emacs Lisp, `git diff` seems to use some sort of fall-back mode, where apparently the closest line without indentation is used; which usually is part of a docstring, not something like `(defun ...`
```
@@ -9,4 +9,5 @@ Last docstring line."
(run-task3)
(when (run-condition)
(run-task4)
- (run-task5)))
+ (run-task5)
+ (run-task6)))
```
Is it possible to make Git aware of how to identify a useful line to use for the `@@` line?
#### Complete example source
For reference I attach the full source used to produce the examples.
```
/// run.c
int main() {
// foo
task1();
task2();
task3();
if(condition()) {
task4();
task5();
task6();
}
}
```
```
;;; run.el
(defun run-main ()
"1st docstring line.
2nd docstring line.
Last docstring line."
(run-task1)
(run-task2)
(run-task3)
(when (run-condition)
(run-task4)
(run-task5)
(run-task6)))
```
# Answer
> 13 votes
> Is it possible to make Git aware of how to identify a useful line to use for the `@@` line?
Yes, quoth section "Defining a custom hunk-header" in `man 5 gitattributes`:
```
Defining a custom hunk-header
Each group of changes (called a "hunk") in the textual diff output
is prefixed with a line of the form:
@@ -k,l +n,m @@ TEXT
This is called a hunk header. The "TEXT" portion is by default a
line that begins with an alphabet, an underscore or a dollar sign;
this matches what GNU diff -p output uses. This default selection
however is not suited for some contents, and you can use a
customized pattern to make a selection.
First, in .gitattributes, you would assign the diff attribute for
paths.
*.tex diff=tex
Then, you would define a "diff.tex.xfuncname" configuration to
specify a regular expression that matches a line that you would
want to appear as the hunk header "TEXT". Add a section to your
$GIT_DIR/config file (or $HOME/.gitconfig file) like this:
[diff "tex"]
xfuncname = "^(\\\\(sub)*section\\{.*)$"
```
So, to teach Git about Elisp files, you could first add the following to your `$XDG_CONFIG_HOME/git/attributes` file (which defaults to `~/.config/git/attributes`):
```
*.el diff=elisp
```
Then, you can configure the exact header-matching regexp in your `$XDG_CONFIG_HOME/git/config` file (which defaults to `~/.config/git/config`), e.g. as follows:
```
[diff "elisp"]
xfuncname = ^\\([^[:space:]]+[[:space:]]+([^()[:space:]]+)
```
This is the relatively liberal regexp that I use globally. The Emacs repository itself uses a slightly more restricted one:
```
[diff "elisp"]
xfuncname = ^\\([^[:space:]]*def[^[:space:]]+[[:space:]]+([^()[:space:]]+)
```
You can find it by searching for `xfuncname` in the script `autogen.sh`.
---
Tags: git
--- |
thread-63911 | https://emacs.stackexchange.com/questions/63911 | Generate .bib local bbliography with all the bibtex entries cited in an org document | 2021-03-15T17:36:39.287 | # Question
Title: Generate .bib local bbliography with all the bibtex entries cited in an org document
I have a large refs.bib file where I collect all my bibliography. I'd like to export only the relevant bibtex entries cited in a org document. So then I can email the document.bib and document.tex files to my collaborators.
I am pretty sure this piece of functionality already exists but I haven't been able to find it.
# Answer
> 3 votes
If you are using org-ref see `org-ref-extract-bibtex-entries` or `org-ref-extract-bibtex-to-file`.
# Answer
> 1 votes
> I have a large refs.bib file where I collect all my bibliography. I'd like to export only the relevant bibtex entries cited in a org document.
The `bog` package provides a command `bog-create-combined-bib` that can do something like this:
```
bog-create-combined-bib is an autoloaded interactive compiled Lisp function in
`bog.el'.
(bog-create-combined-bib &optional ARG)
Create a buffer that has entries for a collection of citekeys.
If in Dired, collect citekeys from marked files. Otherwise,
collect citekeys from the current buffer. With prefix argument
ARG, reverse the meaning of `bog-combined-bib-ignore-not-found'.
```
For example, with the following contents in the current `org-mode` buffer:
```
* Robin Milner
...
** milner1999communicating
Communicating and Mobile Systems: The π-Calculus
...
* tzevelekos2011fresh
...
* martens2021linear
Linear time parallel algorithm to calculate strong bisim on parallel random
access machines.
...
```
`M-x bog-create-combined-bib RET` generates the following `*Bog combined bib*` buffer:
```
@InProceedings{martens2021linear,
author = {Martens, Jans and Groote, Jan Friso and van den Haak, Lars and
Hijma, Pieter and Wijs, Anton},
title = {A linear parallel algorithm to compute bisimulation and
relational coarsest partitions},
date = 2021,
booktitle = {Proceedings of the 2021 International Conference on
Foundations of Software Science and Computation Structures}
}
@book{milner1999communicating,
author = {Milner, Robin},
title = {Communicating and Mobile Systems: The {$\pi$}-Calculus},
year = 1999,
publisher = {Cambridge University Press},
isbn = {978-0-521-65869-0}
}
@article{tzevelekos2011fresh,
author = {Tzevelekos, Nikos},
title = {Fresh-Register Automata},
year = 2011,
issue_date = {January 2011},
publisher = {Association for Computing Machinery},
address = {New York, NY, USA},
volume = 46,
number = 1,
issn = {0362-1340},
url = {https://doi-org.elib.tcd.ie/10.1145/1925844.1926420},
doi = {10.1145/1925844.1926420},
abstract = {What is a basic automata-theoretic model of computation with
names and fresh-name generation? We introduce Fresh-Register
Automata (FRA), a new class of automata which operate on an
infinite alphabet of names and use a finite number of
registers to store fresh names, and to compare incoming names
with previously stored ones. These finite machines extend
Kaminski and Francez's Finite-Memory Automata by being able to
recognise globally fresh inputs, that is, names fresh in the
whole current run. We examine the expressivity of FRA's both
from the aspect of accepted languages and of bisimulation
equivalence. We establish primary properties and connections
between automata of this kind, and answer key decidability
questions. As a demonstrating example, we express the theory
of the pi-calculus in FRA's and characterise bisimulation
equivalence by an appropriate, and decidable in the finitary
case, notion in these automata.},
journaltitle = {SIGPLAN Not.},
month = jan,
pages = {295–306},
numpages = 12,
keywords = {computation with fresh-name generation, finite-memory
automata, register automata}
}
```
In my case I have a separate `bib` file for each entry, but `bog` also supports multiple entries in a single `bib`; you just need to customise the user options `bog-find-citekey-bib-func` and `bog-bib-file`. See the project's README for more.
# Answer
> 1 votes
I just went crazy looking for an answer as well. I've done it numerous times in the past, but never remembered how to do it. The key was to google **without** mentioning emacs!
I copy an answer from here (that I normally use): https://tex.stackexchange.com/questions/41821/creating-bib-file-containing-only-the-cited-references-of-a-bigger-bib-file
With a TeX Live distribution (possibly also with MiKTeX) there is a `bibexport` program. Assuming your document is `myarticle.tex`, you have to compile it normally and then you call
`bibexport -o extracted.bib myarticle.aux`
where `extracted.bib` is the name that you want to give to your new `.bib` file. Notice that you have to give the extension `.aux` (or no extension at all).
Then you have to change the name of the `.bib` file in your document, in order to use `extracted.bib`.
---
Tags: org-mode, bibtex, org-ref
--- |
thread-66249 | https://emacs.stackexchange.com/questions/66249 | ESS: start R in current directory conflicts with ivy-mode | 2021-06-10T18:57:11.183 | # Question
Title: ESS: start R in current directory conflicts with ivy-mode
I use ivy-mode for completion. I don't usually want to see the dot files ("./" and "../") when selecting files/directories, so I've set `(setq ivy-extra-directories nil)`. I also want to use the selectable prompt option: `(setq ivy-use-selectable-prompt t)`.
Mostly, this is fine. However, there's one unfortunate interaction. When I want to start an R session with the `ESS` package, I'm prompted for the buffer I want to start in. Of course, the list doesn't include the current directory `./`, since I've configured it not to. And the prompt from ESS requires a match from the list of directories, which prevents me from selecting the empty prompt.
This means the default directory selected will be the first directory within the current directory, and if I want to select the current directory I need to back up one level and select it from there. This is awkward.
How can I configure ESS and/or ivy to allow me to start R in the current directory by default, while maintaining my ivy configurations globally?
# Answer
> 0 votes
The function in ESS that sets the directory is `ess-prompt-for-directory`. By applying an `:around` advice, we can temporarily add the dot files back to the ivy-mode completion targets:
```
(defun tws-ess-ivy-fix (orig-fun &rest args)
"Temporarily add dot files to the list of directories offered."
(let ((ivy-extra-directories '("../" "./")))
(apply orig-fun args)))
(advice-add 'ess-prompt-for-directory :around #'tws-ess-ivy-fix)
```
---
Tags: ess, ivy, advice
--- |
thread-66248 | https://emacs.stackexchange.com/questions/66248 | highlight occurences for thing under point also for substrings | 2021-06-10T18:46:35.563 | # Question
Title: highlight occurences for thing under point also for substrings
With point over a word, pressing C-u C-s highlights this word and any identical words. How can I make this work for substring search as well, i.e. if highlighting the word **house**, occurrences of **houses** are also highlighted?
Also, I would like to have this functionality extend through the entire buffer, so that if I scoll with C-v and M-v words are already highlighted.
# Answer
> 1 votes
Try this. Bind it to a key. You can use `M-s h u` to unhighlight the last-highlighted word. You're prompted for the word, with the word at point as default.
The regexp to match is whatever word you enter, expanded by word chars on either side. So if you want to match `houses`, entering `house` will pick that up too.
There's no easy answer to what you might be expecting, which is to have Emacs know about actual English (or whatever language) words, e.g., to know that `houses` is a word but `thouses` is not. But it's not too likely that you'll end up with such non-words in your buffer.
If you want to allow only for suffixes (e.g. `s`) and not also prefixes, then replace the `"\\b\\w*"` with just `"\\b"`.
```
(defun foo (word)
(interactive (list (read-string "Word: " (word-at-point))))
(highlight-phrase (concat "\\b\\w*" word "\\w*\\b")))
```
---
But if your question was really about *searching*, then use `C-M-s C-w` to pick up the word at point, then `M-e` to edit that search pattern, then type `\w*\b` for a pattern that adds suffixes, then `C-s` to continue searching.
If you want Isearch to highlight across the whole buffer then set variable `lazy-highlight-buffer` to `t`.
If you want Isearch highlighting to persist till the next search, set variable `lazy-highlight-cleanup` to `nil`.
---
Tags: highlighting, words
--- |
thread-66255 | https://emacs.stackexchange.com/questions/66255 | Org timestamp prompt that returns timestamp as a string? | 2021-06-10T21:12:54.510 | # Question
Title: Org timestamp prompt that returns timestamp as a string?
The function `#'org-time-stamp` prompts a minibuffer that reads control strings from the user, and call `#'org-insert-time-stamp` to insert the resulting time stamp as a string into the buffer. For example, the control string `"2021-01-01 9am"` results to the time stamp `"<2021-01-01 Fri 09:00>"`.
How to factor these functions to create a new function that still prompts a minibuffer, but only returns a string without insertion? Some thing like
```
(org-time-stamp-read "2021-01-01 9am")
;; => "<2021-01-01 Fri 09:00>"
```
# Answer
> 2 votes
`org-read-date` does what you want:
```
org-read-date is a compiled Lisp function in `org.el'.
(org-read-date &optional WITH-TIME TO-TIME FROM-STRING PROMPT
DEFAULT-TIME DEFAULT-INPUT INACTIVE)
Read a date, possibly a time, and make things smooth for the user.
```
# Answer
> 0 votes
A direct way that offers the same result is
```
(with-temp-buffer
(org-time-stamp nil)
(buffer-string))
```
However, this is not efficient enough. I still hope to see a proper factoring.
---
Tags: org-mode, time-date
--- |
thread-61810 | https://emacs.stackexchange.com/questions/61810 | completion and goto-function in matlab-mode | 2020-11-18T12:53:34.500 | # Question
Title: completion and goto-function in matlab-mode
I've been working with matlab-mode and matlab-shell for the last few days, and I'm really digging it so far. The only two things I can't get to work properly are completion - neither in shell, nor in .m files - and jumping to function definitions, and I would really appreciate some help with these. when I hit TAB in shell, my text turns into
```
>> emacsdocomplete('EEG.(cond')
```
and when I hit RETURN I get (the appropriate):
```
emacs_completions_output =
java.lang.String[]:
'cond'
'condeig'
```
but it's not integrated into the shell properly, i.e. I can't choose which of the above I want, I have to re-type the command along with the chosen completion. In .m files I just get nothing except for the word completion for words already in the buffer - which I've configured myself.
I've read somewhere that the completion is meant to be related to CEDET somehow but I couldn't make out much more (I'm working on Doom Emacs, and I seen to have CEDET installed, and can run matlab-cedet-setup, which does nothing as far as I can tell).
As to function definitions - I don't even know where to start.. I've read that ctags now supports matlab, but I don't know where (if) the actual .m files for the built-in functions reside in the install dir.
Ideally I'd love to be able to stand on a function name and be able to get the "help funcName" output in another buffer or something (this works from the shell).
Thanks a lot!
# Answer
The problem is that the output is read-only in Doom Emacs. As a workaround use `inhibit-read-only`.
I did it like this:
```
(defadvice! inhibit-real-only-a (oldfun &rest r)
"Temporary remove read-only lines in shell buffer"
:around#'matlab-shell-collect-command-output
(let ((inhibit-read-only t)) (apply oldfun r)))
```
> 0 votes
---
Tags: doom, cedet, matlab
--- |
thread-45990 | https://emacs.stackexchange.com/questions/45990 | How can I find out which packages were not available? | 2018-11-14T09:24:07.183 | # Question
Title: How can I find out which packages were not available?
When I run `package-install-selected-packages` I see the following message:
```
1 packages are not available (the rest already installed)
```
But it doesn't say which package was not available.
All the packages in `package-selected-packages` appear to have been installed, but apparently I requested something that was not available.
How can I find out what it was?
# Answer
I just copied and modified the relevant snippet from `package-install-selected-packages`:
```
(let* ((not-installed (seq-remove #'package-installed-p package-selected-packages))
(unavailable (seq-filter (lambda (p) (not (assq p package-archive-contents)))
not-installed)))
unavailable)
```
Pasted this into `*scratch*`, evaluated and got the missing packages.
> 5 votes
---
Tags: package
--- |
thread-66266 | https://emacs.stackexchange.com/questions/66266 | prevent eval of a single src block | 2021-06-11T15:40:08.307 | # Question
Title: prevent eval of a single src block
How do I ensure that only the second block never evaluates, while still allowing the first block to be evaluated normally?
```
#+begin_src shell
echo "hi"
#+end_src
#+begin_src python
print("no print please")
#+end_src
```
# Answer
You can use the `:eval no` attribute on the block that you want to disable:
```
#+begin_src shell
echo "hi"
#+end_src
#+RESULTS:
: hi
#+begin_src python :eval no
print("no print please")
#+end_src
```
> 5 votes
---
Tags: org-babel
--- |
thread-66261 | https://emacs.stackexchange.com/questions/66261 | How to get the following indentation style in c? | 2021-06-11T05:50:25.187 | # Question
Title: How to get the following indentation style in c?
I would like to have the following behavior:
```
int main(){
```
to result in:
```
int main(){
|
}
```
Where pipe is the cursor, and I DON'T have to press RETURN key after '{'.
I have already achieved the following behavior:
```
int main(){
```
which results in:
```
int main()
{
|
}
```
Using c-toggle-auto-indent and electric-pair-mode.
So, how do I make it the way I want to? i.e to:
```
int main(){
|
}
```
I have been looking around and found this page:
> First you need to find the syntactic context of the brace—type a RET before the brace to get it on a line of its own, then type C-c C-s. That will tell you something like:
>
> ((substatement-open 1061))
>
> So here you need to put the entry (substatement-open . (after)) into c-hanging-braces-alist
This is what I have tried:
1. Found the syntactic context to be: `substatement-open`
2. Putting `(setq c-hanging-braces-alist '(substatement-open . (after)))` in init.el.
But this isn't working.
I really have no idea how to do this. Can someone help me?
# Answer
First, customize `c-hanging-braces-alist` to use the `style` settings: I think that's the default, but since you've been mucking around with customizing it, go back and make sure it is set to the default.
Then try the different built-in styles: Type `C-c .` and choose a style (there is `TAB` completion). Enter a brace and see if it does what you want: if it does not, go back and try another style. I wasn't particularly careful so this may be wrong, but the only style I could find that did what you want was the `awk` style. Whether that satisfies all your other (unstated) requirements is unknown, but even if it does not, you might be able to crib the style and create your own that does exactly what you want. See the doc string for the variable `c-style-alist` and the function `c-add-style`.
For completeness, here's a bit of code to add to your `init.el` to do what you want (assuming that the `awk` style is good enough for your other purposes:
```
(defun ndk/auto-newline ()
"Enable auto-newline."
(c-toggle-auto-newline 1))
(defun ndk/c-set-style ()
"Set the default C style to \"awk\"."
(c-set-style "awk"))
(defun ndk/electric-pair-mode ()
"Enable electric-pair-mode."
(electric-pair-mode 1))
(add-hook 'c-mode-hook #'ndk/auto-newline)
(add-hook 'c-mode-hook #'ndk/c-set-style)
(add-hook 'c-mode-hook #'ndk/electric-pair-mode)
```
You could use `lambda`s, but I prefer to use named functions in hooks: it keeps things neater.
EDIT: I think the operative detail for what you want is the setting of `defun-open` to `after` in the `awk` style, since that is the syntactic class of a brace in the context you describe.
> 4 votes
---
Tags: indentation, c
--- |
thread-66247 | https://emacs.stackexchange.com/questions/66247 | How can I get request.el to return data directly? | 2021-06-10T17:25:33.593 | # Question
Title: How can I get request.el to return data directly?
I know how to use request.el to get data and insert it into a buffer, but what if I want to simply have request.el return the data itself (e.g., for saving in a variable)?
Here's my attempt, but this doesn't actually return data (in this case a small amount of test JSON):
```
(request "https://jsonplaceholder.typicode.com/todos/1"
:parser 'json-read
:success (cl-function
(lambda (&key data &allow-other-keys)
data))))
```
# Answer
> 2 votes
You are looking for this I think:
```
(request-response-data
(request "https://jsonplaceholder.typicode.com/todos/1"
:parser 'json-read
:sync t))
```
the :sync arg avoids the need for a callback I think by making it wait for the request to be done.
---
Tags: url
--- |
thread-31295 | https://emacs.stackexchange.com/questions/31295 | How can I navigate up/down a log from magit-rev-mode? | 2017-03-07T16:09:49.597 | # Question
Title: How can I navigate up/down a log from magit-rev-mode?
When I'm reviewing a patch series in magit I want to be able to look in detail at each patch in a tree. However there doesn't seem to be an easy way to navigate to the next/previous commit from inside magit-revision-mode. I end up having to switch back to log mode to select the next commit which is inefficient.
Does magit-revision-mode have any context for where in the log view it was when it was called?
# Answer
> 7 votes
That isn't supported yet but you can do it "the other way around". Instead of pressing `RET` to show *and select* the revision buffer, press `SPC` to show the revision buffer *but stay in the log buffer*.
When you move to another revision in the log buffer, the revision buffer is automatically updated. And you can press `SPC` again to scroll the revision buffer, while staying in the log buffer.
Of course some things are not possible when you stay in the log buffer, e.g. you cannot collapse any sections in the revision buffer from the log buffer. So yes, it would be nice to move to the next/previous revision while in the revision buffer. Please open a feature request for that.
# Answer
> 0 votes
With this piece of code, after press `SPC` in the log buffer, it display commit diff each time you move up or down. Another `SPC` to disable.
```
(defun magit-log-move-down-and-show-diff ()
"Move to next line and show diff"
(interactive)
(next-line)
(magit-diff-show-or-scroll-up))
(defun magit-log-move-up-and-show-diff ()
"Move to previous line and show diff"
(interactive)
(previous-line)
(magit-diff-show-or-scroll-up))
(define-minor-mode magit-log-auto-diff-mode
"In git log buffer, minor mode to update revision buffer each time up or down
key is pressed"
:keymap (let ((map (make-sparse-keymap)))
(define-key map (kbd "<down>") 'magit-log-move-down-and-show-diff)
(define-key map (kbd "<up>") 'magit-log-move-up-and-show-diff)
map)
(if magit-log-auto-diff-mode
(magit-diff-show-or-scroll-up)))
(with-eval-after-load "magit-log"
(define-key magit-log-mode-map (kbd "SPC") 'magit-log-auto-diff-mode))
```
---
Tags: magit, navigation
--- |
thread-66276 | https://emacs.stackexchange.com/questions/66276 | Search ELPA/MELPA Package repositories | 2021-06-12T15:02:39.617 | # Question
Title: Search ELPA/MELPA Package repositories
I know searching for packages in the ELPA/MELPA repositories might be available within emacs itself, but I'm just wondering, can I do the search on the Internet as well? Just like I know I can search for packages on my Android phone, but I still prefer doing searches for them on the Internet.
# Answer
> 3 votes
You can search MELPA directly: https://melpa.org
The site also allows you to sort by downloads (popularity).
You can also search GNU ELPA from its website: https://elpa.gnu.org/packages/
GNU ELPA does not appear to provide for sorting by popularity.
---
Tags: search, package-repositories
--- |
thread-66283 | https://emacs.stackexchange.com/questions/66283 | How can I export my org file to be locally exactly like the github version? | 2021-06-12T18:23:00.863 | # Question
Title: How can I export my org file to be locally exactly like the github version?
I am new to emacs. In addition, I decided to learn org-mode which seems to be fantastic.
I wrote this `.org` file that you can check here. In Github, the file has this appearance:
In Emacs, it has a different appearance as the source:
I would like to see the content locally as it will be presented on Github.
I tried using `C-c C-e` with options like .HTML and .odt. However, the output files do not look like the Github one.
Is there something that I could do to get what I want?
Ideally, it would be good to have a "previewer" instead of really exporting a file just to see how it would look like.
# Answer
I am no expert at this, but I guess github uses its own CSS, and ultimately renders html. So I guess there has to be some kind of export involved.
I know about two easy options, of which I would recommend grip-mode (requires the python grip package). The other option gfm-mode (appears to rely on deprecated packages Docter or Marked 2).
Looking back at this PR, I see there is also vmd-mode.
> 5 votes
---
Tags: org-mode, org-export
--- |
thread-66272 | https://emacs.stackexchange.com/questions/66272 | How to autoload a non-elpa package such as help-fns+.el? | 2021-06-12T01:53:18.900 | # Question
Title: How to autoload a non-elpa package such as help-fns+.el?
I read from some posts (require vs. package-initialize?, and here) that Emacs can autoload packages installed via ELPA/MELPA, which avoids using `require` on packages and speeds up loading during initialization. And quoting this answer:
> Note that for 99% of the packages require should not be needed (the autoloads should cause the package to be loaded as soon as you try to make use of it).
I do have quite a few usages of `(require ...)` in my `init.el` that significantly slow down emacs initialization. By turning things on and off, some culprits seems to be
```
(require 'help-fns+) ; about 0.2 to 0.3 s
(require 'org)
(require 'ob-octave) ; not sure, but up to 1 s
```
I tried to just comment out these `require` statements (since I use emacs 27.1 under Ubuntu). But help-fns+.el does not seem to work anymore. Functions defined there (e.g. `describe-buffer`) can no longer be found.
My questions are:
*Is it the right way to take advantage of autoloads by just removing the `require` call? Or is it because `help-fns+.el` doesn't have the autoload capability from ELPA?*
*If the latter case, (how) can I autoload `help-fns+.el` and avoid a hard `require` in `init.el`?*
# Answer
There are some alternatives. Do any of them after putting the library in a directory that's in your `load-path`.
1. Unconditionally load the library.
```
(require 'help-fns+)
```
2. Autoload the library for individual commands (or other functions, but typically commands), by putting a sexp like this in your init file:
```
(autoload 'describe-command "help-fns+" "Help commands." t)
```
Then, whenever you invoke that command, the file will automatically be loaded.
3. But library help-fns+.el also provides `;;;###autoload` cookies, so you can alternatively generate a file of autoloads for it, using command `update-file-autoloads`.
As @NickD wrote in a comment, see the Elisp manual, node Autoload.
> 2 votes
---
Tags: init-file, help, autoload, help-mode
--- |
thread-55018 | https://emacs.stackexchange.com/questions/55018 | init.el and trampling of custom-set-variables | 2020-01-19T22:40:23.813 | # Question
Title: init.el and trampling of custom-set-variables
My new `init.el` uses `require` to load various settings that I have organised into directories and files. This is an attempt to tame what was a very large and messy `init.el` and `custom.el` file. Also I ultimately hope to use `org` files to better document each setting.
I'm trying (and largely failing) to make this setup play nicely with `customize`.
My old `init.el` has grown over a few years and makes liberal use of `setq`.
But reading this: Advantages of setting variables with setq instead of custom.el?
And these: https://www.reddit.com/r/emacs/comments/b1jzno/need\_help\_making\_my\_initel\_file\_look\_cleaner\_its/
https://www.reddit.com/r/emacs/comments/9rrhy8/emacsers\_with\_beautiful\_initel\_files\_what\_about/
I decided to try replacing `setq` with `custom-set-variables` for custom variables.
The problem I have is that despite the fact that I've explicitly set variables using `custom-set-variables`, `customize` appears to take all my explicit settings and appends them to the end of my `init.el` or in a separate file if `custom-file` is set. This duplicates the settings needlessly, and create more, not less mess.
What's worse is that complicated expressions seems to get rendered incorrectly when trampled, the below:
```
(let* ((default-directory temporary-file-directory)
(emacs-temp (expand-file-name current-user "emacs-saves")))
(custom-set-variables '(backup-directory-alist (`(("." . ,emacs-temp))))
'(auto-save-file-name-transforms (`(("." ,emacs-temp t))))))
```
Is trampled with `custom.el` containing an out of scope `emacs-temp`. No such issues are seen using `setq`:
```
(custom-set-variables
;; custom-set-variables 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.
'(auto-save-file-name-transforms ((\` (("." (\, emacs-temp) t)))))
'(backup-by-copying t)
'(backup-directory-alist ((\` (("." \, emacs-temp))))))
```
It appears I can prevent customize writing anything out by using:
`(setq custom-file null-device)`
But this is problematic because `customize` settings made outside of my `init.el` and it's `require` statements, will then never be recorded. Apart from my own (very occasional) use of `customize`, other packages may try to write to the custom file - eg `package-selected-packages`.
The way I see it - `customize` should only be writing out settings that are not already explicitly set in `init.el`, etc. This will avoid trampling of any settings I've explicitly made.
Any other settings made within `customize` (or elsewhere) that would not trample anything explicitly set in `init.el`, could then be appended to `init.el`, or directed elsewhere by `custom-file`.
The closest behaviour to this seems to be the use of `setq` not `custom-set-variables` which seems to be ignored by `customize`. However I take the points that use of `defcustom` keywords means that `setq` use can be problematic.
My question is - how do I correctly and safely initialize custom values in my initialization script(s), such that they are not then trampled by `customize` saving these values back down to a file, and without preventing other `customize` values from being saved to file?
Will `use-package` help me? Can I make `setq` use safe without interleaving setup before and after initialization?
**EDIT**
Responding to some feedback, I'm going to walk through a few simple cases step by step.
As you'll see below following through a simple example as suggested by @Drew yields the correct result. However a more complex example using `require` to pull in programmatically set customizable variables reproduces the issue.
**Attempt 1: Simplest Example - This works as expected**
1. Take a fresh install of emacs (for this I used v25.2.2)
2. Inside the empty ~/.emacs.d place an `init.el` file containing a single line `(setq backup-by-copying t)`. `~/.emacs.d$ echo '(setq backup-by-copying t)' > init.el`. This represents a value that I do not want to set directly in `customize` as I want to organize my own setup into more readable sections over several files/directories - I've picked `backup-by-copying` at arbitrarily.
3. I then run emacs and see the following in `customize` \- `Backup By Copying`, `[ State ]: CHANGED outside Customize.`.
4. So far no surprises. Now let's set a completely unrelated item directly in `customize`. The logic here, is that either via automated other packages or directly by me, it's possible that something is required to be recorded directly in `customize` appended to `init.el` (by default). So in the `customize` UI I search for and `Toggle` `Create Lockfiles`.
5. This gives me `[ State ]: EDITED, shown value does not take effect until you set or save it.`
6. To save this (and hopefully only this) setting to the end of `init.el` I'm clicking on `[ Apply and Save ]`
7. emacs confirms `Wrote /home/foo/.emacs.d/init.el`
8. The contents of my `init.el` is now:
```
(setq backup-by-copying t)
(custom-set-variables
;; custom-set-variables 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.
'(create-lockfiles nil))
(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.
)
```
OK - so far everything is as expected, now I'll repeat, overwriting the original `init.el`, replacing `setq` with `custom-set-variables` in point 2:
1. As above
2. `~/.emacs.d$ echo "(custom-set-variables '(backup-by-copying t))" > init.el`
3. In `customize` I now see `Backup By Copying` set to `[ State ]: SAVED and set.`
4. Same as above
5. Same as above
6. Same as above
7. Same as above
8. The contents of my init.el is now
```
(custom-set-variables
;; custom-set-variables 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.
'(backup-by-copying t)
'(create-lockfiles nil))
(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.
)
```
Nothing wrong with this - `'(create-lockfiles nil)` has been pulled under the control of `customize`. There is a single, correct, copy of the setting!
So now I will try to isolate the case I previous had seen.
**Attempt 2: Using `require` Example - Doesn't work as I had expected**
Repeating what was done in Attempt 1 above, but with a sightly more complex `init.el` structure.
Create a subdirectory under `.emacs.d` called `settings`, this is going to contain a single lisp file `file-settings.el` which we will `require` from `init.el`.
1. `echo "(add-to-list 'load-path (expand-file-name \"settings\" user-emacs-directory))" > init.el` followed by `echo "(require 'file-settings)" >> init.el`
2. `echo "(setq backup-by-copying t)" > settings/file-settings.el` followed by `echo "(provide 'file-settings)" >> settings/file-settings.el`
3. Same as `setq` for Attempt 1 - `[ State ]: CHANGED outside Customize.`
4. Same as Attempt 1
5. Same as Attempt 1
6. Same as Attempt 1
7. Same as Attempt 1
8. The contents of my init.el is now:
```
(add-to-list 'load-path (expand-file-name "settings" user-emacs-directory))
(require 'file-settings)
(custom-set-variables
;; custom-set-variables 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.
'(create-lockfiles nil))
(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.
)
```
So far all good. Now, again, let's swap-out `setq` for `custom-set-variables`
1. As above
2. `echo "(custom-set-variables '(backup-by-copying t))" > settings/file-settings.el` followed by `echo "(provide 'file-settings)" >> settings/file-settings.el`
3. Same as Attempt 1 - In `customize` I now see `Backup By Copying` set to `[ State ]: SAVED and set.`
4. Same as above
5. Same as above
6. Same as above
7. Same as above
8. The contents of my init.el is now
```
(add-to-list 'load-path (expand-file-name "settings" user-emacs-directory))
(require 'file-settings)
(custom-set-variables
;; custom-set-variables 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.
'(backup-by-copying t)
'(create-lockfiles nil))
(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.
)
```
BUT the contents of `settings/file-settings.el` is still:
```
(custom-set-variables '(backup-by-copying t))
(provide 'file-settings)
```
So the setting of `backup-by-copying` has been duplicated?
**Is it possible to use `require` (or similar) to organize my config into a modular structure of directories, without running into this issue?**
# Answer
> 1 votes
It sounds like you have done both of the following for some options, i.e., you've done them both for at least one option:
1. Used Customize to set and save the option.
2. Tried to call customize functions to set the option in your init file.
If so, it's you who introduced the redundancy. For a given option, choose one or the other. For example, if you want to define `backup-directory-alist` dynamically, making it dependent on your local variable `emacs-temp`, then remove its setting from your `custom-file`.
Use Customize to set only options whose values are not variable, i.e., they don't depend on anything else or any conditional handling. That's what `custom-file` is for. The settings you provide for it are not sexps that get evaluated when `custom-file` is loaded.
Put any fancy handling of other options in your init file (or a Lisp file that it loads).
And yes, your fancy handling of, say, `backup-directory-alist`, could be done using `setq`, but the effect would be the same.
(The effect won't be the same in general, because of the possibility of `:set` etc. `defcustom` parameters. But the fact of changing the value after it was first set via your `custom-file` is the same.)
The problem is not that Customize *"trample\[s\]"* on such a value *"by saving these values back down to a file"*. The problem is that you saved such values using Customize in the first place.
---
In your comments here you say that if you change an option, say `foo`, outside customize (doesn't matter how), and then you use the Customize UI to set and save some other option, say, `bar`, then both options `foo` and `bar` are written to your `custom-file`.
That doesn't happen if you just use Customize to set and save `bar`. You must be telling Customize to save **all** changed, unsaved options. Please update your recipe (in the question, not in comments) to clarify just what you are doing, and be sure to start Emacs using `emacs -Q` (no init file), to eliminate distractions.
If you start Emacs with `emacs -Q` and you do what I described (set option `foo` without using Customize and set and save (only) option `bar` using Customize, then only `bar` should be written to your `custom-file`.
---
See also Emacs-Wiki page Customizing and Saving for more info about Customize.
# Answer
> 1 votes
### Is it possible to use require (or similar) to organize my config into a modular structure of directories, without running into this issue?
Yes. Don't add `custom-set-variables` to multiple places in your init. There should be exactly one instance of `custom-set-variables`. By default, Emacs creates this in your `init.el` file. If it's already there, you cannot use that form anywhere else without causing problems.
For your intended approach, you should be using `customize-set-variable`. Similar spelling, but important difference!
---
Tags: init-file, customize, defcustom, setq
--- |
thread-66297 | https://emacs.stackexchange.com/questions/66297 | Highlight rectangle and non-rectangle selection at the same time | 2021-06-14T03:40:12.823 | # Question
Title: Highlight rectangle and non-rectangle selection at the same time
By default, Emacs highlights the non-rectangular selection; alternatively, you can use `(rectangle-mark-mode)` to show the rectangular selection. Instead, I'd like to always show both, by highlighting the rectangle in one face, and the normal selection outside the rectangle with another. How do I set that up?
# Answer
> 7 votes
There’s no simple variable you can set to control this, but you can do it with some programming if you want.
There is a variable called `redisplay-highlight-region-function` whose value is a function to be called whenever the region needs to be shown. It creates an overlay that applies the `region` face to the selection (or moves it to a new start/end positions if one already exists).
Meanwhile the rectangle code in `rect.el` adds an `:around` method to this function. An `:around` method is always called instead of the original function, and it can call the original if it wants. This is a way to extend the behavior of an existing function without modifying it. The new method is called `rectangle--highlight-for-redisplay`. The first thing it does is check to see if the variable `rectangle-mark-mode` is set. If it isn’t, then it calls the original `redisplay-highlight-region-function` and does nothing else. Otherwise it goes on to add overlays to the buffer to display the rectangular region (a surprisingly complicated task, as you’ll see from the code).
What you will want to do is make `rectangle--highlight-for-redisplay` do both things, rather than just one or the other.
Take note that both of these functions return the overlay that they create, and that the caller saves this overlay and passes it back the next time it calls them. Presumably this is a performance optimization. When you create two overlays, you will want to return a cons containing both of them so that this optimization is maintained. Of course, when you get back a cons you will want to pass just the first region to the original `redisplay-highlight-region-function`.
---
Tags: faces, region, highlighting, rectangle, selection
--- |
thread-66304 | https://emacs.stackexchange.com/questions/66304 | How do org mode internal links work with no custom ids? | 2021-06-14T21:56:37.137 | # Question
Title: How do org mode internal links work with no custom ids?
I am viewing a file which consists of a table of contents followed by the content. Each ToC entry appears to be an internal link of the form `[[#fixes][Fixes]]`.
My understanding is that these internal are defined to point to a heading with a corresponding CUSTOM\_ID property. The thing is there are no such properties in the file. In this case the heading pointed to contains:
```
*** Fixes
- Fix error: (void-variable helm-bookmark-map) when selecting a candidate from
a Helm buffer (thanks to bmag)
- Fix window number assignation for Neotree buffer window (thanks to duianto)
```
I.e. no properties. I don't understand how these internal links work. The only way I can mimic this behaviour is by either:
1. Creating a CUSTOM\_ID property under my target heading and linking to that, or
2. Creating a * as opposed to # link and specifying the heading name.
How do these internal links work when there are no (as far as I can see) custom ids?
For reference, the file I am looking at is the spacemacs CHANGELOG.org file.
# Answer
> 1 votes
If you download the CHANGELOG.org file, open it in emacs and then click in the `Fixes` link, you are going to get an error message:
```
org-link-search: No match for custom ID: fixes
```
So you are absolutely right to be perplexed: you need to have a `PROPERTY` drawer with a `CUSTOM_ID` property in order for the link to work.
So why does it work on GitHub (for some value of "work")? My (incomplete) understanding is that Org mode files on GitHub are processed using org-ruby to produce HTML, which then gets a mountain of CSS and JS added to it in order to produce the page you see on GitHub. In other words, they take a non-standard implementation and add a lot of their own special sauce to do what they want: you could theoretically do the same thing (assuming they make their CSS and JS available in a readable form), using `org-ruby` for processing and adding the same CSS and JS, but, editorializing a bit, I would say: No, thanks.
---
Tags: org-mode, hyperlinks
--- |
thread-66279 | https://emacs.stackexchange.com/questions/66279 | Flyspell: Ignore comments in LaTeX-documents | 2021-06-12T16:05:48.003 | # Question
Title: Flyspell: Ignore comments in LaTeX-documents
Whenever I run `flyspell-buffer` (using hunspell) in a LaTeX-document, my comments marked with % are spell-checked aswell, although I don't want them to be spell-checked. The simplest solution `(setq ispell-check-comments nil)` does not do anything. I also tried to let ispell ignore all lines commented out by % with
```
(defun flyspell-ignore-TeX-comments ()
"Ignore lines starting with %."
(not (string-match "^ *%" (thing-at-point 'line t))))
(put 'text-mode 'flyspell-mode-predicate 'flyspell-ignore-TeX-comments)
```
This did not do anything either. The comments are recognized as such, though, since they are colored by `font-lock-comment-face`. I have explicitly turned off `flyspell-prog-mode` with `(add-hook 'prog-mode-hook 'turn-off-flyspell t)`.
And now for the weirdest part. When I go to `Tools -> Spell-Checking -> Customize`, emacs tells me that `ispell Check Comments` is toggled *off* and if I spell-check my document with `Tools -> Spell-Checking -> Spell-Check Buffer`, they are ignored as intended, but if I run `M-x flyspell-buffer RET`, they are not!
Does anyone have an idea what I did wrong?
# Answer
`flyspell` and `ispell` are two different packages.
Yes, `flyspell` does use a bit of APIs of `ispell`.
But it does not mean you can set any flag of `ispell` to tweak `flyspell`. It's very possible the flag has no impact on the limited APIs which `flyspell` uses.
To use your predicate, you need run `(flyspell-mode 1)` at least once.
It's because `flyspell-mode-on` will load your per major mode predicate `flyspell-ignore-TeX-comments` into `flyspell-generic-check-word-predicate`.
Code from `flyspell-mode-on`,
`flyspell-mode` and `flyspell-prog-mode` are two minor modes to automate the spelling check. You can only turn on one of them.
By default, they are not turned on. So I don't understand why you need turn off `flyspell-prog-mode`.
I'm not sure `(add-hook 'prog-mode-hook 'turn-off-flyspell t)` can turn off `flyspell-prog-mode`. To turn off `flyspell-prog-mode`, you need `(flyspell-prog-mode -1)`.
BTW, you can use https://github.com/redguardtoo/wucuo instead of `flyspell-mode` or `flyspell-prog-mode`.
> 1 votes
---
Tags: latex, auctex, flyspell
--- |
thread-66306 | https://emacs.stackexchange.com/questions/66306 | Do something for all regular expression matches | 2021-06-15T02:44:50.880 | # Question
Title: Do something for all regular expression matches
I have a named-and-saved keyboard macro that I want to apply to all regular expression matches. How to do that?
(Related: I found this stackoverflow post: Running a macro till the end of text file in Emacs. It kind of works for now, but it is not satisfactory for the following reasons:
1. Not aesthetically pleasing: why run for all lines when you want to run for all matches?
2. Error messages: because the macro is supposed to be run for all matches and not for all lines.)
# Answer
> 1 votes
You can do that simply by recording the search for that regexp as the first part of your macro and using `M-0``<f4>` to execute the macro -- per the Q&A you linked to, a prefix arg of zero repeats the macro indefinitely until you type `C-g` or an error occurs (which is what will happen when the search fails). Refer also to `C-h``i``g` `(emacs)Basic Keyboard Macro`.
This doesn't avoid triggering an error (and indeed it's necessary), but this is the normal way of repeating a macro as many times as needed. Unless that's causing you a genuine problem (how?) then my advice is to just accept it.
Failing that, you can do what you want in elisp. Depending on how the named macro has been stored you should be able to use one of the following:
```
(while (re-search-forward REGEXP nil t)
(your-macro-name))
```
or
```
(while (re-search-forward REGEXP nil t)
(execute-kbd-macro 'your-macro-name))
```
You wouldn't record the search as part of this macro, of course.
---
Tags: regular-expressions, keyboard-macros
--- |
thread-66300 | https://emacs.stackexchange.com/questions/66300 | org mode export to latex a backslash followed by ordinary text | 2021-06-14T11:57:56.413 | # Question
Title: org mode export to latex a backslash followed by ordinary text
The following `org-mode` MCE points out a problem when one wants to export a backslash immediately followed by ordinary text (e.g. `~\~foo` is exported to `\textasciitilde{}$\backslash$~foo` where one expects `\texttt{\textbackslash{}}foo`). As a poor man workaround, one can insert a line break between `~\~` and `foo` but this inserts a line break in the exported `.tex` file and hence a space in the resulting PDF.
How to workaround this issue?
```
~\~
~\foo~
~\~foo
~\~
foo
=\=
=\foo=
=\=foo
=\=
foo
```
# Answer
> 2 votes
You can use a zero width space for this (https://orgmode.org/manual/Escape-Character.html). This will allow the code markup to work, but will not be visible in the export, or in the org file. That char acts like a space, but it has zero width. If you need this a lot there is a convenient function and key binding to insert a zero width space at https://thewanderingcoder.com/2015/03/emacs-org-mode-styling-non-smart-quotes-zero-width-space-and-tex-input-method/.
---
Tags: org-mode, org-export, latex
--- |
thread-46353 | https://emacs.stackexchange.com/questions/46353 | How to quickly convert text to org-mode table? | 2018-12-01T10:12:32.013 | # Question
Title: How to quickly convert text to org-mode table?
windows 10, emacs 26.1
Supose I have the following text:
```
OwnerKey OrganizationName GUID
111192 Infocom 41EA23423423423423423C8-62A61A1532C5
345423 TV A3B8F234234234234239FA5-4D71242359EE
123423 TV A3B823423423424234-234234234322659EE
```
I need to create something like this:
```
| OwnerKey | OrganizationName | GUID |
|----------+------------------+--------------------------------------|
| 111192 | Infocom | 41EA23423423423423423C8-62A61A1532C5 |
| 345423 | TV | A3B8F234234234234239FA5-4D71242359EE |
| 123423 | TV | A3B823423423424234-234234234322659EE |
```
How I can do this quickly. I don't want to do this manually line by line.
# Answer
> 7 votes
Select the data.
`M-x table-capture`
Now it will ask questions like what is the delimiter etc.
For column delimiter hit space key
Row delimiter is `RET`, but we can't use it because it's the confirmation key, so you need to hit
`C-q C-j`
Other options you can probably leave at their defaults.
# Answer
> 12 votes
You find the `Tbl` menu at the right side of the `Org` menu. Mark the region you want to convert to an org-table and click on the menu item `Tbl -> Convert Region`.
The result is a table without header:
```
| OwnerKey | OrganizationName | GUID |
| 111192 | Infocom | 41EA23423423423423423C8-62A61A1532C5 |
| 345423 | TV | A3B8F234234234234239FA5-4D71242359EE |
| 123423 | TV | A3B823423423424234-234234234322659EE |
```
Adding the missing header is easy. Place point behind the first line Press `RET` for a newline and input the two characters `|-` and a `tab`. This adjusts the underlining of the header automagically.
---
You can use the minor mode `orgtbl-mode` also in buffers that are not in `org-mode` but in other major modes like `text-mode`.
Just call `M-x` `orgtbl-mode` `RET` and you get a new menu `OrgTbl` in the menu bar.
There you find the menu item `Create or Convert` bound to the key `C-|`. That works very similar to the above `Convert Region`.
It may be that you cannot insert the newline for the header underlining by just typing `RET` behind the first line. In that case type `C-q C-j` instead of `RET` to insert a newline.
Everything else works like for `Convert Region` above.
The really nice thing is that you even can insert `#+TBLFM:` lines below the table. Those lines work like in `org-mode` when you type `C-c C-c` on them.
# Answer
> 5 votes
While I really liked the answers here, I personally found that both `table-capture` and `orgtbl-create-or-convert-from-region` did not suit my situation well. So here's another option:
Select the text and use either `M-x` `replace-regexp` or `M-x` `query-replace-regexp` for each of the following:
1. `^` -\> `|` (`|``space`)
2. -\> `|` (three spaces to `space``|``space`)
3. `$` -\> `|` (`space``|`)
Finally, insert a line after the heading and type `|``-``TAB` to create a horizontal rule and align the table.
---
Tags: org-mode, org-table
--- |
thread-66308 | https://emacs.stackexchange.com/questions/66308 | Are the Control & Meta "digit argument" bindings duplicates? | 2021-06-15T06:24:03.400 | # Question
Title: Are the Control & Meta "digit argument" bindings duplicates?
As far as I can tell the Meta and Control `digit-argument` bindings (`C-1, C-2, C-3`, `M-1, M-2, M-3`) are duplicates.
There are so few single-modifier, single-key bindings available, it seems like a perfect opportunity for personal bindings.
Is there any special reason one shouldn't use, for example, all the Meta-digit bindings for their own needs?
# Answer
Yes, they are duplicates. If you want to use one of them for your own purposes, I would recommend to keep the meta ones and rebind the control ones. One reason to keep the meta ones is that if you run Emacs in a terminal, most terminals don't transmit `*digit*` differently from plain `Ctrl`+`*digit*`, which makes `Ctrl`+`*digit*` bindings inaccessible. On the other hand text terminals transmit `Meta`+`*digit*` as `Esc` `*digit*`. Another reason to keep the meta bindings is that they are the same bindings that let you type `Esc` `*digit*`…, since the `Meta` (`M-`) modifier is equivalent to the `Esc` (`ESC`) prefix.
If you really want, you can even rebind both, since the same functionality is also available by typing `Ctrl`+`U` and then digits without any modifier. So for example all of the following are equivalent and move the point 12 words to the left:
```
C-1 C-2 C-left
M-1 M-2 M-b
C-u 1 2 C-left
ESC 1 2 C-left
M-1 C-2 M-b
…
```
> 3 votes
# Answer
They are duplicates, indeed. The reason they exist is to make it more ergonomic to type digit arguments regardless if the next command uses Meta or Control. For example, typing `C-5 M-f` is very convoluted; `M-5 M-f` is much easier.
You are free to bind them to your own commands if you like.
> 3 votes
---
Tags: key-bindings, prefix-argument
--- |
thread-66321 | https://emacs.stackexchange.com/questions/66321 | How to "pipe" a string to a shell command in elisp rather than give it as an arg? | 2021-06-15T17:58:21.720 | # Question
Title: How to "pipe" a string to a shell command in elisp rather than give it as an arg?
The command I'm trying to duplicate:
`curl https://example.com | readability https://example.com`
As far as I can see, though, using that `|` pipe is NOT the same as passing the string in as an arg. If I have a string that I am ready to pass to readability, how may I do it in a manner with parity of the bash pipe?
# Answer
See `shell-command-on-region` (suggestively bound to `M-|`). You can select a region and call `shell-command-on-region`, specifying the `readability` command. The region becomes the standard input for the command.
To pass a string, you can create a temp buffer and insert the string, then set the region to the whole buffer before doing the above. This is done often enough in emacs to make it into an idiom: it's a common technique.
> 3 votes
# Answer
Correct. In a shell like Bash, the pipe character `|` forwards the output of the command on the left into the input of the command on the right. Whatever the first command prints to file descriptor 1 (which is called the “standard output”) is available for the second command to read from file descriptor 0 (the “standard input”). There are at least two ways to emulate this:
The first is to call `start-process` to start the second command asynchronously. The return value is a process object that you will need for the next step. Next, call `make-process` to run the first command. Use the `:filter` argument to specify a function that will send all output to the second command using `process-send-string`. Something like this, perhaps:
```
(let (proc2 (start-process "readability" nil "readability" url))
(make-process :name "curl"
:buffer nil
:command (list "curl" url)
:filter (lambda (proc output)
(process-send-string proc2 output))))
```
Another option would be to use the command `start-process-shell-command`, which gives your command to a shell rather than executing it directly. You should be able to give it your pipeline directly, though I’ve never done that before. This option is preferable because it is simpler to write and to understand, though it may be less flexible. On the other hand, quoting things correctly for the shell can be annoying and cumbersome: Something like this:
```
(start-process-shell-command "readability" "readability"
(concat "curl "
(shell-quote-argument url)
" | "
"readability "
(shell-quote-argument url)))
```
You should also search the packages on ELPA to see if there is anything that lets you create pipelines using a nicer syntax.
> 2 votes
---
Tags: shell, bash, pipe
--- |
thread-55579 | https://emacs.stackexchange.com/questions/55579 | AUCTeX: only use monospace for rendering macros? | 2020-02-17T06:42:10.700 | # Question
Title: AUCTeX: only use monospace for rendering macros?
I've been using the fontify features of AUCTeX, as well as magic-latex-buffer, to display my TeX code in a more readable way.
But I'm wondering if I can crank this up to 11: is there a way to render the document text in a variable width font, but have any actual LaTeX code (macros, etc.) rendered using a monospace font.
This isn't a true WYSIWYG, but it at least would make the buffer contents feel more like the final document.
# Answer
You can make the face used for math and the so-called sedate face used for macro names inherit from fixed-pitch, and activate variable-pitch-mode in the LaTeX mode hook:
```
(set-face-attribute 'font-latex-sedate-face nil :inherit 'fixed-pitch)
(set-face-attribute 'font-latex-math-face nil :inherit 'fixed-pitch)
(add-hook 'LaTeX-mode-hook #'variable-pitch-mode)
```
> 3 votes
# Answer
Alternatively, you can use the `mixed-pitch-mode` package to do precisely this.
If you don't like the presets, you can remove/add faces to `mixed-pitch-fixed-pitch-faces`. For example, if you want to fontify section headers, remove `font-latex-sectioning-5-face`. To enable by default set the LaTeX mode hook:
```
(add-hook 'LaTeX-mode-hook #'variable-pitch-mode)
```
> 2 votes
---
Tags: latex, auctex, font-lock, highlighting, tex
--- |
thread-66325 | https://emacs.stackexchange.com/questions/66325 | New line and indent without electric mode | 2021-06-15T21:43:16.417 | # Question
Title: New line and indent without electric mode
I have come to hate the inconsistency of the electric indent mode and I haven't much of a clue about how it works anyways, so I've disabled it and am trying to get the desired behavior from scratch. I want emacs to indent me to the previous line's indentation level *and do nothing else* on `RET`. `indent-relative` seems to be the right function for the job. Seems easy enough, and yet I cannot get it to work. This is what I have thus far:
```
(electric-indent-mode -1)
(defun my-newline-and-indent ()
(interactive)
(newline)
(indent-relative))
```
I used to bind this with `global-set-key`, but hooking it to the specific modes I use is a better idea (found here):
```
(defun my-keys ()
(local-set-key [(return)] 'my-newline-and-indent))
(add-hook 'c-mode-hook 'my-keys)
```
The above does not indent new lines in C. I also tried the same thing with `indent-relative-maybe`, but that doesn't work either. What am I doing wrong?
---
Edit: now that I got it working thanks to @Tyler, the function that better fits the behavior I want is actually `indent-relative-maybe` (though I can't find any documentation on it online). `indent-relative` indents to the last whitespace on the previous line, which is too zealous. For example, here is how it indents in F90 mode:
```
program test
_
```
By contrast, `indent-relative-maybe` seems to only indent to the first non-whitespace character.
# Answer
> 2 votes
In a terminal the value of `[(return)]` doesn't apply. You need to use `(kbd "RET")` instead. (or probably other variations would do, but not `[(return)]`).
---
Tags: key-bindings, indentation, minor-mode, electric-indent
--- |
thread-38793 | https://emacs.stackexchange.com/questions/38793 | How to detect if emacs starts with a file? | 2018-02-12T23:40:23.457 | # Question
Title: How to detect if emacs starts with a file?
I would like to be able to implement the following logic.
```
(if (developer-opened-file-with-emacs)
(do nothing, get on with working as fast as possible)
(load fancy splash screen that may take a while))
```
What would be a good way to detect this case so that I may use this to choose what kind of startup behavior to use?
Another way to say this is: Will emacs show `*scratch*` buffer once it's started.
---
Examples of opening emacs with a file include:
```
emacs somefile.txt
```
Or using elisp:
```
emacs --eval '(progn (find-file "test.txt"))'
```
---
*Note that checking `argv` isn't a good option since elisp may be used in a command line argument to open files.*
# Answer
> 2 votes
As pointed out in the comment by @ideasman42, you can use `buffer-file-name` (both variable and function):
```
(defun tim/run-after-emacs-is-loaded ()
(if (not buffer-file-name)
(tim/load-session)))
(add-hook 'window-setup-hook #'tim/run-after-emacs-is-loaded)
```
---
Tags: start-up
--- |
thread-12899 | https://emacs.stackexchange.com/questions/12899 | Can Emacs use tramp to run in an interactive session on a remote HPC node? | 2015-06-04T17:06:03.633 | # Question
Title: Can Emacs use tramp to run in an interactive session on a remote HPC node?
I have been using Emacs with ESS and tramp to load remote files and run remote R processes on HPC computers. With ssh keys, tramp makes this easy with `C-x C-f` to find file at `/ssh:myserver:/path/to/file` followed by `M-x R` to launch an R session.
However, on HPC computers that use a job scheduling system (e.g. Sun Grid Engine or Torque) there are restrictions on how much memory and CPU can be used on the head node, so I have to launch an interactive session using `qsub -I`.
Is it possible to configure tramp, ssh, and/or Emacs to launch an interactive session on a slave node (using `qsub -I` or equivalent) after an ssh connection is made?
# Answer
It sounds like you should extend `tramp-methods`, adding a new method which is similar to the `sudo` method but uses `qsub -I` instead. You would then be able to use a multi-hop tramp path to first connect to the head node and then to connect to a compute node.
Try this:
```
(add-to-list 'tramp-methods
'("qsub"
(tramp-login-program "qsub")
(tramp-login-args (("-I"))) ; other options here?
;; Local $SHELL could be a nasty one, like zsh or fish. Let's override it.
(tramp-login-env (("SHELL") ("/bin/sh")))
(tramp-remote-shell "/bin/sh")
(tramp-remote-shell-args ("-c"))
(tramp-connection-timeout 10)))
```
You would then use a tramp path like `/ssh:myserver|qsub:myserver:/path/to/file`.
You may need to specify other options to pass to qsub; I've not used it so I can't help you there. You'll also want to look over the other options you can specify on a tramp method; there are a couple of dozen listed in tramp.el.
> 7 votes
# Answer
I have been struggling to do the same. I found a different route that allowed me to do basically the same thing.
You can open a shell buffer by `M-x shell` and from there connect to the login node, and then connect to the interactive session by `qsub -I`. Once you're in the interactive session, start an R session by typing the command `R`. There, you can do `M-x ess-remote`. This will prompt a mini-buffer asking which program you want to run (R, S+, Stata, etc.) Once you select R, then you can use the R session on the remote shell just as you use ESS in the local machine.
I personally open Rscripts saved in the remote node by tramping into it (in a separate window) and work with the R session connected by the `ess-remote` as described above. This way, the R session can directly interact with the Rscripts that I am working with. (For example, `source('code.R')` command in R will be able to read the 'code.R' in the HPC cluster, which I might have just edited. If I was editing Rscripts in my local machine instead, the ess-remote session of R wouldn't be able to read them unless I uploaded them to the remote node each time.)
> 6 votes
# Answer
I am using a cluster with pjsub rather than qsub, but I have had success with the following. First, create an expect script called, say, inter\_R.sh:
```
#!/usr/bin/expect --
set cmdargs [lrange $argv 0 end]
set timeout 130
spawn -nottyinit pjsub --interact -g groupname -L rscgrp=interactive --sparam wait-time=120 -X --X11
expect -ex "username/ #$ "
send "stty -echo\n"
send "echo /usr/bin/R $cmdargs \n"
send "exec /usr/bin/R $cmdargs \n"
interact
```
Then in emacs customize, set "Inferior Ess R Program" to be /home/username/inter\_R.sh. Now, use tramp to open a connection to a login node on the cluster (say, a directory listing of /home/username). Now do M-x R to start R in that tramp buffer. This will run inter\_R.sh on the login node, which will start an interactive job on a compute node and run R on that compute node.
An important argument to pjsub is the -X, which passes all the environment variables through. Without this the shell prompt on the compute node is different than what emacs is expecting because $PS1 isn't passed through. Hopefully qsub would have some equivalent.
> 1 votes
---
Tags: tramp, ess, interactive, ssh
--- |
thread-66284 | https://emacs.stackexchange.com/questions/66284 | use-package session example please | 2021-06-12T18:26:24.217 | # Question
Title: use-package session example please
I want to setup `session` with `use-package` but I don't know elisp except copying from working code. Here is what I've copied:
```
;;;_* session
(use-package session
:if (not noninteractive)
:load-path "site-lisp/session/lisp/"
:init
(progn
(session-initialize)
(defun remove-session-use-package-from-settings ()
(when (string= (file-name-nondirectory (buffer-file-name)) "settings.el")
(save-excursion
(goto-char (point-min))
(when (re-search-forward "^ '(session-use-package " nil t)
(delete-region (line-beginning-position)
(1+ (line-end-position)))))))
(add-hook 'before-save-hook 'remove-session-use-package-from-settings)
;; expanded folded secitons as required
(defun le::maybe-reveal ()
(when (and (or (memq major-mode '(org-mode outline-mode))
(and (boundp 'outline-minor-mode)
outline-minor-mode))
(outline-invisible-p))
(if (eq major-mode 'org-mode)
(org-reveal)
(show-subtree))))
(add-hook 'session-after-jump-to-last-change-hook
'le::maybe-reveal)
(defun save-information ()
(with-temp-message "Saving Emacs information..."
(recentf-cleanup)
(loop for func in kill-emacs-hook
unless (memq func '(exit-gnus-on-exit server-force-stop))
do (funcall func))
(unless (or noninteractive
running-alternate-emacs
(eq 'listen (process-status server-process)))
(server-start))))
(run-with-idle-timer 300 t 'save-information)
(if window-system
(add-hook 'after-init-hook 'session-initialize t))))
```
But I am getting the following error with `--debug-init`:
```
Debugger entered--Lisp error: (void-function session-initialize)
(session-initialize)
(progn (session-initialize) (defalias 'remove-session-use-package-from-settings #'(lambda nil (if (string= (file-name-nondirectory (buffer-file-name)) "settings.el") (progn (save-excursion (goto-char ...) (if ... ...)))))) (add-hook 'before-save-hook 'remove-session-use-package-from-settings) (defalias 'le::maybe-reveal #'(lambda nil (if (and (or (memq major-mode ...) (and ... outline-minor-mode)) (outline-invisible-p)) (progn (if (eq major-mode ...) (org-reveal) (show-subtree)))))) (add-hook 'session-after-jump-to-last-change-hook 'le::maybe-reveal) (defalias 'save-information #'(lambda nil (let ((with-temp-message "Saving Emacs information...") (current-message)) (unwind-protect (progn (if with-temp-message ...) (recentf-cleanup) (let* ... ... nil) (if ... nil ...)) (and with-temp-message (if current-message ... ...)))))) (run-with-idle-timer 300 t 'save-information) (if window-system (add-hook 'after-init-hook 'session-initialize t)))
(condition-case err (progn (session-initialize) (defalias 'remove-session-use-package-from-settings #'(lambda nil (if (string= (file-name-nondirectory ...) "settings.el") (progn (save-excursion ... ...))))) (add-hook 'before-save-hook 'remove-session-use-package-from-settings) (defalias 'le::maybe-reveal #'(lambda nil (if (and (or ... ...) (outline-invisible-p)) (progn (if ... ... ...))))) (add-hook 'session-after-jump-to-last-change-hook 'le::maybe-reveal) (defalias 'save-information #'(lambda nil (let ((with-temp-message "Saving Emacs information...") (current-message)) (unwind-protect (progn ... ... ... ...) (and with-temp-message ...))))) (run-with-idle-timer 300 t 'save-information) (if window-system (add-hook 'after-init-hook 'session-initialize t))) ((debug error) (funcall use-package--warning10 :init err)))
(progn (condition-case err (progn (session-initialize) (defalias 'remove-session-use-package-from-settings #'(lambda nil (if (string= ... "settings.el") (progn ...)))) (add-hook 'before-save-hook 'remove-session-use-package-from-settings) (defalias 'le::maybe-reveal #'(lambda nil (if (and ... ...) (progn ...)))) (add-hook 'session-after-jump-to-last-change-hook 'le::maybe-reveal) (defalias 'save-information #'(lambda nil (let (... ...) (unwind-protect ... ...)))) (run-with-idle-timer 300 t 'save-information) (if window-system (add-hook 'after-init-hook 'session-initialize t))) ((debug error) (funcall use-package--warning10 :init err))) (if (not (require 'session nil t)) (display-warning 'use-package (format "Cannot load %s" 'session) :error)))
(condition-case err (progn (condition-case err (progn (session-initialize) (defalias 'remove-session-use-package-from-settings #'(lambda nil (if ... ...))) (add-hook 'before-save-hook 'remove-session-use-package-from-settings) (defalias 'le::maybe-reveal #'(lambda nil (if ... ...))) (add-hook 'session-after-jump-to-last-change-hook 'le::maybe-reveal) (defalias 'save-information #'(lambda nil (let ... ...))) (run-with-idle-timer 300 t 'save-information) (if window-system (add-hook 'after-init-hook 'session-initialize t))) ((debug error) (funcall use-package--warning10 :init err))) (if (not (require 'session nil t)) (display-warning 'use-package (format "Cannot load %s" 'session) :error))) ((debug error) (funcall use-package--warning10 :catch err)))
(progn (defvar use-package--warning10 #'(lambda (keyword err) (let ((msg (format "%s/%s: %s" ... keyword ...))) (display-warning 'use-package msg :error)))) (condition-case err (progn (condition-case err (progn (session-initialize) (defalias 'remove-session-use-package-from-settings #'(lambda nil ...)) (add-hook 'before-save-hook 'remove-session-use-package-from-settings) (defalias 'le::maybe-reveal #'(lambda nil ...)) (add-hook 'session-after-jump-to-last-change-hook 'le::maybe-reveal) (defalias 'save-information #'(lambda nil ...)) (run-with-idle-timer 300 t 'save-information) (if window-system (add-hook 'after-init-hook 'session-initialize t))) ((debug error) (funcall use-package--warning10 :init err))) (if (not (require 'session nil t)) (display-warning 'use-package (format "Cannot load %s" 'session) :error))) ((debug error) (funcall use-package--warning10 :catch err))))
(if (not noninteractive) (progn (defvar use-package--warning10 #'(lambda (keyword err) (let ((msg ...)) (display-warning 'use-package msg :error)))) (condition-case err (progn (condition-case err (progn (session-initialize) (defalias 'remove-session-use-package-from-settings #'...) (add-hook 'before-save-hook 'remove-session-use-package-from-settings) (defalias 'le::maybe-reveal #'...) (add-hook 'session-after-jump-to-last-change-hook 'le::maybe-reveal) (defalias 'save-information #'...) (run-with-idle-timer 300 t 'save-information) (if window-system (add-hook ... ... t))) ((debug error) (funcall use-package--warning10 :init err))) (if (not (require 'session nil t)) (display-warning 'use-package (format "Cannot load %s" 'session) :error))) ((debug error) (funcall use-package--warning10 :catch err)))))
eval-buffer(#<buffer *load*-868872> nil "/home/...
```
I cannot figure out anything from the above error message.
Somebody give me a working use-package session example please.
# Answer
> 0 votes
Adapted from https://github.com/ronert/.emacs.d/blob/master/lisp/init-sessions.el#L29
```
(use-package session
:ensure t
;:pin melpa-stable
:config
(progn
(setq session-save-file (expand-file-name "~/.emacs.d/.session"))
(add-hook 'after-init-hook 'session-initialize)
;; save a bunch of variables to the desktop file
;; for lists specify the len of the maximal saved data also
(setq desktop-globals-to-save
(append '((extended-command-history . 30)
(file-name-history . 100)
(grep-history . 30)
(compile-history . 30)
(minibuffer-history . 50)
(query-replace-history . 60)
(read-expression-history . 60)
(regexp-history . 60)
(regexp-search-ring . 20)
(search-ring . 20)
(comint-input-ring . 50)
(shell-command-history . 50)
desktop-missing-file-warning
tags-file-name
register-alist)))
))
```
Tested fine.
# Answer
> 1 votes
`use-package`'s `:init` block is run *before* the package has been loaded. Try putting the code inside a `:config` block instead, like:
```
(use-package session
:config
(session-initialize)
(defun ...
```
I also removed the `progn`, as `use-package` allows multiple statements in the `:config` block.
EDIT: as requested in a comment, the desktop-save-mode use-package block:
```
(use-package desktop
:ensure nil
:config
(desktop-save-mode))
```
---
Tags: use-package, config, session
--- |
thread-16668 | https://emacs.stackexchange.com/questions/16668 | How to customize files pattern while using rgrep? | 2015-09-16T16:53:36.387 | # Question
Title: How to customize files pattern while using rgrep?
elpy-mode internally uses this command to search for a `regexp` in \*.py files.
```
(setq elpy-rgrep-file-pattern "*.py")
(rgrep regexp
elpy-rgrep-file-pattern
default-directory))
```
However `elpy-rgrep-file-pattern` is customisable. I want to include html files also while searching.
I have tried the following patterns
```
(setq elpy-rgrep-file-pattern "*.py|*.html")
(setq elpy-rgrep-file-pattern "*.py\|*.html")
(setq elpy-rgrep-file-pattern "*.(py\|html)")
(setq elpy-rgrep-file-pattern "py\|html")
(setq elpy-rgrep-file-pattern '(("html" . "*.html") ("py" . "*.py")))
```
but nothing seems to work. How do I correctly specify file pattern to search \*.py & \*.html files?
# Answer
> 4 votes
`rgrep` takes as its second argument file description in a format similar to shell globbing, which also exists in other languages, for example, in Python.
There's also a useful variable in Emacs related to `rgrep`: `grep-files-aliases`, which can be customized to alias various file groups, for instance
```
(push (cons "pyml" "*.py *.htm *.html") grep-files-aliases)
```
will add an alias `pyml` for files with extensions `py`, `htm` and `html`. After evaluating the code above, one should be able to execute:
`M-x``rgrep``RET``search query``RET``pyml``RET` in order to search in files with the extensions aliased by `pyml`.
# Answer
> 0 votes
`rgrep` does not accept spaces in the mini-buffer at the "files matching wildcard" prompt.
The workaround is to pass in:
```
*[.py,.htm,.html,pyml]
```
If just looking through extensions:
```
*.[py,htm,html]
```
---
Tags: regular-expressions, elpy, rgrep
--- |
thread-448 | https://emacs.stackexchange.com/questions/448 | What is the easiest way to search all useful files inside a single project? | 2014-09-29T11:40:49.163 | # Question
Title: What is the easiest way to search all useful files inside a single project?
**What is the easiest way to search for a regexp throughout the contents all files in the current project, skipping files that are not useful?**
Useless files are things like compiled files, imported libraries, version-control files, etc.
I’m aware of `rgrep`, but it just searches everything. Is there a package that searches ‘inteligently’ and knows about several different programming languages, so I wouldn’t have to configure it for each individual project?
# Answer
> 41 votes
Project based searching within Emacs can be done using projectile.
It allows for per-project configuration of ignore files (in a `<projectroot>\.projectile` file), or specify subdirectories to monitor and ignore all others.
It can run `grep`, `ack` (requires `ack-and-a-half.el`) and `ag` (`ag.el`) on files within the defined project (either based on the `.projectile` file or by finding a supported VC file to define a project root).
### Useful Commands
(With regards to searching through useful files)
As per Projectile Readme
* `C-c p s g` :: Run `grep` on the files in the project.
* `C-c p s a` :: Runs `ack` on the project. Requires the presence of ack-and-a-half.
* `C-c p s s` :: Runs `ag` on the project. Requires the presence of ag.el.
* `C-c p f` :: Display a list of all files in the project.
* `C-c p d` :: Display a list of all directories in the project.
* `C-c p a` :: Switch between files with the same name but different extension in the project.
* `C-c p o` :: Runs `multi-occur` on all project buffers currently open.
These will only act on files defined as being part of the project (or found when the cache is generated/regenerated).
# Answer
> 14 votes
The project-wide search of only relevant files can be done using `ag` aka the\_silver\_searcher.
### Why ag?
* It ignores file patterns from your `.gitignore`, `.hgignore`, `svn:ignore`. *You can choose for your searches to NOT use the ignore list from the version-control ignore lists by using the `-U` switch.*
* If there are files in your source repo you don't want to search, just add their patterns to a `.agignore` file.
+ A global `.agignore` file can be put in your `$HOME` and then you can put more project specific `.agignore` files in your project roots.
### Setting up `ag` and emacs
* Install `ag` aka the\_silver\_searcher on your system.
* Set up the `.agignore` file. *I prefer to have just a global `.agignore` file in my `$HOME`.*
* Install the `ag` package (available on Melpa).
* You can then use the `ag-project` or `ag-project-regexp` function (that come with the `ag` package) to do project-wide file searches.
+ By default, these functions use the root of the VCS repo as the directory to search in. You can override this by setting or customizing the `ag-project-root-function`.
+ Even if your project is not git controlled, you can mark a project-root for the `ag-project` / `ag-project-regexp` based searches by putting an empty `.git` folder in your project root. You then don't have to customize `ag-project-root-function`.
# Answer
> 8 votes
If your project uses Git, you only need `counsel` https://github.com/abo-abo/swiper
* `counsel-git` to find file
* `counsel-git-grep` to grep
The only dependency is git
Text grepping is faster than the silver searcher (ag)
Counsel also provides other powerful tools. For example, after running `counsel-git-grep`, you can press `C-c C-o` and `C-x C-q` to go into `wgrep-mode` to easily replace text in the project scope.
There is an article https://sam217pa.github.io/2016/09/11/nuclear-power-editing-via-ivy-and-ag/ explaining details. That article uses `counsel-ag` (another command built into counsel) but `cousnel-git-grep` uses exactly same work flow.
# Answer
> 1 votes
The first answer is beautiful, but it leaves out some critical details about modern versions of Emacs. I am knew to Emacs myself, so other newcomers might not be aware of this. Given your goal is to search for text WITHIN a file in a PROJECT, then you would first install Projectile using the MELPA repository.
This installs the package in .emacs.d and adds some basic configuration to .emacs in your $USER directory (assuming you had created the .emacs file), such as requiring Projectile in your Emacs install.
However, you still need to enable it and associate keymap prefixes, so you can invoke it in the mini buffer.
The accepted answer mentions the following command:
```
C-c p s g
```
This will not work, unless you configure Projectile with this keymap prefix. But I configured it to use C-c C-p as the command for Project in .emacs:
```
(projectile-mode +1)
(define-key projectile-mode-map (kbd "C-c C-p") 'projectile-command-map)
```
Now given this, I am able to perform text searches in files in a project using grep:
```
C-c C-p f # switch to a project first
C-c C-p s g # perform grep search in project
```
To break it down, `C-c C-p` will invoke Projectile, and `s g` will perform the grep search. You will get a beautiful output like this, assuming your search is `visit_contact` and you are searching Ruby's rspec in a project:
```
./spec/support/capybara_classification_code_helper.rb:21: def visit_contact
./spec/features/admin_edits_classification_code_role_dynamic_field_spec.rb:8: visit_contact
./spec/features/admin_edits_classification_code_role_dynamic_field_spec.rb:33: visit_contact
./spec/features/user_views_global_filters_from_line_item_spec.rb:9: visit_contact
```
# Answer
> 1 votes
`M-x` `rgrep` `search-pattern` `*.[c,h]`
---
Tags: search, project
--- |
thread-66341 | https://emacs.stackexchange.com/questions/66341 | How to automatically open the debugger whenever `kill-buffer` is invoked? | 2021-06-16T20:09:02.220 | # Question
Title: How to automatically open the debugger whenever `kill-buffer` is invoked?
I'm using Elpy for Python development, and when I run code with `C-c C-c` the source buffer closes -- which I don't want. Have to constantly reopen.
One idea is to set a breakpoint in `kill-buffer` \- except upon doing `C-h f on kill-buffer` I find that it's written in C source code. How then would I debug invocations of `kill-buffer`?
# Answer
`M-x debug-on-entry kill-buffer`
That opens the standard Emacs debugger whenever `kill-buffer` is invoked. It doesn't matter that it's a built-in (primitive, not coded in Lisp).
See the Elisp manual, nodes Function Debugging and Using Debugger.
> 3 votes
---
Tags: debugging, kill-buffer, debug
--- |
thread-33103 | https://emacs.stackexchange.com/questions/33103 | No org-babel-execute function for calc? | 2017-05-28T10:00:08.990 | # Question
Title: No org-babel-execute function for calc?
In `org-mode`:
```
#+BEGIN_SRC calc :var x=5 :var y=2
2+a*x**y
#+END_SRC
```
returns
```
No org-babel-execute function for calc!
```
How do I enable `calc` for `org-babel-execute`?
# Answer
As described in org documentation:
> By default, only 'emacs-lisp' is enabled for evaluation. To enable or disable other languages, customize the 'org-babel-load-languages' variable either through the Emacs customization interface, or by adding code to the init file as shown next:
>
> In this example, evaluation is disabled for 'emacs-lisp', and enabled for \`R'.
>
> ```
> (org-babel-do-load-languages
> 'org-babel-load-languages
> '((emacs-lisp . nil)
> (R . t)))
>
> ```
So here you could do the following:
```
(org-babel-do-load-languages
'org-babel-load-languages
'((calc . t)))
```
> 8 votes
# Answer
To add to JeanPierre's answer, you can run `M-x customize-variable` with `org-babel-load-languages` to modify the list from Emacs.
> 0 votes
---
Tags: org-mode, org-babel
--- |
thread-14197 | https://emacs.stackexchange.com/questions/14197 | How to prettify/format an XML buffer? | 2015-07-23T17:23:15.583 | # Question
Title: How to prettify/format an XML buffer?
I have a file with xml all on one line. Does the functionality already exist to reformat this buffer to be somewhat user-readable?
# Answer
> 37 votes
> Does the functionality already exist to reformat this buffer to be somewhat user-readable?
Of course, and you have plenty of options. I'd probably feed it to an external program using:
```
C-x h C-u M-| xmllint --format - RET
```
This program comes with `libxml2`. You could also use `tidy`. Here's a list of commandline xml formatting tools: https://stackoverflow.com/questions/16090869/how-to-pretty-print-xml-from-the-command-line
You could also do a search and replace and then indent:
`M-% > < RET > C-q C-j < RET ! C-M-\`
Neat trick: you can copy and paste the above string into `M-:` (`eval-expression`) like this:
```
(execute-kbd-macro (kbd "M-% > < RET > C-q C-j < RET ! C-M-\\"))
```
# Answer
> 33 votes
The built-in `sgml-mode` has a command to do this: `sgml-pretty-print`. If you're in `nxml-mode` it looks like you need switch to `sgml-mode` first. You could write a command to temporarily switch to sgml-mode, run pretty-print, then switch back to nxml-mode.
For example, here is a command that will pretty-print the region, optionally with auto-fill enabled:
```
(defun xml-pretty-print (beg end &optional arg)
"Reformat the region between BEG and END.
With optional ARG, also auto-fill."
(interactive "*r\nP")
(let ((fill (or (bound-and-true-p auto-fill-function) -1)))
(sgml-mode)
(when arg (auto-fill-mode))
(sgml-pretty-print beg end)
(nxml-mode)
(auto-fill-mode fill)))
```
# Answer
> 16 votes
Mark your xml and do:
```
M-x sgml-pretty-print
```
Or just run the command without a marked region to prettify the whole buffer.
# Answer
> 7 votes
write this into your `~/.emacs.d/init.el`:
```
(require 'sgml-mode)
(defun ninrod/reformat-xml ()
(interactive)
(save-excursion
(sgml-pretty-print (point-min) (point-max))
(indent-region (point-min) (point-max))))
```
reload emacs, then just call `M-x reformat-xml` on the badly formatted xml buffer.
source: https://davidcapello.com/blog/emacs/reformat-xml-on-emacs/
# Answer
> 5 votes
In `nxml-mode`, `C-x H` will mark the whole buffer and `TAB` will indent the selection.
# Answer
> 0 votes
Following the hint of the answer above, and assuming you have `tidy` installed a variation could be:
```
`C-x h M-| tidy -quiet -xml -utf8 -indent -`
```
This will open a new buffer `*Shell Command Output*` instead of directly replacing the contents of the buffer. After checking the result, replace the old contents with the new with:
```
C-x h M-insert-buffer
```
choose the suggested default which will probably be `*Shell Command Output*`. You can save the command for later with a keyboard macro:
```
C-x ( C-x h M-| tidy -quiet -xml -utf8 -indent - C-x)
C-x C-k n pretty-xml
```
With this you can execute `M-x pretty-xml` to reformat the buffer.
---
Tags: formatting, nxml, xml
--- |
thread-31906 | https://emacs.stackexchange.com/questions/31906 | in org-mode, a function to delete all properties drawers? | 2017-04-03T23:18:33.687 | # Question
Title: in org-mode, a function to delete all properties drawers?
I use Pandoc to convert from HTML and Markdown to org-mode. The conversion leaves lots of extraneous org-mode PROPERTIES drawers. How can I direct org-mode to delete all PROPERTIES drawers?
ADDITION: I'm using this shell script to run the conversion.
```
function pandoc2org () {
basename=${1%%.*} # remove old file extension
pandoc -s -S "$1" -o $basename.org # name file as oldfile.org
}
```
# Answer
If you don't mind using a shell script to accomplish what you want, you can try:
```
pandoc -t org file.md | sed -E "/^[[:space:]]+:/ d" > file.org
```
This will remove all lines starting with one (or more) spaces followed by a semicolon.
I believe you can fit it into your script by doing the following:
```
function pandoc2org () {
basename=${1%%.*}
pandoc -s -S "$1" -t org | sed -E "/^[[:space:]]+:/ d" > $basename.org
}
```
You can find an explanation of the function here.
> 4 votes
# Answer
I use
```
perl -0777 -pe 's/^\s*(:PROPERTIES:(.|\n)*?:END:)|(<<.*?>>)\s*$//gm'
```
to remove the extra stuff.
Also see this question.
> 0 votes
---
Tags: org-mode, pandoc
--- |
thread-2323 | https://emacs.stackexchange.com/questions/2323 | Can I change the background color of the inactive minibuffer? | 2014-10-18T10:00:21.457 | # Question
Title: Can I change the background color of the inactive minibuffer?
I tried it with the following settings:
```
(add-hook 'minibuffer-setup-hook
(lambda ()
(make-local-variable 'face-remapping-alist)
(add-to-list 'face-remapping-alist '(default (:background "green")))))
(set-face-background 'minibuffer-prompt "blue")
```
but they only affected the active minibuffer:
# Answer
> 6 votes
`minibuffer-setup-hook` is used only when the minibuffer is set up, i.e., activated, not when it is deactivated.
`minibuffer-exit-hook` takes effect when the minibuffer is exited. There is also `minibuffer-inactive-mode-hook`.
But although those do initiate the color change (as shown by adding `(debug)` at the beginning of the hook function, and then stepping through the debugger with `d`), it seems that `kill-local-variables` removes the added color at some point. I don't have time now to check further, but perhaps you can, or perhaps someone else has a quick solution. Sorry for providing only incomplete info.
Gotta go now - but quickly, I'm guessing that maybe you don't need to fiddle with hooks at all, and you can just do the face remapping for all buffers with names matching `\` \*Minibuf-[0-9]+\*\'`.
---
FWIW, I use a separate minibuffer frame, and I put this on `minibuffer-exit-hook` to color the frame background:
```
(defun 1on1-color-minibuffer-frame-on-exit ()
"Change background of minibuffer frame to reflect the minibuffer depth.
Use this when reducing the minibuffer recursion depth."
(when 1on1-minibuffer-frame
(save-window-excursion
(select-frame 1on1-minibuffer-frame)
(cond ((= (minibuffer-depth) 2)
(set-background-color 1on1-active-minibuffer-frame-background))
((< (minibuffer-depth) 2)
(set-background-color 1on1-inactive-minibuffer-frame-background))
(t
(set-background-color (hexrgb-increment-hue ; Change bg hue slightly.
(frame-parameter nil 'background-color)
1on1-color-minibuffer-frame-on-exit-increment)))))))
```
# Answer
> 4 votes
You might try:
```
(dolist (buf '(" *Echo Area 0*" " *Echo Area 1*"))
(with-current-buffer (get-buffer buf)
(make-local-variable 'face-remapping-alist)
(add-to-list 'face-remapping-alist '(default (:background "green")))))
```
# Answer
> 0 votes
I'm about to look into this in detail, but from the opposite point of view, highlighted when active, because boomer eyes. The minibuffer is a true, if specialized window/buffer, so I'm going to try simply setting the bg color to "noticeable" in the setup hook and "normal" in the exit hook. If that works then you can set the highlight you set the color when it first appears, then do that in reverse. Changing bg colors using
```
(cl-defun dp-set-buffer-background-color (color
&optional buffer
&key begin end (widenp t)
&allow-other-keys))
```
Although there are certainly better ways. This is very old.
---
Tags: customize, faces, minibuffer
--- |
thread-60936 | https://emacs.stackexchange.com/questions/60936 | When using flycheck, how to permanently disable pylint? | 2020-10-01T17:01:07.880 | # Question
Title: When using flycheck, how to permanently disable pylint?
I'm using Doom Emacs on macOS, if it matters.
Essentially, I'd like to disable the pylint checker entirely when editing Python files. I don't use pylint, and I don't have it installed in my Pyenv environments; it gives me false positives.
But I'm not a skilled Emacs user, and I can't figure out how to disable it. I have this in my config:
```
(use-package! flycheck
:config
(add-to-list 'flycheck-disabled-checkers 'python-pylint)
(add-hook 'pyhon-mode-local-vars-hook
(lambda ()
(when (flycheck-may-enable-checker 'python-flake8)
(flycheck-select-checker 'python-flake8)))))
```
But it doesn't seem to matter -- every time I open a Python file, it tries to start up pylint.
# Answer
This is working for me:
```
(use-package flycheck
:config
(setq-default flycheck-disabled-checkers '(python-pylint)))
```
> 3 votes
# Answer
I took a look at the flycheck docs and the following worked, as suggested by the docs:
```
(setq-default flycheck-disabled-checkers '(python-pylint))
```
> 0 votes
---
Tags: flycheck
--- |
thread-66354 | https://emacs.stackexchange.com/questions/66354 | What controls whether `M-x compile` splits a frame into two windows? | 2021-06-17T18:40:22.533 | # Question
Title: What controls whether `M-x compile` splits a frame into two windows?
To resolve some performance issues I refactored my `.emacs`, and since the refactoring, `M-x compile` does not split a frame into two windows. Instead, running `M-x compile` takes over the entire frame with a single `*compilation*` window. This workflow is not good for me, and I want to get the old behavior back: `M-x compile` should split the frame into two windows, or if the frame is already split, should put a `*compilation*` buffer in the *other* window. How can I accomplish this?
Searching has turned up a couple of questions addressing the opposite problem (How can I force emacs to never split frames, in particular for compile-goto-error? and How can I block a frame from being split?), but I've had no luck finding a way to force a split. How can I do it?
# Answer
> 3 votes
`compile` displays the output buffer using `display-buffer` (as do most other commands, fwiw). You can see this in compile.el, which is included with Emacs. There is always a link from the help for a function to the source code. Use `C-h f compile RET` to show the help for this function, then click the link. `compile` ends by calling `compile-start`, which does most of the work. The part you care about looks like this:
```
;; Pop up the compilation buffer.
;; http://lists.gnu.org/archive/html/emacs-devel/2007-11/msg01638.html
(setq outwin (display-buffer outbuf '(nil (allow-no-window . t))))
```
`outbuf` is the buffer that holds the compilation output. It calls `display-buffer` to make that buffer visible to the user in some way. It saves the resulting window in `outwin` because it probably queries or adjusts that window in some way; it may be necessary to examine what it does with that window, but for now I’m going to ignore it.
The key here is that `compile` does not care about how the buffer is displayed, that is `display-buffer`’s job. This allows `display-buffer` to handle policy decisions about where buffers should show up, without having to make `compile` care much about the details.
Let’s look at the help for `display-buffer` (you should use `C-h f` to view it in your Emacs as well):
```
display-buffer is an interactive compiled Lisp function in
‘window.el’.
(display-buffer BUFFER-OR-NAME &optional ACTION FRAME)
Display BUFFER-OR-NAME in some window, without selecting it.
BUFFER-OR-NAME must be a buffer or the name of an existing
buffer. Return the window chosen for displaying BUFFER-OR-NAME,
or nil if no such window is found.
Optional argument ACTION, if non-nil, should specify a display
action. Its form is described below.
Optional argument FRAME, if non-nil, acts like an additional
ALIST entry (reusable-frames . FRAME) to the action list of ACTION,
specifying the frame(s) to search for a window that is already
displaying the buffer. See ‘display-buffer-reuse-window’.
If ACTION is non-nil, it should have the form (FUNCTION . ALIST),
where FUNCTION is either a function or a list of functions, and
ALIST is an arbitrary association list (alist).
Each such FUNCTION should accept two arguments: the buffer to
display and an alist. Based on those arguments, it should
display the buffer and return the window. If the caller is
prepared to handle the case of not displaying the buffer
and returning nil from ‘display-buffer’ it should pass
(allow-no-window . t) as an element of the ALIST.
The ‘display-buffer’ function builds a function list and an alist
by combining the functions and alists specified in
‘display-buffer-overriding-action’, ‘display-buffer-alist’, the
ACTION argument, ‘display-buffer-base-action’, and
‘display-buffer-fallback-action’ (in order). Then it calls each
function in the combined function list in turn, passing the
buffer as the first argument and the combined alist as the second
argument, until one of the functions returns non-nil.
If ACTION is nil, the function list and the alist are built using
only the other variables mentioned above.
```
Yea, it’s pretty long (I didn’t even include most of it). There are a lot of things you can tweak and customize! Basically what it does is build a list of functions and call them each in turn until one of them has done the job. Most of these functions handle special cases, and return `nil` in the general case. The last function in the list should be one that handles the general case with some default action. You could add a special case for them to handle, or you could change what that final function is. Just be aware that doing the latter will change the behavior of everything calling `display-buffer`, which is a lot of things.
The content of the ACTION argument is also passed to each of these functions, and the content also changes their behavior. There are about half a dozen things you can put in there, and I’m not going to duplicate their documentation here.
Of the four variables mentioned in the documentation above, three default to nil. That is, they are places for the user to add customizations, rather than a place to put the default Emacs behavior. The final variable, `display-buffer-fallback-action`, is what implements the default Emacs behavior. On my system it has this value:
```
((display-buffer--maybe-same-window
display-buffer-reuse-window
display-buffer--maybe-pop-up-frame-or-window
display-buffer-in-previous-window
display-buffer-use-some-window
display-buffer-pop-up-frame))
```
Note however that I’m using a computer with an old version of Emacs today, so yours might be different. You can check with `C-h v`.
You can check the help for each of these functions to see exactly what they do (again, using `C-h f`), but the names are fairly clear. The final one in the list is the ultimate fallback, since it cannot fail except in quite exceptional circumstances.
The solution to your problem will depend greatly on how you have already customized Emacs, the details of your system (such as how many lines tall your Emacs frames can be, and so on), and on exactly what you want Emacs to do. As such I cannot offer very specific advice.
If you only want to change the behavior of `compile`, and not of other commands like `grep`, then I suggest adding an entry to `display-buffer-alist`. This alist contains entries whose first element is a regular expression that is matched against buffer names, so you can easily target just the `*compile*` buffer.
On the other hand, if you want to change the behavior of many commands then you should look at the functions listed in `display-buffer-fallback-action`. Each of these has customizable options you can tweak, such as how wide or tall a window must be before it can be split in half.
If all else fails, you could write a completely new function and add it to `display-buffer-overriding-action`. You could make it handle any cases you care about in whatever way you prefer. This can allow you to get the behavior you desire without needing to understand the plethora of existing options and behaviors.
Edit: something that might help you debug this is to trace all of the functions involved:
```
(dolist (action (car display-buffer-fallback-action))
(trace-function action))
(trace-function 'display-buffer)
```
You’ll end up with a trace buffer that looks something like this:
```
======================================================================
1 -> (display-buffer #<buffer *grep*> (nil (allow-no-window . t)))
| 2 -> (display-buffer--maybe-same-window #<buffer *grep*> ((allow-no-window . t)))
| 2 <- display-buffer--maybe-same-window: nil
| 2 -> (display-buffer-reuse-window #<buffer *grep*> ((allow-no-window . t)))
| 2 <- display-buffer-reuse-window: nil
| 2 -> (display-buffer--maybe-pop-up-frame-or-window #<buffer *grep*> ((allow-no-window . t)))
| 2 <- display-buffer--maybe-pop-up-frame-or-window: #<window 22 on *grep*>
1 <- display-buffer: #<window 22 on *grep*>
======================================================================
1 -> (display-buffer #<buffer *trace-output*> nil 0)
| 2 -> (display-buffer--maybe-same-window #<buffer *trace-output*> ((reusable-frames . 0)))
| 2 <- display-buffer--maybe-same-window: nil
| 2 -> (display-buffer-reuse-window #<buffer *trace-output*> ((reusable-frames . 0)))
| 2 <- display-buffer-reuse-window: nil
| 2 -> (display-buffer--maybe-pop-up-frame-or-window #<buffer *trace-output*> ((reusable-frames . 0)))
| 2 <- display-buffer--maybe-pop-up-frame-or-window: nil
| 2 -> (display-buffer-in-previous-window #<buffer *trace-output*> ((reusable-frames . 0)))
| 2 <- display-buffer-in-previous-window: nil
| 2 -> (display-buffer-use-some-window #<buffer *trace-output*> ((reusable-frames . 0)))
| 2 <- display-buffer-use-some-window: #<window 22 on *trace-output*>
1 <- display-buffer: #<window 22 on *trace-output*>
```
You can see here that it first displayed the `*grep*` buffer, followed by the `*trace-output*` buffer. Although the trace doesn’t show precisely what these functions did, it is easy to guess. In the first case, `display-buffer--maybe-pop-up-frame-or-window` returned a window, so it must have split the frame into two windows. When it came time to display the `*trace-output*` buffer though, `display-buffer--maybe-pop-up-frame-or-window` appears to have declined to split the frame again and it instead returned nil. Eventually `display-buffer-use-some-window` picked an existing window to display the buffer in, and it picked the one same one that had just been created.
Of course you can trace more low–level functions as well, to get more detail about what is going on. Reading the source of the action functions will show you what you can trace.
---
Tags: window-splitting, compile
--- |
thread-12662 | https://emacs.stackexchange.com/questions/12662 | EMMS doesn't seem to see anything from MPD | 2015-05-24T01:33:30.373 | # Question
Title: EMMS doesn't seem to see anything from MPD
I've set up MPD, and it's definitely running and indexing everything correctly. I followed the instructions here to set up EMMS to work with MPD, and after running `M-x emms-cache-set-from-mpd-all`, it indexed the right number of tracks, and connecting via `emms-player-connect` seems to work without error. However, when I call `M-x emms`, all I see is an empty window. What am I missing?
For reference, this is my config:
```
;;Media
(require 'emms-player-mpd)
(require 'emms-setup)
(emms-standard)
(emms-default-players)
(setq emms-player-mpd-server-name "localhost")
(setq emms-player-mpd-server-port "6600")
(add-to-list 'emms-player-list 'emms-player-mpd)
(add-to-list 'emms-info-functions 'emms-info-mpd)
```
# Answer
> 0 votes
I don't think `emms` is what you want. Try following the instructions in the emms manual carefully, ending up at `emms-smart-browse`.
# Answer
> 0 votes
Unless your MusicPD is configured to use absolute file names, you must set the `emms-player-mpd-music-directory` variable to the value of "music\_directory" in your MusicPD configuration.
Add for example as follows:
```
(setq emms-player-mpd-music-directory "~/Music/")
```
---
Tags: emms
--- |
thread-66353 | https://emacs.stackexchange.com/questions/66353 | mu4e gmail smtp settings | 2021-06-17T18:36:00.830 | # Question
Title: mu4e gmail smtp settings
I'm trying to use `mu4e` to send/receive email with my Gmail account. I've followed what I believe is the official documentation here, but I think some of the description here seems outdated. As far as receiving mail goes, everything's fine - I'm using `offlineimap` and an app password from Google (which is saved in an encrypted file).
Sending mail is a problem - I write my message and hit `^C ^C`, and am then prompted for an smtp username and password.
Here is the template that I'm using in my `init.el`:
```
(require 'smtpmail)
(setq message-send-mail-function 'smtpmail-send-it
starttls-use-gnutls t
smtpmail-starttls-credentials '(("smtp.gmail.com" 587 nil nil))
smtpmail-auth-credentials
'(("smtp.gmail.com" 587 "USERNAME@gmail.com" nil))
smtpmail-default-smtp-server "smtp.gmail.com"
smtpmail-smtp-server "smtp.gmail.com"
smtpmail-smtp-service 587)
```
which is from the standard Gmail template with USERNAME appropriately changed.
I want to keep this setup relatively simple and I've seen other issues with more complicated arrangements that I want to avoid to begin with.
It does seem to me that I need a password of some kind -- how do I set this up (and why isn't this mentioned in this standard template?!). I played around with `gnus` before, is the simplest solution getting another app password and saving it to some `auth.gpg` file?
# Answer
> 3 votes
In the end, I created another app password from my google account and stored it in `.authinfo.gpg`, which is formatted as per the Gnus Gmail instructions
```
machine smtp.gmail.com login <USER> password <APP-PASSWORD> port 587
```
To get this to work, I added
```
smtpmail-auth-credentials (expand-file-name "~/.authinfo.gpg")
```
into the `smtpmail` config block shown in my initial question.
There may be something more convenient (I now have to separate app passwords for `offlineimap` and for `smtpmail`) but I'll figure that out as I go along.
---
Tags: mu4e, email, smtpmail
--- |
thread-66367 | https://emacs.stackexchange.com/questions/66367 | Show in org-agenda the org-entries with deadlines only after a specific time | 2021-06-18T11:06:29.487 | # Question
Title: Show in org-agenda the org-entries with deadlines only after a specific time
How do I show the todo entries that have deadlines only after a specific time? This helps agenda display more accurately what are needed to be displayed.
For example, I'm hoping for some thing like
```
* TODO Do this.
DEADLINE: <2025-01-01> AFTER: <2024-10-31>
```
As you see, I have a todo whose due is very distant from now. However, I want to start worrying about it only after `<2024-10-31>`. Is it possible to let it show in the `org-agenda` after that date?
# Answer
> 2 votes
You can set it globally with the variable `org-deadline-warning-days`. For example, to start showing all tasks 3 days before the deadline:
```
(setq org-deadline-warning-days 3)
```
If you want to set it individually, you can use the following construct in the timestamp itself:
```
DEADLINE: <2021-07-20 dom -3d>
```
Here, you can also use other modifiers, such as weeks, months and years: `-3w`, `-3m`, `-3y`.
---
Tags: org-mode, org-agenda, deadline
--- |
thread-30852 | https://emacs.stackexchange.com/questions/30852 | How can I move point to where the mouse is pointing now | 2017-02-19T10:24:27.603 | # Question
Title: How can I move point to where the mouse is pointing now
I want to move `point` to where the mouse is pointing. This is easy to do interactively: just click and `point` will move to where the mouse is pointing.
However, I need to do this inside elisp code. I tried to find a nice way by inspecting the source for mouse-drag-region and by reading the manual on Mouse Position but did not manage :-(
Anyone has an elegant solution?
# Answer
You can do something like this:
```
(defun jump-to-cursor ()
"Jump to the position under the mouse cursor if possible."
(interactive)
(when-let ((cursor-pos (mouse-position))
(line (cddr cursor-pos))
(col (cadr cursor-pos))
(p (save-excursion
(goto-char (window-start))
(forward-line line)
(if (> (- (line-end-position) (line-beginning-position)) col)
(progn (move-to-column col) (1- (point)))
nil))))
(goto-char p)))
```
That function tries to compute the position under the cursor and then go to it if it can.
> 2 votes
# Answer
```
(mouse-set-point last-input-event)
(redisplay t)
```
As MT indicates, this moves the point (aka caret) to the mouse pointer (aka cursor) the purpose being to then perform point operations. For example, I have bound C-S-leftClick to a function that, depending on text in the line at the pointer, invokes another function or opens a context menu.
```
(global-set-key [C-S-mouse-1]#'lxa-mouse-open)
...
(defun lxa-mouse-open()
"Move cursor to mouse position and invoke `lxa-open'"
(interactive) ; Required for binding to mouse button
(mouse-set-point last-input-event)
(redisplay t)
(lxa-open)
...
```
> 2 votes
# Answer
`(mouse-position)` returns line+column relative to the frame, not the window. You need to subtract `window-top-line` and `window-left-column` to get line+column relative to window.
> 1 votes
---
Tags: mouse
--- |
thread-66371 | https://emacs.stackexchange.com/questions/66371 | How to exit org-agenda windows without deleting existing windows? | 2021-06-18T17:37:26.170 | # Question
Title: How to exit org-agenda windows without deleting existing windows?
I am trying to use popwin to make org-agenda related windows popup windows. My goal is to dismiss agenda windows with `C-g` when done, leaving the whole window configuration the same way as it was before the agenda windows showed up.
(Dismissing agenda windows with `q` seems to delete some of the existing windows that they replace.)
I've installed popwin via MELPA and tried to set the related variable in `init.el` as described in the documentation:
```
(require 'popwin)
(push '(org-agenda-mode :position bottom) popwin:special-display-config)
(popwin-mode 1)
```
However, this does not seem to work. Pressing `C-g` doesn't dismiss the agenda window (which is launched with `C-c a t` and then `t`). I've also tried using `agenda-mode` instead of `org-agenda-mode` in above without success. Yet, popwin and `C-g` works on occur-mode, and the customization show up in `M-x customize-variable` interface.
(This is with Emacs 27.1 installed via PPA under Ubuntu 20.04)
My question is:
*How to correctly set up emacs so that existing windows are preserved after closing org agenda windows?*
Related:
popup windows, popwin problem?
How to control in which window a buffer is displayed? (solution doesn't seem to work)
# Answer
Quite by chance, I encountered this blog, which has the following setting from org-mode itself that does exactly what I need:
> Restore layout after exit from agenda view
>
> (setq org-agenda-restore-windows-after-quit t)
After adding this to `init.el`, hitting `q` on transitional org agenda windows no longer deletes the windows that they replace.
> 2 votes
---
Tags: org-agenda
--- |
thread-66377 | https://emacs.stackexchange.com/questions/66377 | Is there a command in EWW for copying the URL of the current webpage? | 2021-06-19T04:11:49.643 | # Question
Title: Is there a command in EWW for copying the URL of the current webpage?
In org capture, it's possible to capture the URL of a webpage in EWW, and then store the link in an .org file.
My question is:
Is there a general way to copy the URL of the current page into the clipboard/kill ring, so that one can later paste the URL into any mode, not just into org-mode?
# Answer
As always, `C-h``m` tells you about the major mode and its keybindings, where we can see:
```
w eww-copy-page-url
```
Which will "Copy the URL of the current page into the kill ring."
`w` is usefully similar to the standard `M-w` for copying text, so should be easy to remember on that account.
> 2 votes
---
Tags: eww
--- |
thread-59832 | https://emacs.stackexchange.com/questions/59832 | What is the org-mode equivalent of \gls{keyword} in LaTeX? | 2020-07-26T12:10:29.050 | # Question
Title: What is the org-mode equivalent of \gls{keyword} in LaTeX?
Is there an org-mode equivalent of the LaTeX glossary package?
Use case - you have an external file with a glossary list, the \gls{keyword} gets expanded at compile time to whatever is referenced in the external file.
# Answer
You may wish to look at John Kitchin's org-ref, which also includes glossary support.
> 1 votes
---
Tags: org-mode, writing
--- |
thread-44199 | https://emacs.stackexchange.com/questions/44199 | Adding advice to interactive functions | 2018-08-20T04:02:41.340 | # Question
Title: Adding advice to interactive functions
I want to add advice to \`describe-function'. However, when I try to do so, I get an error due to wrong number of arguments. Function:
```
(defun describe-function-advice (function)
(interactive)
(setq-local help-buffer-type "describe-function")
(setq-local help-buffer-arg function))
(advice-add 'describe-function :after #'describe-function-advice)
```
Error:
```
Debugger entered--Lisp error: (wrong-number-of-arguments (1 . 1) 0)
#f(compiled-function (function) "Display the full documentation of
FUNCTION (a symbol).\nWhen called from lisp, FUNCTION may also be
a function object." (interactive #f(compiled-function ()
#<bytecode 0x12b6b$
apply(#f(compiled-function (function) "Display the full documentation
of FUNCTION (a symbol).\nWhen called from lisp, FUNCTION may also
be a function object." (interactive #f(compiled-function ()
#<bytecode 0$
describe-function()
funcall-interactively(describe-function)
#<subr call-interactively>(describe-function nil nil)
apply(#<subr call-interactively> describe-function (nil nil))
call-interactively@ido-cr+-record-current-command(
#<subr call-interactively> describe-function nil nil)
apply(call-interactively@ido-cr+-record-current-command
#<subr call-interactively> (describe-function nil nil))
call-interactively(describe-function nil nil)
command-execute(describe-function)
```
For the given problem, I can probably use \`help-fns-describe-function-functions', but I would still like to understand how to use advice-add with interactive functions.
# Answer
> 1 votes
Untested, but your `(interactive)` form doesn't tell Emacs how to obtain the `FUNCTION` argument, so that's presumably your problem.
# Answer
> 0 votes
When you advice a function with `:after` your function is called after the original function with the same arguments. So `setq-local` take effect in the buffer where you call the function.
See: https://www.gnu.org/software/emacs/manual/html\_node/elisp/Advice-Combinators.html
This works but probably doesn't give the result you expect:
```
(defun describe-function-advice (&rest args)
(setq-local help-buffer-type "describe-function"))
(advice-add 'describe-function :after #'describe-function-advice)
```
---
Tags: interactive, advice, nadvice
--- |
thread-66382 | https://emacs.stackexchange.com/questions/66382 | How to set the default indentation width globally? | 2021-06-19T09:20:37.227 | # Question
Title: How to set the default indentation width globally?
By default Emacs uses tab instead of spaces for indentation, so I changed these 2 variables to change this behavior,
```
(setq-default indent-tabs-mode nil) ;; Disable indent with tabs
(setq default-tab-width 4) ;; Set default indent width
```
It did change the indent mode from tab to space, but if I press `RET`, when I am in a programming buffer `C++` for example, to enter a new line, I get 2 spaces of indentation instead of 4. How do I set this indentation level to 4 be default globally.
Also when when I am editing a line for example, it auto shift the line back to 2 space of indentation, for some reason, and also re-formats how I wrote the code, for example, I usually write like this,
```
if (true)
{
// 4 spaces for indentation.
}
```
If I try to edit or add something, it pushes the lines back to 2 spaces of indentation and also sometimes re-formats the brackets position,
```
if (true) {
// 2 spaces for indentation.
}
```
I am constantly fighting with this thing, and it gets annoying very quickly sometimes. As far as I know, I did not install any formatting package.
# Answer
There is no global setting for the indentation width. Instead, each mode has it’s own setting. In `c-mode` it is called `c-basic-offset`. In `js2-mode` it is `js2-basic-offset`. For `lisp-mode` there are two: `lisp-body-indent` and `lisp-indent-offset`.
You’re probably using `c-mode` for editing your C++ files, so you should customize the `c-basic-offset` variable. Run `M-x customize-variable` then enter the variable name that you would like to change.
> 3 votes
---
Tags: indentation, tabs
--- |
thread-66375 | https://emacs.stackexchange.com/questions/66375 | Required help with making LSP (Scala Metals) working | 2021-06-18T22:52:42.347 | # Question
Title: Required help with making LSP (Scala Metals) working
My current emacs version is 27.2, OS is Ubuntu 20.04,Java version is 11.0.11.
I was following the official guide of installing metals on emacs, did a little change from the course at the start (I first installed required packages/dependencies through `M-x package-list-packages` and only then did what was going on on the guide, but from my understanding, it shouldn't matter. My current `init.el` file contains the code related to `lsp-mode`:
```
;; Install use-package if not already installed
(unless (package-installed-p 'use-package)
(package-refresh-contents)
(package-install 'use-package))
(require 'use-package)
;; Enable defer and ensure by default for use-package
;; Keep auto-save/backup files separate from source code: https://github.com/scalameta/metals/issues/1027
(setq use-package-always-defer t
use-package-always-ensure t
backup-directory-alist `((".*" . ,temporary-file-directory))
auto-save-file-name-transforms `((".*" ,temporary-file-directory t)))
;; Enable scala-mode for highlighting, indentation and motion commands
(use-package scala-mode
:interpreter
("scala" . scala-mode))
;; Enable sbt mode for executing sbt commands
(use-package sbt-mode
:commands sbt-start sbt-command
:config
;; WORKAROUND: https://github.com/ensime/emacs-sbt-mode/issues/31
;; allows using SPACE when in the minibuffer
(substitute-key-definition
'minibuffer-complete-word
'self-insert-command
minibuffer-local-completion-map)
;; sbt-supershell kills sbt-mode: https://github.com/hvesalai/emacs-sbt-mode/issues/152
(setq sbt:program-options '("-Dsbt.supershell=false"))
)
;; Enable nice rendering of diagnostics like compile errors.
(use-package flycheck
:init (global-flycheck-mode))
(use-package lsp-mode
;; Optional - enable lsp-mode automatically in scala files
:hook (scala-mode . lsp)
(lsp-mode . lsp-lens-mode)
:config
;; Uncomment following section if you would like to tune lsp-mode performance according to
;; https://emacs-lsp.github.io/lsp-mode/page/performance/
;; (setq gc-cons-threshold 100000000) ;; 100mb
;; (setq read-process-output-max (* 1024 1024)) ;; 1mb
;; (setq lsp-idle-delay 0.500)
;; (setq lsp-log-io nil)
;; (setq lsp-completion-provider :capf)
(setq lsp-prefer-flymake nil))
;; Add metals backend for lsp-mode
(use-package lsp-metals)
;; Enable nice rendering of documentation on hover
;; Warning: on some systems this package can reduce your emacs responsiveness significally.
;; (See: https://emacs-lsp.github.io/lsp-mode/page/performance/)
;; In that case you have to not only disable this but also remove from the packages since
;; lsp-mode can activate it automatically.
(use-package lsp-ui)
;; lsp-mode supports snippets, but in order for them to work you need to use yasnippet
;; If you don't want to use snippets set lsp-enable-snippet to nil in your lsp-mode settings
;; to avoid odd behavior with snippets and indentation
(use-package yasnippet)
;; Use company-capf as a completion provider.
;;
;; To Company-lsp users:
;; Company-lsp is no longer maintained and has been removed from MELPA.
;; Please migrate to company-capf.
(use-package company
:hook (scala-mode . company-mode)
:config
(setq lsp-completion-provider :capf))
;; Use the Debug Adapter Protocol for running tests and debugging
(use-package posframe
;; Posframe is a pop-up tool that must be manually installed for dap-mode
)
(use-package dap-mode
:hook
(lsp-mode . dap-mode)
(lsp-mode . dap-ui-mode)
)
```
without the first part of adding `melpa`, since I got it added already. After doing everything and restarting the Emacs, I proceeded with opening .scala file and on open I get a debug message:
```
Debugger entered--Lisp error: (void-function -compose)
-compose(lsp--client-path->uri-fn lsp--workspace-client)
lsp--path-to-uri("pathtoemacs/.emacs.d/index.sqlite")
#f(compiled-function () #<bytecode 0x15566aea7e91>)()
funcall(#f(compiled-function () #<bytecode 0x15566aea7e91>))
eval((funcall #'#f(compiled-function () #<bytecode 0x15566aea7e91>)))
custom-initialize-reset(lsp-serenata-index-database-uri (funcall #'#f(compiled-function () #<bytecode 0x15566aea7e91>)))
custom-declare-variable(lsp-serenata-index-database-uri (funcall #'#f(compiled-function () #<bytecode 0x15566aea7e91>)) "The location to store the index database.\nNote tha..." :group lsp-serenata :ty$
byte-code("\301\302\303\304 \305\306\307!\310\311\312\313&\10!\210\314\315\316\317\320\321\322\323\324\325&\11\210\326\327\330\331\332DD\333\334\335\320\315\324\336&\11\210\326\337\330..." [lsp-intele$
require(lsp-php nil t)
#f(compiled-function (package) #<bytecode 0x15566ad2cc81>)(lsp-php)
mapc(#f(compiled-function (package) #<bytecode 0x15566ad2cc81>) (ccls lsp-actionscript lsp-ada lsp-angular lsp-bash lsp-beancount lsp-clangd lsp-clojure lsp-cmake lsp-crystal lsp-csharp lsp-css lsp-d $
seq-do(#f(compiled-function (package) #<bytecode 0x15566ad2cc81>) (ccls lsp-actionscript lsp-ada lsp-angular lsp-bash lsp-beancount lsp-clangd lsp-clojure lsp-cmake lsp-crystal lsp-csharp lsp-css lsp-$
lsp--require-packages()
lsp()
run-hooks(change-major-mode-after-body-hook prog-mode-hook scala-mode-hook)
apply(run-hooks (change-major-mode-after-body-hook prog-mode-hook scala-mode-hook))
run-mode-hooks(scala-mode-hook)
scala-mode()
set-auto-mode-0(scala-mode nil)
set-auto-mode()
normal-mode(t)
after-find-file(nil t)
find-file-noselect-1(#<buffer test.scala> "~/Scala/test.scala" nil nil "~/Python_rofli/Scala/test.scala" (5288230 2065))
find-file-noselect("~/Scala/test.scala" nil nil)
ido-file-internal(raise-frame)
ido-find-file()
funcall-interactively(ido-find-file)
call-interactively(ido-find-file nil nil)
command-execute(ido-find-file)
```
I can try to open the .scala file again and it will be opened, but upon trying to activate `lsp-mode`, it will tell `[Disabled]` and a bunch of other errors about not having a connection to the server. And according to the debug message, I am supposed to have some kind of `index.sqlite` inside my `.emacs.d` folder, but I don't have one, and creating one didn't help. I also followed the alternative LSP server listed there, the "Eglot", and it worked fine, but upon switching back to `lsp-mode` variant, it was still giving the same error. Any idea how to start debugging this mess? I tried to manually install metals, tried shenanigans with a "coursier", nothing helped.
# Answer
> 1 votes
Got a response on emacs-metals GitHub on how to fix that issue. The solution is to update/install a `dash` package.
---
Tags: package, lsp-mode
--- |
thread-66380 | https://emacs.stackexchange.com/questions/66380 | Change prompt style to minibuffer from GUI dialogs | 2021-06-19T08:37:56.210 | # Question
Title: Change prompt style to minibuffer from GUI dialogs
Emacs by default does not ask if you are sure you want to exit Emacs, so I added this to my configuration to prompt me to answer yes or no before quitting Emacs.
```
(setq confirm-kill-emacs 'y-or-n-p) ;; Confirm before killing emacs
```
I use `evil-mode` so if I try to exit with `:wq` or `:w` it does prompt me in the mini buffer, but (as I am a WM only user using DWM) if I press `Super+Shift+c` shortcut for my WM to close a program, it prompts me with a dialog instead of the minibuffer.
How do I set it so no matter what, always prefer the minibuffer, not just for prompting this, but for any kind of prompt, I would prefer the minibuffer. For example I have `mu4e` also setup for my Email, and every time I try to resync the mails, it asks for my GPG authentication passphrase, in a GUI dialog. I would also like that to be in the minibuffer, so I want this setting to be globally set.
# Answer
> 3 votes
This is controlled through the `use-dialog-box` variable. Either put this in your init file:
```
(setq use-dialog-box nil)
```
or use the Customize interface.
---
Tags: minibuffer, mouse, prompt, gui
--- |
thread-64273 | https://emacs.stackexchange.com/questions/64273 | org-mode source block: conditional header | 2021-04-02T17:39:00.050 | # Question
Title: org-mode source block: conditional header
How can I modify the header of a source block dynamically, based on the backend used to export my org-mode document? Specifically, I want the header to include `:results output html` when the file is exported to HTML, and `:results output latex` when the file is exported to LaTeX.
I believe that I should use the `org-export-current-backend` variable to achieve this, but I have been unable to write a header that does what I need.
For example, I think I could include an `if` call in the header. Unfortunately, this example triggers the HTML build correctly but not the LaTeX one (I can successfully export to LaTeX by inverting the `if` conditional):
```
#+begin_src emacs-lisp :exports both :results output (if (eq org-export-current-backend 'html) html latex)
(if (eq org-export-current-backend 'html)
(princ "<ul><li>Green tea</li><li>Black tea</li></ul>")
(princ "\\begin{itemize}\n\\item Green tea\n\\item Black tea\n\\end{itemize}"))
#+end_src
```
# Answer
I did not find a direct answer to my question, so I turned to an alternative that works almost as well as what I had in mind: Org-Mode Macros. In this example, we use the `conditional-header` macro to "decorate" the source block and dynamically change the header based on the output format. This org-mode document thus exports automatically to both PDF and HTML without altering the code.
```
#+MACRO: conditional-header (eval (concat "#+header: :results output " (prin1-to-string org-export-current-backend)))
{{{conditional-header}}}
#+begin_src emacs-lisp :exports both
(if (eq org-export-current-backend 'html)
(princ "<ul><li>Green tea</li><li>Black tea</li></ul>")
(princ "\\begin{itemize}\n\\item Green tea\n\\item Black tea\n\\end{itemize}"))
#+end_src
```
> 2 votes
# Answer
I think you just needed to add quotes around the values `html` and `latex` in the header elisp snippet as follows:
```
#+begin_src emacs-lisp :exports both :results output (if (eq org-export-current-backend 'html) "html" "latex")
(if (eq org-export-current-backend 'html)
(princ "<ul><li>Green tea</li><li>Black tea</li></ul>")
(princ "\\begin{itemize}\n\\item Green tea\n\\item Black tea\n\\end{itemize}"))
#+end_src
```
Then the code block seems to generate the right results depending on the `org-export-current-backend` variable.
> 3 votes
---
Tags: org-mode, org-babel
--- |
thread-66390 | https://emacs.stackexchange.com/questions/66390 | Function add-variable-watcher does not watch "last-command" variable | 2021-06-19T17:50:06.630 | # Question
Title: Function add-variable-watcher does not watch "last-command" variable
I have added a watcher function to watch the **last-command** variable.
```
(defun my-watch (symbol newval op where)
(message "Hello"))
(add-variable-watcher 'last-command #'my-watch)
```
The function **my-watch** does not get invoked at all. How to watch for a variable?
# Answer
> 3 votes
\[Please pose a separate question for what you're really trying to do (your first paragraph, which I've removed): *how to highlight all the words in the buffer that match the word under cursor, when the cursor is moved*. This question should just be about `add-variable-watcher` (the rest of your post).\]
---
The variable watcher actually works. But `last-command` is apparently not being set.
To see that it works:
```
(defun my-watch (symbol newval op where)
(message "SYM: %S, VAL: %S, OP: %S, WHERE: %S" symbol newval op where))
(add-variable-watcher 'last-command #'my-watch)
(setq last-command 'foobar)
```
That shows this in the echo area (and buffer `*Messages*`):
```
SYM: last-command, VAL: foobar, OP: set, WHERE: nil
```
But note the limitations documented in node Watching Variables of the Elisp manual:
> There are a couple of ways in which a variable could be modified (or at least appear to be modified) *without triggering a watchpoint*.
>
> Since watchpoints are attached to symbols, modification to the objects contained within variables (e.g., by a list modification function see Modifying Lists) is not caught by this mechanism.
>
> Additionally, **C code can modify the value of variables directly, bypassing the watchpoint mechanism.**
>
> A minor limitation of this feature, again because it targets symbols, is that **only variables of dynamic scope may be watched**. This poses little difficulty, since modifications to lexical variables can be discovered easily by inspecting the code within the scope of the variable (unlike dynamic variables, which can be modified by any code at all, see Variable Scoping).
---
Tags: debugging, variables, variable-watchers
--- |
thread-66391 | https://emacs.stackexchange.com/questions/66391 | "inspect element" for GUI elements? | 2021-06-19T18:10:03.540 | # Question
Title: "inspect element" for GUI elements?
Is there a way to "inspect elements" for Emacs?
---
e.g. In Firefox, I would open the developer tools, select this icon:
Then pick an element on the page to get information on it.
---
For an Emacs example, I have the following window:
Is there a way for me to "select" the top yellow bar and get more information about what elisp code is rendering it?
### Additional Information
After an Emacs update, one of my packages enabled this yellow top bar by default. I did not want it there. I am looking for an easy way to discover what package, elisp code, or general information about the rendering of a specific UI element either under the cursor, x/y coordinate, or mouse click (like in Firefox).
As for "this" top yellow bar, after a bit of guessing and enabling/disabling packages & modes, this was the culprit:
* `lsp-headerline-breadcrumb-mode`
### References
# Answer
The two scenarios are different, but `C-u``C-x``=` calls (with a prefix argument) `what-cursor-position` which may help you -- it will tell you a lot of information about the character at point, including the faces and text properties.
This won't tell you "what elisp code is rendering it", because no elisp code is rendering it. The rendering is the responsibility of the redisplay code (which is written in C).
---
Edit: The question was about the header line...
`C-c``v` `header-line-format` and `mode-line-format` control the contents of those two lines in any given buffer. See the latter and `C-h``i``g` `(elisp)Mode Line Format` for details of how those work.
> 2 votes
---
Tags: debugging, gui
--- |
thread-66398 | https://emacs.stackexchange.com/questions/66398 | vt100 codes in man-mode | 2021-06-20T09:19:43.667 | # Question
Title: vt100 codes in man-mode
Emacs in this particular installation doesn't parse hyphens in `Man-mode`. I found the definition and initialization of `Man-filter-list`, but I don't really know what to do with it, as I cannot really see well the code being displayed incorrectly.
I think, this may also be related to the font not having the hyphen character. So, I'm not sure which direction to take this: try to look for a different font, or try to filter out the hyphens.
Would appreciate a snippet for filtering it out though, just in case.
---
I just tried changing font, it seems to be unrelated. Also, this appears in `ansi-term` in Emacs too, i.e. man pages render incorrectly around hyphens (the characters preceding hyphens appear to have a caret on top of them). This doesn't appear in other terminal emulators, like Gnome terminal. However, in XTerm `man` seems to run in a mode where it doesn't try to hyphenate words (it's slightly uglier, but no botched symbols).
---
OK, setting `Man-switches` to `"--nh -E ascii"` (for no hyphenation and no other weird characters) helps avoiding the botched characters, however, I'd love to know how to have hyphens and have them displayed properly.
# Answer
> 1 votes
OK, finally, I more or less figured out what the problem was.
Long story short, Emacs was running `man` with ISO Latin as its encoding system. However, `man` will still generate a bunch of special characters, hoping that the terminal will somehow interpret that, yet the terminal didn't know how to handle them.
So, one way was to tell man to not to generate strange characters, that is by setting `Man-switches` to `--nh -E ascii`.
Or, tell Emacs to deal with Unicode in Man pages by setting `Man-coding-system` to `utf-8`.
---
Tags: man, ansi
--- |
thread-66401 | https://emacs.stackexchange.com/questions/66401 | Is there some way to do `bufdo` in spacemacs? | 2021-06-20T10:29:29.670 | # Question
Title: Is there some way to do `bufdo` in spacemacs?
I am very used to using `bufdo` from vim to perform an action across all buffers. I can do things like
```
:bufdo %s/\( *\), top=/\1, blockTop=/
```
to do a search an replace over multiple buffers or
```
:bufdo w | !pdflatex %
```
To compile each buffer as a Latex file.
I'm really new to spacemacs and I'd like to be able to do this sort of thing where I just run my vim command over every buffer. Is there some way I can do this?
# Answer
> 2 votes
Not all buffers in Emacs are visiting files, so you would basically never want to do something like a search and replace across "all buffers".
For ad-hoc use I would use `M-x` `ibuffer` to mark the target buffers (marking by major mode is probably a useful way to go), and then one of the following:
* `r` (`ibuffer-do-replace-regexp`)
* `Q` (`ibuffer-do-query-replace`)
* `I` (`ibuffer-do-query-replace-regexp`)
* `!` (`ibuffer-do-shell-command-file`) runs a shell command on the buffer's file.
There are many other things you can do. See the "Mark" and "Operate" menus in the `ibuffer` buffer, and use `C-h``m` in that buffer to learn more.
---
Tags: spacemacs, vim-emulation
--- |
thread-53212 | https://emacs.stackexchange.com/questions/53212 | How can I use evil-mc in spacemacs? | 2019-10-18T00:19:45.133 | # Question
Title: How can I use evil-mc in spacemacs?
This question is a semantically similar question but the OP's intent was more about which implementation of multiple cursors was "best".
I echo one of the commenters of that question who asked "Can you explain how to use it? I'm superconfused". . . as am I! That answer included a list of keybindings (which are also available (though not in handy table format) on the `evil-mc` readme). When I search on the web for this I get keybindings and others with the same question but have not found just basic instructions.
Could someone just walk through an example of *how to use multiple cursors*? For example, let's say I have this list of variables cut from a spec (including non-alignment):
```
`purpose`
`dtlastmod`
`lastmod`
`dtrelver`
`relver`
`comps`
```
I want to change that list to:
```
String purpose;
String dtlastmod;
String lastmod;
String dtrelver;
String relver;
String comps;
```
It *seems* like multiple cursors might make this easy but I'll be darned if I can't figure it out. Is that a good use case? If not, what is a good example and could you talk through the steps?
# Answer
For a pure evil-mc solution you need to have a cursor in each line. I don't know of such a function out of the box, but since this is the hackable editor I defined one:
```
(define-key evil-normal-state-map (kbd "C-M-<") 'rno/evil-mc-make-cursors-for-all-regexp)
(evil-define-command rno/evil-mc-make-cursors-for-all-regexp ()
"Initialize `evil-mc-pattern' and make cursors for all matches ignoring exact letter matches."
:repeat ignore
:evil-mc t
(if (evil-mc-has-cursors-p) (user-error "Cursors already exist.")
(setq evil-mc-pattern
(cons (evil-ex-make-search-pattern (replace-regexp-in-string
"\\w+"
"\\w+"
(buffer-substring-no-properties
(region-beginning)
(region-end))
t
'literal))
nil))
(evil-exit-visual-state)
(evil-mc-make-cursors-for-all)
(evil-mc-print-cursors-info "Created")))
```
How to use:
* make a visual selection of the first delimited term from backtick to backtick
* call the new function using `C-M-<` to create a cursor on each closing backtick
+ the function takes the selection and replaces all word characters (e.g. letters) by a regex matching all word characters, so it basically searches for two backticks with letters in between and creates cursors there
* `D` to delete the backtick and any other characters, e.g. trailing whitespace
* `a;ESC` to insert the semicolon at the end
* `T`` to move backwards before the next backtick
* `d0` to delete everything until the beginning of the line, e.g. leading whitespace
* `iString SPC ESC` to prepend "String "
* `g r q` to get rid of all fake cursors
Here is a short animation what it looks like:
> 2 votes
# Answer
For only affecting the six rows you could `narrow-to-region` using `SPC n r`
I'd break it down in the necessary steps:
* Remove leading whitespace using `SPC SPC delete-whitespace-rectangle RET`
* Remove trailing whitespace using `SPC x d w`
* Remove backticks using a series of commands, e.g.:
+ `v` on one backtick to create a visual selection
+ `g r m` to get a cursor for each instance of the selection
+ `x` to remove it
+ `g r q` to get rid of the cursors
* Prepending "String SPC"
+ `ggVG` to mark all lines in visual-line mode
+ `I` to jump the beginning of a line
+ `String` to insert "String "
+ `ESC` to leave insert mode and have the insertion apply to all previously selected lines
* Appending ";"
+ `ggVG` to mark all lines in visual-line mode
+ `A` to jump the end of a line
+ `;` to insert the semicolon
+ `ESC` to leave insert mode and have the insertion apply to all previously selected lines
check out my other answer for a pure evil-mc solution
> 2 votes
---
Tags: spacemacs, evil
--- |
thread-66374 | https://emacs.stackexchange.com/questions/66374 | Add autoloading use-package keywords to a fork of general.el | 2021-06-18T20:36:05.200 | # Question
Title: Add autoloading use-package keywords to a fork of general.el
I have forked `general.el` to add a few autoloaded keywords of my own, by using the `:general` keyword use-package functions as a template. However, this bit of code, originally used for `:general`, is not working (read "not being autoloaded"):
```
(defun use-package-handler/:gone (name _keyword args rest state)
"Use-package handler for :gone."
(use-package-concat
(use-package-process-keywords name rest state)
`(,@(mapcar (lambda (arglist)
;; Note: prefix commands are not valid functions
(if (or (functionp (car arglist))
(macrop (car arglist)))
`(,@arglist :package ',name)
`(general-def (:keymaps '(global aiern-insert-state-map aiern-normal-state-map))
,@arglist
:package ',name)))
(plist-get args :arglists)))))
```
The part I have changed is the `general-def` bit, by adding `(:keymaps '(global aiern-insert-state-map aiern-normal-state-map))`. When demanding the package, it works fine. Am I missing anything here? I've also copied the `use-package-autoloads/:general` and `use-package-handler/:general` functions as well, which are exactly the same, and renamed them appropriately.
# Answer
> 0 votes
So, I've found the solution! ... Use the normalizer, handler, and autoloader for `:ghook` instead...
```
(defun use-package-handler/:gone (name _keyword arglists rest state)
"Use-package handler for :gone"
(use-package-concat
(use-package-process-keywords name rest state)
`(,@(mapcar (lambda (arglist)
arglist
`(general-def :keymaps '(global aiern-insert-state-map aiern-normal-state-map) ,@arglist))
arglists))))
(defalias 'use-package-autoloads/:gone #'use-package-autoloads/:ghook)
(defalias 'use-package-normalize/:gone #'use-package-normalize/:ghook)
```
---
Tags: use-package, autoload
--- |
thread-66405 | https://emacs.stackexchange.com/questions/66405 | How to find the function that is run after cursor is moved? | 2021-06-20T12:13:51.187 | # Question
Title: How to find the function that is run after cursor is moved?
I am working with a highly customized emacs configuration that is not built by me and it highlights all the words in the buffer that match the word under the cursor.
How to find the function that highlights all the words under the cursor?
After the key sequence **forward-word**, **backward-word** or **down-mouse-1** the highlight occurs. There are no hooks set up for these key sequences.
It appears there is a small delay after the cursor move ends and the highlight occurs.
Are there any cursor or timer hooks that can be examined to find the function that highlights the words under the cursor?
# Answer
I know 2 packages for highlighting symbol under curser.
Both of them use the same hook: `post-command-hook`, see `symbol-overlay-mode` and `highlight-symbol-mode`
Both of them use timers.
> 3 votes
---
Tags: debugging
--- |
thread-66400 | https://emacs.stackexchange.com/questions/66400 | terraform tfls server always asks if restart when edit a .tf file in spacemacs | 2021-06-20T10:11:29.343 | # Question
Title: terraform tfls server always asks if restart when edit a .tf file in spacemacs
When I use terraform layer with spacemacs, after operate a .tf file, at the status bar it always notices the message below:
```
Server tfls:3869 exited with status exit(check corresponding stderr buffer for details). Do you want to restart it? (y or n)
```
What i set in the `~/.spacemacs` file is
```
dotspacemacs-configuration-layers
'(lsp
git
(terraform :variables
terraform-auto-format-on-save t
terraform-backend 'lsp)
```
How to avoid its notice message? Why it always wants to restart?
`lsp-log` buffer
```
Command "terraform-lsp" is present on the path.
Command "terraform-lsp" is present on the path.
Found the following clients for /Users/user12/terraform/module1/main.tf: (server-id tfls, priority -1)
The following clients were selected based on priority: (server-id tfls, priority -1)
This server does not support foldingRangeProvider
```
`Message` buffer
```
Loading /Users/user12/.spacemacs...done
(Spacemacs) Warning: Cannot find any of the specified fonts (Source Code Pro)! Font settings may not be correct.
Spacemacs is ready.
Loading /Users/user12/.emacs.d/.cache/recentf...done
Skipping check for new version (reason: dotfile)
Package cl is deprecated
[yas] Prepared just-in-time loading of snippets successfully.
LSP :: Connected to [tfls:33908/starting].
LSP :: tfls:33908 initialized successfully in folders: (/Users/user12/terraform)
LSP :: tfls has exited (exited abnormally with code 2)
```
# Answer
> 1 votes
Emacs is starting `tfls` for you, but it is exiting abnormally. This usually indicates that it is encountering some sort of error that prevents it from functioning. Emacs is then asking if you want to restart it.
A language server is intended to run in the background and provide answers to queries so that your editor can implement IDE–like features. This allows the language designer to implement these features once, without needing to know anything about all the editors that people might use.
You should look to the `tfls` documentation or community for answers. `tfls` is not part of Emacs, and troubleshooting it is beyond the scope of this community.
---
Tags: spacemacs, init-file, buffers, lsp-mode, server
--- |
thread-66411 | https://emacs.stackexchange.com/questions/66411 | Percentage sign in `print` and `message` | 2021-06-21T06:35:55.997 | # Question
Title: Percentage sign in `print` and `message`
I am trying to output
```
Humidity: 42%
```
using both functions `print` and `message`. While `print` has no problem with the literal percentage sign, `message` throws a "Format string ends in middle of format specifier". What am I missing?
```
(defun demo()
(interactive)
(progn
(setq text (format "Humidity: %s%%" 42))
(print text)
(message text)
))
(global-set-key (kbd "<f5>") 'demo)
```
# Answer
By running `(message (format ...))`, you're using the string as a format **twice**.
`print` takes an *object* as its parameter, while `message` takes a *format string*. Use `"%s"` as the format and you can specify the string as the second optional argument to `message`:
```
(setq text (format "Humidity %s%%" 42))
(print text)
(message "%s" text)
⇒ "Humidity 42%"
```
or don't run format on `text` before sending it to `message`:
```
(setq value 42)
(setq format "Humidity %s%%")
(print (format format value))
(message format value)
⇒ "Humidity 42%"
```
> 4 votes
---
Tags: message, print, format
--- |
thread-64923 | https://emacs.stackexchange.com/questions/64923 | How can I use the physics package in mathjax for org-mode HTML export? | 2021-05-20T10:22:37.050 | # Question
Title: How can I use the physics package in mathjax for org-mode HTML export?
I’m trying to use org-mode to export something as an HTML document, with MathJax equations. I know that MathJax supports the physics package, so it seems like it should be possible to tell emacs to tell MathJax to load `physics`. But how?
The code suggested in the link above is
```
window.MathJax = {
loader: {load: ['[tex]/physics']},
tex: {packages: {'[+]': ['physics']}}
};
```
so I tried putting variations of these lines in the document:
* `#+HTML_MATHJAX: loader: {load: ['[tex]/physics']} tex: {packages: {'[+]': ['physics']}}`
* `#+HTML_MATHJAX: load: ['[tex]/physics'] packages: {'[+]': ['physics']}`
But neither worked. What’s the right way to do this?
Example:
```
#+TITLE: Some physics
^^^ What can I put here to use the physics package?
$\ket{-}=\frac{\ket{0}-\ket{1}}{\sqrt{2}}$
```
**Edit**: I put one solution down below that uses pandoc.
# Answer
> 1 votes
I've probably looked through every single piece of documentation related to Org Mode's LaTeX to HTML export and MathJax, and this is what I've got:
Launch Emacs, then open up your MathJax configuration using `M-x org-customize`. Go to `Org Export` -\> `Org Export HTML` -\> `Org HTML MathJax template`. There, you will find a window where you can edit the MathJax config.
Change it up so it looks like this:
```
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
displayAlign: "%ALIGN",
displayIndent: "%INDENT",
extensions: ["[Contrib]/physics/physics.js"],
"HTML-CSS": { scale: %SCALE,
linebreaks: { automatic: "%LINEBREAKS" },
webFont: "%FONT"
},
SVG: {scale: %SCALE,
linebreaks: { automatic: "%LINEBREAKS" },
font: "%FONT"},
NativeMML: {scale: %SCALE},
TeX: { equationNumbers: {autoNumber: "%AUTONUMBER"},
MultLineWidth: "%MULTLINEWIDTH",
TagSide: "%TAGSIDE",
TagIndent: "%TAGINDENT"}
}
});
</script>
<script type="text/javascript"
src="%PATH"></script>
```
The important line to add is:
```
extensions: ["[Contrib]/physics/physics.js"],
```
When you're in this editing mode the `<return>` key might not add a whitespace character. Remember that you can always add one using the `C-o` shortcut. After you're done select `[ Apply and save ]`. Now the `physics` package should be working properly.
# Answer
> 0 votes
Okay, this works for my specific case (thanks to Ian’s comment):
1. Install the package `ox-pandoc`.
2. Customize the option `org-pandoc-options-for-html5` to include `mathjax` set to `t`.
3. Run the command `org-pandoc-export-to-html5`.
---
Tags: org-mode, latex, html, mathjax
--- |
thread-66415 | https://emacs.stackexchange.com/questions/66415 | Change emacs keyboard layout | 2021-06-21T08:55:50.250 | # Question
Title: Change emacs keyboard layout
I have a UK keyboard and this is setup and functioning on Ubuntu 21.04 with all of my apps. When I open emacs inside a terminal using `emacs -nw` it also correctly used the gb keyboard layout. However when opening emacs (27.2, built from repo) in a new frame from a call to `emacs` or clicking on the shortcut, it switches to a us keyboard layout. I am unable to get it to use a qwerty-gb layout.
I have tried setting in my config/calling interactively:
```
(setq quail-keyboard-layout 'pc105-uk)
```
However whatever I choose doesn't appear to have any impact.
I have also tried interactively calling `set-input-method british`. This has had some help in the shift+3 is now '£' instead of '#'. However other keys such as my '#' come out as '\\'.
Please could I have some help?
# Answer
I managed to resolve this issue by explicitly calling `setxkbmap -model pc105 -layout gb` in the terminal before opening emacs. I have added this to my .bashrc
The following thread was my inspiration for trying this: Unable to change keyboard layout in EXWM/Emacs27.1
> 1 votes
---
Tags: keyboard-layout
--- |
thread-66418 | https://emacs.stackexchange.com/questions/66418 | Disable 'beautification' of text when point is on same line in org | 2021-06-21T12:15:03.263 | # Question
Title: Disable 'beautification' of text when point is on same line in org
When writing `org` documents, some parts of the text (like links and figures) automatically get 'beautified' (I'm unsure what the technically correct term is), meaning that some surrounding text elements (e.g. the brackets) gets hidden automatically.
Although that looks nice, it's sometimes inconvenient for me, especially if I want to change some parts of it. Therefore I'm looking for an option to disable the 'beautification' when the point is on the same line.
Any ideas on how I could do that? I'm currently using `Emacs 26.1` on `Debian stable (Buster)` (actually `PureOS 9.0 Amber`).
---
ps.: To me this seems similar to the `prettify-symbols-mode` but from what I understand it must be a different function that is handling this.
# Answer
> 4 votes
I've wanted this too.
1. (2021) Try the org-appear package, which can toggle emphasis, entities, and a few other things while your cursor is in the hidden text (not the entire line though). There are settings to choose which of these categories to display.
2. (2019) Try my experimental code, which shows all the hidden characters on the current line. It works in both org and markdown mode, but it has some glitches at times.
---
Tags: org-mode, org-link, gui-emacs, prettify-symbols-mode
--- |
thread-66303 | https://emacs.stackexchange.com/questions/66303 | how to stop emacsclient on terminal insert `[I]` when I open a file? | 2021-06-14T21:05:56.867 | # Question
Title: how to stop emacsclient on terminal insert `[I]` when I open a file?
I'm using `emacs` on MacOS (v11.4 Big Sur) installed from homebrew-emacs-plus and, every time I want to open a file for a quick edit on the terminal (on `iTerm2`) using `emacsclient`, a character gets inserted at the beginning the file (please check the attached image).
Other function keys like `delete` also insert sequences like `[3~]` and, I know there must be a simple solution I can find a direct reference to this.
How can I fix this so that I can do quick edits on directly on my terminal?
Regards,
# Answer
> 2 votes
Following the advice from @NickD, I found the offending config on my `init.el`:
```
(global-set-key (kbd "M-[") 'insert-pair)
(global-set-key (kbd "M-{") 'insert-pair)
(global-set-key (kbd "M-\"") 'insert-pair)
```
Thanks!
---
Tags: character-encoding, config, control-characters
--- |
thread-64065 | https://emacs.stackexchange.com/questions/64065 | What is the keycode of C-TAB? | 2021-03-23T12:41:07.593 | # Question
Title: What is the keycode of C-TAB?
iTerm does not send ctrl+tab itself, so I need to configure it myself. I can't figure it what key code ctrl+tab is though.
# Answer
1. In iTerm2 profiles, pick the profile you're using, then go to the Keys settings.
2. Click `+` to add a key command. Click and press `Ctrl+Tab`. Then choose the command Send Escape Sequence. Use `[27;5;9~` as the sequence.
Then test this in `emacs -nw -q` by using `C-h k C-tab` to see if it displays `<C-tab>`.
> 1 votes
---
Tags: key-bindings, term, keyboard-layout, ascii
--- |
thread-38988 | https://emacs.stackexchange.com/questions/38988 | Archive DONE tasks that are at least month after completion | 2018-02-21T16:56:16.310 | # Question
Title: Archive DONE tasks that are at least month after completion
I use org-archive-subtree to clean my org files. Most of my tasks lie under `* Tasks` header so I run the function on it using prefix (`C-u C-c C-x C-s`). I noticed that the function only asks for confirmation when it encounters a DONE task.
Would it be possible to change its behavior to:
1) Ask only when the item has DONE state **and** it has a CLOSED timestamp that's at least month old (or does not have this timestamp at all but is still in DONE). I like to review my last week seeing what I did so archiving too young tasks breaks this option for me.
2) Do the above checks but archive without asking if the conditions are met.
# Answer
> 1 votes
I use this approach from the excellent page http://doc.norang.ca/org-mode.html#Archiving -- the whole of that page is worth a read, and Bernt Hansen deserves all the credit for this not me.
This creates a function used to produce a custom agenda showing tasks suitable for archiving. First, there's the function that skips tasks that *aren't* suitable for archiving:
```
;; Custom agenda skip function to skip entries with activity in the
;; past month used to find candidates for archiving. Adapted from
;; http://doc.norang.ca/org-mode.html#Archiving
(defun my/skip-non-archivable-tasks ()
"Skip trees that are not available for archiving"
(let ((next-headline (save-excursion (or (outline-next-heading) (point-max)))))
;; consider only tasks with done todo headings as archivable tasks
(if (member (org-get-todo-state) org-done-keywords)
(let* ((subtree-end (save-excursion (org-end-of-subtree t)))
(daynr (string-to-number (format-time-string "%d" (current-time))))
(a-month-ago (* 60 60 24 (+ daynr 1)))
(last-month (format-time-string "%Y-%m-" (time-subtract (current-time) (seconds-to-time a-month-ago))))
(this-month (format-time-string "%Y-%m-" (current-time)))
(subtree-is-current (save-excursion
(forward-line 1)
(and (< (point) subtree-end)
(re-search-forward (concat last-month "\\|" this-month) subtree-end t)))))
(if subtree-is-current
next-headline ;; has a date in this month or last month, so skip it
nil)) ;; available to archive
(or next-headline (point-max)))))
```
Next a custom agenda command is defined to show an agenda with tasks that can be archived.
```
;; Add an agenda view that utilises this skip function.
(setq org-agenda-custom-commands
(cons
'("A" "Candidate trees for archiving" tags "-NOARCHIVE"
((org-agenda-overriding-header "Candidate tasks for archiving")
(org-agenda-skip-function 'my/skip-non-archivable-tasks)))
org-agenda-custom-commands))
```
Finally, use this as follows:
1. Pull up the Agenda view of old tasks (no activity this or last month) with `C-c a A` (`A` is the custom agenda command defined above).
2. To archive individually go to the entry and do `C-c C-x C-a`
3. To bulk archive mark each entry in the agenda with `m` then bulk archive them with `B $`.
# Answer
> 0 votes
You do not give an example of the initial input and the desired output. However, if i understood correctly, assuming today is July 2020 and you have:
```
* Tasks
** TODO My task 1
SCHEDULED: <2020-06-28 Fri>
My task 1 description
** DONE My task 2
SCHEDULED: <2020-06-29 Sat>
My task 2 description
** DONE My task 3
SCHEDULED: <2020-06-30>
My task 3 description
** DONE My task 4
SCHEDULED: <2020-07-01>
My task 4 description
```
this should do what you want:
```
(defun my-arch ()
(interactive)
(org-map-entries 'my-arch-map
(format-time-string "SCHEDULED<\"<%Y-%m-01>\"/DONE")
'tree))
(defun my-arch-map ()
(unless (string= (org-element-property :raw-value (org-element-at-point)) "Tasks")
(org-archive-subtree)
(setq org-map-continue-from (org-element-property :begin (org-element-at-point)))))
```
Specifically, if you put your cursor at Tasks level and execute `M-x my-arch`, the Task 2 and 3 (done in the past month) are archived.
Task 1, occurred in the past, but undone is not archived.
Task 4, done in the current month, is not archived.
As regards the code, `org-map-entries` applies a function (here `my-arch-map`) to everything matching a condition. The condition here is set dynamically on the basis of the current date, assumed something in July 2020. See orgmode.org/manual/Matching-tags-and-properties.html to learn about setting conditions.
The scope of `org-map-entries` is the tree, so nothing is done outside the tasks subtree.
After parsing an entry, `org-map-entries` skips to the next one. However, if your action implies removing the entry (such as here when archiving), the cursor is automatically placed on the next, so the skip would just cause an incorrect parsing here. To avoid this, with `org-map-continue-from`, you bring the cursor back to the beginning of current element, so the skip does not harm.
The `unless` condition is not strictly necessary here, but could turn handy for alternate matching. In fact, since the scope of `org-map-entries` is the tree, the whole Tasks subtree is parsed first and then the subtree elements. If you use a negative condition, such as archiving everything not marked as TODO, then the entire Tasks subtree matches and is archived disregarding its element values. Also is you condition is only related to the `SCHEDULING` property, no property at Tasks level means a matching and so again it would be archived. To avoid this edge cases, we set to never parse an entry, such as the main one, whose raw value is "Tasks".
# Answer
> 0 votes
This is an old question but recently tried to solve the same problem with `org-ql`. Hopefully, someone else stumbling on this will find it useful.
This is what I came up with
```
(defun +org-archive-archivable()
"Automatically archive all items that were closed 30 days ago or before"
(interactive)
(org-ql-select org-agenda-files `(closed :to ,(ts-format (ts-adjust 'day -30 (ts-now))))
:action 'org-archive-subtree-default))
```
---
Tags: org-mode, org-ql
--- |
thread-66426 | https://emacs.stackexchange.com/questions/66426 | Why does setting use-package-always-ensure cause Emacs to contact package repositories at startup? | 2021-06-21T19:42:57.167 | # Question
Title: Why does setting use-package-always-ensure cause Emacs to contact package repositories at startup?
I have the following in my init.el:
```
(setq use-package-always-ensure t)
```
because I want packages referenced by `use-package` to be downloaded automatically if I don't have them.
When I enable this setting however, *every time* Emacs starts I see "Contacting host ..." for each package repository (ELPA, MELPA, etc) before start-up is complete and it takes a very long time. It's as if my package archive contents are always assumed to be stale.
Why is this happening and how can I stop it?
# Answer
After a quick skim of the `org-package-ensure` package’s source code, it should only contact the package server if it is asked to install a package that you don’t have. Are you sure you’re not asking it to install a package that doesn’t exist?
> 1 votes
---
Tags: use-package, package-repositories, start-up
--- |
thread-66428 | https://emacs.stackexchange.com/questions/66428 | How can I get projectile-grep et al to choose the project before searching? | 2021-06-21T20:46:09.647 | # Question
Title: How can I get projectile-grep et al to choose the project before searching?
Projectile-grep, projectile-ag et al always execute the search in the current file's project.
What I want to do is to select the project from a completion list and get projectile to search that project instead of having to open a file in the project directory and running the search from there.
Does emacs or projectile itself have some way of doing that? The only way I can think of for now is to get the completion dialog to open a buffer onto a file from that project and run the projectile-grep command after that. That seems clumsy some how.
# Answer
> 1 votes
`s-p p` (where `s-p` represents whatever prefix key you have chosen) will allow you to choose a different project. It then prompts you to open a file from that project; you can just open whatever file is first in the list for speed. Then do the search.
https://docs.projectile.mx/projectile/configuration.html#switching-projects
---
Tags: projectile, grep, directory, helm-selection
--- |
thread-66419 | https://emacs.stackexchange.com/questions/66419 | Expanding Abbrev Mode Alphabet | 2021-06-21T12:52:43.867 | # Question
Title: Expanding Abbrev Mode Alphabet
Is it possible to write some elisp code so that we can use numbers for Abbrev Mode abbreviations? E.g.,
m2 -\> me too
h4 -\> hope for
gr8 -\> greate
# Answer
> 2 votes
Yes, you can do this:
```
(define-abbrev global-abbrev-table "h4" "hope for")
```
if you really want an h4, you just "undo" (for me that is C-/, but you may have it bound to something else.) You can also limit the scope to a specific mode, e.g. `org-mode-abbrev-table` or so.
---
Tags: abbrev, numbers
--- |
thread-66422 | https://emacs.stackexchange.com/questions/66422 | How do I use a proxy for only some specific URLs? | 2021-06-21T15:23:09.010 | # Question
Title: How do I use a proxy for only some specific URLs?
Like with FoxyProxy, I want to use proxy in emacs only for URLs that match a specific regexp.
E.g., if the URL matches `\\.ec2\\.internal`, I want the `url-proxy-services` to be `"ip-10-0-37-237.ec2.internal:8081"`, otherwise none.
Note that the `no_proxy` key works the other way around - it *excludes* matching URLs from proxy processing, while I want to only *include* some URLs.
# Answer
Package `url-proxy` provides a *defvar* called `url-proxy-locator` that allows you to define your own locator.
```
(defun locate-my-url-proxy (urlobj host)
(cond
((string-match-p "\\.ec2\\.internal" host)
"PROXY ip-10-0-37-237.ec2.internal:8081")
(t "DIRECT")))
;;; returns "http://ip-10-0-37-237.ec2.internal:8081/"
(let ((url-proxy-locator #'locate-my-url-proxy)
(urlobj (url-generic-parse-url "https://sldjf.ec2.internal/jdsklfj")))
(url-find-proxy-for-url urlobj (url-host urlobj)))
```
> 0 votes
---
Tags: url, proxy
--- |
thread-66410 | https://emacs.stackexchange.com/questions/66410 | Different abbrevs for each major mode | 2021-06-21T03:29:05.197 | # Question
Title: Different abbrevs for each major mode
The https://www.emacswiki.org/emacs/AbbrevMode says
> You can have different abbrevs for each mode (cperl, c++, Message);
but it doesn't show exactly how, yet that's exactly what I am looking for. So,
I found the following code from here,
```
(setq xem-abbrev-table nil)
(define-abbrev-table 'xem-abbrev-table
'(
("`d" "(defun f▮ ()\n \"DOCSTRING\"\n (interactive)\n (let (VAR)\n\n ))" )
("`i" "(insert ▮)" )
("`l" "(let (x▮)\n x\n)" )
("`m" "(message \"%s▮\" ARGS)" )
("`p" "(point)" )
("s" "(setq ▮ VAL)" )
("w" "(when ▮)" )
("bsnp" "(buffer-substring-no-properties START▮ END)" )
;; hundreds more
)
"Abbrev table for `xem'"
)
(abbrev-table-put xem-abbrev-table :regexp "\\([_-*0-9A-Za-z]+\\)")
(abbrev-table-put xem-abbrev-table :case-fixed t)
(abbrev-table-put xem-abbrev-table :system t)
(define-derived-mode xem prog-mode "∑lisp"
"A major mode for emacs lisp...."
(abbrev-mode 1)
:abbrev-table xem-abbrev-table ; actually, we don't need this line, because our name is “xem” + “-abbrev-table” so define-derived-mode will find it and set for us
)
```
Q1: I want to change it to a minor mode for the `elisp` major mode, how to do that? Please be specific, as I know the question is quite similar with How to use abbrev with different configuration for each mode? but I don't understand the replies there as I don't know elisp except copying from working code.
Q2: Note the first several abbreviations have leading "\`", that's what the prefix I want all my abbreviations to start with, but it's not working, maybe because of Alternative to abbrev-mode that supports special characters in abbreviations? however, I really don't understand the elisp code there. So, can you make the above code work with leading "\`" as abbreviations prefix please?
PS.
Using an abbreviation prefix comes from https://www.emacswiki.org/emacs/AbbrevMode as well:
```
;;; sample abbrev definitions
(eval-after-load "cc-mode"
'(declare-abbrevs (c-mode-abbrev-table c++-mode-abbrev-table)
(("#s" "#include <>" "C-b")
("#i" "#include \"\"" "C-b")
("#ifn" "#ifndef")
("#e" "#endif /* */" "C-3 C-b")
("#ifd" "#ifdef")
. . .
```
However, that's not exactly what I was looking for, defining different abbrevs for each mode, because *"The third column is a series of keystrokes you should have issued after the expansion"*.
# Answer
As you've seen, abbrev normally requires the abbreviation to contain only word-constituent characters, and that doesn't normally include ```. You could *make* that character word-constituent by changing its syntax for the mode in question, but I believe it would be better to adapt abbrev (only) to your requirement (as lots of things are affected by syntax).
You may find this suitable:
```
(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.")
```
And then to use it in `emacs-lisp-mode`:
```
(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)
```
To use it with a mode which is not loaded by default, you would do something like this:
```
(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))
```
Where `"sh-script"` is the name of the library (sans `.el` extension or similar) in which the major mode `sh-mode` is defined, as indicated by `C-h``f` `sh-mode`.
---
Note that you don't need to define a minor mode. Every major mode has an abbrev table, which is available for you to use provided that the library defining the major mode has been loaded (hence the use of `with-eval-after-load` for things which aren't loaded by default).
> 4 votes
---
Tags: minor-mode, abbrev
--- |
thread-48571 | https://emacs.stackexchange.com/questions/48571 | On using Elisp macros for partial application | 2019-03-25T11:59:17.553 | # Question
Title: On using Elisp macros for partial application
I want to improve my Elisp, but despite reading about the differences between functions and macros (including discussions here in Emacs SE and on Reddit), I still find examples where the distinction confuses me.
For example, in the "starter-pack" Radian, a macro can be found which wraps `use-package` ensuring some sort of partial application:
```
(defmacro use-feature (name &rest args)
"Like `use-package', but with `straight-use-package-by-default' disabled."
(declare (indent defun))
`(use-package ,name
:straight nil
,@args))
```
As a case study, would it not be possible to achieve the same with a `defun`? After all, this seems like a simple case of partial application, or am I missing something? Do we need a macro here just because `use-package` itself is a macro which we don't want a `defun` body to evaluate?
And would there be a safe way to improve this macro to take care of a possibly unwanted case `(use-feature foo :straight t)`?
# Answer
> 1 votes
This is an old question, but every question deserves an answer. You basically had it with "because use-package itself is a macro which we don't want a defun body to evaluate". More specifically, it couldn't be a defun, because:
1. Order Of Evaluation: `use-package` defines the order of evaluation (before and after loading its package) with, for example, the `:init`, `:config` and `:after` keywords. If `use-feature` were a defun, all arguments would be evaluated in order.
2. Quoting: Some `use-package` sections, such as `:bind` take unquoted data as arguments (which would throw an error for not being a function), and many take an unquoted symbols (which emacs would try to evaluate as variables). You could require the user to manually quote everything, but that would make the `use-feature` API very different from `use-package`.
To answer the finall question at the end of the post - if there are 2 `:straight` keywords, the order of evaluation depends on the internals of `use-package`. If this version of the macro lets the user override it, swapping the lines `,@args` and `:straight t` would probably change that behaviour. But might not, and you probably can't know without reading the code of `use-package`.
---
Tags: elisp-macros
--- |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.