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-57676 | https://emacs.stackexchange.com/questions/57676 | Schedule to "now" (current time) in date/time prompt (calendar) | 2020-04-08T19:31:07.073 | # Question
Title: Schedule to "now" (current time) in date/time prompt (calendar)
I would like to be able to insert the current time with a shortcut when I schedule a task.
There is the "." for jumping to the current day (today), but I have not been able to figure out a shortcut to put the current time (now) in the org-schedule input line. I tried putting in "now", but it does not take effect.
The shortcut is useful if I have some Tasks scheduled without time for the day and would like to set them on the agenda time grid. Also when I get a unplanned tasks that I have to do right away this would be useful.
I know there is the `C-u C-u C-c .` command to insert a current timestamp, but it does not work in the date/time prompt.
Any idea is appreciated.
# Answer
> 0 votes
This is not a pure emacs way, but more of a hack. Still it works pretty good in day to day use:
The software espanso works on linux, mac and windows and expands keys similar to the package `yasnippet`.
On their documentation there is an example how to match the current time to `:now`, which solves the problem for me. It worked basically everywhere I needed it for now, also in emacs interactive dialogues. Its good enough until there is a native way.
https://espanso.org/docs/matches/#date-extension
---
Tags: org-mode, calendar, todo, prompt
--- |
thread-63186 | https://emacs.stackexchange.com/questions/63186 | How can I pass an expression to a prefix argument? | 2021-02-05T06:57:37.210 | # Question
Title: How can I pass an expression to a prefix argument?
Sometimes it would be useful to be able to pass an expression to a prefix argument, for example
```
c-u 3*4 c-n
```
If I try the command above though it will print three asterisks followed by the '4' character then cursor-down.
Is there something I can do so the prefix argument can be the value of an expression?
# Answer
There's no convenient interface for that.
For some simple operations, you can make use of two facts:
* Using `C-u` with no number gives you powers of 4. `C-u C-n` moves 4 lines down, `C-u c-u C-n` moves 16 lines down, etc. (There are rare exceptions with commands that treat the no-number case differently.)
* The prefix argument is usually a repeat count, so you can do additions by repeating the command.
If you want a complex calculation, you can use `M-:` (`eval-expression`) to call the command. First, if you need to, look up the command name by pressing `C-h c` (or `f1 c`) and the keyboard shortcut you meant to invoke. To copy-paste the command name, switch to the `*Messages*` buffer, or alternatively use `C-h k` rather than `C-h c` and switch to the `*Help*` buffer. Then invoke `eval-expression` with `M-:` and specify `M-: (*the-command-name* *(the-argument-expression)*)`. This assumes that the prefix argument is the sole argument to the function, which is often but not always the case: check the function's documentation.
Another approach, which works regardless of how the command consumes its prefix argument, is to set `prefix-arg` explicitly. invoke `eval-expression` with `M-:` and specify `M-: (setq prefix-arg *(the-argument-expression)*)`, then immediately invoke the command. Under the hood, commands read the prefix argument from `current-prefix-arg`. Between each interactive command, Emacs sets `current-prefix-arg` to the value of `prefix-arg` and resets `prefix-arg` to `nil`.
> 3 votes
---
Tags: prefix-argument
--- |
thread-60278 | https://emacs.stackexchange.com/questions/60278 | GPG No Public Key | 2020-08-22T23:45:26.243 | # Question
Title: GPG No Public Key
Emacs gives a error about not finding a GPG key.
# The Error
```
Failed to verify signature archive-contents.sig:
No public key for 066DAFCB81E42C40 created at 2020-08-22T21:05:02+0000 using RSA
Command output:
gpg: keyblock resource '/e/z_gis/gulfmx/c:/Users/jake9/msys64/home/jake9/.emacs.d/elpa/gnupg/pubring.kbx': No such file or directory
gpg: Signature made Sat, 22 Aug, 2020 21:05:02 CUT
gpg: using RSA key C433554766D3DDC64221BFAA066DAFCB81E42C40
gpg: Can't check signature: No public key
```
# Weird Path
What is really weird is the *keybox* path given:
* `/e/z_gis/gulfmx/c:/Users/jake9/msys64/home/jake9/.emacs.d/elpa/gnupg/pubring.kbx`
The first part is what ever working directory I was in when Emacs launched:
* `/e/z_gis/gulfmx/`
# My Setup
* OS: Win10
* msys2 / mingw64
* Emacs 27.1
`gnu-elpa-keyring-update` version 2019.3 is installed.
# Answer
> 3 votes
I had the same problem, on msys2, with the mingw64 version of emacs, which is 27.1, incidentally.
The problem I've found comes from emacs's package.el not agreeing (in msys2's context) with `gpg` on what to do with the `--homedir` argument.
As it is suggested here, package.el sets this argument to be `(expand-file-name "gnupg" package-user-dir)`, but, unfortunately, `expand-file-name` returns a path that starts with "`c:/etc...`" and `gpg` does not understand this syntax, and simply appends this string to the current working directory. This is then a meaningless path.
But on msys2 you can send "`/c/etc...`", instead, which `gpg` understands and uses as it is.
So, my solution is to set `package-gnupghome-dir` to your actual linux-style path "`/c/Users/jake9/msys64/home/jake9/.emacs.d/elpa/gnupg/`"
Now I realize you are using your msys2 home (and not your Windows home) so maybe you can get away with setting `package-gnupg-home` to just "`/home/jake9/.emacs.d/elpa/gnupg/`"
# Answer
> 1 votes
I have been experiencing same issue with GNU's official Emacs install, since Emacs 27.1.
For now, the only way I found to fix it is to disable signature checking and verify all packages by hand.
In my `init.el` I have temporarily added:
```
;; disable because of elpa bug in emacs 27.1
(setq package-check-signature nil)
```
Hopefully the bug will be fixed in next release.
---
Tags: microsoft-windows, gpg
--- |
thread-63164 | https://emacs.stackexchange.com/questions/63164 | How to know the list of possible commands when in a session? | 2021-02-04T09:48:35.690 | # Question
Title: How to know the list of possible commands when in a session?
For instance: When I am in `C-c C-e` (export), by pressing # you get extra options. How to know this?
Another example: When in a helm session, by pressing `C-c C-f`, you activate `helm-follow-mode`. But this is not obvious.
Is there a "help" shortcut to show potential keys in such buffers? Thanks!
# Answer
> 1 votes
If I may consider you thought about "..a way to see the available keys in a session." then you are probably looking for documentation depending on the mode you are in right now.
1. If it is just about keybindings then I highly recommend the `which-key` package. Basically this allows you to stop in the middle of any prefix-key and displays follow up solutions in a popup-buffer
2. If it is about the major mode you are interested in, then you should have a look at `C-h i`. This will let you navigate through most of your installed packages built in documentation. Not every mode/package is fully documented but e.g. the Org-Mode part is great and I actually learned a lot about stuff I wasn't even aware of.
3. If it is about an overview of the current major and all minor modes that are active then you are probably searching for `C-h m` that will give you an overview of e.g. active modes, prefix keys and so on.
I hope that helped.
# Answer
> 1 votes
I second the recommendation to use `which-key`. It's been a valuable part of my configuration for some time.
---
Tags: org-mode, org-export, keymap, help
--- |
thread-63204 | https://emacs.stackexchange.com/questions/63204 | How can I display a buffer in a whole frame, removing the rest in the act? | 2021-02-05T16:58:55.740 | # Question
Title: How can I display a buffer in a whole frame, removing the rest in the act?
Basically that. I need a function that would do this when I open a buffer in a frame with many other windows. Maybe Emacs has one by default.
# Answer
What about
```
(defun switch-buffer-delete-other-windows ()
(interactive)
(call-interactively 'switch-to-buffer)
(delete-other-windows))
(defun find-file-delete-other-windows ()
(interactive)
(call-interactively 'find-file)
(delete-other-windows))
```
and so on…?
> 1 votes
# Answer
`C-x 5 2` does what you request: it opens the current buffer in a separate frame. But it does not delete the original window showing the buffer in the original frame.
Command `tear-off-window` does both: opens the buffer in a separate frame *and* deletes its window from the original frame.
Personally, I bind `tear-off-window` to `C-x 5 1`. (I don't use that key's original binding of `delete-other-frames`.)
> 0 votes
---
Tags: buffers, window, frames
--- |
thread-63206 | https://emacs.stackexchange.com/questions/63206 | How can I go back to Texinfo native mode | 2021-02-05T17:38:54.577 | # Question
Title: How can I go back to Texinfo native mode
I have a `early-init.el` file with:
```
(add-to-list 'load-path "~/.emacs.d/el-get/el-get")
(unless (require 'el-get nil 'noerror)
(require 'package)
(add-to-list 'package-archives
'("melpa" . "http://melpa.org/packages/"))
(package-refresh-contents)
(package-initialize)
(package-install 'el-get)
(require 'el-get))
(add-to-list 'el-get-recipe-path "~/.emacs.d/el-get-user/recipes")
(el-get 'sync)
```
If I don't put the last line `(el-get 'sync)`then I have no problem getting those commands Inserting Frequently Used Commands in a `.texi` file...
but, if I put `(el-get 'sync)` then `C-c C-c` runs the command `TeX-command-master` (found in Texinfo-mode-map), which is an autoloaded interactive compiled Lisp function in ‘tex-buf.el’ and I no longer have access to previous commands.
As I understand the problem comes from AUCTeX which includes a major mode for editting Texinfo files. This major mode is not the same mode as the native Texinfo mode of Emacs, although they have the same name.
How can I go back to Texinfo native mode ?
(Emacs Version 27.1 (9.0) on macOS BigSur Version 11.2)
# Answer
The solution is:
* `M-x customize-variable` Customize variable: TeX-modes
* uncheck texinfo-mode
* State: Save for Future Sessions
> 1 votes
---
Tags: auctex, texinfo, el-get
--- |
thread-21180 | https://emacs.stackexchange.com/questions/21180 | Is there a way to show/open a file from a URI/URL | 2016-03-23T09:42:58.990 | # Question
Title: Is there a way to show/open a file from a URI/URL
Is there some way to download and show a file from a URI/URL?
I now I can use `wget` and then open the downloaded file and I guess I could even try to write myself a small function to do this.
But most likely someone did before me so is there a function/package that will let me get a file from the internets (would be great if it did not save the file somewhere first) and open it in a new buffer?
# Answer
> 17 votes
```
M-x url-handler-mode
C-x C-f http://emacs.stackexchange.com/questions/21180/is-there-a-way-to-show-open-a-file-from-a-uri-url
```
This opens the HTML file of this stackexchange question in your Emacs.
# Answer
> 3 votes
If you want the file "rendered", you can use the web browser eww - just do `M-x eww RET url RET`
# Answer
> 2 votes
You can turn URLs in a buffer into clickable buttons with Emacs **goto-address-mode** minor mode. If the URL represents a web page, then you can get Emacs to browse that page by clicking on the URL button.
Turn this mode on/off with: `M-x goto-address-mode`
This works with Emacs running in Graphics mode and in terminal mode. A special key map is activated when point is over the URL button. The `C-c RET` key sequence is bound to **goto-address-at-point** which makes Emacs browse the web page.
It's also possible to add key binding to that special map. In my system I added keys to navigate to the next or previous URL and to copy he content of the file identified by the URL into a local temporary file and then visit it. To do that add a function to the goto-address-mode-hook that maps commands into the `goto-address-highlight-keymap`.
---
Tags: find-file, url
--- |
thread-38770 | https://emacs.stackexchange.com/questions/38770 | Editing subtitles or closed caption files? | 2018-02-11T23:33:30.747 | # Question
Title: Editing subtitles or closed caption files?
I'm having trouble locating any Emacs modes supporting YouTube caption/subtitles files.
This YouTube help page details the list of file formats for subtitles and captioning supported by YouTube:
* Basic file formats
+ SubRip (`.srt`)
+ SubViewer (`.sbv` or `.sub`)
+ MPsub (`.mpsub`)
+ LRC (`.lrc`)
+ Videotron Lambda (`.cap`)
* Advanced file formats
+ SAMI (`.smi` or `.sami`)
+ RealText (`.rt`)
+ WebVTT (`.vtt`)
+ TTML (`.ttml`)
+ DFXP (`.ttml` or `.dfxp`)
* Broadcast file formats
+ Scenarist (`.scc`)
+ EBU-STL (`.stl`)
+ Caption Center (`.tds`)
+ Captions Inc. (`.cin`)
+ Cheetah (`.asc`)
+ NCI (`.cap`)
The help page ends with the note:
> Scenarist Closed Caption (.scc file extension) files are our preferred file format. These files have an exact representation of CEA-608 data, which is the preferred format whenever captions are based on CEA-608 features.
Short of trying each of these formats and seeing if any of them are close enough to a mode Emacs *does* deal with, I'm not sure which of these, if any, are editable with Emacs as more than plain text or XML. (Most of the "broadcast" ones listed above aren't even that, they're binary files.)
TTML, being an XML language (see, for example, this gist), obviously can be edited and syntax-highlighted. But what dedicated captions editors do goes far beyond this; at a minimum, you need a programmatic way of dealing with timestamps.
Anyone have any suggestions for solutions here for Emacs?
# Answer
Just in case someone else is wondering about this, I downloaded the autogenerated SBV files, converted them to WebVTT and fixed the timestamps to be non-overlapping, and then used the subed package (https://github.com/rndusr/subed) to edit the timestamps. I have a blog post at https://sachachua.com/blog/2020/12/editing-subtitles-in-emacs-with-subed-with-synchronized-video-playback-through-mpv/ with some details. I like the workflow because I can play the video from a local file or URL via mpv, and subed can pick up or manipulate the current playback position.
> 2 votes
---
Tags: nxml, video, accessibility
--- |
thread-33967 | https://emacs.stackexchange.com/questions/33967 | esc-right and M-right function differently in org-mode headers | 2017-07-05T00:42:47.983 | # Question
Title: esc-right and M-right function differently in org-mode headers
I'm on macOS 10.12.5 and Emacs 25.2.1. For some reason `M-right` is interpreted as `M-f`. `ESC-right` is correctly interpreted as `ESC-right`. I can't see anything in the macOS keyboard shortcuts list that might be capturing `M-right/left`. How might I figure out what's going on here?
I ended up switching to mitsuarhu's Emacs osx port instead, which doesn't have this problem. I noticed that terminal Emacs in `iterm2` also doesn't have this problem. I guess `terminal.app` is capturing `M-right` and turning it in to `M-f` for some reason.
# Answer
I think it is due to the fact shown in the following picture.
Terminal app in MacOS capture the behaviour of the keyboard.
In the menu Terminal\>Preferences go to Profiles tab and select the default profile or the profile it's been used then Select the keyboard tab.
Here the list show how the input is modified, sending special characters to the terminal.
In this case M-right is bounded to \033f.
To fix the issue remove the interested row.
The same solution could apply for other combination of keys in the list.
> 3 votes
# Answer
You have hit something quite interesting here that came clear when you added that you see the behaviour in org mode headers. Although surprising, your emacs works as it should.
According to emacs faq, "Emacs converts M-a internally into ESC a anyway (depending on the value of meta-prefix-char)." The value of meta-prefix-char is by default 27 (esc).
However, when the cursor is in org mode header, meta and escape are indeed doing different things:
* ESC right (translated from escape right) runs the command forward-word (found in global-map), which is an interactive built-in function in ‘C source code’.
* M-right runs the command org-metaright (found in org-mode-map), which is an interactive compiled Lisp function in ‘org.el’.
Based on these observations, the conversion of meta to esc happens at C source code level, and if any Emacs major modes written in lisp redifine the meta + key(s) mapping, it leaves the global escape mapping intact. That's is not clearly stated anywhere I looked and quite good to know!
> 2 votes
# Answer
I had similar issue with macOS Catalina (10.15.7) & Emacs from https://emacsformacosx.com/
In org-mode:
* `ESC <left>` was `backward-word`
* `ESC <right>` was `org-metaright` while I wanted it to be `forward-word`.
I was able to fix this with the following (inspired by How to override a keybinding in Emacs org-mode):
```
(with-eval-after-load "org"
(define-key org-mode-map (kbd "ESC <right>") nil))
```
With that, `ESC-right` is `forward-word` also in org-mode.
> 0 votes
---
Tags: key-bindings, osx, terminal-emacs
--- |
thread-63217 | https://emacs.stackexchange.com/questions/63217 | Mark all email in mu4e as read | 2021-02-06T05:04:40.940 | # Question
Title: Mark all email in mu4e as read
I have downloaded my emails using getmail and indexed them by mu. The problem now is that my mu4e has around 50000 emails that are marked as unread: is there a simply way to mark the entire Maildir as read?
I have tried a couple of scripts external to emacs adding the flag "S" to all the emails, then when I open mu4e they all still have unread flag.
# Answer
> 1 votes
Unfortunately `mu` itself doesn't let you interactuate with it in that way using predefined commands that I'm aware of. I guess that if you know enough about xapian databases, which isn't my case, you could do it. Still, you have a few options out of the box.
* On `mu4e-contrib` you have `mu4e-headers-mark-all-unread-read`, which probably will fit your bill for most use cases. Notice that only flag visible emails, but doesn't excute it, which means:
1. you're more likely operating on a subset of your stored messages. How big the subset is depends on `mu4e-headers-results-limit`'s value, which by default is 500 IIRC.
2. you still have to execute your actions.
Mind you that almost always your day-to-day workflow will be operating on subsets defined by bookmarks. Thread messages, Today's messages, this month's messages, or whatever actual. Having unread messages outside of current/used scopes shouldn't mean much.
* Also, in `mu4e-contrib` you can find `mu4e-headers-mark-all` which asks what to do with the marks and execute. Still applies point 1.
If that falls short or lets you down the basics of doing a search and processing it are well described in Rules for dealing with email in mu4e. It shouldn't be too hard to modify that code using the contributed functions cited above to make your own function. `mu script` is another option which will require a similar effort.
---
Tags: mu4e
--- |
thread-63212 | https://emacs.stackexchange.com/questions/63212 | Looking for a function to determine if an org-mode entry has a tag | 2021-02-05T20:55:09.700 | # Question
Title: Looking for a function to determine if an org-mode entry has a tag
I can use `(org-entry-get (point) "myproperty")` to get the value of the `myproperty` property for the current `org-mode` entry.
What about tags? Since a tag is either present or not, I was expecting some org API function such as `org-entry-has-tag` but there doesn't seem to be such a function. Am I missing something? If not, what's a good way to write such a function?
# Answer
There is a special property called `TAGS`, so you can look up the tags of any entry the same way that you look up any other property:
```
(org-entry-get (point) "TAGS")
```
And of course if there are no tags, that returns `nil`, so you can check for the existence of tags by using it in a conditional form, e.g. `(if (org-entry-get (point) "TAGS") ...)`.
> 4 votes
# Answer
Somehow I didn't find `org-get-tags` -- I tried `apropos`, but it only showed me interactive functions, and `org-get-tags` isn't interactive. Thanks Drew.
For the exact question I have here, you just use `member` and `org-get-tags`:
```
(defun org-has-tag (tag)
(member tag (org-get-tags)))
```
> 1 votes
---
Tags: org-mode
--- |
thread-63229 | https://emacs.stackexchange.com/questions/63229 | In Emacs Calc, how do I find the distance between two points (x1,y1) and (x2,y2)? | 2021-02-06T20:59:25.500 | # Question
Title: In Emacs Calc, how do I find the distance between two points (x1,y1) and (x2,y2)?
I'm trying to calculate the euclidean distance between two points `(x1,y1)` and `(x2,y2)` which is
```
sqrt( (x2-x1)^2 + (y2-y1)^2 )
```
Is there a way to calculate this easily with Emacs calc?
(I looked in the Info pages, but was not able to tell if there a way to do this easily. I can use `f h` to compute the hypotenuse, but I can't figure out how to use that with points, or if Emacs has any first class notion of a point)
# Answer
> 3 votes
You can represent points with complex numbers or vectors. The calc-abs (A) function returns the absolute value of a complex number or the Euclidean norm of a vector. For instance this is the trail trace which results from the calculus of the distance from \[7 -2\] to \[4 2\]
```
Emacs Calculator Trail
alg' [7, -2]
alg' [4, 2]
- [-3, 4]
abs 5
```
---
Tags: calc
--- |
thread-63236 | https://emacs.stackexchange.com/questions/63236 | Change org-log-done setting only for a subtree | 2021-02-07T08:33:12.287 | # Question
Title: Change org-log-done setting only for a subtree
In my configuration, I have:
```
(setq org-log-done 'time)
```
However, for one particular subtree, I want to suppress this behavior. So, closing any items here will not record a time.
Can this be done by setting some property for the heading? Or any other method?
# Answer
> 3 votes
This can be done by setting the local property `LOGGING` to `nil` (usually by pressing `C-c C-x p`):
```
* No logging section
:PROPERTIES:
:LOGGING: nil
:END:
** DONE A task
```
See Tracking TODO stage changes in the manual.
---
Tags: org-mode
--- |
thread-63232 | https://emacs.stackexchange.com/questions/63232 | Let-bind diplayed windows and their size/posizion | 2021-02-06T23:36:05.380 | # Question
Title: Let-bind diplayed windows and their size/posizion
Can I let-bind diplayed windows and their size/posizion? Is there a variable that stores these infos?
I need to run a script that will change the diplayed windows, opening some help temp buffers. At the end of the script I'd like to restore the starting layout (displayed windows and their size/posizion).
**Edit.** Finally I found that `current-frame-configuration`/`set-frame-configuration` is what I need,
# Answer
> 1 votes
In the manual, browse through the top level table of content. You're interested in windows, so go to the chapter on windows. Browse through its table of contents until you find “Saving and restoring the state of the screen”, which is the section window configurations. Now you know how Emacs calls what you're looking for and you know what functions are available.
```
(save-window-excursion
;; your code goes here
)
```
Furthermore, as noted in the documentation, there's a related macro `save-selected-window` with similar usage but which does something slightly different.
```
(save-selected-window
;; your code goes here
)
```
`save-window-excursion` saves the exact window arrangement (sizes, positions, displayed buffer) of the current frame only. `save-selected-window` does not save window arrangements, but remembers which window is selected in each frame. Given what you want to do, which involves displaying (and therefore making room for) extra windows, I think `save-window-excursion` is the right one.
---
Tags: window, window-configuration
--- |
thread-63221 | https://emacs.stackexchange.com/questions/63221 | How can I bind F12 in serial-term mode to minicom's F12? | 2021-02-06T11:08:41.980 | # Question
Title: How can I bind F12 in serial-term mode to minicom's F12?
When I use emacs serial-term mode
Can I invoke F12 or other function keys as minicom's F12?
I tried below... but it doesn't work
```
(global-set-key [f12] nil)
```
Thank you in advance!
# Answer
The input of an application running in a terminal consists of characters, not keys. So Minicom doesn't directly see a key `F12`. What it sees is an *escape sequence* (which is a string starting with the escape character `?\e`), which it knows represents `F12`. See How do keyboard input and text output work? for more information.
Therefore you need to instruct Emacs to send the escape sequence for `F12` when you press `F12`. The code of term mode has examples of how to do it for other function keys that are predefined in this way. For example, press `F1` `k` `Left` in Term mode to see what the `Left` key does:
```
<left> runs the command term-send-left (found in term-raw-map), which
is an interactive compiled Lisp function in ‘term.el’.
```
Its definition is:
```
(defun term-send-left () (interactive) (term-send-raw-string "\eOD"))
```
Now you need to find the escape sequence to send for `F12`.
* One way to do this is to use another terminal (not Emacs-based) and press `Ctrl`+`V` `F12` at a shell prompt. `Ctrl`+`V` causes the next character (which is the escape character that starts the escape sequence) to be entered literally rather than interpreted as a command (to start an escape sequence). You'll see `^[[24~`, where `^[` is a visual representation of the escape character.
* Another way to do this is to run Emacs in a terminal and press `Ctrl`+`Q` `F12`. Here too, you'll see `^[[24~` where `^[` is a visual representation of the escape character.
* Alternatively, you can look up how Emacs does the translation. This information is terminal-specific, but all modern terminals are based on the same standard and xterm is the de facto reference implementation of that standard. Run `M-x load-library RET term/xterm RET` then look up the definition of the variable `xterm-function-map` (`f1 v xterm-function-map RET` then follow the link to the source)¹.
Now that you've identified the escape sequence, bind it in `term-raw-map`.
```
(defun term-send-f12 () (interactive) (term-send-raw-string "\e[24~"))
(define-key term-raw-map [f12] 'term-send-f12)
```
In your init file:
```
(defun my-eval-after-load-term ()
(defun term-send-f12 () (interactive) (term-send-raw-string "\e[24~"))
(define-key term-raw-map [f12] 'term-send-f12)
)
(eval-after-load "term" my-eval-after-load-term)
```
¹ <sub> It might be nice to look this up programmatically, but there doesn't seem to be a convenient way. `(where-is-internal [f12] xterm-function-map)` doesn't work (it returns `nil`), I don't know why. </sub>
> 0 votes
---
Tags: key-bindings, term
--- |
thread-63234 | https://emacs.stackexchange.com/questions/63234 | Turn off auto-completion/company while in org-journal | 2021-02-07T03:59:22.367 | # Question
Title: Turn off auto-completion/company while in org-journal
Trying to get org-journal working, but it wants to auto-complete nearly every word I type, then require two space bar hits to advance to type next word.
I tried this and it works
```
(add-hook 'org-mode-hook (lambda () (toggle-auto-completion-off)))
```
but this is a false-friend and causes bizarre problems other places. I want company on but just not while typing text in org-journal. Can that be done?
Here is my org-journal config
```
(use-package org-journal
:after org
:custom
(org-journal-dir "~/Dropbox/org/journal/")
(org-journal-date-prefix "#+TITLE: ")
(org-journal-time-prefix "* ")
(org-journal-file-format "%Y/%m/%Y%m%d.org")
(org-journal-date-format "%Y-%m-%dT%H:%M:%S")
(org-journal-enable-agenda-integration t)
:bind
("C-c j" . org-journal-new-entry))
```
Yes, when I disable company, the problem goes away. A hook should allow this, but I'm getting it wrong?
```
(add-hook 'org-journal-mode-hook (company-mode -1))
```
# Answer
At the suggestion of Fran Burstall above in the comments, I added a properly written hook to `org-journal-mode-hook` to my org-journal `use-package` block
```
(use-package org-journal
:after org
:custom
(org-journal-dir "~/Dropbox/org/journal/")
(org-journal-date-prefix "#+TITLE: ")
(org-journal-time-prefix "* ")
(org-journal-file-format "%Y/%m/%Y%m%d.org")
(org-journal-date-format "%Y-%m-%dT%H:%M:%S")
(org-journal-enable-agenda-integration t)
:bind
("C-c j" . org-journal-new-entry)
:config
(add-hook 'org-journal-mode-hook (lambda () (company-mode -1))))
```
> 0 votes
---
Tags: hooks, auto-complete-mode, org-journal
--- |
thread-63239 | https://emacs.stackexchange.com/questions/63239 | How to keep minibuffer height compact as possible? | 2021-02-07T12:26:08.903 | # Question
Title: How to keep minibuffer height compact as possible?
I am using `GNU Emacs 26.3` under `iTerm2`. My goal is to keep minibuffer size as compact/minimum as possible.
Default height view:
---
Sometimes minibuffer's height increases and remains as it is. The empty space is small but I cat detected it, since I spent hours in `emacs`.
* I observe that when the `iTerm2`'s size is changed (increased and decreased) it also affects the minibuffer's size.
* When I restarted the `emacs` minibuffer size may still remain with the additional empty space. I am not sure this is result of `iTerm` or `emacs`'s configuration.
---
Example of increased minibuffer height:
# Answer
A program running inside of a terminal only knows how many whole lines of text will fit. Most terminals just leave the extra space empty, filled with just the background color. Resize the window slowly and watch what happens as the lower edge of the window approaches the bottom of the visible text in the window.
Emacs has a GUI as well, which allows it much more flexibility than it has when it runs inside a terminal. You might prefer it.
> 1 votes
---
Tags: minibuffer
--- |
thread-63243 | https://emacs.stackexchange.com/questions/63243 | evil-mode exec register ignores pipe | 2021-02-07T16:13:12.357 | # Question
Title: evil-mode exec register ignores pipe
In vim, assume `:r!ls | grep foo` is in the register **l**.
You can then do: `@l` to exec `ls | grep foo` and insert the contents matching foo in to the current buffer.
In evil-mode I get:
```
Usage: grep [OPTION]... PATTERN [FILE]...
Try 'grep --help' for more information.
```
Is this a bug, or a setting I'm missing?
# Answer
> 1 votes
That's one of the many unimplemented Ex features in Evil. There's nothing you're overlooking, except maybe a chance to contribute it.
---
Tags: evil, registers
--- |
thread-63226 | https://emacs.stackexchange.com/questions/63226 | resize-temp-buffer doesn't work in my code when 2 windows are diplayed into the frame | 2021-02-06T16:26:53.203 | # Question
Title: resize-temp-buffer doesn't work in my code when 2 windows are diplayed into the frame
I'm searching for a way to display messages while replacements are proposed to the users of a script.
I tried to write a macro but I'm in trouble with this code:
```
(defmacro with-user-explanation (MESSAGE &rest body)
"DOCSTRING."
(declare (indent 1))
`(let* ((temp-buffer-resize-mode temp-buffer-resize-mode)
(frame-config (current-frame-configuration))
(fit-frame-to-buffer t))
(temp-buffer-resize-mode 1)
(resize-temp-buffer-window)
(unwind-protect
(progn
(with-output-to-temp-buffer "REPLACEMENT INFO"
(princ ,MESSAGE))
,@body)
;; *CLEANUP*
(progn
(kill-buffer "REPLACEMENT INFO")
(set-frame-configuration frame-config)))))
(defun my-ue-test ()
"DOCSTRING"
(interactive)
(save-excursion
(let* ((a (point-min-marker))
(z (point-max-marker)))
(with-user-explanation
"This message provide info about this specific string replacement in the document."
(query-replace "foo" "bar" nil a z)))))
```
I have 2 issues:
1. When I run the function with 2 windows opened: the temp buffer is not resized: I need it to be resized: It is correctly resize when I run the function with only one window diplayed.
2. At the function exit, the layout (the color) of the pointer has changed (from white to gray). **I moved this issue here: Cursor's color differs from what specified in the frame parameters**
**Edit.** Maybe using a temp-buffer to display MESSAGE is not a good idea. Everything is messed up, also with the Arch Stanton's solution, if I use e.g. `occur`:
```
(defun my-ue-test ()
"DOCSTRING"
(interactive)
(save-excursion
(let* ((a (point-min-marker))
(z (point-max-marker)))
(with-user-explanation
"This message provide info about this specific string replacement in the document."
(occur "foo")
(query-replace "foo" "bar" nil a z)))))
```
**EDIT 2.** This last issue is solved with `set-window-dedicated-p`:
```
(defmacro with-user-explanation (MESSAGE &rest body)
"DOCSTRING."
(declare (indent 1))
`(let* ((temp-buffer-resize-mode temp-buffer-resize-mode)
(frame-config (current-frame-configuration))
(fit-frame-to-buffer t)
(temp-buffer-show-function
(lambda (bufname)
(display-buffer bufname '(display-buffer-at-bottom)))))
(unwind-protect
(progn
(with-output-to-temp-buffer "REPLACEMENT INFO"
(princ ,MESSAGE))
(fit-window-to-buffer (get-buffer-window "REPLACEMENT INFO"))
(set-window-dedicated-p (get-buffer-window "REPLACEMENT INFO") t)
,@body)
;; *CLEANUP*
(progn
(kill-buffer "REPLACEMENT INFO")
(set-frame-configuration frame-config)))))
```
# Answer
I never encountered any issue with the cursor's colour, so it may still be off for you, but the other issue seems fixed in this version,
```
(defmacro with-user-explanation (MESSAGE &rest body)
"DOCSTRING."
(declare (indent 1))
`(let* ((temp-buffer-resize-mode temp-buffer-resize-mode)
(frame-config (current-frame-configuration))
(fit-frame-to-buffer t)
(temp-buffer-show-function
(lambda (bufname)
(display-buffer bufname '(display-buffer-at-bottom)))))
(unwind-protect
(progn
(with-output-to-temp-buffer "REPLACEMENT INFO"
(princ ,MESSAGE))
(fit-window-to-buffer (get-buffer-window "REPLACEMENT INFO"))
(set-window-dedicated-p (get-buffer-window "REPLACEMENT INFO") t)
,@body)
;; *CLEANUP*
(progn
(kill-buffer "REPLACEMENT INFO")
(set-frame-configuration frame-config)))))
(defun my-ue-test ()
"DOCSTRING"
(interactive)
(save-excursion
(let* ((a (point-min-marker))
(z (point-max-marker)))
(with-user-explanation
"This message provide info about this specific string replacement in the document."
(query-replace "foo" "bar" nil a z)))))
```
I've set the `temp-buffer-show-function` (that's where you can choose where to place the `REPLACEMENT INFO` buffer's window. I chose at the bottom, you can see the other options in the documentation of `display-buffer`) and replaced `(temp-buffer-resize-mode 1)` and `(resize-temp-buffer-window)` with `(fit-window-to-buffer (get-buffer-window "REPLACEMENT INFO"))`.
> 1 votes
---
Tags: message
--- |
thread-63249 | https://emacs.stackexchange.com/questions/63249 | Dynamic name for org-capture template file | 2021-02-07T20:51:41.937 | # Question
Title: Dynamic name for org-capture template file
I am new to org-mode (and to Emacs in general) and am trying to set up org-capture. I would like to define a todo capture item whose template is located in the file `~/.emacs.d/org-templates/todo.tmpl`. I have tried with
```
(global-set-key (kbd "C-c c") 'org-capture)
(setq org-directory "~/org/")
(setq org-default-notes-file (concat org-directory "notes.org"))
(setq org-todo-template (concat user-emacs-directory "org-templates/todo.tmpl"))
(setq org-capture-templates
'(("t"
"Todo list item"
entry
(file+headline org-default-notes-file "Tasks")
(file org-todo-template)
)))
```
I get the error:
```
Wrong type argument: stringp, org-todo-template
```
if I replace the line
```
(file org-todo-template)
```
with
```
(file "~/.emacs.d/org-templates/todo.tmpl")
```
then it works, and I do not understand why.
For reference, the content of the file `~/.emacs.d/org-templates/todo.tmpl` is
```
* TODO %^{Description}
%i
%a
- %?
:LOGBOOK:
CREATED: %U
:END:
```
# Answer
> 1 votes
Try this:
```
(setq org-capture-templates
`(("t"
"Todo list item"
entry
(file+headline org-default-notes-file "Tasks")
(file ,org-todo-template)
)))
```
The backquote quotes the list but allows the `,` to interpolate the value of the variable `org-todo-template`.
---
Tags: org-capture, variables
--- |
thread-63230 | https://emacs.stackexchange.com/questions/63230 | Org-mode hook following creation of a new <<<radio target>>> | 2021-02-06T21:24:38.497 | # Question
Title: Org-mode hook following creation of a new <<<radio target>>>
I want to call `org-update-radio-target-regexp` as soon as `org-mode` recognises that a new `<<<radio target>>>` has been created (which seems to happen as soon as the third `">"` is typed, at least this is when it gets fontified).
What hook can I use to get this done?
# Answer
> 1 votes
Following NickD's input on my first answer (thanks @NickD) I think a better approach is to limit `org-update-radio-target-regexp` to only fire when the target is first created. This is done by binding the `">"` key and then testing whether point is just to the right of a `<<<radio target>>>` (after it is pressed). Here is the code:
```
(define-key org-mode-map (kbd ">")
(lambda ()
(interactive)
(if (and (org-in-regexp org-target-regexp)
(not (org-in-regexp org-target-regexp nil t)))
(progn
(insert ">")
(org-update-radio-target-regexp))
(insert ">"))))
```
# Answer
> 0 votes
This works:
```
(defun org-at-radio-target-p ()
(not (eq (org-in-regexp org-radio-target-regexp) nil)))
(add-hook 'post-command-hook
(lambda ()
(when (org-at-radio-target-p)
(org-update-radio-target-regexp))))
```
I am not sure how efficient it is, hooking into `post-command-hook`. But it seems to work okay, so far...
---
Tags: org-mode, hooks, hyperlinks
--- |
thread-63255 | https://emacs.stackexchange.com/questions/63255 | What's the difference between magit-branch-checkout and magit-branch-and-checkout? | 2021-02-07T23:39:44.600 | # Question
Title: What's the difference between magit-branch-checkout and magit-branch-and-checkout?
If I'm on the commandline, and I'm in the master branch, and I want to create a new branch and immediately start working on it, I'd just do `git checkout -b foo`.
So I'm looking for the magit equivalent to this, i.e., I'd like to be able to call some magit function from within a branch, and then find myself working on the same buffer, but in a new branch that I've named. Once I find that function, I intend to bind it to a key so that I can avoid having to muck around with transient states and such.
In the magit docs, I see two different commands that might qualify:
1. `magit-branch-and-checkout` which, according to the manual, "creates a new branch like `magit-branch`, but then also checks it out." (Incidentally, this is kind of a bizarre bit of documentation, since according to the very same page of the manual, `magit-branch` does not, in fact, create a new branch, but rather is a prefix command that puts one in a branching transient stage. so... huh??)
2. `magit-branch-checkout` which, according to the docs, takes the name of a branch from the user (I assume `magit-branch-and-checkout` must do that too, right? unless, like, magit just picks a name for you for the new branch?), and then, per the docs, "If the user enters a new branch name, then it creates and checks that out, after also reading the starting-point from the user."
So, those sound like *the exact same functionality.* Except maybe that `magit-branch-checkout` asks for a "starting point" (is that a commit hash? a preexisting branch? we are not told.). But if that's the difference between the two, then this raises a sub-puzzle, viz.: how does magit determine the starting point for whatever `magit-branch-and-checkout` does?
So if I wanted to just do the magit equivalent of `git checkout -b foo` and immediately be working on the buffer in the new branch, would I use one of those? Something else entirely? Impossible within magit?
(I really wish there were a translation table somewhere from ordinary commandline git calls to magit function calls.)
# Answer
> 5 votes
I think all of your confusion is due to a typo in the docs. I believe "creates a new branch like magit-branch" should read "creates a new branch like magit-branch-create".
So `b``c` `magit-branch-and-checkout` does this:
> Create \[and checkout\] a new branch. The user is asked for a branch or arbitrary revision to use as the starting point of the new branch. When a branch name is provided, then that becomes the upstream branch of the new branch. The name of the new branch is also read in the minibuffer.
While `b``l` `magit-branch-checkout` does this:
> This command checks out an existing or new local branch. It reads a branch name from the user offering all local branches and a subset of remote branches as candidates. Remote branches for which a local branch by the same name exists are omitted from the list of candidates. The user can also enter a completely new branch name.
>
> * If the user selects an existing local branch, then that is checked out.
> * If the user selects a remote branch, then it creates and checks out a new local branch with the same name, and configures the selected remote branch as the push target.
> * If the user enters a new branch name, then it creates and checks that out, after also reading the starting-point from the user.
>
> In the latter two cases the upstream is also set. Whether it is set to the chosen starting point or something else depends on the value of magit-branch-adjust-remote-upstream-alist.
---
So to answer your questions:
> magit-branch-checkout asks for a "starting point" (is that a commit hash? a preexisting branch? we are not told.)
A "starting point" means the same thing as `<start-point>` does in Git's own documentation (see, e.g., `man git-branch`): any commit reference -- which might be a commit hash, a branch name, or a tag (i.e. anything which git accepts as a point in the commit history).
> how does magit determine the starting point for whatever `magit-branch-and-checkout` does?
Magit acts contextually -- in most cases where a reference is read from the user, the reference at point will be offered as a default value. If there is no commit at point, then a default value may be offered (in this case, the current HEAD commit).
So a great deal of the time you would just type `RET` at that prompt to use the default. So long as you understand where the default value is coming from, the simplest way of selecting a commit to do something with is usually to arrange that it will be the default value (typically by having point on the relevant line).
> So if I wanted to just do the magit equivalent of `git checkout -b foo` and immediately be working on the buffer in the new branch, would I use one of those?
You *could* use either -- it will only really affect the order in which you enter the two arguments (being the name of the new branch, and its starting point). I always use `b``c` for this.
---
Tags: magit
--- |
thread-63247 | https://emacs.stackexchange.com/questions/63247 | How do I permanently change my emacs load-path? | 2021-02-07T19:16:55.803 | # Question
Title: How do I permanently change my emacs load-path?
Having searched for advice on how to change the load-path, I found this answer in the EmacsWiki:
https://www.emacswiki.org/emacs/LoadPath
I have evaluated a similar command in the minibuffer:
```
(add-to-list 'load-path "/usr/share/emacs/27.1/lisp/6502")
```
The intention is to add a 6502 major mode to emacs found here:
http://www.tomseddon.plus.com/beeb/6502-mode.html
Once I have entered that expression, querying the load-path variable confirms it has changed.
When I then test the change by quitting and restarting emacs I see an error which says
```
File is missing: Cannot open load file, No such file or directory, 6502-mode
```
When I then query the load-path again the change I made was forgotten.
How do I make changes to the load-path permanent?
# Answer
Evaluating lisp expressions in the minibuffer (or in the *scratch* buffer, or with `C-x C-e` in an emacs-lisp buffer, or loading lisp libraries by hand with `M-x load-file` or ....) only affects the current session of emacs. The moment you kill this emacs session everything that is not part of the initial emacs state is lost irretrievably. So even if you `(add-to-list 'load-path ...)` appropriately and you `(require '6502-mode)` in *this* session, if you are doing it interactively, you are only affecting the current session.
In order to affect a future emacs session, you need to save this initialization in a file and load that file into the future emacs session somehow. That's what the init file provides: when emacs starts up, it *automatically* knows to load that file. So you need to add such settings to your init file:
```
(add-to-list 'load-path "/usr/share/emacs/27.1/lisp/6502")
(require '6502-mode)
```
From that point on, *every* session of emacs you start up will load the init file, evaluating everything in it.
---
Sometimes, it is useful to start an emacs session that does *NOT* load your init file, e.g. there might be something wrong with it and your emacs session misbehaves: it is often useful in such cases to create an emacs session without your initializations in order to see whether emacs misbehaves the same way; if it does not, then that tells you that there is something wrong in your init file and you need to find it and fix it.
To start an emacs session without your initialization file, you can say `emacs -q`: the `-q` option tells emacs *not* to do its usual default action of loading the init file.
---
BTW, there are lots of details about the init file in the Emacs Manual: it's well worth reading that section (as is the whole manual of course, but you cannot read it in one sitting, but you should familiarize yourself with it, so you know where to go to look up something).
Another, very useful, way to read the manual is by using the Info system from *within* emacs. Assuming that you have the manual installed (which should be the case on any platform that you might use: Linux, Windows or MacOS), then in emacs you can say `C-h i g (emacs)Init file RET` which will take you to the same page in your local copy of the manual that the link above takes you in the copy that's available on the web.
Learning how to use Info to look up things in emacs will prove invaluable: I highly recommend it.
> 1 votes
---
Tags: load-path
--- |
thread-63258 | https://emacs.stackexchange.com/questions/63258 | What is the system-wide location for init.el? | 2021-02-08T03:27:44.133 | # Question
Title: What is the system-wide location for init.el?
Is there a way to have a common `init.el` for several system users? /etc/emacs.d/init.el for example?
# Answer
> 1 votes
This is documented in chapter 49.4 The Emacs Initialization File of the Emacs manual (which is also included as part of Emacs, use `C-h i` to open the info browser which will show you this and many other manuals already on your computer). In short, Emacs loads both `site-lisp.el` and `defaults.el` in addition to your own startup file, and these two files may be located anywhere in the `load-path`. Exactly what directories end up in your `load-path` may vary across operating systems and distributions, but in most Linux distributions it will include a directory like `/usr/share/emacs/site-lisp`.
---
Tags: init-file, system-environment
--- |
thread-63261 | https://emacs.stackexchange.com/questions/63261 | How do I change the highlighted background color inside the parenthesis? | 2021-02-08T06:50:56.223 | # Question
Title: How do I change the highlighted background color inside the parenthesis?
I am using pretty much the default theme color however, I do want to change the highlighted background color inside the parenthesis.
Is there any specific Face Attributes setting for this specific case?
# Answer
```
(set-face-attribute 'show-paren-match-expression nil :background "yellow")
```
See Faces in the Elisp manual, in particular Face Attribute Functions, and Matching Parentheses.
If you want to tweak a face, positioning the cursor on a character and hitting `C-u` `C-x` `=` (`what-cursor-position`) will open a buffer with information about the faces used to display that character (that's how I found out about `show-paren-match-expression`). If you click on a face that interests you Emacs will open its documentation, saying in which library it's defined, with a link to the library. Click it. Most definitions have a `:group` keyword, for example `:group 'paren-showing-faces`. You can invoke `customize-group` and give it that keyword as argument, i.e. you can type `M-x customize-group RET paren-showing-faces RET` and you'll be brought to a buffer with a list of options for that topic.
> 2 votes
---
Tags: faces, colors
--- |
thread-63266 | https://emacs.stackexchange.com/questions/63266 | How add specifc string(ex: TODO) along with a comment character for a specifc mode? | 2021-02-08T12:44:35.820 | # Question
Title: How add specifc string(ex: TODO) along with a comment character for a specifc mode?
Based on specific `mode`, by using a keybinding I want to add a `TODO` string that is preceded by an unique comment character. For example, (org-mode is exception since `**` does not stands for comment and TODO shouldn't followed by `:`)
* `python-mode:` =\> `# TODO:`
* for script-mode: =\> `# TODO:`
* for latex mode: =\> `% TODO:`
* for org-mode: =\> `** TODO`
Basically comment character of the current mode on the buffer followed by `TODO:` .
# Answer
This function should cover the first cases (comment delimiter followed by " TODO: ")
```
(defun insert-todo ()
(interactive "*")
(insert comment-start " TODO: "))
```
This one covers the `org-mode` case:
```
(defun org-insert-todo ()
(interactive "*")
(insert "** TODO "))
```
You could bind them to a key combination with something like this
```
(define-key prog-mode-map (kbd "C-c t") #'insert-todo)
(define-key org-mode-map (kbd "C-c t") #'org-insert-todo)
```
In case you're wondering, the `*` in the `interactive` form serves to signal an error when the user invokes the function in a read-only buffer (see the manual).
> 1 votes
---
Tags: comment, todo
--- |
thread-63267 | https://emacs.stackexchange.com/questions/63267 | How to duplicate text but increment a numeric part of a name? | 2021-02-08T14:14:18.773 | # Question
Title: How to duplicate text but increment a numeric part of a name?
Say that I have rect1 one and I'll multiply it 3 times by yanking.
```
let rect1 = Rectangle {
width: 10,
height: 40,
}
let rect1 = Rectangle {
width: 10,
height: 40,
}
let rect1 = Rectangle {
width: 10,
height: 40,
```
How can I obtain rect1, rect2, rect3 etc. instead of just repeating rect1?
# Answer
> 3 votes
query-replace-regexp can do the trick. Select the region you want for replacing and :
```
C-M % \brect1\b RET rect\,(1+ \#) RET !
```
for more information
```
(info "(emacs)Regexp Replacement")
```
;;;;;;;;;;;;;;;;;;;;;;;;; A function for more comfort;;;;;;;;;;;;;;;;;;;;;;;;;
```
(defun multiple-paste-renum(n renum paste )
"Paste N copy of PASTE and renumber the string RENUM followed by digits
from 1 to until the last"
(interactive "nNumber repeats: \nsWord to be renumerate: \nsText or RET for the current kill-ring: ")
(let ((text (if (string= "" paste) (substring-no-properties (current-kill 0))paste)))
(insert (with-temp-buffer
(dotimes (p n) (insert "\n" text "\n"))
(goto-char (point-min))
(let ((p 0))
(while (search-forward-regexp (format "\\b%s[0-9]+\\b" renum) nil t)
(replace-match (format "%s%d" renum (setq p (1+ p))))))
(buffer-string)))))
```
---
Tags: text-editing, keyboard-macros, query-replace-regexp
--- |
thread-63270 | https://emacs.stackexchange.com/questions/63270 | Where to place org-agenda-files sexp | 2021-02-08T17:34:24.110 | # Question
Title: Where to place org-agenda-files sexp
I have this
```
(setq org-agenda-files (directory-files-recursively "~/Dropbox/org/journal/" "\\.org$"))
```
but I don't know where to place it in order to make sure that on the event of a new daily org-journal file creation in my journal directory (e.g. ~Dropbox/org/journal/2021/02/) the agenda file list will immediately be updated. At the moment I have it placed early in my init.el, which thereafter calls a big, general config.org full of package initializations and tweaks, then a private `custom-set-variables` file. Does this sexp need to be part of some special trigger/hook/event code to know to update the `org-agenda-files` list when a new org-journal day file appears?
# Answer
TL;DR: set the variable `org-agenda-files` to be a *list* of all the *directories* that you want to scan recursively for `*.org` files:
```
(setq org-agenda-files '("~/Dropbox/org/journal/"))
```
Explanation:
There are two `org-agenda-files` objects: a function and a variable. Org mode calls the *function* when it needs the list. The function looks at the `org-agenda-files` *variable* and proceeds accordingly:
* if the variable is a filename, then it is interpreted as a file that contains the names of all the agenda files. So this is static: you need to add any additional files that you want.
* if the variable is a *list* of filenames, then that's the list of agenda files, except that if an entry in the list is a directory it is scanned recursively for any files that match `org-agenda-file-regexp`. The latter matches files of the form `foo.org` so you don't have to do this yourself.
If you look at the implementation of the *function* `org-agenda-files`, you'll see that it does already the recursive scan, so you don't have to. And it uses the `org-agenda-file-regexp` so you don't have to.
Untested.
> 1 votes
---
Tags: org-agenda, hooks, org-journal
--- |
thread-40965 | https://emacs.stackexchange.com/questions/40965 | How to convert a BibTeX entry into formatted string? | 2018-04-10T22:39:38.337 | # Question
Title: How to convert a BibTeX entry into formatted string?
I'd like to be able to export BibTeX entries as (flexibly formatted) strings.
For example, a BibTeX entry like this one:
```
@Article{Chomsky:59,
author = {Noam Chomsky},
title = {On Certain Formal Properties of Grammars},
year = {1959},
volume = {2},
pages = {137--167},
journal = {Information and Control}
}
```
Should be converted into the following string:
```
Chomsky, Noam. 1959. On Certain Formal Properties of Grammars. Information and Control 2. 137--167.
```
I used to manage my BibTeX database with JabRef which lets you customize exports. But I haven't seen something similar in Emacs/`bibtex.el`.
# Answer
> 1 votes
I've eventually found a very flexible way to achieve this using `helm-bibtex` and `citeproc.el`, adding just the following code (taken from here):
```
(defvar helm-bibtex-csl-style "~/.emacs.d/csl/unified-style-sheet-for-linguistics.csl")
(defvar helm-bibtex-csl-locale-dir "~/.emacs.d/csl")
(defun helm-bibtex-insert-citeproc-reference (_candidate)
(let* ((locale-getter (citeproc-locale-getter-from-dir helm-bibtex-csl-locale-dir))
(item-getter (citeproc-itemgetter-from-bibtex helm-bibtex-bibliography))
(proc (citeproc-create helm-bibtex-csl-style item-getter locale-getter))
(cites (mapcar (lambda (x) (citeproc-citation-create :cites `(((id . ,x)))))
(helm-marked-candidates))))
(citeproc-append-citations cites proc)
(insert (car (citeproc-render-bib proc 'plain)))))
(helm-add-action-to-source "Insert citeproc-formatted reference" 'helm-bibtex-insert-citeproc-reference helm-source-bibtex)
```
This method requires that you provide a CSL file and specify its path in `helm-bibtex-csl-style` and `helm-bibtex-csl-locale-dir`. There exist CSL files for virtually every formatting style. You can choose and download them conveniently here.
# Answer
> 6 votes
The `org-ref` package contains this functionality. Contrary to the name, `org-ref` has a lot of functionality outside of org mode. Take a look at the function `org-ref-format-bibtex-entry`. It also integrates this into `helm-bibtex`, so if you get everything set up correctly, you can call `helm-bibtex`, mark the citations you want, then hit `f7` which inserts a formatted list.
EDIT:
If you didn't want to add a whole package with lots of dependencies, you can write your own function. Here's an example to illustrate:
```
(defun bibtex-format-entry-to-string ()
"Format bibtex entry under point to a string."
(interactive)
(save-excursion
(bibtex-beginning-of-entry)
(let ((authors (bibtex-text-in-field "author"))
(year (bibtex-text-in-field "year"))
(title (bibtex-text-in-field "title")))
(format "%s, %s, %s" authors year title))))
```
---
Tags: bibtex
--- |
thread-63271 | https://emacs.stackexchange.com/questions/63271 | Locking an org-timer into the mode-line | 2021-02-08T17:46:21.420 | # Question
Title: Locking an org-timer into the mode-line
**Context.** I frequently use
1. org-mode timers
2. The org-mode clock (which just displays the clock in the org-mode mode-line)
3. A custom "target time" clock, which shows a point in time (either a few minutes or a few hours from now) that I'm trying to get something done by
Here's the way it looks now as an example:
`12:40PM 0.57` is the current time, `<0:00:42>` is the active timer, and `12:48PM` is the "target time" I'm trying to get my current task done by.
**Problem.** This mode-line disappears or gets mangled *all of the time* (particularly, I think, when I switch buffers around?). I would like it to be displayed universally no matter which emacs buffer I'm in. I've tried setting
```
(setq global-mode-string '("" display-time-string org-mode-line-string org-timer-mode-line-string " " est-target))
```
where `est-target` is my "target time" (as described in (3)), but it doesn't always work (even when I bind it to key and press it on the current buffer).
Does anyone know how to lock this mode-line in place?
# Answer
You can set the mode line to be fixed with
```
(setq-default mode-line-format "FOO")
```
It will always show "FOO" and nothing else.
I assume that if you do
```
(setq-default mode-line-format '("" display-time-string org-mode-line-string org-timer-mode-line-string " " est-target))
```
and enable things appropriately (e.g. you have to call `(display-time)` to have `display-time-string` show anything) you will get what you want.
BUT: the mode line contains all sorts of useful information that you would lose this way.
There is another possibility and that is the header line: it is used occasionally, but not nearly as much as the mode line, so it should be safer to muck around with it. Basically do the same thing but with `header-line-format`:
```
(setq-default header-line-format '("" display-time-string org-mode-line-string org-timer-mode-line-string " " est-target))
```
Maybe that will not be interfered with as much.
Note BTW, that both `mode-line-format` and `header-line-format` become buffer-local when set, so using `setq` only sets the buffer-local-variable. `setq-default` sets the global value, which is used to initialize the buffer-local variable. Modifying the buffer-local variable by adding things to it but not clobbering it completely should then behave more or less as you expect.
But I have not tested any of this to any extent, so no guarantees: if it breaks, you get to keep the pieces. I would experiment on a session of emacs created for the purpose, *not* on my main session.
> 1 votes
---
Tags: org-mode, timers
--- |
thread-63265 | https://emacs.stackexchange.com/questions/63265 | c w movement up to next word instead of end of word | 2021-02-08T10:37:15.087 | # Question
Title: c w movement up to next word instead of end of word
In vi, `c w` stops at the end of the current word (that movement is normally `e`, as in `c e`). This is different from `w` alone or `d w`, which go up to the beginning of the next word.
A popular Vim configuration causes `c w` to do work like other `w` commands, where the "word" movement takes you UP TO the next word. Consuming any whitespace.
How do I make `c w` work in evil as it does in this Vim configuration?
Evil: 1.14.0
Emacs: 27.1
# Answer
Do `C-h v` `evil-want-change-word-to-end` `RET`, then `customize` that variable from `t` to `nil`.
Reference:
> evil-want-change-word-to-end is a variable defined in ‘evil-vars.el’. Its value is t
>
> You can customize this variable.
>
> Documentation: Whether ‘cw’ behaves like ‘ce’.
> 1 votes
---
Tags: evil
--- |
thread-63276 | https://emacs.stackexchange.com/questions/63276 | How to append some behavior to a command? | 2021-02-09T02:24:14.343 | # Question
Title: How to append some behavior to a command?
How do I string together functions and actions in a key binding.
Say I want to make a binding that does `comment-dwim` and then appends "TODO: " to achieve `/* TODO: */` in C.
```
(global-set-key (kbd "C-c T") 'comment-dwim "TODO: ")
```
This doesn't work because `comment-dwim` interprets the following as an argument.
Same for
```
(defun insert-todo () "TODO: ")
(global-set-key (kbd "C-c T") 'comment-dwim 'insert-todo)
```
# Answer
The problem with your first binding is not that `comment-dwim` interprets `"TODO: "` as an argument, it's that `global-set-key` tries to do so. You're giving `"TODO: "` as a third argument to `global-set-key`, but it only accepts two (the keys and the command).
To be clear, let me make another example using the command `insert-char`, which uses its argument in a more straightforward way than `comment-dwim`. `(insert-char ?c)` inserts a `c` in the current buffer. Now can you bind that call like this: `(global-set-key (kbd "C-c T") (insert-char ?c))`? No you can't. Key bindings only accept commands, not command calls (`insert-char` is a command, `(insert-char ?c)` is a call to that command). Note, command means *interactive* function, i.e. a function with an `interactive` form in its definition (see the manual). That's one of the problems with your second binding, the function is not interactive.
The other problem with your `insert-todo` is that the way it's defined, it *returns* `"TODO: "`, you didn't tell Emacs to *insert* it. Did you try to run `insert-todo`? Type `M-:`, enter `(defun insert-todo () "TODO: ")`, hit `RET`, then type `M-:` again, `(insert-todo)`, `RET`. You'll see `"TODO: "` in the echo area, as its return value. You need to give `"TODO: "` as argument to the function `insert` in order to insert it in the buffer when you call the function.
So I'd say you don't want to string together a function and an "action", you want to string together two function calls: `(comment-dwim nil)` (`comment-dwim` requires an argument and `nil` will do) and `(insert "TODO: ")`. Now if you need to call one or more functions with their arguments using a key combination, you can define a new interactive function that includes the calls to the functions and bind this new function, or you can put the same definition as an unnamed interactive function directly in the key binding:
* named function
```
(defun insert-todo-comment ()
(interactive "*")
(comment-dwim nil)
(insert "TODO: "))
(global-set-key (kbd "C-c T") #'insert-todo-comment)
```
* anonymous function
```
(global-set-key (kbd "C-c T") (lambda ()
(interactive "*")
(comment-dwim nil)
(insert "TODO: ")))
```
> 2 votes
---
Tags: commands
--- |
thread-52410 | https://emacs.stackexchange.com/questions/52410 | Org-link font size in the heading | 2019-08-29T17:19:40.887 | # Question
Title: Org-link font size in the heading
I often use org-links in headings, e.g.:
```
*** Heading [[foo]]
**** Subheading [[bar]]
```
And I use different font-sizes for different levels.
Now, I would like the face of the link to be of the same font-size as the heading's. Is that possible?
I tried using `:inherit` but that's not working.
# Answer
> 1 votes
I think the `org-link` face is set exclusively not in addition to other faces.
And there is only a fixed reference point for `:inherit`.
There would either
1. have to be a context sensitive `:inherit` or
2. different faces for the context, like with the `org-level` faces. There is `org-level-1`, `org-level-2` and so forth. But there are no separate faces for `org-link-level-1`, `org-link-level-2`
You could probably
> use a custom font-lock keyword function that programmatically applies colors to org tags based on location
as suggestet in this question
---
Tags: org-mode, faces
--- |
thread-63279 | https://emacs.stackexchange.com/questions/63279 | Tramp/Emacs 27 freeze on Mac | 2021-02-09T08:16:31.627 | # Question
Title: Tramp/Emacs 27 freeze on Mac
I'm facing a major issue with Tramp and Emacs 27.1 on a Mac (10.15.7), which makes it almost impossible to work on remote files ...
As soon as I start to type a SSH or SCP based URL in the mini buffer (after C-x C-f), I get a dialog from the OS, that I need to permit access to some keychain password. One of those trigger this issue:
```
/ssh:
/sshx:
/scp:
/-:
```
The dialog always asks for access to the oldest entry in my keychain, totally unrelated to what I do in emacs.
When I permit the access, I've still a chance to stop (ESC or C-g). When I reject, the emacs freeze and I can only kill the app.
Any hint or recommendation is very appreciated.
Br, Michael
PS: When I type the URL faster, or paste the full URL, I pass the issue sometimes and I can open remote files.
# Answer
Thanks to the hints I've updated the bundled version of tramp (2.4) with the one from ELPA (2.5.0.1).
After this the problems were resolved in Emacs 27.1.
All URLs over SSH/SCP are working, on high and low latency networks, with and without SUDO.
Thanks for the support!
> 0 votes
---
Tags: tramp, mac
--- |
thread-63282 | https://emacs.stackexchange.com/questions/63282 | How to create a function to lauch org-capture with a selected template? | 2021-02-09T09:19:10.973 | # Question
Title: How to create a function to lauch org-capture with a selected template?
Let's say my capture template is bound to 't':
```
(defun my/captureTemplate ()
(interactive)
(org-capture "r")
```
This won't work as it will show me the whole list of potential templates to choose from. Thanks!
# Answer
This should be
```
(defun my/captureTemplate ()
(interactive)
(org-capture nil "r"))
```
as `KEY` is the second optional argument to `org-capture`.
> 1 votes
---
Tags: org-capture
--- |
thread-63287 | https://emacs.stackexchange.com/questions/63287 | Issue with macro and `buffer-name` | 2021-02-09T10:53:37.520 | # Question
Title: Issue with macro and `buffer-name`
I want to write a macro that makes a `diffpdf` before and after some changes in my `LaTeX` file (that would be compiled twice by `pdflatex`).
I tried:
```
(defmacro with-diffpdf-after-changes (&rest body)
"DOCSTRING"
(declare (indent 1))
(let* ((FILE_NAME (file-name-sans-extension (buffer-name)))
(PDF_FILE (concat FILE_NAME ".pdf")))
`(progn
(save-buffer)
(call-process-shell-command
(concat "pdflatex \"\\let\\oldExecuteOptions\\ExecuteOptions\"\\\n"
"\"\\def\\ExecuteOptions#1{\\oldExecuteOptions{#1,draft}}\"\\\n"
"\"\\nonstopmode\\input{" (buffer-name) "}\";"
"mv " ,PDF_FILE " /tmp/" )
nil nil)
,@body
(save-buffer)
(call-process-shell-command
(concat "pdflatex \"\\let\\oldExecuteOptions\\ExecuteOptions\"\\\n"
"\"\\def\\ExecuteOptions#1{\\oldExecuteOptions{#1,draft}}\"\\\n"
"\"\\nonstopmode\\input{" (buffer-name) "}\";"
"diffpdf -a " ,PDF_FILE " /tmp/" ,PDF_FILE )
nil nil)
)
))
```
But something's wrong with my code. `PDF_FILE` is named by the file that calls the macro while I need it to be named by the buffer of my LaTeX file.
E.g. my LaTeX file is `paper.tex`, the macro is called by a function in the file `replacements.el`
I get that the macro makes `diffpdf` look for `./replacements.pdf` and `/tmp/replacements.pdf`
I need `diffpdf paper.pdf /tmp/paper.pdf`.
# Answer
> 1 votes
My let-bindings was outside the quoted part.
The working code is:
```
(defmacro with-diffpdf-after-changes (&rest body)
"DOCSTRING"
(declare (indent 1))
`(progn
(let* ((FILE_NAME (file-name-sans-extension (buffer-name)))
(PDF_FILE (concat FILE_NAME ".pdf")))
(save-buffer)
(call-process-shell-command
(concat "pdflatex \"\\let\\oldExecuteOptions\\ExecuteOptions\"\\\n"
"\"\\def\\ExecuteOptions#1{\\oldExecuteOptions{#1,draft}}\"\\\n"
"\"\\nonstopmode\\input{" (buffer-name) "}\";"
"mv " PDF_FILE " /tmp/" )
nil nil)
,@body
(save-buffer)
(call-process-shell-command
(concat "pdflatex \"\\let\\oldExecuteOptions\\ExecuteOptions\"\\\n"
"\"\\def\\ExecuteOptions#1{\\oldExecuteOptions{#1,draft}}\"\\\n"
"\"\\nonstopmode\\input{" (buffer-name) "}\";"
"diffpdf -a " PDF_FILE " /tmp/" PDF_FILE )
nil nil)
)
))
```
Thanks to phils and Basil for their usefull comments.
---
Tags: elisp-macros
--- |
thread-63283 | https://emacs.stackexchange.com/questions/63283 | Creating a new text file in a directory using org-capture | 2021-02-09T09:21:23.897 | # Question
Title: Creating a new text file in a directory using org-capture
Following this response: `Org-Mode - How do I create a new file with org-capture` https://stackoverflow.com/questions/11902620/org-mode-how-do-i-create-a-new-file-with-org-capture?
I am trying to make this piece of code work, but I get the error: invalid file location: nil.
```
(defun capture-report-date-file (path)
(let ((name (read-string "Name: ")))
(expand-file-name (format "%s-%s.txt"
(format-time-string "%Y-%m-%d")
name) path)))
(setq org-capture-templates
'(("t"
"todo"
entry
(file (capture-report-date-file "~/path/path/name"))
"* TODO")))
```
# Answer
The code is outdated. Since version 9.1 `org-capture-templates` no longer accepts S-expressions as file names, so you have to turn:
```
(capture-report-date-file "~/path/path/name")
```
into
```
(lambda () (capture-report-date-file "~/path/path/name"))
```
> 1 votes
---
Tags: org-capture
--- |
thread-52567 | https://emacs.stackexchange.com/questions/52567 | company doesn't pop up completion list automatically | 2019-09-08T14:01:58.957 | # Question
Title: company doesn't pop up completion list automatically
I'm trying to get company mode to automatically trigger the pop-up with a list of possible completion. Unless I'm doing this wrong this is not the default behaviour? Current I have to run M-x company-complete manually.
I am not interesting in binding it to a key. I want the idle-completion behaviour. I'm using this with rustic (rust-mode fork).
Steps to reproduce:
* Start from fresh emacs
```
[ -e ~/.emacs.d ] && mv ~/.emacs.d ~/.emacs.d.bak
mkdir ~/.emacs.d && cat <<'EOT' > ~/.emacs.d/init.el
(setq package-archives '(("gnu" . "http://elpa.gnu.org/packages/")
("marmalade" . "https://marmalade-repo.org/packages/")
("melpa" . "http://melpa.org/packages/")))
(require 'package)
(package-initialize)
EOT
```
* Start Emacs
* Install packages (from MELPA): lsp-mode, company, rustic
* Install `rustup` (instructions at https://rustup.rs )
* Install additionnal components: `rustup component add rls rustfmt rust-src`
* Create new test project: `cargo new rtest`
* Add the following to init.el:
```
(defun my-rust-hook ()
(require 'company)
(setq company-minimum-prefix-length 2)
(setq company-idle-delay 0)
;; conf 1
;(setq company-auto-complete nil)
;; conf 2
(setq company-auto-complete t)
(add-to-list 'company-auto-complete-chars (char-syntax ?:))
(company-mode 1)
)
(eval-after-load 'rustic
'(progn
(require 'lsp)
(when (not (require 'yasnippet nil 'no-err))
(setq lsp-enable-snippet nil))
(add-hook 'rustic-mode-hook 'my-rust-hook)))
```
* Restart emacs
* Open `rtest/src/main.rs`
* Type:
```
use std::env;
fn main() {
// place point here at the end
}
```
* Type `env::` and wait. **Completion menu doesn't show up**.
* You can try conf 1 or 2 from the init.el but you will see same result.
* Running `M-x company-complete` works and shows the menu **but idling doesn't**.
# Answer
What is the value of `company-begin-commands`? It should include at least `self-insert-command`. Also, try changing `company-idle-delay` to a low value above zero.
The Rust setup I describe in my setting up Rust with Emacs guide comes with a repo that has a working auto completion config via company. When in doubt, compare with that.
> 1 votes
---
Tags: completion, rust, company
--- |
thread-63289 | https://emacs.stackexchange.com/questions/63289 | How to type superscript Roman numeral in Emacs, e.g., by using TeX input method? | 2021-02-09T11:54:08.647 | # Question
Title: How to type superscript Roman numeral in Emacs, e.g., by using TeX input method?
One can type normal Roman numerals by using `C-x 8 RET`. For example, to type one use `C-x 8 RET 2162 RET`. Furthermore, one can type superscript numbers, English letters and Greek ones by using the TeX input-method. For example, to type superscript alpha one switch to the TeX input-method and use `^\alpha`. However, it seems that one cannot type superscript Roman numerals, not even by expanding the TeX input-method as suggested ?
# Answer
Apparently, you are asking for a way to insert a superscript Roman numerals as raw text.
Let's first find out whether such characters exist. Note that not all characters have a superscript or subscript form. For example, in the table "Latin superscript and subscript letters" at this article in Wikipedia, it is mentioned that there is no superscript minuscule character for the character "q".
We know some names of the superscript characters
* ²: SUPERSCRIPT TWO
* ⁹: SUPERSCRIPT NINE
* ᴬ: MODIFIER LETTER CAPITAL A
* ᶿ: MODIFIER LETTER SMALL THETA
* ᵅ: MODIFIER LETTER SMALL ALPHA
As we can see above, there is no common pattern for the characters which are considered superscripts. For this reason, if we were to search in the names of all characters, we would need to list all those characters which contain the string `ROMAN` in its name.
We can print all the available characters which contain `ROMAN` in its name by executing the following
```
(require 'cl-lib)
(let ((chars (cl-loop for code from 0 to #x10FFFF
for name = (get-char-code-property code 'name)
when (and name (string-match "ROMAN" (get-char-code-property code 'name)))
collect `(,(number-to-string code) ,(format "%c" code) ,name))))
(dolist (char chars)
(princ (format "%s\n" (mapconcat 'identity char " ")))))
```
```
8544 Ⅰ ROMAN NUMERAL ONE
8545 Ⅱ ROMAN NUMERAL TWO
8546 Ⅲ ROMAN NUMERAL THREE
8547 Ⅳ ROMAN NUMERAL FOUR
8548 Ⅴ ROMAN NUMERAL FIVE
8549 Ⅵ ROMAN NUMERAL SIX
8550 Ⅶ ROMAN NUMERAL SEVEN
8551 Ⅷ ROMAN NUMERAL EIGHT
8552 Ⅸ ROMAN NUMERAL NINE
8553 Ⅹ ROMAN NUMERAL TEN
8554 Ⅺ ROMAN NUMERAL ELEVEN
8555 Ⅻ ROMAN NUMERAL TWELVE
8556 Ⅼ ROMAN NUMERAL FIFTY
8557 Ⅽ ROMAN NUMERAL ONE HUNDRED
8558 Ⅾ ROMAN NUMERAL FIVE HUNDRED
8559 Ⅿ ROMAN NUMERAL ONE THOUSAND
8560 ⅰ SMALL ROMAN NUMERAL ONE
8561 ⅱ SMALL ROMAN NUMERAL TWO
8562 ⅲ SMALL ROMAN NUMERAL THREE
8563 ⅳ SMALL ROMAN NUMERAL FOUR
8564 ⅴ SMALL ROMAN NUMERAL FIVE
8565 ⅵ SMALL ROMAN NUMERAL SIX
8566 ⅶ SMALL ROMAN NUMERAL SEVEN
8567 ⅷ SMALL ROMAN NUMERAL EIGHT
8568 ⅸ SMALL ROMAN NUMERAL NINE
8569 ⅹ SMALL ROMAN NUMERAL TEN
8570 ⅺ SMALL ROMAN NUMERAL ELEVEN
8571 ⅻ SMALL ROMAN NUMERAL TWELVE
8572 ⅼ SMALL ROMAN NUMERAL FIFTY
8573 ⅽ SMALL ROMAN NUMERAL ONE HUNDRED
8574 ⅾ SMALL ROMAN NUMERAL FIVE HUNDRED
8575 ⅿ SMALL ROMAN NUMERAL ONE THOUSAND
8576 ↀ ROMAN NUMERAL ONE THOUSAND C D
8577 ↁ ROMAN NUMERAL FIVE THOUSAND
8578 ↂ ROMAN NUMERAL TEN THOUSAND
8579 Ↄ ROMAN NUMERAL REVERSED ONE HUNDRED
8581 ↅ ROMAN NUMERAL SIX LATE FORM
8582 ↆ ROMAN NUMERAL FIFTY EARLY FORM
8583 ↇ ROMAN NUMERAL FIFTY THOUSAND
8584 ↈ ROMAN NUMERAL ONE HUNDRED THOUSAND
65936 ROMAN SEXTANS SIGN
65937 ROMAN UNCIA SIGN
65938 ROMAN SEMUNCIA SIGN
65939 ROMAN SEXTULA SIGN
65940 ROMAN DIMIDIA SEXTULA SIGN
65941 ROMAN SILIQUA SIGN
65942 ROMAN DENARIUS SIGN
65943 ROMAN QUINARIUS SIGN
65944 ROMAN SESTERTIUS SIGN
65945 ROMAN DUPONDIUS SIGN
65946 ROMAN AS SIGN
65947 ROMAN CENTURIAL SIGN
113741 DUPLOYAN LETTER ROMANIAN I
113750 DUPLOYAN LETTER ROMANIAN U
```
As we could see above, there is no `SUPERSCRIPT` characters for the roman numerals. For this reason, inserting such characters as raw text (i.e. what you are requesting) is not possible.
PD: I tried searching `"superscript roman numeral"` (note the double quotes) in Google and found some websites (here, here) which encourage to use such characters for different purposes, so those characters might be commonly used in other contexts not yet of interest to the Unicode Consortium.
> 3 votes
---
Tags: input-method, tex
--- |
thread-63137 | https://emacs.stackexchange.com/questions/63137 | my rust analyzer don't work on emacs 27 | 2021-02-02T22:18:20.247 | # Question
Title: my rust analyzer don't work on emacs 27
I recently installed the latest version of emacs and Rust-analyzer, and downloaded the lsp-mode package as well, but when I activate the rust-analyzer with the "lsp" command it simply returns an error saying that the rust-analyzer keep loading
# Answer
> 2 votes
rust-analyzer can take a while to index and load a project. You should still be fine, even if the text in the minibuffer doesn't immediately change. Try using e.g. the auto completion and see if it works.
If you want to test a prebuilt config, I recently written a guide to setup Emacs for Rust and it has a repo with an example config that you can run as-is. This was tested with Emacs 27.1, MacOS, Win 10, and Ubuntu.
---
Tags: lsp, rust
--- |
thread-22659 | https://emacs.stackexchange.com/questions/22659 | Integrate rust-clippy into Emacs Rust development | 2016-05-31T00:16:19.310 | # Question
Title: Integrate rust-clippy into Emacs Rust development
`rust-clippy` is a linter for Rust. Is there an existing package or idiom that integrates it into an Emacs Rust workflow, the way `emacs-racer` integrates `racer`?
# Answer
> 2 votes
Since `rust-clippy` normally works at compile time, it should get integrated into whatever you are using for compiling Rust code in Emacs (e.g. `cargo-minor-mode`). This is touched on in this blog post on setting up Emacs for Rust, in case you have not seen it already.
# Answer
> 2 votes
When you use rust-analyzer via lsp-mode you can tell it to use clippy as the default linter via `(setq lsp-rust-analyzer-cargo-watch-command "clippy")` (normally it would use check).
The config presented in this guide uses it by default.
---
Tags: rust
--- |
thread-63200 | https://emacs.stackexchange.com/questions/63200 | How to convert single line comments to multiline comments? | 2021-02-05T15:14:51.380 | # Question
Title: How to convert single line comments to multiline comments?
I have a bunch of single line comment blocks in C-code that I want to change to multiline. Example:
```
// foo
// bar
```
should become:
```
/* foo
* bar
*/
```
How can I do this easily in Emacs?
# Answer
Try this:
```
(defun ph/switch-inline-c-comments-to-block (beg end)
"Change whole-line inline C comments between BEG and END to block comments.
If the region contains any lines which are not whole-line inline C comments
then the behavior of this command is undefined."
(interactive "*r")
(narrow-to-region beg end)
(unwind-protect
(let ((whole-line-inline-comment "^[[:space:]]*//\\(.*\\)$"))
(goto-char (point-min))
(replace-regexp whole-line-inline-comment "/*\\1" nil (point)
(line-end-position))
(forward-line)
(replace-regexp whole-line-inline-comment " *\\1")
(when (eolp)
(open-line 1)
(forward-line))
(insert " */"))
(widen)))
```
To use it, first evaluate the defun, then mark the sequence of whole-line inline comments you want to change to a K&R-style comment and execute `M-x ph/switch-inline-c-comments-to-block RET` (or bind it to a key of your choice).
> 1 votes
---
Tags: comment, cc-mode
--- |
thread-63308 | https://emacs.stackexchange.com/questions/63308 | Clear console output on *R* buffers when using ESS | 2021-02-10T09:46:40.083 | # Question
Title: Clear console output on *R* buffers when using ESS
I have this kbd in my `init.el`
```
(global-set-key (kbd "C-l") 'comint-clear-buffer)
```
When I use Emacs-ess mode fro programming in R, I use this kbd to clear the R output buffer, this is usually called `*R*`. That works, but it requires that I go into the `*R*` buffer and do `C-l` from there.
Can this be modded so that wherever I am into some other buffer, the `comint-clear-buffer` command is applied specifically to the `*R*` buffer when I am into an ESS mode buffer?
# Answer
This switches to the R REPL buffer in its window, or in the the current one if no window is displaying it, and clears the screen.
```
(defun my-r-clear-buffer ()
(interactive)
(pop-to-buffer (ess-get-process-buffer) '((display-buffer-reuse-window
display-buffer-same-window)))
(comint-clear-buffer))
(define-key ess-r-mode-map (kbd "C-l") #'my-r-clear-buffer)
```
However, `C-l` is normally already bound to `recenter-top-bottom`, which is a pretty useful function. I suggest you to use
```
(define-key ess-r-mode-map (kbd "C-c l") #'my-r-clear-buffer)
```
instead.
---
`(ess-get-process-buffer)` retrieves the R REPL buffer associated with the current R source code buffer. IOW, the function above clears the buffer that `C-RET` sends lines to.
This version should be more stubborn about finding an R REPL buffer to clear.
```
(defun my-r-clear-buffer ()
(interactive)
(let ((r-repl-buffer (seq-find (lambda (buf)
(string-prefix-p "*R" (buffer-name buf)))
(buffer-list))))
(if r-repl-buffer
(pop-to-buffer r-repl-buffer '((display-buffer-reuse-window
display-buffer-same-window)))
(user-error "No R REPL buffers found"))
(comint-clear-buffer)))
```
It just switches to the first buffer in the buffer list whose name begins with "\*R" and clears that.
Note: the reason why I search for a buffer whose name begins with "\*R" instead of just aiming at the buffer named `*R*` is that in my Emacs (v. 27.1, ESS v. 18.10) R REPL buffers have paths in their names, like `*R:~*`.
---
> it doesn't move back to the original associated buffer.
You just have to ask.
```
(defun my-r-clear-buffer ()
(interactive)
(let ((r-repl-buffer (seq-find (lambda (buf)
(string-prefix-p "*R" (buffer-name buf)))
(buffer-list))))
(if r-repl-buffer
(with-current-buffer r-repl-buffer
(comint-clear-buffer))
(user-error "No R REPL buffers found"))))
(global-set-key (kbd "C-c l") #'my-r-clear-buffer)
```
> 1 votes
---
Tags: ess, r, comint
--- |
thread-63310 | https://emacs.stackexchange.com/questions/63310 | When is it better to use the backquote, `(…), and when to use (list …)? | 2021-02-10T11:10:48.260 | # Question
Title: When is it better to use the backquote, `(…), and when to use (list …)?
The docstring for `quote` says,
> Quoting should be reserved for constants that will never be modified by side-effects, unless you like self-modifying code.
Are there cases in which it is the best choice instead?
Are there any cases in which `list` should be avoided?
---
I've asked this question to complement When to use quote for lists? Modifying quoted lists in Elisp, which is mostly about the potential drawbacks of using `quote`. What I'd like to know is not only when it is ok to use it, but if there are cases in which it is the best choice over `list` or `cons`.
---
**PS** This question was originally about `quote` and `list`, then Dan made me realize I had conflated `quote` and `backquote` in my mind. The functions I was actually confused about were `backquote` and `list`. Sorry for the confusion.
# Answer
> Are there cases in which \[`backquote`\] is the best choice
Yes, when constructing complex list expressions that involve a lot of quoting, unquoting, and splicing. The best example of this is macro bodies. See the example in `(info "(elisp) Defining Macros")`:
```
(defmacro t-becomes-nil (variable)
`(if (eq ,variable t)
(setq ,variable nil)))
```
Without backquoting, this would be:
```
(defmacro t-becomes-nil (variable)
(list 'if (list 'eq variable t)
(list 'setq variable nil)))
```
which is far harder to grok. The problem becomes even more pronounced when splicing (`,@`) lists in the middle of other lists, as `list` and `cons` become insufficient, and `append` is needed as well.
> Are there any cases in which `list` should be avoided?
TL;DR: No. `list` and `cons` are the fundamental building blocks of Elisp, and are implicitly and explicitly used everywhere all the time.
The only reason to prefer `backquote` over `list` is for readability.
The only reason to avoid `list` altogether is when you know for certain that some code, e.g. in a tight loop, doesn't strictly need a freshly allocated cons, and you want to reduce the amount of garbage created for performance reasons. But this is rare and as always should be profiled and analysed carefully.
> 4 votes
# Answer
Quoted values are established at read-time, and so incur no eval-time cost to build. So there ought to be a slight efficiency benefit to using a quoted value in cases where it's safe to do that.
It it's a genuinely constant value, then quoting is the best choice.
> Are there any cases in which `list` should be avoided?
`quote` returns the same<sup>1</sup> value every time, while `list` and `cons` build a new value every time; so obviously don't use `list` or `cons` if you're writing code which needs to see the *same* value each time.
That aside, if you didn't *need* to create the list at eval-time, then it *could* potentially be confusing to the reader if you were doing so.
---
<sup>1</sup> For a lisp-based definition of "same".
> 1 votes
# Answer
`list` and `quote` do not function in the same way. `list` evaluates its arguments, and quote does not:
```
(list 1 2 (+ 1 2)) ; => (1 2 3)
(quote (1 2 (+ 1 2))) ; => (1 2 (+ 1 2))
```
> 0 votes
---
Tags: list
--- |
thread-45561 | https://emacs.stackexchange.com/questions/45561 | How to jump to R source code with ESS? | 2018-10-25T01:01:19.713 | # Question
Title: How to jump to R source code with ESS?
**Q:** how can I get to the source code of R packages using ESS?
When I'm working with elisp, I can access the source code for any package easily with `find-library` or by following the links in `find-function` or `find-variable`.
I'd like to be able to do the same thing with R via Emacs Speaks Statistics (`ess`). How can I get `ess` to send me to the source code of a given function/package?
# Answer
> 1 votes
I have had some decent success with `ess-r-xref`. `(require 'ess-r-xref)` and then `M-.` (`xref-find-definitions`) with point on some symbol. It should prompt you to save a TAGS file. Then `M-.` should do what you want.
Check out https://www.gnu.org/software/emacs/manual/html\_node/emacs/Xref.html
**Alternately:**
I'm a big proponent of the Language Server Protocol. There's an R language server that should work with `lsp-mode`, but does not yet support find definition/reference requests AFAIK. I would recommend monitoring that project.
# Answer
> 0 votes
This is probably old, but I found out how to do it just looking at this question.
I installed ESS under Emacs 26.3 and I didn't do anything particular with this. It seems `ess-r-xref` works without doing any specific setting.
If do `M-.` or `M-x xref-find-definitions` and I am asked what I'm looking for ( auto-completion works nicely), than it opens a new buffer with the file containing the object I am looking for.
---
Tags: ess, r
--- |
thread-63179 | https://emacs.stackexchange.com/questions/63179 | embark-collect-* showing wrong number of arguements from Selectrum | 2021-02-04T20:46:49.730 | # Question
Title: embark-collect-* showing wrong number of arguements from Selectrum
I've been trying to get Selectrum, Embark and other packages working together as a completion framework, but am running into a problem with `embark-collect-snapshot` (and `embark-collect-live`).
In the minibuffer, using selectrum, when I run the command `embark-collect-snapshot` I get the error
```
Wrong number of arguments: (2 . 2), 10
```
I've tinkered a bit but don't really know how to solve, or diagnose, the problem.
To recreate the issue you can follow the following steps:
1. Create new .emacs.d directory with the following `init.el` file:
```
(require 'package)
(add-to-list 'package-archives
'("melpa" . "https://melpa.org/packages/"))
(when (< emacs-major-version 27)
(package-initialize))
;; Bootstrap 'use-package'
(unless (package-installed-p 'use-package)
(package-refresh-contents)
(package-install 'use-package))
(eval-when-compile
(require 'use-package))
(use-package selectrum
:ensure t
:demand t
:config
(selectrum-mode t))
(use-package embark
:ensure t
:demand t
:bind (("C-," . embark-act)
:map selectrum-minibuffer-map
("C-," . embark-act)
("C->" . embark-become)))
```
2. Open emacs
3. Evoke a function that opens up a Selectrum completion list (for example `C-x b`)
4. Run `embark-act` with `C-,`
5. Choose `embark-collect-snapshot` with `S`
Other info:
```
GNU Emacs 26.3 (build 2, x86_64-pc-linux-gnu, GTK+ Version 3.24.14) of 2020-03-06, modified by Debian
Distributor ID: Ubuntu
Description: Ubuntu 20.10
Release: 20.10
Codename: groovy
```
# Answer
Turns out this was a bug in the embark package, which has now been fixed by the maintainer.
> 0 votes
---
Tags: minibuffer
--- |
thread-63319 | https://emacs.stackexchange.com/questions/63319 | Emacs script to indent files from the command line | 2021-02-10T15:55:45.387 | # Question
Title: Emacs script to indent files from the command line
I am trying to create an Emacs script that indents HTML files from the command line. This is what I have so far:
```
#!/usr/bin/env -S emacs --script
(require 'web-mode)
(indent-region (point-min) (point-max) nil)
(save-buffer)
```
I saved this file as `indent` and made it executable with `chmod 755 indent`. Then, I tried running it on an HTML file:
```
$ ./indent base.html
Loading /etc/emacs/site-start.d/00debian.el (source)...
Loading /etc/emacs/site-start.d/50autoconf.el (source)...
Loading /etc/emacs/site-start.d/50cmake-data.el (source)...
Loading /etc/emacs/site-start.d/50dictionaries-common.el (source)...
Loading debian-ispell...
Loading /var/cache/dictionaries-common/emacsen-ispell-default.el (source)...
Loading /var/cache/dictionaries-common/emacsen-ispell-dicts.el (source)...
Loading /etc/emacs/site-start.d/50figlet.el (source)...
Loading /etc/emacs/site-start.d/50gettext.el (source)...
Package gettext-el removed but not purged. Skipping setup.
Loading /etc/emacs/site-start.d/50latexmk.el (source)...
Loading /etc/emacs/site-start.d/50pylint.el (source)...
Indenting region...
Indenting region...done
```
It seemed to work, but there is no output. The content of file `base.html` remains unchanged. I'd really like to get this working, because I want to use this command as a git hook to format HTML files using `web-mode.el`.
Could anyone help?
# Answer
> 6 votes
@glucas's answer is correct in its diagnosis, but has a minor problem (you want the 0th element of `argv`) and is incomplete. Here is a more complete example:
```
#!/usr/bin/env -S emacs --script
(find-file (nth 0 argv))
(mhtml-mode)
(indent-region (point-min) (point-max) nil)
(save-buffer)
```
This does not use `web-mode` which is not available to me (does it exist?); instead I use `mhtml-mode` which is what my emacs uses when editing HTML files.
One safety point: instead of modifying a file in place, I would rather save it to a different file name, so if something goes wrong, I still have the original file and I can retry after fixing any problems (although you can use a backup, either one you made, or one made for you by emacs). So you might want to go with something like this:
```
#!/usr/bin/env -S emacs --script
(setq fname (nth 0 argv))
(find-file fname)
(mhtml-mode)
(indent-region (point-min) (point-max) nil)
(write-file (concat fname ".indent") t)
```
When invoked like this:
```
./indent foo.html
```
the script will save the result in a new file `foo.html.indent` (if `foo.html.indent` exists already, the `t` argument of `write-file` will cause the script to ask you whether to overwrite it: if you say `y` it will overwrite it; if you say `n` it will not, but you'll get a backtrace, since the script does not handle error conditions gracefully).
# Answer
> 3 votes
I believe your example is not loading the file specified on the command line. It looks like with --script you need to get the file name from the command-line arguments passed to emacs and open that file before you try to process it. Something like:
```
(find-file (nth 1 argv))
(web-mode)
;; etc
```
---
Tags: indentation, html, script
--- |
thread-63324 | https://emacs.stackexchange.com/questions/63324 | org-mode delete all checked items | 2021-02-11T01:44:50.540 | # Question
Title: org-mode delete all checked items
I use org-mode for my shopping lists and I would like to be able to remove all checked items in one action.
i.e.
* \[X\] cotton buds
* \[ \] cordial
* \[X\] milk
* \[X\] sugar
In the list above remove all the lines except `+ [ ] cordial`
Is this currently available or has anyone written a function to perform this?
# Answer
> 1 votes
I'm not sure I'm more daring than @lawlist, but I'm almost certainly foolish for even encouraging you in this: after all, the X's are exactly there to mark those list items as done; so why delete them?
That said, here's some code that *seems* to work in the above situation (the only situation tested). The code does use `kill-region`, so you should be able to undo your way back from disaster. Event though `org-at-item-checkbox-p` still exists in the code, I did not use it, although a different solution could almost certainly be built around it, but I'm not sure it would be any simpler.
```
#+begin_src emacs-lisp :results drawer
(defun delx (items)
(while (not (null items))
(let ((item (car items)))
(if (equal (nth 4 item) "[X]")
(kill-region (nth 0 item) (car (last item)))))
(setq items (cdr items))))
(defun ndk/clean-up-shopping-list ()
(interactive)
(save-excursion
(let* ((elt (org-element-at-point))
(type (org-element-type elt)))
(when (eq type 'plain-list)
(let ((items (plist-get (cadr elt) :structure)))
(delx (reverse items)))))))
#+end_src
```
To invoke it, you put your cursor at the beginning of the list and say `M-x ndk/clean-up-shopping-list`.
Some explanations:
* the `ndk/clean-up-shopping-list` function uses the `org-element` parser to figure out whether it's at the beginning of a plain list. If so, it retrieves the list of items in the list, and calls the auxiliary function `delx` with the *reverse* of the item list (see below for the reason).
* `delx` loops over the list of items and for each item, if the item is checked, it kills the region from the beginning to the end of the item.
* the reason that we reverse the list before passing to `delx` is that the list of items looks like this: `((126 0 "- " nil "[X]" nil 144) (144 0 "- " nil "[ ]" nil 158) (158 0 "- " nil "[X]" nil 169) (169 0 "- " nil "[ ]" nil 186) (186 0 "- " nil "[X]" nil 198))`, a list of items in increasing order of position; each item is a list of the form `(beg _ _ _ "[x]" _ end)` where `beg` is the character position of the beginning of the item, `end` is the character position at the end of the item, `_` indicates "don't care" stuff and `"[x]"` can be either a checked box or an empty box. `delx` figures out whether each item is checked or unchecked and if it is checked, it calls `kill-region` with `beg` and `end` as arguments. But it has to process the list of items in reverse order, because if it starts deleting things from the top, the character positions of the later items *will change*, so we would not be able to use the `beg/end` numbers. Doing the deletions from the end does not have that problem: the character positions of the earlier items do not change, so the `beg/end` info from the item list remains valid.
BTW, note that the end position of each item is the same as the beginning position of the next item. So another way to do it is to delete from the beginning but then recalculate the `beg/end` positions of subsequent items. That's not too difficult but I think it's messier, so I opted for deleting from the bottom.
---
Tags: org-mode
--- |
thread-63296 | https://emacs.stackexchange.com/questions/63296 | Sort lines omitting a prefix of a certain length? | 2021-02-09T19:45:24.047 | # Question
Title: Sort lines omitting a prefix of a certain length?
Many of my python files have an import section that looks like this:
```
from datetime import datetime, timedelta
from typing import Callable
import numpy as np
import pandas as pd
```
I'd like to sort those lines by the library names. I'd like to run `sort-lines` but somehow tell it to overlook the first seven characters when assigning the order to a line, but to of course include those seven characters when it actually moves the line. That is, I'd like to end up with this:
```
from datetime import datetime, timedelta
import numpy as np
import pandas as pd
from typing import Callable
```
# Answer
> 3 votes
`C-h f sort-columns`:
> **`sort-columns`** is an interactive autoloaded compiled Lisp function in `sort.el`.
>
> It is bound to `menu-bar edit sort sort-columns`.
>
> `(sort-columns REVERSE &optional BEG END)`
>
> Sort lines in region alphabetically by a certain range of columns.
>
> For the purpose of this command, the region `BEG`...`END` includes the entire line that point is in and the entire line the mark is in. The column positions of point and mark bound the range of columns to sort on. A prefix argument means sort into `REVERSE` order. The variable `sort-fold-case` determines whether alphabetic case affects the sort order.
>
> Note that `sort-columns` rejects text that contains tabs, because tabs could be split across the specified columns and it doesn't know how to handle that. Also, when possible, it uses the `sort` utility program, which doesn't understand tabs. Use M-x untabify to convert tabs to spaces before sorting.
See also the Elisp manual, node Sorting:
> Command: `sort-columns reverse &optional beg end`
>
> This command sorts the lines in the region between `beg` and `end`, comparing them alphabetically by a certain range of columns. The column positions of `beg` and `end` bound the range of columns to sort on.
>
> If `reverse` is non-`nil`, the sort is in reverse order.
>
> One unusual thing about this command is that the entire line containing position beg, and the entire line containing position end, are included in the region sorted.
>
> Note that `sort-columns` rejects text that contains tabs, because tabs could be split across the specified columns. Use `M-x untabify` to convert tabs to spaces before sorting.
>
> When possible, this command actually works by calling the `sort` utility program.
# Answer
> 1 votes
If you are working on linux or Unix, you should have a sort command at the command line. Emacs has `shell-command-on-region` (on my machine, bound to `M-|`). Mark the region to sort, press `M-|`, and type `sort -k 2`. The sorted results appear in a buffer named `*Shell Command Output*`.
The -k option to sort tells what key (or field) to sort by.
---
Tags: sorting, column
--- |
thread-48625 | https://emacs.stackexchange.com/questions/48625 | Why ido mode automatically change current folder when create new file? | 2019-03-28T08:26:01.813 | # Question
Title: Why ido mode automatically change current folder when create new file?
I want to create file `credenentials.txt` in folder `d:/dev/GoogleDrive/_IPTV/Playlists/OttClub/`
```
M-x C-x C-f
```
Press "**c**" result:
press "**cr**" result:
As you can see Emacs change folder to `d:/personal`
I don't need this. I only want to create file in folder `d:/dev/GoogleDrive/_IPTV/Playlists/OttClub/`
How I can do this?
P.S. I also try by `-Q` mode and enable only `ido-mode` I get same result: Press "**cr**"
As you can see Emacs **automatically change** folder.
# Answer
You should either set `ido-auto-merge-work-directories-length` to a negative value, or increase the number of seconds in `ido-auto-merge-delay-time`.
> 6 votes
# Answer
It's also possible to pause Ido completion by typing `C-f` at the Ido prompt as soon as you have the correct directory, and then type the new file name:
`C-x C-f` navigate to directory `C-f` type new file name `RET`
You can also list the key bindings available during the Ido file prompt by typing the following (either during and Ido prompt or outside):
`C-h f` ido-find-file `RET`
> 2 votes
---
Tags: ido
--- |
thread-41099 | https://emacs.stackexchange.com/questions/41099 | Reorganize timestamps into drawers | 2018-04-19T06:59:36.347 | # Question
Title: Reorganize timestamps into drawers
I just learned about the following org-mode option, which ensures **newly entered** timestamps end up in the LOGBOOK drawer:
```
(setq org-log-into-drawer t)
```
How can I automatically move **existing** timestamps (which so far have been logged outside of the drawer) so that they all end up inside the drawer?
As an example, how to quickly go from:
```
** TODO Important task
SCHEDULED: <2018-04-23 Mon .+7d>
- State "DONE" from "TODO" [2018-04-09 Mon 14:05]
CLOCK: [2018-04-09 Mon 14:02]--[2018-04-09 Mon 14:05] => 0:03
- State "DONE" from "TODO" [2018-03-26 Mon 09:21]
- State "DONE" from "TODO" [2018-03-19 Mon 13:15]
CLOCK: [2018-03-19 Mon 13:09]--[2018-03-19 Mon 13:15] => 0:06
- State "DONE" from "TODO" [2018-03-01 Thu 12:39]
CLOCK: [2018-02-26 Mon 08:43]--[2018-02-26 Mon 08:56] => 0:13
- State "DONE" from "TODO" [2018-01-18 Thu 08:20]
- State "DONE" from "TODO" [2017-11-13 mån 14:07]
CLOCK: [2017-11-13 mån 14:06]--[2017-11-13 mån 14:07] => 0:01
- State "DONE" from "TODO" [2017-10-23 mån 17:55]
CLOCK: [2017-10-23 mån 10:08]--[2017-10-23 mån 10:11] => 0:03
- State "DONE" from "TODO" [2017-10-02 mån 10:46]
CLOCK: [2017-10-02 mån 10:44]--[2017-10-02 mån 10:46] => 0:02
```
To something like:
```
** TODO Important task
SCHEDULED: <2018-04-23 Mon .+7d>
:LOGBOOK:
CLOCK: [2018-04-09 Mon 14:02]--[2018-04-09 Mon 14:05] => 0:03
CLOCK: [2018-03-19 Mon 13:09]--[2018-03-19 Mon 13:15] => 0:06
CLOCK: [2018-02-26 Mon 08:43]--[2018-02-26 Mon 08:56] => 0:13
CLOCK: [2017-11-13 mån 14:06]--[2017-11-13 mån 14:07] => 0:01
CLOCK: [2017-10-23 mån 10:08]--[2017-10-23 mån 10:11] => 0:03
CLOCK: [2017-10-02 mån 10:44]--[2017-10-02 mån 10:46] => 0:02
:END:
- State "DONE" from "TODO" [2017-10-23 mån 17:55]
- State "DONE" from "TODO" [2017-10-02 mån 10:46]
[...]
```
# Answer
## Native solution
From the documentation of `org-clock-into-drawer` (see it with `C-h f org-clock-into-drawer`):
```
Non-nil when clocking info should be wrapped into a drawer.
When non-nil, clocking info will be inserted into the same drawer
as log notes (see variable ‘org-log-into-drawer’), if it exists,
or "LOGBOOK" otherwise. If necessary, the drawer will be
created.
When an integer, the drawer is created only when the number of
clocking entries in an item reaches or exceeds this value.
When a string, it becomes the name of the drawer, ignoring the
log notes drawer altogether.
```
Therefore, after running `(setq org-clock-into-drawer t)` and clocking in on a headline, any lines under that headline that are a clock segment such as:
```
CLOCK: [2018-04-09 Mon 14:02]--[2018-04-09 Mon 14:05] => 0:03
```
are first moved into a drawer, creating one if necessary and in reverse order that they appear, and the new clock time is added at the top.
## Solution in Python
I disliked the reverse order and am too unfamiliar with Emacs LISP to adapt the source code from function `org-clock-find-position` (lines 1508 onwards of `org-clock.el.gz` in my version). So I used Python 3.
The code below runs the doc-tests first and only if they all pass does it process the file. It also moves into the drawer any lines that are state changes:
```
- State "DONE" from "TODO" [2019-07-23 Tue 23:11]
```
It keeps the order of appearance of lines that are clock segments or state changes. It creates a backup of the file before running it. I inspected the result manually and could not find any errors.
Save as `<name-of-script>`, then call with `python3 <name-of-script> -f <path-to-org-file>`.
```
import argparse
import doctest
import os
import re
import shutil
DEFAULT_FILE = os.path.expanduser("~/org/gtd.org")
LOGBOOK_START = ":LOGBOOK:"
LOGBOOK_END = ":END:"
META_DATA_RE = "^( |\\t)*:?(CLOSED|DEADLINE|SCHEDULED|END|#+END):"
HEADLINE_RE = "[*]+ "
def find_end_of_metadata(lines):
"""Finds the last index of metadata in the array
>>> lines = ['** TODO task', \
'SCHEDULED: <2019-09-24 Tue 08:04 ++1d>', \
':PROPERTIES:', \
':LAST_REPEAT: [2019-09-23 Mon 11:42]', \
':END:', \
':LOGBOOK:', \
'...', \
':END:', \
'some comment']
>>> find_end_of_metadata(lines) == len(lines) - 2
True
"""
if list != type(lines):
raise ValueError("This function requires a list as input")
num_lines = len(lines)
for i in range(num_lines - 1, -1, -1):
line = lines[i]
if re.match(META_DATA_RE, line) or re.match(HEADLINE_RE, line):
return i
assert False, "Unable to find end of metadata!" + "\n".join(lines)
def process_headline(headline, logbook_start = LOGBOOK_START, logbook_end = LOGBOOK_END):
"""Processes the headline, creating a logbook drawer if needed, and
moving state changes and clocks into the logbook drawer.
>>> no_drawer_headline = '\\n'.join(['** TODO task', \
'SCHEDULED: <2019-09-19 Thu 21:00 ++1d>', \
':PROPERTIES:', \
':LAST_REPEAT: [2019-09-18 Wed 21:24]', \
':END:', \
'- State "DONE" from "TODO" [2019-09-18 Wed 21:24]', \
'- State "DONE" from "TODO" [2019-09-17 Tue 12:52]', \
'CLOCK: [2019-09-24 Tue 09:01]--[2019-09-24 Tue 09:41] => 0:40', \
'CLOCK: [2019-04-22 Mon 14:31]--[2019-04-22 Mon 15:23] => 0:52'])
>>> no_drawer_actual = process_headline(no_drawer_headline)
>>> no_drawer_expected = '\\n'.join(['** TODO task', \
'SCHEDULED: <2019-09-19 Thu 21:00 ++1d>', \
':PROPERTIES:', \
':LAST_REPEAT: [2019-09-18 Wed 21:24]', \
':END:', \
':LOGBOOK:', \
'- State "DONE" from "TODO" [2019-09-18 Wed 21:24]', \
'- State "DONE" from "TODO" [2019-09-17 Tue 12:52]', \
'CLOCK: [2019-09-24 Tue 09:01]--[2019-09-24 Tue 09:41] => 0:40', \
'CLOCK: [2019-04-22 Mon 14:31]--[2019-04-22 Mon 15:23] => 0:52', \
':END:'])
>>> drawer_headline = '\\n'.join(['** TODO task', \
'SCHEDULED: <2019-09-19 Thu 21:00 ++1d>', \
':PROPERTIES:', \
':LAST_REPEAT: [2019-09-18 Wed 21:24]', \
':END:', \
':LOGBOOK:', \
'- State "DONE" from "TODO" [2019-09-18 Wed 21:24]', \
'CLOCK: [2019-09-24 Tue 09:01]--[2019-09-24 Tue 09:41] => 0:40', \
':END:', \
'- State "DONE" from "TODO" [2019-09-17 Tue 12:52]', \
'CLOCK: [2019-04-22 Mon 14:31]--[2019-04-22 Mon 15:23] => 0:52'])
>>> drawer_actual = process_headline(drawer_headline)
>>> drawer_expected = '\\n'.join(['** TODO task', \
'SCHEDULED: <2019-09-19 Thu 21:00 ++1d>', \
':PROPERTIES:', \
':LAST_REPEAT: [2019-09-18 Wed 21:24]', \
':END:', \
':LOGBOOK:', \
'- State "DONE" from "TODO" [2019-09-18 Wed 21:24]', \
'CLOCK: [2019-09-24 Tue 09:01]--[2019-09-24 Tue 09:41] => 0:40', \
'- State "DONE" from "TODO" [2019-09-17 Tue 12:52]', \
'CLOCK: [2019-04-22 Mon 14:31]--[2019-04-22 Mon 15:23] => 0:52', \
':END:'])
>>> no_drawer_actual == no_drawer_expected
True
>>> drawer_actual == drawer_expected
True
"""
# Split by lines
lines = re.split("\n|\r", headline)
# Find the indices of all the lines that are a state change
# and copy them over
indices = []
logbook_lines = []
for iLine, line in enumerate(lines):
if line.startswith('- State') or line.startswith('CLOCK: '):
indices.append(iLine)
logbook_lines.append(line)
if 0 == len(logbook_lines):
return headline
# Delete lines from original
for iLine in reversed(indices):
lines.pop(iLine)
# Initialize new array to hold result
processed_lines = []
# Find index of logbook drawer, if any
if logbook_start in lines:
logbook_start_index = lines.index(logbook_start)
logbook_end_index = lines.index(logbook_end, logbook_start_index)
else:
logbook_start_index = find_end_of_metadata(lines) + 1
lines = lines[:logbook_start_index] + [logbook_start, logbook_end] + lines[logbook_start_index:]
logbook_end_index = logbook_start_index + 1
# Add clock lines in the logbook drawer
return "\n".join(lines[:(logbook_start_index + 1)] + logbook_lines + lines[logbook_end_index:])
def split_headlines(s):
"""Splits the contents of an Org file by headline and keeps the delimiter that marks it.
>>> contents = "\\n".join(['* Level 1', \
'** TODO Level 2', \
'comments', \
'** Level 2'])
>>> actual = split_headlines(contents)
>>> expected = ['* Level 1', \
'\\n'.join(['** TODO Level 2', 'comments']),
'** Level 2']
>>> actual == expected
True
"""
regex = re.compile("(\\n|\\r)" + HEADLINE_RE)
matches = []
prev_end = 0
for match in regex.finditer(s):
match_start = match.start()
matches.append(s[prev_end:match.start()])
prev_end = match_start
if s[prev_end] in ['\n', '\r']:
prev_end += 1
if prev_end < len(s):
matches.append(s[prev_end:])
return matches
def process_file(filepath):
"""For the org file in the argument, moves the state changes and clock segments into drawers.
"""
# Make a backup, just in case
backup = filepath + "_backup"
assert not os.path.exists(backup), "Backup file already exists!"
shutil.copy(filepath, backup)
assert os.path.exists(backup)
with open(filepath, "r") as f:
contents = f.read(-1)
with open(backup, "r") as f:
backup_contents = f.read(-1)
assert contents == backup_contents
# Split by headlines
headlines = split_headlines(contents)
# Process each
new_headlines = []
count = 0
for h in headlines:
new_h = process_headline(h)
new_headlines.append(new_h)
# Write to file
with open(filepath, "w") as f:
f.write("\n".join(new_headlines))
def get_args():
parser = argparse.ArgumentParser(description = "Process text in an Org file")
parser.add_argument("-f", "--file", default=DEFAULT_FILE)
return parser.parse_args()
def main():
args = get_args()
filepath = args.file
process_file(filepath)
if "__main__" == __name__:
doctests = doctest.testmod()
assert 0 == doctests.failed, "Some doc-tests failed, will not run the script"
main()
```
Cross-posted from this other thread that deals with lines with state changes.
> 2 votes
# Answer
You may want to check my answer here
Summary:
```
(setq org-log-done t)
```
puts both clocking and state changes in the :LOGBOOK: drawer. Nice and tidy.
> 0 votes
---
Tags: org-mode
--- |
thread-63337 | https://emacs.stackexchange.com/questions/63337 | The list-buffers command. How to make the 'Buffer' column sort case-insensitively, when click on it? | 2021-02-11T21:12:27.587 | # Question
Title: The list-buffers command. How to make the 'Buffer' column sort case-insensitively, when click on it?
`C-x C-b` is normally bound to the `list-buffers` command. The resulting buffer has various columns, which are CRM, Buffer, Size, Mode, and File.
When I can click on the `Buffer` column-header, it will toggle sorting the contents of the window, switching between ascending and descending sorting according to the buffer name. Which is fine. However, the sorting according to the buffer name is case-sensitive.
What I would prefer is for the contents of the window to sort with the buffer name being considered *case-insensitively*. As it is now, for ascending order, names that begin with (A-Z) are shown first, then names (a-z) are shown after them. I would prefer if the *case of the letters was ignored*, when sorting by buffer name.
# Answer
> 1 votes
`list-buffers` uses tabulated list sorting, which I've not delved into. `ibuffer` OTOH has a specific command for sorting by name, and you could redefine it to be case-insensitive like so:
```
(with-eval-after-load 'ibuf-ext
;; Create a case-insensitive ibuffer sort command. Derived from
;; `ibuffer-do-sort-by-alphabetic' which is defined in ibuf-ext.el
;; by (define-ibuffer-sorter alphabetic ...).
(define-ibuffer-sorter alphabetic-ignore-case
"Sort the buffers by their names, ignoring case."
(:description "buffer name")
(string-collate-lessp
(buffer-name (car a))
(buffer-name (car b))
nil t))
;; Assign the new command to the 'Name' header keymap.
(define-key ibuffer-name-header-map [(mouse-1)]
'ibuffer-do-sort-by-alphabetic-ignore-case)
(put 'ibuffer-make-column-name 'header-mouse-map
ibuffer-name-header-map))
```
`ibuffer` is a super-charged replacement for `list-buffers` so I recommend binding `C-x C-b` to this (and then doing some reading about its excellent features -- use `?` in the buffer or `C-h f ibuffer-mode` to read its primary help).
---
Tags: sorting, buffer-list
--- |
thread-63336 | https://emacs.stackexchange.com/questions/63336 | Deleting a file with name that already exists in Trash | 2021-02-11T20:38:58.577 | # Question
Title: Deleting a file with name that already exists in Trash
I use `delete-by-moving-to-trash` to move deleted files and folders into trash instead of deleting them. However, if the file or folder with the same name is already in Trash I get an error `file already exists"`.
On macOS and while I delete file using Finder which name already exists in the Trash it adds current timestamp to the deleted file name to differentiate it. For example `foo` become `foo 20.28.19`.
Is there a way achieve the same in Emacs?
That would solve the problem, but I'm also open for other solutions if they exists.
# Answer
You can use the Finder to move the files with the following function
```
(defun system-move-file-to-trash (filename)
"Move file or directory named FILENAME to the trash."
(ns-do-applescript
(format
"tell application \"Finder\" to delete POSIX file \"%s\""
filename)))
```
Not tested on recent Mac OS versions.
> 4 votes
---
Tags: files
--- |
thread-63349 | https://emacs.stackexchange.com/questions/63349 | How to make sure no global variables have been created in a piece of lisp code? | 2021-02-12T15:38:42.617 | # Question
Title: How to make sure no global variables have been created in a piece of lisp code?
I am writing some lisp code and I would like it not to mess with the global variables in the system. I am therefore being very careful to only use variables within the scope of the `let` special form.
However, as the code gets longer, it becomes harder to make sure this principle is being fully respected, especially since there is the risk of a mispelled variable suddently becoming global in case the incorrect spelling turns the name of a variable into one not bound in any `let` form.
Ideally it would be great to be able to simply prohibit new global variables to be `setq`, say with a lisp command `inhibit-setting-global-variables-not-already-defined`. My question is thus:
**Question**. Is it possible to automatically verify that a piece of lisp code does not create any new global variables?
# Answer
> Is it possible to automatically verify that a piece of lisp code does not create any new global variables?
Turn on `lexical-binding`:
```
;;; foo.el --- just frobnicating some foo -*- lexical-binding: t -*-
(setq foo-bar nil)
(defun foo-bar ()
(let (x)
(setq y nil)))
;;; foo.el ends here
```
and then the byte-compiler will do the work for you:
```
emacs -Q -batch -f batch-byte-compile foo.el
In toplevel form:
foo.el:3:7: Warning: assignment to free variable ‘foo-bar’
foo.el:5:1: Warning: Unused lexical variable ‘x’
In foo-bar:
foo.el:7:11: Warning: assignment to free variable ‘y’
```
If you want to be particularly strict, you can turn warnings into errors:
```
emacs -Q -batch -eval '(setq byte-compile-error-on-warn t)' -f batch-byte-compile foo.el
In toplevel form:
foo.el:3:7: Error: assignment to free variable ‘foo-bar’
```
To see these warnings interactively, turn on `flymake-mode`.
To reduce the chance of typos to begin with, you can use symbol completion (`C-M-i` \- `completion-at-point`), dynamic abbreviations (`M-/` \- `dabbrev-expand`), or similar.
> 10 votes
---
Tags: local-variables, let-binding, lexical-binding
--- |
thread-63317 | https://emacs.stackexchange.com/questions/63317 | How to color specific keywords in python-mode? | 2021-02-10T13:16:00.477 | # Question
Title: How to color specific keywords in python-mode?
My goal is to color specific keywords as function definition such as `log` in `Python-mode` to a spefic color or color of functions.
Example, pattern for `log("....")`: coloring only `log`.
```
from utils import log # no color for log
logging.info("hello") # no color for log
log("hello world") # color for log
```
I have tried follows answer for shell-mode `alias` keyword is not recognized as font-lock-builtin-face type but it colors all the `log` string.
---
```
(font-lock-add-keywords 'python-mode
'(("log" . font-lock-builtin-face)))
```
# Answer
I think you want something like this where you only apply the face to part of the match, in this case we mark log as group 1, and only apply the face to it. This pattern won't match the other places you show log above.
```
(font-lock-add-keywords 'python-mode
'(("\\(log\\)(.*)" 1 font-lock-builtin-face)))
```
> 1 votes
---
Tags: python, fonts
--- |
thread-2445 | https://emacs.stackexchange.com/questions/2445 | Dired: only reuse buffer for directories | 2014-10-22T16:03:46.130 | # Question
Title: Dired: only reuse buffer for directories
To prevent creation of a buffer every single time I enter a directory in dired I use this:
`(put 'dired-find-alternate-file 'disabled nil)`
My problem now is that when I visit a file from dired pressing `RET` and then kill it, dired buffer is killed too.
Would it be possible to reuse dired buffer only for directories?
# Answer
Load library **Dired+** (dired+.el). Then use `C-M-R` (aka `C-M-S-r`) to toggle whether Dired should reuse dired buffers.
If you want to turn this reuse on by default, do this in your init file:
```
(diredp-toggle-find-file-reuse-dir 1)
```
> 6 votes
# Answer
If you get used to the fact that `a` replaces the current (dired) buffer with the selected file/directory, then you're not limited by a default approach; you just use the option you want at the time.
> 6 votes
# Answer
The solution (accepted answer) by Drew of using Dired+ didn't work for me (it was messing with my dired buffers so that only folders/file names appeared, but not all the other info normally in dired buffer. It could be to do with one of my customisations).
I then found another that worked way using dired-simple.el . After downloading the linked file and placing it in your load path, include this in your init file
```
(require 'dired-single)
(defun my-dired-init ()
"Bunch of stuff to run for dired, either immediately or when it's
loaded."
;; <add other stuff here>
(define-key dired-mode-map [return] 'dired-single-buffer)
(define-key dired-mode-map [mouse-1] 'dired-single-buffer-mouse)
(define-key dired-mode-map "^"
(function
(lambda nil (interactive) (dired-single-buffer "..")))))
;; if dired's already loaded, then the keymap will be bound
(if (boundp 'dired-mode-map)
;; we're good to go; just add our bindings
(my-dired-init)
;; it's not loaded yet, so add our bindings to the load-hook
(add-hook 'dired-load-hook 'my-dired-init))
```
> 0 votes
# Answer
I found dired+ solution doesn't work for me, because I use to have multiple windows displaying the same buffer, and when I go folder up or down on any of them the buffer is closed for all the windows. This is why I implemented my own solution.
When changing the buffer for parent or sub buffer, if the buffer is displayed in other windows than don't delete it, otherwise delete it. In other words, when you go from one folder to another it will keep deleting previous buffer that is not used by any window, period.
```
(defun farynaio/dired-go-up-reuse (&optional dir)
(interactive)
(let ((new-dir (if dir (expand-file-name dir) (dired-get-file-for-visit)))
(buffer
(seq-find
(lambda (w) (and (not (eq w (selected-window))) (eq (current-buffer) (window-buffer w))))
(window-list-1))))
(if buffer
(find-file new-dir)
(find-alternate-file new-dir))))
```
I bind it in the following way:
```
(define-key dired-mode-map (kbd "<backspace>") (lambda () (interactive) (farynaio/dired-go-up-reuse "..")))
```
> 0 votes
---
Tags: dired, customize
--- |
thread-22600 | https://emacs.stackexchange.com/questions/22600 | `M-f` doesn't move to next line in evil-mode | 2016-05-28T06:30:27.057 | # Question
Title: `M-f` doesn't move to next line in evil-mode
This happens on the Emacs splash page primarily. I can move back to the end of the previous line with `M-b` but cannot move onto the beginning of the next with `M-f`.
As an experiment, I'm going through and replacing some vim emulation commands in evil-mode with their vanilla emacs equivalents.
```
(setq package-archives
'(("melpa" . "http://melpa.milkbox.net/packages/")
("gnu" . "http://elpa.gnu.org/packages/")))
(require 'package)
(package-initialize)
(require 'evil)
(evil-mode +1)
;; experiment with rebinding the normal state keys.
(define-key evil-normal-state-map (kbd "w") #'forward-word)
(define-key evil-normal-state-map (kbd "b") #'backward-word)
(define-key evil-normal-state-map (kbd "W") #'forward-sexp)
(define-key evil-normal-state-map (kbd "B") #'backward-sexp)
```
I noticed that `M-f` and `M-b` (and `w` and `b`) no longer move onto the next line and I'm wondering why that is. The help text for `M-f` seems to suggest that the value of `inhibit-field-text-motion` may play a role, but it's `nil` regardless of whether `evil-mode` is enabled.
```
M-f runs the command forward-word, which is an interactive built-in
function in `syntax.c'.
It is bound to w, M-f, ESC <right>.
(forward-word &optional ARG)
Move point forward ARG words (backward if ARG is negative).
If ARG is omitted or nil, move point forward one word.
Normally returns t.
If an edge of the buffer or a field boundary is reached, point is left there
and the function returns nil. Field boundaries are not noticed if
`inhibit-field-text-motion' is non-nil.
```
Still confused, I checked the source code to see how `forward-word` is actually implemented and to see what variable or bit of emacs state might be changing to influence the behavior of `forward-word`. The source code is here https://github.com/emacs-mirror/emacs/blob/c8874e2113221a08252113b6d46ecc7066c62c8c/src/syntax.c (reproduced below for convenience).
```
DEFUN ("forward-word", Fforward_word, Sforward_word, 0, 1, "^p",
doc: /* Move point forward ARG words (backward if ARG is negative).
If ARG is omitted or nil, move point forward one word.
Normally returns t.
If an edge of the buffer or a field boundary is reached, point is
left there and the function returns nil. Field boundaries are not
noticed if `inhibit-field-text-motion' is non-nil.
The word boundaries are normally determined by the buffer's syntax
table, but `find-word-boundary-function-table', such as set up
by `subword-mode', can change that. If a Lisp program needs to
move by words determined strictly by the syntax table, it should
use `forward-word-strictly' instead. */)
(Lisp_Object arg)
{
Lisp_Object tmp;
ptrdiff_t orig_val, val;
if (NILP (arg))
XSETFASTINT (arg, 1);
else
CHECK_NUMBER (arg);
val = orig_val = scan_words (PT, XINT (arg));
if (! orig_val)
val = XINT (arg) > 0 ? ZV : BEGV;
/* Avoid jumping out of an input field. */
tmp = Fconstrain_to_field (make_number (val), make_number (PT),
Qnil, Qnil, Qnil);
val = XFASTINT (tmp);
SET_PT (val);
return val == orig_val ? Qt : Qnil;
}
```
So it looks like the logic that could be making the behavior of `foward-word` differ in evil normal state and vanilla emacs must be contained within `scan-words` (https://github.com/emacs-mirror/emacs/blob/c8874e2113221a08252113b6d46ecc7066c62c8c/src/syntax.c#L1417). This function is really long so I won't paste it here.
I'm wondering how exactly evil-mode is changing the behavior of `forward-word` and how to prevent it from doing that? It seems unlikely that messing with the syntax tables would enable or disable line-wrapping for `forward-word`, but I'm really not sure.
# Answer
Evil prevents the cursor from moving to the last position in a line when in normal mode, which causes the cursor to be placed inside of the last word on the line instead of after it. This makes `forward-word` think it needs to move to the end of the line, but because it can't, it doesn't move at all.
To fix this, set `evil-move-beyond-eol` to `t`, which will allow the cursor to move to the final position on the line.
> 1 votes
---
Tags: evil
--- |
thread-63305 | https://emacs.stackexchange.com/questions/63305 | What are these underlines shown for whitespace at the end of some lines? | 2021-02-10T05:31:47.703 | # Question
Title: What are these underlines shown for whitespace at the end of some lines?
The following screenshot shows Emacs 26.3 (*GNU Emacs 26.3 (build 2, x86\_64-pc-linux-gnu, GTK+ Version 3.24.14) of 2020-03-26, modified by Debian*) editing a Markdown file:
Note that on some lines of the code block, some of the space characters at the end of lines are rendered as `_`. If I go to any of these locations and do a `describe-char`, they are reported as normal spaces:
```
character: SPC (displayed as SPC) (codepoint 32, #o40, #x20)
```
Looking at the file with a hex editor, I can confirm that these are normal `0x20` spaces just like all the other ones that don't show any artefacts.
These artefacts are stable across closing and reopening the file in Emacs. However, they are not shown in `fundamental-mode`, only `markdown-mode`.
What do they mean, do they mean anything or is it just a bug, and is there anything I can do to get rid of them?
# Answer
> 2 votes
In Markdown, two spaces at the end of the line cause a hard line break. markdown-mode highlights those for you, because otherwise they are indistinguishable from soft line breaks. It seems you have trailing white space in your diagram.
However, this is a bug since it shouldn't apply that face to trailing whitespace inside a code block.
---
Tags: whitespace, markdown-mode, rendering
--- |
thread-7650 | https://emacs.stackexchange.com/questions/7650 | How to open a external terminal from emacs | 2015-01-23T05:19:04.190 | # Question
Title: How to open a external terminal from emacs
Brand new emacs user here.
I want to have the ability of opening a terminal with current file path from emacs, like what the `open terminal here` package does in sublime text 2.
By terminal, I mean a separate external terminal emulator running bash or zsh, like gnome-terminal, not the emulated shells inside emacs, like `M-x shell` `M-x eshell`, which I can't appreciate for now.
I googled but had nothing found... It seems that emacs guys really enjoy living in emacs.
# Answer
Another try that disowns the process so your terminal will survive even after emacs is killed.
```
(defun run-gnome-terminal-here ()
(interactive "@")
(shell-command (concat "konsole --workdir"
(file-name-directory (or load-file-name buffer-file-name))
" > /dev/null 2>&1 & disown") nil nil))
```
> 7 votes
# Answer
What terminal emulator are you using? Take KDE's `Konsole` as example, just write a function:
```
(defun open-konsole ()
(interactive)
(call-process "konsole" nil 0 nil "--workdir" default-directory))
```
The args from 5st place are konsole's argument. See your prefered terminal simulator's man page.
`M-x open-konsole` will open a new konsole process and use current `default-directory` (`pwd` in ELisp) as working directory.
> 2 votes
# Answer
The other answers didn't work for me. This code does:
```
(defun open-gnome-terminal ()
(interactive)
(shell-command "gnome-terminal"))
```
> 2 votes
# Answer
You can use the external package terminal-here. This does only one thing, but does it well; exactly what you requested. And works for me on multiple OS.
> 2 votes
# Answer
Building on terminal-here as proposed before, I created a small function that determines depending on the system and desktop environment the program to run. It can be useful if you like changing desktop, or keep your `.emacs` synchronized between several computers. Note that I didn't tested the windows/darwin/gnome/... shell code, only KDE is tested for now.
```
;; ##########################################################
;; ### Open terminal
;; ##########################################################
;; Define a function to recognize the desktop environment easily
;; You shouldn't need to touch this function
(defun get-desktop-environment ()
(interactive)
(let (
;; Create new variable with DE name
(de_env (getenv "XDG_CURRENT_DESKTOP"))
;; Make sure search is case insensitive
(case-fold-search t))
(cond ((eq system-type 'darwin)
"darwin")
((memq system-type '(windows-nt ms-dos cygwin))
"windows")
((string-match ".*kde.*" de_env)
"kde")
((string-match ".*gnome.*" de_env)
"gnome")
((string-match ".*unity.*" de_env)
"unity")
((string-match ".*xfce.*" de_env)
"xfce")
((string-match ".*lxde.*" de_env)
"lxde")
((string-match ".*mate.*" de_env)
"mate")
((string-match ".*cinnamon.*" de_env)
"cinnamon")
(t "unknown"))))
;; You can edit this function if you want to change the default command for a specific desktop
(defun get-terminal (path)
(alist-get (get-desktop-environment)
'(("darwin" . ("open" "-a" "Terminal.app" "."))
("windows" . ("cmd.exe" "/C" "start" "cmd.exe"))
("kde" . ("konsole" "--workdir" "."))
("gnome" . ("gnome-terminal" "--working-directory=."))
("xfce" . ("xfce4-terminal" "--working-directory=.")))
'("x-terminal-emulator") nil 'equal))
(use-package terminal-here
:ensure t
:bind (("<f6>" . terminal-here-launch))
:config
(setq terminal-here-terminal-command #'get-terminal))
```
> 1 votes
# Answer
Most of the time I use `shell-mode`. So I heavily use shell-here. But when I need external terminal. I use urxvt-client with tmux using this:
* Create file named 'term-here' in /usr/local/bin/ containing
```
urxvtc -e bash -c "tmux -q has-session && exec tmux attach-session -d || exec tmux new-session -n$USER -s$USER@$HOSTNAME"
```
* Create new function in emacs
```
(defun term-here ()
(interactive)
(start-process "" nil "term-here"))
```
* Bind to your favorite key
This will open urxvt-client (with tmux) in your current directory. I bind it in dired-mode-map.
```
(use-package dired
:ensure nil
:ensure-system-package urxvt
:bind ((:map dired-mode-map
("," . term-here))))
```
I choose urxvt-client because it is fast and simple. Don't forget to run your urxvt-daemon at startup.
> 0 votes
# Answer
This worked perfectly fine for me: `(delete-window (async-shell-command "gnome-terminal"))`. Swap out your terminal command.
> 0 votes
---
Tags: term
--- |
thread-63299 | https://emacs.stackexchange.com/questions/63299 | Access Table data from from elisp using headline ID | 2021-02-09T20:22:44.623 | # Question
Title: Access Table data from from elisp using headline ID
I have a bunch of recipes under different headline, and each have an ingredient list specified as a table.
I would like to access that table as an list in a src block using the headline id, same as if I where to use the name table name (which is very easy)
Truth to be told I have a usecase where I'd like to do the same for lists.
```
* Recepies
** Killer Sandwich
:PROPERTIES:
:ID: 0123
:END:
A really good sandwich!
#+name: sandwich_recipie
| 1 | piece | bread |
| 100 | g | cheese |
| 100 | g | butter |
#+begin_src elisp :var data=sandwich_recipie headline_id=0123 :results output
(= sandwich_data (magic-org-function-to-get-first-table-as-list headline_id))
#+end_src
```
So far I've been looking into org-element, but it seems like I'm not smart enough to use that... sorry
# Answer
It seems you have figured out almost everything. Using `:var data=heading` and `#+name: heading` already does the conversion of a table into a list for you and binds it to a variable by that name. Here's a full example:
```
* Recipes
** Killer Sandwich
:PROPERTIES:
:ID: 0123
:END:
A really good sandwich!
#+name: sandwich_recipe
| 1 | piece | bread |
| 100 | g | cheese |
| 100 | g | butter |
#+begin_src elisp :var data=sandwich_recipe headline-id="0123" :results output
(require 'seq)
(princ (format "Recipe: %s\n" headline-id))
(dolist (line data)
(seq-let (amount unit ingredient) line
(princ (format "%s%s of %s\n"
(if (= amount 1) "one " amount)
unit
ingredient))))
#+end_src
#+RESULTS:
: Recipe: 0123
: one piece of bread
: 100g of cheese
: 100g of butter
```
Here's a simpler source block that shows just the conversions:
```
#+begin_src elisp :var data=sandwich_recipe :results value drawer
data
#+end_src
#+RESULTS:
:results:
((1 piece bread) (100 g cheese) (100 g butter))
:end:
```
> 1 votes
---
Tags: org-mode
--- |
thread-63370 | https://emacs.stackexchange.com/questions/63370 | How to make a thin red cursor | 2021-02-13T08:01:59.357 | # Question
Title: How to make a thin red cursor
This is a newbie question.
I'd like to have a red cursor with a width of 4. This code doesn't work:
```
(setf cursor-type '(bar . 4))
(set-cursor-color "#FF0000")
```
how can i correct this to display a red cursor with a width of 4?
# Answer
> 3 votes
Since `cursor-type` is a buffer-local variable, if you use `setf` (or `setq`) you only change its value in the temporary buffer used while reading the init file (ref.). When a variable's doc string says "Automatically becomes buffer-local when set" it means you have to use `setq-default` to change it. This works for me
```
(setq-default cursor-type '(bar . 4))
(set-cursor-color "#FF0000") ; You can also use ‘"red"’.
```
---
From the comments: You can change the shape of the cursor in unselected windows by setting `cursor-in-non-selected-windows`, for example `(setq-default cursor-in-non-selected-windows '(bar . 1))`.
---
Tags: cursor
--- |
thread-63350 | https://emacs.stackexchange.com/questions/63350 | How can I display very large SVG files using `image-mode`? | 2021-02-12T15:52:02.133 | # Question
Title: How can I display very large SVG files using `image-mode`?
I'm trying to use Emacs to visualise very large UML diagrams created by PlantUML \[1\]. In PNG form these diagrams have over 20000x1300 - in fact, the reason why I moved from PNG to SVG for their generation is that I could not find the right value for `PLANTUML_LIMIT_SIZE`. At any rate, they generate correctly in SVG and also open correctly using Google Chrome (see \[2\] for an example diagram from my git repo). However, when I try to visualise them in Emacs, after a long time, I get a 30x30 size and a blank square.
So my question is: are there any settings I need to toggle in order to display very large SVG files using image-mode, or did I perhaps hit some kind of limitation?
**Update 1**: Please note that I can display regular (small) SVG images correctly, including smaller PlantUML diagrams.
**Update 2**: I'm using Emacs 27.1 on Debian GNU/Linux testing.
**Update 3**: I have read through the code of `image-mode` \[3\] and I cannot see any obvious conditional handling for SVG based on size. However, I am not an elisp expert so I probably missed something.
**Update 4**: I ran emacs with `-q` to figure out if this was a problem of my config, and it supplied me with a much more informative message:
```
Invalid image size (see ‘max-image-size’)
```
I then subsequently set this variable to some very large values:
```
(setq max-image-size 162704)
```
However, this only changed the error:
```
Error parsing SVG image ‘(image :type svg :file PATH_TO_IMAGE/dogen.text.svg :scale 1 :max-width 643 :max-height 324)’
```
\[1\] https://plantuml.com/
\[2\] https://raw.githubusercontent.com/MASD-Project/dogen/master/projects/dogen.text/modeling/dogen.text.svg
\[3\] https://github.com/emacs-mirror/emacs/blob/master/lisp/image.el
# Answer
OK I think I got to the bottom of this. So, to recap, if you want images with either width or height which are larger than the default, you can update `max-image-size`, *e.g.*:
```
(setq max-image-size 20000)
```
You can see how this variable is used in Emacs C code \[1\]. However, Emacs uses `librsvg` for SVG support, and in its code you will find this \[2\]:
```
if (scaled_width > 32767 || scaled_height > 32767) {
g_printerr (_("The resulting image would be larger than 32767 pixels on either dimension.\n"
"Librsvg currently cannot render to images bigger than that.\n"
"Please specify a smaller size.\n"));
exit (1);
}
```
To prove this is indeed the case, you can use `libsvg` directly via the command line, like so:
```
$ rsvg-convert --unlimited -d 1000 -p 1000 -w 35000 -h 38456 -o output.png dogen.text.svg
The resulting image would be larger than 32767 pixels on either dimension.
Librsvg currently cannot render to images bigger than that.
Please specify a smaller size.
```
For details as to why this limit exists, Sven Neumann explained \[3\]:
> librsvg uses cairo for rendering and the image size limit exists in cairo. As far as I understand cairo's main goal is to provide rendering for the desktop, taking advantage of display hardware acceleration if possible. Limiting the target surface size to what can be expressed as 16bit integers allows some optimizations and given the target of the cairo rendering library performance is very important. Of course for the librsvg use case this limit is unfortunate and we would love to get rid of it. That is certainly not an easy task though
Finally, I believe the reason why you do not see this error coming out of emacs is due to the way errors are being handled in `image.c`:
```
rsvg_error:
fn_g_object_unref (rsvg_handle);
/* FIXME: Use error->message so the user knows what is the actual
problem with the image. */
image_error ("Error parsing SVG image `%s'", img->spec, Qnil);
```
In summary, as things stand, `max-image-size` will work up to a limit of `32767`. I'm yet to prove that, as it requires reorganising my diagrams.
\[1\] https://emacsformacosx.com/emacs-bzr/trunk/src/image.c
\[2\] https://gitlab.gnome.org/JustMonika/librsvg/-/blob/master/rsvg-convert.c
\[3\] https://gitlab.gnome.org/GNOME/librsvg/-/issues/658#note\_1035036
> 3 votes
---
Tags: image-mode
--- |
thread-63345 | https://emacs.stackexchange.com/questions/63345 | How to restart elpy if it is not launch? | 2021-02-12T12:44:30.997 | # Question
Title: How to restart elpy if it is not launch?
I am working with `python` using `Emacs 26.3`. My goal is to jump to definition of the function and jump back, for that I am using https://github.com/jacktasia/dumb-jump, which runs `elpy-goto-definition` on the background.
I am starting emacs on startup using crontab using `(&>/dev/null emacsclient -t -q &)`. On that case, `elpy-goto-definition` never works. I have to restart emacs. But after the restart, it takes around 30 seconds for `elpy` to launch, sometimes it does not launch (I do not know why).
* What may be the main reason that let `elpy-goto-definition` to fail. Can I force `elpy-goto-definition` to work if it fails? or restart `elpy` within `emacs` if possible?
My setup:
```
(setq elpy-rpc-backend "jedi")
(add-hook 'elpy-mode-hook (lambda () (highlight-indentation-mode -1)))
(add-hook 'xref-backend-functions #'dumb-jump-xref-activate)
;; https://emacs.stackexchange.com/a/19194/18414
(defun goto-def-or-rgrep ()
"Go to definition of thing at point or do an rgrep in project if that fails"
(interactive)
(condition-case nil (elpy-goto-definition)
(error (elpy-rgrep-symbol (thing-at-point 'symbol)))))
(global-set-key "\C-x\C-j" 'goto-def-or-rgrep)
```
# Answer
> 1 votes
To jump to a definition I simply use `M-.`and to jump back `M-,` In my init file I have that:
```
(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.
'(elpy-modules
(quote
(elpy-module-company elpy-module-eldoc elpy-module-pyvenv elpy-module-highlight-indentation elpy-module-yasnippet elpy-module-django elpy-module-sane-defaults)))
'(elpy-rpc-python-command "python3")
'(elpy-rpc-virtualenv-path "~/.virtualenvs/python3.8")
)
```
In the menu bar \> Elpy \> Configure
```
Elpy Configuration
Emacs.............: 27.1
Elpy..............: 1.35.0
Virtualenv........: None
Interactive Python: python 2.7.16 (/usr/bin/python)
RPC virtualenv....: python3.8 (/Users/raoul/.virtualenvs/python3.8)
Python...........: python3 3.8.1 (/Users/raoul/.virtualenvs/python3.8/bin/python3)
Jedi.............: 0.16.0 (0.18.0 available)
Rope.............: Not found (0.18.0 available)
Autopep8.........: 1.5 (1.5.5 available)
Yapf.............: 0.29.0 (0.30.0 available)
Black............: 19.10b0 (20.8b1 available)
Syntax checker....: Not found (flake8)
```
---
Tags: python, elpy
--- |
thread-63356 | https://emacs.stackexchange.com/questions/63356 | How to make the current window display the buffer it was displaying before the current one? | 2021-02-12T20:36:35.120 | # Question
Title: How to make the current window display the buffer it was displaying before the current one?
For example, imagine I have two windows and three buffers. Both windows are displaying buffer 1 and I do the following,
1. in window 1, switch to buffer 2;
2. in window 2, switch to buffer 3, then to buffer 2.
Now both widows are displaying buffer 2. This command, invoked in window 1 would switch to buffer 1 and invoked in window 2 would switch to buffer 3. Invoked again it would bring back the selected window to buffer 2, that is, it should just cycle between the last two buffers displayed in the selected window, not transverse the window's buffer history.
# Answer
I took a look at the implementation of `switch-to-prev-buffer` (thanks Tobias! I didn't think to look there…), found the function `window-prev-buffers` and came up with this:
```
(defun previous-buffer-cycle ()
"Switch to the buffer previously displayed in the current
window."
(interactive)
(pop-to-buffer-same-window (caar (window-prev-buffers))))
```
I bound it to `C-c c` and I'll see if it's worthy of that key.
---
Update: The function above does nothing when the buffer it ought to move to is dead. For example, you're in buffer 1, you type `C-c c` (if you've bound it to that key) to go to buffer 2 and then you kill it. Now you're back to buffer 1, you hit `C-c c` and nothing happens because `previous-buffer-cycle` should switch to buffer 2 but that's not alive anymore. When that happens, the following version switches to the last *live* buffer that was displayed in the current window.
```
(defun previous-buffer-cycle ()
"Switch to the last live buffer that was displayed in the
current window."
(interactive)
(pop-to-buffer-same-window
(caar (assq-delete-all (current-buffer) (window-prev-buffers)))))
```
> 1 votes
# Answer
Doc-string of the command `previous-buffer`:
> In selected window switch to ARGth previous buffer. Call `switch-to-prev-buffer` unless the selected window is the minibuffer window or is dedicated to its buffer.
It is bound to `C-x C-left`.
There is also the command `mode-line-previous-buffer` which does the same as `previous-buffer` but first selects the window from which the mouse event originates.
This command is bound to `mouse-1` clicks on the buffer name in the mode line.
There are analogous commands for the next buffer bound to `C-x C-right` and `mouse-3`, respectively.
> 0 votes
---
Tags: buffers, window
--- |
thread-63374 | https://emacs.stackexchange.com/questions/63374 | How to archive an online article | 2021-02-13T10:50:01.043 | # Question
Title: How to archive an online article
Often times I find an interesting article online that I want to read later but I have a different priorities so I just paste a link into my org notes. Later these links become broken, and the articles are lost forever.
What I found works pretty well is to use https://archive.org/web/ to preserve online articles for later use. To save an article we just use the form on the bottom of the page. After a moment the link is ready.
I wish to simplify this process by just converting link at the point to archived one. The archiving is not guaranteed, though. Some of the websites don't allow crawlers and for the archive.org this is a must - "Only available for sites that allow crawlers."
Does anyone of you managed to implement such a solution?
I consider alternative solutions like downloading the page with the images into separate folder - most often I use w3m to read these articles, but not all of them may be opened in no-JS browser and I wish to have solution that will work even then.
# Answer
> 1 votes
The following package provides an excellent solution and is easy to set up:
```
org-web-tools
(require 'org-web-tools)
(bind-key "C-x w" 'org-web-tools-read-url-as-org)
```
https://github.com/alphapapa/org-web-tools
# Answer
> 0 votes
After testing one of suggested solution I decided to create my own package which function that converts link at point to archive.org processed link.
It's available here: https://github.com/farynaio/org-url-archive
---
Tags: org-mode
--- |
thread-63382 | https://emacs.stackexchange.com/questions/63382 | org-mode org-babel share a global variable across the file | 2021-02-13T20:08:56.090 | # Question
Title: org-mode org-babel share a global variable across the file
I'm a beginner org-mode user. Is there a way to remove baseUrl being duplicated in each block like the following one?
```
#+NAME: request-something
#+HEADER: :var baseUrl="http://localhost:3000"
#+HEADER: :var email="foo@bar.com"
#+BEGIN_SRC http
POST ${baseUrl}/api/foo
Content-Type: application/json
{
"email": "${email}",
}
#+END_SRC
```
I've tried to extract it as
```
#+NAME: baseUrl
| http://localhost:3000 |
```
but keep getting "cannot resolve a template to values" ob-http error trying to read it in src block
# Answer
OK the following solution did the trick:
1. add
```
#+PROPERTY: header-args :var baseUrl="http://localhost:3000"
```
2. restart org-mode
`Ctrl``c``c` in my case while staying on that PROPERTY line
*Messages* buffer would output the following lines as a result:
```
>org-mode restarted
>Local setup has been refreshed
```
Take a look at this related question if you want to know more How to specify default header arguments in orgmode code blocks
> 4 votes
---
Tags: org-mode, org-babel
--- |
thread-45097 | https://emacs.stackexchange.com/questions/45097 | Smooth scrolling by pixel-lines | 2018-10-02T00:42:37.680 | # Question
Title: Smooth scrolling by pixel-lines
With GNU Emacs 26.1 installing either smooth scroll while adding
```
(require 'smooth-scroll)
(smooth-scroll-mode t)
```
to my `.emacs`, or smooth scrolling with
```
(require 'smooth-scrolling)
(smooth-scrolling-mode 1)
```
does turn on the smooth scrolling mode just fine, but two-finger vertical swipes on the trackpad do not deliver the purported smooth scrolling.
Switching to Yamamoto Mitsuharu's Emacs is a bit too much for just this one nice feature. I'd rather stick to a package.
Did you manage to get either of these two packages to smooth scroll with 26.1 or a recent version of Emacs?
By "smooth scroll" here I mean that one would get the scrolling obtained with, say, Safari (with files whose length exceeds that of the window/frame).
**Update**
The discussions online
are inherently confused. Missing in the middle of the questions/conversations is a definition of "line" in the expression "smooth scrolling by line". One solution is to qualify that term by replacing it with either "character-line" or "pixel-line". The present question is about the latter.
# Answer
M-x `pixel-scroll-mode`, available since Emacs 26, is all that's needed to have pixel scrolling. Credit to @db48x
> 8 votes
# Answer
You may also try `good-scrool.el`, a library which offers pixel scrolling like pixel-scroll-mode, but supports dynamic scrolling speed.
> 2 votes
---
Tags: scrolling
--- |
thread-63385 | https://emacs.stackexchange.com/questions/63385 | why do i get random "^[" when using eshell? | 2021-02-13T23:07:44.543 | # Question
Title: why do i get random "^[" when using eshell?
Using Eshell and the SSH command, I've logged on to a remote server. After installing a few server packages I noticed this strange thing:
Why is this happening? What can I do to prevent it?
# Answer
`ESC 7` and `ESC 8` are terminal escape sequences that save and restore the cursor position.
Eshell is a terminal emulator that only aims to run command line applications, not full-screen text mode applications. So it sets the `TERM` environment variable to `dumb` to indicate that it is a *dumb terminal*, i.e. a terminal that can only display text and move to the next line, and does not support any escape sequence to do things like moving the cursor. SSH propagates the value of `TERM` to the remote host.
So either you have a configuration somewhere that mangles the value of `TERM` or the application you're running assumes that every terminal supports ANSI escape sequences, which is almost but not quite the case. Given that the remote application here is dpkg and I can't reproduce the problem, I suspect the former.
Possible fixes and workarounds:
* If you have a configuration file somewhere that sets `TERM`, don't do it. It's always set by the terminal emulator.
* If you want terminal escape sequences to work, use a full-fledged terminal emulator such as `M-x term`, and not a shell command line like `M-x eshell`.
* If an application assumes that every terminal is an ANSI terminal, try running `… | cat` or `cat | …` or `cat | … | cat` instead of just . Even such applications will usually assume that they aren't running on a terminal if they're supplying output to a pipe.
> 1 votes
# Answer
Eshell is not a terminal. It does not interpret any escape sequences. The program you are running is using escape sequences to control the position of the cursor, so that it can draw a fancy progress bar. All well-behaved programs will only do this if the value of the TERM variable indicates that it is supported; make sure that you aren't setting this variable to anything other than "dumb" while using Eshell.
If the program is not well-behaved and simply assumes that you're running it in a terminal without checking (or of it only does useful things when it is running in a terminal), then you should add it to Eshell's list of visual commands, which is stored in the variable `eshell-visual-commands`. Eshell will run a terminal emulator for you whenever you run the commands in that list. For more information, see Chapter 4 Input/Output of the Eshell manual. To open the manuals, type `C-h i`. To go directly to this chapter of this manual, type `C-h i g (eshell)Input/Output RET`.
> 1 votes
---
Tags: eshell
--- |
thread-63388 | https://emacs.stackexchange.com/questions/63388 | Deleting a minibuffer only frame on C-g | 2021-02-14T00:49:14.557 | # Question
Title: Deleting a minibuffer only frame on C-g
**What I'm trying to achieve**
I'm trying to create a popup that runs an elisp funtion I've written which searches my library directory for pdfs, gets the user to choose an option (using completing read) and opens the selected pdf.
**What I've done**
Because I want it available as a keybinding in my desktop env, I'm running it through a wrapper using emacsclient. I'm calling:
```
emacsclient --eval "(mwe-pdf-lookup-and-quit)" -a ""
```
Which points to the function:
```
(defun mwe-pdf-lookup-and-quit ()
(make-frame '((width . 80) (height . 25)
(minibuffer . only)
(name . "lookup")))
(sleep-for 0.01)
(select-frame-by-name "lookup")
(select-frame-set-input-focus (selected-frame))
(message (completing-read ; This is where my pdf search function goes
"Choose: "
'("Option 1" "Option 2")))
(delete-frame))
```
**The problem**
Works perfectly if I choose a file. The pdf is opened and the frame is deleted. The problem is, if I decide I don't want to open a file anymore and press C-g, the frame displays "Quit emacsclient request" and hangs around. I would like to know how I can delete the minibuffer frame instead.
# Answer
> 1 votes
You could use `unwind-protect` like that:
```
(make-frame '((width . 80) (height . 25)
(minibuffer . only)
(name . "lookup")))
(sleep-for 0.01)
(select-frame-by-name "lookup")
(select-frame-set-input-focus (selected-frame))
(unwind-protect
(message (completing-read ; This is where my pdf search function goes
"Choose: "
'("Option 1" "Option 2")))
(delete-frame)))
```
The unwind forms are executed unconditionally, also in the case of `C-g`.
---
Tags: frames, minibuffer
--- |
thread-33061 | https://emacs.stackexchange.com/questions/33061 | TLS connection to marmalade-repo.org:443 is insecure after updating to Emacs 25 | 2017-05-25T21:26:06.633 | # Question
Title: TLS connection to marmalade-repo.org:443 is insecure after updating to Emacs 25
When I run `M-x list-packages` I get the following error with Marmalade after updating to Emacs 25.
```
Certificate information
Issued by: COMODO RSA Domain Validation Secure Server CA
Issued to: Domain Control Validated
Hostname: marmalade-repo.org
Public key: RSA, signature: RSA-SHA256
Protocol: TLS1.2, key: ECDHE-RSA, cipher: AES-256-GCM, mac: AEAD
Security level: Medium
Valid: From 2015-07-12 to 2018-07-11
The TLS connection to marmalade-repo.org:443 is insecure for the
following reasons:
the certificate was signed by an unknown and therefore untrusted authority
certificate could not be verified
```
Relevant `.emacs` code: (full .emacs here)
```
(require 'package)
(add-to-list 'package-archives
'("melpa" . "http://melpa.org/packages/") t)
(add-to-list 'package-archives
'("gnu" . "http://elpa.gnu.org/packages/") t)
(add-to-list 'package-archives
'("marmalade" . "http://marmalade-repo.org/packages/") t)
(package-initialize)
;; bootstrap use-package
;; https://github.com/jwiegley/use-package/
(unless (package-installed-p 'use-package)
(package-refresh-contents)
(package-install 'use-package))
(eval-when-compile (require 'use-package))
```
I've also tried to solve it with gnutils-cli suggestion: `$ gnutls-cli --tofu marmalade-repo.org` but couldn't make it work yet. Any ideas?
```
$ gnutls-cli --tofu marmalade-repo.org
gnutls-cli --tofu marmalade-repo.org
Processed 173 CA certificate(s).
Resolving 'marmalade-repo.org:443'...
Connecting to '80.69.77.43:443'...
- Certificate type: X.509
- Got a certificate list of 1 certificates.
- Certificate[0] info:
- subject `CN=marmalade-repo.org,OU=PositiveSSL,OU=Domain Control Validated', issuer `CN=COMODO RSA Domain Validation Secure Server C
A,O=COMODO CA Limited,L=Salford,ST=Greater Manchester,C=GB', serial 0x5f7ce5cf6602297b4cbd14639b670e7d, RSA key 2048 bits, signed usin
g RSA-SHA256, activated `2015-07-12 00:00:00 UTC', expires `2018-07-11 23:59:59 UTC', SHA-1 fingerprint `6e080a477d14631d2edf839de582a
c04d4363d09'
Public Key ID:
aba6d76ab3d363fa190d654160236eefd32a46dc
Public key's random art:
+--[ RSA 2048]----+
| . +oo |
| . o . . |
| o o |
| . . o |
| . .S |
| o.E= |
| . o= o |
| O.== |
| .*=X+. |
+-----------------+
- Status: The certificate is NOT trusted. The certificate issuer is unknown.
*** PKI verification of server certificate failed...
- Description: (TLS1.2)-(ECDHE-RSA-SECP256R1)-(AES-256-GCM)
- Session ID: 53:BF:2F:D2:86:74:BD:BC:85:A8:67:12:0B:39:7A:12:EA:2F:91:1F:8E:06:5E:94:7F:20:11:4F:FC:51:60:8F
- Ephemeral EC Diffie-Hellman parameters
- Using curve: SECP256R1
- Curve size: 256 bits
- Key Exchange: ECDHE-RSA
- Server Signature: RSA-SHA256
- Cipher: AES-256-GCM
- MAC: AEAD
- Compression: NULL
- Options: safe renegotiation,
- Handshake was completed
- Simple Client Mode:
*** Fatal error: The TLS connection was non-properly terminated.
*** Server has terminated the connection abnormally.
```
Related *unsolved* issue: Server TLS configuration is broken and vulnerable #144
# Answer
The server configuration on marmalade.org is broken: It does not serve the intermediate certificate it is using. This has been pointed out in half a dozen of issues now at https://github.com/nicferrier/elmarmalade -- I can discern no action.
So one can say that marmalade is defunct.
Unfortunately, I also don't know yet how to make the Emacs package manager work again in the presence of this error.
> 9 votes
# Answer
Now in 2021, the error message still is the same but the certificate in question is even expired. Moreover, fetching the package list from marmelade is unacceptably slow, and eventually results in an error.
There are also other indicators of obsolescence. Thus, the currently best answer I can give is:
*Do not use the marmalade-repo.org package repository.*
It is very unfortunate, even unfraternal by the maintainer, not to declare it officially dead.
> 7 votes
# Answer
I got this to work by downloading the PEM file for \[Intermediate CA #2\] COMODO RSA Organization Validation Secure Server CA (SHA-2) into `~/etc/tls/certificates/comodo.rsa.ca.intermediate.crt` and adding the following to `.emacs`:
```
(require 'gnutls)
(add-to-list 'gnutls-trustfiles
(expand-file-name
"~/etc/tls/certificates/comodo.rsa.ca.intermediate.crt"))
```
> 5 votes
---
Tags: package-repositories
--- |
thread-63391 | https://emacs.stackexchange.com/questions/63391 | How do I link to an ID on a non org-mode file? | 2021-02-14T10:34:06.080 | # Question
Title: How do I link to an ID on a non org-mode file?
I'd like to create a link inside an org-mode file to a source code file, say in C++. But I'd like the link to point to a possibly changing position in the file, so I want to use a unique identifier. For example, say the C++ file is as follows:
```
// {{{ 507ab9d0-d1a5-4fa9-97a9-d78a48a08c3d
<some content>
// }}}
```
I want to create a link that takes me to `507ab9d0-d1a5-4fa9-97a9-d78a48a08c3d`. Can this be done in org-mode? I've been looking at org-id \[1\], but to the lay person, it does not seem to fit this use case.
\[1\] https://github.com/tkf/org-mode/blob/master/lisp/org-id.el
# Answer
You can use a file link like this:
file:f1.cpp::507ab9d0-d1a5-4fa9-97a9-d78a48a08c3d
It should open the file and then search for the string you put in.
> 8 votes
---
Tags: org-mode
--- |
thread-27580 | https://emacs.stackexchange.com/questions/27580 | Change fill-column-indicator rule color immediately | 2016-10-05T06:58:09.903 | # Question
Title: Change fill-column-indicator rule color immediately
How can I change the color of the fill-column-indicator and have the changes visible immediately?
```
(defun my:change-fci-color (color)
(setq fci-rule-color color)
(fci-redraw-frame))
```
The previous code doesn't change the color in existing buffers until the major mode is changed or I reload the buffer.
The following code works but feels like a gross hack.
```
(with-current-buffer "fill-column-indicator.el"
(when fci-mode
(turn-off-fci-mode)
(turn-on-fci-mode)))
```
Ultimately, I want to change `fci-rule-color` based on the current theme's background color. So, when I change from a light theme to a dark theme, `fci-rule-color` remains a subtle shade off of the background color.
# Answer
> 4 votes
The following three lines of code in this specific order will immediately visibly update the `fci-rule-color` -- in this example, I am using the color "red".
```
(setq fci-rule-color "red")
(fci-make-overlay-strings)
(fci-update-all-windows t)
```
# Answer
> 3 votes
Here's the complete end-to-end solution I ended up with based on lawlist's answer.
```
(defun my:color-is-closer-to-white-p (color)
"Returns t if COLOR is closer to white than black."
(< (color-distance color "white") (color-distance color "black")))
(defun my:get-subtle-color-from-background (percent-difference)
"Gets a shade PERCENT-DIFFERENCE from the current background color.
If the color is closer to white, multiply percent-difference by 2
so it's easier to see."
(let* ((current-background-color (face-background 'default)))
(if (my:color-is-closer-to-white-p current-background-color)
(color-darken-name current-background-color (* 2 percent-difference))
(color-lighten-name current-background-color percent-difference))))
(defun my:change-fci-color (&rest args)
"Change the fill-column-indicator based on the background.
ARGS is only used because we use this function as advice after
`load-theme'."
(setq fci-rule-color (my:get-subtle-color-from-background 10))
(let* ((wins (window-list (selected-frame) 'no-minibuf))
(bufs (delete-dups (mapcar #'window-buffer wins))))
(dolist (buf bufs)
(with-current-buffer buf
(when fci-mode
(fci-make-overlay-strings)
(fci-update-all-windows t))))))
(advice-add 'load-theme :after 'my:change-fci-color)
```
# Answer
> 3 votes
I was looking for an example of setting `fill-column-indicator` font color in Emacs 27.1, and this page keeps coming up. As I eventually worked out what I needed I'm posting the answer here.
```
(set-face-foreground 'fill-column-indicator "salmon")
```
See `(info "(emacs) Displaying Boundaries")` for more information on the built-in `display-fill-column-indicator-mode`.
---
Tags: colors, display, fill-column
--- |
thread-63396 | https://emacs.stackexchange.com/questions/63396 | How to properly align org table with mixed English-Bengali script? | 2021-02-14T15:54:46.067 | # Question
Title: How to properly align org table with mixed English-Bengali script?
I am unable to tidy up this table, so that last column is properly aligned, as the other two:
```
|-----------+----------------+------------|
| English | Bengali s. | Bengali w. |
|-----------+----------------+------------|
| Monday | Shōmbār | সোমবার |
| Tuesday | Monggolbār | মঙ্গলবার |
| Wednesday | Budhbār | বুধবার |
| Thursday | Brihoshpotibār | বৃহস্পতিবার |
| Friday | Shukrobār | শুক্রবার |
| Saturday | Shonibār | শনিবার |
| Sunday | Robibār | রবিবার |
|-----------+----------------+------------|
```
No matter what I do, I can't have Org-mode make it look proper.
Is there a command that help with mixed English-Bengali scripts?
I am using Emacs 27.1 with standard Org-mode, with fixed-width Hack font. Other fixed-width fonts also do not seem to help.
Is this possible at all, or shall I report this as a bug (or feature request)?
# Answer
> 1 votes
The glyphs in your Bengali font are not the same width as the glyphs in the font you're using for everything else. In fact, your main font very likely doesn't have any Bengali glyphs in it at all, so Emacs is falling back to other fonts that you have installed on your system. With the glyph shaping that Bengali requires, it may not even be possible to have a properly monospaced Bengali font.
You can position the cursor over the Bengali text and type `C-u C-x =` to find all the details about the text at that location, including the font that supplied the glyph.
Edit: It's not a bug. Org Mode relies on the font being monospaced to line up the columns, and when you mix scripts you frequently lose that ability. You wouldn't be the first to suggest that columns should be sized based on pixel sizes, but Emacs currently doesn't make that easy.
---
Tags: org-mode, org-table, unicode
--- |
thread-63398 | https://emacs.stackexchange.com/questions/63398 | How would I create smarter HTTP links in org mode? | 2021-02-14T16:28:32.120 | # Question
Title: How would I create smarter HTTP links in org mode?
I have lots of links that look like:
```
https://domain.com/en/res/main/r1/sm-e/spec/1/1#q=1-1-1
```
I want to be able to enter a string like:
```
A-1-1
```
and be able to create a correct link like:
```
[[https://domain.com/en/res/main/r1/sm-e/spec/1/1#q=1-1-1][A-1-1]]
```
In the past, I was able to find help for links to pdf documents. But this is more complex, but I would love to hear your suggestions.
# Can I have a bonus answer?
How do I pass multiple parameters to my abbreviations? Can the following be a clue? where I can find examples?
```
(org-link-set-parameter "type" :complete #'some-completion-function)
```
# Answer
tl;dr:
```
#+LINK: jira https://jira.mycompany.com/browse/%s
[[jira:TASK-1234][TASK-1234: label]]
```
will create the links you desire.
As NickD mentions, find "Link Abbreviations" in the org manual., also via `C-h i g (org)Link Abbreviations <RET>`
> 4 votes
---
Tags: org-mode
--- |
thread-63390 | https://emacs.stackexchange.com/questions/63390 | Get filename of a message opened in mu4e | 2021-02-14T10:07:28.333 | # Question
Title: Get filename of a message opened in mu4e
How can I get the actual file name of a message (as it is stored on my disk) opened with mu4e?
# Answer
> 1 votes
This gets the current message the active cursor is in `(plist-get (mu4e-message-at-point) :path)`.
---
Tags: mu4e
--- |
thread-63406 | https://emacs.stackexchange.com/questions/63406 | How to modify text that's yanked? | 2021-02-14T21:20:53.447 | # Question
Title: How to modify text that's yanked?
I copy text from websites and paste/yank into emacs buffers. But this text sometimes has silent hyphens in them. The behaviour when copying and pasting text with soft hyphens in it varies across applications, but for emacs (on Windows), it seems to paste the text *including* the soft hyphens. I want it to not include the soft hyphens.
What I've been doing right now is a manual `M-x replace-string` where I paste in the soft-hyphen to be replaced with nothing.
Is there a way to have emacs automatically replace soft-hyphen with nothing after a yank? Is there a hook to use?
# Answer
> 1 votes
There is a variable named `interprogram-paste-function` that is bound to the function that retrieves the value from the system.
You can define your own function that calls the original function and remove the hyphens, and bind it to this variable.
The package https://github.com/Lindydancer/highlight2clipboard does similar things, although it modifies things copied from Emacs to the outside world.
---
Tags: hooks, replace, yank
--- |
thread-63401 | https://emacs.stackexchange.com/questions/63401 | Use wildcard in tag search | 2021-02-14T17:46:59.267 | # Question
Title: Use wildcard in tag search
Hi I would like to use
`C-c a m`
To create a todo list that is filtered by tags.
If I have a tag like `:Makeamilliondollars:`
I would like to be able search for it using a wildcard.
Eg I would like to enter `Makea`
I tried
`Makea*`
and this does not work.
Looking at the docs: 11.3.3 Matching tags and properties https://orgmode.org/manual/Matching-tags-and-properties.html
The only example given for a wildcard search is:
> For example, ‘work+{^boss.\*}’ matches headlines that contain the tag ‘:work:’ and any tag starting with ‘boss’.
So I am wondering in my case do I need to use
`{^Makea.*}`
That seems like a lot of extra characters to type in each time I want to do a wildcard search.
Could someone tell me what the minimum additional characters are to do a wildcard search?
# Answer
> 1 votes
Org mode uses the standard Emacs minibuffer completion mechanism for tags: whenever a tag is expected (e.g. at the `C-c a m` prompt), you can type `TAB` to get a completion list. You can click on a completion to choose it (or, without a mouse, switch to the completion buffer, navigate to the completion of interest and press `RET`); or you can narrow down the selection by typing a letter or two and pressing another `TAB`: when you have reduced the choices to just one, type `RET` to choose it. E.g. if I say `C-c a m` and type `TAB` at the matching prompt, I might get a completion buffer with many tags:
```
drill emacs export fedora firewalld git html latex linux
nfs noexport org pacc project python rh selinux ssh
```
Typing `e TAB` reduces the list to two: `emacs export`, and typing `m TAB` completes it to just `emacs` at which point I type `RET` and I am done: the tag `emacs` is selected.
At a more advanced level, there are ways to influence what tags are added to the completion list: by default, it's all the tags in the file (e.g. when you try to insert a tag on a headline), or all the tags in all the agenda files (that's what `C-c a m` uses); but you can use the variables `org-tag-alist` and `org-tag-persisten-alist` and you can also use in-buffer settings to modify the completion list. You can find the gory details here or, better, just say `C-h i g (org)Setting tags` to your emacs (that invokes the Info system in emacs - learning to use the Info system is highly recommended: you can use emacs to tell you (almost) all about emacs). Although I mention this for completeneess, you should probably not worry about it now. After you get comfortable with standard completion, you might want to come back and reread this paragraph.
The standard Emacs minibuffer completion mechanism is described here but, as above, you can also use Info to get to the same information inside your emacs: `C-h i g (emacs)Completion` \- and BTW, you can use completion to get to the right place: say `C-h i g (em TAB )Compl TAB` and you don't have to type the whole thing (or even remember it). Completion is powerful!
In the future, you might want to investigate some other completion mechanisms that are available (John Kitchin mentions helm and ivy in his answer), but I would recommend that you leave them for later: you can spend years working with Emacs without feeling the need for any of these additional mechanisms.
# Answer
> 1 votes
That is the correct way to do it. Your only other approach is to use something like ivy or helm, which when you type C-c a m will offer you a list of tags that you can use completion on to narrow down.
---
Tags: org-mode, tags
--- |
thread-63410 | https://emacs.stackexchange.com/questions/63410 | Assign default priority cookie to captured tasks | 2021-02-14T22:55:57.080 | # Question
Title: Assign default priority cookie to captured tasks
I looking for a way to explicitly add priority cookies to tasks created via org-capture with default the cookie that represents `org-priority-default`. This is to avoid the situation that some tasks rely on default priority that may change over time, rather than the one attached at the moment of their creation.
This should be possible to be achieved using `‘%(EXP)’` in `org-capture-templates`, by taking `org-priority-default` and converting it to cookie representation.
How the `org-capture-templates` should look to work like that?
# Answer
> 1 votes
Untested, but I think adding this to your init file
```
(defun prio ()
(format "[#%c]" org-default-priority))
```
and then using
```
...
* %(prio) TODO
...
```
in your capture template should do the trick. E.g.
```
(add-to-list 'org-capture-templates
'("s" "Shopping" entry
(file+headline "~/lib/org/shopping.org" "Shopping")
"* %(prio) TODO %?
%U"
:prepend t))
```
---
Tags: org-mode
--- |
thread-63413 | https://emacs.stackexchange.com/questions/63413 | finding git conflict in the same buffer if cursor is at end of the buffer | 2021-02-15T15:13:43.363 | # Question
Title: finding git conflict in the same buffer if cursor is at end of the buffer
I am using `next-conflict` to detect is there any git conflict, using following answer: Jump to next merge conflict in project using Magit and Smerge. I experience that if I am at the end of the file/buffer and if there is a conflict in the same buffer/file, the conflict is not found. But if I switch into another buffer, or go to top of the buffer it iss found.
Is there any workaround to fix this issue?
---
setup:
```
(defun smerge-try-smerge ()
(save-excursion
(goto-char (point-min))
(when (re-search-forward "^<<<<<<< " nil t)
(require 'smerge-mode)
(smerge-mode 1))))
(add-hook 'find-file-hook 'smerge-try-smerge t)
(add-hook 'after-revert-hook 'smerge-try-smerge t)
(defun smerge-next-safe ()
"returns t on success, nil otherwise"
(condition-case err
(not (smerge-next))
('error
nil)))
(require 'vc)
(defun next-conflict () ;; key-binding
(interactive)
(let ((buffer (current-buffer)))
(when (not (smerge-next-safe))
(vc-find-conflicted-file)
(if (eq buffer (current-buffer))
(message "No conflicts found")
(goto-char 0)
(smerge-next-safe)))))
```
# Answer
Good idea. Here's a `next-conflict` function that wraps around whenever there is no more conflicted files, but the current one still has conflicts:
```
(defun next-conflict ()
(interactive)
(let ((buffer (current-buffer)))
(when (not (smerge-next-safe))
(vc-find-conflicted-file)
(when (eq buffer (current-buffer))
(let ((prev-pos (point)))
(goto-char (point-min))
(unless (smerge-next-safe)
(goto-char prev-pos)
(message "No conflicts found")))))))
```
I modified the answer you are referring to as well *(it was mine answer)* as such behavior is more intuitive. And changed behavior accordingly of the built-in emacs function with similar functional.
Might be worth noting that I looked at how `smerge-next` is defined, and it is defined with `easy-mmode-define-navigation` macro. As far as I look through the macro there's no way to make `smerge-next` wrap around the search *(e.g. by changing some variable or something like that)*, so I open-coded the wrapping higher the stack.
> 2 votes
---
Tags: magit, smerge
--- |
thread-51100 | https://emacs.stackexchange.com/questions/51100 | emacs: cannot open terminfo database file | 2019-06-18T15:21:44.013 | # Question
Title: emacs: cannot open terminfo database file
I've created a new terminfo entry to enable italics in my terminal, as described here. The new terminfo entry looks like:
```
xterm-256color-italic|xterm with 256 colors and italic,
sitm=\E[em, ritm=\E[23m,
use=xterm-256color,
```
and it's saved to `~/xterm-256color-italic.terminfo`.
I installed the new terminfo entry by running `tic -x xterm-256color-italic.terminfo`. I see the compiled terminfo file in `~/.terminfo/78/xterm-256color-italic`. When I `export TERM=xterm-256color-italic` and run `infocmp`, I see:
```
# Reconstructed via infocmp from file: /Users/rpatnaik/.terminfo/78/xterm-256color-italic
xterm-256color-italic|xterm with 256 colors and italic,
am, bce, ccc, km, mc5i, mir, msgr, npc, xenl,
colors#0x100, cols#80, it#8, lines#24, pairs#0x10000,
acsc=``aaffggiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz{{||}}~~,
bel=^G, blink=\E[5m, bold=\E[1m, cbt=\E[Z, civis=\E[?25l,
clear=\E[H\E[2J, cnorm=\E[?12l\E[?25h, cr=\r,
csr=\E[%i%p1%d;%p2%dr, cub=\E[%p1%dD, cub1=^H,
cud=\E[%p1%dB, cud1=\n, cuf=\E[%p1%dC, cuf1=\E[C,
cup=\E[%i%p1%d;%p2%dH, cuu=\E[%p1%dA, cuu1=\E[A,
cvvis=\E[?12;25h, dch=\E[%p1%dP, dch1=\E[P, dim=\E[2m,
dl=\E[%p1%dM, dl1=\E[M, ech=\E[%p1%dX, ed=\E[J, el=\E[K,
el1=\E[1K, flash=\E[?5h$<100/>\E[?5l, home=\E[H,
hpa=\E[%i%p1%dG, ht=^I, hts=\EH, ich=\E[%p1%d@,
il=\E[%p1%dL, il1=\E[L, ind=\n, indn=\E[%p1%dS,
initc=\E]4;%p1%d;rgb\:%p2%{255}%*%{1000}%/%2.2X/%p3%{255}%*%{1000}%/%2.2X/%p4%{255}%*%{1000}%/%2.2X\E\\,
invis=\E[8m, is2=\E[!p\E[?3;4l\E[4l\E>, kDC=\E[3;2~,
kEND=\E[1;2F, kHOM=\E[1;2H, kIC=\E[2;2~, kLFT=\E[1;2D,
kNXT=\E[6;2~, kPRV=\E[5;2~, kRIT=\E[1;2C, kb2=\EOE, kbs=^H,
kcbt=\E[Z, kcub1=\EOD, kcud1=\EOB, kcuf1=\EOC, kcuu1=\EOA,
kdch1=\E[3~, kend=\EOF, kent=\EOM, kf1=\EOP, kf10=\E[21~,
kf11=\E[23~, kf12=\E[24~, kf13=\E[1;2P, kf14=\E[1;2Q,
kf15=\E[1;2R, kf16=\E[1;2S, kf17=\E[15;2~, kf18=\E[17;2~,
kf19=\E[18;2~, kf2=\EOQ, kf20=\E[19;2~, kf21=\E[20;2~,
kf22=\E[21;2~, kf23=\E[23;2~, kf24=\E[24;2~,
kf25=\E[1;5P, kf26=\E[1;5Q, kf27=\E[1;5R, kf28=\E[1;5S,
kf29=\E[15;5~, kf3=\EOR, kf30=\E[17;5~, kf31=\E[18;5~,
kf32=\E[19;5~, kf33=\E[20;5~, kf34=\E[21;5~,
kf35=\E[23;5~, kf36=\E[24;5~, kf37=\E[1;6P, kf38=\E[1;6Q,
kf39=\E[1;6R, kf4=\EOS, kf40=\E[1;6S, kf41=\E[15;6~,
kf42=\E[17;6~, kf43=\E[18;6~, kf44=\E[19;6~,
kf45=\E[20;6~, kf46=\E[21;6~, kf47=\E[23;6~,
kf48=\E[24;6~, kf49=\E[1;3P, kf5=\E[15~, kf50=\E[1;3Q,
kf51=\E[1;3R, kf52=\E[1;3S, kf53=\E[15;3~, kf54=\E[17;3~,
kf55=\E[18;3~, kf56=\E[19;3~, kf57=\E[20;3~,
kf58=\E[21;3~, kf59=\E[23;3~, kf6=\E[17~, kf60=\E[24;3~,
kf61=\E[1;4P, kf62=\E[1;4Q, kf63=\E[1;4R, kf7=\E[18~,
kf8=\E[19~, kf9=\E[20~, khome=\EOH, kich1=\E[2~,
kind=\E[1;2B, kmous=\E[<, knp=\E[6~, kpp=\E[5~,
kri=\E[1;2A, mc0=\E[i, mc4=\E[4i, mc5=\E[5i, meml=\El,
memu=\Em, oc=\E]104\007, op=\E[39;49m, rc=\E8,
rep=%p1%c\E[%p2%{1}%-%db, rev=\E[7m, ri=\EM,
rin=\E[%p1%dT, ritm=\E[23m, rmacs=\E(B, rmam=\E[?7l,
rmcup=\E[?1049l\E[23;0;0t, rmir=\E[4l, rmkx=\E[?1l\E>,
rmm=\E[?1034l, rmso=\E[27m, rmul=\E[24m,
rs1=\Ec\E]104\007, rs2=\E[!p\E[?3;4l\E[4l\E>, sc=\E7,
setab=\E[%?%p1%{8}%<%t4%p1%d%e%p1%{16}%<%t10%p1%{8}%-%d%e48;5;%p1%d%;m,
setaf=\E[%?%p1%{8}%<%t3%p1%d%e%p1%{16}%<%t9%p1%{8}%-%d%e38;5;%p1%d%;m,
sgr=%?%p9%t\E(0%e\E(B%;\E[0%?%p6%t;1%;%?%p5%t;2%;%?%p2%t;4%;%?%p1%p3%|%t;7%;%?%p4%t;5%;%?%p7%t;8%;m,
sgr0=\E(B\E[m, sitm=\E[3m, smacs=\E(0, smam=\E[?7h,
smcup=\E[?1049h\E[22;0;0t, smir=\E[4h, smkx=\E[?1h\E=,
smm=\E[?1034h, smso=\E[7m, smul=\E[4m, tbc=\E[3g,
u6=\E[%i%d;%dR, u7=\E[6n, u8=\E[?%[;0123456789]c,
u9=\E[c, vpa=\E[%i%p1%dd,
```
which indicates to me that the terminfo entry has been installed correctly. However, when I run `emacs -nw`, I get: `emacs: cannot open terminfo database file`. I've verified that `~/.terminfo` and the termcap file are both world-readable, so it shouldn't be a permission issue. I'm wondering where I go from here -- it looks like I've configured everything correctly, and the error message gives me no further details.
I'm running emacs 26.2, which I've installed from Homebrew. This is running on MacOS Mojave 10.14.5.
# Answer
So, I have found 2 solutions for 2 different terminal emulators.
1. with Kitty terminal emulator
2. with Alacritty terminal emulator
---
# Kitty
Using the Kitty terminal emulator I had the same issue, I was following the emacs FAQ
The fix was to do `use=xterm-kitty` instead of `use=xterm-256color`.
So I used:
```
xterm-emacs|xterm with 24-bit direct color mode for Emacs,
use=xterm-kitty,
setb24=\E[48\:2\:\:%p1%{65536}%/%d\:%p1%{256}%/%{255}%&\
%d\:%p1%{255}%&%dm,
setf24=\E[38\:2\:\:%p1%{65536}%/%d\:%p1%{256}%/%{255}%&\
%d\:%p1%{255}%&%dm,
```
then
```
$ tic -x -o ~/.terminfo terminfo-custom.src
```
and you can do
```
$ TERM=xterm-emacs emacs -nw
```
why does it work? I have no idea, but it didn't work following the `xterm-256color`, I would get
```
emacs: cannot open terminfo database file
```
Related GitHub issue on the Kitty repo
---
# Alacritty
From this other SO question, the following worked by following the FAQ, but using this `tic`:
```
/usr/bin/tic -x -o ~/.terminfo terminfo-custom.src
```
and, works!
when I do `which tic` I get `/opt/local/bin/tic` and I guess that one gave me issue.
> 3 votes
---
Tags: fonts, terminal-emacs, terminfo
--- |
thread-63417 | https://emacs.stackexchange.com/questions/63417 | Adding directory local variable for projectile test command is not working | 2021-02-15T21:30:17.350 | # Question
Title: Adding directory local variable for projectile test command is not working
I'm setting up my python lsp using this video tutorial.
My emacs init.el configuration file is here
By default `projectile-project-test-cmd` runs the command `python -m unittest discover`. I want to change it to `pytest` instead as explained by tutor.
I followed the below steps -
```
1. M-x add-dir-local-variable RET
2. choose mode 'python-mode'
3. Add local-variable 'projectile-project-test-cmd'.
4. Add local variable value "pytest".
```
It creates .dir-locals.el file with below contents -
```
((python-mode . ((projectile-project-test-cmd . "pytest"))))
```
Now when I run `M-x projectile-test-project` it runs pytest command.
But when I close emacs and reopen it, it stops running pytest and runs `python -m unittest discover` instead.
How to fix this issue?
# Answer
Did you save the .dir-locals.el file? Are you loading these files via TRAMP? By default, Emacs doesn't look for the .dir-locals.el file when loading files via TRAMP, as it might add significant delays. If this is the problem, you can set `enable-remote-dir-locals` to `t` to opt in.
> 2 votes
---
Tags: projectile, directory-local-variables
--- |
thread-63420 | https://emacs.stackexchange.com/questions/63420 | How to limit mark/kill size of huge (org-mode) files? | 2021-02-16T01:33:33.113 | # Question
Title: How to limit mark/kill size of huge (org-mode) files?
I have `org-mode` files about 50K lines long, which I can edit and save file; but once in a while accidentally marked a large region by typing `C-x C-x` or `C-x h`, and copied too much data into clipboard, so Emacs hangs until killed by oom.
Is there a mode or customization helping to limit mark/kill size to avoid this pain?
# Answer
It's not clear to me why Emacs hangs in what you describe, or what you mean by that.
But I think you're talking about accidentally defining a large region of text, and then killing or copying that, and that it is that killing or copying that you want to avoid.
If that's the case, then this may help: `wimpy-del.el`. It's what I bind to `C-w`, in place of `kill-region`. It's a silly little thing I picked up somewhere eons ago, but I've become used to it and like it.
Here's the doc string:
> Kill the text between `BEG` and `END`, putting it in the kill ring.
>
> (Interactively, uses the region.)
>
> If the previous command was a completion, just remove the completion. Else, if the region is \> `wimpy-delete-size`, you must confirm the kill.
Pretty simple, really. Mostly it just asks you to confirm killing if the region size is greater than the value of variable `wimpy-delete-size`.
(The part about previous command being a "completion" isn't very relevant nowadays. That refers to the use of standard Emacs library `completion.el`, which is useful but which hardly anyone is even aware of anymore, even though it's still part of Emacs.)
> 1 votes
---
Tags: org-mode, kill-text, large-files
--- |
thread-61745 | https://emacs.stackexchange.com/questions/61745 | Is there a general way to delay computing & displaying mode-line text? | 2020-11-15T10:26:53.457 | # Question
Title: Is there a general way to delay computing & displaying mode-line text?
Some things I'd like to show in the mode-line are quite expensive to compute, so I'd rather use an idle timer.
Is there a general way to do this? or does this need to be added individually? (using a method similar to `which-function-mode`, for example).
# Answer
This can be done using idle timers, although this can get a little involved if you have multiple idle timers and want to prevent them setting each other off.
I've wrapped this up into a small package: mode-line-idle, a small dedicated package which does just this, without any configuration or minor-modes.
Calls to the main function can be done in `:eval` blocks in the `mode-line-format` variable.
> 0 votes
---
Tags: mode-line, idle-timer
--- |
thread-63395 | https://emacs.stackexchange.com/questions/63395 | How to change the size on mode-line horizontal line | 2021-02-14T14:49:36.100 | # Question
Title: How to change the size on mode-line horizontal line
I am running emacs version GNU Emacs 27.1 (build 1, x86\_64-pc-linux-gnu, GTK+ Version 3.24.20, cairo version 1.16.0) of 2020-09-19, on Ubuntu 20.04 on a laptop with 4K display in 200% scaling mode (hiDPI).
Emacs does not adapt fully to scaling changes. On a large monitor I use 100% and everything renders ok. But when using the laptop screen only, the horizontal divider of the mode-line is incorrectly scaled. Can the size of the divider be customized?
I also have to change the Default font size every time I change between 100% and 200% scaling, is there a setting in Emacs where that can be automatically set based on screen resolution/scaling settings?
**EDIT**
The mode line is not an issue any more, since I was informed that it was a scrollbar that concealed the text.
I still have a problem when changing from large monitor to laptop screen in 4K resolution. I have to manually change the default font size, and the cursor is too small.
Does Emacs have support for automatic adaptation to HiDPI screen sizes?
# Answer
> 0 votes
A solution to the main problem is to hide the horizontal scroll-bar, either as suggested by Arch Stanton in a comment, or by disabling it in:
Options -\> Show/Hide -\> Scroll bar -\> Horizontal
I did not understand that it was the scrollbar that was incorrectly rendered so that the text in the mode line was covered.
---
Tags: mode-line, customization, emacs27
--- |
thread-63427 | https://emacs.stackexchange.com/questions/63427 | Preventing shell mode from treating ! as a history reference | 2021-02-16T09:57:45.037 | # Question
Title: Preventing shell mode from treating ! as a history reference
Various command-line tools, such as gdb, ftp, sftp, etc, use ! to prefix a command to be run in a shell. So (for instance) `!mkdir foo` will make a directory called foo. When using these tools inside emacs shell-mode, the shell-mode treats the ! as a history reference, does a history lookup, and expands the result before putting the command in the history ring. So if I have previously typed `mkdir bar`, shell-mode puts `mkdir bar foo` into the history ring.
Can I easily suppress all special treatment of ! in the shell history? I want the history to contain `!mkdir foo`. I don't ever use ! at the shell, so I'd be happy with a way of turning this off entirely, although I suppose it could be made switchable based on the prompt.
# Answer
Figured it out: `(setq shell-input-autoexpand nil)`. I spent a long while looking at `comint-input-autoexpand` which was getting mysteriously set to `'history`: this is done by shell-mode based on `shell-input-autoexpand`. I don't see an easy way to make it prompt-dependent, though.
> 2 votes
---
Tags: shell-mode, gdb, history, ftp
--- |
thread-63425 | https://emacs.stackexchange.com/questions/63425 | Best practice for long string literals in emacs lis? | 2021-02-16T09:01:21.283 | # Question
Title: Best practice for long string literals in emacs lis?
What are best practices for handling long string literals in Emacs Lisp?
E.g.
```
(... stuff that causes indentation ...
(error "`my-config-alist' mapped command `%s' to `%S' instead of a major-mode"
command mode))
10 20 30 40 50 60 70 80
```
I know several workarounds, all of which are awkward and worse for readability than the long line, e.g.
```
(error (concat "`my-config-alist' mapped command `%s' "
"to `%S' instead of a major-mode")
command mode))
(error "%s%s%s%S%s"
"`my-config-alist' mapped command `" command
"' to `" mode "' instead of a major-mode"))
10 20 30 40 50 60 70 80
```
Such situations happen frequently. If this were python, I could use implied string concatenation, such as
```
blocks that cause indentation:
assert mode, f"`config' object mapped command " \
f"{command!r} to {mode!r} instead " \
f"of a major-mode"
10 20 30 40 50 60 70 80
```
Is there any accepted best-practice to do this in Emacs-Lisp or other lisps?
# Answer
I don't know a best-practice recommendation. Personally, I use the `concat` approach. But I have seen also something like this:
```
(... stuff that causes indentation ...
(error "\
`my-config-alist' mapped command `%s' to `%S' instead of a major-mode"
command mode))
```
> 1 votes
---
Tags: string, coding-conventions
--- |
thread-63432 | https://emacs.stackexchange.com/questions/63432 | How can I show a tabular list of variables and their values? | 2021-02-16T16:09:19.177 | # Question
Title: How can I show a tabular list of variables and their values?
Is there a way to see the values of a list of variables? E.g., if I have `var1`, `var2` and `var3`, is there a standard `elisp` function that shows me the values of these variables at the same time?
I mean something that returns an output like:
```
var1 nil
var2 t
var3 nil
```
I don't need the output to be a string. I just need to read it in a window.
Please note that I asked if is there an emacs standard function that already does it. Otherwise every help is welcome but I can also try to do it by myself.
# Answer
The relevant function is `symbol-value`.
According to its documentation:
```
symbol-value is a function defined in C source code.
Signature
(symbol-value SYMBOL)
Documentation
Return SYMBOL's value. Error if that is void.
Note that if lexical-binding is in effect, this returns the
global value outside of any lexical scope.
```
This is an example of using it on a list of variables.
```
(mapcar #'symbol-value '(emacs-version emacs-build-time evil-undo-system))
;;=> ("27.1 nil nil)
```
EDIT:
I copied your desired ouput and wrote a function which returns a string. Not that we need to use unique symbols so we avoid the possibility of running into scope problems (when a variable you want to print has the same name as the parameter of the lambda).
```
(defun my/tabular-values (variable-list)
(let ((var (gensym "var")))
(mapc `(lambda (,var)
(thread-last (symbol-value ,var)
(format "%S %S\n" ,var)
(insert)))
variable-list)))
(let ((var1 nil)
(var2 t)
(var3 nil))
(my/tabular-values '(var1 var2 var3)))
;; The following is inserted into buffer after using `eval-print-last-sexp`.
var1 nil
var2 t
var3 nil
```
> 1 votes
# Answer
This is a slight elaboration of Aquaactress' answer that uses an Org mode code block to produce a table. It uses `-zip-with` from the dash package.
```
#+begin_src emacs-lisp
(setq x 'foo y 'bar z 'baz)
(setq l '(x y z))
(-zip-with #'list (mapcar #'symbol-name l) (mapcar #'symbol-value l))
#+end_src
#+RESULTS:
| x | foo |
| y | bar |
| z | baz |
```
BTW, I tried producing the pairs with a function and failed miserably:
```
#+begin_src emacs-lisp
(setq x 'foo y 'bar z 'baz)
(setq l '(x y z))
(defun symbol-name-value (x)
(list (symbol-name x) (symbol-value x)))
(mapcar #'symbol-name-value l)
#+end_src
#+RESULTS:
| x | x |
| y | bar |
| z | baz |
```
The failure is obvious in retrospect, but I don't know how to fix it.
> 1 votes
---
Tags: variables
--- |
thread-50662 | https://emacs.stackexchange.com/questions/50662 | Proper syntax highlighting of $...$ in org-mode | 2019-05-22T23:12:06.393 | # Question
Title: Proper syntax highlighting of $...$ in org-mode
I've put
```
(setq org-highlight-latex-and-related '(latex script entities))
```
in my emacs config and yet `$..$` that contain more than one symbol aren't highlighted properly:
>
How to fix?
**EDIT:** This still does not work for me as of `org-version` `9.4`.
# Answer
> 0 votes
Actually, I experience the same behaviour, even if I choose `native` highlight instead of `latex`. It seems that it gets confused because in `org-mode` you can insert even currency such as $3500 and .12$. So it's difficult to distinguish whether and expression is indeed a latex expression or if it's a text inside two monetary values.
If you are using latex I suggest to use the `\( \)` notation, that's why I've never noticed this before.
If you want to dive deep to resolve the issue you can have a look at the function `org-inside-LaTeX-fragment-p` and the variable `org-latex-regexps` defined in `org.el`. Unfortunately it's very complex.
---
Tags: org-mode, latex, preview-latex
--- |
thread-52828 | https://emacs.stackexchange.com/questions/52828 | Autocomplete files/paths while typing in any mode or fundamental mode, like bash does at prompt | 2019-09-25T13:15:25.250 | # Question
Title: Autocomplete files/paths while typing in any mode or fundamental mode, like bash does at prompt
After opening up an empty file named
```
~/work/aback
```
using `emacsclient -nw` ... .
I type in
```
~/huTAB
```
in the body of the file. how can I get autocompletion candidates shown? In this case, any files/folders starting with the name `hu`
# Answer
`M-x hippie-expand`
> Try to expand text before point, using multiple methods. The expansion functions in `hippie-expand-try-functions-list` are tried in order, until a possible expansion is found. Repeated application of `hippie-expand` inserts successively possible expansions.
Also see Emacs manual
> 1 votes
# Answer
Interesting... I use find-file-at-point (ffap.el) which is offering me completion. In scratch buffer (having ran `emacs -q`):
```
(require 'ffap)
(ffap-bindings)
~/.prof
```
With the cursor after .prof `C-x C-f` then asks if I want to load .profile, pressing `tab` I can then choose other files. Using Copy `C-x h M-w` I can then paste that into the file. Possibly not the solution you're looking for.
> 0 votes
---
Tags: completion
--- |
thread-61386 | https://emacs.stackexchange.com/questions/61386 | package refresh hangs | 2020-10-23T03:14:02.567 | # Question
Title: package refresh hangs
On Emacs 26.3, Ubuntu 20.04, when I run
```
emacs -Q
```
followed by
```
(package-refresh-contents)
```
I get
```
Contacting host: elpa.gnu.org:443
```
So the package refresh just hangs. I tried to switch from https to http, but no luck.
# Answer
> 4 votes
Try:
```
(custom-set-variables
'(gnutls-algorithm-priority "normal:-vers-tls1.3"))
```
Found by @sds (https://emacs.stackexchange.com/a/56067/21569) and the emacs-devel mailing list (Cf. https://emacs.stackexchange.com/a/56067/795 ).
Supposedly the underlying issue was fixed in emacs 26.3, but I still see it in emacs 27.1\[^1\].
\[^1\]: exact versions
```
( cat /etc/fedora-release ; uname -a ; rpm -q emacs) | sed -e "s/$(hostname)/XXX/"
Fedora release 33 (Thirty Three)
Linux XXX 5.10.12-200.fc33.x86_64 #1 SMP Mon Feb 1 02:40:52 UTC 2021 x86_64
x86_64 x86_64 GNU/Linux
emacs-27.1-2.fc33.x86_64
```
# Answer
> 0 votes
Having a similar issue with the *MELPA stable* repository (GNU Emacs 26.1 on Debian 10.6), I've been able to workaround this with :
```
(package-initialize)
(setq package-check-signature nil)
(require 'package)
(setq package-archives '(
("melpa-stable" . "http://www.mirrorservice.org/sites/stable.melpa.org/packages/")
)
)
```
with some limitations / remarks :
---
Tags: package
--- |
thread-63442 | https://emacs.stackexchange.com/questions/63442 | How to start a process with multiple arguments? | 2021-02-17T08:34:25.460 | # Question
Title: How to start a process with multiple arguments?
Instead running `sudo su joe -s prime-run firefox` in the shell I'd rather bind it to a key.
Yet, nothing happens on pressing `M-n` (while `M-i` works).
What am I doing wrong?
```
(setq exwm-input-global-keys
`(
;; Working >> Run firefox
([?\M-i] . (lambda ()
(interactive)
(start-process "" nil "/usr/bin/firefox")))
;; Not working >> Run firefox on the GPU
([?\M-n] . (lambda ()
(interactive)
(start-process "" nil "/usr/bin/sudo su joe -s /usr/bin/prime-run /usr/bin/firefox")))
)
)
```
# Answer
> 3 votes
C-h f start-process
```
start-process is a compiled Lisp function in `subr.el'.
(start-process NAME BUFFER PROGRAM &rest PROGRAM-ARGS)
Probably introduced at or before Emacs version 17.
Start a program in a subprocess. Return the process object for it.
NAME is name for process. It is modified if necessary to make it unique.
BUFFER is the buffer (or buffer name) to associate with the process.
Process output (both standard output and standard error streams)
goes at end of BUFFER, unless you specify a filter function to
handle the output. BUFFER may also be nil, meaning that this
process is not associated with any buffer.
PROGRAM is the program file name. It is searched for in `exec-path'
(which see). If nil, just associate a pty with the buffer. Remaining
arguments PROGRAM-ARGS are strings to give program as arguments.
```
So PROGRAM has to be the name of your executable, and then you pass its arguments as individual strings:
```
(start-process "" nil "/usr/bin/sudo" "su" "joe" "-s" "/usr/bin/prime-run" "/usr/bin/firefox")
```
In this case you might be better off using `shell-command`, that allows you to just pass in a commmand+args as a single string.
---
Tags: key-bindings, process
--- |
thread-42338 | https://emacs.stackexchange.com/questions/42338 | After change to org-mode 9.1.13, TAB not work when put after `<s` | 2018-06-30T15:14:38.913 | # Question
Title: After change to org-mode 9.1.13, TAB not work when put after `<s`
Usually, `TAB` after `<s` expand to `#+BEGIN_SRC` in org-mode, but today I updated my org to version 9.1.13, and `TAB` not work this way any more.
I don't know where to start to figure this out, but I `C-h k TAB` after `<s` and the help message is like this:
> runs the command org-cycle, which is an interactive autoloaded compiled Lisp function in \`org.el'.
>
> It is bound to `tab`, `TAB`, `menu-bar` `Tbl` `Next Field`, `menu-bar` `Org` `Show/Hide` `Cycle Visibility`.
>
> (org-cycle &optional ARG)
>
> For more information check the manuals.
>
> TAB-action and visibility cycling for Org mode.
>
> This is the command invoked in Org mode by the ‘TAB’ key. Its main purpose is outline visibility cycling, but it also invokes other actions in special contexts.
>
> When this function is called with a ‘C-u’ prefix, rotate the entire buffer through 3 states (global cycling) 1. OVERVIEW: Show only top-level headlines. 2. CONTENTS: Show all headlines of all levels, but no body text. 3. SHOW ALL: Show everything.
>
> With a ‘C-u C-u’ prefix argument, switch to the startup visibility, determined by the variable ‘org-startup-folded’, and by any VISIBILITY properties in the buffer.
>
> With a ‘C-u C-u C-u’ prefix argument, show the entire buffer, including any drawers.
>
> When inside a table, re-align the table and move to the next field.
>
> When point is at the beginning of a headline, rotate the subtree started by this line through 3 different states (local cycling) 1. FOLDED: Only the main headline is shown. 2. CHILDREN: The main headline and the direct children are shown. From this state, you can move to one of the children and zoom in further. 3. SUBTREE: Show the entire subtree, including body text. If there is no subtree, switch directly from CHILDREN to FOLDED.
>
> When point is at the beginning of an empty headline and the variable ‘org-cycle-level-after-item/entry-creation’ is set, cycle the level of the headline by demoting and promoting it to likely levels. This speeds up creation document structure by pressing ‘TAB’ once or several times right after creating a new headline.
>
> When there is a numeric prefix, go up to a heading with level ARG, do a ‘show-subtree’ and return to the previous cursor position. If ARG is negative, go up that many levels.
>
> 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.
>
> As a special case, if point is at the beginning of the buffer and there is no headline in line 1, this function will act as if called with prefix arg (‘C-u TAB’, same as ‘S-TAB’) also when called without prefix arg, but only if the variable ‘org-cycle-global-at-bob’ is t.
>
> \[back\]
Can you help me with where should I start to figure the problem out?
# Answer
I would like to add to the answer of m43cap:
`<s` `TAB`
works in Orgmode 9.2 and later if you activate the checkbox for `org-tempo` of the customization option `org-modules`.
You get to that customization option through the menu item `Options -> Customize Emacs -> Specific Option ...`, input of the option name `org-modules`, and `RET`. Tab-completion is possible during the input of the option name.
Alternatively you can input `M-x` `customize-option` `RET` `org-modules` `RET`. Tab-completion is possible.
> 4 votes
# Answer
```
<s TAB
```
still works at least since org-mode version 9.1.0. In org-mode version 9.2.4 (and maybe earlier) it might be better to use
```
M-x org-insert-structure-template
```
which should be bound to C-c C-,
> 3 votes
# Answer
This github issue explains the source of the issue.
Currently
```
C-c C-, s
```
Will insert a source code block. Note that there are a suite of other templates that can be inserted this way by choosing a letter other than `s`. At first I really didn't like this change but I have gotten used to it, it takes about the same amount of effort as `<s TAB` for me but has the added benefit of showing what other templates are available in a popup menu.
Also, if you feel so inclined or use custom blocks you can hit
```
C-c C-, TAB
```
which pops up a mini-buffer and lets you type in a custom block name.
Eg.
```
C-c C-, TAB myBlock
---yields---
#+begin_myBlock
#+end_myBlock
```
> 0 votes
---
Tags: org-mode
--- |
thread-19700 | https://emacs.stackexchange.com/questions/19700 | use-package :requires explanation | 2016-01-20T02:35:27.073 | # Question
Title: use-package :requires explanation
I found that there's a `:requires` (source) section, but I'm not quite sure what it does and there doesn't seem to be any documentation on it. Can someone explain what it does?
# Answer
Unfortunately, `use-package` is not as thoroughly documented as it should be. I remember finding an explanation of this keyword at some point, but can't seem to turn it up now. Looking at the source for `use-package-handler/:requires`, I think what this does is make the entire `use-package` block conditional on the presence of the specified feature(s).
Macroexpanding a sample block seems to confirm this interpretation. Take
```
(use-package foo
:requires (bar baz)
:config
(blah))
```
and call `pp-macroexpand-last-sexp` on it. You get this:
```
(if
(not
(member nil
(mapcar #'featurep
'(bar baz))))
(progn
(if
(not
(require 'foo nil 'noerror))
(ignore
(message
(format "Could not load %s" 'foo)))
(condition-case-unless-debug err
(blah)
(error
(ignore
(display-warning 'use-package
(format "%s %s: %s" "foo" ":config"
(error-message-string err))
:error))))
t)))
```
If you remove the `:requires` line and try again, you get just the contents of the `progn` form. So if all of the features you listed are present at the time the block is being executed, then everything's the same. If any feature is missing, nothing is loaded whatsoever.
> 4 votes
# Answer
@Aaron Harris' answer above is a good one. Just expanding a little on it here.
:after specifies that the main package should only load after the packages in the :after form are loaded. This can be useful when you don't want to have to declare dependencies before the main package. I use this because I like to organize my packages in alphabetical order which is often not the same as dependency order.
:requires specifies that the main package should only load after the packages in the :requires form are loaded. If they are not already loaded prior to the use-package declaration for our main package then just ignore the whole use-package form. Note that unlike when using :after, your dependencies (those packages in the :requires form must already have been loaded or the whole thing fails, it doesn't wait for dependencies to be loaded).
Example using :requires
```
(use-package foo
:requires bar baz
:config
(blah))
```
macroexpands to
```
(progn
(straight-use-package 'foo)
(when
(not
(member nil
(mapcar
(function featurep)
'(bar baz))))
(defvar use-package--warning460
(function
(lambda
(keyword err)
(let
((msg
(format "%s/%s: %s" 'foo keyword
(error-message-string err))))
(display-warning 'use-package msg :error)))))
(condition-case-unless-debug err
(eval-after-load 'foo
'(condition-case-unless-debug err
(progn
(blah)
t)
(error
(funcall use-package--warning460 :config err))))
(error
(funcall use-package--warning460 :catch err)))))
```
Example using :after
```
(use-package foo
:after bar baz
:config
(blah))
```
macroexpands to
```
(progn
(straight-use-package 'foo)
(defvar use-package--warning461
(function
(lambda
(keyword err)
(let
((msg
(format "%s/%s: %s" 'foo keyword
(error-message-string err))))
(display-warning 'use-package msg :error)))))
(condition-case-unless-debug err
(eval-after-load 'baz
'(eval-after-load 'bar
'(eval-after-load 'foo
'(condition-case-unless-debug err
(progn
(blah)
t)
(error
(funcall use-package--warning461 :config err))))))
(error
(funcall use-package--warning461 :catch err))))
```
NOTE: The macrostep emacs package is a handy one to do the expansions.
> 0 votes
---
Tags: use-package
--- |
thread-63436 | https://emacs.stackexchange.com/questions/63436 | Is there some way to view the HTML part of an email in an external browser or as a PDF in notmuch? | 2021-02-16T20:27:18.147 | # Question
Title: Is there some way to view the HTML part of an email in an external browser or as a PDF in notmuch?
I have just started using notmuch for email. I was wondering if there is some way I can view the HTML part of an email in an external browser or rendered to a pdf and viewed inside Emacs (like you can do with mu4e)?
# Answer
You can use `notmuch-show-view-part` (bound to `.-v` by default) while point is in the `text/html` part to accomplish this.
For this to function properly you'll need to make sure your `~/.mailcap` file has settings for `text/html`.
Here's what I have in mine on my Mac:
```
text/html; open %s; nametemplate=%s.html
```
Each line is `;` delimited with the first field specifying the content type, the second field specifying the command to use, and any additional fields specifying options.
So I have `nametemplate` which essentially adds `.html` to the filename that `notmuch` generates, which is then passed to `open` (which knows how to handle it because of the `.html` ending).
The format is described in RFC 1524.
---
As mentioned, you need to be in the `text/hmtl` part of the email for this to work. Since this can be inconvenient, I use this function which you can call from anywhere in the message in order to open the html part:
```
(defun notmuch-show-view-html+ ()
"Open the text/html part of the current message using
`notmuch-show-view-part'."
(interactive)
(save-excursion
(goto-char
(prop-match-beginning
(text-property-search-forward
:notmuch-part
"text/html"
(lambda (value notmuch-part)
(equal (plist-get notmuch-part :content-type)
value)))))
(notmuch-show-view-part)))
```
> 3 votes
---
Tags: html, pdf, notmuch
--- |
thread-51986 | https://emacs.stackexchange.com/questions/51986 | show-paren-mode only highlights when cursor is one character after closing parenthesis | 2019-08-04T04:06:42.313 | # Question
Title: show-paren-mode only highlights when cursor is one character after closing parenthesis
### Problem
I have `show-paren-mode` enabled, but the highlighting behavior unintuitive. In particular, the matching parentheses are only highlighted in two situations as shown below (the second of which is unintuitive):
1. Cursor on the opening parenthesis (which is expected behavior):
```
( some characters here ) some more characters here
^
cursor must be at the caret for highlighting to show
```
2. Cursor on the character **after** the closing parenthesis (which is unintuitive):
```
( some characters here ) some more characters here
^
cursor must be at the caret for highlighting to show
```
### Question
Is there a way for the matching parentheses to be highlighted when the cursor is **on** the closing parenthesis?
Like this:
```
( some characters here ) some more characters here
^
```
# Answer
> 2 votes
The following mutilating shortening of `show-paren--locate-near-paren` does what you want.
Copy these lines into your init file and restart Emacs.
```
(defun show-paren--locate-near-paren-ad ()
"Locate an unescaped paren \"near\" point to show.
If one is found, return the cons (DIR . OUTSIDE), where DIR is 1
for an open paren, -1 for a close paren, and OUTSIDE is the buffer
position of the outside of the paren. Otherwise return nil."
(let* ((before (show-paren--categorize-paren (point))))
(when (or
(eq (car before) 1)
(eq (car before) -1))
before)))
(advice-add 'show-paren--locate-near-paren :override #'show-paren--locate-near-paren-ad)
```
# Answer
> 0 votes
The following advice does what you want. When the block cursor is "on" the opening parenthesis, the closing parenthesis is highlighted. When the block cursor is "on" the closing parenthesis, the opening parenthesis is highlighted.
```
(advice-add show-paren-data-function
:around
(lambda (orig-fun)
(cond ((looking-at "\\s(")
(funcall orig-fun))
((looking-at "\\s)")
(save-excursion (forward-char 1) (funcall orig-fun))))))
```
The first cond clause handles an opening delimiter character (e.g. when the cursor is "on" an opening parenthesis). Since the default Emacs behavior already does what you want, we do not need to change the behavior, so we just reuse the original function.
The second cond clause handles a closing delimiter character (e.g. when the cursor is "on" a closing parenthesis). The default Emacs behavior is not doing what you want. To solve the problem, we "trick" the original function into believing that the cursor is right after the closing parenthesis whenever the cursor is "on" the closing parenthesis.
Otherwise, we return `nil`.
---
You may also want to consider this variant:
```
(advice-add show-paren-data-function
:around
(lambda (orig-fun)
(cond ((looking-at "\\s)")
(save-excursion (forward-char 1) (funcall orig-fun)))
(t (funcall orig-fun)))))
```
When the block cursor is "on" a closing parenthesis, it will highlight the opening parenthesis. When the block cursor is not "on" a closing parenthesis, but the previous character is a closing parenthesis, it will highlight the opening parenthesis.
I have tried these code snippets in GNU Emacs 26.3.
# Answer
> 0 votes
I believe setting `show-paren-when-point-inside-paren` to `t` does what you want.
From the docs:
```
Documentation:
If non-nil, show parens when point is just inside one.
This will only be done when point isn’t also just outside a paren.
```
Can be set with:
```
(setq show-paren-when-point-inside-paren t)
```
---
Tags: parentheses
--- |
thread-63451 | https://emacs.stackexchange.com/questions/63451 | Referencing Lexically Bound Variable in Mocked Function | 2021-02-18T02:10:39.130 | # Question
Title: Referencing Lexically Bound Variable in Mocked Function
I'd like to mock a function for a unit test that I'm writing. I want the mocked function to count how many times it was called but I'm having issues related to the scope of the count variable.
Here is an example of what I'm trying to do:
```
;; Assumes lexical-binding is t
(defvar example-settings nil)
(defun function-to-test ()
(funcall (car example-settings)))
(let* ((function-to-mock-call-cnt 0)
(example-settings
'((lambda ()
(setq function-to-mock-call-cnt
(1+ function-to-mock-call-cnt))))))
(function-to-test)
function-to-mock-call-cnt)
```
However, this fails with the error void-variable.
Can someone help me understand why this doesn't work?
# Answer
> 1 votes
The binding for variable `example-settings` is to a *quoted list*. The lambda form `(lambda...)` in that list isn't defined as a function there it's just a *list*.
You can't expect the lexical binding of variable `function-to-mock-call-cnt` to be captured within that lambda - nothing indicates to Emacs that the list `(lambda...)` is a function.
You can instead use a function such as `list` or use a backquote with a comma:
```
(example-settings
(list (lambda ()
(setq function-to-mock-call-cnt
(1+ function-to-mock-call-cnt))))))
```
or
```
(example-settings
`(,(lambda ()
(setq function-to-mock-call-cnt
(1+ function-to-mock-call-cnt))))))
```
---
Tags: functions, lexical-scoping
--- |
thread-63456 | https://emacs.stackexchange.com/questions/63456 | How to make sh-set-shell insert "#!/bin/sh" instead of "#!/usr/bin/sh" | 2021-02-18T09:22:57.207 | # Question
Title: How to make sh-set-shell insert "#!/bin/sh" instead of "#!/usr/bin/sh"
When I open a shell script (e.g. `emacs myscript.sh`) and do `C-c :` (`M-x sh-set-shell`), and select `sh` as the shell, Emacs will insert a `#!/usr/bin/sh` shebang instead of `#!/bin/sh`. I want Emacs to insert `#!/bin/sh` instead of `#!/usr/bin/sh`. I realize that Emacs is probably behaving like this because `/usr/bin` comes before `/bin` in my shell's `PATH`. What are some ways to prioritize the `/bin` directory only when running `sh-set-shell`?
# Answer
Simply add an advice around `sh-set-shell` will do.
```
(defun sh-set-shell-tmp-path-advice (func &rest r)
"Wrap `sh-set-shell' with temporarily modified
`exec-path'."
(let ((exec-path (cons "/bin/" exec-path)))
(apply func r)))
(advice-add 'sh-set-shell
:around 'sh-set-shell-tmp-path-advice)
```
> 2 votes
---
Tags: shell-mode
--- |
thread-55918 | https://emacs.stackexchange.com/questions/55918 | Don't kill helm search result buffer, navigate with M-g n | 2020-03-04T16:01:09.387 | # Question
Title: Don't kill helm search result buffer, navigate with M-g n
I was previously using ag-project to search string in my project. I had it setup so that it opened the relevant buffer on Enter, while keeping the result window open. I could then edit in that window, then `M-g n` (with compile minor mode) later to jump to the next result.
Now that I am evaluating helm, I try using `helm-ag-project-root` instead. What breaks my workflow is that I cannot go to the buffer where the match is, without killing the helm result buffer. The least I want to do is to browse the results of my helm search, and be able to scroll the buffers that open.
The best I would like to do is do a search, go to a match, do loads of other stuff, then go back to the result window without searching again, or even directly go to the next match.
I've found this, but don't find it satisfactory.
# Answer
> 1 votes
I'm on Spacemacs & am not sure whether this is specific or "universal", but checked at *Helm Do Ag*'s Help:
Previewing an item (search result line):
```
C-S-j/C-S-down helm-follow-action-forward -- select next line and preview
C-S-k/C-S-up helm-follow-action-backward -- select previous line and preview
C-i <not stated in help> -- preview item on selected line
```
Scrolling the preview buffer:
```
C-M-down helm-scroll-other-window
C-M-up helm-scroll-other-window-down
<mouse wheel scrolling also works>
```
There's also `C-c C-f` to toggle `helm-follow-mode`, then just next/prev-line does the preview.
I haven't found a reliable way to edit a previewed file while keeping the search buffer opened (sometimes clicking into it & returning via `SPC w b` works, but sometimes clicking doesn't do anything), but just opening a file, doing some work and returning to the session via `SPC r s` is enough for me (cursor position in the search results list is being remembered).
(not sure "preview" is the right term, but the buffer gets to the original content when helm session ends)
# Answer
> 0 votes
I faced the exact same problem and I came across this reddit item : https://www.reddit.com/r/spacemacs/comments/5wf24a/preserving\_helmminibuffer\_results/. You don't need a persistent buffer. You can resume the last helm search by simply pressing `SPC r s` in Spacemacs. You can resume any last helm session by pressing `SPC r l` Hope this solves your problem
---
Tags: helm, helm-ag
--- |
thread-63461 | https://emacs.stackexchange.com/questions/63461 | How to turn on "helm-mode" for a specific function? | 2021-02-19T04:17:55.550 | # Question
Title: How to turn on "helm-mode" for a specific function?
# The context
I've defined a big set of `yasnippet` snippets and sometimes I forget the shortcut for those snippets. I've found out recently that the function `yas-insert-snippet` can be used to insert a snippet by writing its name and the completion list of the function lists all the existing snippets.
I would like to use `helm` only for selecting an item from the completion list shown by `yas-insert-snippet`. However, I don't want `helm-mode` to be enabled because that would change the behavior of all functions that show a completion list (e.g. `switch-to-buffer`, `bookmark-jump`, `kill-buffer`, etc.).
I just want `helm-mode` to be enabled when executing the function `yas-insert-snippet`.
I've found that the variable `helm-completing-read-handlers-alist` can only be used to turn off `helm-mode` for specific functions but I would need to add all the functions to `helm-completing-read-handlers-alist` using cons of the form `(FUNCTION . nil)` if I want `helm-mode` to be disabled when executing FUNCTION.
# The question
How can I toggle `helm-mode` for an specific function? I assume that `helm-mode` is disabled by default since `helm` is not used for all functions.
# Additional context
I've tried the following but it doesn't work. I wrote it because I noticed that `helm-mode` is a variable.
```
(let ((previous-helm-mode helm-mode))
(helm-mode 1)
(call-interactively 'yas-insert-snippet)
(helm-mode previous-helm-mode))
```
# Answer
You can use the following function to accomplish that
```
(defun execute-with-helm (command)
(if helm-mode
(call-interactively command))
(progn
(helm-mode 1)
;; We call `unwind-protect' to ensure that `helm-mode' is
;; disabled even though `command' doesn't complete normally.
;;
;; Without `unwind-protect', if the user presses =C-g= while
;; `command' is being executed, then the entire function would
;; be exited and therefore, `helm-mode' wouldn't be disabled'
(unwind-protect (call-interactively command)
(helm-mode -1))))
```
Then, you can use that function as follows
```
(execute-with-helm 'switch-to-buffer)
```
```
(execute-with-helm 'kill-buffer)
```
```
(execute-with-helm 'yas-insert-snippet)
```
> 3 votes
---
Tags: helm, completion, yasnippet
--- |
thread-63474 | https://emacs.stackexchange.com/questions/63474 | How to make Isearch highlight more matches when I scroll? | 2021-02-19T17:35:57.800 | # Question
Title: How to make Isearch highlight more matches when I scroll?
upon having used Isearch or `C-u C-s` to highlight a word, when I use then `C-v` or `M-v` for scrolling the highlights remain due to setting
```
(setq-default
isearch-allow-scroll t
lazy-highlight-cleanup nil
lazy-highlight-initial-delay 0)
```
But isearch only highlights words which were visible when the search was triggered, and if I scroll up or down identical words are not highlighted. How can I change this behavior?
# Answer
> 1 votes
By default, lazy highlighting is lazy. It doesn't highlight beyond what's visible or has already been visible. You want to make it highlight matches everywhere, even those not yet visible.
Try setting option `lazy-highlight-buffer` to `t`. `C-h v` tells us:
> **`lazy-highlight-buffer`** is a variable defined in `isearch.el`. Its value is `nil`
>
> You can customize this variable.
>
> This variable was introduced, or its default value was changed, in version 27.1 of Emacs.
>
> Documentation:
>
> Controls the lazy-highlighting of the full buffer.
>
> When non-`nil`, **all text in the buffer** matching the current search string is highlighted lazily (see `lazy-highlight-initial-delay`, `lazy-highlight-interval` and `lazy-highlight-buffer-max-at-a-time`). This is useful when `lazy-highlight-cleanup` is customized to `nil` and doesn’t remove full-buffer highlighting after a search.
---
Tags: search, highlighting, isearch, scrolling
--- |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.