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-69624 | https://emacs.stackexchange.com/questions/69624 | Display attachment to mu4e message (a PDF) in the same window rather than new frame | 2021-12-03T16:39:03.290 | # Question
Title: Display attachment to mu4e message (a PDF) in the same window rather than new frame
I am using mu4e and pdf-tools. Whenever I go to open an attached pdf (e.g., with `gnus-article-press-button`) the attachment pops open in a new frame. How can I control where it pops up? Looking at that function and trying to trace it I couldn't find anything related to `display-buffer` or something I recognized as window management functionality.
# Answer
> 1 votes
So I think that `gnus-article-press-button` eventually boils down to calling `xdg-open`.
I had `emacsclient` set as my default pdf reader in `mimeapps.list` and using a desktop file that called `emacsclient` with a `--create-frame` argument. Removing the `--create-frames` argument solved the problem and now `emacsclient` tries to use the existing frame when displaying a buffer.
---
Tags: window, mu4e, gnus, display-buffer
--- |
thread-62136 | https://emacs.stackexchange.com/questions/62136 | .dir-locals for specific directory but not its children | 2020-12-06T07:42:33.943 | # Question
Title: .dir-locals for specific directory but not its children
How to set a directory local variable for a directory itself non-recursively? I don't want the variable set in `.dir-locals.el` affect the sub-directories.
---
Edited:
My use case is: I'd like to hide dot files under `~` by setting `dired-omit-files` since there are quite a lot of them in my home directory. But I do not want to hide dot files of any other subdirectory of `~`. Though I think I can set it using some `dired-mode-hook` by comparing `buffer-name` or `buffer-file-name`, I guessed there may be simpler solution by using directory local variables.
# Answer
The Directory Variables section of the emacs manual says:
> Here’s an example of a ‘.dir-locals.el’ file:
>
> ```
> ((nil . ((indent-tabs-mode . t)
> (fill-column . 80)
> (mode . auto-fill)))
> (c-mode . ((c-file-style . "BSD")
> (subdirs . nil)))
> ("src/imported"
> . ((nil . ((change-log-default-name
> . "ChangeLog.local"))))))
>
> ```
>
> \[... snip ...\] The special ‘subdirs’ element is not a variable, but a special keyword which indicates that the C mode settings are only to be applied in the current directory, not in any subdirectories.
so that should do the job, e.g.
```
((nil . ((dired-omit-files . t)
(subdirs . nil))))
```
although for some reason when I test, it seems to be applying to all directories, and don't have time to figure out why. Perhaps you'll have better luck!
> 2 votes
# Answer
No, there isn't. You can set the variable in the directory-local variables, and the unset it in the child directory's variables. Or you can use file-local variables.
> 1 votes
---
Tags: dired, directory-local-variables, local-variables
--- |
thread-69626 | https://emacs.stackexchange.com/questions/69626 | How do I remove the key translation for function keys with modifiers? | 2021-12-03T18:53:18.910 | # Question
Title: How do I remove the key translation for function keys with modifiers?
I would like to bind the dedicated function keys (F1 through F10) using the standard modifier key, e.g. `(define-key my-keymap (kbd "<S-F2>") #'my-function)`. However, this and similar keybindings have no effect.
`describe-key` reports: "\<f2\> (translated from \<S-f2\>) runs the command. . ." and gives the target command for the unmodified F2 key. This is true for all the function keys on my system (using Windows 10 and Emacs 27.2).
Earlier StackExchange answers about key translation suggest that I must modify one of the translation keymaps. Following some specific advice, I have tried `(define-key input-decode-map [f2] 'nil)` but evaluating this form has no effect.
More generally, I cannot find where this bulk translation is occurring. Running `emacs -q` shows that some of the translations, but not all, are set early in the start-up process. With `-q`, `define-key()` says that "\<f3\> (translated from \<S-f3\>) runs the command kmacro-start-macro-or-insert-counter."
Is there is an easier way to de-translate the function keys? Is there a downside to doing so?
# Answer
> ```
> (define-key my-keymap (kbd "<S-F2>") #'my-function)
>
> ```
> describe-key reports: `"<f2> (translated from <S-f2>)`
`<S-F2>` is not `<S-f2>`
Note that `define-key` doesn't know whether the specified key actually exists or not -- you could equally define a binding for `<S-jewfjwjpfwmpfm>` and it would happily accept it. It's just that in practice neither `<S-jewfjwjpfwmpfm>` nor `<S-F2>` will ever be received.
> More generally, I cannot find where this bulk translation is occurring
It's a hard-coded feature in the `read_key_sequence` C code.
> 2 votes
---
Tags: key-bindings, key-translation-map, function-key
--- |
thread-69579 | https://emacs.stackexchange.com/questions/69579 | How detect when lsp-mode has loaded a files references? | 2021-12-01T04:42:33.177 | # Question
Title: How detect when lsp-mode has loaded a files references?
I'm running into an awkward bug with `lsp-mode` \+ `clangd` for batch editing files.
When a source file is loaded, the symbols it points to aren't immediately available (using `xref-find-definitions` for example).
Calling `xref-find-definitions` fails on a newly loaded buffer.
Adding a sleep timer: e.g: `(sleep-for 3.0)` then calling `xref-find-definitions` works as expected (showing the header for an implementation of a function for example).
How can this be handled more reliably than sleeping and hoping the file references have loaded?
---
For reference
# Answer
> 0 votes
Emacs doesn’t index the file, the LSP server does (in this case that is clangd). The LSP protocol supports asynchronous notifications when results are available, so in principle clangd should be accepting your request and replying with a token that will identify the results when they are available. `lsp-mode` would then process the results as normal once it receives a notification with that token.
In the comments, you reported seeing these log messages:
```
LSP :: Connected to [clangd:57835/starting].
Debugger entered--Lisp error: (error "The connected server(s) does not support method te...")
error("The connected server(s) does not support method %s..." "textDocument/definition")
lsp--send-request-async((:jsonrpc "2.0" :method "textDocument/definition" :params
```
This indicates that clangd has not advertised that it supports looking up definitions. Since it then starts working a few seconds later, this sounds like a bug in clangd. Or maybe clangd just doesn’t support this at all, and you’re falling back to some other xref backend, in which case the answer to your question has nothing to do with `lsp-mode` at all. You should check the value of `xref-backend-functions`.
Edit: if the problem is simply that your batch process is running before the connection to the LSP server is fully established, then use the `lsp-after-initialize-hook` hook to start it instead.
---
Tags: lsp-mode
--- |
thread-69632 | https://emacs.stackexchange.com/questions/69632 | How can I load some snippets depending on the extension of current file? | 2021-12-04T07:52:37.517 | # Question
Title: How can I load some snippets depending on the extension of current file?
When I work on web files I usually use `web-mode` for javascript, php and css files, the problem I have is that yasnippet uses the current mode to find what snippets to load for that buffer ( as stated in the docs ), but I would like to load a basic set of snippets for the current mode and also load some different sets of snippets depending on the file extension. Is this possible?.
# Answer
Instead of associating `web-mode` with that extension in `auto-mode-alist`, associate your own custom derivative mode (using `define-derived-mode`), and load whatever you want in the body of that mode.
> 0 votes
---
Tags: yasnippet, web-mode
--- |
thread-69641 | https://emacs.stackexchange.com/questions/69641 | How can I change the default `init.el` file Emacs automatically searches for? | 2021-12-04T18:52:22.687 | # Question
Title: How can I change the default `init.el` file Emacs automatically searches for?
I am new to emacs. Following the instruction online, the default customization file is in my home directory and is under the name `.emacs`. I want to follow the tutorial I am currently going over and want to save everything in a folder and upload it to my GitHub repo for future reference. However, the folder I am currently working in is the `\emacs.d` folder and I did have another copy of `init.el` file under that folder. I am wondering if it's possible to force emacs to follow the customization under that `init.el` file instead of loading `.emacs` in my home directory?
# Answer
There's a priority order for possible init file names, and Emacs will use the first one that it finds.
If you don't want it to use `~/.emacs` then you'll have to make sure that file does not exist so that it will continue looking for other possibilities.
Refer to `C-h``i``g` `(emacs)Find Init`
> 1 votes
---
Tags: init-file
--- |
thread-69311 | https://emacs.stackexchange.com/questions/69311 | How to deal with "No TeX trees available; configure ‘TeX-tree-roots’" error? | 2021-11-10T21:01:08.643 | # Question
Title: How to deal with "No TeX trees available; configure ‘TeX-tree-roots’" error?
When I open a new tex file and hit C-c C-e \<RET\> to create document environment, the message buffer shows
> TeX-search-files-by-type: No TeX trees available; configure ‘TeX-tree-roots’.
It will then exit the environment input procedure and there is no automatically created \begin{document} \end{document}. How do I deal with this problem? This has not happened before.
I am using an M1 MacBook Pro running macOS Monterey 12.0.1
Emacs version: 27.2
AUCTeX version: 13.0.14
Edit: The problem appears only when using GUI. Emacs in terminal works fine.
# Answer
It turns out that the issue is, as @ArashEsbati suggested, that Emacs is not able to find `kpsewhich` in GUI. It is a macOS specific issue, as discussed in this problem. We may set the environment PATH in GUI to be the same as in terminal by using the package exec-path-from-shell. With `use-package`, adding the following to my init file solved the problem.
```
(use-package exec-path-from-shell
;; Get environment variables such as $PATH from the shell
:ensure t
:config (when (memq window-system '(mac ns x))
(exec-path-from-shell-initialize)))
```
> 1 votes
---
Tags: latex, auctex, tex
--- |
thread-69656 | https://emacs.stackexchange.com/questions/69656 | how to fix / workaround wonky emacs auto-indenting of some C++ | 2021-12-06T18:07:35.173 | # Question
Title: how to fix / workaround wonky emacs auto-indenting of some C++
See the below. I have two definitions of a floating point array. The latter is valid with C++11.
The first one is auto indented in a sane fashion. The second one looks like emacs just doesn't know what to do with it.
I don't really care that much what the auto-indenter decides to do as long as it doesn't look irrational.
Is there a way to fix this or workaround it?
Here is the C++ code, formatted as by the emacs `indent-region` function:
```
int main() {
// looks good to me
float nums[9] =
{
1., 2., 3.,
4., 5., 6.,
7., 8., 9.,
};
// wtf
float * numsp = new float[9]
{
1., 2., 3.,
4., 5., 6.,
7., 8., 9.,
};
}
```
# Answer
I see this with `c++-mode`, but not with `c-mode`. Consider filing a bug report to fix it for C++ mode: `M-x report-emacs-bug`.
There's also a related, more-general thread about fixing such indentation of data, in `emacs-devel@gnu.org`.
> 1 votes
---
Tags: indentation, c++
--- |
thread-27765 | https://emacs.stackexchange.com/questions/27765 | Get a better printed representation of a hash-table | 2016-10-12T19:40:06.047 | # Question
Title: Get a better printed representation of a hash-table
I work with ELisp hash-table and I would like to have a better printed representation of it. I'm on Emacs version 24.5.1. When I create a hash-table
```
(setq table (make-hash-table))
(puthash :name "john" table)
(puthash :age 31 table)
```
I get something like:
```
#s(hash-table size 65 test eql rehash-size 1.5 rehash-threshold 0.8 data
(:name "john" :age 31))
```
But I just want to have the content (i.e. `data`) of my hash-table.
```
(:name "john" :age 31)
```
I know that you can have a specific printed representation in Common Lisp thanks to the `print-object` method. Even the pretty printer `pp` displays the hash-table metadata. Any idea?
Thanks
# Answer
> 2 votes
EDIT
An even easier/more straightforward alternative to my original answer is to just use `maphash`:
```
(let (plist)
(maphash (lambda (k v)
(push k plist)
(push v plist))
table)
(pp (nreverse plist)))
```
END EDIT
I would suggest to just reformat the `pp` output yourself, e.g. using:
```
(defun pp-hash (table)
(let ((data (nthcdr 2 (nbutlast
(split-string (pp-to-string table) "[()]")
2))))
(princ (concat "(" (car data) ")"))))
```
You can now print your table using `(pp-hash table)`.
NOTE that the Emacs manual defines the *printed representation* of an object as the output generated by the Lisp printer (the function `prin1`) for that object (i.e. a syntax that is accepted by the Lisp reader, `read`. See also @wasamama's comment)
# Answer
> 2 votes
Note: this solution is just for pretty visualization of a complex hash-table and can't really be read back
Another option would be to use the yaml.el package (https://melpa.org/#/yaml) which provides the function `yaml-encode`. Here is an example of its usage:
```
(let ((h (make-hash-table :test 'equal))
(nested (make-hash-table :test 'equal)))
(puthash 'a [1 2 3] nested)
(puthash 'b [3 4 5] nested)
(puthash [7 8] 'x nested)
(puthash 'nested-map nested h)
(puthash 'another-key 7 h)
(puthash 'favorite-numbers '(1 2 12 29 40) h)
(puthash 'state "Arizona" h)
(yaml-encode h))
```
produces the following YAML:
```
nested-map:
a: [1, 2, 3]
b: [3, 4, 5]
[7, 8]: x
another-key: 7
favorite-numbers: [1, 2, 12, 29, 40]
state: Arizona
```
Disclaimer: I'm the author of yaml.el
# Answer
> -1 votes
I was able to pretty print a hash table by executing the following
```
ELISP> (json-read-from-string (json-encode org-id-locations))
((40a4d409-c922-4cc6-875f-15a711bf7f78 . "~/e/main.org")
(f7d35e36-8485-41bb-b499-af9371b240c1 . "~/e/main.org")
(71205b41-0d40-4846-adb8-8ada7381160e . "~/e/main.org"))
```
Where `ord-id-locations` is a hash table (as can be seen below)
```
ELISP> (type-of org-id-locations)
hash-table
```
---
Tags: print, hash-tables
--- |
thread-69661 | https://emacs.stackexchange.com/questions/69661 | How to define multiple key bindings more concisely? | 2021-12-07T04:51:02.463 | # Question
Title: How to define multiple key bindings more concisely?
I'm trying to write a helper macro to conveniently define keybindings in my configuration file.
The idea is to replace the following configuration entry:
```
(use-package org-roam
:config
(define-key evil-normal-state-map (kbd "SPC n g") #'org-roam-graph)
(define-key evil-insert-state-map (kbd "C-c n g") #'org-roam-graph)
(define-key evil-visual-state-map (kbd "C-c n g") #'org-roam-graph))
```
With that one:
```
(use-package org-roam
:config
(define-evil-key "n g" #'org-roam-graph))
```
Here's how I'm trying to write such a macro:
```
(defmacro define-evil-key (k fn)
(define-key evil-normal-state-map (kbd (concat "SPC " k)) fn)
(define-key evil-insert-state-map (kbd (concat "C-c " k)) fn)
(define-key evil-visual-state-map (kbd (concat "C-c " k)) fn))
```
But when I press the defined keybinding `SPC n g`, I get the following error: `Wrong type argument: commandp, #'org-roam-graph`.
I'm not really sure, what is going wrong. It seems to me, that the macros should be expanded on the sequence of `define-key` calls, but it doesn't work that way.
Could someone please explain how to properly define this macros and how to debug similar errors in the future?
# Answer
> 2 votes
A macro has to return code. The return value of your macro is whatever the last form evaluated to:
```
(defmacro define-evil-key (k fn)
(define-key evil-normal-state-map (kbd (concat "SPC " k)) fn)
(define-key evil-insert-state-map (kbd (concat "C-c " k)) fn)
(define-key evil-visual-state-map (kbd (concat "C-c " k)) fn))
(pp-macroexpand-expression '(define-evil-key "x" #'foo))
=> #'foo
```
Being what the last `define-key` form had evaluated to.
The specific error "Wrong type argument: commandp, #'org-roam-graph." is related to the fact that macro arguments are not evaluated -- this prevents the `define-key` calls from binding the intended command.
You wanted something like this:
```
(defmacro define-evil-key2 (k fn)
`(progn
(define-key evil-normal-state-map (kbd ,(concat "SPC " k)) ,fn)
(define-key evil-insert-state-map (kbd ,(concat "C-c " k)) ,fn)
(define-key evil-visual-state-map (kbd ,(concat "C-c " k)) ,fn)))
(pp-macroexpand-expression '(define-evil-key2 "x" #'foo))
=> (progn
(define-key evil-normal-state-map (kbd "SPC x") #'foo)
(define-key evil-insert-state-map (kbd "C-c x") #'foo)
(define-key evil-visual-state-map (kbd "C-c x") #'foo))
```
That said, I see no reason to use a macro for this. I recommend that you make this a function.
---
Tags: key-bindings, elisp-macros
--- |
thread-69612 | https://emacs.stackexchange.com/questions/69612 | How to warn before editing or saving a buffer whose underlying file no longer exists? | 2021-12-02T16:36:46.603 | # Question
Title: How to warn before editing or saving a buffer whose underlying file no longer exists?
(**NB:** In this post, I will use expressions like "a buffer's *underlying* file" to mean, in the Emacs' documentation's terminology, "the file a buffer is *visiting*", i.e. the value of `(buffer-file-name SOME-BUFFER)` for the buffer `SOME-BUFFER`.)
---
Sometimes it happens that a buffer's underlying file gets modified on disk by some other process.
If one tries to modify such a buffer, Emacs warns of the on-disk change, and requests confirmation; e.g. (in the minibuffer):
```
one_really_busy_file changed on disk; really edit the buffer? (y, n, r or C-h)
```
Furthermore, if after responding `y` to such a confirmation request, one modifies such a buffer, and then attempts to *save* the modified buffer, then Emacs once again issues a warning and a confirmation request; e.g.:
```
one_really_busy_file has changed since visited or saved. Save anyway? (y or n)
```
To be sure, Emacs does not regard *all* modifications to a buffer's underlying file as being equally worthy of all this fuss. Changes to the underlying file's permissions, for example, do not elicit any of this.
Strangely enough, according to out-of-the-box Emacs, a buffer's underlying file's ***disappearance*** *also* fails to warrant such a response!
To be more specific, Emacs remains perfectly quiet if one modifies a buffer whose underlying file has ***disappeared***, and—even more surprising—, it remains equally silent when one then *saves* (`C-x C-s`) the modified buffer (thereby *re-creating* the underlying file).
---
**Q:** How can I get Emacs to issue a warning and a confirmation request also ***when one attempts to modify a buffer*** whose underlying file has disappeared?
# Answer
You can do this:
```
(add-hook 'before-save-hook 'foo)
(defun foo ()
(when (and (buffer-file-name) (not (file-exists-p (buffer-file-name))))
(unless (y-or-n-p "No such file. Create it?")
(error "OK, not saved"))))
```
However, this could be regarded as a feature: Emacs creates a file for a buffer you ask it to save.
But if you don't like this behavior you might consider filing a bug report (enhancement request): `M-x report-emacs-bug`.
> 1 votes
# Answer
You can use the `write-file-functions` hook to do this. It's what's called an "abnormal" hook, which means its return value is taken into account, unlike `before-save-hook`. In this case, if it returns `t`, the \`save-buffer' command returns without saving the buffer. E.g.
```
(add-hook 'write-file-functions #'foo)
(defun foo ()
(when (and (buffer-file-name) (not (file-exists-p (buffer-file-name))))
(not (y-or-n-p "No such file. Create it?"))))
```
> 1 votes
---
Tags: buffers, text-editing, warning, saving
--- |
thread-69672 | https://emacs.stackexchange.com/questions/69672 | Change and later restore the window configuration of a frame | 2021-12-07T22:15:52.160 | # Question
Title: Change and later restore the window configuration of a frame
Imagine I have a frame containing some number of windows—sometimes only one, sometimes split in various ways.
Now imagine that one of the displayed windows contains an `org-mode` buffer. What I want is:
1. When I invoke `org-edit-src-code`, I want to
* save the current configuration of the window,
* delete all the other windows on that frame, and
* display *only* the source-editing window in that frame.
2. When I invoke `org-edit-src-exit` to return to the `org-mode` buffer, I want to restore that frame's original window configuration. (Obviously, if some of the other buffers have been killed in the interim, those windows will have to display something else.)
The `display-buffer` and `window-quit` don't seem to offer such a capability, but maybe I'm missing it.
I'm imagining implementing it using a custom "display action function" that would stash the window configuration (from `current-window-configuration`) in a window parameter and with a custom `quit-window-hook` that would check for that window parameter.
1. Does something like this already exist?
2. Does this seem like a stupid thing to even want?
3. Does such a sketch of a plan seem like a reasonable approach?
# Answer
> 1 votes
This should get you started. One of the easiest ways to save an restore a window config is to use a register. See the Emacs manual, node Configuration Registers.
That explains how to do this interactively. You can use the code that accomplishes it in your own Elisp code, to do whatever similar you like.
Here is that entire Elisp-manual node:
> You can save the window configuration of the selected frame in a register, or even the configuration of all windows in all frames, and restore the configuration later. See Windows, for information about window configurations.
>
> * **`C-x r w R`**
>
> Save the state of the selected frame’s windows in register R (`window-configuration-to-register`).
> * `C-x r f R`
>
> Save the state of all frames, including all their windows, in register `R` (`frameset-to-register`).
>
> Use **`C-x r j R`** to restore a window or frame configuration. This is the same command used to restore a cursor position. When you restore a frame configuration, any existing frames not included in the configuration become invisible. If you wish to delete these frames instead, use `C-u C-x r j R`.
---
Tags: window-configuration, display-buffer
--- |
thread-48874 | https://emacs.stackexchange.com/questions/48874 | cycling between minibuffer and last window|buffer | 2019-04-11T15:30:08.897 | # Question
Title: cycling between minibuffer and last window|buffer
I'd like to cycle between an active minibuffer window and the last recent buffer.
```
1 (defun cycle-to-minibuffer-window ()
2 (interactive)
3 (when (active-minibuffer-window)
4 (if (minibuffer-window-active-p (get-buffer-window))
5 (select-window (other-buffer (current-buffer)))
6 (select-window (active-minibuffer-window)))))
7
8 (global-set-key (kbd "C-<f9>") #'cycle-to-minibuffer-window)
```
To bad that line 5 `(other-buffer (current-buffer))` returns, in this case, the wrong buffer. :(
**Which elisp construct could I use instead to get the buffer|window I wanted?**
*Example* (tested with `emacs -Q`):
1. There are 3 buffers: `*scratch*`, `*Messages*` and `*Minibuffer-0*`.
2. My active buffer is `*scratch*`. I do `find-file` aka `C-x C-f`.
3. Now pressing `C-<F9>` (calling my function), wants to switch to `*Messages*` buffer, but `*scratch*` buffer would be correct.
# Answer
> 1 votes
If you use Icicles then the buffer you want is the value of variable `icicle-pre-minibuffer-buffer`. It is the buffer that was current before the minibuffer became active."
If you don't use Icicles then you can save this buffer in a variable yourself by adding a function that sets it to `minibuffer-setup-hook`. E.g.
```
(defvar my-pre-minibuffer-buffer nil
"Buffer that was current before the minibuffer became active.")
(defun my-save-pre-buffer ()
"Set `my-pre-minibuffer-buffer'."
(setq my-pre-minibuffer-buffer (my-last-non-minibuffer-buffer)))
(defun my-last-non-minibuffer-buffer ()
"Return the most recently used non-minibuffer live buffer."
(catch 'my-last-non-minibuffer-buffer
(dolist (buf (buffer-list))
(when (and (buffer-live-p buf) (not (minibufferp buf)))
(throw 'my-last-non-minibuffer-buffer buf)))
nil))
(add-hook 'minibuffer-setup-hook 'my-save-pre-buffer)
```
Having this buffer in a global variable means you can access it anytime. E.g.:
```
(with-current-buffer my-pre-minibuffer-buffer ...)
```
or
```
(pop-to-buffer my-pre-minibuffer-buffer)
```
# Answer
> 1 votes
Another option I've found:
```
(nth 1 (buffer-list))
```
The minibuffer will be the 0th one in the `buffer-list` and the previous buffer is the 1st.
# Answer
> 0 votes
Another solution, which will only work if you use `ivy`, is to replace line 5 from my question with:
```
(select-window (ivy--get-window ivy-last))
```
---
Tags: buffers, window, minibuffer
--- |
thread-69674 | https://emacs.stackexchange.com/questions/69674 | How can I make `font-latex-sedate-face` have precedence over `font-latex-math-face`? | 2021-12-08T00:09:56.000 | # Question
Title: How can I make `font-latex-sedate-face` have precedence over `font-latex-math-face`?
In LaTeX mode, the face `font-latex-sedate-face` highlights commands of the form `\foo` which are not known by AUCTeX. I'd like commands of the form `\foo` which appear inside a math environment such as `\(\)` to respect `font-latex-sedate-face`. In a math environment, the face used is `font-latex-math-face`. The command `C-u C-x =` with the cursor over a `\foo` inside a math environment shows me both faces are used:
```
There are text properties here:
face (font-latex-math-face font-latex-sedate-face)
```
I've tried using the `( ... &override)` when customizing such faces but without success. What would be the correct way to make one face have priority over another? If I checked it correctly, none of those faces uses the overlay mechanism, so it should be possible to make `font-latex-sedate-face` override `fojnt-latex-math-face` instead of the other way around.
# Answer
> 1 votes
I ended up editing the `AUCTeX` file `font-latex.el`. I did not find a way to change this via my personal configuration file. Roughly, I had to (1) alter the order in which "ocurrences" of `font-latex-sedate-face` and `font-latex-math-face` are added in a list and (2) change what the function `font-latex-match-simple-command` finds by editing the variable `font-latex-match-simple-exclude-list`. When the editing of `font-latex.el` is done, I needed only to recompile the package. \[If you are a Doom Emacs user, running `doom build` (usually run after upgrading Emacs) takes care of that.\]
(1) In `font-latex.el`, in the end of the definition of the function `font-latex-make-user-keywords` we have:
```
(dolist (item
'((font-latex-match-math-env
(0 'font-latex-warning-face t t)
(1 'font-latex-math-face append t))
(font-latex-match-math-envII
(1 'font-latex-math-face append t))
(font-latex-match-simple-command
(0 'font-latex-sedate-face append))
(font-latex-match-script
(1 (font-latex-script (match-beginning 0)) append))
(font-latex-match-script-chars
(1 (font-latex-script-char (match-beginning 1)) prepend))))
(add-to-list 'font-latex-keywords-2 item t))
```
I reordered this so that the result of the search done by the function `font-latex-match-simple-command` receiving the face `font-latex-sedate-face` takes precendence over the result of the searches `font-latex-match-math-env` and `font-latex-match-math-envII` receiving the face `font-latex-warning-face`.
**Remark**: changing `append` to `prepend` in
```
font-latex-match-simple-command
(0 'font-latex-sedate-face append))
```
does force `font-latex-sedate-face` precedence over `font-latex-math-face`. However, it establishes precedence over other faces which we would not like it to override such as comments or the `\foo` commands known by AUCTeX.
(2) I had to edit the variable `font-latex-match-simple-exclude-list` adding parentesis and brackets to it:
```
(defvar font-latex-match-simple-exclude-list
'("%" "-" "," "/" "&" "#" "_" "`" "'" "^" "~" "=" "." "\"" "(" ")" "[" "]"))
```
The reason is to avoid TeX excerpts like `\(X\)` being incorrectly fontified with `font-latex-sedate-face`.
---
Tags: latex, auctex, faces, font-lock, highlighting
--- |
thread-69670 | https://emacs.stackexchange.com/questions/69670 | Forcing buffers whose names start with "*" to be skipped in many commands? | 2021-12-07T18:27:37.780 | # Question
Title: Forcing buffers whose names start with "*" to be skipped in many commands?
I'm using Emacs 26. There are many Elisp commands which offer the "next" buffer as part of the command's execution or after the command completes. I am looking for a way to keep buffers whose names start with `*` from showing up as the "next" buffer in all such commands.
Some commands which would have to change are `kill-buffer`, `switch-to-buffer`, *etc*.
I could search for all Elisp commands which offer the "next" buffer and write my own versions of these commands. However, I'm wondering if there might be more general way to keep all buffers whose names start with `*` from being treated as the "next" buffer in ***any*** command.
# Answer
I figured it out:
```
(defun my-buffer-predicate (buffer)
(let ((buffname (buffer-name buffer)))
(not (or (string-prefix-p "*" buffname)
(string-prefix-p " *" buffname)))
))
(defun my-set-buffer-predicate ()
(modify-all-frames-parameters
(list
(cons 'buffer-predicate #'my-buffer-predicate))))
(add-hook 'after-make-frame-functions 'my-set-buffer-predicate)
```
And I also run `(my-set-buffer-predicate)` at emacs startup.
This excludes buffers whose names start with "\*" and " \*" from many commands which automatically switch to their idea of a "next" or "previous" or "other" buffer. So, it's thankfully not necessary for me to try to advise a myriad of existing functions. Also, this doesn't inhibit a switch to `*scratch*` if there are no existing buffers to switch to, because that logic is handled elsewhere in emacs. The `*scratch*` buffer shows up as a fallback when no other eligible buffers exist.
All of this is exactly the functionality that I have been looking for.
> 1 votes
# Answer
There's no need to advise functions. `M-x info-apropos buffer-list` gives us a link to this info node: The Buffer List.
This paragraph in particular offers a solution:
> To change the order or value of a specific frame’s buffer list, set that frame’s ‘buffer-list’ parameter with ‘modify-frame-parameters’.
There isn't a `with-frame-parameters` as far as I know, but we can monkey-wrench one pretty easily:
```
(defmacro clean-buffer-list (&rest body)
"Remove all entries from the current frame's buffer-list parameter
that match the regex, \" ?\\\\\\*\"; update the parameter, and then
execute BODY in a `progn'. Note that this permanently modifies the
frame's buffer-list as a side effect."
(declare (indent defun)
(debug (body)))
`(let ((buffers ',(cl-loop for x in (frame-parameter nil 'buffer-list)
unless (string-match (rx (: (? " ") "*")) (buffer-name x))
collect x into rs
finally return rs)))
(set-frame-parameter nil 'buffer-list buffers)
(progn ,@body)))
```
I tested it like this:
```
M-x buffer-menu <RET>
(other-buffer) ; returns "*Buffer List*"
(clean-buffer-list (other-buffer)) ; returns "a.el"
```
The \*-buffers still live on in the fundamental buffer-list, but I'm not sure how to access them, and I think that's beyond the scope of this question. The linked info page should give you some pointers if that's what you need. The macro right now might also cause some wonky behaviour if you're calling it from within a \*-buffer; I haven't tested that extensively.
> 2 votes
---
Tags: buffers
--- |
thread-69687 | https://emacs.stackexchange.com/questions/69687 | Any way to disable tab usage in display algorithm? | 2021-12-09T05:17:41.053 | # Question
Title: Any way to disable tab usage in display algorithm?
When emacs displays buffer text to the terminal, along with whatever ANSI (or other termcap/terminfo) sequences it uses, it will occasionally use ordinary ASCII TAB characters to move the cursor. Since this is an output operation, its choice to use a TAB will often have nothing whatsoever with whether there is an actual TAB character in the text being edited, or whether I used the TAB key while editing.
The problem is that if the "terminal" emacs is displaying to is a Terminal window on my Mac (as it always is), and if I use the mouse and Mac clipboard to copy some emacs-displayed text somewhere else, those stray tab characters end up in the Mac clipboard, and they tend to paste as tabs, too, with often deleterious results.
If there's a way to, I would like to tell emacs never to use tabs while displaying text to me in its terminal. If that means emacs has to inefficiently use, say, two or more spaces instead of a single tab, or a move-cursor sequence instead of a tab, I am totally fine with that.
(P.S. I realize this sounds like a strange question. You may be wondering why I'm using the mouse cursor and Mac clipboard, instead of (actually as well as) the emacs kill buffer, to copy text. You may be wondering why I'm using terminal-mode emacs at all, instead of window-mode emacs. But I am, and I am, because that's the way I like it. And I'll like it even more if I can get those stray tabs out of the picture, because they really do get in the way sometimes.)
# Answer
> 0 votes
Not as far as I know. Note that there are also conditions where tabs in the buffer will be replaced with spaces.
---
Tags: terminal-emacs, redisplay, terminfo
--- |
thread-69649 | https://emacs.stackexchange.com/questions/69649 | parinfer-rust-mode doesn't get enabled automatically with clojure-mode via hook | 2021-12-05T16:02:39.753 | # Question
Title: parinfer-rust-mode doesn't get enabled automatically with clojure-mode via hook
The problem: upon opening a `.clj` file, the `clojure-mode` correctly starts. However, `parinfer-rust-mode` doesn't, despite being added to a `clojure-mode-hook`.
The setup (everything related to clojure from my config):
```
;; clojure
(use-package clojure-mode
:init
(setq clojure-indent-style 'align-arguments)
(setq clojure-align-forms-automatically t))
;; extra highlight
(use-package clojure-mode-extra-font-locking)
;; cider
(use-package cider)
;; parinfer disables https://www.emacswiki.org/emacs/ElectricPair mode. Look into re-enabling it for other languages I work in
(use-package parinfer-rust-mode
:hook clojure-mode
:init
(setq parinfer-rust-auto-download t))
```
`C-h v clojure-mode-hook`:
```
clojure-mode-hook is a variable defined in ‘clojure-mode.el’.
Its value is shown below.
This variable may be risky if used as a file-local variable.
Hook run after entering Clojure mode.
No problems result if this variable is not bound.
‘add-hook’ automatically binds it. (This is true for all hook variables.)
Value:
(parinfer-rust-mode #f(compiled-function
()
#<bytecode -0x1e6605021ebab616>)
(closure
(t)
nil
(set
(make-local-variable 'sesman-system)
'CIDER))
clojure--check-wrong-major-mode)
```
If I manually eval `(parinfer-rust-mode)`, mode gets enabled without any warnings or such.
I also tried to remove `:hook` from `use-package` and add it manually like so -
```
(add-hook 'clojure-mode-hook #'parinfer-rust-mode)
```
but it doesn't change anything, `parinfer-rust-mode` still doesn't start automatically.
What am I doing wrong?
# Answer
Turns out everything was working fine, except the files that I thought would be opened would not be opened really, and instead get loaded from some form of cache or something, apparently with already defined enabled modes. I'm not well-versed in emacs so can't pin-point it, but I know `find-alternate-file` (`C-x C-v`) on a Clojure buffer would re-run all the modes, all the hooks and everything would work out well.
> 0 votes
---
Tags: hooks, minor-mode, clojure
--- |
thread-69690 | https://emacs.stackexchange.com/questions/69690 | shell-mode how to color only keywords | 2021-12-09T11:20:01.927 | # Question
Title: shell-mode how to color only keywords
I have following definitions in my `.emacs` file for keyword coloring in `shell-mode`:
```
(add-hook 'shell-mode-hook 'ansi-color-for-comint-mode-on)
(font-lock-add-keywords 'shell-mode '(("alias " . font-lock-builtin-face)))
(font-lock-add-keywords 'shell-mode '(("mv " . font-lock-builtin-face)))
(font-lock-add-keywords 'shell-mode '(("rm " . font-lock-builtin-face)))
(font-lock-add-keywords 'shell-mode '(("cp " . font-lock-builtin-face)))
```
It successfully color those keywords but it also colors them if they are end of a word(string).
Example:
For `git clone https://github.com/SchedMD/slurm` it colors `rm` at the end:
Would it be possible to prevent this, where I just want to highlight the keyword?
Related: shell-mode `alias` keyword is not recognized as font-lock-builtin-face type
# Answer
> 2 votes
`font-lock-add-keywords` takes a list of regular expressions, not merely strings. You can use the regular expression syntax to match more complicated constructs. In particular, you can match word boundaries with `\b`. Try this instead:
```
(font-lock-add-keywords 'shell-mode '(("\\brm\\b" . font-lock-builtin-face)))
```
For more information on regular expressions, see chapter 35.3.1.3 Backslash Constructs in Regular Expressions in the Emacs Lisp manual. Don’t forget that you can open the manuals inside of Emacs using `C-h i`.
Also, just a head’s up; this function takes a list of multiple regexes. Instead of calling it four times, you can call it with one list of four things:
```
(font-lock-add-keywords 'shell-mode '(("\\balias\\b" . font-lock-builtin-face)
("\\bmv\\b" . font-lock-builtin-face)
("\\brm\\b" . font-lock-builtin-face)
("\\bcp\\b" . font-lock-builtin-face)))
```
Because it takes regular expressions, you can also use alternations to express the same thing:
```
(font-lock-add-keywords 'shell-mode '(("\\b\\(alias\\|mv\\|rm\\|cp\\|\\)\\b" . font-lock-builtin-face)))
```
Finally, there is a new syntax for regular expressions which is less traditional, but is often easier to read and maintain:
```
(font-lock-add-keywords 'shell-mode `((,(rx word-boundary
(or "alias" "mv" "rm" "cp")
word-boundary)
. font-lock-builtin-face)))
```
This is documented in chapter 34.3.3 The rx Structured Regexp Notation of the Emacs Lisp manual.
---
Tags: shell-mode, customize-face
--- |
thread-69693 | https://emacs.stackexchange.com/questions/69693 | Display define-key output in echo area | 2021-12-09T14:57:05.237 | # Question
Title: Display define-key output in echo area
This is my function,
```
(define-key global-map
(kbd "µ")
(display-message-or-buffer (message "`%s'" (eval '(solar-sunrise-sunset-string (calendar-current-date))))))
```
But, when I call it, through the `alt+m` keystroke the command literally outputs text where my cursor is, with the output.
For example, under my cursor, the text appears as so,
How can I direct this message to my `Echo Area`?
# Answer
What you are doing is defining the key to the *result of the evaluation of the expression* `(display-message-or-buffer (message "`%s'" (eval '(solar-sunrise-sunset-string (calendar-current-date)))))`. When I evaluate that expression in my `*scratch*` buffer, I get the string `"‘Sunrise 7:04am (EST), sunset 4:10pm (EST) at 42.4N, 71.2W (9:06 hrs daylight)’"`. IOW, what you did is equivalent to this:
```
(define-key global-map (kbd "µ") "‘Sunrise 7:04am (EST), sunset 4:10pm (EST) at 42.4N, 71.2W (9:06 hrs daylight)’")
```
Of course, geographical differences will give you a different string, but that is irrelevant to the main point.
If you want to define the key to run a command, you first define the function that you want to run and then you give the *function* to `define-key` \- like this:
```
(defun my/func ()
(interactive)
(display-message-or-buffer (message "`%s'" (eval '(solar-sunrise-sunset-string (calendar-current-date)))))
(define-key global-map (kbd "µ") #'my/func)
```
BTW, you don't need the `eval`: `(display-message-or-buffer (message "`%s'" (solar-sunrise-sunset-string (calendar-current-date))))` will work just as well (or better: explicit use of `eval` is generally frowned upon - see the first paragraph of the `eval` section of the Emacs Lisp manual, which you can get to with `C-h v i g(elisp)eval`).
> 2 votes
---
Tags: key-bindings, echo-area, keystrokes
--- |
thread-69683 | https://emacs.stackexchange.com/questions/69683 | Why having a system loaded makes any difference for indentation? | 2021-12-08T22:36:23.287 | # Question
Title: Why having a system loaded makes any difference for indentation?
I am using Common Lisp, SBCL, Emacs, and Slime. During a code review, a co-worker mentioned that the indentation of an s-expression was wrong.
Usually, I just use `indent-sexp`(bounded to `C-M-q`) to fix this kind of situation. In this case, I forgot to use it before code review. After his comment, I just executed the command.
This was the previous code:
```
(defun bookmark-frequent-visit (threshold)
"Check if current URL is frequently visited and not included in the
bookmarks. If this is the case, prompt the user about bookmarking it."
(labels ((bookmarked-url-p (url-address)
"The local function `bookmarked-url-p' returns the URL
address itself if it is new to the bookmark list or NIL if it is
already there."
(let ((bookmarks-address-list
(mapcar #'(lambda (e) (render-url (url e)))
(with-data-unsafe (bookmarks (bookmarks-path (current-buffer)))
bookmarks))))
(if (member url-address bookmarks-address-list :test #'string=)
nil
url-address))))
(sera:and-let* ((history-entries (with-data-unsafe (history (history-path (current-buffer)))
(mapcar #'htree:data (alex:hash-table-keys (htree:entries history)))))
(current-url-history
(find (url (current-buffer)) history-entries :test #'equalp :key #'url))
(implicit-visits-value
(nyxt::implicit-visits current-url-history))
(current-url-address
(render-url (url current-url-history)))
(threshold threshold))
(run-thread ;; identation is off here
(if (and (> implicit-visits-value threshold)
(bookmarked-url-p current-url-address))
(if-confirm ("Bookmark ~a?" current-url-address)
(bookmark-url :url current-url-address)))))))
```
This is the new code with my attempt to fix it:
```
(defun bookmark-frequent-visit (threshold)
"Check if current URL is frequently visited and not included in the
bookmarks. If this is the case, prompt the user about bookmarking it."
(labels ((bookmarked-url-p (url-address)
"The local function `bookmarked-url-p' returns the URL
address itself if it is new to the bookmark list or NIL if it is
already there."
(let ((bookmark-url-strings
(mapcar #'(lambda (e) (render-url (url e)))
(with-data-unsafe (bookmarks (bookmarks-path (current-buffer)))
bookmarks))))
(if (member url-address bookmark-url-strings :test #'string=)
nil
url-address))))
(sera:and-let* ((history-entries (with-data-unsafe (history (history-path (current-buffer)))
(mapcar #'htree:data (alex:hash-table-keys (htree:entries history)))))
(current-url-history
(find (url (current-buffer)) history-entries :test #'equalp :key #'url))
(implicit-visits-value
(nyxt::implicit-visits current-url-history))
(current-url-string
(render-url (url current-url-history)))
(threshold threshold))
(run-thread ;; attempt to fix the indentation with C-M-q
(if (and (> implicit-visits-value threshold)
(bookmarked-url-p current-url-string))
(if-confirm ("Bookmark ~a?" current-url-string)
(bookmark-url :url current-url-string)))))))
```
One thing intrigued me, though. He said: "make sure the system is loaded".
Why having the system loaded makes any difference for indentation?
# Answer
> 2 votes
SLIME examines the argument list of macros to determine how to indent them correctly. Note that the indentation for the code supplied to the `sera:and-let*` macro went from being aligned with the first argument to being indented by two spaces from the macro name.
For reference, the macro is defined here: https://github.com/ruricolist/serapeum/blob/21b683a6969236f4b02066c1ce40a27cafbba512/binding.lisp#L266
Chapter 3.14 Semantic indentation of the SLIME manual says:
> SLIME automatically discovers how to indent the macros in your Lisp system. To do this the Lisp side scans all the macros in the system and reports to Emacs all the ones with &body arguments. Emacs then indents these specially, putting the first arguments four spaces in and the “body” arguments just two spaces, as usual.
If you don’t actually have your project’s system loaded into your lisp environment, then SLIME cannot do this, and it will simply assume that everything is a function and that all the args should be lined up vertically.
---
Tags: indentation, slime, sexp, system-environment, sly
--- |
thread-69698 | https://emacs.stackexchange.com/questions/69698 | How to enable fuzzy matching in Ivy's prompt-buffer via use-package? | 2021-12-09T19:31:20.830 | # Question
Title: How to enable fuzzy matching in Ivy's prompt-buffer via use-package?
I used to use Helm and I really liked it. After watching System Crafter's YouTube series called "Emacs from Scratch", I decided to use the configuration showcased. The YouTuber prefers Ivy instead of Helm. This is the configuration for the first episode when Ivy is shown for the first time.
He does the installation and configuration via `use-package`. This is my almost identical use of the same approach:
```
;; Using Ivy from System Crafters
(use-package ivy
:diminish ;keeps ivy out of the mode line
:bind (("C-s" . swiper)
:map ivy-minibuffer-map
;("TAB" . ivy-alt-done)
("C-l" . ivy-alt-done)
("C-j" . ivy-next-line)
("C-k" . ivy-previous-line)
:map ivy-switch-buffer-map
("C-k" . ivy-previous-line)
("C-l" . ivy-done)
("C-d" . ivy-switch-buffer-kill)
:map ivy-reverse-i-search-map
("C-k" . ivy-previous-line)
("C-d" . ivy-reverse-i-search-kill))
:config
(ivy-mode 1))
```
I miss two things from Helm: (1) Helm fuzzy matching, and (2) Helm's prompt-buffer listing the last used command at the top of the prompt-buffer.
Since Ivy is configurable, I have been trying to fulfill my desires. Some answers in Stack Exchange pointed to using:
```
(setq ivy-re-builders-alist
'((swiper . ivy--regex-plus)
(t . ivy--regex-fuzzy)))
```
Thus, I tried tweaking the ivy configuration to be:
```
;; Using Ivy from System Crafters
(use-package ivy
:diminish ;keeps ivy out of the mode line
:bind (("C-s" . swiper)
:map ivy-minibuffer-map
;("TAB" . ivy-alt-done)
("C-l" . ivy-alt-done)
("C-j" . ivy-next-line)
("C-k" . ivy-previous-line)
:map ivy-switch-buffer-map
("C-k" . ivy-previous-line)
("C-l" . ivy-done)
("C-d" . ivy-switch-buffer-kill)
:map ivy-reverse-i-search-map
("C-k" . ivy-previous-line)
("C-d" . ivy-reverse-i-search-kill))
:config
'((ivy-mode 1)
(t . ivy--regex-fuzzy)))
```
But, it did not work out to solve problem (1). At the same time, I tried installing `ivy-prescient` to have the last used command listed first and solve problem (2). It seems to work, not sure if this is the best approach, though:
```
;; Make the last used command be the first-one
(use-package ivy-prescient
:init
(ivy-prescient-mode 1))
```
# Answer
> 0 votes
This solved the fuzzy match problem (not sure if this is the best way):
```
(use-package ivy
:diminish ;keeps ivy out of the mode line
:bind (("C-s" . swiper)
:map ivy-minibuffer-map
;("TAB" . ivy-alt-done)
("C-l" . ivy-alt-done)
("C-j" . ivy-next-line)
("C-k" . ivy-previous-line)
:map ivy-switch-buffer-map
("C-k" . ivy-previous-line)
("C-l" . ivy-done)
("C-d" . ivy-switch-buffer-kill)
:map ivy-reverse-i-search-map
("C-k" . ivy-previous-line)
("C-d" . ivy-reverse-i-search-kill))
:config
'((ivy-mode 1)
(ivy--regex-fuzzy 1)))
```
I am still not sure if this is the best approach for `ivy-prescient`. But it seems to do the trick:
```
;; Make the last used command be the first-one
(use-package ivy-prescient
:init
(ivy-prescient-mode 1))
```
---
Tags: use-package, ivy, fuzzy-search, fuzzy-matching
--- |
thread-69696 | https://emacs.stackexchange.com/questions/69696 | How to create independent Dired buffers for the same directory? | 2021-12-09T15:49:04.913 | # Question
Title: How to create independent Dired buffers for the same directory?
I'm trying to programmatically define the windows in my frame. I have 4 windows, two with dired buffers in them so that I can select the file I want to visit.
```
(delete-other-windows)
(split-window-horizontally)
(dired ".")
(split-window-vertically)
(find-file "test.txt")
(other-window -1)
(split-window-vertically)
(dired ".")
(other-window -1)
```
```
+-----------+-----------+
| | |
| | |
| test.txt | dired |
| | |
| | |
+-----------+-----------+
| | |
| dired | whatever |
| | |
| | |
+-----------+-----------+
```
To open a file in the current dired buffer, I set `(put 'dired-find-alternate-file 'disabled nil)` to disable the warning and select the file I want with `a` (`dired-find-alternate-file`). When I do this, however, it kills the other dired buffer I have open. It seems that dired can only have one buffer per directory.
How can I have two dired buffers for the same directory, but kill each of them independently?
**edit**
Using indirect buffers, I can get what I want, but it ain't pretty. Good gravy, is there a better way?
```
(defun my-clone-indirect-buffer-same-window (newname display-flag &optional norecord)
"A copy-paste of clone-indirect-buffer, but with pop-to-buffer
changed to pop-to-buffer-same-window."
(interactive
(progn
(if (get major-mode 'no-clone-indirect)
(error "Cannot indirectly clone a buffer in %s mode" mode-name))
(list (if current-prefix-arg
(read-buffer "Name of indirect buffer: " (current-buffer)))
t)))
(if (get major-mode 'no-clone-indirect)
(error "Cannot indirectly clone a buffer in %s mode" mode-name))
(setq newname (or newname (buffer-name)))
(if (string-match "<[0-9]+>\\'" newname)
(setq newname (substring newname 0 (match-beginning 0))))
(let* ((name (generate-new-buffer-name newname))
(buffer (make-indirect-buffer (current-buffer) name t)))
(with-current-buffer buffer
(run-hooks 'clone-indirect-buffer-hook))
(when display-flag
(pop-to-buffer-same-window buffer norecord))
buffer))
(delete-other-windows)
(split-window-horizontally)
(dired ".")
(split-window-vertically)
(find-file "test.txt")
(other-window -1)
(split-window-vertically)
(switch-to-buffer (cdr (car dired-buffers)))
(my-clone-indirect-buffer-same-window nil t)
(other-window -1)
```
**edit2**
Based on Drew's answer, the following does what I asked:
```
(setq my-root ".")
(setq my-main "test.txt")
(delete-other-windows)
(split-window-horizontally)
(dired my-root)
(split-window-vertically)
(find-file my-main)
(other-window -1)
(split-window-vertically)
;; creates a new buffer with same name as my-root containing
;; a snapshot of the file listing
(dired (cons my-root (directory-files my-root)))
(other-window -1)
```
# Answer
> 1 votes
You **can** create additional buffers that Dired the same directory, but with this *caveat*: those additional buffers are in fact Dired listings of a *particular set of files* (and subdirs etc.), which you *specify when you create the buffers*.
So changing the set of files in the directory does not change the set of files listed in the Dired listing of such an additional buffer for that directory.
To create such a Dired buffer `other-DIR`, given that you already have a Dired buffer named `DIR` (where `DIR` is the directory name), do this:
```
M-: (dired (cons "other-DIR" (directory-files "DIR")))
```
This gives you a *separate Dired buffer*, but its set of files is defined when you create the buffer. You can of course also specify particular `ls` switches etc.
With this technique you can create Dired buffers listing *any* set of files and subdirs - they need not even be in the same directory tree. In this particular case (above), the arbitrary set of files happen to be the files in the given directory (obtained with `directory-files`) at the time the buffer is created.
See the doc of command `dired` for more info.
---
Library Dired+ offers more flexibility for using such Dired buffers that list an arbitrary set of files.
---
Tags: buffers, dired
--- |
thread-69678 | https://emacs.stackexchange.com/questions/69678 | Is there a command to wrap a characters in a word using Emacs? Or something to insert "/" around a word while using org-mode? | 2021-12-08T20:06:19.497 | # Question
Title: Is there a command to wrap a characters in a word using Emacs? Or something to insert "/" around a word while using org-mode?
In `org-mode`, writing a word wrapped by `/` makes it italic. For instance, `/word/` becomes *word*.
Is there a command in Emacs to make something go from `ẁord` to `/word/`? Maybe some org related command only to do this?
# Answer
> 5 votes
As usual, Org has you covered: `org-emphasize`, bound by default to `C-c C-x C-f`.
This will work for all emphasis markers. So, for italics, select the word and `C-c C-x C-f /`.
# Answer
> 1 votes
When `electric-pair-mode` is on, the following syntax rule suffices:
```
(modify-syntax-entry ?/ "(/")
```
Notice that such rules should be added to `org-mode` only.
# Answer
> 1 votes
The wrap-region package does this. You can install it from MELPA.
Once you have it installed, you can add wrappers for org:
```
(wrap-region-add-wrappers
'(("*" "*" nil org-mode)
("/" "/" nil org-mode)
("~" "~" nil org-mode)
("+" "+" nil org-mode)))
```
You turn it on with `M-x wrap-region-mode`, or `M-x wrap-region-global-mode` if you want it for every buffer. Once it's on, if you select a word (or sentence or ...) and press one of the 'wrapper' keys, the characters will be added to the beginning and end of the active region. See the link above for details about customization for different modes.
---
Tags: org-mode, wrapping, words
--- |
thread-69702 | https://emacs.stackexchange.com/questions/69702 | Flyspell and Ispell find different incorrect words | 2021-12-09T21:49:17.620 | # Question
Title: Flyspell and Ispell find different incorrect words
There are words that are considered to be wrong by Flyspell that are instead considered correct by Ispell. I thought that Flyspell was merely an *async* version of Ispell, I must be wrong...
To add to the confusion, there cases in which `ispell-buffer` finds nothing, but `ispell-word` instead considers some words in the buffer to be wrong, coherently to what Flyspell has to say.
Here's an example:
```
$ echo http://example.com >/tmp/test
$ emacs -Q /tmp/test
```
Then execute `M-x flyspell-buffer`. The word `http` is now marked as wrong, in fact, `ispell-word` shows the usual interactive menu. Yet, `M-x ispell-buffer` completes without finding any wrong words.
Can you help me understanding what's going on here?
# Answer
Flyspell tries to respect Ispell as much as possible (e.g., `ispell-program-name` and `ispell-dictionary`), but does not use the functionalities exposed by Ispell to do the spell checking.
`ispell-buffer` uses `ispell-begin-skip-region-regexp` to skip over some parts of the buffer; this is what causes it to skip over `http`.
If you create a buffer called `*Ispell Debug*` and then enable debugging by evaluating `(defvar ispell-debug-buffer "*Ispell Debug*")`, you will see `ispell-buffer` print something along the lines of
```
ispell-region: Search for first region to skip after (ispell-begin-skip-region-regexp)
ispell-region: First skip: http://example.com at (pos,line,column): (1,1,0).
```
in `*Ispell Debug*`. `ispell-word` does not do any of this skipping.
> 2 votes
---
Tags: flyspell, ispell
--- |
thread-69505 | https://emacs.stackexchange.com/questions/69505 | How to debug error in process sentinel? | 2021-11-26T11:06:13.127 | # Question
Title: How to debug error in process sentinel?
I've recently switched to `doom` emacs, and for the most part it's working great.
However, when I'm looking at a folder in `dired-mode`, if I copy a file using `C` the file is copied but `*Messages*` contains the following:
```
error in process sentinel: vc-exec-after: Unexpected process state
error in process sentinel: Unexpected process state No library
simple.el in search path
```
More significant is that it leaves a `.git/index.lock` which I need to manually delete.
I have the following questions:
1. How can this issue be investigated?
2. How can this specific issue be fixed?
3. How can the 'vc' aspect of dired be disabled?
The last point is because I would like to use `magit` exclusively.
# Answer
> 1 votes
With regard to 1., I'm not sure about Doom Emacs, but on GNU Emacs you could navigate to lisp/vc/vc-dispatcher.el, move pointer to `(defun vc-exec-after (code) ...` and invoke `C-u C-M-x` to invoke `eval-defun`. Move cursor to first line, add a breakpoint `edebug-set-breakpoint`, and run the code/command again to use Edebug to step through the code.
Also, maybe you can get a hint from invoking `toggle-debug-on-error`. It should show a minibuffer with error and stack trace when errors occur anywhere in the elisp code paths.
# Answer
> 0 votes
With regard to 3, there is a variable that specifies a list of backends to ignore:
> Documentation
>
> VC backends to ignore.
>
> The directories registered to one of these backends won't have status indicators.
Adding the following in `.doom.d/config.el` adds `Git` to the list of ignored backends:
```
(after! dired
(setq diff-hl-dired-ignored-backends (append
'((Git) (RCS)))))
```
---
Tags: magit, dired, debugging, doom
--- |
thread-60431 | https://emacs.stackexchange.com/questions/60431 | Quick temporary colour change | 2020-09-01T17:00:37.247 | # Question
Title: Quick temporary colour change
I'm using a dark theme to write Clojure, with rainbow parentheses etc.
I like this theme and its syntax colouring, and I don't want to change it or mess it up.
BUT ... I'm currently sitting outside in a place with lots of sunlight and I can't read the screen.
What I'd like to be able to do is quickly, and *temporarily* (just in this session) invert the main colours : switch to a white background and black text (the other syntax colours I'm happy to keep the same)
Is there a way to do this?
# Answer
Answering the question in your title, if you don't like the colors of a particular part of the text, you put the cursor there, press `C-u C-x =`, and find the face name:
Knowing the face name you can change the foreground (`M-x set-face-foreground`), the background (`M-x set-face-background`) or any other attribute (`set-face-attribute`):
```
(set-face-attribute 'package-name nil :weight 'bold)
```
Replace `package-name` with the desired face name. `nil` means "for existing and newly created frames."
About foreground and background of the current frame, use `M-x set-foreground-color`, and `M-x set-background-color`.
To display the list of colors use `M-x list-colors-display`.
You can execute non-interactive functions (like `set-face-attribute`) via `M-:`, in a scratch buffer (`C-x C-e`), or put them into `~/.emacs`.
The same applies to interactive functions (like `set-face-foreground`, `set-face-background`, `set-foreground-color`, `set-background-color`). But they can also be executed via `M-x`.
> 1 votes
---
Tags: colors, coloring
--- |
thread-51766 | https://emacs.stackexchange.com/questions/51766 | How to preserve linebreaks of MS-Word text pasted into an Emacs buffer | 2019-07-22T11:52:28.807 | # Question
Title: How to preserve linebreaks of MS-Word text pasted into an Emacs buffer
This is similar to There's a way to use emacs like MS Word, to make text permanently colored, stylized, etc...? However, I do only wish to preserve linebreaks so that the pasted raw text from word looks somewhat readable and not just one long line. Are there any utilities in Emacs to achieve this?
# Answer
The linebreaks in a paragraph of a word document are usually not hard.
Therefore, in the text that you copy and paste from Word there are no linebreaks to be kept.
You can use Visual line mode (Menu item `Options -> Line Wrapping in This Buffer -> Word Wrap (Visual Line Mode)`) to get a similar filling of paragraphs in Emacs.
I suggest to use it in combination with `adaptive-wrap`. That mode can be installed from elpa with `install-package`.
Visual line mode adapts the line filling to the window-width. Thereby you can adjust the width of the text with the mouse by resizing Emacs or the window border.
If you want to keep the line ends found by Visual line mode for copying and pasting you can use the following command `make-visual-lines-hard`.
```
(require 'adaptive-wrap)
(defun make-visual-lines-hard (&optional beg end)
"Insert ?\\n at each visual line end which is not a hard line end."
(interactive)
(when (and (called-interactively-p 'any)
(region-active-p))
(setq beg (region-beginning)
end (set-marker (make-marker) (region-end))))
(save-excursion
(goto-char (or beg (point-min)))
(unless end (setq end (set-marker (make-marker) (point-max))))
(while (progn
(end-of-visual-line)
(< (point) end))
(if (looking-at "\n")
(forward-line)
(insert "\n" (adaptive-wrap-fill-context-prefix (line-beginning-position) (line-end-position)))
(looking-at "[[:space:]]*")
(replace-match "")
))))
```
Install `adaptive-wrap`, copy the above Elisp code to your init file and restart Emacs.
Afterwards you can use `make-visual-lines-hard`.
> 1 votes
# Answer
Save as plain text from word. Dialog box appears and you select “Line breaks” as one of the options!
> 0 votes
---
Tags: formatting, ms-word
--- |
thread-69708 | https://emacs.stackexchange.com/questions/69708 | How can I live-preview org-mode for readme files? | 2021-12-10T10:37:20.253 | # Question
Title: How can I live-preview org-mode for readme files?
I am using `org-mode` to format readme files. When I commit a `README.org` file into `github.com`, I am able to see its formatted preview. But since I make a lot of changes, I have to keep commit to see its final preview.
=\> `Markdown` has some editors where, while you are making change into `markdown file` you can see its final preview in real-time; example: (https://github.com/MacDownApp/macdown).
Is there any live-preview approach for `org-mode` as well? Could it be done within `emacs`?
Only approach I was able to come up is use https://github.com/GeneKao/orgmode-latex-templates to convert it into `pdf` for preview after each save.
# Answer
> 1 votes
You can try exporting `README.org` as html and view it in a browser.
Simplest is `C-c C-e h h` (bound to `org-html-export-to-html`) which produces a basic html file. If you need more than this for testing, you could tweak templates and css as described in the manual, and there are various other packages for changing the output on melpa (e.g. ox-twbs).
For a live preview, there is org-preview-html which should be able to preview the generated html in emacs (but I've not tested it)
---
Tags: org-mode, previewing
--- |
thread-35744 | https://emacs.stackexchange.com/questions/35744 | can't load python tags table | 2017-09-25T21:20:23.770 | # Question
Title: can't load python tags table
generating python tags with
```
for file in $(find -type f -regex ".+\\.\(py\)"); do etags -a $file; done
```
doesn't load at emacs with error
> path/TAGS is not a valid tags file
although other language i.e c works just fine, and syntax of generated TAGS doesn't look odd!
# Answer
> 0 votes
the problem was with emacs configuration, it worked after re-installation.
with general regex
```
cd $1
rm -rf TAGS
for file in $(find $1 -type f -regex ".+\\.c?h?S?\(cpp\)?\(cxx\)?\(cc\)?\(hpp\)?\(hxx\)?\(hh\)?\(rb\)?\(go\)?\(js\)?\(py\)?\(java\)?" ); do
echo "adding $file"
etags -a $file
done
```
# Answer
> 1 votes
You can generate the TAG file like this:
`find . -name "*.py" | xargs etags -a`
Then in .emacs file:
`(setq tags-table-list (list "/path/to/TAG/file/dir/"))`
# Answer
> 0 votes
It may depend on which application is being used to generate the tags. Most, I belief, support an option specifically for use with Emacs. For Universal Ctags, there is the `-e` flag:
```
-e Output tag file for use with Emacs.
```
To generate,
```
# -R to recurse, -e for Emacs
ctags -Re .
```
Load the result into Emacs with `M-x visit-tags-table`.
---
Tags: python, ctags, tags
--- |
thread-69706 | https://emacs.stackexchange.com/questions/69706 | How to open a file (from an org link) within current window? | 2021-12-10T09:34:13.160 | # Question
Title: How to open a file (from an org link) within current window?
When I do `C-c C-o` on an org link it opens the org file in a new window. This is fine, but sometimes I'd prefer to open org files within the current window, creating a new key binding for the matter (for example `"C-c <C-return>"`).
I've tried to adapt some code I found on emacs.stackexchange, namely :
*How to force Org-mode to open a link in another frame?*
```
(defun zin/org-open-other-frame ()
"Jump to bookmark in another frame. See `bookmark-jump' for more."
(interactive)
(let ((org-link-frame-setup (acons 'file 'find-file-other-frame org-link-frame-setup)))
(org-open-at-point)))
```
and *Open org link in the same window*
```
(setf (cdr (assoc 'file org-link-frame-setup)) 'find-file)
```
But my understanding of Elisp is so poor that I didn't manage to do it...
# Answer
Adding this to your init will allow you to open a link in the current window through `C-o`:
```
(defun mda/org-open-current-window ()
"Opens file in current window."
(interactive)
(let ((org-link-frame-setup (cons (cons 'file 'find-file) org-link-frame-setup)))
(org-open-at-point)))
(define-key global-map (kbd "C-o") #'mda/org-open-current-window)
```
> 1 votes
---
Tags: org-mode, org-link
--- |
thread-69719 | https://emacs.stackexchange.com/questions/69719 | "fingerprint has changed" message when attempting to connect to smtp.gmail.com | 2021-12-11T02:16:56.847 | # Question
Title: "fingerprint has changed" message when attempting to connect to smtp.gmail.com
For the last two days, whenever I try to send an email, Emacs displays the following message:
```
The TLS connection to smtp.gmail.com:587 is insecure for the following reason:
* fingerprint has changed
```
I was unable to diagnose the problem after reading the relevant section of the manual or searching for answers online. My knowledge of network security is minimal, so I apologize if the solution is obvious.
# Answer
Every secure connection is protected by encryption that relies on a pair of keys called the public key and the private key. The server that you are talking to sends its public key to your computer at the start of the connection so that your computer can use it during the encryption. The server decrypts everything using its private key, which is why the private key must remain private.
Additionally, every key pair is signed by a Certificate Authority. The server presents the certificate along with the public key, and your computer verifies the signature. It also verifies that the signature comes from a source that it trusts. The list of trusted sources is something that you can control, but most people just use the default list provided by their operating system or web browser. It is also possible for your employer to tamper with the list of trusted sources.
In your case, the error indicates that the signature is valid and from a trusted source, but that the public key is not the same as the public key that Emacs expected to see. Three days ago when Emacs connected to the server the key was A, but today it is B. A and B are different, so Emacs is concerned. Because keys are rather large, we humans usually only compare fingerprints, which are just fixed–length hashes of the keys.
This is a sign that your connection to the server might have been hijacked by a malicious party. But at the same time, it could just be that the owner of the server has recently started using a new key pair. The signatures on the certificates do expire, and it is not uncommon to install a completely new key pair at the same time you install a new certificate.
Emacs is asking you to decide whether it is really safe to connect to the server or not. Emacs stores key fingerprints in `~/.emacs.d/network-security.data` by default, though you can change that by modifying the `nsm-settings-file` variable.
It is up to you to decide if it is safe to proceed or not, but I will point out that merely hijacking the connection usually results in a failure to verify the certificate. To avoid this, the hijacker would need to convince a Certificate Authority to issue a valid certificate for a domain that the hijacker does not control, and any Certificate Authority that was caught doing this would be removed as a trusted source and would go out of business. It has happened before though, so it’s certainly not impossible. Because the certificate is both valid and signed by a trusted source, a hijacked connection seems unlikely.
However, recall that your employer could have modified the list of trusted sources. Some companies use “security” products that hijack all secure connections in order to scan them for threats, and to avoid the attention of their employees they add themselves to the list of trusted certificate sources. In principle, anyone with access to your computer, or any software that you have run on it, could have modified the list of trusted certificates.
If you decide that it is safe, then you can remove the fingerprint for that server from the `nsm-settings-file` and Emacs will save the new fingerprint in its place.
> 3 votes
---
Tags: email
--- |
thread-63722 | https://emacs.stackexchange.com/questions/63722 | How to use doom emacs as a golang ide quickly? | 2021-03-04T01:09:51.723 | # Question
Title: How to use doom emacs as a golang ide quickly?
I installed the newest doom emacs on macOS. Also configed language packages as
```
$ emacs ~/.doom.d/init.el
:lang
(go +lsp)
:tools
lsp
$ ~/.emacs.d/bin/doom sync
```
When I open a .go file, the code became highlight. But after save the file, the code can't been formated automatically. I have installed `gofmt` and `goimports`. How to set emacs to use them?
I read this document: lang/go module. It seems it can do it: `Auto-formatting on save (gofmt)`. Maybe because of environment path? So how to call system path from emacs? My `GOPATH` is `~/go`, it set in `~/.zshrc`. When I open `shell` via `M+x`, something is different from terminal. How to import `.zshrc` configuration completely?
# Answer
> 0 votes
In your doom init.el file you need to enable format +onsave in the :editor section. See the snippet below or look at the example init.el (with format +onsave disabled) on the doom emacs git repo
>
```
:editor
(evil +everywhere); come to the dark side, we have cookies
file-templates ; auto-snippets for empty files
fold ; (nigh) universal code folding
(format +onsave) ; automated prettiness
;;god ; run Emacs commands without modifier keys
;;lispy ; vim for lisp, for people who don't like vim
;;multiple-cursors ; editing in many places at once
;;objed ; text object editing for the innocent
;;parinfer ; turn lisp into python, sort of
;;rotate-text ; cycle region at point between text candidates
snippets ; my elves. They type so I don't have to
;;word-wrap ; soft wrapping with language-aware indent
```
# Answer
> 0 votes
```
$ emacs ~/.doom.d/init.el
:editor
(evil +everywhere)
(format +onsave)
:lang
(go +lsp)
:tools
lsp
$ ~/.emacs.d/bin/doom sync
```
Keys:
* use `SPC p s` to format and save all project's buffers
* use `SPC c o` to auto-remove from Go `import ()` (or auto-add, but it mostly happens as you edit text)
* use `SPC m i z z` to jump to the Go `imports ()` block
* use `C-o` to jump back (I'm not sure how this works so far)
There is no integration between `import ()` and the `go mod`. For example adding a new package, does not add the corresponding module.
---
Tags: shell, doom, environment, path, golang
--- |
thread-51517 | https://emacs.stackexchange.com/questions/51517 | is it possible to have a "calc embedded" indicator in doom-modeline? | 2019-07-09T20:46:25.490 | # Question
Title: is it possible to have a "calc embedded" indicator in doom-modeline?
this is indispensable, since I use "calc embedded" in auctex and need to leave this mode after have activate it.
# Answer
Sorry, I hadn't read the documentation carefully enough. Actually, there was an icon to indicate calc-embedded mode, but in the form of an inaudible Unicode character. I installed the all-the-icons font from `M-x all-the-icons-install-fonts` and since then I have an icon indicating that I am in calc-embedded mode.
> 0 votes
---
Tags: mode-line, calc
--- |
thread-35959 | https://emacs.stackexchange.com/questions/35959 | Emacs Blue color too dark | 2017-10-06T07:59:31.473 | # Question
Title: Emacs Blue color too dark
Emacs blue (on dark background) is too dark. `classA` is readable with difficulty in the example below:
How to fix the dark blue colour?
# Answer
> 20 votes
Add `frame-background-mode` to your init file:
```
(setq frame-background-mode 'dark)
```
# Answer
> 19 votes
Put the cursor on the blue word, and say `C-u C-x =`. Find the `face` entry and click on its value. Then click on `customize this face` and change the foreground value to e.g. `Cyan1`.
If you are in a console or are doing `emacs -nw` in a terminal, instead of clicking, put the cursor on the appropriate element and press `RET`.
# Answer
> 11 votes
Faces in Emacs can have different values, depending on display attributes such as the number of colors supported or whether they're displayed on a light/dark background. Emacs can guess the latter without any issues in graphical mode, for textual frames however the guessing isn't nearly as good. If it turns out to be wrong, you'll get dark blue on black (because it mistakenly assums a light background on which there would be enough contrast to the dark blue), like in the screenshot above.
To check whether that's the case for you, inspect the value of `frame-background-mode` and customize it if needed.
# Answer
> 5 votes
NickD has a good answer but doesn't update your menu bar which may also have the same dark blue (can you see what it says when you type `ctrl + s`?). This method will also fix hard to read menus.
1. Run emacs
2. Type `alt + x customize-themes`
3. Arrow down to **manoj-dark** and hit return (or pick a different theme)
4. Type `ctrl + x, ctrl + s` to save the settings
5. Type `ctrl + x, ctrl + c` to quit
This theme is saved to your `.emacs` file and will be used when you use emacs in the future. Here are more exhaustive instructions.
# Answer
> 0 votes
To change the colors of a part of a text, you put the cursor there, press `C-u C-x =`, and find the face name:
Knowing the face name you can change the foreground (`M-x set-face-foreground`), or the background (`M-x set-face-background`). There's also (`set-face-attribute`):
```
(set-face-attribute 'package-name nil :foreground "cyan1")
```
Replace `package-name` with the desired face name. `nil` means "for existing and newly created frames."
To display the list of colors use `M-x list-colors-display`.
You can execute non-interactive functions (like `set-face-attribute`) via `M-:`, in a scratch buffer (`C-x C-e`), or put them into `~/.emacs`.
The same applies to interactive functions (like `set-face-foreground`, `set-face-background`). But they can also be executed via `M-x`.
---
Tags: faces, colors
--- |
thread-69727 | https://emacs.stackexchange.com/questions/69727 | How to delete inserted directory names for `find-file` input? | 2021-12-11T22:05:38.370 | # Question
Title: How to delete inserted directory names for `find-file` input?
I've been trying to figure out how to erase directories faster when I use `find-file` in vanilla Emacs. An example is Doom Emacs, you press backspace once, and erase the entire directory, but when I try to do the same thing on vanilla Emacs, I need to erase the entire directory name. How I can modify this behavior to make my Emacs file navigation faster?
# Answer
Does `C-x DEL` (`C-x <backspace>`) do what you want? That's bound by default to `backward-kill-sentence`, which generally deletes all or most of what's already in the minibuffer before point.
You can of course bind that command to another key. And you can do that in a minibuffer keymap, if you don't want to do it globally. Globally `DEL` (`<backspace>`) is bound by default to `backward-delete-char-untabify`.
> 0 votes
---
Tags: minibuffer, find-file, deletion
--- |
thread-69729 | https://emacs.stackexchange.com/questions/69729 | How to add a new keyboard layout to Emacs input methods? | 2021-12-12T09:03:26.163 | # Question
Title: How to add a new keyboard layout to Emacs input methods?
I've downloaded a new layout from https://qwerty-lafayette.org/ which I would like to use. However I am struggling to understand how I can use it inside Emacs. Usually I set languages by using `(set-input-method "language")`. However here I can't select the language, how can I do this for this particular language?
# Answer
> 2 votes
AFAIK there's not much documentation for the quail / leim stuff in Emacs; but once you know where to look, you can generally muddle your way through based on existing cases (there are so many of them, that there's generally likely to be something similar to use as a basis).
See `M-x` `find-library` `RET` `leim-list` for all of the `register-input-method` calls. To pick an example with a keyboard layout:
```
(register-input-method
"english-dvorak" "English" 'quail-use-package
"DV@" "English (ASCII) input method simulating Dvorak keyboard"
"quail/latin-post")
```
The following is then a verbatim quote of the `english-dvorak` input method and keyboard layout from that `quail/latin-post` library. I believe that the call to `quail-define-rules` is automatically using the most-recent `quail-define-package` declaration, so this is pretty much all there is.
Note that you can visit that library with `M-x` `find-library` `RET` `quail/latin-post` (type it verbatim; completion won't complete it), and of course the many other files in the same directory provide other different examples.
Checking your link, I guess the better examples to look at are the `french-keyboard` and `french-azerty` input methods (which are also in `latin-post.el`). Once you have this working, perhaps you could contribute it upstream alongside those?
```
(require 'quail)
(quail-define-package
"english-dvorak" "English" "DV@" t
"English (ASCII) input method simulating Dvorak keyboard"
nil t t t t nil nil nil nil nil t)
;; 1! 2@ 3# 4$ 5% 6^ 7& 8* 9( 0) [{ ]} `~
;; '" ,< .> pP yY fF gG cC rR lL /? =+
;; aA oO eE uU iI dD hH tT nN sS -_ \|
;; ;: qQ jJ kK xX bB mM wW vV zZ
(quail-define-rules
("-" ?\[)
("=" ?\])
("`" ?`)
("q" ?')
("w" ?,)
("e" ?.)
("r" ?p)
("t" ?y)
("y" ?f)
("u" ?g)
("i" ?c)
("o" ?r)
("p" ?l)
("[" ?/)
("]" ?=)
("a" ?a)
("s" ?o)
("d" ?e)
("f" ?u)
("g" ?i)
("h" ?d)
("j" ?h)
("k" ?t)
("l" ?n)
(";" ?s)
("'" ?-)
("\\" ?\\)
("z" ?\;)
("x" ?q)
("c" ?j)
("v" ?k)
("b" ?x)
("n" ?b)
("m" ?m)
("," ?w)
("." ?v)
("/" ?z)
("_" ?{)
("+" ?})
("~" ?~)
("Q" ?\")
("W" ?<)
("E" ?>)
("R" ?P)
("T" ?Y)
("Y" ?F)
("U" ?G)
("I" ?C)
("O" ?R)
("P" ?L)
("{" ??)
("}" ?+)
("A" ?A)
("S" ?O)
("D" ?E)
("F" ?U)
("G" ?I)
("H" ?D)
("J" ?H)
("K" ?T)
("L" ?N)
(":" ?S)
("\"" ?_)
("|" ?|)
("Z" ?:)
("X" ?Q)
("C" ?J)
("V" ?K)
("B" ?X)
("N" ?B)
("M" ?M)
("<" ?W)
(">" ?V)
("?" ?Z)
)
```
---
For a minimal example of a layout which switches the "f" and "o" characters, you could put this in your init file:
```
(add-to-list 'load-path (expand-file-name "~/.emacs.d/lisp"))
(register-input-method
"foo" "French" 'quail-use-package
"FOO@" "Example input method"
"foo-input-method")
```
And create a file `~/.emacs.d/lisp/foo-input-method.el` containing:
```
(require 'quail)
(quail-define-package
"foo" "Foo" "Foo" t
"Example input method"
nil t t t t nil nil nil nil nil t)
(quail-define-rules
("F" ?O)
("f" ?o)
("O" ?F)
("o" ?f)
)
(provide 'foo-input-method)
```
---
Tags: input-method
--- |
thread-69720 | https://emacs.stackexchange.com/questions/69720 | TAB should indent at start of line and advance to tab stop otherwise | 2021-12-11T02:45:32.663 | # Question
Title: TAB should indent at start of line and advance to tab stop otherwise
More precisely, I would like `TAB` to indent the current line when there are 0 or more whitespace characters between the start of line and the point and to advance to the next tab stop otherwise. I used to have this behavior 1 or 2 major versions ago, but I lost it in an upgrade (I'm currently using 27.2).
I tried customizing `tab-always-indent` to `nil` as defined in indent.el, but I think the programming mode is overriding this behavior (I primarily deal in curly-brace languages).
I use this behavior to create "columns" in my source. i.e.
```
private int able;
private boolean baker;
public int getAble() { return able; }
public boolean getBaker() { return baker; }
```
Turns out I needed to pay closer attention to the description when customizing tab-always-indent and customize c-tab-always-indent as:
> Some programming language modes have their own variable to control this, e.g., 'c-tab-always-indent', and do not respect this variable.
# Answer
A more careful reading of the customize description for `tab-always-indent` points to **`c-tab-always-indent`** as controlling this behavior for the c programing family (c, c++, java, probably c#).
> Controls the operation of the TAB key. If t, hitting TAB always just indents the current line. If nil, hitting TAB indents the current line if point is at the left margin or in the line’s indentation, otherwise it inserts a "real" TAB character. If ‘complete’, TAB first tries to indent the current line, and if the line was already indented, then try to complete the thing at point.
>
> Some programming language modes have their own variable to control this, e.g., ‘c-tab-always-indent’, and do not respect this variable.
> 0 votes
---
Tags: indentation, align
--- |
thread-69712 | https://emacs.stackexchange.com/questions/69712 | Stopping repeated tasks forever | 2021-12-10T12:37:23.303 | # Question
Title: Stopping repeated tasks forever
Simple question: how to stop repeated tasks in Org (Emacs)? A related subquestion would be how to set a repeated task for a period of time. Let's say I want to do a certain task from January to March only, so I know when I am doing the last repetition.
Example:
```
** TODO TASK
SCHEDULED: <2021-12-11 Sat .+1d>
:PROPERTIES:
:STYLE: habit
:LAST_REPEAT: [2021-12-10 Fri 14:30]
:END:
:LOGBOOK:
- State "DONE" from "TODO" [2021-12-10 Fri 14:30]
- State "DONE" from "TODO" [2021-12-09 Thu 00:16]
- State "DONE" from "TODO" [2021-12-07 Tue 18:20]
[etc.]
:END:
```
Is this possible at all?
# Answer
To mark a repeated task in Org as definitely done (cancelling the repeater), call `org-todo` with a -1 argument: `C-- 1 C-c C-t`, then mark it done.
And, no, it is not possible to set an end to a repeated task in Org. But you can easily make multiple copies of it with shifted schedules with `org-clone-subtree-with-time-shift`, bound by default to `C-c C-x c`.
> 2 votes
---
Tags: org-mode
--- |
thread-69735 | https://emacs.stackexchange.com/questions/69735 | Abstract block for HTML export? | 2021-12-12T18:22:24.267 | # Question
Title: Abstract block for HTML export?
I see the abstract block
```
#+begin_abstract
Hello, here's my article's abstract...
#+end_abstract
```
and it exports nicely into LaTeX with a nice title heading "Abstract" above it, i.e., LaTeX export knows what to do with it. But with an HTML export it just throws the text and no title. How could I alter things to have a LaTeX-like export with my HTML export? In general, I could use a nice How To Hack the HTML Export tutorial, all the essentials, main points, first principles...
# Answer
LaTeX export has the handy feature that if you give it a special block (like `#+begin_abstract ... #+end_abstract`), it will blindly turn it into a LaTeX environment (`\begin{abstract}...\end{abstract}` in this case) and let *LaTeX* do what it will with it. Since LaTeX knows how to deal with the `abstract` environment, everything works out well. If you gave it a different special block (e.g. `foo`), it would still be turned into a `foo` environment and LaTeX would barf since the environment `foo` is not defined. But you could define it in a package, and make sure that the package is loaded, thereby teaching LaTeX how to deal with it. See `org-latex-latex-special-block` for the code.
HTML is much less structured: the same special block is turned into a `<div class="abstract"><p>...</p></div>` but, in contrast to LaTeX, HTML doesn't know anything about an `abstract` class, so it just renders the text (but note that it does not barf, as LaTeX does with an unknown environment). Now, "teaching" HTML about the `abstract` class is merely a matter of including some CSS that tells HTML how to style the class and some way to include the title for the abstract, simulating what LaTeX does.
E.g. for CSS styling, try something like this:
```
#+TITLE: Nice title, isn't it?
#+AUTHOR: A.U.Thor
#+HTML_HEAD_EXTRA: <style> div.abstract { margin: auto; width: 80%; text-align: justify; color: red; } </style>
#+begin_abstract
Lorem ipsum dolor sit amet, ... sunt in culpa qui officia deserunt mollit anim id est laborum.
#+end_abstract
```
That will certainly distinguish the abstract from the rest of the text! A bit garish for my taste though, although getting rid of the color is easy.
As a debugging hint for the above and also for what follows, I highly recommend that you create an Org mode file as above, export it to HTML, look in the HTML file to see what is produced (you only need to worry about the added `<style>` and the abstract) and also check the file in a browser. It's easy to iterate with a setup like this: make a change in the Org file, save it, export it to HTML, hop to the browser, refresh; if it doesn't work, look in the HTML file and see what happened - lather, rinse, repeat.
The one remaining thing is to add a title `Abstract`, like LaTeX. AFAIK, that cannot be done with CSS. One way to do it is to define your own exporter derived from HTML and overriding the `org-html-special-block` function: your function can check what kind of special block it is dealing with and inject the title in the appropriate place.
Another way to do it is to define a filter (see the "Filters" section in the Org manual with `C-h i g(org)filters`).
Here is a filter solution:
```
#+begin_src elisp
(defun ndk/add-title-to-abstract (text backend info)
(when (org-export-derived-backend-p backend 'html)
(if (string-match "class=\"abstract\"" text)
;; got one - rewrite the text to include the title
(replace-regexp-in-string "<p>" "<div class=\"abstract_title\">Abstract</div><p>" text))))
(add-to-list 'org-export-filter-special-block-functions
#'ndk/add-title-to-abstract)
#+end_src
```
Note that the filter is applied to the transcoded string (i.e. the string that is produced by `org-html-special-block`). It is an HTML string like this:
```
<div class="abstract" id="orgdbb679b">
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
...
sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
</div>
```
We define a filter that checks only special blocks (since it is added to `org-export-filter-special-block-functions`). It checks that the backend is (derived from) `html` and does a crude string search to make sure that it is an `abstract` by checking that it contains `class="abstract"`. It then replaces the `<p>` by adding some stuff so that the `<p>` line now looks like this: `<div class="abstract_title">Abstract</div><p>`.
That will produce the title, but it is not going to be styled very nicely. But that's why we added the new `div` with its own distinctive class, so that we can style it just as we did the `abstract` class. So back to CSS we go to add some styling for the new `abstract_title` class:
```
#+HTML_HEAD_EXTRA: <style> div.abstract_title { font-size: 150%; font-variant: small-caps; text-align: center; color: blue; } </style>
```
I should point out that what I know about CSS can be written down on an index card: seasoned CSS people are probably ROFLTAO or worse...
If I find some time, I may come back and do the derived-backend implementation. But there are many examples of derived backends e.g. on Github, although they will probably be a bit more complicated than is necessary for the simple problem we are considering here. We only need to override one function: `org-html-special-block`.
> 2 votes
---
Tags: org-mode, org-export, latex, html
--- |
thread-63429 | https://emacs.stackexchange.com/questions/63429 | Hide ifdef(or gray out) through compile_command.json | 2021-02-16T13:19:52.467 | # Question
Title: Hide ifdef(or gray out) through compile_command.json
I've just finished to set up LSP with ccls and company packages. It works but I have one more possible wish that such LSP packages could do. Now I'm using hide-ifdef package to gray out the inactve code area but it reads preprocessors from my certain .dir-locals.el. As you know, such preprocessors are already in compile\_commands.json. I wonder some of LSP package could do the same thing - ie graying out the inactive area. Or whether I have to write a new package to do so. Please share your experience.
# Answer
> 2 votes
old but it may help someones. You need to use lsp token highligthing by setting this variable:
```
lsp-semantic-tokens-enable
```
to `t`.
---
Tags: lsp-mode, ccls
--- |
thread-69743 | https://emacs.stackexchange.com/questions/69743 | Use regex as key/car in alist | 2021-12-13T14:08:43.087 | # Question
Title: Use regex as key/car in alist
I'd like to set up an alist (similar to `auto-mode-alist`), which is made up from regular expressions as key (AKA car) of the list. Next I'd like to be able, to match, say the major mode, against the regex in order to retrieve the value/cdr of the matching key/car.
```
(setq jb-string-mode-alist
'(("\\(emacs-\\)?lisp\\(-interaction\\)?-mode" . "Combined")
(lisp-interaction-mode . "Interaction") ; works
(emacs-lisp-mode . "Emacs") ; works also
(lisp-mode . "Lisp") ; works also
(latex-mode . "LaTeX") ; works also
(".*$" . "Default")))
```
Afterwards I tried something like the following:
```
(assoc major-mode jb-tools-date-time-string-mode-alist) ; => "Interaction"
```
Evaluating the expression in the `*scratch*` buffer of emacs yields `"Interaction"` as the mode of the `*scratch*` buffer is `lisp-interaction-mode`. This matches the third entry in my alist, but it should match the first entry consisting of the regular expression.
Using `assq` instead of `assoc` makes no difference.
What is the trick, to evaluate the mode with respect to regular expressions?
# Answer
> 2 votes
`assoc` has the following documentation, which you can view by running `C-h f assoc`:
```
(assoc KEY ALIST &optional TESTFN)
Return non-nil if KEY is equal to the car of an element of ALIST.
The value is actually the first element of ALIST whose car equals KEY.
Equality is defined by the function TESTFN, defaulting to equal.
TESTFN is called with 2 arguments: a car of an alist element and KEY.
```
See that third argument? You can supply your own function there and it will be called instead of `equal`. If it returns true, the `assoc` be finished and will return the value associated with this key.
If you look in chapter 35.4 Regular Expression Searching of the Emacs Lisp manual, you will find that there is a function called `string-match-p` which returns `t` when the provided string matches the provided regexp. It is no coincidence that it takes the arguments in the same order that `assoc` provides them. Put the two together and call `assoc` like this:
```
(assoc major-mode jb-tools-date-time-string-mode-alist 'string-match-p)
```
Don’t forget that you can read the manuals inside of Emacs by running `C-h i`. Everything you need to know is in there.
---
Tags: regular-expressions, alists
--- |
thread-69745 | https://emacs.stackexchange.com/questions/69745 | Exotic dired-based window-splitting mode | 2021-12-13T20:19:09.947 | # Question
Title: Exotic dired-based window-splitting mode
NOTE: I added more info to this query. Initially, I didn't mention `dired`, but after experimenting, I see that it needs to be explicitly discussed here, because of how it manages buffers.
I'm using `emacs-27.2`. I am looking for what I consider to be an "exotic" (*i.e.*, non-standard) way to split a buffer between two windows when using `dired`, as follows:
1. Enter dired
2. Split the dired buffer into two windows
3. The two windows are next to each other, left and right, in the same frame.
4. The same dired info appears in both windows.
5. In the leftmost window, the topmost lines of the dired list appear, with the cursor ***initially*** automatically positioned to the first line of the dired list as soon as I enter this mode.
6. In the rightmost window, the bottommost lines of the dired list appear, with the cursor ***initially*** automatically positioned to the last line of the dired list as soon as I enter this mode.
7. As soon as select a subdirectory in the dired list of one of the windows, the directory gets displayed at the same time in the other window, with the top of the buffer showing in the leftmost window and the bottom of the buffer showing in the rightmost window, as described above.
I want all of these characteristics exactly as described, not just a subset of them nor any kind of variation.
I know how to split the window, and I'm sure that I can figure out how to write a function to accomplish what I want. However, before I "reinvent the wheel", I'm wondering if there already is some sort of command or mode which can give me this functionality.
# Answer
Based on the very helpful answer by Drew, I figured out what to do.
First, I wrote this command ...
```
(defun my-dired-action ()
(interactive)
(let* ((files (dired-get-marked-files t current-prefix-arg))
(file (expand-file-name (car files)))
(dired-view-file)
(when (file-directory-p file)
(delete-other-windows)
(follow-delete-other-windows-and-split))
))
```
And then, I start `dired` as follows:
```
(require 'dired)
;; set up `dired-mode-hook` to map the `my-dired-action`
;; function to the desired keystrokes and mouse clicks
(dired)
(follow-delete-other-windows-and-split)
```
The `follow-delete-other-windows-and-split` function is a standard elisp function to split the current window and to then initiate `follow-mode`.
> 0 votes
# Answer
`M-x follow-mode` is very close to what you're requesting. It lets you show a buffer in two windows, with one of the windows starting at the line where the other left off.
You may have to explicitly visit a subdir in both windows, and turn on `follow-mode` for that buffer as well, but out-of-the-box `follow-mode` gets you quite close. (You can write a command that visits a subdir and sets that up the same way etc.)
> 0 votes
---
Tags: buffers, dired, window-splitting
--- |
thread-24190 | https://emacs.stackexchange.com/questions/24190 | send orgmode sh babel block to eshell/term in emacs? | 2016-06-26T08:29:18.087 | # Question
Title: send orgmode sh babel block to eshell/term in emacs?
Does anyone know if its possible to send the bash code in a orgmode sh block and run in in a new eshell/term buffer in emacs? for example as a use case i would like to run/eval a code block like this
```
#+BEGIN_SRC sh
sudo pacman -Syuu
#+END_SRC
```
and have the command execute within emacs in term, eshell etc?
is that possible?
# Answer
I use the following to send the current line or selected region to the shell associated with a given buffer:
```
(defun kdm/sh-send-line-or-region ()
(interactive)
(if (use-region-p)
(append-to-buffer (get-buffer (directory-shell-buffer-name)) (mark)(point))
(let (p1 p2)
(setq p1 (line-beginning-position))
(setq p2 (line-end-position))
(append-to-buffer (get-buffer (directory-shell-buffer-name)) p1 p2)
))
(let (b)
(setq b (get-buffer (current-buffer)))
(switch-to-buffer-other-window (get-buffer (directory-shell-buffer-name)))
(execute-kbd-macro "\C-m")
(switch-to-buffer-other-window b)
)
)
(global-set-key "\M-s" 'kdm/sh-send-line-or-region)
```
> 1 votes
# Answer
If you want to simply execute some commands then write them in the source block and execute using `C-c C-c` while in the block. To execute on a remote machine or as sudo combine use of `:dir` and tramp, For example:
```
#+BEGIN_SRC sh :dir /sudo:pacman@localhost:
who am i
date
#+END_SRC
```
reference
> 0 votes
# Answer
Yes, there are several ways this could be done. The most straight forward at the time of writing is probably to use a session:
```
#+BEGIN_SRC sh :session *my-shell*
sudo pacman -Syuu
#+END_SRC
```
This will create a new comint process (like with `M-x shell`) called "\*my-shell\*". Blocks whose header specifies the session will be executed in that shell. If you wanted to interact with it outside of Org, you can switch to it in the buffer list.
> 0 votes
---
Tags: org-mode
--- |
thread-69669 | https://emacs.stackexchange.com/questions/69669 | html-mode: publish to browser and jump to cursor location | 2021-12-07T18:07:15.917 | # Question
Title: html-mode: publish to browser and jump to cursor location
In `html-mode`, how can a user publish an html page to browser (`browse-url-of-buffer`), and also jump to the approximate location in the webpage as the cursor in the corresponding Emacs buffer.
# Answer
> 5 votes
One way is using an elisp function and a temporary anchor in the html:
* Surround the line where cursor is with an anchor `<a name='CursorPosition'>`
* Use `browse-url-firefox` (or preferred browser) to include that anchor (`#CursorPosition`)
Working example:
```
(defun browse-url-of-buffer-with-cursor-position ()
"""Browse url of buffer, jumping to location of cursor"""
(interactive)
(let* ((p1 (point-at-bol))
(p2 (point-at-eol))
(old-buffer (current-buffer))
(old-line (thing-at-point 'line t))
(replacement-line (concat "<a name=\"CursorPosition\">" old-line "</a>")))
(get-buffer-create "*temp-browse*")
(with-current-buffer "*temp-browse*"
(erase-buffer)
(insert-buffer-substring old-buffer)
(replace-string old-line replacement-line nil (point-min) (point-max))
;; directly from browse-url-of-buffer:
(let ((file-name
;; Ignore real name if restricted
(and (not (buffer-narrowed-p))
(or buffer-file-name
(and (boundp 'dired-directory) dired-directory)))))
(when (or (not file-name)
;; This can happen when we're looking at a file from a
;; zip file buffer, for instance.
(not (file-exists-p file-name)))
(unless browse-url-temp-file-name
(setq browse-url-temp-file-name
(convert-standard-filename
(make-temp-file
(expand-file-name "burl" browse-url-temp-dir)
nil ".html"))))
(setq file-name browse-url-temp-file-name)
(write-region (point-min) (point-max) file-name nil 'no-message))
;; customized to add cursor position anchor
(setq new-url (concat (browse-url-file-url file-name) "#CursorPosition"))
(browse-url-firefox new-url)))))
```
Note this uses a temporary buffer and will not modify the original buffer/html.
---
Tags: html
--- |
thread-69471 | https://emacs.stackexchange.com/questions/69471 | How to select and delete a column of text in emacs? | 2021-11-25T00:49:00.713 | # Question
Title: How to select and delete a column of text in emacs?
I have this text
```
1 A
2 B
3 C
```
I want to remove the first column to make it
```
A
B
C
```
Ok so I need to make a rectangle. Reading about rectangles I see
"To specify a rectangle for a command to work on, set the mark at one corner and point at the opposite corner. The rectangle thus specified is called the region-rectangle. If point and the mark are in the same column, the region-rectangle is empty. If they are in the same line, the region-rectangle is one line high."
I go to line 1 column 1 and set the mark with C-SPC. I go to the end of the rectangle at line 3 column 2 (to include column 1 only). Then I do C-w. It kills everything up to C:
```
C
```
Obviously it included columns 2 and 3. How to prevent this and only select column 1?
# Answer
> 19 votes
`C-w` kills the text between point and mark; it’s the normal command you would use to kill text. `C-x r k` kills the *rectangle* between point and mark. This is the one you want to use.
# Answer
> 18 votes
If you *select* the rectangle, which in Emacs terms means make it an *active* rectangular region, then `C-w` does just what you expect.
Use **`C-x SPC`** to activate a rectangular region that you want to kill. Then just use `C-w`, the usual key for killing the active region.
To select a rectangular region, do one of the following:
* Put point and mark at opposite corners (the same thing you'd need to do to be able to use `C-x r k`) and then hit `C-x SPC`.
* Use `C-x SPC` first (that activates an empty rectangular region), and then move point to the opposite corner, extending the selection as you move the cursor.
* Drag `C-M-mouse-1` to select the rectangle. (Thanks to @pst for pointing this out in a comment here.) For this, you need Emacs 27 or later.
# Answer
> 0 votes
If you use evil, I've found `evil-visual-block` bound to `C-v` to be the most straightforward.
* `C-v` to enter visual block mode
* Arrows (or preferred movement) to select column/rectangular region
* `d` delete
---
Tags: region, rectangle, kill-text
--- |
thread-18265 | https://emacs.stackexchange.com/questions/18265 | How do I change the working directory used by pdb/gud? | 2015-11-20T22:54:17.127 | # Question
Title: How do I change the working directory used by pdb/gud?
When running `M-x pdb` from Emacs, the current directory seems to be set to that of the directory of the script you are running, so
```
pdb ~/path/to/project/__main__.py
```
Would set the working directory to `~/path/to/project/`. However, what if I need the working directory to be a different directory - say, one directory back? Is there a way to set the directory that pdb/gud uses as the "working directory"? At the first `pdb` prompt I can change the directory with `os.chdir()`, which works, but I would like to not have to do this every time. Thank you!
# Update:
I have found that one potential solution would be to set `gud-chdir-before-run` (mentioned by @Nsukami\_ below) to `nil` and then change to the desired directory with `(cd "/path/to/directory")` before running `pdb`. I tried doing this with the `gud-mode-hook` but the directory is changed too late. I have also, tried to do this with by advising `pdb` and `gud-mode-hook`, but don't yet have the lisp skills for this apparently...Is there a good way to call `cd` *before* `gud-mode-hook`/ before the dubugger starts?
# Answer
**Emacs specific:**
Using a custom elisp function to call pdb with the `-c COMMAND` option, specifying the command as `import os; os.chdir('..')` (modifying directory as needed).
Working example:
```
(defun pdb-chdir ()
"""Change working directory when calling pdb"""
(interactive)
(let ((pdb-cmd-name
(concat "python -m pdb -c \"import os; os.chdir('..')\" "
buffer-file-name)))
(pdb pdb-cmd-name)))
```
Benefit being no additional scripts or files to create.
---
**A couple options using pdb's .pdbrc files:**
* Add a .pdbrc file in the same directory as your .py script, containing
```
import os
os.chdir('/path/to/dir')
```
You would need to add just one .pdbrc file for each directory, but would apply when running pdb on any script in that directory
* Add a .pdbrc to your home directory `~`(this would be overridden by commands in a local .pdbrc file as above, if they both exist).
```
import os
os.chdir('..') # one directory up relative to script
```
Only need to create one .pdbrc file, in the event you always want the working directory in the same relative path when using pdb. But note this would get executed every time you run pdb, regardless of script location.
> 1 votes
# Answer
```
import os; os.chdir('/path/to/dir');
```
To get know current working directory:
```
import os; os.getcwd();
```
> 0 votes
---
Tags: python, debugging, gud
--- |
thread-69754 | https://emacs.stackexchange.com/questions/69754 | How can I send a desktop notification via Emacs? | 2021-12-14T17:10:32.633 | # Question
Title: How can I send a desktop notification via Emacs?
In bash syntax, one can use `notify-send` to make a message appear in the desktop. How can we accomplish the same with `elisp`?
# Answer
On GNU/Linux systems, there is the notifications.el package in core Emacs. Example from the info manual:
```
(require 'notifications)
(defun my-on-action-function (id key)
(message "Message %d, key \"%s\" pressed" id key))
⇒ my-on-action-function
(defun my-on-close-function (id reason)
(message "Message %d, closed due to \"%s\"" id reason))
⇒ my-on-close-function
(notifications-notify
:title "Title"
:body "This is <b>important</b>."
:actions '("Confirm" "I agree" "Refuse" "I disagree")
:on-action 'my-on-action-function
:on-close 'my-on-close-function)
⇒ 22
A message window opens on the desktop. Press ``I agree''.
⇒ Message 22, key "Confirm" pressed
Message 22, closed due to "dismissed"
```
The whole description is in the Elisp manual, see `(info "(elisp) Desktop Notifications")`
> 7 votes
# Answer
you can use `notifications.el` as described in Michael Albinus' answer or the alert package from melpa which can be simpler in many cases and works cross-platform.
e.g. `(alert "This is an alert" :title "My Alert" :category 'debug)`
> 2 votes
---
Tags: notifications
--- |
thread-69765 | https://emacs.stackexchange.com/questions/69765 | Matching non-# in Regexp | 2021-12-15T19:35:11.933 | # Question
Title: Matching non-# in Regexp
I'm trying to use replace-regexp to change the following code
```
samples <- rep(10, 5)*1000 ## steps determined by samples * thin
adaptive.ratio <- c(rep(c(1,0), 2), 0) ## Alternate between adaptive and non-adaptive
...
```
to
```
print(paste0("samples: ", samples)) ## steps determined by samples * thin
print(paste0("adaptive.ratio: ", adaptive.ratio)) ## Alternate between adaptive and non-adaptive
...
```
I am using the following regexp to do so
```
^\(\b.*\b\)\([^#]*\) → print(paste0("\1: ", \1) ) \2
```
But this highlights
```
samples <- rep(10, 5)*1000 ## steps determined by samples * thin
adaptive.ratio <- c(rep(c(1,0), 2), 0)
```
for the first replacement rather than what I want, which is to highlight only
```
print(paste0("samples: ", samples)) ## steps determined by samples * thin
```
I've tried escaping the # sign with #, adding a space between the two sets of parentheses, but that doesn't help.
I realize this is somehow related to the greedy nature of regexp matching, but I don't understand what am I doing wrong nor, as a result, how to fix it.
# Answer
Okay, I figured it out. I was misusing the word boundary markers (which I don't understand how so a comment or two would be great.)
This is the code I want to use
```
^\([A-z0-9_.]+\) \([^# <C-q 012>]*\) → print(paste0("\1: ", \1)
```
Where \<C-q 012\> inserts the new line character.
> 1 votes
# Answer
Change your regexp to exclude not only `#` chars but also newline chars.
```
^\(\b.*\b\)\([^#
]*\) → print(paste0("\1: ", \1)) \2
```
That's what you type to interactively type the regexp, where the newline shown is typed using `C-q C-j`.
If you're defining the regexp in Lisp code, as a Lisp string, use this:
```
^\\(\\b.*\\b\\)\\([^#\n]*\\) → print(paste0("\\1: ", \\1)) \\2
```
> 0 votes
---
Tags: query-replace-regexp
--- |
thread-69763 | https://emacs.stackexchange.com/questions/69763 | `shell-command` output not working when in a function | 2021-12-15T18:56:37.497 | # Question
Title: `shell-command` output not working when in a function
I have
```
(shell-command-to-string "ls")
```
which works just fine but when I put it in a function it breaks as
```
(defun testing ()
(shell-command-to-string "ls")
)
```
outputs `nil`. I am new to `elisp` so I am clearly missing something. Can someone point me in the right direction?
# Answer
> 0 votes
In Lisp, a function call is denoted like this: `(func arg1 arg2 ...)`. IOW, the first element of the list is the function and subsequent elements are the (evaluated) arguments. Contrast this with most other languages where a function call is denoted like this: `func(arg1, arg2, ...)`.
So you *define* the function like this:
```
(defun testing ()
(shell-command-to-string "ls")
)
```
Doing `C-x C-e` after the closing paren evaluates the `defun` and adds the definition of the function to the system. Then to *call* the function you say:
```
(testing)
```
This *calls* the function `testing` with *no* arguments.
You should probably read the "Introduction to Programming in Elisp" which can be found here.
---
Tags: shell-command
--- |
thread-46899 | https://emacs.stackexchange.com/questions/46899 | How do I set latex face attributes in init.el? | 2019-01-04T11:10:30.207 | # Question
Title: How do I set latex face attributes in init.el?
When I try to put
```
(set-face-attribute 'font-latex-italic-face nil :foreground green)
(set-face-attribute 'font-latex-math-face nil :foreground orange)
(set-face-attribute 'font-latex-script-char-face nil :foreground red)
(set-face-attribute 'font-latex-string-face nil :foreground red)
```
into my init.el (green & are variables I have given values), I am told that 'font-latex-... are 'invalid faces'. this also happens if i try to evaluate the expressions before having opened a latex buffer. how am i suppsed to customize these faces in my init.el? (i don't want to use custom-set-faces.)
# Answer
The standard method to do this sort of thing, given that the faces are defined in the `font-latex` library:
```
(with-eval-after-load 'font-latex
(set-face-attribute 'font-latex-italic-face nil :foreground green)
(set-face-attribute 'font-latex-math-face nil :foreground orange)
(set-face-attribute 'font-latex-script-char-face nil :foreground red)
(set-face-attribute 'font-latex-string-face nil :foreground red))
```
This way, you don't force the loading of `font-latex` before you need it. If the file has already been loaded, the commands will be run immediately; otherwise, they will be run after the file is loaded, as the name indicates. (Strictly speaking, they will be run after the loading of any file that runs `(provide 'font-latex)`. But no other file should do that.)
> 3 votes
# Answer
You have to load or autoload a symbol before you can customize it. The easiest way is to insert
```
(require 'font-latex)
```
before the `set-face-attribute` commands.
> 0 votes
# Answer
I faced a similar issue with `ediff`. The faces are defined here, required here, but they're loaded only when I start resolving a conflict. But there's a `ediff-load-hook` in `ediff.el`, so I did this:
```
(add-hook 'ediff-load-hook
(lambda ()
(set-face-attribute 'ediff-even-diff-A nil :background "dim grey")
(set-face-attribute 'ediff-odd-diff-A nil :background "dim grey")
(set-face-attribute 'ediff-even-diff-B nil :background "dim grey")
(set-face-attribute 'ediff-odd-diff-B nil :background "dim grey")
(set-face-attribute 'ediff-even-diff-C nil :background "dim grey")
(set-face-attribute 'ediff-odd-diff-C nil :background "dim grey")))
```
> 0 votes
---
Tags: auctex, faces
--- |
thread-69762 | https://emacs.stackexchange.com/questions/69762 | Establish plink ssh connection via tramp to AWS instance | 2021-12-15T17:55:07.383 | # Question
Title: Establish plink ssh connection via tramp to AWS instance
on my freaking company windows machine I am trying to use tramp to connect to my aws instance.
On pressing C-x C-f, on linux I usually did press slash twice to erase the path and the put in: ssh:....
But on windows I cannot use double slash or double backslash to delete the c:\ part of the path to input "plink:..."
How can I make this work please?
# Answer
I guess there's a typo when you write "on linux I usually did press backslash twice". Like you mean the slash `/` key.
This doesn't work on MS Windows indeed. Emacs on MS Windows supports UNC file names. That is, if you have mounted a network drive `share` on your machine, you can access the respective directory in Emacs as `//share/...`. That's why the leading two slashes `//` are always kept when you try file name completion in the minibuffer. You must delete the slash with the backspace key on your keyboard.
> 1 votes
# Answer
Not sure of the answer. I also use tramp with plink on windows. After some similar frustrations I started using counsel-tramp as shown below. Since I adopted this method it has always worked well. Counsel-tramp is an additional library that needs to be installed (I already was using Ivy and related libraries).
```
(setq tramp-default-method "plink")
(define-key global-map (kbd "C-c t") 'counsel-tramp)
(setq counsel-tramp-custom-connections '(/plink:ian@host1.xx:~/
/plink:host1.xx|sudo::/
/plink:admin@host2.com:~/
/plink:hostshortcut:~/
/plink:hostshortcut2:~/
/plink:hostshortcut3:~/
/plink:hostshortcut4:~/))
```
> 0 votes
---
Tags: microsoft-windows, tramp
--- |
thread-69776 | https://emacs.stackexchange.com/questions/69776 | How can I keep an item collapsed in org-mode when emacs starts? | 2021-12-16T18:08:29.413 | # Question
Title: How can I keep an item collapsed in org-mode when emacs starts?
I have multiple items in my `org-mode`, example:
```
* work wanted behavior when emacs startup
** item_1 | ** item_1
Notes ... | ** item_2
** item_2 | Notes...
Notes... |
```
my setup:
```
(require 'org)
(add-hook 'org-mode-hook (lambda ()
(local-set-key (kbd "C-c s") 'org-show-subtree)))
```
When I restart emacs all show up as expanded. Would it be possible to keep selected ones collapsed?
# Answer
You can set the `VISIBILITY` property of an entry:
```
* work
** item_1
:PROPERTIES:
:VISIBILITY: folded
:END:
Notes
** item_2
:PROPERTIES:
:VISIBILITY: all
:END:
Notes
```
See the "Initial Visibility" section of the manual: `C-h i g(org)initial visibility`.
> 4 votes
---
Tags: org-mode
--- |
thread-69773 | https://emacs.stackexchange.com/questions/69773 | Is it possible to comment a line from a table? | 2021-12-16T15:37:51.990 | # Question
Title: Is it possible to comment a line from a table?
Let's say I have the following table :
```
|--------+--------|
| Letter | Number |
|--------+--------|
| A | 1 |
| B | 2 |
| C | 3 |
|--------+--------|
```
I'd like to only export some part of it. Let's say:
```
|--------+--------|
| Letter | Number |
|--------+--------|
| A | 1 |
| C | 3 |
|--------+--------|
```
Is it possible?
# Answer
> 2 votes
You can modify the `org-table-export` function to add a filtering effect. The following excludes rows whose first column matches `"B"` (exact match). The added code is after `;; start of custom filter`, but the rest is identical to `org-table-export`.
Working example:
```
(defun org-table-export-filtered (&optional file format)
"org-table-export with an added filter based on values in the first column"
(interactive)
(unless (org-at-table-p) (user-error "No table at point"))
(org-table-align) ; Make sure we have everything we need.
(let ((file (or file (org-entry-get (point) "TABLE_EXPORT_FILE" t))))
(unless file
(setq file (read-file-name "Export table to: "))
(unless (or (not (file-exists-p file))
(y-or-n-p (format "Overwrite file %s? " file)))
(user-error "File not written")))
(when (file-directory-p file)
(user-error "This is a directory path, not a file"))
(when (and (buffer-file-name (buffer-base-buffer))
(file-equal-p
(file-truename file)
(file-truename (buffer-file-name (buffer-base-buffer)))))
(user-error "Please specify a file name that is different from current"))
(let ((fileext (concat (file-name-extension file) "$"))
(format (or format (org-entry-get (point) "TABLE_EXPORT_FORMAT" t))))
(unless format
(let* ((formats '("orgtbl-to-tsv" "orgtbl-to-csv" "orgtbl-to-latex"
"orgtbl-to-html" "orgtbl-to-generic"
"orgtbl-to-texinfo" "orgtbl-to-orgtbl"
"orgtbl-to-unicode"))
(deffmt-readable
(replace-regexp-in-string
"\t" "\\t"
(replace-regexp-in-string
"\n" "\\n"
(or (car (delq nil
(mapcar
(lambda (f)
(and (string-match-p fileext f) f))
formats)))
org-table-export-default-format)
t t)
t t)))
(setq format
(org-completing-read
"Format: " formats nil nil deffmt-readable))))
(if (string-match "\\([^ \t\r\n]+\\)\\( +.*\\)?" format)
(let ((transform (intern (match-string 1 format)))
(params (and (match-end 2)
(read (concat "(" (match-string 2 format) ")"))))
(table (org-table-to-lisp)))
(unless (fboundp transform)
(user-error "No such transformation function %s" transform))
;; start of custom filter
(let* ((org-table-temp (org-table-to-lisp))
(new-org-table-temp '()))
(while org-table-temp
(setq row (car-safe org-table-temp))
(setq row-text (format "%s" (car-safe row)))
(if (bound-and-true-p row-text)
;; change "B" below to filter on different value
(if (string= row-text "B") nil (push row new-org-table-temp))) ;; appends if not matching
(setq org-table-temp (cdr org-table-temp)))
(setq new-org-table-temp (nreverse new-org-table-temp))
(setq table new-org-table-temp)
)
;; end of custom filter
(let (buf)
(with-current-buffer (find-file-noselect file)
(setq buf (current-buffer))
(erase-buffer)
(fundamental-mode)
(insert (funcall transform table params) "\n")
(save-buffer))
(kill-buffer buf))
(message "Export done."))
(user-error "TABLE_EXPORT_FORMAT invalid")))))
```
This works by taking original table produced when executing `org-table-export`, checking value in first column of each row for `"B"`, and if it does not match appends row to a new filtered table.
# Answer
> 1 votes
One way is to use the original table as input to a source block that produces the table you want to export. Then it's just a matter of *not* exporting what you don't want:
```
* Original table :noexport:
#+name: orig
|--------+--------|
| Letter | Number |
|--------+--------|
| A | 1 |
| B | 2 |
| C | 3 |
|--------+--------|
* New table
#+begin_src elisp :var tbl=orig :exports results
(progn
(setf (nth 2 tbl) nil)
(delete nil (append (list 'hline (car tbl) 'hline) (cdr tbl))))
#+end_src
```
---
Tags: org-mode, org-table
--- |
thread-69781 | https://emacs.stackexchange.com/questions/69781 | How to set the file-permissions of a buffer before it's written? | 2021-12-16T22:15:54.850 | # Question
Title: How to set the file-permissions of a buffer before it's written?
Is it possible to set the permissions on a buffer before it's written to a file? Or is it necessary to change the permissions after writing it?
(technically this would allow some small time-frame for another user to read the file, I would rather avoid this).
---
Note that this is for a package that writes files, so I rather not change the default system/emacs wide.
# Answer
Change your umask so that only your user can read newly–created files. Note that this can be done in the shell before you start Emacs (shells usually provide a command called `umask` for this purpose), or while Emacs is running by calling `set-default-file-modes`. See chapter 26.7 Changing File Names and Attributes.
Note that all processes have a umask, so you can use this solution with all programs, not just Emacs.
Edit: your modification changes the nature of the question quite significantly. However, if you take another look at chapter 26.7 Changing File Names and Attributes of the Emacs Lisp manual, you will find a macro called `with-file-modes` that allows you to do exactly what you want.
Also, NickD’s suggestion to simply change the permissions of the cache directory is a sound one. It doesn’t matter much if the files in a directory are readable or not if other users cannot traverse into it.
> 2 votes
---
Tags: files, permissions
--- |
thread-31502 | https://emacs.stackexchange.com/questions/31502 | How do I open an ansi-term on a remote server via Tramp? | 2017-03-16T17:35:43.113 | # Question
Title: How do I open an ansi-term on a remote server via Tramp?
I am editing a file on a remote server via Tramp, and I decide that I want to open up an `ansi-term` session on the remote server (as opposed to relying on `shell-command`). How do I do this? When I run `ansi-term`, it just opens up a new session on my local computer.
# Answer
You can use the following function
```
(defun dfeich/ansi-terminal (&optional path name)
"Opens an ansi terminal at PATH. If no PATH is given, it uses
the value of `default-directory'. PATH may be a tramp remote path.
The ansi-term buffer is named based on `name' "
(interactive)
(unless path (setq path default-directory))
(unless name (setq name "ansi-term"))
(ansi-term "/bin/bash" name)
(let ((path (replace-regexp-in-string "^file:" "" path))
(cd-str
"fn=%s; if test ! -d $fn; then fn=$(dirname $fn); fi; cd $fn;")
(bufname (concat "*" name "*" )))
(if (tramp-tramp-file-p path)
(let ((tstruct (tramp-dissect-file-name path)))
(cond
((equal (tramp-file-name-method tstruct) "ssh")
(process-send-string bufname (format
(concat "ssh -t %s '"
cd-str
"exec bash'; exec bash; clear\n")
(tramp-file-name-host tstruct)
(tramp-file-name-localname tstruct))))
(t (error "not implemented for method %s"
(tramp-file-name-method tstruct)))))
(process-send-string bufname (format (concat cd-str " exec bash;clear\n")
path)))))
```
This code is also linked this gist. I have a similar gist for opening gnome-terminals at the current path (or any given path) here.
With the ansi terminal there may just some small but non-critical problem with the remote server not knowing the 'eterm-color' type. E.g. look at this stackoverflow question.
> 2 votes
# Answer
I have implemented @phils suggestion based on the answer provided by @dfeich. The advantage is that without the local shell indirection, the terminal management is "instant".
```
(defun aratiu/terminal (&optional path name)
"Opens a terminal at PATH. If no PATH is given, it uses
the value of `default-directory'. PATH may be a tramp remote path.
The term buffer is named based on `name' "
(interactive)
(require 'term)
(unless path (setq path default-directory))
(unless name (setq name "term"))
(let ((path (replace-regexp-in-string "^file:" "" path))
(cd-str "fn=%s; if test ! -d $fn; then fn=$(dirname $fn); fi; cd $fn; exec bash")
(start-term (lambda (termbuf)
(progn
(set-buffer termbuf)
(term-mode)
(term-char-mode)
(switch-to-buffer termbuf)))))
(if (tramp-tramp-file-p path)
(let* ((tstruct (tramp-dissect-file-name path))
(cd-str-ssh (format cd-str (tramp-file-name-localname tstruct)))
(user (if (tramp-file-name-user tstruct)
(tramp-file-name-user tstruct)
user-login-name))
(switches (list "-l" user
"-t" (tramp-file-name-host tstruct)
cd-str-ssh))
(termbuf (apply 'make-term name "ssh" nil switches)))
(cond
((equal (tramp-file-name-method tstruct) "ssh")
(funcall start-term termbuf))
(t (error "not implemented for method %s"
(tramp-file-name-method tstruct)))))
(let* ((cd-str-local (format cd-str path))
(termbuf (apply 'make-term name "/bin/sh" nil (list "-c" cd-str-local))))
(funcall start-term termbuf)))))
```
> 2 votes
---
Tags: tramp, ssh, ansi-term
--- |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.