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-64892 | https://emacs.stackexchange.com/questions/64892 | How to disable certain org-mode blocks from accidental execution | 2021-05-18T13:21:56.460 | # Question
Title: How to disable certain org-mode blocks from accidental execution
I have some shell code that can be dangerous to run on local machine in a org-mode source code block. Globally, I have configured org-mode to prompt for execution, but I would still like to make sure that these blocks will NEVER be executed with per-block configuration.
# Answer
To explicitly disable certain org-mode code blocks from execution, add `:eval no` or `:noeval` in the code block header line. See the example below:
```
#+begin_src bash :noeval
sudo rm -rf /
#+end_src
```
When doing `C-c C-c` to attempt to run the code, the following message is produced:
```
Evaluation of this bash code block is disabled.
```
> 3 votes
---
Tags: org-mode, org-babel
--- |
thread-64895 | https://emacs.stackexchange.com/questions/64895 | Get process id (pid) for running python (jupyter-kernel) | 2021-05-18T16:54:35.363 | # Question
Title: Get process id (pid) for running python (jupyter-kernel)
I've started a jupyter kernel form emacs-jupyter. I'd like to get the process id for the python process associated with the buffer so that I can attach a debugger to it. How can I do this in elisp?
# Answer
> 0 votes
Something like this:
```
(process-id (get-buffer-process (current-buffer)))
```
should do it. You can replace the call to `current-buffer` by some other means of identifying the buffer of interest, and you should probably check that the result of `get-buffer-process` is not nil.
---
Tags: python, process, ipython
--- |
thread-64898 | https://emacs.stackexchange.com/questions/64898 | How to fix buffer-local variable? | 2021-05-18T19:09:18.973 | # Question
Title: How to fix buffer-local variable?
I have the following in my init.el,
```
(setq-default display-line-numbers 'visual)
(global-display-line-numbers-mode 1)
```
which should give me relative line numbering. On starting emacs, it does on the startup page, but as soon as I switch to another file, the `display-line-numbers` variable is overriden to `t`, which removes relative line numbering. I am confused, as I thought that setting `setq-default` would ensure that new buffers would default to `visual`. Or is there something else going on that I am missing?
# Answer
When I do `C-h f display-line-numbers-mode` I see this as part of the doc:
> **To change the type of line numbers displayed by default, customize `display-line-numbers-type`.** To change the type while the mode is on, set `display-line-numbers` directly.
Have you tried doing that? Dunno whether that will help. If it does, then maybe the doc string of `global-display-line-numbers-mode` should also say something about this.
---
(I filed doc bug #48511 for this.)
> 2 votes
---
Tags: init-file, line-numbers
--- |
thread-64897 | https://emacs.stackexchange.com/questions/64897 | How to insert date into minibuffer, or how to create a new file with date as part of filename? | 2021-05-18T19:07:10.493 | # Question
Title: How to insert date into minibuffer, or how to create a new file with date as part of filename?
shell way: `touch testfile-`date +%Y-%m-%d``
emacs way? `c-x c-f testfile-`... now what?
I want to type the first part of the filename myself, but not the date.
# Answer
> 1 votes
I got what I wanted by adding this to my config:
```
(defun insert-current-date () (interactive)
(insert (shell-command-to-string "echo -n $(date +%Y-%m-%d)")))
(global-set-key (kbd "C-c d") 'insert-current-date)
```
---
Tags: minibuffer, filenames
--- |
thread-64902 | https://emacs.stackexchange.com/questions/64902 | flyspell error enabling with nuspell | 2021-05-18T22:44:57.343 | # Question
Title: flyspell error enabling with nuspell
I want to use nuspell as my spellchecker for emacs. I have installed dictionary and it works fine when I call the program from terminal. But I got the following msg in emacs:
```
Error enabling Flyspell mode:
(nuspell exited with code 1)
```
Here is my setting for flyspell;
```
(setq
ispell-program-name
"nuspell")
(setq ispell-hunspell-dict-paths-alist
'(("en_US" "/usr/share/hunspell/en_US.aff")))
(setq ispell-local-dictionary "en_US")
```
`nuspell -v` is the version information. `nuspell -vv` isn't an valid argument.
```
~ ❱ nuspell -v
nuspell 4.2.0
Copyright (C) 2016-2020 Dimitrij Mijoski and Sander van Geloven
License LGPLv3+: GNU LGPL version 3 or later <http://gnu.org/licenses/lgpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Written by Dimitrij Mijoski and Sander van Geloven.
~ ❱ aspell -vv
@(#) International Ispell Version 3.1.20 (but really Aspell 0.60.8)
```
# Answer
A brief look at the code (in Emacs 27.1 and also a recent build of 28) suggests that `ispell`, `aspell`, `hunspell`, and `enchant` are all supported. There is no mention of `nuspell` in the code.
Is `nuspell` compatible with any of the supported programs in how it should be invoked, and the output it produces? I.e. is there a reasonable expectation that this ought to be working?
The detection of the specific program being used is based on all of them accepting a `-vv` option and identifying themselves as *ostensibly* ispell, "but really Aspell 0.60.7-20110707" (for example).
What does `nuspell -vv` display?
Unless it uses that same output to announce itself as one of the supported programs, I suspect it won't work out of the box.
(Whether or not it can be *made* to work without custom support being added would probably depend on how compatible it is with the other programs.)
> 0 votes
---
Tags: flyspell
--- |
thread-64886 | https://emacs.stackexchange.com/questions/64886 | Indentation in Org Mode Source Block with Return | 2021-05-17T22:59:24.223 | # Question
Title: Indentation in Org Mode Source Block with Return
I have a weird behavior in `org-mode`. When I create a source block, pressing `RET` indents the current *and all previous* lines with 2 spaces, resulting in something like
```
#+begin_src bash :results output
a=0
b=1
c=2
#+end_src
```
No "manual" indentation was applied, it all came from pressing `RET` after each line.
I do not have this behavior if I press `C-j` instead instead of `RET`.
I also do not have it if I start Emacs with the `-Q` option, but I disabled all my `org-mode` configuration and had the same results, so I am not sure what is causing it.
# Answer
This issue has been fixed in commit 857ae366b3 of the Org repo.
You can use that bugfix in Org version 9.4.3 (that comes with Emacs 27.1.90) by the following lines in your init files:
```
(with-eval-after-load "org"
(when (version-list-= (version-to-list org-version) '(9 4 3))
(defun org-return-fix (fun &rest args)
"Fix https://emacs.stackexchange.com/questions/64886."
(let* ((context (if org-return-follows-link (org-element-context)
(org-element-at-point)))
(element-type (org-element-type context)))
(if (eq element-type 'src-block)
(apply #'org--newline args)
(apply fun args))))
(advice-add 'org-return :around #'org-return-fix)))
(with-eval-after-load "org-src"
(when (version-list-= (version-to-list org-version) '(9 4 3))
(defun org-src--contents-for-write-back ()
"Return buffer contents in a format appropriate for write back.
Assume point is in the corresponding edit buffer."
(let ((indentation-offset
(if org-src--preserve-indentation 0
(+ (or org-src--block-indentation 0)
(if (memq org-src--source-type '(example-block src-block))
org-src--content-indentation
0))))
(use-tabs? (and (> org-src--tab-width 0) t))
(source-tab-width org-src--tab-width)
(contents (org-with-wide-buffer (buffer-string)))
(write-back org-src--allow-write-back))
(with-temp-buffer
;; Reproduce indentation parameters from source buffer.
(setq indent-tabs-mode use-tabs?)
(when (> source-tab-width 0) (setq tab-width source-tab-width))
;; Apply WRITE-BACK function on edit buffer contents.
(insert (org-no-properties contents))
(goto-char (point-min))
(when (functionp write-back) (save-excursion (funcall write-back)))
;; Add INDENTATION-OFFSET to every non-empty line in buffer,
;; unless indentation is meant to be preserved.
(when (> indentation-offset 0)
(while (not (eobp))
(skip-chars-forward " \t")
;; (unless (eolp) ;ignore blank lines
(let ((i (current-column)))
(delete-region (line-beginning-position) (point))
(indent-to (+ i indentation-offset)))
;;)
(forward-line)))
(buffer-string))))))
```
> 2 votes
---
Tags: org-mode, indentation
--- |
thread-64903 | https://emacs.stackexchange.com/questions/64903 | Override org-mode indentation function in evil insert mode | 2021-05-19T02:14:27.893 | # Question
Title: Override org-mode indentation function in evil insert mode
How can I override the org-mode indentation function of `TAB` in `evil-insert-state-map`? I'd like it to always fold and unfold the current or parent header, and switch the indentation functionality to another keybinding.
# Answer
> 0 votes
From the doc of `org-cycle`:
```
When point is not at the beginning of a headline, execute the global
binding for `TAB', which is re-indenting the line. See the option
`org-cycle-emulate-tab' for details.
```
Seems setting `org-cycle-emulate-tab` to `nil` will do.
---
Relevant doc:
```
Where should ‘org-cycle’ emulate TAB.
nil Never
white Only in completely white lines
whitestart Only at the beginning of lines, before the first non-white char
t Everywhere except in headlines
exc-hl-bol Everywhere except at the start of a headline
If TAB is used in a place where it does not emulate TAB, the current subtree
visibility is cycled.
```
---
Relevant code:
Note how when everything fails, fallback to cycle the headings (Last 4 lines).
```
(cond
......
((or (eq org-cycle-emulate-tab t)
(and (memq org-cycle-emulate-tab '(white whitestart))
(save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
(or (and (eq org-cycle-emulate-tab 'white)
(= (match-end 0) (point-at-eol)))
(and (eq org-cycle-emulate-tab 'whitestart)
(>= (match-end 0) pos)))))
(call-interactively (global-key-binding (kbd "TAB"))))
(t
(save-excursion
(org-back-to-heading)
(org-cycle))))
```
---
Tags: org-mode, evil, doom
--- |
thread-57613 | https://emacs.stackexchange.com/questions/57613 | org babel sql results output in raw form | 2020-04-06T02:00:30.373 | # Question
Title: org babel sql results output in raw form
Is the way to get same output as in terminal with `ob-doc-sql`.
Executing the sql-query in org will process results into org-table ignoring other than table information. It doesn't fare well with multiple query in the block as show below will squash both into single table.
```
#+BEGIN_SRC sql :engine postgresql :database postgres
SELECT 'hello';
SELECT 'hello', 'world';
#+END_SRC
#+RESULTS:
| ?column? | |
|----------+----------|
| hello | |
| ?column? | ?column? |
| hello | world |
```
header argument `:results` with **output** or **verbatim** value produce correct structure but table formatting is stripped out. But stil doesn't produce any terminal like output as shown below.
```
#+RESULTS:
: ?column?
: hello world
: ?column? ?column?
: hello world
```
Althouh expected output can be produced via shell execution,
```
#+BEGIN_SRC sh :results output
psql postgres -X -c "SELECT 'hello'" -c "SELECT 'hello', 'world';"
#+END_SRC
#+RESULTS:
#+begin_example
?column?
----------
hello
(1 row)
?column? | ?column?
----------+----------
hello | world
(1 row)
#+end_example
```
# Answer
ob-sql passes the `-A` or `--no-align` option to `psql` that
> Switches to unaligned output mode. (The default output mode is aligned.) This is equivalent to `\pset format unaligned`.
ob-sql's `:cmdline` line doesn't help, because it's passed to psql after all other parameters, and psql does everything in order:
> When either `-c` or `-f` is specified, psql does not read commands from standard input; instead it terminates after processing all the `-c` and `-f` options **in sequence**.
Even if we add `:cmdline "-c '\\pset format aligned'"` it won't affect the result.
So to get the output you want apply `:results verbatim` and then call `\a` inside your code blocks:
```
#+BEGIN_SRC sql :engine postgres :database postgres :results verbatim
\a
\pset footer 1
SELECT 'hello';
SELECT 'hello', 'world';
#+END_SRC
#+RESULTS:
#+begin_example
SET
?column?
----------
hello
(1 row)
?column? | ?column?
----------+----------
hello | world
(1 row)
#+end_example
```
`\pset footer 1` brings `(1 row)` messages back, as ob-sql turns them off too with `-P footer=off`.
I think it should also be possible to copy the `org-babel-execute:sql` function to your config and change it however you like. I don't see an easier way to customize this behavior.
> 2 votes
---
Tags: babel, postgresql
--- |
thread-3105 | https://emacs.stackexchange.com/questions/3105 | How to use an external program as the default way to open PDFs from Emacs? | 2014-11-04T22:20:47.640 | # Question
Title: How to use an external program as the default way to open PDFs from Emacs?
When I `M-x find-file` a PDF, it is opened in Emacs. While this is nice, Emacs' PDF viewer lacks many features that I need and I would prefer to open PDFs in an external program instead. How can I configure Emacs to use an external program as the default viewer for PDFs?
# Answer
Try `openwith`. The following code will enable it, and allow you to open PDFs with `evince` (change to your favorite PDF viewer):
```
(require 'openwith)
(openwith-mode t)
(setq openwith-associations '(("\\.pdf\\'" "evince" (file))))
```
> 42 votes
# Answer
If you want to view PDF with many features (highlighting search, highlighting selection, annotate, content tree), use pdf-tools. As you can see in the demo, I can using Isearch with highlighting. Emacs is now my favourite PDF reader. You can also bookmark specific PDF page by using Bookmark(+).
**EDIT**: If you use `helm` and want to use external program, `helm` already has one in the action menu for opening external file: `Open file externally C-c C-x. C-u to choose again`. What it does it that it offers a list of **all** available programs in your system and present you with a nice Helm interface to select from; once you select, Helm remembers it until you run the command with prefix argument `C-u` to select a new one.
> 24 votes
# Answer
You asked about `find-file`. In addition to what others (e.g., Dan) say about that, it is worthwhile to also know about opening files using an application associated with the file type (e.g. extension) in option `dired-guess-shell-alist-user`. And if you use Emacs on MS Windows, then it is worthwhile knowing how to open a file using Windows file associations.
Option **`dired-guess-shell-alist-user`** is available after you load standard library `dired-x.el`. The default association of a PDF file is defined in variable `dired-guess-shell-alist-default`, and it is program `xpdf` (available on UNIX and GNU/Linux). Using option `dired-guess-shell-alist-user` you can, for instance, associate it instead with Adobe Acrobat Reader by adding this association to the alist: `("\.pdf$" . "AcroRd32.exe")`.
Then you can open a PDF file in Dired just by using `!`. That provides default programs as "guesses", which you can access by repeating `M-n`. So `!` followed by `M-n` will give you the shell command `AcroRd32.exe` if point is on a PDF file name and if that command/program is associated with regexp `\.pdf$`.
In addition to Dired, you can make use of the file associations in `dired-guess-shell-alist-user` as a bookmark file handler, that is, have the PDF file association take effect for any bookmarks to PDF files, if you use library **Bookmark+**. The current value of `dired-guess-shell-alist-user` is used as the default value of option **`bmkp-default-handlers-for-file-types`**, which controls this.
You can think of options `dired-guess-shell-alist-user` and `bmkp-default-handlers-for-file-types` as somewhat analogous to `auto-mode-alist`. But they map file-name patterns to file actions instead of mapping them to buffer modes. And they take effect only when you use certain commands.
If you use MS Windows then you can instead (or also) take advantage of existing *Windows file associations* when you open a file in Dired or "jump" to a bookmark. For this you need library `w32-browser.el`.
For Dired, you also need library **Dired+** \- see Using Windows File Associations in Dired. For bookmarks, you also need **Bookmark+** \- see Bookmarking Files You Cannot Visit With Emacs and Opening Bookmarks Using Windows File Associations.
> 14 votes
# Answer
I'm using runner. Here is an excerpt of my configuration file
```
(defun my:open-file-with-dired (file)
"Ask dired how it would open FILE.
This code is useful if dired is well configured to open files
with external applications. I recommend using the `runner`
package to do so."
(use-package dired-aux)
(dired-do-async-shell-command
(dired-guess-shell-command (format "Open %s " file) (list file))
0
(list file)))
(add-to-list 'org-file-apps '(t . (my:open-file-with-dired file)))
(add-to-list 'org-file-apps '("\\.png\\'" . default))
```
> 3 votes
# Answer
What about that one?
```
W runs the command browse-url-of-dired-file (found in dired-mode-map), which is
an autoloaded interactive compiled Lisp function in ‘browse-url.el’.
It is bound to W, <normal-state> W.
(browse-url-of-dired-file)
Probably introduced at or before Emacs version 26.1.
In Dired, ask a WWW browser to display the file named on this line.
```
> 2 votes
# Answer
This is what I put in my init file:
```
(setq dired-guess-shell-alist-user '(("\\.pdf$" "nohup xdg-open * </dev/null >/dev/null 2>&1 &")))
```
It uses `dired-guess-shell-alist-user` as suggested in the answer by Drew and `xdg-open` as suggested by Lei Zhao. So when I hit `!` in dired it will open the pdf with my pdf viewer picked by `xdg-open` (my OS is Ubuntu). Furthermore the stdin, stdout and stderr is redirected. This has the effect that no strange `nohup.out` will be created. This is according to the thorough answer given by Mark Reed on how to avoid nohup.out.
Lastly to make it work also add
```
(require 'dired-x)
```
or something comparable to your init.el. The necessity to load `dired-x` is mentioned by Sean Allred in responde to a similar question.
The code above only works for dired, so `find-file` will not work. Furthermore, it also splits the dired window in half giving a short message, which is a little bit annoying.
I added this answer, because I found the `*` notation helpful, which is mentioned in the online documentation. The asterisk notation allows one to wrap the command in `nohup` and `&` to let it run in background and not terminate when the terminal is closed.
Adding further file extensions besides `pdf` is simple:
```
(setq dired-guess-shell-alist-user '(("\\.pdf$" "nohup xdg-open * </dev/null >/dev/null 2>&1 &")
("\\.jpg$" "nohup xdg-open * </dev/null >/dev/null 2>&1 &")
("\\.ods$" "nohup xdg-open * </dev/null >/dev/null 2>&1 &")))
```
**Edit 1**: Added input and output redirection to nohup
**Edit 2**: Add hint to (require 'dired-x) (sry for bumping old thread, last edit I promise)
> 1 votes
# Answer
My way to achieve this without any plugins is the following. I run Emacs 25.3 under Ubuntu 16.04 LTS. If your OS is macOS or Windows, you definitely need to change the the first function `xdg-open` defined here. I found this link very helpful as a starting point.
```
(defun xdg-open (filename)
(interactive "fFilename: ")
(let ((process-connection-type))
(start-process "" nil "xdg-open" (expand-file-name filename))))
(defun find-file-auto (orig-fun &rest args)
(let ((filename (car args)))
(if (cl-find-if
(lambda (regexp) (string-match regexp filename))
'("\\.pdf\\'" "\\.docx?\\'"))
(xdg-open filename)
(apply orig-fun args))))
(advice-add 'find-file :around 'find-file-auto)
```
After the above code is loaded, when you press `C-x C-f` for PDF and word file, it will automatically open the file using system default app.
I really like the advice mechanism provided by Emacs, see (elisp) Advising Functions. By advising existent function in a compatible way, I avoid re-binding common keys like `C-x C-f` to new function.
> 0 votes
---
Tags: pdf, find-file
--- |
thread-64894 | https://emacs.stackexchange.com/questions/64894 | Tex indentation with TAB | 2021-05-18T14:07:03.460 | # Question
Title: Tex indentation with TAB
Recently, when editing files in LaTex, upon pressing TAB, I get a huge indentation. Instead, the default behavior used to be to align with respect to previous environment definition. :
I start with this (Example 1):
```
\begin{align}
\begin{split}
F = ma
\end{split}
\end{align}
```
Upon pressing TAB in the second row I get something like (Example 2):
```
\begin{align}
\begin{split}
F = ma
\end{split}
\end{align}
```
Whereas I would like to just smash the TAB button to get (Example 3):
```
\begin{align}
\begin{split}
F = ma
\end{split}
\end{align}
```
Example 3 is what ***used to be the case*** but I might have broken something and I don't know what. Now I get Example 2. Also, if I hit the TAB outside of the align environment, I get a huge (12 spaces) displacement, which is also bizarre (previously it wouldn't do that).
I tried adding the following suggestions into my .emacs file:
1. Suggestion in the question and first answer of Confusion by the usage of indent-tabs-mode nil
2. The suggestion in Why is emacs indenting with tabs even though indent-tabs-mode is nil?
# Answer
Looks like I somehow managed to switch to Tex mode, instead of LaTex mode. Changing to LaTex mode is easy: M-x latex-mode. Many thanks to @vonbrand for telling me to check the mode!
> 2 votes
---
Tags: latex, tabs, syntax-table, tex
--- |
thread-64912 | https://emacs.stackexchange.com/questions/64912 | Underscore in if-let | 2021-05-19T13:57:03.693 | # Question
Title: Underscore in if-let
I often find myself wanting to do something like this:
```
(if-let* ((foo (get-foo))
(_ (conditionp foo))
(bar (get-bar-from-foo foo)))
...)
```
As an alternative to:
```
(let ((foo (get-foo)))
(when (and foo (conditionp foo))
(if-let ((bar (get-bar-from-foo)))
...)))
```
The problem is, the underscore is not used so it gives the bytecomp warning: `Warning: variable ‘_’ not left unused`.
I think the first example is much easier to read than the second, is there something similar to the first example which gets around this warning?
# Answer
Since Emacs 26, the underscore (or any variable symbol in general) can be omitted:
```
if-let is a Lisp macro in `subr-x.el'.
(if-let SPEC THEN &rest ELSE)
Probably introduced at or before Emacs version 25.1.
Bind variables according to SPEC and evaluate THEN or ELSE.
Evaluate each binding in turn, as in `let*', stopping if a
binding value is nil. If all are non-nil return the value of
THEN, otherwise the last form in ELSE.
Each element of SPEC is a list (SYMBOL VALUEFORM) that binds
SYMBOL to the value of VALUEFORM. An element can additionally be
of the form (VALUEFORM), which is evaluated and checked for nil;
i.e. SYMBOL can be omitted if only the test result is of <======
interest. It can also be of the form SYMBOL, then the binding of
SYMBOL is checked for nil.
```
So your example can be written as:
```
(eval-when-compile
(require 'subr-x))
(if-let* ((foo (get-foo))
((conditionp foo))
(bar (get-bar-from-foo foo)))
...)
```
> 7 votes
# Answer
Apologies for not helpfully answering the question posed, but hoping this might help anyway...
Instead of something *"similar to the first"*, I'd likely use something that (I think) is simpler than either of them.
Your first example macro-"expands" to code that I think is clearer, than either of your examples:
```
(macroexpand '(if-let* ((foo (get-foo))
(_ (conditionp foo))
(bar (get-bar-from-foo foo)))
X))
```
gives:
```
(let* ((foo (and t (get-foo)))
(_ (and foo (conditionp foo)))
(bar (and _ (get-bar-from-foo foo))))
(if bar X))
```
If I were to code that expansion by hand it would be simpler still:
```
(let* ((foo (get-foo))
(_ (and foo (conditionp foo)))
(bar (and _ (get-bar-from-foo foo))))
(if bar X))
```
And that assumes that the sexps would in reality be more complex. Otherwise I'd probably just use something like this:
```
(let ((foo (get-foo)))
(and foo (conditionp foo) (get-bar-from-foo foo) X))
```
Even just a structural comparison of that with the `if-let*` form shown in @Basil's answer shows that the above sexp is simpler. Remove everything except the parens from each, to compare:
```
(((())(())(()))) ; Simplified `if-let*` form (@Basil's answer)
(((()))(()())) ; Simple `let` shown above
```
> 3 votes
---
Tags: elisp, elisp-conventions
--- |
thread-14652 | https://emacs.stackexchange.com/questions/14652 | attach multiple files from the same directory to an email message? | 2015-08-11T15:51:10.343 | # Question
Title: attach multiple files from the same directory to an email message?
**Q:** how can I attach multiple files to an outbound email with a minimum amount of fuss?
I'm using `mu4e` (which reuses `message-mode`, if that helps) to work with email. I often need to send emails with multiple attachments. `mu4e` uses `mml-attach-file` to handle attachments.
So far so good. However: it's an unpleasant task to use multiple attachments. `mml-attach-file` prompts for each file anew, which is time-consuming when the file is buried deep in a subtree.
It is almost always the case that, when I need to attach multiple files, they are all in the same directory. In this situation, **how can I convince `mml-attach-file` to detect an attachment in the existing message buffer and, if it finds one, use that attachment's directory as the default for the next file I attempt to attach?**
NB: If one digs into the source code, `mml-attach-file` relies on `mml-minibuffer-read-file`, which in turn uses either `mml-default-directory` or `default-directory`.
PS: I'm aware of How to attach multiple files in `message-mode`, but there's no answer there.
# Answer
> 13 votes
I can only suggest a solution for `gnus` and `dired` but it is at least easier as **lawlist** suggested. Open the directory in `dired` with `C-x` `4` `d` and type `M-x turn-on-gnus-dired-mode`. Then mark the required files and type `C-c` `RET` `C-a`. That's it and the files can be attached to an already opened or a new message buffer (I'm not sure if this works for other MUAs as well)!
# Answer
> 3 votes
open up a GUI file browser and drag the files to your emacs draft window/buffer
# Answer
> 3 votes
I like to use helm-find-files for this. You navigate to where the files are, mark the ones you want with C-spc, and attach them with C-c C-a (or press tab and find the attach files to email action).
The ivy equivalent of this is counsel-find-file. First, add this action to it:
```
(ivy-add-actions
'counsel-find-file
'(("a" (lambda (x)
(unless (memq major-mode '(mu4e-compose-mode message-mode))
(compose-mail))
(mml-attach-file x)) "Attach to email")))
```
In this case, you navigate to the files, and type C-M-o then a, and continue to the next file. I don't like this as much as marking them all at once in helm, but I don't often attach many files.
# Answer
> 1 votes
Old post but I got here having the same basic desire and rolled my own snippet to solve it. For others coming here this might be something suitable.
```
(defun compose-attach-marked-files ()
"Compose mail and attach all the marked files from a dired buffer."
(interactive)
(let ((files (dired-get-marked-files)))
(compose-mail nil nil nil t)
(dolist (file files)
(if (file-regular-p file)
(mml-attach-file file
(mm-default-file-encoding file)
nil "attachment")
(message "skipping non-regular file %s" file)))))
```
This code means to attach all marked dired "normal" files to a new message buffer if none exist or add attachments to an existing message buffer. Works perfect here.
# Answer
> 0 votes
Old post, but I want to propose an improvement on @Tompa answer. Here is how to attach multiple files to an existing email:
1. I open a dired buffer and select the files I want to attach
2. I run the following function:
```
(defun attach-marked-files (buffer)
"Attach all marked files to BUFFER"
(interactive "BAttach to buffer: ")
(let ((files (dired-get-marked-files)))
(with-current-buffer (get-buffer buffer)
(dolist (file files)
(if (file-regular-p file)
(mml-attach-file file
(mm-default-file-encoding file)
nil "attachment")
(message "skipping non-regular file %s" file)))))
(switch-to-buffer buffer))
```
3. The function will interactively ask me to which buffer I want to attach the files, and it's done.
---
Tags: email, mu4e, message-mode
--- |
thread-20810 | https://emacs.stackexchange.com/questions/20810 | Get time in AM/PM format | 2016-03-07T09:59:15.543 | # Question
Title: Get time in AM/PM format
`(format-time-string "%p")` is empty in my Emacs. How I can format date in AM/PM format?
That answer second part of Show time in different time zones
**UPDATE**
```
(length (format-time-string "%p")) ; is 0
(getenv "LC_TIME") ; is "en_DK.utf8"
```
My default preferences (in `.emacs`):
```
(setq display-time-24hr-format t)
(setq display-time-day-and-date nil)
```
# Answer
`format-time-string` requires a format together with an actual time to format. So you want to write something like
```
(format-time-string "%p" (current-time))
```
which at the moment outputs `am` for me. Similarly
```
(format-time-string "%l:%M %p" (current-time))
```
currently gives `9:40 am`.
> 2 votes
# Answer
According to Locales section in Elisp manual, the `format-time-string` function is influenced by the system locale configuration. Moreover, the function docstring says "%p is the **locale’s** equivalent of either AM or PM.".
Because of these tips, I wrote the following code to changed the locale temporarily before using the format function:
```
(let ((system-time-locale "en_US.UTF-8"))
(format-time-string "%r %p" (current-time)))
```
After some tries at the scratch buffer, it seems that using the "en\_US.UTF-8" locale prints the "PM"/"AM". These are the results after executing each sexp with `C-j` (`eval-print-last-sexp`):
```
(let ((system-time-locale "en_US.UTF-8"))
(format-time-string "%r %p" (current-time)))
"01:21:33 PM PM"
(let ((system-time-locale "en_DK.UTF-8"))
(format-time-string "%r %p" (current-time)))
"01:21:55 "
(let ((system-time-locale "en_UK.UTF-8"))
(format-time-string "%r %p" (current-time)))
"01:22:14 "
```
> 2 votes
# Answer
Inside the emacs manual there is this page: https://www.gnu.org/software/emacs/manual/html\_node/emacs/Time-Display-Format.html. that talks about changing the time format.
The following code should do what you want if I understand correctly.
```
(setq display-time-24hr-format nil)
(setq display-time-string-forms
'(12-hours ":" minutes am-pm))
```
> 0 votes
---
Tags: time-date
--- |
thread-64907 | https://emacs.stackexchange.com/questions/64907 | Pseudo-terminal will not be allocated because stdin is not a terminal. ssh_askpass: exec(/usr/libexec/openssh/ssh-askpass): No such file or directory | 2021-05-19T07:12:33.143 | # Question
Title: Pseudo-terminal will not be allocated because stdin is not a terminal. ssh_askpass: exec(/usr/libexec/openssh/ssh-askpass): No such file or directory
CentOS 7, Emacs 27.1
Here content of file **myFile.sh**:
```
ssh myuser@10.111.11.111
```
So when in **vterm** mode I use this:
```
./myFile.sh
```
then I success connect to the remote machine (ip = 10.111.11.111) by Tramp mode.
Nice.
Now I want to run **myFile.sh** in **dired** mode. Here folder with myFile.sh in dired mode.
So I try
```
! (dired-do-shell-command)
```
As result in the minibuffer show.
Then in the minibuffer I input
```
./myFile.sh
```
and press **Enter**.
But I get error:
```
Pseudo-terminal will not be allocated because stdin is not a terminal.
ssh_askpass: exec(/usr/libexec/openssh/ssh-askpass): No such file or directory
Permission denied, please try again.
ssh_askpass: exec(/usr/libexec/openssh/ssh-askpass): No such file or directory
Permission denied, please try again.
ssh_askpass: exec(/usr/libexec/openssh/ssh-askpass): No such file or directory
Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).
```
# Answer
You must add the arguments "-t -t" to your ssh call (yes, "-t" twice).
> 0 votes
---
Tags: dired, ssh, shell-command
--- |
thread-64927 | https://emacs.stackexchange.com/questions/64927 | Weird error on org-capture | 2021-05-20T13:55:42.897 | # Question
Title: Weird error on org-capture
I got my command for `Ctrl+C - c - t` (i.e. invoke org-capture) slightly wrong (i.e. missed a key or something when trying to type it). I know I got it wrong because it didn't work but instead changed something in one of my open buffers slightly (sorry, I can't remember what, and I don't know what key I mistyped). Now, if I try to use Ctrl+C-c-t again, it's giving me the following debug error:
```
Debugger entered--Lisp error: (error "Selection owner couldn't convert" UTF8_STRING)
x-get-selection-internal(CLIPBOARD UTF8_STRING nil nil)
#f(compiled-function (selection-symbol target-type &optional time-stamp terminal) #<bytecode 0x1fe12375f05f>)(CLIPBOARD UTF8_STRING)
apply(#f(compiled-function (selection-symbol target-type &optional time-stamp terminal) #<bytecode 0x1fe12375f05f>) (CLIPBOARD UTF8_STRING))
gui-backend-get-selection(CLIPBOARD UTF8_STRING)
gui-get-selection(CLIPBOARD UTF8_STRING)
gui--selection-value-internal(CLIPBOARD)
gui-selection-value()
current-kill(0)
org-capture-fill-template()
org-capture(nil)
funcall-interactively(org-capture nil)
call-interactively(org-capture nil nil)
command-execute(org-capture)
```
This is entirely opaque to me -- any idea what it might be and how to fix it?
# Answer
The command `view-lossage`, bound to `C-h l` by default, will display the last few input keystrokes and the commands run. This can be helpful when trying to untangle the consequences of a mis-pressed key.
> 1 votes
---
Tags: org-mode, org-agenda, org-capture
--- |
thread-64924 | https://emacs.stackexchange.com/questions/64924 | Cyrillic and other characters show as numerals enclosed in \ slashes | 2021-05-20T11:15:26.603 | # Question
Title: Cyrillic and other characters show as numerals enclosed in \ slashes
When I use Cyrillic characters, a pound sign (£), degree sign and others, they appear as figures enclosed by forward slashes when I open the file again. How can I prevent this?
# Answer
> 1 votes
Do you mean a sequence of 3 octal numerals preceded by a backslash? Or do you really mean a sequence of "figures" (numerals?) *enclosed* by two backslashes?
If the former, you're likely seeing a character's code represented in octal form.
1. In that case, first see if the value of variable `ctl-arrow` is `nil`, and if so whether changing the value to non-`nil` helps. `C-h v ctl-arrow`:
> `ctl-arrow` is a variable defined in `C source code`.
>
> Its value is `t`
>
> Automatically becomes buffer-local when set.
>
> Documentation:
>
> Non-`nil` means display control chars with uparrow.
>
> A value of `nil` means use backslash and octal digits. This variable does not apply to characters whose display is specified in the current display table (if there is one).
>
> You can customize this variable.
2. Second, try a different font - perhaps your font just can't display those particular Cyrillic characters.
3. Read the Emacs manual, node Text Display, where it says this:
> The raw bytes with codes `U+0080` (octal 200) through `U+009F` (octal 237) are displayed as “octal escape sequences”, with the `escape-glyph` face. For instance, character code ‘U+0098’ (octal 230) is displayed as `\230`. If you change the buffer-local variable `ctl-arrow` to `nil`, the ASCII control characters are also displayed as octal escape sequences instead of caret escape sequences.
4. See also the Elisp manual, node Usual Display, where it says this:
> “Raw bytes” are non-ASCII characters with codes 128 through 255 (See Text Representations). These characters display as “octal escapes”: sequences of four glyphs, where the first glyph is the ASCII code for `\`, and the others are digit characters representing the character code in octal. (A display table can specify a glyph to use instead of `\`.)
---
Tags: character-encoding
--- |
thread-64930 | https://emacs.stackexchange.com/questions/64930 | How to temporarily change the definition of a function? | 2021-05-20T16:03:44.650 | # Question
Title: How to temporarily change the definition of a function?
In the following code the function `foo` calls the outer `f2` function. How to make it call the anonymous function bound within the `let`?
```
(defun f2 ()
(message "outer f2"))
(defun foo ()
(f2))
(let ((f2 (lambda ()
(message "inner f2"))))
(foo)) ;; `foo' does not call `f2' in the `let', i.e. prints "outer f2"
```
# Answer
> How to temporarily change the definition of a function?
Calling a function by its (symbol) name means calling that symbol's function slot. So, to temporarily change the definition of a function that is called by its name, you need to temporarily modify its `symbol-function` value. The shortest way to do that is with `cl-letf`; see `(info "(cl) Modify Macros")`.
```
(eval-when-compile
(require 'cl-lib))
(defun f2 ()
(message "outer f2"))
(defun foo ()
(f2))
(cl-letf (((symbol-function 'f2)
(lambda () (message "inner f2"))))
(foo)) ;; => inner f2
```
An alternative, more compositional approach is to use function advice, but to my knowledge there isn't a handy macro for that, and it doesn't provide any benefits in simple cases like the example above. For example:
```
(unwind-protect
(progn
(advice-add 'f2 :override
(lambda () (message "inner f2"))
'((name . my-override)))
(foo))
(advice-remove 'f2 'my-override)) ;; => inner f2
```
> 5 votes
---
Tags: functions, lexical-scoping, dynamic-scoping
--- |
thread-64901 | https://emacs.stackexchange.com/questions/64901 | How can I specify the maximum number of windows | 2021-05-18T22:26:46.997 | # Question
Title: How can I specify the maximum number of windows
I like to work with two windows split horizontally or vertically. However, when I try to use `C-x 4 f` (`ido-find-file-other-window`) when I already have two windows, it will split one of my windows so I have a total of three windows. How can I change this behavior so that no more than two windows should ever be open?
# Answer
Actually, the option `pop-up-window` controlls the generation of new windows.
The pitfall is, that there are commands that locally bind that variable to t.
The command `switch-to-buffer-other-window` is such a command that is especially relevant for your problem, since `ido-find-file-other-window` uses it.
The strategy for displaying buffers is controlled by a chain of action lists for the command `display-buffer`.
Normally, all action lists but `display-buffer-fallback-action` are set to `(nil)` which means "no action in this list".
The last action list `display-buffer-fallback-action` cannot be modified by the user and it has the following value:
```
((display-buffer--maybe-same-window display-buffer-reuse-window
display-buffer--maybe-pop-up-frame-or-window
display-buffer-in-previous-window display-buffer-use-some-window
display-buffer-pop-up-frame))
```
The option `pop-up-window` is used in `display-buffer--maybe-pop-up-window` (called from `display-buffer--maybe-pop-up-frame-or-window`) to block the call of `display-buffer-pop-up-window`.
Since we do not have full control over `pop-up-window` in a non-hacky way we need to override `display-buffer-fallback-action` with a similar action list like `display-buffer-fallback-action` that does only split the window if it is the only one of the frame. We use `display-buffer-base-action` for that purpose which is processed before `display-buffer-fallback-action`:
```
(defun display-buffer-2-windows (buffer alist)
"If only one window is available split it and display BUFFER there.
ALIST is the option channel for display actions (see `display-buffer')."
(when (eq (length (window-list nil 'no-minibuf)) 1)
(display-buffer--maybe-pop-up-window buffer alist)))
(setq display-buffer-base-action
'((display-buffer--maybe-same-window
display-buffer-reuse-window
display-buffer--maybe-pop-up-frame
display-buffer-2-windows
display-buffer-in-previous-window
display-buffer-use-some-window
display-buffer-pop-up-frame)))
```
> 2 votes
---
Tags: window-splitting, ido-find-file
--- |
thread-64938 | https://emacs.stackexchange.com/questions/64938 | org-map-entries says "Wrong type argument: char-or-string-p, nil" | 2021-05-21T14:16:56.703 | # Question
Title: org-map-entries says "Wrong type argument: char-or-string-p, nil"
I have this code:
```
(defun org-get-logbook-notes ()
(save-excursion
(unless (org-at-heading-p)
(outline-previous-heading))
(when (re-search-forward ":LOGBOOK:" (save-excursion
(outline-next-heading)
(point))
t)
(let* ((elt (org-element-property-drawer-parser nil))
(beg (org-element-property :contents-begin elt))
(end (org-element-property :contents-end elt)))
(buffer-substring-no-properties beg end)))))
(require 's)
(defun my/org-rotten-set ()
(interactive "P")
(setq lognotes (org-get-logbook-notes))
(setq numresched (number-to-string (s-count-matches "Rescheduled from" lognotes)))
(org-entry-put nil "ROTTEN" numresched ))
```
What it should do is simply the following task:
* Get the contents of the :LOGBOOK: drawer
* Count how many times the string "Rescheduled from" occurs
* Transform this into a number and create a property "ROTTEN" with this number as a value
If I use IELM, place the point inside a single entry in my orgfile and execute
```
ELISP> (my/org-rotten-set)
```
This works perfectly fine. The occurences of "Rescheduled from" will be count, the "ROTTEN" property will be created.
Now if I try to use this function together with org-map-entries it doesn't work.
```
ELISP> (org-map-entries 'my/org-rotten-set)
*** Eval error *** Wrong type argument: char-or-string-p, nil
```
What am I doing wrong here? It seems to be related to the org-get-logbook-notes function that I defined a the beginning, but I have no idea why?
# Answer
`org-map-entries` operates on whatever you specify as its SCOPE (see the doc string for details). Since you have not expicitly specified the scope in your call, it is `nil`: that means it operates on the current buffer (respecting the restriction, if any - but that's unimportant here). The main point is that you are executing it in the IELM buffer, so that's the current buffer, *not* your Org mode file.
Try
```
(with-current-buffer (get-buffer "name of your Org mode file here")
(org-map-entries #'my/org-rotten-set))
```
But there is a problem in `my/org-rotten-set` that you need to fix: if there is no `LOGBOOK` drawer in an entry, `(org-get-logbook-notes)` will return `nil` and that will cause `s-count-matches` to give you the error you get: " (wrong-type-argument char-or-string-p nil)". You need to check the return value and do nothing if it is nil:
```
(defun my/org-rotten-set ()
(interactive)
(setq lognotes (org-get-logbook-notes))
(when lognotes
(setq numresched (number-to-string (s-count-matches "Rescheduled from" lognotes)))
(org-entry-put nil "ROTTEN" numresched )))
```
It's also better to use let-bound variables in the function, rather than using `setq` and global variables :
```
(defun my/org-rotten-set ()
(interactive)
(let ((lognotes (org-get-logbook-notes)))
(when lognotes
(org-entry-put nil "ROTTEN" (number-to-string
(s-count-matches "Rescheduled from" lognotes))))))
```
Another (less likely) problem is that if the string ":LOGBOOK:" occurs in the file (outside the context of a LOGBOOK drawer), `org-get-logbook-entries` might get confused. I'll leave that problem for the interested reader to pursue :-)
> 1 votes
---
Tags: org-mode
--- |
thread-10353 | https://emacs.stackexchange.com/questions/10353 | how to remove the red underline | 2015-03-27T18:18:08.413 | # Question
Title: how to remove the red underline
Occasionally I have this ugly red underline in my python code. It seems not related to any flymake error/warnings. Does anyone know why it shows and how it can be removed? Thanks!
I am using latest elpy and emacs (24.4) on Mac OSX 10.9
The problem only occurs occasionally (but very annoying). Now it happens again. Here is the output of `describe-char` on a SPACE character in red underline region:
```
position: 848 of 1960 (43%), column: 6
character: SPC (displayed as SPC) (codepoint 32, #o40, #x20)
preferred charset: ascii (ASCII (ISO646 IRV))
code point in charset: 0x20
script: latin
syntax: which means: whitespace
category: .:Base, a:ASCII, l:Latin
to input: type "C-x 8 RET HEX-CODEPOINT" or "C-x 8 RET NAME"
buffer code: #x20
file code: #x20 (encoded by coding system utf-8-unix)
display: by this font (glyph code)
mac-ct:-*-Menlo-normal-normal-normal-*-12-*-*-*-m-0-iso10646-1 (#x03)
Character code properties: customize what to show
name: SPACE
general-category: Zs (Separator, Space)
decomposition: (32) (' ')
There are 4 overlays here:
From 42 to 1961
semantic [Show]
From 400 to 1961
face semantic-unmatched-syntax-face
semantic unmatched
From 517 to 1469
semantic [Show]
From 531 to 1961
face semantic-unmatched-syntax-face
semantic unmatched
There are text properties here:
face font-lock-string-face
fontified t
[back]
```
# Answer
When you spot a problem in the way how emacs behaves and if that happens only when you load your emacs config (`init.el` or `.emacs`) and not when you run `emacs -Q`, you need to bisect your init to find the culprit as @Drew mentioned in the comments.
Fortunately, you don't have to bisect your init in this case as you have a tangible visual clue of the problem.
The visual problem is that you get the red underlines which you don't want. As it is visual, you can always figure out what's causing that formatting by following these steps:
1. Move the point to one of that characters that has the unwanted red underline.
2. Do `M-x describe-char`.
3. Find out which faces are active for that character (from the information that the above step prints out).
4. *Grep* for that face name in your `elpa/` (technically the directory name saved in `package-user-dir` variable) directory. If that does not yield any results, repeat the grep in the emacs source code `lisp/` directory. This step will tell you which package and function(s) assigned that face to that string.
5. Once you figure out the function name(s) assigning this face, you need to figure out where you are calling that(those) function(s); *grep* for it(them) in your `~/.emacs.d` (technically the directory name saved in `user-emacs-directory`).
That will tell you which piece of code is enabling those faces.
*PS: Though bisecting the init is default way to debug your emacs setup issues.*
> 8 votes
# Answer
Following @Kaushal Modi's answer, the offending face, for me, was `nobreak-space`. I removed the face with:
```
(set-face-attribute 'nobreak-space nil :underline 'unspecified :inherit 'unspecified)
```
> 1 votes
---
Tags: python, elpy
--- |
thread-64945 | https://emacs.stackexchange.com/questions/64945 | How use rgrep for only org AND java files? | 2021-05-21T20:22:21.200 | # Question
Title: How use rgrep for only org AND java files?
Linux Mint 20
Emacs 27.2
I want to find text **end** in the org files in my folder (recursively). So I use **rgrep**
```
M-x rgrep
*.org
```
Here steps:
step 1:
step 2:
step 3 (result):
Nice. As result I found text **end** only in the org files.
But... now I want to found text **end** in the **org** files AND **java** files.
How I can do this?
```
M-x rgrep
*.org, *.java not help
```
# Answer
> 4 votes
Instead of `*.org, *.java`, say `*.org *.java` at the second prompt (no comma).
Note: to input in such completion prompt, type `C-q SPC` (that is, hold `Ctrl` and press `q`, then release `Ctrl` and hit `Space`).
---
Tags: rgrep
--- |
thread-64947 | https://emacs.stackexchange.com/questions/64947 | Bulk convert text under heading to individual sub-headings? | 2021-05-21T22:02:34.833 | # Question
Title: Bulk convert text under heading to individual sub-headings?
I have this in an org-mode buffer
```
* Synonyms
culture
discipline
improvement
information
learning
literacy
scholarship
```
and would like to simply highlight this list starting with `culture` and ending with `scholarship` and turn them all into sub-headings directly under `Synonyms`. Is this possible, already a feature? I realize I can put the cursor in front of each entry and hit M-Enter, but is a bulk way possible?
# Answer
`C-c *` on region to run `org-ctrl-c-star`
> 4 votes
# Answer
As @nichijou points out, `C-c *` on the region will turn a sequence of plain lines into a sequence of headings (and vice-versa: in this context, `org-ctrl-c-star` runs the function `org-toggle-heading` which turns text to headings or headings to text - you should do `C-h f` on each of these functions to find out more about it, e.g. what happens with list items).
Similarly, `C-c -` on a region turns a sequence of lines into a sequence of list items (and vice-versa: as you might have guessed `C-c -` is bound to the function `org-ctrl-c-minus` which in this context runs `org-toggle-item`).
The main point of this however, is that instead of asking on Emacs SE, you can really make your life easier by *asking Emacs itself*. E.g. in this case, you might start by doing an `apropos` search for commands that match `org` and `heading`: `C-c a org heading` \- that will get you a list of a dozen or so matching commands with one-line descriptions, the last of which is the aforementioned `org-toggle-heading` whose description reads: `Convert headings to normal text, or items or text to headings.` Bingo!
You can then ask for help on the function with `C-h f org-toggle-heading` and you can look for it in the manual with `C-h i g (org) org-toggle-heading` which will point you to the C-c \*\` keybinding.
You might think that this is 20-20 hindsight, but if you keep at it for a little bit, you will find that the Emacs documentation system is the bee's knees, and if you learn to use it effectively (which is not that hard to do), you will be able to answer the vast majority of your questions much faster than you can type the question on Emacs SE (and maybe in a little while, faster than you can type "Emacs SE", let alone typing the question :-) )
> 2 votes
---
Tags: org-mode, outline
--- |
thread-64951 | https://emacs.stackexchange.com/questions/64951 | lsp-mode tramp auto-completions | 2021-05-22T04:55:41.420 | # Question
Title: lsp-mode tramp auto-completions
Ive set up remote lsp-mode with tramp and pylsp server. While the server does start when I open a remote py file, many server features such as auto completions, code format, references dont work.
Here is my setup
```
(eval-when-compile
(require 'use-package))
(use-package lsp-mode
:hook (python-mode . lsp)
:config
(lsp-register-client
(make-lsp-client :new-connection (lsp-tramp-connection "pylsp")
:major-modes '(python-mode)
:remote? t
:server-id 'pyls-remote)))
;; Set tramp remote path
(add-to-list 'load-path "/usrlocal/share/emacs/site-lisp/")
(require 'tramp)
(add-to-list 'Info-directory-list "/usr/local/share/info/")
(add-to-list 'tramp-remote-path "~/envs/general/bin")
(add-to-list 'tramp-remote-path 'tramp-own-remote-path)
(use-package company
:ensure t
:diminish company-mode
:hook (prog-mode . global-company-mode)
:commands (company-mode company-indent-or-complete-common)
:init)
```
# Answer
Oh there's a typo
```
(add-to-list 'load-path "/usrlocal/share/emacs/site-lisp/")
```
should be (add-to-list 'load-path "/usr/local/share/emacs/site-lisp/")
Cant believe I spent 40+ hours debugging this
> 0 votes
---
Tags: tramp, lsp-mode
--- |
thread-64556 | https://emacs.stackexchange.com/questions/64556 | How to suppress warning about positional arguments in define-minor-mode | 2021-04-23T17:57:47.050 | # Question
Title: How to suppress warning about positional arguments in define-minor-mode
I am on Emacs 28.0.5 and keep getting warnings about:
```
Warning: Use keywords rather than deprecated positional arguments to `define-minor-mode'
```
Unfortunately it is for packages I don't control like lsp-mode. I would like to suppress the warning using something like (I use radian Emacs config, hence the use of use-feature for Emacs-provided packages - imagine a require 'warnings if you are more familiar with that):
```
(use-feature warnings
:config
(add-to-list 'warning-suppress-log-types '(what-to-put-here?)))
```
but apparently I am not passing the type that warning-suppress-log-types expects for this warning to be picked up because it keeps happening when lsp-mode loads (I won't bore you with all the incantations that I've tried in 'what-to-put-here?'. If you read the source for define-minor-mode you'll see that the way the warning is generated is perhaps non-standard, i.e., it doesn't seem to call display-warning. Do you know a way to make it stop generating this message?
I'd do a pull request to lsp-mode, but I am an outlier by using such a bleeding edge Emacs version and I don't imagine they'll want to accommodate that version in the common case.
Note: I have filed an issue with lsp-mode in the meantime.
# Answer
This is already fixed in 7.1 version - lsp-mode is now using the emacs new keyword syntax for minor modes.
> 1 votes
# Answer
Well, turns out radian Emacs config provides an advice for such things:
```
(dolist (func '(define-minor-mode))
(advice-add func :around #'radian--advice-silence-messages))
```
which you can add to your init.local.el.
Here is its definition:
```
(defun radian--advice-silence-messages (func &rest args)
"Invoke FUNC with ARGS, silencing all messages. This is an `:around' advice for many different functions."
(cl-letf (((symbol-function #'message) #'ignore))
(apply func args)))
```
> 1 votes
---
Tags: lsp-mode, warning
--- |
thread-64959 | https://emacs.stackexchange.com/questions/64959 | capture the content of buffer as a list | 2021-05-22T18:03:59.553 | # Question
Title: capture the content of buffer as a list
I want to pass a buffer's content into a list. I figured out how to read the content of the buffer I want to use but cannot figure out how to correctly capture the content and then use it as a list.
Let's say I have a buffer called "test" whose content is `"A" "B" "C"`
I've written the following to extract the content
```
(with-current-buffer "test"
(setq list-of-variables (buffer-substring-no-properties (point-min)(point-max)))
)
(message "%S" list-of-variables)
```
The output I got so far literally is `" \"A\" \"B\" \"C\" "` which is clearly useless as it is not recognized as a proper list...
# Answer
> 0 votes
```
(with-current-buffer "test"
(setq list-of-variables (split-string (substring-no-properties (buffer-string))))
)
```
which renders
```
("\"A\"" "\"B\"" "\"C\"")
```
You can prefer
```
(with-current-buffer "test"
(setq list-of-variables
(split-string (substring-no-properties (buffer-string))"\"" t " "))
)
```
which renders
```
("A" "B" "C")
```
---
Tags: list, string
--- |
thread-64964 | https://emacs.stackexchange.com/questions/64964 | Difference between [mouse-1] and [down-mouse-1] | 2021-05-23T07:48:07.137 | # Question
Title: Difference between [mouse-1] and [down-mouse-1]
I noticed two keys: `[mouse-1]` and `[down-mouse-1]`.
When I use `describe-key` with a single click, it shows:
```
There were several key-sequences:
<down-mouse-1> at that spot runs the command evil-mouse-drag-region
<mouse-1> at that spot runs the command mouse-set-point
```
If I want to bind a function to a single click event, which key is better?
Besides, when clicking the mouse, how to only trigger a single key sequence, either `<down-mouse-1>` or `<mouse-1>` but not both?
# Answer
`down-mouse-1` is a "button-down" event which is generated immediately when you press the mouse button.
`mouse-1` is a "click" event, which is generated if you release the button at the same position as the "button-down" event.
`drag-mouse-1` is a "drag" event which would be generated if you released the button at a different position.
You can learn about these and more at `C-h``i``g` `(elisp)Input Events`
> 8 votes
---
Tags: key-bindings, mouse
--- |
thread-64965 | https://emacs.stackexchange.com/questions/64965 | Can't type SPC in second prompt on rgrep | 2021-05-23T08:20:51.667 | # Question
Title: Can't type SPC in second prompt on rgrep
Linux Mint 20, Emacs 27.2
I want to find text "end" in the org files AND java files in my folder (recursively). So I use **rgrep**
```
M-x rgrep
```
Step1
Step2
But when I try to input `*.org SPC *.java`, I can't type `SPC`. I get message `"No match"`
I know that I can use `C-q SPC` but I want type `SPC` only by type `SPC`
# Answer
> 1 votes
`C-h``k``SPC` tells us:
```
SPC runs the command minibuffer-complete-word (found in
minibuffer-local-completion-map), which is an interactive compiled
Lisp function in ‘minibuffer.el’.
Complete the minibuffer contents at most a single word.
After one word is completed as much as possible, a space or hyphen
is added, provided that matches some possible completion.
Return nil if there is no valid completion, else t.
```
Which firmly suggests that changing this particular binding is going to affect more than just `rgrep` prompts. Still, you can do this as follows if you wish to:
```
(define-key minibuffer-local-completion-map (kbd "SPC") nil)
```
You've already mentioned one workaround with `C-q``SPC` but there's another one which is almost as easy to type as `SPC` itself:
`M-SPC` runs `cycle-spacing` which, in the absence of any space at point, inserts a single space. YMMV, but this binding is sufficiently convenient for me to not care when `SPC` has a non-space binding.
---
Tags: rgrep
--- |
thread-64968 | https://emacs.stackexchange.com/questions/64968 | Open two files on startup - how to set vertical split as default? | 2021-05-23T13:30:33.470 | # Question
Title: Open two files on startup - how to set vertical split as default?
When I invoke Emacs from the shell with the command `emacs fileA fileB`, I'd like to have the Emacs window split vertically (i.e. with one file on the left and one file on the right), not horizontally, to show the two buffers. How should I edit my .emacs configuration file?
# Answer
> 1 votes
If you don't care which file goes on the right and which file goes on the left, try the following init file:
```
(setq inhibit-splash-screen t)
(split-window-horizontally)
```
And yes: `split-window-horizontally` splits it vertically in your terminology :-) Emacs's terminology is different from yours.
---
Tags: init-file, window-splitting
--- |
thread-64467 | https://emacs.stackexchange.com/questions/64467 | How to make GNU Emacs start automatically right after booting and start with having much used files in buffers? | 2021-04-17T21:01:38.533 | # Question
Title: How to make GNU Emacs start automatically right after booting and start with having much used files in buffers?
When I switch on my computer, 1st things I do: Open GNU Emacs, C-x C-f \[file name A\], Enter, C-x C-f \[file name B\], Enter, C-x b, Enter - in doing so going back to buffer of file A - C-x s, es - searching for a certain spot in file A - C-c C-o - opening a link in the web browser
That happens every day without an exeption! Day by day, can't that be automated some how to save time & effort?
How? I have some ideas, but finally am too unexperienced in making it work - I also can't program, yet. I assume a kbd macro of said steps could be placed into that so called init file. But this vague idea isn't enough, and still one open question is how to make GNU Emacs start automatically every time I switch on or restart the computer.
The file /GNU Emacs/ is appreciated as being in a buffer every session. I would keep that. It's just that I want a different file as being a landing page or '1st thing displayed after starting my GNU Emacs'.
I am using GNU Emacs 24.5.1 on a fully free/libre GNU/Linux distribution - free as in freedom.
Issue halfway solved: Automatic start of GNU Emacs right after booting & restarting of the computer works! And it's really easy to achieve: Probably at least most GNU/Linux OS have a desktop task bar with menu button. Clicking on this and navigating through the menu options one can get to a place like 'System \> Preferences \> Personal \> Startup Applications'. This path leads to an options window where there are already some programs set as startup applications, and all what has to be done from there is clicking on the 'add' button and adding GNU Emacs to that list this way.
So, all what still needs to be solved now is: 'How to make those couple of first actions right after start of GNU Emacs automatically?' I still think that best grab would be to somehow make any of those spots with init files also contain a kbd macro, which gets triggered as 1st action after the general GNU Emacs startup. But how does that work? I've looked into the manual and GNU Emacs regarding init files and got very confused and frustrated: There is not just 1 spot for the init file, there are a couple of spots for or with init files! And I don't have a clue what spot to prefer for editing an init file for what reason and how many init files are necessary on my system, anyway. And when you look at videos or elsewhere around, anybody says something else, uses a different spot for making an init file or init file edit. I just can't tell: What way is appropriate or the best in my case. And I don't know, if it's possible, at all, to edit the init structure in a way that it ends startup with executing a kbd macro.
Update: We're up to something thanks to alephnull! The plan: Adding a function to emacs-startup-hook, which executes the couple of steps I do by hand whenever I start an emacs session.
The thing is this: I've tried to put this hint into action, but it has no effect on how emacs starts - as if I haven't changed anything at /.emacs .
Here's what I have done:
1. Making the function, which is supposed to execute the things I do manually whenever an GNU Emacs session starts.
For that I made a kbd macro, and saved it in form of lisp code on my computer, so that I can copy and paste the snippet later.
```
1.2. Making kbd macro
1.2.1. C-x ( ;; starting kbd macro definition
1.2.2. C-x C-f testfile A ;; find testfile A
1.2.3. C-x ) ;; end kbd macro definition
1.3. Saving kbd macro
1.3.1. C-x C-k n kbd macro 1 ;; naming the kbd macro "kbd macro 1" for saving
1.3.2. M-x insert-kbd-macro ;; still being in testfile A now the following lisp code is in the file:
(fset 'kbd\ macro\ 1
(lambda (&optional arg) "Keyboard macro." (interactive "p") (kmacro-exec-ring-item (quote ([24 6 116 101 115 116 102 105 108 101 32 65 return] 0 "%d")) arg)))
```
2. Editing /.emacs
Before:
```
(custom-set-variables
;; custom-set-variables was added by Custom.
;; If you edit it by hand, you could mess it up, so be careful.
;; Your init file should contain only one such instance.
;; If there is more than one, they won't work right.
'(ansi-color-faces-vector
[default default default italic underline success warning error])
'(ansi-color-names-vector
[ *certain values* ])
'(browse-url-browser-function (quote browse-url-generic))
'(browse-url-generic-program
" *path of certain program* ")
'(custom-enabled-themes (quote ( *certain theme* )))
'(desktop-save-mode nil))
(custom-set-faces
;; custom-set-faces was added by Custom.
;; If you edit it by hand, you could mess it up, so be careful.
;; Your init file should contain only one such instance.
;; If there is more than one, they won't work right.
)
```
After:
I assumed that inserting the hook should be done right after the line with `'(desktop-save-mode nil))` in a new line, have the same format as the other lines, and incorporate only the lambda-part.
```
(custom-set-variables
;; custom-set-variables was added by Custom.
;; If you edit it by hand, you could mess it up, so be careful.
;; Your init file should contain only one such instance.
;; If there is more than one, they won't work right.
'(ansi-color-faces-vector
[default default default italic underline success warning error])
'(ansi-color-names-vector
[ *certain values* ])
'(browse-url-browser-function (quote browse-url-generic))
'(browse-url-generic-program
" *path of certain program* ")
'(custom-enabled-themes (quote ( *certain theme* )))
'(desktop-save-mode nil)
'(add-hook 'emacs-startup-hook (lambda (&optional arg) "Keyboard macro." (interactive "p") (kmacro-exec-ring-item (quote ([24 6 116 101 115 116 102 105 108 101 32 65 return] 0 "%d")) arg))))
(custom-set-faces
;; custom-set-faces was added by Custom.
;; If you edit it by hand, you could mess it up, so be careful.
;; Your init file should contain only one such instance.
;; If there is more than one, they won't work right.
)
```
I've saved /.emacs & testfile A like that. From that point on I expected and hoped, that when I start Emacs, first thing I see will be a buffer containing testfile A. But that didn't happen. Instead I still saw *GNU Emacs* as the first thing after GNU Emacs start.
How come that said edit has no effect? Actually to my understanding my init file /.emacs should end with doing the sequence of actions stored in the kbd macro. But that doesn't happen *puzzled* ...
# Answer
You probably want to start with desktop-save-mode.
There are parts to your question which I have not addressed.
* starting emacs automatically on boot, this is usually OS specific
* opening recently used files
With desktop-save-mode, unless something bad happens, restarting emacs will bring you back to exactly where you were including registers, tab/window configuration...
> 4 votes
# Answer
> Problem #1: What I want is rather like a specific desktop checkpoint, which doesn't change, which is always the same, no matter what buffers I open or close on top of it within a session. `desktop-save-mode`, however, seems to take every change.
You could create and use a separate desktop file with your desired start-up configuration like this:
```
;; To prepare the start-up desktop file...
;; 1. Run a separate temporary instance of Emacs, and within that:
;; 2. M-x make-directory RET ~/.emacs.d/start RET
;; 3. M-x desktop-change-dir RET ~/.emacs.d/start RET
;; 4. Visit files, etc -- create the configuration you wish to store
;; 5. M-x desktop-save-in-desktop-dir
;; 6. Quit the temporary instance of Emacs
;; 7. Add the following to your regular init file
(let (desktop-dirname)
(desktop-read "~/.emacs.d/start")
(desktop-release-lock))
```
> 2 votes
---
Tags: start-up
--- |
thread-64976 | https://emacs.stackexchange.com/questions/64976 | org-mode: Make C-a and C-e go to beginning or ending of logical line | 2021-05-24T02:06:05.587 | # Question
Title: org-mode: Make C-a and C-e go to beginning or ending of logical line
What I'm trying to do is have C-a and C-e take me to the beginning or ending, respectively, of the *logical* line, not the visual line, in org-mode (with visual-line-mode active). I see that C-a is mapped to org-beginning-of-line, which, like a lot of org-mode things, seems to be context-dependent.
Here's what I'm trying.
```
(define-key org-mode-map (kbd "C-a") 'move-beginning-of-line)
(define-key org-mode-map (kbd "C-e") 'move-end-of-line)
```
This seems to do nothing. `C-h k` followed by `C-a` still shows it's still mapped to org-beginning-of-line. I also tried using the angle bracket form of calling kbd: `(kbd "<C-a>")`, which made no difference.
If it helps, here's what I get when I do `C-h m`:
```
Enabled minor modes: Auto-Composition Auto-Compression Auto-Encryption
Blink-Cursor Electric-Indent File-Name-Shadow Font-Lock Global-Eldoc
Global-Font-Lock Global-Visual-Line Line-Number Mac-Mouse-Wheel
Menu-Bar Show-Paren Tool-Bar Tooltip Transient-Mark Visual-Line
```
**Update**: both @Tyler and @NickD solved the problem with their answers. Also it turns out the visual-line-mode-map had a remapping as well, which also needed to be unmapped. Here's specifically what I added to my .emacs file to solve the entire thing:
```
(add-hook 'visual-line-mode-hook
(lambda ()
(define-key visual-line-mode-map [remap move-beginning-of-line] nil)
(define-key visual-line-mode-map (kbd "C-a") 'move-beginning-of-line)
(define-key visual-line-mode-map [remap move-end-of-line] nil)
(define-key visual-line-mode-map (kbd "C-e") 'move-end-of-line)))
(add-hook 'org-mode-hook
(lambda ()
(define-key org-mode-map [remap move-beginning-of-line] nil)
(define-key org-mode-map (kbd "C-a") 'move-beginning-of-line)
(define-key org-mode-map [remap move-end-of-line] nil)
(define-key org-mode-map (kbd "C-e") 'move-end-of-line)))
```
# Answer
> 1 votes
Org-mode remaps `move-beginning-of-line` to `org-beginning-of-line`. Consequently, any keybinding you attach to `move-beginning-of-line` will call `org-beginning-of-line`. To undo this, you need to undo the remapping:
```
(define-key org-mode-map [remap move-beginning-of-line] nil)
(define-key org-mode-map (kbd "C-a") 'move-beginning-of-line)
```
# Answer
> 0 votes
Org mode remaps `move-beginning-of-line` to `org-beginning-of-line` using this code (in `org-keys.el`):
```
(org-remap org-mode-map
...
'move-beginning-of-line 'org-beginning-of-line
'move-end-of-line 'org-end-of-line
...
)
```
(where I have elided a bunch of other remappings).
I don't understand the mechanism well enough to provide a decent explanation (which is also a warning to take the following suggestion with a large grain of salt), but remapping them afterwards to themselves seems to work (no guarantees, if it breaks you own it, etc.):
```
(with-eval-after-load "org-keys"
(org-remap org-mode-map
'move-beginning-of-line 'move-beginning-of-line
'move-end-of-line 'move-end-of-line))
```
---
Tags: org-mode
--- |
thread-48563 | https://emacs.stackexchange.com/questions/48563 | Prevent mouse click from changing cursor position while in insert mode | 2019-03-24T22:21:40.483 | # Question
Title: Prevent mouse click from changing cursor position while in insert mode
I work on a laptop most of the time and it happens somewhat often that while inserting some text (in evil mode) I will accidentally hit the touchpad with my thumb, changing the cursor position and causing the next few words to be inserted into some unrelated paragraph. The somewhat annoying thing is that undo is usually of no help here, because the last saved undo state is whenever I entered insert mode and I might have written several sentences since then that I don't want to lose. I'd rather not completely disable use of the mouse, so I'm hoping to implement one of the following acceptable fixes:
* Don't allow mouse clicks to change position while in evil insert mode, only in normal mode (this sounds the simplest).
* Update the undo state whenever I change cursor position with the mouse, if there is a callback for that.
Are either of these possible?
# Answer
I appended this to my `.emacs` to disable the changing of point (cursor) on tap: `(defun mouse-set-point (event))`
What it does is basically it changes the definition of the `mouse-set-point` function to nothing so that the function does not change the point (position in the buffer).
If you want to go back to the default definition, remove the line or uncomment it.
This will sometimes make the clicking of the link hard so fiddle with the variable: `mouse-1-click-follows-link` to see what suits you best.
> 1 votes
# Answer
Two potential answers:
1) This is not exactly an emacs fix for your question, and may or may not apply in your situation. The exact steps will depend on your os and desktop environment:
If you're using linux with one of many desktop environments (gnome3, MATE, openbox, etc.) there is a setting under "mouse" settings (sometimes on the "touchpad" tab of the mouse-settings window) that says something to the effect of "disable touchpad while typing" (see also "synaptic"). This will not help if you pause typing and then touch the touchpad.
2) emacs solution: Stolen directly from: https://www.reddit.com/r/emacs/comments/a799um/how\_to\_disable\_mouse\_in\_emacs/
This involves setting the keybinding for the mouse to do nothing (nil):
```
(use-package evil
:ensure t
:diminish evil
:init (evil-mode 1)
(setq evil-insert-state-cursor '((bar . 1) "white")
evil-visual-state-cursor '(box "dark orange")
evil-normal-state-cursor '(box "white"))
:bind (:map
evil-insert-state-map
([S-left] . windmove-left)
([S-right] . windmove-right)
([S-up] . windmove-up)
([S-down] . windmove-down)
("<down-mouse-1>" . nil)
("<mouse-1>" . nil)
("<down-mouse-3>" . nil)
("<mouse-3>" . nil)
("SPC" . nil)
:map
evil-normal-state-map
(";" . evil-ex)
(":" . evil-repeat-find-char)
("<down-mouse-1>" . nil)
("<mouse-1>" . nil)
("<down-mouse-3>" . nil)
("<mouse-3>" . nil)
("SPC" . nil)
:map evil-motion-state-map
([S-left] . windmove-left)
([S-right] . windmove-right)
([S-up] . windmove-up)
([S-down] . windmove-down)
("<down-mouse-1>" . nil)
("<mouse-1>" . nil)
("<down-mouse-3>" . nil)
("<mouse-3>" . nil)
("SPC" . nil)
))
```
> 0 votes
---
Tags: evil, mouse
--- |
thread-64985 | https://emacs.stackexchange.com/questions/64985 | how to end macro expansion in *scratch* buffer and return to writable buffer | 2021-05-24T09:54:03.470 | # Question
Title: how to end macro expansion in *scratch* buffer and return to writable buffer
In *scratch* buffer, Emacs can expand macros(C-c e; macrostep-expand). But once I expanded the macro, it seems to become a read-only buffer. I don't know how to end macro expansion and return to writable buffer.
It would be very helpful if you could tell me the solution.
My environment is below.
* GNU Emacs 27.1 (build 1, x86\_64-pc-linux-gnu, GTK+ Version 3.24.20, cairo version 1.16.0)
* WSL2
Thanks
EDIT macro-expansion is a function of macrostep.el.
# Answer
The solution was just to press q on the expanded macro.
according to M-x describe-bindings
```
q macrostep-collapse-all
c macrostep-collapse
u macrostep-collapse
DEL macrostep-collapse
n macrostep-next-macro
p macrostep-prev-macro
e macrostep-expand
```
> 0 votes
---
Tags: keyboard-macros
--- |
thread-64974 | https://emacs.stackexchange.com/questions/64974 | How to kill all buffers except the buffer current one and *other*? | 2021-05-23T20:52:18.780 | # Question
Title: How to kill all buffers except the buffer current one and *other*?
I use this:
```
(defun kill-other-buffers ()
"kill all other buffers."
(interactive)
(mapc 'kill-buffer (delq (current-buffer) (buffer-list))))
```
I need to add one more buffer
# Answer
> 1 votes
Per the comments, you can simply `delq` the "one more buffer" you wish to exclude. You would be deleting it from the list which was returned by the initial `delq` form:
```
(delq (get-buffer "init.el")
(delq (current-buffer)
(buffer-list)))
```
You can, of course, generalise this to act on some arbitrary list of exclusions:
```
(require 'cl-lib)
(let ((exclusions (list (current-buffer) (get-buffer "init.el"))))
(cl-reduce #'delq exclusions :from-end t :initial-value (buffer-list)))
```
Or you might find this approach more-readable:
```
(require 'cl-lib)
(let ((exclusions (list (current-buffer) (get-buffer "init.el"))))
(cl-loop for b being the buffers
unless (memq b exclusions)
collect b))
```
All three forms should return the same list.
# Answer
> 1 votes
Another approach (depending on your needs) is to use the `kill-buffer-query-functions` hook to prevent specific buffers from being killed regardless of how `kill-buffer` is invoked.
I use my own small library to prevent certain buffers from being killed but there are various other examples out there. With this approach you can keep your kill-other-buffers command simple and manage your list of protected buffers separately.
---
Tags: buffers, kill-buffer
--- |
thread-21597 | https://emacs.stackexchange.com/questions/21597 | Using magit for the most basic add, commit, push | 2016-04-13T08:23:58.077 | # Question
Title: Using magit for the most basic add, commit, push
I normally use only a few git commands each time I want to commit changes to a repository:
```
$ git add --all .
$ git commit -m "update."
$ git push -u origin master
```
Can magit be useful in this regard? `M-x magit-status` seems helpful but I am not fulling understanding the language of "staging/unstaging" "hunks" etc. from ref1 ref2 ref3.
What might be the equivalent commands in `magit`? Thanks in advance -
**Edit** This page seems to speak better to my level but is `C-u s` the equivalent of `git add --all .`? Though that page says it does not work.
# Answer
* `S` stages all files
* `c c` initiates a commit. Write the message and then press `C-c C-c` to actually create the commit.
* `P u` pushes to the upstream branch. In the popup that appears after you have pressed `P` you can see the upstream. If the upstream is not set yet, then you can still use `P u`. You'll be asked for a branch which is then configured as the upstream before pushing.
> 44 votes
# Answer
This one is also quite easy technique without learning shortcuts of magit by using `hydra`.
```
(defhydra yt-hydra/help (:color blue :hint nil)
"
_mp_ magit-push #_mc_ magit-commit #_md_ magit diff #_mla_ magit diff #_mla_ magit status
"
;;Magit part
("mp" magit-push)
("mc" magit-commit)
("md" magit-diff)
("mla" magit-log-all)
("ms" magit-status)
)
(global-set-key (kbd "<f1>") 'yt-hydra/help/body)
```
> 2 votes
# Answer
I just write an easy shell function to help PUSHING ALL.
```
function lazy-git {
git add -A
git commit -a -m " $1"
git push
}
lazy-git "Update somethinng"
```
or in Emacs
```
(defun push-all (comment)
(interactive (list
(read-string (format " Push for [%s]: " (current-directory-name)))))
(save-some-buffers t) ; save all buffer
(shell-command (format "git add -A; git commit -a -m \" %s\"; git push &"
comment)))
```
> 1 votes
---
Tags: magit
--- |
thread-36848 | https://emacs.stackexchange.com/questions/36848 | Move cursor to beginning of visible text in current buffer | 2017-11-13T09:44:46.160 | # Question
Title: Move cursor to beginning of visible text in current buffer
Is there a shortcut key combination for moving the cursor to the beginning, resp. end, of the *visible* text in the current buffer, i.e. to the first, resp. last, cursor position that can be seen on the current screen, without scrolling up or down? Contrast this with the *absolute* beginning/end of the text in the current buffer, for which the shortcuts `M-<`, resp. `M->`, will work.
# Answer
> 8 votes
Ah, you're looking to move point to the top or bottom of the *window*.
`M-r` calls `move-to-window-line-top-bottom` which cycles through the top/middle/bottom positions. You can also use a prefix argument, for which "zero means top of window, negative means relative to bottom of window."
e.g.:
* `M-0``M-r`
* `M--``M-r`
Or write a command to call `move-to-window-line` directly with an appropriate argument.
# Answer
> 0 votes
I like to use the following bindings to easily get to the top (t) and bottom (b):
```
(global-set-key (kbd "C-S-t") (lambda () (interactive)
(push-mark (point)) ; save place
(let ((current-prefix-arg 0))
(call-interactively 'move-to-window-line-top-bottom))))
(global-set-key (kbd "C-S-b") (lambda () (interactive)
(push-mark (point)) ; save place
(let ((current-prefix-arg '(-1)))
(call-interactively 'move-to-window-line-top-bottom))))
```
They are specific calls to `move-to-window-line-top-bottom` (with needed prefix args) to go to those spots directly, instead of pressing `M-r` two or three times.
You may wish to use different bindings, but the recipe of going there directly is there.
---
Tags: motion
--- |
thread-64996 | https://emacs.stackexchange.com/questions/64996 | Key to move to next ancestor heading in org mode | 2021-05-24T20:59:30.837 | # Question
Title: Key to move to next ancestor heading in org mode
I would like to jump to the next parent heading from a lower level directly. Is there a shortcut for that in org mode?
```
* a
** b
** c
* d
```
So to jump, say, from b to d.
# Answer
> 1 votes
You can do `C-c C-u` to go to parent then `C-c C-f` to go to next heading of the same level (i.e., sibling)
---
Tags: org-mode, motion
--- |
thread-65003 | https://emacs.stackexchange.com/questions/65003 | Tramp mode - very slow connect | 2021-05-25T14:05:30.710 | # Question
Title: Tramp mode - very slow connect
CentOS 7, Emacs 27.1
Suppose I wan to to connect to the remote host (by ssh).
**Approach#1** Opent Linux terminal and run the next command
```
ssh someLogin@10.222.11.111
```
Type password and after about **3 seconds** I success connected to the remote host. Nice.
Now I want do same by Emacs.
**Approach#2**
I use Tramp mode. I my bookmarks I already has link to remote host. So I only jump to bookmarks like this;
```
mybookmarskEntity /ssh:someLogin@10.222.11.111:/home/someLoginHome/
```
and wait ... about 30 seconds. And only **after 30 seconds** I success connected to the remote host.
Why so slowly?
# Answer
Very likely you run into a timeout. You could detect this, if you retry your test with `tramp-verbose` set to 10. If you ned assistance in reading Tramp's traces, contact us at ML`tramp-devel@gnu.org` .
> 2 votes
---
Tags: tramp, performance
--- |
thread-65008 | https://emacs.stackexchange.com/questions/65008 | What is the difference between writing and saving a file in Emacs? | 2021-05-25T23:27:24.657 | # Question
Title: What is the difference between writing and saving a file in Emacs?
What is the problem if I keep writing a file while editing it instead of saving it?
What exactly am I going to lose? Some sort of backup? Is this a "bad" practice?
# Answer
> 3 votes
The source for write-file is available.
As of May 2021, it does some checks (e.g., to make sure the location being saved to isn't a directory, see if a file is being overwritten), then calls save-buffer.
So you're not missing anything by calling `write-file`; it calls the same function you would call to save the buffer. I'm not exactly sure why you would want to do this, as it seems like you'd have to specify the filename each time you want to save. But you can.
To make this a self-contained answer, the complete source is here:
```
(defun write-file (filename &optional confirm)
"Write current buffer into file FILENAME.
This makes the buffer visit that file, and marks it as not modified.
Interactively, prompt for FILENAME.
If you specify just a directory name as FILENAME, that means to write
to a file in that directory. In this case, the base name of the file
is the same as that of the file visited in the buffer, or the buffer
name sans leading directories, if any, if the buffer is not already
visiting a file.
You can also yank the file name into the minibuffer to edit it,
using \\<minibuffer-local-map>\\[next-history-element].
If optional second arg CONFIRM is non-nil, this function
asks for confirmation before overwriting an existing file.
Interactively, confirmation is required unless you supply a prefix argument."
;; (interactive "FWrite file: ")
(interactive
(list (if buffer-file-name
(read-file-name "Write file: "
nil nil nil nil)
(read-file-name "Write file: " default-directory
(expand-file-name
(file-name-nondirectory (buffer-name))
default-directory)
nil nil))
(not current-prefix-arg)))
(or (null filename) (string-equal filename "")
(progn
;; If arg is a directory name,
;; use the default file name, but in that directory.
(if (directory-name-p filename)
(setq filename (concat filename
(file-name-nondirectory
(or buffer-file-name (buffer-name))))))
(and confirm
(file-exists-p filename)
;; NS does its own confirm dialog.
(not (and (eq (framep-on-display) 'ns)
(listp last-nonmenu-event)
use-dialog-box))
(or (y-or-n-p (format-message
"File `%s' exists; overwrite? " filename))
(user-error "Canceled")))
(set-visited-file-name filename (not confirm))))
(set-buffer-modified-p t)
;; Make buffer writable if file is writable.
(and buffer-file-name
(file-writable-p buffer-file-name)
(setq buffer-read-only nil))
(save-buffer)
;; It's likely that the VC status at the new location is different from
;; the one at the old location.
(vc-refresh-state))
```
---
Tags: overwrite, save
--- |
thread-65009 | https://emacs.stackexchange.com/questions/65009 | Open recent directories like Ido opens files | 2021-05-26T05:33:05.287 | # Question
Title: Open recent directories like Ido opens files
When I want to open a recent file, I use `ido-find-find` (`C-x C-f`) or `ido-switch-buffer` (`C-x b`) and type a few characters and Ido automatically finds the right file among the recent files I have visited.
I would like to have something similar for directories. For example, with `ido-dired`, Ido suggests the current directory and I have to navigate my filesystem to reach the one I have in mind. For example, to reach `~/some/sub/directory/containing/the/RightDirectory/`, I have to type in the first letters of all the parent directories (and remember them) to reach `RightDirectory/`. I find that cumbersome.
Is there a way to get an interface similar to `ido-find-file` to reach a recent directory?
Note: I am open to any other suggestion of workflow to reach a recent (or any) directory quickly.
# Answer
> 1 votes
Something quick. Far from perfection, but it's a start. (You might want to add some cache mechanism since it's rather slow)
```
(defun find-recent-dirs (dir)
(interactive
(list (completing-read "Recent dirs: "
(-filter (lambda (p) (and (not (file-remote-p p))
(f-directory? p)))
(-uniq (-map #'f-dirname recentf-list)))))))
(find-file dir))
```
# Answer
> 1 votes
> I am open to any other suggestion of workflow to reach a recent (or any) directory quickly.
Dired+ lets you open a Dired buffer that shows recently used directories (commands `diredp-dired-recent-dirs` and `diredp-dired-recent-dirs-other-window`, bound globally to **`C-x D r`** and **`C-x 4 D r`**).
This is similar to the commands showing recent *files* (`C-x D R` and `C-x 4 D R`).
`C-h C-x D r` says:
> Open Dired in `BUFFER`, showing recently visited directories.
>
> Like `diredp-dired-recent-files`, but limited to recent directories. *A directory is recent if any of its files is recent.*
The more extensive doc string for `C-x D R` (recent files) says this. It all applies also to the recent-directories commands.
> `diredp-dired-recent-files` is an interactive compiled Lisp function in `dired+.el`.
>
> It is bound to `C-x D R`.
>
> `(diredp-dired-recent-files BUFFER &optional ARG FILES)`
>
> Open Dired in `BUFFER`, showing recently visited files and directories.
>
> You are prompted for `BUFFER` (default: `Recently Visited Files`).
>
> With a ***numeric** prefix arg* you can enter names of recent files to *include or exclude*.
>
> *No prefix arg or a **plain** prefix arg* (`C-u`, `C-u C-u`, etc.) means list *all* of the recently used files.
>
> With a prefix arg:
>
> * If 0, `-`, or plain (`C-u`) then you are prompted for *the `ls` switches* to use.
> * If not plain (`C-u`) then:
>
> + If \>= 0 then the *files to include* are read, one by one.
> + If \< 0 then the *files to exclude* are read, one by one.
>
> When entering files to include or exclude, use `C-g` to end.
>
> The file listing is *sorted by option `diredp-default-sort-arbitrary-function`*, if non-`nil`. If `nil` (the default) then the listing is in reverse chronological order of opening or writing files you access.
>
> Use `g` to *revert* the buffer, as usual. If you use it without a prefix arg then the same files are relisted. A *prefix arg* is handled as for `C-x D R` itself.
>
> When called from Lisp:
>
> * `ARG` corresponds to the raw prefix arg.
> * `FILES` is passed to `diredp--dired-recent-files-1`. It is used only when the command is used as part of the `revert-buffer-function`.
You can even *sort* such Dired buffers, using **`C-M-L`** (aka `C-M-S-l`).
---
Tags: dired, ido, recentf
--- |
thread-65014 | https://emacs.stackexchange.com/questions/65014 | How can I copy+paste `org-mode` headlines only? | 2021-05-26T08:46:15.137 | # Question
Title: How can I copy+paste `org-mode` headlines only?
I have an `org-mode` file containing a structure like this:
```
*** H1
**** H2
- Foo
Foo
**** H2
Foo
Foo
```
I would like to make a copy of `H1` and all it's subheadings, but none of the non-headline content. I would then like to be able to paste this copy, adding the following content to the file:
```
*** H1
**** H2
**** H2
```
Currently the way I do this is to collapse `H1` using `yy` (I use `evil-mode`), move to the appropriate place, with `p`, and then manually delete all the non-headline content.
How can I copy+paste `org-mode` headlines only?
# Answer
> 10 votes
`org-copy-visible`, bound to `C-c C-x v`, does this: collapse your outline until just the headings you want to copy are visible, set a region around them, and copy via `org-copy-visible`.
---
Tags: org-mode, copy-paste
--- |
thread-65013 | https://emacs.stackexchange.com/questions/65013 | How to use a particular syntax table with arbitrary functions? | 2021-05-26T08:20:32.227 | # Question
Title: How to use a particular syntax table with arbitrary functions?
I have an Elisp function which takes a string and performs capitalization (`capitalize`) on it, and then inserts it into a file. Apparently `capitalize` doesn't consider the single quote as a "word constituent" and therefore I get results like "I'M A Cat".
I understand that this is because of the syntax table in place. The default returned by `(standard-syntax-table)` treats the quote as a "word constituent", so I'm assuming that code execution uses `emacs-lisp-mode-syntax-table` which has it otherwise.
I tried executing `capitalize` inside `with-temp-buffer` but that didn't work for some reason.
So my questions are:
* Does the functions I have in my config use`emacs-lisp-mode-syntax-table` when I call them?
* What's the standard way of dealing with this? What's a way to isolate my functions from inheriting all this context? I don't want to manually create a new table and use `with-syntax-table` for every function in my config or change the current table using `modify-syntax-entry`, and I want my strings to be treated like normal English sentences.
# Answer
You say you don't want to have to "manually create a new table and use `with-syntax-table` for every function in my config or change the current table using `modify-syntax-entry`."
I think you have to do either that or give yourself a more general function that you can apply to accomplish the same thing.
Here's a particular command, just for capitalizing the region the way you want:
```
(defun my-capitalize-region (begin end)
"..."
(interactive "r")
(let ((s-table (copy-syntax-table)))
(modify-syntax-entry ?' "w" s-table)
(with-syntax-table s-table (capitalize-region begin end))))
```
You could use essentially the same code as a helper, to apply to a command, such as `capitalize-region` passed as an arg.
```
(defun with-word-apostrophe (command &rest args)
"..."
(let ((s-table (copy-syntax-table)))
(modify-syntax-entry ?' "w" s-table)
(with-syntax-table s-table (apply command args))))
(defun my-capitalize-region (begin end)
"..."
(interactive "r")
(with-word-apostrophe #'capitalize-region begin end))
```
You can't just use `standard-syntax-table`, e.g.:
```
(defun with-word-apostrophe (command &rest args)
"..."
(with-syntax-table (standard-syntax-table) (apply command args)))
```
because apostrophe has syntax *punctuation* in the standard syntax table:
```
(aref (standard-syntax-table) ?') ; ==> (1), which means punctuation
```
> 4 votes
---
Tags: syntax-table, capitalization
--- |
thread-64796 | https://emacs.stackexchange.com/questions/64796 | Switch to the most recently selected buffer in the current window | 2021-05-10T22:20:37.353 | # Question
Title: Switch to the most recently selected buffer in the current window
I am looking for a command that would switch to the buffer I most recently selected in the current window. The command `mode-line-other-buffer` will switch to the most recently selected buffer not displayed in any window, regardless of whether it was selected in the current window or in some other window.
For illustration, suppose I have two open windows, *1* and *2*, and four open buffers, *A*, *B*, *C*, *D*. Buffer *A* is displayed in window *1*, and buffer *C* is displayed in window *2*. Now suppose that,
* with point on *A*,
* I first switch to *B*, then
* select window *2*, then
* switch to *D*, and finally
* select window *1*.
At that point, the command `mode-line-other-buffer`, if invoked, will switch to *C*. I would like an alternative command that, if invoked, would switch to *A* instead. Moreover, repeated invocations of this alternative command should toggle between *B* and *A* (just like repeated invocations of `mode-line-other-buffer` toggle between *B* and *C*), since either of these buffers becomes the most recently selected buffer when the other buffer is selected.
# Answer
> 0 votes
Although I'm not a Spacemacs user, I found that Spacemacs has a command that does exactly what I described:
```
(defun spacemacs/alternate-buffer (&optional window)
"Switch back and forth between current and last buffer in the
current window."
(interactive)
(let ((current-buffer (window-buffer window))
(buffer-predicate
(frame-parameter (window-frame window) 'buffer-predicate)))
;; switch to first buffer previously shown in this window that matches
;; frame-parameter `buffer-predicate'
(switch-to-buffer
(or (cl-find-if (lambda (buffer)
(and (not (eq buffer current-buffer))
(or (null buffer-predicate)
(funcall buffer-predicate buffer))))
(mapcar #'car (window-prev-buffers window)))
;; `other-buffer' honors `buffer-predicate' so no need to filter
(other-buffer current-buffer t)))))
```
# Answer
> 1 votes
The function you are looking for is `previous-buffer`.
Its doc string says:
> Call ‘switch-to-prev-buffer’ unless the selected window is the
> minibuffer window or is dedicated to its buffer.
The referenced function `switch-to-prev-buffer` is mentioned on the info page for Window History:
> – Command: switch-to-prev-buffer &optional window bury-or-kill
> This command displays the previous buffer in WINDOW. The argument
> WINDOW should be a live window or ‘nil’ (meaning the selected
> window). If the optional argument BURY-OR-KILL is non-‘nil’, this
> means that the buffer currently shown in WINDOW is about to be
> buried or killed and consequently should not be switched to in
> future invocations of this command.
>
> The previous buffer is usually the buffer shown before the buffer
> currently shown in WINDOW. However, a buffer that has been buried
> or killed, or has been already shown by a recent invocation of
> ‘switch-to-prev-buffer’, does not qualify as previous buffer.
>
> If repeated invocations of this command have already shown all
> buffers previously shown in WINDOW, further invocations will show
> buffers from the buffer list of the frame WINDOW appears on (\*note
> Buffer List::), trying to skip buffers that are already shown in
> another window on that frame.
---
Tags: buffers, window
--- |
thread-65020 | https://emacs.stackexchange.com/questions/65020 | Certain keywords show font weight of bold | 2021-05-26T18:11:43.263 | # Question
Title: Certain keywords show font weight of bold
The syntax highlighting in Emacs is not great so I installed `tree-sitter` plugin to improve it and configured it like this,
```
;; Tree sitter
(use-package! tree-sitter
:config
(require 'tree-sitter-langs)
(global-tree-sitter-mode)
(add-hook 'tree-sitter-after-on-hook #'tree-sitter-hl-mode))
```
It does work, but for some reason certain keywords like a call to a class method show up as font weight of bold, when they should show as normal weight.
As you can see all `#include` statements show as bold here and,
These methods also show as bold.
Is there a way to make them normal weight, without turning off the bold weight globally?
# Answer
`tree-sitter` appears to be using the default faces for syntax highlighting. You can find out what face is applied by putting point (the cursor) on to the highlighted word, and calling `M-x describe-face`. The default value is the face applied to the word at point. You can then use that value to customize the face, where you will have the option of removing the bold-weight.
For example, if `describe-face` tells me I'm looking at `font-lock-keyword-face`, I can customize how it appears with `M-x customize-face font-lock-keyword-face`.
> 1 votes
---
Tags: fonts, highlighting
--- |
thread-65006 | https://emacs.stackexchange.com/questions/65006 | How do I hook fundamental-mode and all modes derived from it for modifying syntax for underscores | 2021-05-25T16:28:42.417 | # Question
Title: How do I hook fundamental-mode and all modes derived from it for modifying syntax for underscores
Here is the definition of `fundamental-mode`:
```
(defun fundamental-mode ()
"Major mode not specialized for anything in particular.
Other major modes are defined by comparison with this one."
(interactive)
(kill-all-local-variables)
(run-mode-hooks))
```
There does not seem to be a `fundamental-mode-hook` defined.
I would like to call some code for all "fundamental-mode" buffers *and* all derived modes from it, *without* having to itemize all such modes and explicitly call `add-hook` on all of their mode functions.
Is there a way or am I stuck paying the itemization cost? If yes, then how do I do this inside all modes:
```
(modify-syntax-entry ?_ "w")
```
because after decades of Emacs usage, I've finally grown tired of my cursor getting hung up on every single underscore for every time I use `M-f` (`ALT`+`f`), across all *new* modes that are invented and that I install into my setup.
# Answer
**1st:** Dealing with your actual problem of setting the syntax for `?_` in modes derived from `fundamental-mode`.
There are no commands setting the syntax table in `fundamental-mode`. Therefore, it uses the `(standard-syntax-table)`. If the syntax for `?_` is not defined in a mode it uses the entry in its inherited syntax table. By default, `(standard-syntax-table)` is inherited. Since there are no circular references for syntax tables `(standard-syntax-table)` is eventually the fallback for all modes.
If we assume that modes setting the syntax for `?_` do it for a good reason it should be sufficient to use the following line in your init files:
```
(modify-syntax-entry ?_ " " (standard-syntax-table))
```
(This works at least in Emacs 27.1.90.)
**2nd:** The user is not supposed to customize `fundamental-mode`. So there is no hook for that mode.
Furthermore, `fundamental-mode` does not really play a role in the inheritance hierarchy. For all modes but `fundamental-mode` itself `(derived-mode-p 'fundamental-mode)` evaluates to `nil`.
Nevertheless, there is `after-change-major-mode-hook` that is run at the very end of major mode functions. That allows you to do general settings for all modes.
> 4 votes
---
Tags: syntax-table
--- |
thread-64960 | https://emacs.stackexchange.com/questions/64960 | `C-c C-c` compilation stopped working in SLIME but works if manually typed, how to fix it? | 2021-05-22T18:45:21.247 | # Question
Title: `C-c C-c` compilation stopped working in SLIME but works if manually typed, how to fix it?
I am new to Emacs and Slime. I have been using both of them daily for the last 10 days. And it is amazing! I am impressed.
Today, I decided to install and try the package Paredit. Not sure if this is a coincidence, but after a while, Slime stopped working as it used to.
I was using `C-c C-c` all the time to compile specific Common Lisp functions. Now, it does not work.
Even with slime running after pressing `M-x slime` I get from the mini-buffer:
```
C-c C-c is undefined
```
If I try a stronger compilation with `C-c C-k` the keyboard also does not work.
However, the compilation works if I manually compile the region or the whole file after typing on the mini-buffer:
```
M-x slime-compile-region
M-x slime-compile-and-load
```
Before writing this, even the manual typed compilation was not working. Suddenly, it started to work again. But the keyboard shortcut is not back.
I do not really understand this behavior from emacs/slime.
This is my current config file.
Why is this happening? Did I break something after installing Paredit?
What should I inspect to understand why the famous commands (C-c C-c and C-c C-k) suddenly stopped working?
Thanks for your attention.
# Answer
> 1 votes
I did not mention it in my post, but after installing Paredit I also installed **Sly**, a fork from the **Slime** project. This was the root of the problem.
I learned how to uninstall packages with this post.
In addition, @nega connected the dots between this problem and this other post.
After removing Sly, Slime is perfectly functioning! And the keybindings such as `C-c C-c` are working as usual.
---
Tags: keyboard-macros, compilation, slime
--- |
thread-64955 | https://emacs.stackexchange.com/questions/64955 | What’s the most common way to debug C++ on Mac | 2021-05-22T10:45:31.747 | # Question
Title: What’s the most common way to debug C++ on Mac
I'm wondering what's the most common way to debug C++ programs using emacs for Mac users? I’m currently using gdb, which takes a moment for me to make it work for Mac, so I’m now considering give dap-mode a try.
I’m new to emacs. Just wanna know what most Mac users do to debug C++ on Mac?
# Answer
I don't debug C++ from within Emacs, but have you looked into `clang/lldb`? You can use either Apple's native version or a version from upstream. I get mine via Homebrew (`brew install llvm`). `dap-mode` supports `lldb`. It's also supported by realgud (along with a host of others), and its `realgud--lldb` extension.
> 0 votes
---
Tags: gdb, debug
--- |
thread-64950 | https://emacs.stackexchange.com/questions/64950 | how to properly install coverage mode? | 2021-05-22T04:06:01.320 | # Question
Title: how to properly install coverage mode?
What I did
What I got:
* opened a .rb file
* M-x coverage-mode
* in *Messages*:
cond: Wrong type argument: number-or-marker-p, (lines . \[1 1 1 nil 1 0 0 nil 0 0 ...\]) Error running timer ‘coverage-redraw-buffers’: (wrong-type-argument number-or-marker-p (lines . \[1 1 1 nil 1 0 0 nil 0 0 nil nil nil\])) \[6 times\]
# Answer
> 0 votes
Recent developments have actually broken this package. One workaround is to pin the version of simplecov in your Gemfile to an older version.
---
Tags: ruby-mode
--- |
thread-65029 | https://emacs.stackexchange.com/questions/65029 | org files are not refreshed in emacsclient | 2021-05-27T02:10:00.627 | # Question
Title: org files are not refreshed in emacsclient
My org files are stored on the cloud so I can edit them from multiple machines. Whenever I make a change to an org file (from a different machine), emacsclient does not reflect these changes, but a regular instance of emacs does. I understand that the emacsclient is just an emacs server. How can I get emacsclient to show the changes to my org files?
# Answer
> 1 votes
Add `(global-auto-revert-mode 1)` to your init to automatically refresh files changed on disk.
As the doc states (`C-h f global-auto-revert-mode`):
> If called from Lisp, toggle the mode if ARG is ‘toggle’. Enable the mode if ARG is nil, omitted, or is a positive number. Disable the mode if ARG is a negative number.
---
Tags: org-mode, org-agenda, emacsclient, server
--- |
thread-64980 | https://emacs.stackexchange.com/questions/64980 | How can I show timestamp in natural date format in minibuffer? | 2021-05-24T06:55:45.310 | # Question
Title: How can I show timestamp in natural date format in minibuffer?
I am working quite a lot with Unix timestamps. I installed the `ts` package, but I am not able to create a key-binding to show the conversion of a timestamp to natural date format.
I would like to be able to show the natural day of a marked timestamp. Is it possible to show in the minibuffer? Or at cursor point?. I don't want to replace or timestamp or insert in the current buffer.
# Answer
Here's a simple-minded implementation that tries to detect the Unix timestamp at point. Assuming it finds one, it converts it to a human-readable date and prints it in the echo area, in the format specified by `ts-default-format` (which is defined in the `ts` package):
```
(require 'ts)
(defun ndk/ts-at-point ()
(unless (looking-at "[0-9.]")
nil)
(let ((origin (point))
beg end)
(save-excursion
(setq beg (+ origin (skip-chars-backward "0123456789."))))
(save-excursion
(setq end (+ origin (skip-chars-forward "0123456789."))))
(list beg end)))
(defun ndk/show-date-at-point ()
(interactive)
(let* ((r (ndk/ts-at-point))
(beg (nth 0 r))
(end (nth 1 r))
(unix_ts (buffer-substring beg end)))
(message (ts-format (make-ts :unix (float (read unix_ts)))))))
```
The first function scans backwards and forwards trying to find the beginning and end of the timestamp that `point` is on. It's a bit fragile and simplistic and can be fooled easily, but it should do the job if you don't push it too far.
It is called by `ndk/show-date-at-point` to get the limits, which then reads that portion of the buffer, tries to convert it to a float and, if it succeeds, it assumes it's a Unix timestamp and converts it to a human-readable date, which is then echoed in the echo area with `message`.
To use it, put your cursor on a timestamp and say `M-x ndk/show-date-at-point`. Or bind it to a key to make it easy to call:
```
(global-set-key (kbd "C-c d") #'ndk/show-date-at-point)
```
`C-c d` is supposed to be unused by packages so that users can use it for their own purposes, but if you happen to use it already, choose another `C-c <letter>` binding.
> 0 votes
---
Tags: key-bindings, time-date
--- |
thread-65033 | https://emacs.stackexchange.com/questions/65033 | Using a variable as the REGEXP in `query-replace-regexp` | 2021-05-27T10:32:20.490 | # Question
Title: Using a variable as the REGEXP in `query-replace-regexp`
I know, Emacs allows calling ELisp while replacing a text with a regex, aka `C-M-%`, which is bound to `query-replace-regexp`. I'm trying to make use of that to store an unwieldy regexp as a variable, so instead of writing it out every time, I could just extract it from a variable.
For the sake of simplification, in the testcase here I'm using just a text, so no backslashes are involved:
```
(setq foo "text")
```
Text is:
```
text text
```
Here's what I tried as the REGEXP in `query-replace-regexp`:
* `\,foo`
* `\,'foo`
* `\,(eval 'foo)`
* `\,(eval foo)`
None of those work for me. How can I make it work?
# Answer
> 1 votes
In reading the doc of `query-replace-regexp`, it mentions the `\,` syntax in the *replacement text* part, but not in the *regex part*:
> In interactive calls, the replacement text can contain ‘,’ followed by a Lisp expression.
So AFAICT, you cannot do what you want interactively: you'd have to write your own souped-up version of `query-replace-regexp` as @choroba suggests in the comments.
# Answer
> 3 votes
```
M-: (query-replace-regexp foo "bar") RET
```
---
Tags: regular-expressions, query-replace-regexp
--- |
thread-64986 | https://emacs.stackexchange.com/questions/64986 | How to change encoding of a string (to fix bad encoding)? | 2021-05-24T11:38:58.610 | # Question
Title: How to change encoding of a string (to fix bad encoding)?
I'm really confused about this issue since it *should* be doable, but i fail to understand it.
I have some file with broken encoding (a pdf file, actually), which I copy some text from. When I paste this text into emacs (or anywhere else) I get sth like "íàïðèìåð", while the correct variant should be cyrillic "например". My buffer encoding is `utf-8` and the broken text has something to do with `cp1251`. My goal is - obviously - to repair this broken encoding and insert it in place of the broken pasted text.
I tried different combinations of `encode-coding-string` and `decode-coding-string` with `utf-8` and `cp1251`, but it gave me some other broken encodings or just a bunch of spaces (that's kinda weird)
Sorry for my messy statement, I just really don't get all this encoding stuff.
---
What I achieved is a (half)solution for the reverse problem: if i write `(encode-coding-string "например" 'cp1251)` and press `C-x C-e`, it prints "íàïðèìåð" to the messages. It's strange, but if I try to *insert* result of this computation into a buffer I get some nonsense yet again... Maybe I miss another aspect of this problem...
# Answer
> 0 votes
It seems I was suspecting the wrong encoding. The following code (using dash)
```
(-> "íàïðèìåð"
(encode-coding-string 'iso-8859-1)
(decode-coding-string 'cp1251)
insert)
```
inserts "например" into a buffer. Though I don't have a clue what's going on)
That's a total victory against these silly encodings, ladies and gentlemen!
---
Tags: character-encoding, string
--- |
thread-64963 | https://emacs.stackexchange.com/questions/64963 | Why don't my frame titles update? | 2021-05-22T23:59:01.920 | # Question
Title: Why don't my frame titles update?
I run Emacs 27.1 on my MacOS MBP and use `desktop-mode`.
After starting emacs (with frames re-created by the desktop restore), the frame titles are wrong and seem to remain wrong until I do something like evaluate `(set-for 0)` in each frame.
Anyone know why that happens?
My `frame-title-format` has value `"%b"`. I don't explicitly set the frame parameter `name`.
GNU Emacs 27.1 (build 1, x86\_64-apple-darwin19.6.0, NS appkit-1894.60 Version 10.15.6 (Build 19G2021)) of 2020-08-18
# Answer
Maybe you forgot the backtick (\`)
```
(setq-default frame-title-format `("%b"))
```
> 1 votes
---
Tags: osx, frame-parameters, frame-title-format
--- |
thread-22363 | https://emacs.stackexchange.com/questions/22363 | Possible to "detach" a child process? | 2016-05-19T01:55:26.737 | # Question
Title: Possible to "detach" a child process?
I use `browse-url`/`browse-url-firefox` to open links in Firefox from within Emacs 24.5.1 under Linux (Fedora 23) which in essence executes the `firefox` executable with the URL by `start-process`. If there is already a Firefox instance running, this will in turn cause the URL to be opened in a new tab and terminate the `firefox` executable spawned from Emacs, but otherwise a new Firefox instance will be running as a process child of Emacs (for testing purposes, this is equivalent to `M-! sleep 1h & RET`).
If I then want to exit Emacs, it asks me "Active processes exist; kill them and exit anyway?" with the option to either kill the Firefox instance or, well, leave Emacs running. Instead I would like to "detach" the `firefox` process from the Emacs parent so that I can exit Emacs while keeping the Firefox instance running.
Is it possible to spawn processes from Emacs that "survive" exiting Emacs, or must all spawned processes die when Emacs exits?
# Answer
> 5 votes
here's solution, shorting @abo-abo's answer.
```
(cond
((string-equal system-type "windows-nt") ; Windows
// ...
)
((string-equal system-type "gnu/linux")
(start-process "my-browse"
nil "setsid"
"firefox"
(concat "file://" buffer-file-name ))
;; (browse-url ξurl)
)
((string-equal system-type "darwin") ; Mac
// ...
))
```
Note that condition is necessary, because Mac doesn't have setsid.
# Answer
> 5 votes
Currently the best way to achieve this (although it does not work for Windows) is by using the command `call-process` with the `destination` argument set to `0` (see https://www.gnu.org/software/emacs/manual/html\_node/elisp/Synchronous-Processes.html).
E.g. to start firefox you could use:
```
(call-process "firefox" nil 0 nil "www.spacemacs.org")
```
# Answer
> 1 votes
Here's a command that does what you want:
```
(defun ora-dired-start-process (cmd &optional file-list)
(interactive
(let ((files (dired-get-marked-files
t current-prefix-arg)))
(list
(unless (eq system-type 'windows-nt)
(dired-read-shell-command "& on %s: "
current-prefix-arg files))
files)))
(if (eq system-type 'windows-nt)
(dolist (file file-list)
(w32-shell-execute "open" (expand-file-name file)))
(let (list-switch)
(start-process
cmd nil shell-file-name
shell-command-switch
(format
"nohup 1>/dev/null 2>/dev/null %s \"%s\""
(if (and (> (length file-list) 1)
(setq list-switch
(cadr (assoc cmd ora-dired-filelist-cmd))))
(format "%s %s" cmd list-switch)
cmd)
(mapconcat #'expand-file-name file-list "\" \""))))))
(define-key dired-mode-map "r" 'ora-dired-start-process)
```
The key thing here is to use `nohup`.
See the source here.
---
Tags: linux, process, exit
--- |
thread-64999 | https://emacs.stackexchange.com/questions/64999 | "VC method not implemented for backend" for project-find call | 2021-05-25T01:58:40.977 | # Question
Title: "VC method not implemented for backend" for project-find call
I am trying out project based search via `project-find-regexp`, but I get the error:
```
vc-call-backend: VC method not implemented for backend: find-ignore-file, CVS
```
How can I fix this? I assume this is a CVS specific problem. Is there way to make CVS working with the project system? (Or just ignoring the CVS aspect when doing the project search?)
# Answer
For a quick workaround, you can try adding this definition to your init script:
```
(defun vc-cvs-find-ignore-file (file)
(expand-file-name ".cvsignore" (file-name-directory file)))
```
> 1 votes
---
Tags: search, project, etags
--- |
thread-61879 | https://emacs.stackexchange.com/questions/61879 | Using a predicate function in display-buffer-alist | 2020-11-22T16:53:01.557 | # Question
Title: Using a predicate function in display-buffer-alist
I want to add a rule to `display-buffer-alist`, that splits the frame to the right when opening a `.pdf` file if and only if there is a corresponding `.tex` file in the same folder.
According to the documentation of `display-buffer-alist`, I can specify a predicate function which takes a buffer name and an action. I can't get it to work however, and I don't understand what the action argument of the predicate function is supposed to do.
My code looks like this:
```
(setq display-buffer-alist
`((#'cst/latex-pdf-p . ((display-buffer-reuse-window display-buffer-in-side-window)
(side . right)
(slot . 1)
(window-width . 0.33)
(reusable-frames . nil)))))
(defun cst/latex-pdf-p (buffer-name action)
"Determine if there is a corresponding .tex file in the current folder."
(when (string= "pdf" (file-name-extension buffer-name))
(file-exists-p (concat (file-name-base buffer-name) ".tex"))))
```
The predicate function seems to work as expected when I evaluate it from a buffer `split.pdf` with `split.tex` in the same folder it returns `t`, on other pdfs it returns `nil`. When using the regexp `\\.pdf$` the split works, but on all pdfs. Using the rule with the predicate function it does not work on any pdf.
I feel like I misunderstand how the predicate function should work.
# Answer
try :
```
(setq display-buffer-alist
'((cst/latex-pdf-p
(display-buffer-reuse-window display-buffer-in-side-window)
(side . right)
(slot . 1)
(window-width . 0.33)
(reusable-frames . nil))))
```
The predicate is evaluated by `display-buffer-assq-regexp`, which uses `funcall` on a variable with as value, your function. It won't work if you quote it. Also your alist was not well formed.
> 2 votes
---
Tags: display-buffer-alist, display-buffer
--- |
thread-65025 | https://emacs.stackexchange.com/questions/65025 | How can I prevent pasting after org-copy-visible leaving cursor at end of text? | 2021-05-26T21:42:49.903 | # Question
Title: How can I prevent pasting after org-copy-visible leaving cursor at end of text?
In evil-mode, if I use `3yy` to copy three lines, then move somewhere else in my file and do `P` (`evil-paste-before`), the three lines are pasted before the line with the cursor, and the cursor is left at the top of the pasted text.
If however I copy a section of text using `org-copy-visible` and paste that using `P`, the cursor ends up at the bottom of the pasted text.
I can get the desired result (cursor left at start of text) in the latter case if I subsequently do an undo / redo but that is too hacky even for me.
How can I paste following a call to `org-copy-visible` and leave the cursor at the start of the pasted text?
# Answer
> 1 votes
Per the vim manual, just `p` would do, but unluckily when I tried in Vim, both leave cursor after the new text, and evil didn't bind `gp` at all. dead end for me.
```
p put E353
["x]p Put the text [from register x] after the cursor
[count] times.
...
gp
["x]gp Just like "p", but leave the cursor just after the new
text.
```
The Emacs way:
> The basic yanking command is C-y (yank). It inserts the most recent kill, leaving the cursor at the end of the inserted text. It also sets the mark at the beginning of the inserted text, without activating the mark; this lets you jump easily to that position, if you wish, with C-u C-\<SPC\>
>
> With a plain prefix argument (C-u C-y), the command instead leaves the cursor in front of the inserted text, and sets the mark at the end. Using any other prefix argument specifies an earlier kill; e.g., C-u 4 C-y reinserts the fourth most recent kill.
Good news is evil's paste commands set mark of the other side of newly pasted text for you too. You can go to the other side either:
* C-x C-x (exchange-point-and-mark) :: if transient-mark-mode is on, add C-u to avoid activating the region incidently.
* C-u C-\<SPC\>
---
Tags: org-mode, evil, copy-paste
--- |
thread-16545 | https://emacs.stackexchange.com/questions/16545 | Make names of major modes shorter in the mode-line | 2015-09-11T18:56:52.837 | # Question
Title: Make names of major modes shorter in the mode-line
I want to make names of major modes shorter. No longer than three characters. Is there any packages that do something like that?
It's better to shorten mode names in automatic fashion, so one doesn't need to constantly manage this thing manually. I'm ready to consider any principle of shortening. Most trivial would be to use abbreviations, so `emacs-lisp-mode` would become `el`, for example. `interactive-haskell-mode` would become `ih`. Not bad at all for a start.
I also like Unicode characters like Greek letters and other stuff to be mode names, currently I use sort of hack to “rename” modes, but maybe there is full featured package to do it?
---
Clarification: the question is about mode names (values of variable `mode-name` usually), they are displayed in mode line. I want to make major mode “lighters” shorter.
# Answer
Cyphejor can handle this. Here is how it works (copied from `README.md` file):
First you need to set value of variable `cyphejor-rules`. This variable contains rules that the package uses to generate new names for major modes from their symbol names (values of `major-mode` variable).
Value of `cyphejor-rules` should be a list. Every element of the list must be either a list:
```
(string replacement &rest parameters)
```
where `string` is a “word” in major mode symbol name, `replacement` is another string to be used instead, `parameters` is a list that may be empty but may have the following keywords in it as well:
* `:prefix` — put it in the beginning of result string
* `:postfix` — put it in the end of result string
Apart from elements of the form described above the following keywords are allowed (they influence the algorithm in general):
* `:downcase` — replace words that are not specified explicitly with their first letter downcased
* `:upcase` — replace words that are not specified explicitely with their first letter upcased
If nothing is specified, use word unchanged separating it from other words with spaces if necessary.
Example of setup:
```
(setq
cyphejor-rules
'(:upcase
("bookmark" "→")
("buffer" "β")
("diff" "Δ")
("dired" "δ")
("emacs" "ε")
("fundamental" "Ⓕ")
("inferior" "i" :prefix)
("interaction" "i" :prefix)
("interactive" "i" :prefix)
("lisp" "λ" :postfix)
("menu" "▤" :postfix)
("mode" "")
("package" "↓")
("python" "π")
("shell" "sh" :postfix)
("text" "ξ")
("wdired" "↯δ")))
```
Next, just enable `cyphejor-mode` in your configuration file:
```
(cyphejor-mode 1)
```
> 7 votes
# Answer
If you just want to always trim the mode name to a particular length, then how about this:
```
(defcustom mode-name-max-length 8
"The number of characters after which a major mode name will be
truncated in the modeline.")
(defun truncate-mode-name ()
(setq mode-name (truncate-string-to-width mode-name mode-name-max-length nil nil 't)))
(add-hook 'after-change-major-mode-hook #'truncate-mode-name)
```
(Updated to use `truncate-string-to-width` with ELLIPSIS argument per the comments -- thanks!)
> 4 votes
# Answer
You can also just get rid of the major mode lighter in the mode-line altogether.
Just take the code defining `mode-line-modes` from `bindings.el`, and comment-out or remove these lines, to try it out:
```
`(:propertize ("" mode-name)
help-echo "Major mode\n\
mouse-1: Display major mode menu\n\
mouse-2: Show help for major mode\n\
mouse-3: Toggle minor modes"
mouse-face mode-line-highlight
local-map ,mode-line-major-mode-keymap)
```
Result:
```
(defvar mode-line-modes
(let ((recursive-edit-help-echo "Recursive edit, type C-M-c to get out"))
(list (propertize "%[" 'help-echo recursive-edit-help-echo)
"("
;;; `(:propertize ("" mode-name)
;;; help-echo "Major mode\n\
;;; mouse-1: Display major mode menu\n\
;;; mouse-2: Show help for major mode\n\
;;; mouse-3: Toggle minor modes"
;;; mouse-face mode-line-highlight
;;; local-map ,mode-line-major-mode-keymap)
'("" mode-line-process)
`(:propertize ("" minor-mode-alist)
mouse-face mode-line-highlight
help-echo "Minor mode\n\
mouse-1: Display minor mode menu\n\
mouse-2: Show help for minor mode\n\
mouse-3: Toggle minor modes"
local-map ,mode-line-minor-mode-keymap)
(propertize "%n" 'help-echo "mouse-2: Remove narrowing from buffer"
'mouse-face 'mode-line-highlight
'local-map (make-mode-line-mouse-map
'mouse-2 #'mode-line-widen))
")"
(propertize "%]" 'help-echo recursive-edit-help-echo)
" "))
"Mode line construct for displaying major and minor modes.")
```
> 0 votes
# Answer
I really liked `cyphejor` to shorten the mode name in the mode line (I even threw in some emoji). But I missed the ability to filter by (regular) `mode-name` in `ibuffer` and other places.
So instead of activating `cyphejor-mode`, which actually alters `mode-name`, I just leave the mode off, and use its capabilities to replace the `mode-name` in the mode line, with caching to avoid recalculation:
```
(defun my/cyphejor-with-cache ()
(or (get major-mode 'cyphejor-cypher)
(put major-mode 'cyphejor-cypher
(cyphejor--cypher (symbol-name major-mode) cyphejor-rules))))
(cl-nsubst '(:eval (my/cyphejor-with-cache)) 'mode-name
(if minions-mode minions-mode-line-modes mode-line-modes))
```
> 0 votes
---
Tags: major-mode, mode-line
--- |
thread-41763 | https://emacs.stackexchange.com/questions/41763 | Persistently setting display-line-numbers to relative in emacs init file | 2018-06-01T01:16:21.070 | # Question
Title: Persistently setting display-line-numbers to relative in emacs init file
I am attempting to set up the new emacs 26.1 `display-line-numbers-mode` as described in this comment: hybrid line number mode in emacs?
I have added this to my .emacs file:
```
(setq display-line-numbers 'relative
display-line-numbers-current-absolute t)
```
When I evaluate the above expression the desired behavior is produced, but it is not persistent. For example, it is not automatically evaluated on restarting emacs, and when I try to use my keybinding toggle:
```
(global-set-key (kbd "C-c l") 'display-line-numbers-mode)
```
The line numbers that are toggled are not relative.
What is the appropriate way to set `display-line-numbers` to `relative` in my configuration file so that using the keybinding results in relative line numbers?
# Answer
Use `setq-default` to set buffer-local default values. Or, make sure you are in the desired buffer if you wish to use `setq`.
`C-h v` \[aka `M-x describe-variable`\] for `display-line-numbers`: "*. . . Automatically becomes buffer-local when set.*"
`display-line-numbers-current-absolute` is a global variable. \[How do we know? Because the `*Help*` buffer for describing that variable does not mention anything about it being buffer-local.\]
The variable `display-line-numbers-type` is a global variable with a doc-string that states: "*The default type of line numbers to use in ‘display-line-numbers-mode’. See ‘display-line-numbers’ for value options.*" Therefore, the O.P. could use `(setq display-line-numbers-type 'relative)` in the `.emacs` or `init.el` file to achieve the desired result.
> 3 votes
# Answer
So I am an emacs novice myself, but the way I understood it (and have it in my init.el file):
```
;; set type of line numbering (global variable)
(setq display-line-numbers-type 'relative)
;; activate line numbering in all buffers/modes
(global-display-line-numbers-mode)
```
You could also be more specific and only have line numbering in a subset of major modes by using hooks. For instance:
```
;; Activate line numbering in programming modes
(add-hook 'prog-mode-hook 'display-line-numbers-mode)
```
Source for the last snippet.
> 1 votes
---
Tags: init-file
--- |
thread-65046 | https://emacs.stackexchange.com/questions/65046 | How can I make source block in org mode to be scrollable? | 2021-05-28T03:27:37.490 | # Question
Title: How can I make source block in org mode to be scrollable?
As the title says, I'm trying to make the source blocks, when export, to be scrollable (e.g. vertical) so that the long source blocks don't mess up with the rest of content and the html/pdf files look neat in this way.
After doing some research, I've found a html way to do it, a little bit ugly, by adding html export block before the coding block
```
#+begin_export html
<pre style="height: 300px; overflow: scroll;">
#+end_export
#+begin_src python
very very long long source code
#+end_src
```
It exports as like Which looks like nested blocks, but what I want is to make the source block can scroll itself.
# Answer
> 2 votes
If you want to set it for all your Org files you can use the following lines in your init file:
```
(setq org-html-head "<style type=\"text/css\">
/*<![CDATA[*/
pre.src {
height: 100px;
overflow: auto;
}
/*]]>*/
</style>")
```
For a single Org file set the corresponding export property within the Org file instead:
```
#+HTML_HEAD: <style type="text/css">/*<![CDATA[*/ pre.src { height: 100px; overflow: auto; } /*]]>*/ </style>
```
Thereby, adapt the `height` attribute to your needs.
---
Tags: org-mode
--- |
thread-64982 | https://emacs.stackexchange.com/questions/64982 | Copy a file content to clipboard with dired | 2021-05-24T08:56:01.063 | # Question
Title: Copy a file content to clipboard with dired
I would like to emulate the fonctionnality of `xclip` in dired. That is, copying file content to clipboard (but without opening it in Emacs).
Sadly, using `dired-do-async-shell-command` and `xclip` does not work. Any ideas ? Thanks !
# Answer
> 4 votes
```
(save-window-excursion
(dired-find-file)
(kill-new (buffer-substring-no-properties (point-min) (point-max)))
(kill-current-buffer))
```
# Answer
> 4 votes
@nichijou's answer is fine. But there's no need to actually put the buffer in a window. You can use `find-file-noselect` to visit a buffer without displaying it.
```
(defun foo ()
(interactive)
(let ((buf (find-file-noselect (dired-get-file-for-visit))))
(with-current-buffer buf
(kill-new (buffer-substring-no-properties (point-min) (point-max))))
(kill-buffer buf)))
```
# Answer
> 0 votes
I can't reproduce your error, and want to suggest that you're possibly using `xclip` incorrectly. This answer should also benefit others because no-one needs to create a custom emacs function for this to work.
From a `dired` buffer, I select a small-sized file, and enter `&` to get the async dialog. Then I enter `xclip -i`. That sends the contents of the selected file to the PRIMARY clipboard, one of the three clipboards present in all modern GUI environments (the other two are called SECONDARY and CLIPBOARD). Then, from a terminal emulator outside emacs, I run `xclip -o` and I do see the contents of that file inserted into the terminal.
If you want `xclip` to operate on the CLIPBOARD clipboard (I know, it is confusing, I didn't design it), then pass it the arguments `-selection clipboard`. Personally, I have it defined as a shell alias. There also exists the command-line program `xsel`, which has shorter option names.
---
Tags: dired
--- |
thread-65055 | https://emacs.stackexchange.com/questions/65055 | org-mode: force heading subtree to start folded | 2021-05-28T13:24:50.767 | # Question
Title: org-mode: force heading subtree to start folded
I know `:ARCHIVE:` does this, but I use that tag to mean the subtree is essentially useless now. I want sth like `:FOLD:`.
# Answer
> 6 votes
You can set the initial visibility for a single subtree with the `visibility` property:
```
* My Folded Heading
:PROPERTIES:
:VISIBILITY: folded
:END:
```
You can set initial visibility options for the entire file by including a `STARTUP` directive:
```
#+STARTUP: overview
```
Finally, you can set this globally via the customizable variable `org-startup-folded`
For details, see the manual (org) Initial visibility
---
Tags: org-mode
--- |
thread-65061 | https://emacs.stackexchange.com/questions/65061 | How Do I Create Init file | 2021-05-28T17:55:40.660 | # Question
Title: How Do I Create Init file
I want to find my init file.. but I cannot, supposedly it must be created? How do I create an init.el file?
Do I just `C-X C-F` and then type `~/.emacs.d/init.el`?
# Answer
Yes, that is one of the default locations emacs looks for configuration files. If it does not exist you can create it and emacs will load it the next time it starts.
From the docs
> Traditionally, file ~/.emacs is used as the init file, although Emacs also looks at ~/.emacs.el, ~/.emacs.d/init.el, ~/.config/emacs/init.el, or other locations.
https://www.gnu.org/software/emacs/manual/html\_node/emacs/Init-File.html
> 0 votes
---
Tags: init-file
--- |
thread-64185 | https://emacs.stackexchange.com/questions/64185 | Emacs not being scaled properly? | 2021-03-28T21:43:40.793 | # Question
Title: Emacs not being scaled properly?
I had to reinstall my OS but I made a backup of my `.emacs.d`. Then, once the new OS was installed, I copied it back and installed all the fonts. This time however, the scaling is really small! With the same `.emacs.d`, OS, machine and the fonts my Emacs scaling was fine before. `emacs -Q` is also tiny. `lsb_release -a` returns,
```
No LSB modules are available.
Distributor ID: Ubuntu
Description: Ubuntu 20.04.2 LTS
Release: 20.04
Codename: focal
```
Here is how I installed it,
```
usr@machine:~$ apt policy emacs27
emacs27:
Installed: 27.1~1.git86d8d76aa3-kk2+20.04
Candidate: 27.1~1.git86d8d76aa3-kk2+20.04
Version table:
*** 27.1~1.git86d8d76aa3-kk2+20.04 500
500 http://ppa.launchpad.net/kelleyk/emacs/ubuntu focal/main amd64 Packages
100 /var/lib/dpkg/status
```
Here is how it looks,
Other people have had this issue and suggested solutions include changes to the init files but I ran this same init file on the same distro and things were fine. So what changed must be outside of my init?
*Edit:*
Instead of `emacs27`, I installed `emacs`, i.e.,
```
emacs:
Installed: 1:26.3+1-1ubuntu2
Candidate: 1:26.3+1-1ubuntu2
Version table:
*** 1:26.3+1-1ubuntu2 500
500 http://us.archive.ubuntu.com/ubuntu focal/universe amd64 Packages
500 http://us.archive.ubuntu.com/ubuntu focal/universe i386 Packages
100 /var/lib/dpkg/status
```
This scales fine!
Edit 2:
I am using Iosevka. Note that the with the same font and init file, Emacs from Ubuntu's repositories renders fine.
# Answer
> 1 votes
Well, since I could not find any non-configuration file based solutions, I ended up adding this to my file.
```
(add-to-list 'default-frame-alist '(width . 80))
(add-to-list 'default-frame-alist '(height . 24))
(add-to-list 'default-frame-alist ; High DPI Fix
`(font . ,(let ((dims (nth 1 (frame-monitor-attributes)))
(m (/ 1.0 388800.0)) (b (/ 23.0 3.0)))
(format "Iosevka-%d" (+ (* m (nth 3 dims) (nth 4 dims)) b)))))
```
Replace `Iosevka` with whatever font you'd like to use. What we are doing here is linearly scaling the font-size `y=mx+b` where the slope and y-intercept were calculated using points `(1920×1080, 13), (3840×2160, 29)`.
---
Tags: gui-emacs, scaling
--- |
thread-65064 | https://emacs.stackexchange.com/questions/65064 | What is the difference/purpose between "require" and "package-install"? | 2021-05-29T03:19:44.953 | # Question
Title: What is the difference/purpose between "require" and "package-install"?
I am trying to understand the subtle nuances of Emacs' packaging system(s). I do not find that anyone has really clarified or explained the difference between two, what I assume to be, key components of Emacs package system: `require` and `package-install`.
I commonly see code like the following in many `init.el` files (illustrative example):
```
(require 'package) ; Use Emacs package system
(add-to-list 'package-archives '("melpa-stable" . "https://stable.melpa.org/packages/") t) ; Add MELPA package repository as a place to go lookup for packages
(package-initialize) ; Turns Emacs package system on
; ... refresh code omitted for brevity
(unless (package-installed-p 'helm) ; Only installed "helm" if we don't see it as already installed
(package-install 'helm)
)
(require 'helm) ; Get helm to actually use
; ...
```
The thought process for understanding what is going on:
* `require` seems to be called for `package` but the "package" for `package` does not need to be "installed". Is this internal somehow?
* Is `package` needed for `use-package` to work but not `require`, correct?
* For `helm` (in this example) we must do/use `package-install` (with some checks) to first "install" `helm` and then `require` to actually use it. Is this correct?
* If we did `(use-package helm ... )` then we would not need either `require` or `package-install 'helm`, right?
To extrapolate:
**If one wanted to use any particular package, they first need to make sure they have an equivalent `package-install` call / statement prior to invoking `require` (or just utilize a `use-package` which will "merge" both steps) on that particular package, correct?**
I just want to be sure I am properly setting up my usage of packages and so forth. Emacs is *very* confusing when it comes to packages, installing, requiring, etc. ... at least that I find.
---
**Q/A Housekeeping Notes:**
According to common advice, there are important differences in the Emacs major versions, so I would like an explanation for each (Emacs version 25, 26, and 27, respectively) for others who may come across the same question but on an older version (if it matters).
*I* am currently on Emacs 27.2 on macOS Catalina (just to be clear).
In an attempt to preempt "duplicate of ..." or "searching will find ...": In my searching, I found require vs. package-initialize? but it does not look like anyone *really* answered the question to satisfaction (or clearly).
# Answer
Think of a *package* as a bunch of e-lisp and maybe other files. Many of these (such as the `package` package itself) come as part of your emacs (these are said to be *built-in*) and so need no further installation. Others, such as `pdf-tools` or `helm` are located in repositories on the interwebs such as *melpa* and so must be downloaded onto your computer before they are available to emacs. This is (part of) what `package-install` does.
A separate concern is to load a package into your running emacs so that you can use its functionality. This is what `require` does. It can only load stuff that is on your system. This is why there is a `package-install` that may have to be done first.
Finally `use-package` can do both things in one shot:
```
(use-package foo)
```
is essentially a fancy wrapper around `(require 'foo)` while
```
(use-package foo
:ensure t)
```
calls `package-install` on `foo`, if necessary.
For a given package, you can do `describe-package` (bound to `C-h P` in vanilla emacs) to see where it comes from and whether it is installed.
There is more to say here: once a package is installed, the magic of autoloads means that `require` may be quite unnecessary: see the previously referenced post require vs. package-initialize? for this.
> 3 votes
---
Tags: package, use-package, require
--- |
thread-65067 | https://emacs.stackexchange.com/questions/65067 | quote copy/paste keys bindings | 2021-05-29T08:43:14.870 | # Question
Title: quote copy/paste keys bindings
how can I copy a quote and paste it onto an emacs file? the shortcuts please?. I have tried to type the text but it is too long to write by hand.
# Answer
> 1 votes
`M-w` copies the selected text into the operating system clipboard, as well as into Emacs’ internal storage.
`C-w` cuts (or “kills”, a name which derives from the very oldest predecessors of Emacs) the selected text, putting it into both the operating system’s clipboard as well as the internal storage. `C-k` kills all the text from the point to the end of the line.
`C-y` pastes (or “yanks”, as it is generally called in Emacs) text into the document.
The internal storage forms a list of all the things you have copied or killed. `C-y` yanks back the text from the head of this list. If you then hit `M-y`, the yanked text will be removed and replaced with the text from the next entry in the list. You can keep hitting `M-y` to go farther and farther back in the list. When you get to the end of the list, the next `M-y` will wrap back around to the beginning again, so this list is called a ring. Thus in the Emacs documentation this is called the `kill-ring`.
In your case you want to copy the text from whatever you’re viewing the quote in, and then go to Emacs and type `C-y`.
I recommend reading the Emacs manual for more information like this. In your case I recommend starting with chapter 12, Killing and Moving Text, which deals with all the ways to cut, copy, and paste text.
In addition to reading the manual online, you can also read it within Emacs itself. Typing `C-h i` will bring up the info viewer. This normally starts at an index of all the manuals installed on your computer, which should at least be the Emacs Manual and the Emacs Lisp Manual, but may include dozens or hundreds of manual from all kinds of programs you have installed (mostly this depends on the operating system that you are using). Select the Emacs Manual, then go down to the chapter you want and select it.
As an Emacs beginner, you may also find the built–in Emacs tutorial helpful. You can access it by typing `C-h t`.
---
Tags: terminal-emacs, copy-paste
--- |
thread-65022 | https://emacs.stackexchange.com/questions/65022 | Why this "keybinding conflicts" message keeps appearing? How can I fix it? | 2021-05-26T20:11:13.610 | # Question
Title: Why this "keybinding conflicts" message keeps appearing? How can I fix it?
After pressing `M-x sly`, I keep receiving this message:
> \[sly\] SLIME detected in 'lisp-mode-hook', causes keybinding conflicts. Remove it for this Emacs session?
The odd thing is that SLIME is not installed in MELPA directories like the other packages:
```
~/.emacs.d/elpa$ ls -l
total 28
-rw-rw-r-- 1 pedro pedro 806 mai 26 16:42 0blayout-readme.txt
drwxrwxr-x 4 pedro pedro 4096 mai 14 17:17 archives
drwx------ 3 pedro pedro 4096 mai 26 16:45 gnupg
drwxrwxr-x 2 pedro pedro 4096 mai 21 20:59 paredit-20191121.2328
drwxrwxr-x 2 pedro pedro 4096 mai 14 17:27 rainbow-blocks-20210412.1937
drwxr-xr-x 6 pedro pedro 4096 mai 22 21:02 sly-20210303.1148
drwxrwxr-x 2 pedro pedro 4096 mai 22 21:18 transpose-frame-20200307.2119
```
Apparently, it was installed with QuickLisp. After pressing `M-x locate-library` in Emacs I get:
```
Library is file ~/.quicklisp/dists/quicklisp/software/slime-v2.26.1/slime.el
```
This is annoying me because Slime keybindings stopped working recently.
I am new to Common Lisp, Emacs, Sly/Slime, and Quicklisp. Maybe I messed up with stuff.
# Answer
> 1 votes
Both SLIME and SLY are user interfaces for interacting with a running Lisp process. SLY is much newer than SLIME, and so it copies some conventions and key bindings from SLIME. You can’t usefully use both at the same time, so the author of SLY made it check to see if you have SLIME configured as well. This is annoying you, but it would certainly annoy you more if both SLIME and SLY were running and stepping on each other’s all the time.
The right answer here is to disable one and use the other for a while, then swap. Figure out which you prefer and then uninstall the other.
---
Tags: key-bindings, package-repositories, slime, sly
--- |
thread-64926 | https://emacs.stackexchange.com/questions/64926 | Emacs elisp debugger: How do i make the debugger jump to source when i press s? | 2021-05-20T12:26:31.930 | # Question
Title: Emacs elisp debugger: How do i make the debugger jump to source when i press s?
The builtin elisp debugger (i.e. the regular one, `debug`, *not* edebug) has a default binding of `s` to command `backtrace-goto-source`.
When I try to use it, it says: `Source code location not known`
You can see what I mean by doing this:
1. Set contents of `/tmp/blah.el` to be:
```
(defun abc ()
(error "hello"))
```
2. Run the command `emacs -Q --eval '(progn (setq debug-on-error t) (load-file "/tmp/blah.el") (abc))'`
3. Highlight fourth line in buffer, the one that reads `abc()`
4. Press `s` key, the error says `Source code location not known`
The docs for `backtrace-goto-source` say:
`If its location is known, jump to the source code for the frame at point`
I checked the builtin info documentation for section *18.1 The Lisp Debugger*, but i couldn't really find a setting for what i want. How do I make a symbol's location known to the debugger so it jumps to the source location when I press s?
Interesting note: the behavior of pressing mouse-1 is completely different from pressing s, and sometimes navigates to bundled source location gzs for me, but also sometimes opens an "Open File" dialog (GUI).
# Answer
> 3 votes
`s` is bound to a new function that was recently added, and indeed it appears to be non–functional. I took a look at the source code, and it does attempt to pull file and line number from the stack frame, but none of the stack frames have any file and line number information :)
It then tries to run hook functions, but the list of hook functions is empty. Those hooks are the ones that are supposed to open the correct source file.
It would be helpful if you could open a bug report about this (use `M-x report-emacs-bug`). It may be that some part of the implementation was left out, or that it was never finished. Probably the best fix is to simply remove the key binding until the problem is fixed.
In the mean time, hitting enter (or left clicking) on any line in the stack trace will take you to the definition of the named function, if it can find it. On most code this will work just fine, but it isn’t very helpful in some situations, such as when someone has called `eval`. In those cases you can jump to the definition of `eval` or to any of the functions that the evaluated code calls, but there’s no way to jump to the code it is evaluating.
---
Tags: debugging, symbols, tags, debug
--- |
thread-65073 | https://emacs.stackexchange.com/questions/65073 | How can I work around json-encode error with key "t" | 2021-05-29T15:22:40.660 | # Question
Title: How can I work around json-encode error with key "t"
While working with JSON in Emacs Lisp, I got an error `json-encode-key: Bad JSON object key: t`. It made sense to me that the key was `"t"` but not necessarily *why*, or *what* I can do about it.
The following code sample reproduces this scenario:
```
(let ((foo (json-read-from-string "{\"t\":42}")))
(message "%s" foo) ; ((t . 42))
(message "%s" (json-encode foo))) ; json-encode-key: Bad JSON object key: t
```
How can I work around this, given that the JSON in question involves a key of `"t"`?
# Answer
This is a well-known long-standing bug in `json.el` that has been fixed in the latest development version of Emacs (what will be released in the future as Emacs 28): https://bugs.gnu.org/42545
If you don't have access to the development version of Emacs, but have an Emacs 27 built with native JSON support (i.e. configured `--with-json` to link against the Jansson library, which is the default on systems where this library is available), then you can use the new native (and faster) functions in place of their `json.el` counterparts:
```
(let ((foo (json-parse-string "{\"t\":42}" :object-type 'alist)))
(message "%s" foo) ; ((t . 42))
(message "%s" (json-serialize foo))) ; {"t":42}
```
See `(info "(elisp) Parsing JSON")` for more on this.
Otherwise, the only workaround for this bug is to avoid objects that have confusable keys such as the symbol `t`. If you generate the data, then happy days: the fix is as simple as using a different object or key type that isn't as ambiguous, for example:
```
(let* ((json-object-type 'hash-table)
(foo (json-read-from-string "{\"t\":42}")))
(message "%s" foo) ; #s(hash-table ...)
(message "%s" (json-encode foo))) ; {"t":42}
(let* ((json-key-type 'keyword)
(foo (json-read-from-string "{\"t\":42}")))
(message "%s" foo) ; ((:t . 42))
(message "%s" (json-encode foo))) ; {"t":42}
```
For more on this, have a read through the variables defined at the top of `M-x find-library RET json RET`.
If you don't generate the data, then you will probably need to sanitise it first.
> 2 votes
---
Tags: json
--- |
thread-65050 | https://emacs.stackexchange.com/questions/65050 | How to automatically accept: Please answer y or n. Process `LaTeX' for document `program' running, kill it? (y or n) | 2021-05-28T10:22:18.267 | # Question
Title: How to automatically accept: Please answer y or n. Process `LaTeX' for document `program' running, kill it? (y or n)
When I save a `LaTeX` file, I want to compile it as well on the background. In order to achieve it I have done following module:
```
(defun my-run-latex ()
(interactive)
(save-all)
(setq TeX-command-force "LaTeX")
(setq TeX-clean-confirm t)
(TeX-command-master))
(add-hook 'LaTeX-mode-hook (lambda ()
(local-set-key (kbd "C-x C-s") 'my-run-latex)))
```
But when I do that I keep having following message:
```
Please answer y or n. Process `LaTeX' for document `program' running, kill it? (y or n)
```
What may be the reason for this message? Is it possible to ignore it or automatically confirm it via `y`?
# Answer
The reason for the message is exactly what it says. A LaTeX process is still running for the master file.
AucTeX is running LaTeX asynchronously. If the LaTeX sources are long the compilation may still be running when you save twice in quick succession.
The right way avoiding that message automatically is killing the still running LaTeX process before `TeX-command-master`.
I suggest the following version of your function `my-run-latex` that does kill the running process if it exists.
Saving files is also done as it is supposed by the AucTeX package. You can change it back to your version with the (for me non-existing) function `save-all` if you want.
```
(defun my-run-latex ()
"Save all buffers and run LaTeX on the current master."
(interactive)
(let* ((TeX-command-force "LaTeX")
(TeX-clean-confirm t)
(TeX-save-query nil)
(master (TeX-master-file))
(process (and (stringp master) (TeX-process master))))
(TeX-save-document master)
(when (and (processp process)
(eq (process-status process) 'run))
(delete-process process))
(TeX-command-master)))
```
> 4 votes
---
Tags: latex
--- |
thread-34261 | https://emacs.stackexchange.com/questions/34261 | Horizontal Scroll Wheel on Mouseover Buffer | 2017-07-18T20:31:51.373 | # Question
Title: Horizontal Scroll Wheel on Mouseover Buffer
My mouse has a horizontal scroll function, where I can tap the scroll wheel left and right to scroll horizontally. By default, it seems Emacs does nothing with that. The scroll wheel produces `<mouse-6>` and `<mouse-7>` key events, so I added this to my `.emacs` as a very basic way to get it to work.
```
(global-set-key (kbd "<mouse-6>") (lambda () (interactive) (scroll-right 6)))
(global-set-key (kbd "<mouse-7>") (lambda () (interactive) (scroll-left 6)))
```
This is fairly close to what I want. But the trouble is this. With vertical scrolling, Emacs always scrolls the buffer that the mouse is currently over. With my custom keys that I've just set here, horizontal scrolling happens in the *active buffer*, not the buffer that the mouse is over. I'd like to get the latter behavior, so that my scroll wheel consistently scrolls whichever buffer the mouse is over.
# Answer
> 2 votes
No need to handroll it yourself. This is provided out of the box in emacs 27, and it probably was available for longer:
> This feature is off by default; the variable `mouse-wheel-tilt-scroll` turns it on, if you customize it to a non-nil value.
```
(setq mouse-wheel-tilt-scroll t)
```
---
Tags: key-bindings, mouse, scrolling
--- |
thread-65065 | https://emacs.stackexchange.com/questions/65065 | Don't replace my buffers with *warnings* or *message* buffers? | 2021-05-29T05:48:33.157 | # Question
Title: Don't replace my buffers with *warnings* or *message* buffers?
Current behavior:
* Emacs replaces one of my buffers with `*warnings*` or `*messages*` if I have multiple buffers open.
* However Emacs creates a new buffer and displays `*warnings*` or `*messages*` if I have exactly one buffer open.
I want this to be the default behavior on my Emacs, that is, irrespective of how many buffers I may have open, I want Emacs to always create a new buffer for its `*warnings*` or `*messages*` (and other similar buffers).
Further I want my Emacs to figure out the following on it's own when creating new buffers:
1. Tall buffers should always split vertically
2. Wide buffers should always split horizontally
How do I accomplish this behavior with my Emacs?
# Answer
You can customize variable `display-buffer-alist` to fine-tune how Emacs handle creating a new window.
Read its documentation `C-h v display-buffer-alist` or the info node on this topic at (elisp) Choosing Window if you had some spare time.
Here is also a good youtube video on this topic from Protesilaos, Emacs: window rules and parameters (\`display-buffer-alist' and extras)
> I want Emacs to always create a new buffer for its *warnings* or *messages* (and other similar buffers)
Put this somewhere in your configuration file,
```
(setq display-buffer-alist ;; Setting window rules
("\\*messages.*" ;; For buffer with a name beginning with "*messages",
(display-buffer-in-side-window) ;; Display it in side window
(window-width . 0.25) ;; Side window takes up 1/4th of the screen
(side . right) ;; On the right side of the screen, please
)
("\\*warnings.*" ;; For buffer with a name beginning with "*warnings",
(display-buffer-in-side-window) ;; Display it in side window
(window-width . 0.25) ;; Side window takes up 1/4th of the screen
(side . right) ;; On the right side of the screen, please
)
;; Add more if you want ....
)
```
Remove the comment if it's too much, this makes Emacs consistent you no longer have to think of where to look for the buffer anymore, if it pops up, Emacs will always put it on the right side of the screen. (Using "screen" loosely here, it's technically called a "frame".
> 1 votes
# Answer
You can customize the variables `split-height-threshold` and `split-width-threshold` to adjust how windows are split. Likely when you already have multiple windows, they are already smaller than `split-height-threshold` so it opts not to split any of them again.
> 1 votes
---
Tags: window, message, warning
--- |
thread-65079 | https://emacs.stackexchange.com/questions/65079 | Add a filter when generating today's agenda view | 2021-05-30T03:48:02.883 | # Question
Title: Add a filter when generating today's agenda view
#### what I want to achieve
Say a `++2d` habit not accomplished yesterday, I don't want it shown in today's agenda view but shown in tomorrow's and 2 days after tomorrow's and so forth.
#### what I tried
```
(defun my/several-day-habit-and-not-due-today ()
"only work for today's habit list"
(interactive)
(let ((time (my/floor-time-to-date (org-time-string-to-time (org-entry-get nil "SCHEDULED"))))
(repeater (org-get-repeat)))
(string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([hdwmy]\\)" repeater)
(let ((repeater-type (match-string 1 repeater))
(day (string-to-number (match-string 2 repeater)))
(what (match-string 3 repeater))
(today (my/floor-time-to-date)))
(when (and (equal what "d")
(< day 5))
(while (time-less-p time today)
(setq time (time-add time (* day 60 60 24))))
(time-less-p today time)))))
(defun my/org-is-habit-p (&optional pom)
"Is the task at POM or point a habit?"
(and (string= "habit" (org-entry-get (or pom (point)) "STYLE" t))
(not (my/several-day-habit-and-not-due-today)) ;will show in ordinary agenda
))
(advice-add 'org-is-habit-p :override 'my/org-is-habit-p)
```
This way filtered it out as a habit, but it will show as a normal entry in agnda view.
#### any idea how I can filter it out in today's agenda view?
# Answer
I don't use org-habit so I can not provide a full answer, but it looks like you can use a `org-agenda-before-sorting-filter-function` function for this. Read its docstring to see how it works.
Then make up some predicate expression that checks if a line is one of your particular org-habits and replace it in the appropriate place in the following code block:
```
(defun org-agenda-yesterday-habit-filter (line)
;; (pp line)
(if (and (= (print (time-to-days (org-time-from-absolute (org-find-text-property-in-string 'date line))))
(print (org-today)))
"replace this string with some predicate expression that returns t for your habit")
nil
line))
(setq org-agenda-before-sorting-filter-function 'org-agenda-yesterday-habit-filter)
```
You could uncomment the `pp` expression to look at the string object in the `*Messages*` buffer. Also, the `if` could be replaced by a `unless` but I leave it in this form here for clarity.
> 0 votes
---
Tags: org-mode, org-agenda, org-habit
--- |
thread-65083 | https://emacs.stackexchange.com/questions/65083 | Is it possible to open Deft in a sidebar? | 2021-05-30T07:33:20.817 | # Question
Title: Is it possible to open Deft in a sidebar?
I'm trying to open Deft in the left sidebar using this code:
```
(setq display-buffer-alist
'(("*Deft*"
(display-buffer-in-side-window)
(window-width . 0.25)
(side . left)
(slot . 0))))
```
This is not working and every time I call `M-x deft`, it shows in the main window.
What's wrong with my code? Has anyone had success in running Deft in the sidebar?
# Answer
Here's the definition of `deft` (version 20210101.1519 on MELPA)
```
(defun deft ()
"Switch to *Deft* buffer and load files."
(interactive)
(switch-to-buffer deft-buffer)
(if (not (eq major-mode 'deft-mode))
(deft-mode)))
```
So it uses your current window, then switch to a buffer with a name of the value of `deft-buffer` variable, `"\*Deft\*"` by default, then call `deft-mode`. This means that it doesn't create a new window, so setting `display-buffer-alist` does nothing. (Hope this is clear enough.)
You can probably write this in function advice, I prefer to not do this because of reasons. So here is a new function
```
(defun deft-side-window ()
(interactive)
(let ((dummy-buf (generate-new-buffer deft-buffer)))
(with-current-buffer dummy-buf
(deft-mode))
(display-buffer dummy-buf)))
```
Firstly, it creates a new buffer named after the variable `deft-buffer`, call `deft-mode` then having Emacs try to display it, with this, it respects your `display-buffer-alist`.
Here's another version with your window rules if you want to do it manually.
```
(defun deft-side-window ()
(interactive)
(let ((dummy-buf (generate-new-buffer deft-buffer)))
(with-current-buffer dummy-buf
(deft-mode))
(display-buffer-in-side-window dummy-buf
'((side . left)
(slot . 0)
(window-width . 0.25))))))
```
I messed up the formatting but it works! Hope this helps.
> 2 votes
---
Tags: window, window-splitting, deft-mode, side-bar
--- |
thread-65090 | https://emacs.stackexchange.com/questions/65090 | How to start a persistent asynchronous process trough emacs? | 2021-05-30T16:23:12.410 | # Question
Title: How to start a persistent asynchronous process trough emacs?
I am writing a lisp program to be run as a batch file through emacs.
The program calls an external application which is supposed to stay running after the call to emacs finishes.
The two basic ways for emacs to call external application that I am aware of are `call-process` and `start-process`.
Since `call-process` creates a synchronous process, it does not meet my requirement to stay alive after the call to emacs is done, so I believe my only alternative is `start-process`.
However, even though `start-process` is supposed to create asynchronous processes, it seems like the created process is killed when emacs finishes.
**Question**. How to start a persistent asynchronous process trough batch in emacs, i.e, one that neither waits for, nor gets killed when emacs finishes?
In the examples below I am using, as external application, the pdf viewer Okular, but you might substitute it for any other GUI application.
```
;; Does not work because emacs waits for call-process to finish.
SHELL-PROMPT> emacs -Q --batch --eval '(call-process "okular" nil nil nil)'
;; Does not work because emacs apparently kills the created process upon exit
SHELL-PROMPT> emacs -Q --batch --eval '(start-process "Okular" nil "okular")'
;; Here is some more evidence that emacs kills the created process upon exit
SHELL-PROMPT> emacs -Q --batch --eval '(progn (start-process "Okular" nil "okular") (sit-for 3))'
```
# Answer
> 3 votes
You can use `call-process` the same way as you did, but just replace the third argument by 0. If the third argument is 0, Emacs don't wait for the process and quit without killing it.
```
SHELL-PROMPT> emacs -Q --batch --eval '(call-process "okular" nil 0 nil)'
```
---
Tags: async, subprocess, call-process
--- |
thread-65078 | https://emacs.stackexchange.com/questions/65078 | Using Shackle to manage WoMan buffers | 2021-05-30T02:25:27.823 | # Question
Title: Using Shackle to manage WoMan buffers
I would like `shackle.el` to manage the buffers created by `WoMan`.
Here's the configuration I'm using:
```
(use-package shackle
:config
(setq shackle-rules '((woman-mode :select t :align below :size 0.5)))
(shackle-mode 1))
```
This should make `WoMan` buffers to appear on the bottom half of the screen.
But for some reason, `shackle` does not seem to work with the buffers created by `WoMan` (it works fine with other buffers, e.g., those that use `help-mode`). Any workaround?
# Answer
> 1 votes
I don't know why this doesn't work. It seems that using the buffer's name instead of `woman-mode` and adding `:popup t` works:
```
(use-package shackle
:config
(setq shackle-rules '(("\\`\\*WoMan .*\\*\\'" :select t :popup t :align below :size 0.5)))
(shackle-mode 1))
```
---
Tags: buffers, window-splitting
--- |
thread-65088 | https://emacs.stackexchange.com/questions/65088 | Format alist into bullet points | 2021-05-30T14:43:04.160 | # Question
Title: Format alist into bullet points
I have this couple of alists:
> `((melpa . 49) (gnu . 14) (nongnu . 1))`
>
> `((nongnu (nongnu . markdown-mode)) (gnu (gnu . adaptive-wrap) (gnu . auctex) (gnu . company) (gnu . consult) (gnu . csv-mode) (gnu . dash) (gnu . diff-hl) (gnu . hydra) (gnu . json-mode) (gnu . queue) (gnu . rainbow-mode) (gnu . spinner) (gnu . transient) (gnu . vertico)) (melpa (melpa . a) (melpa . biblio) (melpa . biblio-core) (melpa . bibtex-actions) (melpa . bibtex-completion) (melpa . cider) (melpa . clojure-mode) (melpa . embark) (melpa . embark-consult) (melpa . envrc) (melpa . epl) (melpa . f) (melpa . flymake-kondor) (melpa . flymake-proselint) (melpa . flymake-quickdef) (melpa . flyspell-correct) (melpa . git-commit) (melpa . git-identity) (melpa . goto-last-change) (melpa . ibuffer-vc) (melpa . inheritenv) (melpa . keychain-environment) (melpa . magit) (melpa . magit-section) (melpa . modus-themes) (melpa . multiple-cursors) (melpa . no-littering) (melpa . olivetti) (melpa . orderless) (melpa . package-lint) (melpa . package-lint-flymake) (melpa . parsebib) (melpa . parseclj) (melpa . parseedn) (melpa . pdf-tools) (melpa . pkg-info) (melpa . restart-emacs) (melpa . s) (melpa . scratch) (melpa . sesman) (melpa . symbol-overlay) (melpa . tablist) (melpa . typo) (melpa . uuidgen) (melpa . web-mode) (melpa . wgrep) (melpa . with-editor) (melpa . xterm-color) (melpa . yaml-mode)))`
What I am looking for is printing them in format like the following:
> * melpa (49): a, biblio, biblio-core ...
> * gnu (14): adaptive-wrap, auctex, company ...
> * nongnu (1): markdown-mode
Is it possible?
# Answer
> 3 votes
I am not sure what kind of answer you expect, but of course it is possible to get the output as a string. It looks like you already know some elisp (assuming that you posted a self defined function), so I guess you are mainly interested in how to print bullet points. You can just insert a bullet into a string using `M-x insert-char`, for example
```
(print "•")
```
where you use the aforementioned command to insert the bullet point.
Ah... what the heck, it is a nice little exercise, so here is the code to get your requested format:
```
(mapconcat
(lambda (archive)
(concat "•"
(format "%s (%s)" (car archive) (cdr archive))
": "
(mapconcat
(lambda (ap-pair)
(symbol-name (cdr ap-pair)))
(alist-get (car archive) list2)
" ")))
list1
"\n")
```
where I have named your first and second list `list1` and `list2` respectively
---
Tags: pretty-print, alists
--- |
thread-65094 | https://emacs.stackexchange.com/questions/65094 | How to quickly cycles through buffers of the same major mode as current one? | 2021-05-30T21:06:10.800 | # Question
Title: How to quickly cycles through buffers of the same major mode as current one?
I'd like to find a way to cycle through all buffers that use the same major mode as the current buffer. For all major modes, including the special buffers.
**Use case example:** when refactoring code I often use several instances of the super useful deadgrep buffers. I search for things before I start to identify the locations that must be edited, and regularly update them as I go up to the point where nothing is found. So I'd like to quickly iterate through all of those buffers in a window, while I use other windows to hold code buffers (where I also might want to cycle through them).
How can I do this?
**Investigation so far:** I tried the iflipb external package and the built-in Buffer Selection bs.el. So far I have not found a way to use them to do what I want, but I'm going through to code to see if I can do that.
# Answer
If you use Icicles then just use one of these with **`C-x b`**:
* **`C-0`** (or `M-0` or `C-u 0` etc.): The candidate buffers will have the ***same*** mode as the current buffer
* **`C-u`**: Same, but include also buffers whose mode is ***derived*** from that of the current buffer.
In Icicle mode, `C-x b` is bound to multi-command `icicle-buffer`.
---
And you need not choose such filtering before you invoke the command. You can instead filter the same way on the fly, during buffer-name completion:
* **`C-x M +`**: Keep only buffers whose mode is the *same* as the current buffer.
* **`C-x C-m +`**: Same, except keep also buffers whose mode is *derived* from that of the current buffer.
---
The same is true for *all* Icicles commands that want a buffer name as input.
So for example, you can use `C-0` with **`C-x k`** to have as candidate buffers to kill, only those with the same mode as the current buffer.
And because that too is a multi-command, you can use it to kill multiple buffers with a single invocation. You can even kill *all* candidates whose name matches your current minibuffer input, using **`C-!`**.
---
See Icicles: Buffer-Name Input.
> 1 votes
---
Tags: buffers, major-mode
--- |
thread-65101 | https://emacs.stackexchange.com/questions/65101 | Pass selected text as argument to a script and replace selected text with output from the script | 2021-05-31T05:58:13.780 | # Question
Title: Pass selected text as argument to a script and replace selected text with output from the script
I'd like to pass some selected text in a buffer to a python script. The python script will process the string and print the result to stdout. This output should replace the original string that was selected. Can this be done?
To tackle this, I first pass a selected buffer to my python script. Below is the elisp function that I wrote, following a similar function to implement the command `wc`
```
(defun it ()
(interactive)
(shell-command (concat "echo "
(buffer-substring (mark) (point))
" | /Users/john/bin/t ")))
```
This command succeeds and prints the output in the mini-buffer. Is there an elisp-way to overwrite the selected text with this output?
# Answer
> 1 votes
Would `shell-command-on-region`, using a prefix argument fit your requirements? `shell-command-on-region` is by default bound to `M-|` (Meta key with '|' key) and the prefix argument is by default bound to `C-u` (Control 'u').
Combining those you can use the key sequence `C-u M-|` (Control 'u' followed by Meta '|') to pipe a region of text to a command and replace the region with the output of the command.
It asks for the command to pipe the selected text to, in your example that would be `/Users/john/bin/t`, and runs that command with the selected text on standard input.
# Answer
> 2 votes
This is perfectly possible and you are almost there. For example to replace e.g. the command/selected text `ls` in a buffer you can use:
```
(defun replace-region-from-shell-output ()
(interactive)
(let ((command-output (shell-command-to-string (buffer-substring (mark) (point)))))
(kill-region (mark) (point))
(insert command-output)))
```
---
Tags: replace, shell-command
--- |
thread-35960 | https://emacs.stackexchange.com/questions/35960 | Magit: Is it possible to edit text directly in "Unstaged changes"? | 2017-10-06T08:02:52.223 | # Question
Title: Magit: Is it possible to edit text directly in "Unstaged changes"?
Windows 10, Emacs 25.1, Magit
Execute command `magit-status` and press "**TAB**". Here result:
If I want to change this text I go to my editor (e.g. Notepad++) and edit text.
The question is:
Can I directy edit text in magit buffer when files are in **Unstaged changes**?
# Answer
> 3 votes
The status buffer is just an interface to git; it's not an editor in itself, so you can't edit right from there. In Emacs, this isn't a problem, since you just RET and it takes you to the file/line/column you were at. There is still a feature request for this enhancement, but such functionality would be weird IMO since you'd *have* to enter some other mode within `magit-status-mode` since most keys already mean something special.
You mention though that you want to use a different editor to edit this text. If *that* is your real question, read below.
If your editor supports command-line arguments, you can do this rather easily at a file-level by advising `magit-diff-visit-file`:
```
(defun open-in-vscode (orig-fun &rest args)
(let ((file (car args)))
;; If you don't want this behavior for every file/project,
;; you can still keep the old behavior using `orig-fun`.
(if (or t (should-open-in-vs-code file))
(call-process
;; This is VS Code, the only other editor I have installed
;; Look up Notepadd++'s arguments as appropriate.
"/Applications/Visual Studio Code.app/Contents/Resources/app/bin/code"
nil nil nil
file)
(apply orig-fun args))))
(advice-add #'magit-diff-visit-file :around #'open-in-vscode)
```
If you want to jump to the file:line:column, you'll have to dig deeper into `magit-diff-visit-file` and possibly provide a reimplementation (then advising using `:override`) that will do the right thing for you. The line/column information is already available in `magit-diff-visit-file`, so it would just be a matter of putting that information to other use.
# Answer
> 1 votes
If you make the status buffer editable (`M-x read-only-mode`), you actually can edit it. Note, though, that this edits only the magit status buffer, and not the underlying file, and this is generally very hacky and it's easy to break the status buffer this way.
However, this can still be useful because you can then perform git operations on the edited diffs - e.g. you can edit a part of a diff, then select and stage the edited variant.
One particularly useful operation which can be done this way is to reorder lines to allow staging only some edits in consecutive edited lines. For example, if the old file is:
```
fun(apple);
bun(banana);
```
and it was changed to:
```
fun(apple2);
bun(banana2);
```
then the diff will be:
```
-fun(apple);
-bun(banana);
+fun(apple2);
+bun(banana2);
```
If you wish to stage only changes in the first line, staging only the `-fun(apple);` and `+fun(apple2);` lines will not do what you want - it will reorder the calls. However, by making the magit status buffer writable, you can reorder lines to make it look like this:
```
-fun(apple);
+fun(apple2);
-bun(banana);
+bun(banana2);
```
Then, you can select the first two lines and stage them, achieving the desired result.
---
Tags: magit
--- |
thread-65113 | https://emacs.stackexchange.com/questions/65113 | C-i combination doesn't work with lowercase i | 2021-06-01T05:10:14.993 | # Question
Title: C-i combination doesn't work with lowercase i
I've configured Doom emacs to run an interactive evil-ex command in visual mode, the reaconfiguration is as below:
```
(defun evil-insert-into-lines ()
(interactive)
(evil-ex "'<,'>norm I"))
(defun evil-append-to-lines ()
(interactive)
(evil-ex "'<,'>norm A"))
(define-key evil-visual-state-map (kbd "C-i") 'evil-insert-into-lines)
(define-key evil-visual-state-map (kbd "C-a") 'evil-append-to-lines)
```
The second function is invoked both by pressing C-a and C-shift-a (C-A) but the first function only works when I press (C-shift-i). Anyone has any idea what could be the reason?
# Answer
Now I get the idea, `C-i` is the same thing as `TAB` character so binding it to a function is a little tricky. this anwer worked for me. Here's the new config:
```
(define-key input-decode-map (kbd "C-i") (kbd "H-i"))
(define-key evil-visual-state-map (kbd "H-i") 'evil-insert-into-lines)
```
> 0 votes
# Answer
Spacemacs has a variable to turn on/off translation of `C-i` under GUI emacs. Perhaps you could try these lines or look for if doom emacs has similar feature provided.
Relevant Code
> 0 votes
---
Tags: key-bindings, evil, doom
--- |
thread-65104 | https://emacs.stackexchange.com/questions/65104 | How to pass org-babel code block as variable to another code block? | 2021-05-31T10:26:15.480 | # Question
Title: How to pass org-babel code block as variable to another code block?
I would like to pass the code from code block `test_python` to `script`. I do not want `test_python` to be evaluated, but simply to have the source code inserted into `script` when I evaluate script. The goal is to have a more generic extended version of `script` that will do some useful stuff to setup the environment and run the contents of `test_python` such that it can be run on different machines. I'd like to eventually hide the `script` block in a `#+INCLUDE`ed org mode file, then just be able to have the `test_python` block and a `#+CALL` to `script` in the primary org mode.
A minimal example where I am trying to do this is:
```
#+NAME: test_python
#+BEGIN_SRC ipython :results none :exports none
import numpy as np
x0 = np.arange(-1, 1, 1/10.)
x1 = np.arange(-1, 1, 1/10.)
x0, x1 = np.meshgrid(x0, x1)
y_truth = x0**2 - x1**2 + x1 - 1
print('inside python')
#+END_SRC
#+NAME: script
#+HEADER: :var python_code=""
#+BEGIN_SRC bash :results output
#!/bin/bash
result=$(python <<EOF
$python_code
EOF
)
echo $python_code
echo $result
echo "done test"
#+END_SRC
#+NAME: script_generator
#+CALL: script[:var python_code=test_python]
```
Adding one more thing: I am actually tangling `script` to write to file. I just removed that for the sake of the example.
--- Edit
I had left out some of this to try to get to a minimal example, but it seems that will make the question more clear. Ultimately I want this to look like the following.
any org file I'm currently working in:
```
* Some cool org stuff
:PROPERTIES:
:OUT_SCRIPT: /ssh:otherMachine:~/scripts/test_python.sh
:END:
#+INCLUDE: ~/org/script_utils.org
#+NAME: test_python
#+BEGIN_SRC ipython :results none :exports none
import numpy as np
x0 = np.arange(-1, 1, 1/10.)
x1 = np.arange(-1, 1, 1/10.)
x0, x1 = np.meshgrid(x0, x1)
y_truth = x0**2 - x1**2 + x1 - 1
print('inside python')
#+END_SRC
#+NAME: script_generator
#+CALL: script[:var python_code=test_python,script_path=OUT_SCRIPT]
```
and
script\_utils.org:
```
#+NAME: script
#+HEADER: :var python_code="", script_path=""
#+BEGIN_SRC bash :results output :tangle script_path
#!/bin/bash
result=$(python <<EOF
$python_code
EOF
)
echo $python_code
echo $result
echo "done test"
#+END_SRC
```
# Answer
> 5 votes
The Noweb reference syntax may help in such cases. Using this syntax, the body of a given code block can be executed inside the body of another code block. As a summary of the Org manual page:
1. You have to `NAME` the first code block
2. Add its `<<NAME>>` in a second code block, which will have `:noweb yes` as a header argument. Then, `<<NAME>>` will be expanded/interpreted as the contents of the first code block.
I give an example below, adapted from your own example:
```
#+NAME: test_python
#+BEGIN_SRC python :results none :exports none
import numpy as np
x0 = np.arange(-1, 1, 1/10.)
x1 = np.arange(-1, 1, 1/10.)
x0, x1 = np.meshgrid(x0, x1)
y_truth = x0**2 - x1**2 + x1 - 1
print('inside python')
#+END_SRC
#+NAME: script
#+BEGIN_SRC bash :results output :noweb yes
#!/bin/bash
result=$(python <<EOF
<<test_python>>
EOF
)
echo $result
echo "done test"
#+END_SRC
#+RESULTS: script
: inside python
: done test
```
---
Tags: org-mode, org-babel
--- |
thread-65110 | https://emacs.stackexchange.com/questions/65110 | Problem reducing over string | 2021-06-01T04:39:03.807 | # Question
Title: Problem reducing over string
I wanted to define a function that removes all spaces from a given string:
```
(defun remove-whitespace (raw-string)
(cl-reduce (lambda (acc char)
(if (equal " " (char-to-string char))
acc
(concat acc char))) raw-string :initial-value " "))
```
However, evaluating `(remove-whitespace "hello world")` results in:
```
Debugger entered--Lisp error: (wrong-type-argument sequencep 104)
concat(" " 104)
(if (equal " " (char-to-string char)) acc (concat acc char))
(lambda (acc char) (if (equal " " (char-to-string char)) acc (concat acc char)))(" " 104)
cl-reduce((lambda (acc char) (if (equal " " (char-to-string char)) acc (concat acc char))) "hello world" :initial-value " ")
remove-whitespace("hello world")
```
This is odd because the char code 104 must have been converted to a string by `char-to-string`. What am I missing?
**Self-answer**: It should have been (concat acc (char-to-string char)), not just (concat acc char).
# Answer
```
(defun remove-whitespace (raw-string)
(cl-reduce (lambda (acc char)
(if (equal ?\s char)
acc
(concat acc (char-to-string char)))) raw-string :initial-value ""))
```
---
## OR
```
(defun remove-whitespace (raw-string)
(cl-reduce (lambda (acc char)
(if (equal " " (char-to-string char))
acc
(concat acc (char-to-string char)))) raw-string :initial-value ""))
```
---
NOTE that `char` is an integer, therefore you can't concat it.
> 2 votes
# Answer
```
(replace-regexp-in-string " " "" "Hello world")
```
> 4 votes
---
Tags: string
--- |
thread-65097 | https://emacs.stackexchange.com/questions/65097 | How to properly use defcustom with backquote / comma grammar? (to edit a mode's font-lock-keywords) | 2021-05-30T23:36:34.513 | # Question
Title: How to properly use defcustom with backquote / comma grammar? (to edit a mode's font-lock-keywords)
I'm trying to edit a mode's `font-lock-keywords` variable to use `defcustom` instead of `defconst` (which it was using previously). Obviously, this is because I want to be able to easily customize the mode's font lock keywords.
Currently it's using a backquote construct to evaluate the list, like so:
```
(defcustom v-font-lock-keywords
`(
;; builtin
(,v-builtin-keywords-regexp . font-lock-builtin-face)
;; careful
(,v-careful-keywords-regexp . font-lock-warning-face)
;; @ # $
;; ("#\\(?:include\\|flag\\)" . 'font-lock-builtin-face)
("[@#$][A-Za-z_]*[A-Z-a-z0-9_]*" . 'font-lock-warning-face)
;; declaration
(,v-declaration-keywords-regexp . font-lock-keyword-face)
;; ... more of the same
;; variable references
("\\($?_?[a-z]+[a-z_0-9]*\\)" 1 'font-lock-variable-name-face))
"An alist mapping regexes to font-lock faces."
:type '(repeat sexp)
:group 'v-mode)
```
The problem is, if I use this backquote / comma structure as it currently exists, I can't properly use the `customize` interface to change the variable.
For example, when I customize one element of the list to have a different face, now the evaluated value for `,v-builtin-keywords-regexp` gets hardcoded into my `.emacs`:
```
(custom-set-variables
;; custom-set-variables was added by Custom.
;; If you edit it by hand, you could mess it up, so be careful.
;; Your init file should contain only one such instance.
;; If there is more than one, they won't work right.
...
'(v-font-lock-keywords
(quote
(("\\<\\(any\\(?:_\\(?:\\(?:floa\\|in\\)t\\)\\)?\\|b\\(?:ool\\|yte\\(?:ptr\\)?\\)\\|charptr\\|f\\(?:32\\|64\\)\\|i\\(?:1\\(?:28\\|6\\)\\|64\\|nt\\|[8t]\\)\\|rune\\|s\\(?:ize_t\\|tring\\)\\|u\\(?:1\\(?:28\\|6\\)\\|32\\|64\\)\\|voidptr\\)\\>" . font-lock-builtin-face)
("\\<\\(C\\|__global\\|as\\(?:sert\\)?\\|break\\|continue\\|defer\\|error\\|go\\(?:to\\)?\\|i\\(?:mport\\|nline\\|[ns]\\)\\|live\\|mut\\|or\\|panic\\|unsafe\\)\\>" . font-lock-warning-face)
("[@#$][A-Za-z_]*[A-Z-a-z0-9_]*" quote font-lock-warning-face)
("\\<\\(enum\\|fn\\|interface\\|return\\|struct\\|type\\)\\>" . font-lock-keyword-face)
...))))
```
I don't want the current values to get hardcoded into there; I just want it to keep using the backquote instead. Or somehow dynamically embed the variable reference there. But I don't see a way to do this.
Is this even doable with `customize`? Perhaps I merely need to use `defvar` to modify the variable instead of `defcustom` and simply edit it in raw Elisp, just eschewing the `customize` interface altogether?
For reference, there is some similar code in the Emacs trunk for `dns-mode.el`:
```
(defcustom dns-mode-font-lock-keywords
`((,(concat "^$" (regexp-opt dns-mode-control-entities))
0 ,dns-mode-control-entity-face)
("^$[a-z0-9A-Z]+" 0 ,dns-mode-bad-control-entity-face)
(,(regexp-opt dns-mode-classes) 0 ,dns-mode-class-face)
(,(regexp-opt dns-mode-types) 0 ,dns-mode-type-face))
"Font lock keywords used to highlight text in DNS master file mode."
:version "26.1"
:type 'sexp
:group 'dns-mode)
```
This variable has the exact same problem which you'll see if you try to edit it in the customize interface via `M-x customize-variable dns-mode-font-lock-keywords` (you'll have to load `dns-mode` first).
# Answer
It's not clear (to me) what you want. The closest you seem to come to it is this, which is also not very clear:
> "I just want it to keep using the backquote instead. Or somehow dynamically embed the variable reference there. But I don't see a way to do this."
Can you specify what you want as the value of the option, and how you want to be able to change that value (with or without using Customize)?
It sounds like you maybe want *variables*, and not their values, in the value of your user option, so that the option value is determined by those variable values. But there's no way (for me at least) to guess what you're really trying to do.
---
In any case, you probably shouldn't be trying to modify/set `font-lock-keywords` directly.
From the Elisp manual, node Search-based Fontification:
> **`font-lock-keywords`**:
>
> Lisp programs **should not set this variable directly**. Normally, the value is automatically set by Font Lock mode, using the `KEYWORDS` element in `font-lock-defaults`. The value can also be altered using the functions `font-lock-add-keywords` and `font-lock-remove-keywords` (See Customizing Keywords).
The usual way to modify/set `font-lock-keywords` is indirectly, by setting `font-lock-defaults` or using `font-lock-add-keywords`, as suggested in the manual.
> 1 votes
# Answer
It looks to me like you misunderstand the logic of the backquote. Even though it allows evaluation of code (instead of simply using the quoted value), it is still evaluated at runtime. That is, `defcustom` does receive a value in the same sense that a quoted list produces a value. Which is why if you look at the stored customizations in your `custom.el` file, you will always find immutable constants and not, say, a function call.
So the real question is what you want to achieve. You must make sure that your customization functions are evaluated when you need them. Maybe a `defcustom` is not the right place for that, since it is evaluated at compile time, or when the lisp file is loaded.
> 1 votes
---
Tags: font-lock, customize, defcustom, backquote
--- |
thread-65089 | https://emacs.stackexchange.com/questions/65089 | emacs org mode define a function in src block and call it | 2021-05-30T16:11:00.420 | # Question
Title: emacs org mode define a function in src block and call it
is there a method/package to use the following syntax to define and call a function?
```
#+NAME: retX
#+BEGIN_SRC python :var x=5
def retX (x):
return x
#+END_SRC
```
... Some text later...
```
#+begin_src pyton
<<retX(x=6)>>
#+end_src
```
I am not a huge fan of being limited to
```
#+name: retX
#+begin_src python :var x=5
return x
#+end_src
```
...later...
```
#+call retX(x=6)
```
as I would like to be able to define a block such as
```
#+begin_src python :var x=5
<<retX(x)>> * <<retX(x=6)>>
#+end_src
```
and similiar.
# Answer
> 3 votes
With python you probably have to use a :session to get persistence between src blocks. I like `:results output` personally, and use print statements where I want them.
You can probably do this as follows:
```
#+BEGIN_SRC python :session :results output
def retX(x):
return x
#+END_SRC
#+RESULTS:
#+BEGIN_SRC python :session :results output
print(retX(x=6))
#+END_SRC
#+RESULTS:
: 6
#+BEGIN_SRC python :session :results output :var x=5
print(retX(x) * retX(x=6))
#+END_SRC
#+RESULTS:
: 30
```
---
Tags: org-mode, org-babel
--- |
thread-65015 | https://emacs.stackexchange.com/questions/65015 | `dtrt-indent-mode` erroneously uses Tab characters | 2021-05-26T14:23:05.910 | # Question
Title: `dtrt-indent-mode` erroneously uses Tab characters
Here is an example file (`/tmp/asdf.sh`), for which I want `dtrt-indent-mode` to do the right thing.
```
#! /usr/bin/env bash
function asdf()
{
printf "asASDFASDF"
echo "1234"
}
printf "qwerqwerqwer\n"
result=$(asdf)
if [ df ] ; then
if [ er ] ; then
wefwefew
fi
fi
```
I have created a minimal Emacs init file (`~/tmp/basic-init.el`) to test this:
```
(require 'package)
(setq package-enable-at-startup nil)
(add-to-list 'package-archives '("melpa" . "http://melpa.org/packages/"))
(add-to-list 'package-archives '("gnu" . "http://elpa.gnu.org/packages/"))
(add-to-list 'package-archives '("melpamilk" . "http://melpa.milkbox.net/packages/"))
(package-initialize)
(unless package-archive-contents
(package-refresh-contents))
(unless (package-installed-p 'use-package)
(package-install 'use-package))
(require 'use-package)
(defun my-prog-mode-hook ()
(dtrt-indent-mode))
(use-package dtrt-indent
:ensure t
:config (dtrt-indent-mode t))
(use-package blank-mode
:ensure t)
(global-set-key (kbd "C-c b") 'blank-mode)
```
Starting emacs with that init file, opening that shell file:
```
emacs -q -l ~/tmp/basic-init.el /tmp/asdf.sh
```
then showing blank characters with `C-c b`, gives this:
(Don't mind the yellow highlight, blank-mode should be setup to leave that alone.)
Going to that yellow line, deleting a space char then pressing `TAB` gives this:
According to me, the right thing to do is not to put a Tab character there.
---
What I have found trying to understand what is going on:
Luckily, `dtrt-indent` has a diagnosis tool. This is the output of `dtrt-indent-diagnosis`, on the original file (no Tab character):
```
Guessing offset for /tmp/asdf.sh
Elapsed time for analysis: 0.001 seconds
Total relevant lines: 5 out of 17 (limit: 5000)
Histogram:
4x 4 spaces
1x 8 spaces
Analysis:
offset 2 works for 100.00% of relevant lines, matching 2 distinct offsets - merged with offset 4 (0.00% deviation, limit 20.00%)
offset 4 works for 100.00% of relevant lines, matching 2 distinct offsets - CONSIDERED
offset 8 works for 20.00% of relevant lines, matching 1 distinct offsets - CONSIDERED
offset 3 works for 0.00% of relevant lines, matching 0 distinct offsets - rejected: too few distinct matching offsets (1 required)
offset 5 works for 0.00% of relevant lines, matching 0 distinct offsets - rejected: too few distinct matching offsets (1 required)
offset 6 works for 0.00% of relevant lines, matching 0 distinct offsets - rejected: too few distinct matching offsets (1 required)
offset 7 works for 0.00% of relevant lines, matching 0 distinct offsets - rejected: too few distinct matching offsets (1 required)
Summary:
Best guess is offset 4 with 100.00% matching lines (80.00% required)
Hard tab percentage: 0.00% (0 lines), -100.00% superior to soft tabs (threshold 300.00%)
Soft tab percentage: 100.00% (5 lines), inf% superior to hard tabs (threshold 300.00%)
Conclusion:
Guessed offset 4 with 100% confidence.
Change indent-tab-setting: yes, to nil
```
I did not manage to find help on `indent-tab-setting`.
However, `C-h k` on `TAB` key press gives this:
```
TAB (translated from <tab>) runs the command indent-for-tab-command
(found in global-map), which is an interactive compiled Lisp function
in ‘indent.el’.
It is bound to TAB.
(indent-for-tab-command &optional ARG)
Indent the current line or region, or insert a tab, as appropriate.
This function either inserts a tab, or indents the current line,
or performs symbol completion, depending on ‘tab-always-indent’.
The function called to actually indent the line or insert a tab
is given by the variable ‘indent-line-function’.
```
and `C-h v` on `indent-line-function`:
```
indent-line-function is a variable defined in ‘indent.el’.
Its value is ‘smie-indent-line’
Local in buffer asdf.sh; global value is indent-relative
```
Apparently, `smie-` is a default naive indentation function.
I was expecting to find a `dtrt-` function here.
How can I make `dtrt-indent-mode` do the right thing?
GNU Emacs 26.1.
# Answer
I received help from the devs at github.
Basically, at its default, `dtrt-indent-mode` does nothing if SMIE also is active. Even if `dtrt-indent-mode` is active. Activating it (even buffer-locally) always defers to SMIE if active, which it is in many programming language modes.
This deferring can be overridden with `dtrt-indent-run-after-smie`.
Here is the relevant section of the basic init file in the question, modified to activate `dtrt` always:
```
(defun my-prog-mode-hook ()
(dtrt-indent-mode))
(add-hook 'prog-mode-hook 'my-prog-mode-hook)
(use-package dtrt-indent
:ensure t
:config
(setq dtrt-indent-run-after-smie t) ;; Run even if SMIE is active
)
```
> 1 votes
# Answer
dtrt-indent is a minor mode that will guess the indentation offset of a file and adjusts those local settings accordingly. It hooks in to several major modes, and works reasonably well.
@Gauthier is wondering why `dtrt-indent` is inserting a TAB character to perform indentation after guessing, with 100% confidence, that the indentation offset is 4 SPACE characters. I have always taken the line in the `dtrt-indent-diagnosis` report to be a recommendation to the user to change the "indent settings" (`indent-tabs-mode`). How the user chooses to do that is up to the user. (File local variables, directory local variables, global configuration, etc). In this case `Change indent-tab-setting: yes, to nil` is saying "Hey, maybe you want to disable `indent-tabs-mode` here. I dunno. You do you."
I believe the reason why @Guathier was able to delete 2 indentation levels of 4 spaces, and insert a single tab character to match those 2 indentation levels is because `indent-tabs-mode` was enabled (`t`). This short example file didn't meet the heuristics required for `dtrt-indent` to change `indent-tabs-mode`. The code in fact states that it may have trouble with small files.
Note that in a comment I stated:
> Oh, also, dtrt-indent only adjusts indent level, it won't change what the indentation is (tabs/spaces). Hence the recommendation on whether or not to change the "indent-tab-settings". – nega 5 hours ago
That comment is incorrect, and I've deleted it. I confirmed I was wrong when I globally set my `indent-tabs-mode` to `nil` and opened a rather large C++ file that was indented with tabs, and `dtrt-indent` locally changed `indent-tabs-mode` to `t`. By default `dtrt-indent` will tell you what it changes in the mini-buffer and `*Messages*` buffer. You can change the verbosity of these messages by customizing `dtrt-indent-verbosity`. Said C++ example reported:
```
Note: c-basic-offset adjusted to 8
Note: indent-tabs-mode adjusted to t
```
I haven't studied the code in depth, but I suspect that this test case, and maybe other examples that @Gauthier has seen just didn't have enough data for `dtrt-indent` to make a decision. Personally, I think that conservatism is a good thing, as I think it would be more jarring to have my indent "things" changed, than just my indent "sizes".
> 1 votes
---
Tags: indentation, tabs
--- |
thread-65117 | https://emacs.stackexchange.com/questions/65117 | What can I use instead of `diff-buffers` in Aquamacs? | 2021-06-01T09:35:57.677 | # Question
Title: What can I use instead of `diff-buffers` in Aquamacs?
According to the Emacs manual, “the command `M-x diff-buffers` compares the contents of two specified buffers”. But Aquamacs (Aquamacs 3.2 GNU Emacs 24.4.51.2, macOS 10.14.4) gives me no match for this command. What can I use instead?
# Answer
`diff-buffers` is a new command in Emacs 27.1.
Do you really want to see the diff output, rather than compare the buffers? Emacs has a nice built-in interface to compare two files: Ediff. (Note that Ediff has its own manual, separate from the Emacs user manual, even though it's been bundled with Emacs since the last century.) Run `M-x ediff-buffers` and choose the two buffers (defaulting to the current buffer and the last one you visited). There's also an “Ediff” submenu in the “Tools” menu.
After starting an Ediff session, the diff is in a buffer called `*ediff-diff*` (or `*ediff-diff2*` etc. if you have multiple active Ediff sessions). Perhaps more conveniently, or if you want a diff format that's different from the one Ediff uses, you can save the diff output to a file by typing `w``d` (`ediff-save-buffer`) in the Ediff control buffer. Set `ediff-custom-diff-options` to control the options passed to `diff` when saving the diff.
I can't think of a generic way to run a command on two buffers. If both buffers are visiting files, you can use `M-x diff`:
1. Visit file 1. Save if necessary.
2. Run `find-file` (`C-x C-f`), press `down` or `C-n` (`next-history-element`) to have the full path to the current file, and copy the full path to the kill-ring (clipboard).
3. Visit file 2. Save if necessary.
4. Run `M-x diff`. Paste the path to file1, and accept the default for file2.
> 3 votes
# Answer
You are using Emacs version 24, but the online manual is for Emacs 27.
You either need to upgrade, or to read the Emacs manual that came with your copy of Emacs. Type `C-h i` to open the info viewer, then select Emacs.
> 2 votes
---
Tags: diff, aquamacs
--- |
thread-65127 | https://emacs.stackexchange.com/questions/65127 | Search for a capital letter in a string and move the cursor to it | 2021-06-01T20:30:31.287 | # Question
Title: Search for a capital letter in a string and move the cursor to it
I am trying to learn how to implement regular expressions in emacs. I have a string that looks like this:
```
Fname0 Mname0 Surname0Fname1 Surname1Fname2
```
I would like to search for any capital letter and move the cursor to it. How do I go about doing that? I would later like to insert space and a comma in that spot.
# Answer
> 1 votes
You can do an interactive regexp search via the command `isearch-forward-regexp`, bound to `M-C-s` by default.
You can search for any upper-case letter via `[A-Z]`, or `[[:upper:]]`. This will take you to the first capital after point. Pressing `C-s` will move to the next, which you can repeat.
To do this from elisp code, you can use the function `search-forward-regexp`.
Your question is very general, so it's hard to tell how familiar you are with Emacs and elisp code in general. If you're new to elisp, the tutorial might be useful. If you have some experience and just need to get oriented to Emacs/elisp, then the manual chapter on Searching and Replacing might be what you're after.
---
Tags: regular-expressions, search
--- |
thread-65123 | https://emacs.stackexchange.com/questions/65123 | Company completion backend company-capf error error | 2021-06-01T15:06:04.570 | # Question
Title: Company completion backend company-capf error error
I am using `lsp-mode` and `company` on top of Pyhton files. When I complete a function I am getting follwing error:
`Company: backend company-capf error "[yas] ‘yas-expand-snippet’ needs properly setup ‘yas-minor-mode’" with args (post-completion get_job_block_number(requester_address, key, index))`
---
Completed function example:
`self.mongo_broker.get_job_block_number(${1:requester_address}, ${2:key}, ${3:index})$0`
which should be just: `self.mongo_broker.get_job_block_number()`
my setup:
```
(diminish 'yas-minor-mode)
(add-hook 'python-mode-hook 'lsp)
(add-hook 'python-mode-hook #'lsp-deferred)
(setq company-auto-complete t)
(global-set-key (kbd "C-c C-k") 'company-complete)
```
What may be the reason of this error and how can I resolve it?
---
// Could be related with following question: Company: backend company-capf error
# Answer
> 1 votes
Seems like I was missing (`yas-global-mode`) call. When I added to my `.emacs` file problem is resolved.
---
Tags: lsp-mode, company
--- |
thread-65080 | https://emacs.stackexchange.com/questions/65080 | Stop major modes from overwriting my keybinding | 2021-05-30T05:53:51.153 | # Question
Title: Stop major modes from overwriting my keybinding
By default `C-x n` is a prefix keymap used for narrowing.
I want to bind `C-x n` to `windmove-down`.
```
(global-set-key (kbd "C-x n") 'windmove-down)
```
This works fine for Text mode. But many major modes seem to overwrite these bindings:
* Markdown mode:
+ C-x n b → markdown-narrow-to-block
+ C-x n s → markdown-narrow-to-subtree
* Orgmode:
+ C-x n b → org-narrow-to-block
+ C-x n e → org-narrow-to-element
+ C-x n s → org-narrow-to-subtree
So I would like to know: How can I stop all (major) modes from overwriting my binding?
# Answer
You should steal the technique used by `bind-key*`.
Basically, the bindings in minor modes take precedence over major modes, and minor modes in the `emulation-mode-map-alists` take über precedence. Mastering Emacs has a good outline of keymap lookup order.
Here's a sampling from my config:
```
(defvar my/keys-keymap (make-keymap)
"Keymap for my/keys-mode")
(define-minor-mode my/keys-mode
"Minor mode for my personal keybindings."
:init-value t
:global t
:keymap my/keys-keymap)
;; The keymaps in `emulation-mode-map-alists' take precedence over
;; `minor-mode-map-alist'
(add-to-list 'emulation-mode-map-alists
`((my/keys-mode . ,my/keys-keymap)))
(define-key my/keys-keymap (kbd "M-o") 'other-window)
```
> 4 votes
# Answer
Emacs has no mechanism to prevent this other than convention. The convention is that all of the alphabetical keys starting with `C-c` are reserved for the user. You could change your key binding to `C-c n` and it wouldn’t be overwritten.
The other alternative is to configure hook functions in your init file so that when a buffer enters a mode that shadows your `C-x n` binding, your hook function resets your keybinding in the mode’s local keymap. However, this probably means writing a different hook function for every mode.
> 1 votes
---
Tags: key-bindings, major-mode, prefix-keys
--- |
thread-65107 | https://emacs.stackexchange.com/questions/65107 | How to only include entries with a certain tag for icalendar export in org-mode? | 2021-05-31T18:51:02.133 | # Question
Title: How to only include entries with a certain tag for icalendar export in org-mode?
Long story short: I'd like to implement something like the opposite of `org-icalendar-exclude-tags` (i.e., `org-icalendar-include-tags`).
I would like to export some entries from my org files into an ICS file using `org-icalendar-combine-agenda-files`. Only entries with a certain tag ("meet") should be included. I first tried setting `org-export-select-tags` but apparently, that's ignored by `org-icalendar-include-tags`.
Reading the documentation for the advanced export configuration I found that probably `org-export-before-parsing-hook` could do the job. The following is a minimal example of what I achieved so far:
```
; This is emacsrc.el
(require 'org)
(defun my-delete-entry ()
"Delete the entry but no sub-entries."
(delete-region (point) (save-excursion (org-next-visible-heading 1) (point)));
(setq org-map-continue-from (org-element-property :begin (org-element-at-point)))
)
(defun my-filter-entries (backend)
"Skip entries without 'meet' tag."
(when (org-export-derived-backend-p backend 'icalendar)
(org-map-entries #'my-delete-entry "-meet")))
(add-hook 'org-export-before-parsing-hook 'my-filter-entries)
; configuration for testing this with emacs --batch -q -l emacsrc.el
(setq org-agenda-files (quote ("test.org")))
(setq org-icalendar-combined-agenda-file "cal.ics")
(setq org-icalendar-include-body nil)
(setq org-icalendar-store-UID nil)
(org-icalendar-combine-agenda-files)
```
Feedings this file to Emacs with `/usr/bin/emacs --batch -q -l emacsrc.el` for the following example `test.org` file:
```
* This should be exported :meet:
<2021-05-31 Mo 10:00>
* This should NOT be exported
<1999-05-31 Mo 10:00>
** <2021-05-31 Mo 12:00> But this should also be exported :meet:
```
yields the following `cal.ics` file:
```
BEGIN:VCALENDAR
VERSION:2.0
X-WR-CALNAME:OrgMode
PRODID:-//foo//Emacs with Org mode//EN
X-WR-TIMEZONE:CEST
X-WR-CALDESC:
CALSCALE:GREGORIAN
BEGIN:VEVENT
DTSTAMP:20210531T211047Z
UID:TS1-af9107ca-5f42-4dea-b07e-c3cda2638494
DTSTART:20210531T100000
DTEND:20210531T120000
SUMMARY:This should be exported
CATEGORIES:meet,test
END:VEVENT
END:VCALENDAR
```
As can be seen, the third entry ("But this should also be exported") is missing, although it has a "meet" tag.
Testing the `my-delete-entry` within `test.org` itself with the following code:
```
#+BEGIN_SRC elisp
(defun my-delete-entry ()
"Delete the entry but no sub-entries."
(delete-region (point) (save-excursion (org-next-visible-heading 1) (point)));
(setq org-map-continue-from (org-element-property :begin (org-element-at-point)))
)
(org-map-entries #'my-delete-entry "-meet")
#+END_SRC
```
works, though, as the file is reduced to:
```
* This should be exported :meet:
<2021-05-31 Mo 10:00>
** <2021-05-31 Mo 12:00> But this should also be exported :meet:
```
Why is the sub-entry not correctly exported?
Is there another, more elegant way to achieve my goal of only exporting entries with a certain tag?
# Answer
The following implementation of `my-delete-entry` does the job:
```
(defun my-delete-entry ()
"Delete the entry but no sub-entries."
(let ((pt (org-entry-end-position)))
(when pt (delete-region (point) (- pt 1))))
)
```
It's a simplification of
```
(defun my-delete-entry ()
"Delete the entry but no sub-entries."
(let ((pt (save-excursion (apply 'org-agenda-skip-entry-if '(timestamp)))))
(when pt (delete-region (point) (- pt 1))))
)
```
as a result of looking at the code of `org-agenda-skip-entry-if` (and subsequently `org-agenda-skip-if`). (Thanks go to DB for this optimization.)
> 0 votes
---
Tags: org-mode, org-export, org-agenda, ical
--- |
thread-64670 | https://emacs.stackexchange.com/questions/64670 | Key binding for pipe in ESS | 2021-05-02T18:38:52.177 | # Question
Title: Key binding for pipe in ESS
I am trying to define keymapping about `%>%` for ess R mode.
Code 1 is my `init.el` based on How to implement the piping operator %\>% in ESS mode?. After evaluation of the code, I get the key binding Code 2. I don't know why such a situation happen and `RET` does not work well. How do I fix it?
Code 1
```
(defun then_R_operator ()
(interactive)
(just-one-space 1)
(insert "%>%"))
(define-key ess-mode-map (kbd "C-%") 'then_R_operator)
(define-key inferior-ess-mode-map (kbd "C-%") 'then_R_operator)
```
Code 2
```
key binding
--- -------
RET then_R_operator
C-% then_R_operator
```
**Update**
I also try a different method as follows. But, I got the same result.
```
(define-key ess-mode-map (kbd "C-M") "%>%")
(define-key inferior-ess-mode-map (kbd "C-M") "%>%")
```
# Answer
> 0 votes
I found an easy solution from https://stackoverflow.com/questions/59251402/how-to-set-up-custom-automatic-character-replacement-in-emacs-ess.
```
(define-key ess-mode-map (kbd "C-%") "%>%")
(define-key inferior-ess-mode-map (kbd "C-%") "%>%")
```
Note `C-M` causes a problem.
# Answer
> 0 votes
Another way to define the key binding is with use-package:
```
(use-package ess
:bind (:map ess-r-mode-map
("C-c >" . " %>% ")
:map inferior-ess-r-mode-map
("C-c >" . " %>% ")))
```
---
Tags: key-bindings, ess
--- |
thread-8041 | https://emacs.stackexchange.com/questions/8041 | How to implement the piping operator %>% in ESS mode? | 2015-02-07T08:46:16.897 | # Question
Title: How to implement the piping operator %>% in ESS mode?
Recently, `R` witnessed the smart introduction of the piping operator `%>%` or `then` operator in code which I use quite frequently nowadays. I wonder if this has already been implemented in the newest version of ESS. If not, it shouldn't be a problem to come up with `elisp` code to write a function for it. I need to implement this so that it will print that operator `%>%` and then jumps to a new indented line.
**MWE**
```
library(ggplot2)
library(dplyr)
diamonds %>%
filter(cut=="Ideal") %>%
ggplot(aes(price)) +
geom_histogram() +
facet_wrap (~ color)
```
My elisp trial - in `.init.el` or `.emacs` file:
```
(defun then_R_operator ()
"%>% operator or 'then' pipe operator"
(interactive)
(insert " %>%") ; note the space before the first %
(reindent-then-newline-and-indent))
(global-set-key (kbd "C-%") 'then_R_operator)
```
It works, but I want to check if there is something wrong with it or are there any suggestions to improve it (being a newbie in elisp). How to restrict this only to `ESS` mode?
**Note**
I realized that font-locking of `%>%` can be done by enabling `ess-fl-keyword:operators`from the ESS menu.
# Answer
thanks to mutbuerger for the helpful comments. Currently, I use this for this operator to work with ESS only.
```
(defun then_R_operator ()
"R - %>% operator or 'then' pipe operator"
(interactive)
(just-one-space 1)
(insert "%>%")
(reindent-then-newline-and-indent))
(define-key ess-mode-map (kbd "C-%") 'then_R_operator)
(define-key inferior-ess-mode-map (kbd "C-%") 'then_R_operator)
```
> 13 votes
# Answer
You can define a key binding for `%>%` with use-package:
```
(use-package ess
:bind (:map ess-r-mode-map
("C-c >" . " %>% ")
:map inferior-ess-r-mode-map
("C-c >" . " %>% ")))
```
> 1 votes
---
Tags: font-lock, ess
--- |
thread-65146 | https://emacs.stackexchange.com/questions/65146 | How to have folding and unfolding of headers in orgmode file persist through emacs sessions | 2021-06-03T15:43:13.240 | # Question
Title: How to have folding and unfolding of headers in orgmode file persist through emacs sessions
Suppose I open an orgmode file and fold and unfold a bunch of headers, is it possible to let the folds and unfolds be the same next time I open emacs. I feel the startup function wont be enough.
```
#+STARTUP: fold
#+STARTUP: nofold
#+STARTUP: content
#+STARTUP: showeverything
```
# Answer
> 2 votes
There is no built-in way to remember the folding state from one session to the next, but each headline can have a `VISIBILITY` property (possible values: `folded`, `children`, `content` and `all`) that can be set like this:
```
* Headline
:PROPERTIES:
:VISIBILITY: folded
:END:
...
```
to set the visibility of each headline independently of any other headline and the global setting. But you'd have to manually set it (or implement a mechanism to automate the setting of it) in order to persist the folding state to future sessions.
---
Tags: org-mode, persistence
--- |
thread-64448 | https://emacs.stackexchange.com/questions/64448 | Doom emacs dired +ranger not obeying evil-mode | 2021-04-16T09:22:09.417 | # Question
Title: Doom emacs dired +ranger not obeying evil-mode
I am using doom emacs and in my init file I have (dired +ranger)
The problem is when I open dired, I cannot press tab to select for example. I have first to toggle off evil-mode. If I do, I lose all doom key bindings.
There should be a work around as in regular dired, I didn't have to toggle off evil mode and doom still working!
# Answer
You could add dired-mode and ranger mode to variable "evil-emacs-state-modes": (add-to-list 'evil-emacs-state-modes 'dired-mode)
> 0 votes
---
Tags: evil, dired, doom, ranger
--- |
thread-24794 | https://emacs.stackexchange.com/questions/24794 | Wrap/trunc text at 80 column width | 2016-07-24T11:11:21.667 | # Question
Title: Wrap/trunc text at 80 column width
Is it possible to wrap text automatically at 80 column length? I mean, writing code or text and then, when I reach 80 characters, put a breakline and continue on the next line (not wrapping the word but putting on the next line).
Thank you!
# Answer
> 3 votes
You can customize `fill-column` or do `(setq-default fill-column 80)` in your init file and use `auto-fill-mode`.
You can activate it per mode by using `(add-hook 'text-mode-hook 'turn-on-auto-fill)` or with key binding: `(global-set-key (kbd "C-c q") 'auto-fill-mode)`. See emacswiki for more.
# Answer
> 1 votes
I know you asked for "automatically" (and 5 years ago...) but...
I do it *manually* with the command `fill-paragraph` (`M-Q`). Having `(setq fill-column 80)` in the init file. It even understands some text structure, e.g. that the text is a comment. Which could be good or bad, depending on your needs.
---
Tags: wrapping
--- |
thread-65154 | https://emacs.stackexchange.com/questions/65154 | How to stop a subprocess? | 2021-06-03T20:53:34.487 | # Question
Title: How to stop a subprocess?
I am unable to make `stop-process` work. I expect that it behaves as `C-z` in a terminal so that I can later continue it with `continue-process`.
Minimal not working example:
```
(setq ptest (start-process "test" "*yes*" "yes"))
```
and then
```
(stop-process ptest)
```
returns `#<process test>` but does nothing (*i.e.* the process is still writing `y` into the output buffer `*yes*`). Especially, running `(process-status ptest)` says `run` instead of `stop`.
What I'm missing ?
Note: GNU Emacs 28.0.50 of 2021-01-20
# Answer
On my system, `yes` doesn't react to `SIGTSTP`, which is the signal sent by `stop-process` (rather than `SIGSTOP` as one might assume).
When you run `yes` in your terminal and shell, `C-z` is going to additionally prevent the process from having a terminal to write to -- so if the process is still running and generating output, the kernel will stop it at that point (via `SIGTTOU` as I understand it). My guess is that that's the difference between the two scenarios.
You can use `(signal-process ptest 'STOP)` to send `SIGSTOP`.
```
-- Function: stop-process &optional process current-group
This function stops the specified PROCESS. If it is a real
subprocess running a program, it sends the signal ‘SIGTSTP’ to that
subprocess. If PROCESS represents a network, serial, or pipe
connection, this function inhibits handling of the incoming data
from the connection; for a network server, this means not accepting
new connections. Use ‘continue-process’ to resume normal
execution.
Outside of Emacs, on systems with job control, the stop character
(usually ‘C-z’) normally sends the ‘SIGTSTP’ signal to a
subprocess. When CURRENT-GROUP is non-‘nil’, you can think of this
function as typing ‘C-z’ on the terminal Emacs uses to communicate
with the subprocess.
```
> 3 votes
---
Tags: subprocess
--- |
thread-66158 | https://emacs.stackexchange.com/questions/66158 | Why is Emacs Entering the Debugger despite a condition case wrapper? | 2021-06-04T17:44:01.220 | # Question
Title: Why is Emacs Entering the Debugger despite a condition case wrapper?
The context of my question: I was editing some clojure code, and point was inside a comment, and to the right of three characters: \`abc'.
I ran the command: `M-x company-diag`, to ask company mode for a diagnosis of the current company configuration.
Emacs entered the debugger. My question is: Why did emacs enter the debugger?
From the documentation for `debug-on-error`:
```
Non-nil means enter debugger if an error is signaled.
Does not apply to errors handled by ‘condition-case’ or those
matched by ‘debug-ignored-errors’.
```
Although the value of `debug-on-error` is `t`, the code which signals the error is wrapped in a `condition-case`. Why didn't this wrapper prevent the debugger from being entered?
Here is the stack trace. Note that I have annotated this stack trace to indicate the condition case wrapping.
```
Debugger entered--Lisp error: (void-function clojure\.lang\.ExceptionInfo:)
clojure\.lang\.ExceptionInfo:("abc" nil t)
all-completions("abc" clojure\.lang\.ExceptionInfo: nil)
completion-pcm--all-completions("" ("abc" point) clojure\.lang\.ExceptionInfo: nil)
completion-basic-all-completions("abc" clojure\.lang\.ExceptionInfo: nil 3)
#f(compiled-function (style) #<bytecode 0x1f03af9>)(basic)
completion--some(#f(compiled-function (style) #<bytecode 0x1f03af9>) (basic partial-completion emacs22))
completion--nth-completion(2 "abc" clojure\.lang\.ExceptionInfo: nil 3 (metadata))
completion-all-completions("abc" clojure\.lang\.ExceptionInfo: nil 3 (metadata))
company-capf--candidates("abc")
company-capf(candidates "abc")
apply(company-capf (candidates "abc"))
company-call-backend-raw(candidates "abc")
apply(company-call-backend-raw (candidates "abc"))
company--force-sync(company-call-backend-raw (candidates "abc") company-capf)
--> WRAPPED IN A CONDITION-CASE company-call-backend(candidates "abc")
company-diag()
funcall-interactively(company-diag)
call-interactively(company-diag record nil)
command-execute(company-diag record)
counsel-M-x-action("company-diag")
ivy-call()
ivy-read("M-x " [dap-go-delve-path hasNextPage diary-included-files usages bmkp-file-this-dir-some-tags-jump-other-window dap-ui-breakpoint-log-message bmkp-tags-map csv-transpose gdb-script-syntax-propertize-function avy-words counsel-alias-expand magit-reflog-commit treemacs-project->path-status duplicate magit-wip-buffer-backed-up diredp-wrap-around-flag LOCALP woman-last-file-name none-but-delete js2-property-flag js2-visit-computed-prop-name-node sgml-syntax-propertize gdb-frame-locals-buffer local-only cl-print--preprocess \.frames clojure-docstring-fill-column dap-python--test-class-p HTMLTableSectionElement lsp:signature-help-active-signature\? js2-EXPORT js2-block-node-len cljr--cljc-file-p being omt one include-omitted-p org-duration-format epl-installed-packages \' :name-match bmkp-non-invokable-alist-only lsp--virtual-buffer-mappings js2-var-decl-node-pos--cmacro sessions magit-diff-wash-hunk we-thinkers-history-log define-mode-local-override lispy-bind-variable Move\ out\ of\ sexp ...] :predicate #f(compiled-function (sym) #<bytecode 0x1f1126d>) :require-match t :history counsel-M-x-history :action counsel-M-x-action :keymap (keymap (67108908 . counsel--info-lookup-symbol) (67108910 . counsel-find-symbol)) :initial-input nil :caller counsel-M-x)
counsel-M-x()
funcall-interactively(counsel-M-x)
call-interactively(counsel-M-x nil nil)
command-execute(counsel-M-x)
```
Emacs is entering the debugger despite the fact that the call to company-call-backend is wrapped in `condition-case`:
```
(condition-case nil
(setq cc (company-call-backend 'candidates (company--prefix-str prefix))
annotations
(mapcar
(lambda (c) (cons c (company-call-backend 'annotation c)))
cc))
(error (setq annotations 'error)))
```
# Answer
Following from Drew's suggestion in the comments, we can see that company.el is using `condition-case-unless-debug` in a number of places, including in `company-call-backend-raw` -- which in your stack trace is being called *after* that "WRAPPED IN A CONDITION-CASE" `company-call-backend` call.
```
(condition-case-unless-debug VAR BODYFORM &rest HANDLERS)
Like ‘condition-case’ except that it does not prevent debugging.
More specifically if ‘debug-on-error’ is set then the debugger will be invoked
even if this catches the signal.
```
> 1 votes
---
Tags: debugging, company-mode, error-handling
--- |
thread-66160 | https://emacs.stackexchange.com/questions/66160 | Log with --first-parent option | 2021-06-05T01:27:59.387 | # Question
Title: Log with --first-parent option
How can I tell magit to use the `--first-parent` option?
I only want to see commits onto this branch, none from merged branches.
# Answer
> 3 votes
`--first-parent` is included in current versions of Magit, but at a higher level than is shown by default in the transient menus.
Refer to `C-h``i``g` `(transient)Enabling and Disabling Suffixes` for how to control this.
From the Magit Log menu you can either:
* Change the default level for that menu using `C-x l C-x l` to make all those hidden options visible.
* Change the level of `--first-parent` specifically with `C-x l =p`, to include it at your current level.
Alternatively, you can customize `transient-default-level`.
---
Tags: magit
--- |
thread-36219 | https://emacs.stackexchange.com/questions/36219 | #000000 and true black in terminal Emacs colors | 2017-10-17T14:50:15.997 | # Question
Title: #000000 and true black in terminal Emacs colors
I just ran into a weird issue while tweaking my colour theme for terminal Emacs. The background wasn't appearing as black as expected, but grey, even though the background was set to `#000000`. So I opened the 'customize-face' dialog, and then opened the 'choose colour' option for background. This presents the following list:
Notice that the first colour, black, is actually grey, despite being listed as `#000000`. Stranger, is there is a second colour named `color-16`, with the same code `#000000`, and it *is* full black (see the bottom of the image).
The upshot is if I set a colour to `#000000` or `black`, I actually get grey, but if I set the colour to `color-16`, I get black.
This doesn't happen in GUI Emacs, where #000000 is called `black`, and produces true black. There is no `color-16` in my GUI emacs.
This is a bit awkward as I'd like to have the same color theme for GUI and terminal emacs, but black seems to mean different things. Can anyone explain this?
Emacs 27.0.50
Debian Linux
gnome terminal
# Answer
> 13 votes
Turns out this was a problem with gnome-terminal. I fixed it by opening the profile preferences from the gnome-terminal menu bar, selecting colours, and changing the built-in scheme to `Linux console`.
# Answer
> 2 votes
`color-16` don't work in emacs gui. I use this configuration:
```
(load-theme 'dark-laptop t)
(if (not (display-graphic-p))
(set-face-background 'default "color-16"))
```
But it's not a good solution. With 16 colors terminal (terminator + telnet + tmux) I have lots of `Unable to load color "color-16"`.
Bellow screenhot of my terminal before setting background to `color-16`. Reading is tiring after a while, especially on large terminals.
Second screenhot is with background set to `color-16`.
---
Tags: terminal-emacs, colors
--- |
thread-62730 | https://emacs.stackexchange.com/questions/62730 | Save current file with a slightly different name in Helm | 2021-01-12T09:23:13.637 | # Question
Title: Save current file with a slightly different name in Helm
This is the same question as Save current file with a slightly different name, but for Helm. (The top answer given for the original question doesn't work in Helm, sadly: `M-n` (`next-history-element`) doesn't do quite the same thing as in vanilla Emacs.)
The question is: how can I insert the filename of the current buffer into the minibuffer during `write-file`. So for example:
`C-x C-w` (this gets me to a minibuffer prompt with the current directory); in plain Emacs I could type `M-n` and this would insert the current filename for me to edit to a slightly different name. What can I do instead in Helm?
# Answer
There's nothing like it in Helm AFAIK, so I tried to mimic what `C-x C-w M-n` does with the following command. The difference is you have to press `C-j` (instead of `M-n`) to expand the filename.
```
(defun helm-write-file ()
(interactive)
(let ((filename (helm-read-file-name
"Write file: "
:preselect (when (buffer-file-name)
(helm-basename (buffer-file-name))))))
(write-file filename)))
(global-set-key (kbd "C-x C-w") 'helm-write-file)
```
Alternatively, you can skip the Helm interface with:
```
(add-to-list 'helm-completing-read-handlers-alist '(write-file . nil))
```
> 1 votes
# Answer
Bring up helm's file name history buffer with (`helm-write-file` followed by) `C-c h`. With a bit of luck, the file name you want is at the top. Select it with `F2`.
Note: To edit the filename, you need to navigate with `C-f` and `C-b` in the minibuffer. Using the arrow keys does not work for me. (The same caveat applies to the other answer.)
> 0 votes
---
Tags: helm, files, minibuffer
--- |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.