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-62322
https://emacs.stackexchange.com/questions/62322
how to add time information to an evaluated org-mode code block?
2020-12-17T04:57:30.313
# Question Title: how to add time information to an evaluated org-mode code block? I'd like to be able to add additional information of when a block was run to the result: ie. ``` #+BEGIN_SRC js var a = 4 var b = 3 return a + b #+END_SRC ``` ``` #+RESULTS: : 7 @ Thurs 8th Dec 2:00pm EST ``` is there a way to do that? # Answer There is an option `org-babel-hash-show-time` that you can set to `t` but it is used in conjunction with the `:cache` argument as @mankoff speculated in a comment. Try this: ``` * source block #+begin_src emacs-lisp :cache "yes" (+ 3 6) #+end_src #+RESULTS[(2020-12-17 15:34:18) 34e9...]: : 9 * Code :noexport: #+begin_src emacs-lisp (setq org-babel-hash-show-time t) #+end_src #+RESULTS: : t ``` The time stamp will be updated if you change the code block in any way, so that the calculated hash value changes - but if you just hit `C-c C-c` repeatedly, the hash value does not change and the time stamp remains at the value it had when the block was initially evaluated. > 2 votes --- Tags: org-mode ---
thread-62341
https://emacs.stackexchange.com/questions/62341
Start an org file with all headers collapsed
2020-12-17T20:59:33.747
# Question Title: Start an org file with all headers collapsed Whenever I open an org file, I want to see only the outline, so I want to have all the headers collapsed. I'm using doom emacs, this is what I have in my config.org file: ``` (setq org-startup-folded "overview") ``` I also tried it like this: ``` (after! org (setq org-startup-folded "overview")) ``` Both of these do not work. When I put this in the org file, it does work: ``` #+STARTUP: overview ``` However, I want this setting to be global and not file specific. # Answer > 11 votes I think the help is a little misleading on this one. You need to set `org-startup-folded` to `t`, not "overview": ``` (setq org-startup-folded t) ``` Alternatively, you can use the `customize-variable` interface to do this interactively (i.e., `M-x customize-variable org-startup-folded`). --- Tags: org-mode ---
thread-62325
https://emacs.stackexchange.com/questions/62325
How to act on the currently highlighted search result with evil mode?
2020-12-17T09:29:12.360
# Question Title: How to act on the currently highlighted search result with evil mode? When using evil mode search, is there a way to act on the currently highlighted search result by... * Converting it into a selection. * Treating it as a text object. * Having the ability to specify the end of the match when editing. Example edits could be: * Delete the text. * Make the text upper case. * Change the text for something else. This something I often want to do when the search is only part of a word, in this case operating on the word is editing past the part of the word I searched for. # Answer After looking into VIM documentation, I found a way to do this which works in evil-mode too. See Visual select current search result. --- `gn` selects the highlighted text, after pressing this you can operate on the selection. Pressing `n.` repeats the operation on the next match. --- Note that you may use `gn` in place of `w` in many operations. * `cgn` can be used to change the current search result. * `gUgn` makes the search result upper case. * `dgn` to delete the current highlight. --- While this on it's own is useful, it would be nice to have a way to enable select-on-search (for example, if the search began in visual mode, or if `gn` was pressed on the previous search result), this is a bit out of the scope of this question though. > 2 votes # Answer For the first point in your question I do not know a default way, but you could define a custom function (and bind it to some key) yourself to change the last match to a selection so that you can further edit it the evil way: ``` (defun my-evil-last-match-to-region () (interactive) (evil-visual-select evil-ex-search-match-beg evil-ex-search-match-end)) ``` You could bind it to `t` (or `f`), which are keys with similar functionality that I guess most users do not use both: ``` (define-key evil-normal-state-map (kbd "t") 'my-evil-last-match-to-region) ``` Subsequently, you can edit it the evil way using e.g. `d`, `U`, `c`. Or you could "specify the end/beginning of the match" using `l`/`oh`. > 0 votes --- Tags: evil, selection ---
thread-61296
https://emacs.stackexchange.com/questions/61296
Given a list of (filepath line column), how to make this open as an xref buffer?
2020-10-19T06:39:52.853
# Question Title: Given a list of (filepath line column), how to make this open as an xref buffer? If I have a list of file locations in elisp, how would I create an xref window, showing these locations? # Answer This function creates an `xref` buffer from a list of references (thanks to @Dmitry's answer). ``` (defun my-xref-from-file-references (file-references) "Create an xref buffer from FILE-REFERENCES ((file line column display-text) ...)." ;; Needed for xref API. (require 'xref) (let ((xrefs (list))) (dolist (item file-references) (pcase-let ((`(,file ,line ,col ,display-text) item)) (push (xref-make display-text (xref-make-file-location file line col)) xrefs)) (xref--show-xrefs (lambda () xrefs) nil)))) ``` Note that `(filepath line column)` isn't quite enough information for `xref`, so a `display-text` has been included which would typically be the line of text - but can be anything. > 1 votes # Answer You will need to convert that list to "xref item" values. See `xref--collect-matches-1` for how this is done. Since your locations are not "xref matches", though, you will call `xref-make` instead of `xref-make-match`, and won't need the `length` argument. Note that you will also need the string contents on that line (it will be shown in the xref buffer as "summary"). To show the list, you call `xref--show-xrefs`. The first argument, `fetcher`, must be a function that returns that list we computed above. Depending on how you retrieve that list, the fetcher could call the retrieval logic as well and then create the xref items from the result. Then `xref-revert-buffer` will work as expected in such buffers. Alternatively, if the list is static, fetcher can just process that list (by either looking up a lexical var up the scope, or some global var defined in the package). Also, for now, `fetcher` can be a simple list (of xref items). But that's an obsolete convention. Note that `xref--show-xrefs` is ostensibly a "private" function. But it should be stable enough in the near future. > 1 votes # Answer Not an answer, but too much code for a comment. May be you can reuse and adapt this code: ``` (save-excursion (and ;;; try finding file from make buffer javac error (re-search-forward "(\\(\\([A-Za-z]:\\)?\\.?\\.?/?[a-zA-Z0-9._/+-]+\\.[a-zA-Z0-9_/,+-]+\\):\\([0-9]+\\))" nil t) (or (and (file-readable-p (match-string 1)) (let ((file (match-string 1)) (line (string-to-int (match-string 3)))) (find-file file) (goto-line line) (recenter) t )) (and (get-buffer (file-name-nondirectory (match-string 1))) (let ((file (get-buffer (file-name-nondirectory (match-string 1)))) (line (string-to-int (match-string 3)))) (switch-to-buffer file) (goto-line line) (recenter) t )) ))) ``` > 0 votes --- Tags: xref ---
thread-62348
https://emacs.stackexchange.com/questions/62348
Use completing-read to call arbitrary function
2020-12-18T06:04:58.760
# Question Title: Use completing-read to call arbitrary function How can one pass a list of (arbitrary) functions to `completing-read` and run the selected candidate? Something like this: ``` (defun find/buffer () (interactive) (completing-read "Chose one: " '(("find-file" . 'find-file)("switch-to-buffer" . 'switch-to-buffer)))) ``` # Answer 1. Remove the quote in front of each function symbol. You've already quoted the alist. 2. Just look up the choice in the alist to get the function, then call it. ``` (defun find/buffer () (interactive) (let* ((choices '(("find-file" . find-file) ("switch-to-buffer" . switch-to-buffer))) (choice (completing-read "Choose one: " choices))) (call-interactively (cdr (assoc choice choices))))) ``` But if you make no difference between the name to choose and the function-symbol name then you might as well just do this: ``` (defun find/buffer () (interactive) (call-interactively (intern (completing-read "Choose one: " '(find-file switch-to-buffer))))) ``` > 1 votes --- Tags: completion, completing-read ---
thread-62352
https://emacs.stackexchange.com/questions/62352
How to have yank visually flash the pasted text
2020-12-18T07:16:56.533
# Question Title: How to have yank visually flash the pasted text I'd like to be able to paste text into a buffer and have emacs give a visual confirmation by flashing the region (highlighting and unhighlighting) the text that was pasted in the buffer. Is there an example of how to do this? # Answer > 3 votes There are three ways that I know of: * `volatile-highlights`: an external package which gives you visual feedback for many operations, including yanking. * `pulse`: a built-in library you can leverage to achieve what you want. You can advice `yank` to use `pulse-momentary-highlight-region`, for instance. * `goggles`: another external package. This one uses `pulse` to do the highlighting. From its README: > This library is the holy counterpart of `evil-goggles`. Another comparable library is `volatile-highlights`, which does not use pulse. By setting `goggle-pulse` to `nil`, the `goggles-mode` behaves similarly to the `volatile-highlights-mode`. --- Tags: yank ---
thread-58304
https://emacs.stackexchange.com/questions/58304
Skip over remaining errors in current file to next error in next file
2020-05-05T20:59:57.563
# Question Title: Skip over remaining errors in current file to next error in next file # tl;dr I am using `:cn` in Evil's Ex command line and would like to use `:cnf` as well, but it is not there, and I don't know what function to bind it to. # Details As a former Vim user who is slowly coming to see the light, I am using `:cnext` in Evil's Ex command line in Spacemacs to navigate errors from the Scala compiler/SBT. I am currently fixing errors caused by missing `import`s: thus, I can add one line at the top of the file and fix numerous errors. As such, I would like to skip straight to the next file with problems, i.e. Vim's `:cnfile`. `:cnf` is not bound, and I cannot find something appropriate to bind it to. I did find that `:cn` is bound to `next-error`, which seems to be associated with Compilation Mode. However that seems to be misdirection as `compilation-next-file` gives "Not in a compilation buffer". # Even more Details My setup includes the following, and I'm not entirely clear how much of this is relevant, so I'll list it all: # Answer It's a minor glitch/bug in the Emacs error interface, `compilation-next-file` only works (at least as of Emacs 25) if you are in the buffer showing the error messages, not in the source file with the error. Do something like `other-window` to get your cursor into error message buffer and `compilation-next-file` will work (and then you probably need to hit something like enter to take you back to the relevant source file. > 2 votes --- Tags: spacemacs, evil, flycheck, compilation-mode, lsp-mode ---
thread-61892
https://emacs.stackexchange.com/questions/61892
How to use a specific latex template in org-mode
2020-11-23T02:21:55.653
# Question Title: How to use a specific latex template in org-mode I would like to create this Latex template in org-mode : ``` \documentclass[french, 11pt]{scrartcl} \usepackage[utf8]{inputenc} \usepackage[T1]{fontenc} \usepackage{babel} \usepackage[hidelinks]{hyperref} \usepackage[ddmmyyyy]{datetime} \usepackage{microtype} \usepackage{antiqua} \author{My Name} \date{\today} \renewcommand{\contentsname}{Table des matières} ``` So I have added this to my .emacs in order to not have any of the default packages, just the one I want, based on what I saw on this tutorial : ``` (require 'ox-latex) (with-eval-after-load 'ox-latex (add-to-list 'org-latex-classes '("koma-article" "\documentclass[french, 11pt]{scrartcl} \usepackage[utf8]{inputenc} \usepackage[T1]{fontenc} \usepackage{babel} \usepackage[hidelinks]{hyperref} \usepackage[ddmmyyyy]{datetime} \usepackage{microtype} \usepackage{antiqua} \author{My Name} \date{\today} \renewcommand{\contentsname}{Table des matières} [NO-DEFAULT-PACKAGES] [NO-PACKAGES]" ("\\section{%s}" . "\\section*{%s}") ("\\subsection{%s}" . "\\subsection*{%s}") ("\\subsubsection{%s}" . "\\subsubsection*{%s}") ("\\paragraph{%s}" . "\\paragraph*{%s}") ("\\subparagraph{%s}" . "\\subparagraph*{%s}")))) ``` So that when I want to create a new document in org-mode I just have to put : ``` #+TITLE: My Title #+LaTeX_CLASS: koma-article ``` However when I try to compile a document I get :`Unknown LaTeX class 'koma-article'`. I am not sure what I'm doing wrong here. Is there a way to load only these packages without having to specify then in the buffer using `#+LATEX_HEADER: \usepackage` ? # Answer As mentioned in the comments above, the latex commands need to be escaped. so this should work as expected.... ``` (add-to-list 'org-latex-classes '("koma-article" "\\documentclass[french, 11pt]{scrartcl} \\usepackage[utf8]{inputenc} \\usepackage[T1]{fontenc} \\usepackage{babel} \\usepackage[hidelinks]{hyperref} \\usepackage[ddmmyyyy]{datetime} \\usepackage{microtype} \\usepackage{antiqua} \\author{My Name} \\date{\\today} \\renewcommand{\\contentsname}{Table des matières} [NO-DEFAULT-PACKAGES] [NO-PACKAGES]" ("\\section{%s}" . "\\section*{%s}") ("\\subsection{%s}" . "\\subsection*{%s}") ("\\subsubsection{%s}" . "\\subsubsection*{%s}") ("\\paragraph{%s}" . "\\paragraph*{%s}") ("\\subparagraph{%s}" . "\\subparagraph*{%s}"))) ``` > 3 votes # Answer According with what you are describing, I would recommend you to escape all the backslashes (all the backslashes that appear between the "koma-article" and \[NO-DEFAULT-PACKAGES\]). Finally, you need to make sure that you have the Koma-Script ‘article’ class installed: https://www.ctan.org/pkg/scrartcl. > 1 votes # Answer Another way is to have an own latex header file, and input it at the very beginning of your file. ``` ("mybestreport" "\\input{/home/path/to/your/latex/header/header.tex}" ("\\chapter{%s}" . "\\chapter*{%s}") ("\\section{%s}" . "\\section*{%s}") ("\\subsection{%s}" . "\\subsection*{%s}") ("\\subsubsection{%s}" . "\\subsubsection*{%s}") ("\\fourthsection{%s}" . "\\fourthsection*{%s}") ("\\fifthsection{%s}" . "\\fifthsection*{%s}") ) ``` > 1 votes --- Tags: org-mode, org-export, latex ---
thread-62357
https://emacs.stackexchange.com/questions/62357
Overlay extending to the end of physical line
2020-12-18T11:15:35.643
# Question Title: Overlay extending to the end of physical line I'm trying to use overlay to highlight a whole line but for some reason my overlay stops at the end of the line (past the last character) instead of the end of the physical line (just before fringe). I'm certainly missing something obvious. Using the code below, `;; Test` is highlighted but I would have expected `;; Test` . ``` ;; Test (save-excursion (goto-char 0) (let ((beg (point-at-bol)) (end (min (point-max) (+ 1 (point-at-eol))))) (overlay-put (make-overlay beg end) 'face '(:background "#f0f0f0")))) ``` **Update** Answer given by @rpluim, I need to add a `:extend t` in the face definition. # Answer Starting in emacs-27 you can specify the `:extend t` attribute when creating the face, and the background will then extend to the right edge of the Emacs window. > 3 votes --- Tags: overlays ---
thread-22266
https://emacs.stackexchange.com/questions/22266
Backspace without adding to kill ring
2016-05-14T16:02:01.427
# Question Title: Backspace without adding to kill ring Using Crtl+Backspace or Ctrl+Del adds the deleted text to the kill ring. How can I prevent this from happening? I do not need to have every single piece of text sent to the kill ring when it gets deleted. Side question: What's the purpose of this default setting anyway? :) # Answer According to the documentation: > `<C-delete>` runs the command kill-word (found in global-map), which is an interactive compiled Lisp function in `‘simple.el’`. > > It is bound to `<C-delete>, M-d`. > > (kill-word ARG) > > Kill characters forward until encountering the end of a word. With argument ARG, do this that many times. Now, let's browse the source code: ``` (defun kill-word (arg) "Kill characters forward until encountering the end of a word. With argument ARG, do this that many times." (interactive "p") (kill-region (point) (progn (forward-word arg) (point)))) ``` Then, inside the documentation for the `kill-region` function we find: > Kill ("cut") text between point and mark. > `This deletes the text from the buffer and saves it in the kill ring`. The command \[yank\] can retrieve it from there. (If you want to save the region without killing it, use \[kill-ring-save\].) > > \[...\] > > Lisp programs should use this function for killing text. (To delete text, use `delete-region`.) Now, if you want to go further, this is some function you can use, for deleting without copying to kill-ring: ``` (defun my-delete-word (arg) "Delete characters forward until encountering the end of a word. With argument, do this that many times. This command does not push text to `kill-ring'." (interactive "p") (delete-region (point) (progn (forward-word arg) (point)))) (defun my-backward-delete-word (arg) "Delete characters backward until encountering the beginning of a word. With argument, do this that many times. This command does not push text to `kill-ring'." (interactive "p") (my-delete-word (- arg))) (defun my-delete-line () "Delete text from current position to end of line char. This command does not push text to `kill-ring'." (interactive) (delete-region (point) (progn (end-of-line 1) (point))) (delete-char 1)) (defun my-delete-line-backward () "Delete text between the beginning of the line to the cursor position. This command does not push text to `kill-ring'." (interactive) (let (p1 p2) (setq p1 (point)) (beginning-of-line 1) (setq p2 (point)) (delete-region p1 p2))) ; bind them to emacs's default shortcut keys: (global-set-key (kbd "C-S-k") 'my-delete-line-backward) ; Ctrl+Shift+k (global-set-key (kbd "C-k") 'my-delete-line) (global-set-key (kbd "M-d") 'my-delete-word) (global-set-key (kbd "<M-backspace>") 'my-backward-delete-word) ``` Courtesy of ErgoEmacs > 12 votes # Answer Since Emacs 24, without any configuration, you can delete any text without adding it to the kill ring by selecting it and then pressing `Backspace` or `Delete`. When the mark is active, these keys delete the region instead of just deleting the character before/after the cursor. That is, move to one end of the text you want to delete, press `Ctrl`+`Space`, move to the other end, and press `Backspace` (or `Delete`) do delete the highlighted region. Or move to one end, hold `Shift` while you use movement keys to go to the other end, and press `Backspace`. > 5 votes # Answer An alternative solution is to `advice` the functions you don't want affecting the kill-ring, in such a way that you'd save and restore the kill-ring when called interactively: ``` (defun my/call-interactively-inhibit-kill-ring (fun &rest args) "Call FUN interactively saving the kill-ring when called interactively. Otherwise call FUN with ARGS." (if (interactive-p) (let ((kill-ring '("dummy")) ; Dummy value in case FUN tries to append. (kill-ring-yank-pointer nil)) (call-interactively fun)) (apply fun args))) (defun my/inhibit-kill-ring-in (cmd) (advice-add cmd :around #'my/call-interactively-inhibit-kill-ring)) (my/inhibit-kill-ring-in 'backward-kill-word) (my/inhibit-kill-ring-in 'kill-word) ``` > 0 votes # Answer I had the same problem and solved it more easily this way: ``` (global-set-key (kbd "<backspace>") '(lambda () (interactive) (backward-delete-char-untabify 1 nil))) ``` Calling `(backward-delete-char-untabify 1 nil)` tells Emacs to backward-delete one char (that's the `1` parameter) and that it refrains from copying to the ring (that's the `nil` parameter). You need a lambda (i.e. anonymous) function because you're binding a function with parameters to a key. > -1 votes --- Tags: kill-ring, deletion ---
thread-62354
https://emacs.stackexchange.com/questions/62354
function that takes a command and a mode-map returning the bound string
2020-12-18T07:45:58.807
# Question Title: function that takes a command and a mode-map returning the bound string Is there a command ie: `get-bounded-string` that is available that performs this? ``` (defun no-op () nil) (define-key dired-mode-map (kbd "C-c C-7") 'no-op) ``` then ``` (get-bound-string dired-mode-map 'no-op) => "C-c C-7" ``` # Answer Emacs has a `substitute-command-keys` function, which takes a format string and substitutes occurrences of specific escape substrings according to their type. Specifically, it replaces `\\[<command>]` with the keybinding for `<command>` *in the context of the current keymap*. What you can do is run the function in the context of a temporary buffer with desired keymap set. It might look something like this: ``` (with-temp-buffer (use-local-map dired-mode-map) (substitute-command-keys "\\[no-op]")) ``` You could, of course, wrap the above in a function definition. > 1 votes # Answer You already accepted an answer as correct, but I interpreted your question differently, as wanting Elisp code that tells you what key(s) a given command is bound to in a given mode. If you're interested in that, `where-is-internal` will do it for you. For example, to find out what keys command `dired-mark` is bound to in Dired mode, use this: `(where-is-internal 'dired-mark dired-mode-map)` See the Elisp manual, node Scanning Keymaps. Interactively, you have command `where-is`, bound to `C-h w`. That tells you which keys a command is bound to in the *current buffer* (mode). > 2 votes --- Tags: key-bindings ---
thread-62363
https://emacs.stackexchange.com/questions/62363
Emacs org mode entitiespretty not complete
2020-12-18T18:44:39.457
# Question Title: Emacs org mode entitiespretty not complete This ``` #+STARTUP: entitiespretty ``` in my org mode buffer allows Latex/MathJax symbols to render in situ . . . almost. I type, e.g., `$\le$` and instantly the markup is replaced by the actual symbol. There are some symbols, however, that don't render -- although they do appear as expected in an export. This isn't a huge problem, but why does the buffer balk on, say, \`$\bot$) or $\mapsto$? # Answer Because they don't exist in the tables `org-entities` or `org-entities-user`. You can customize the latter and add them if you want. You need to figure out what to replace it with for LaTeX, HTML, ASCII, Latin1 and UTF8. Here's a possible definition for `\bot` although the Latin1 part could probably be improved: ``` #+begin_src emacs-lisp (add-to-list 'org-entities-user '("bot" "\\bot" t "&UpTee;" "_|_" "_|_" "⊥")) #+end_src ``` The doc for the variable says: ``` User-defined entities used in Org to produce special characters. Each entry in this list is a list of strings. It associates the name of the entity that can be inserted into an Org file as \name with the appropriate replacements for the different export backends. The order of the fields is the following name As a string, without the leading backslash. LaTeX replacement In ready LaTeX, no further processing will take place. LaTeX mathp Either t or nil. When t this entity needs to be in math mode. HTML replacement In ready HTML, no further processing will take place. Usually this will be an &...; entity. ASCII replacement Plain ASCII, no extensions. Latin1 replacement Use the special characters available in latin1. utf-8 replacement Use the special characters available in utf-8. If you define new entities here that require specific LaTeX packages to be loaded, add these packages to ‘org-latex-packages-alist’. ``` > 1 votes --- Tags: org-mode, latex, fonts, mathjax ---
thread-62351
https://emacs.stackexchange.com/questions/62351
Search and replace in evil mode
2020-12-18T07:00:03.140
# Question Title: Search and replace in evil mode I'm an emacs newbie and am using evil mode for text formatting. I have some text in the following format: ``` word1 = meaning with elaboration; word2 = simpler meaning; word3; word4 = much long explanation needed; ``` and want to wrap each of word1, word2, word3 etc.. into `\textif\textbf{word1}}`, `\textif\textbf{word2}}` etc. and transform the original text as ``` \textif{\textbf{word1}} = meaning with elaboration; \textif{\textbf{word2}} = simpler meaning; \textif{\textbf{word3}}; \textif{\textbf{word4}} = much long explanation needed; ``` In VIM, I verified separately that the following search+replace pattern applies the changes for `word2`, `word3` and `word4` (I know this pattern won't change `word1`) `:%s,;\s*\(\w*\),; \r\\textit\{\\textbf\{\1\}\},g` However, this doesn't work in emacs. All I see is **Ex: Syntax error** Does vim-style search+replace work in emacs? Is there a way to apply the same search+replace in emacs? # Answer > 2 votes Evil's vim-style search-replace does work, but you have to modify it slightly: `:%s/; \(\w+\)/;\n\\textit{\\textbf{\1}}/g` will perform the replacement you want (this won't affect word1, but you've already mentioned that). You have to use `/` to separate the `s`, match, replacement and the global `g`. `\s*` doesn't match the whitespace characters as expected. --- Tags: evil, text-editing ---
thread-62262
https://emacs.stackexchange.com/questions/62262
"Cartograph" font has too much spacing
2020-12-13T22:03:04.100
# Question Title: "Cartograph" font has too much spacing This is what happened when I set my default font to a new font I bought called Cartograph. Looks cool, but I'm not sure I could get used to it. Anyone know what might have happened? It's an otf font. Looks normal in LibreWrite and gedit, BTW. Here's the init entry ``` '(default ((t (:inherit nil :stipple nil :inverse-video nil :box nil :strike-through nil :overline nil :underline nil :slant normal :weight normal :height 143 :width normal :foundry "UKWN" :family "Cartograph CF")))) ``` # Answer > 0 votes Reading through this and following the advice of Arch Stanton in the above comments -- although I didn't understand his instructions > There should be an array of numbers somewhere. The last two values should be in the surroundings of your font size, 14. I did recompile Emacs 27.1 with cairo ``` ./configure --with-cairo ``` and the problem is solved. --- Tags: fonts ---
thread-62371
https://emacs.stackexchange.com/questions/62371
A way to check if "(current-kill 0)" will run onto an error before it happens
2020-12-18T22:33:18.927
# Question Title: A way to check if "(current-kill 0)" will run onto an error before it happens I have an Elisp part involving `(current-kill 0)` to copy the current clipboard content into a variable. This works flawlessly as long as the kill-ring has content. However, if I just started the computer and did not copy anything yet (or use the command-line version of Emacs), running that script runs into the error "Kill ring is empty". Trying `(cond (kill-ring) my_code)` seems dodgy since when starting Emacs and before `(current-kill 0)` is executed, `kill-ring` is actually nil as per `C`-`h` `v` `kill-ring`. Is there a reliable way to find out if the clipboard actually holds content without getting the code running onto an error? # Answer > 1 votes Are you asking *how to check* whether the `kill-ring` is empty? If so, just test whether `kill-ring` is non-`nil`: ``` (when kill-ring ...) ``` Or are you asking how to avoid the error that it's empty? If so, just put something in it, to start with, using `kill-new`. For example: ``` (kill-new "DUMMY") ``` You can also use `ignore-errors` to just ignore that error or all errors: ``` (ignore-errors ;; Code that expects a non-empty `kill-ring` ) ``` --- Tags: error-handling, kill-ring, conditionals ---
thread-62373
https://emacs.stackexchange.com/questions/62373
How can I run a subprocess with emacs --script
2020-12-19T01:19:14.113
# Question Title: How can I run a subprocess with emacs --script I'm trying to write a script using `emacs --script` and in it I am using `start-process`, because I want to use `set-process-filter`. The following does nothing if run as a script: ``` #!/usr/bin/env -S emacs -Q --script # -*- mode: emacs-lisp; lexical-binding: t; -*- (let ((p (start-process "subcommand" nil "notify-send" "Hello!"))) (set-process-sentinel p (lambda (process signal) (start-process "notify" nil "notify-send" "Hello again!"))) (set-process-filter p (lambda (process output) (message output))) ;; (while t) ) ``` However, if I run that same elisp in my gui emacs I get to notifications (one for hello and one for hello again). I tried to solve this using a no-op loop (commented out), but that only allowed the first hello to be sent out. Basically, I want emacs to wait for it's subprocess to finish before exiting. I'm not sure where to go from here. Any ideas on how I can get something like this working? # Answer > 2 votes Basically, Emacs exits before the subprocess has exited. All you have to do is delay the exit until the subprocess has exited. Since Emacs does not have anything useful to do, you can have it sleep for a while. The following sleeps in a loop until the subprocess does not appear in the process list any longer: ``` #!/usr/bin/env -S emacs -Q --script # -*- mode: emacs-lisp; lexical-binding: t; -*- (let ((p (start-process "subcommand" nil "notify-send" "Hello!"))) (if (memq p (process-list)) (message "YES")) (set-process-sentinel p (lambda (process signal) (start-process "notify" nil "notify-send" "Hello again!"))) (set-process-filter p (lambda (process output) (message output))) (while (memq p (process-list)) (sleep-for 1)) ) ``` The loop you had, `(while t)`, was keeping emacs busy and not allowing it to process the sentinel for the subprocess. The loop also never exited, so you have to kill emacs to make it stop, at which point emacs cannot process the sentinel for the subprocess any longer, so you lost the second message. --- Tags: subprocess, command-line-arguments, script ---
thread-62375
https://emacs.stackexchange.com/questions/62375
where to find a list of all the builtin functions that have been implemented in C?
2020-12-19T02:35:55.240
# Question Title: where to find a list of all the builtin functions that have been implemented in C? Is there a list somewhere or a command that can be run to output all the functions that have been implemented in C? # Answer > 5 votes You can use `mapatoms` to iterate over all known symbols and inspect their properties. A built-in function satisfies both `symbol-function` and the value of that satisfies `subrp`: ``` (let (subrs) (mapatoms (lambda (sym) (when (and (symbol-function sym) (subrp (symbol-function sym))) (push sym subrs)))) subrs) ;=> (charset-id-internal memory-use-counts string-make-unibyte % * + - / set-window-new-pixel minibuffer-contents-no-properties get-unused-category < ...) ``` --- Tags: builtin ---
thread-19518
https://emacs.stackexchange.com/questions/19518
Is there an idiomatic way of reading each line in a buffer to process it line by line?
2016-01-13T20:23:15.453
# Question Title: Is there an idiomatic way of reading each line in a buffer to process it line by line? In Python I'd do the following to process a file line by line: ``` with open(infile) as f: for line in f: process(line) ``` Trying to look up how to do the same in elisp (with buffers instead of files), I found no obvious way. (What I want to end up with is two ordered datastructures of lines, one with all the lines matching a regex, the other containing those that did not match.) # Answer There are various ways to do it. Kaushal's way can be made a good bit more efficient, with: ``` (goto-char (point-min)) (while (not (eobp)) (let ((line (buffer-substring (point) (progn (forward-line 1) (point))))) ...)) ``` But in Emacs it is much more customary to work on the buffer rather than on strings. So rather than extract the string and then work on it, you'd just do: ``` (goto-char (point-min)) (while (not (eobp)) ... (forward-line 1)) ``` Also, if you want to operate on a region rather than on the whole buffer, and if your "operate" includes modifying the buffer, it's frequent to do it backwards (so that you don't get bitten by the fact that the "end" position of your region moves every time you modify the buffer): ``` (goto-char end) (while (> (point) start) ... (forward-line -1)) ``` > 29 votes # Answer I don't know of any idiomatic way but I came up with this: ``` (defun my/walk-line-by-line () "Process each line in the buffer one by one." (interactive) (save-excursion (goto-char (point-min)) (while (not (eobp)) (let* ((lb (line-beginning-position)) (le (line-end-position)) (ln (buffer-substring-no-properties lb le))) (message ">> %s" ln) ; Replace this with any processing function you like (forward-line 1))))) ``` > 7 votes # Answer I think the following is as idiomatic as it can get: ``` (dolist (line (split-string (buffer-string) "\n")) ... process line here ... ) ``` EDIT: Here is another solution with `loop` in place of `dolist`, and which also classifies the lines according to whether or not they match your regular expression: ``` (loop for line in (split-string (buffer-string) "\n") if (string-match "your-regexp" line) collect line into matching else collect line into nonmatching finally return (cons matching nonmatching) ) ``` If you set a variable to the output of this function, say `(setq x (loop ...))`, then the desired list of matching lines will be found in `(car x)`, with the list of nonmatching lines being `(cdr x)`. > 5 votes # Answer Just a note to Stefan's answer: ``` (goto-char (point-min)) (while (not (eobp)) ... (forward-line 1)) ``` This will only work if the last line of the file is empty. A simple fix for that would be: ``` (while (not (save-excursion (end-of-line) (eobp))) ``` > 0 votes --- Tags: mapping ---
thread-62211
https://emacs.stackexchange.com/questions/62211
Find/replace all files in a directory? (recursively)
2020-12-10T23:13:33.127
# Question Title: Find/replace all files in a directory? (recursively) One task I still end up using an IDE for is project wide find-replace. The steps are as follows. * Select a directory to replace in (this could default to the projects root). * Select the file extensions to match (this could initialize from other extensions variables, eg `ffip-patterns`, `projectile-other-file-alist`). * Test the replacement, to see what it does. * Show all replacements, giving the option to skip some. * Execute or cancel the replacements for **all files**. This is something I'm used to from an IDE, is there anything that gives similar functionality in Emacs. --- Note that I've seen `dired` can almost do this, it's not too far from what I'm after, but requires opening and accepting changes in **every file**, the proceeding steps are a little cumbersome too, although I suppose they could be streamlined. Reference: https://www.gnu.org/software/emacs/manual/html\_node/efaq/Replacing-text-across-multiple-files.html # Answer I'm using `projectile-replace` `projectile-replace-regexp` for this purpose. If the directory which you want to change is not git project still you can use this functions after creating .projectile file in this directory. Don't forget to save after that via `projectile-save-project-buffers`. > 2 votes # Answer Use `counsel-git-grep` from package `counsel`, API definition, ``` (defun counsel-git-grep (&optional initial-input initial-directory cmd) ``` See its second parameter. After grepping by calling `counsel-git-grep`, * `M-x ivy-occur` (or press `C-c C-o`) to export candidates to a buffer * `M-x ivy-wgrep-change-to-wgrep-mode` (or press `w`) to switch to `wgrep-mode` * Edit text in buffer * `M-x wgrep-finish-edit` (or press `C-c C-c`) to finalize the changes See https://sam217pa.github.io/2016/09/11/nuclear-power-editing-via-ivy-and-ag/ for some use case. In the article, the backend is `ag` instead of `git-grep`, but UI is exactly same. There are other grep backends `counsel` supports. > 1 votes # Answer You say: > Note that I've seen dired can almost do this, it's not too far from what I'm after, but requires opening and accepting changes in every file... Yes, every file you marked is visited. But it doesn't require you to accept each change individually, as far as I know. If you use either `dired-do-find-regexp-and-replace` (`Q`) or `dired-do-query-replace-regexp` the behavior is that of regular `query-replace-regexp`, for the most part. In particular, you can use `!` to replace all subsequent occurrences in the current file. --- And if you use Dired+ then you have a command similar to `dired-do-query-replace-regexp`, but that acts on files marked in the current listing and in subdirs, *recursively*: `diredp-do-query-replace-regexp-recursive`. > 1 votes --- Tags: replace ---
thread-62362
https://emacs.stackexchange.com/questions/62362
How to check if a hydra is displaying?
2020-12-18T17:15:26.353
# Question Title: How to check if a hydra is displaying? If a hydra is opened, how do we check programmatically that it is actually open and displaying? # Answer It's possible to check for a variable `hydra-curr-map`. This will return `nil` if the hydra is hidden or the keymap that it's using given by `<hydra>/keymap`. ie. ``` ;; define hydra (defhydra test-hydra ....) ;; open test-hydra (test-hydra/body) (eq hydra-curr-map test-hydra/keymap) => t ``` > 3 votes --- Tags: hydra ---
thread-62388
https://emacs.stackexchange.com/questions/62388
Showing returned values in the same buffer
2020-12-20T09:43:02.340
# Question Title: Showing returned values in the same buffer When I evaluate an expression with `C-x C-e`, I see the result returned by that expression in the minibuffer, for a while. Can I have that returned value written in the same buffer where the evalued expression is? How? # Answer The emacs way is to ask emacs: `C-h k C-x C-e` ``` C-x C-e runs the command eval-last-sexp (found in global-map), which is an interactive compiled Lisp function in `elisp-mode.el'. It is bound to C-x C-e. (eval-last-sexp EVAL-LAST-SEXP-ARG-INTERNAL) Probably introduced at or before Emacs version 24.4. Evaluate sexp before point; print value in the echo area. Interactively, with a non `-' prefix argument, print output into current buffer. ``` Read that last line. Do: `C-u C-x C-e` and observe the result. > 8 votes --- Tags: eval-expression ---
thread-62391
https://emacs.stackexchange.com/questions/62391
Hook to run on completion of exporting org to html
2020-12-20T16:08:23.667
# Question Title: Hook to run on completion of exporting org to html I've defined a custom command with `shell-interpreter` to rsync files to my VPS... ``` (defun rsync_html () (interactive) (with-shell-interpreter :path "~/org" :interpreter "bash" :form (message "rsync org html output to OVH") (message (shell-command-to-string "rsync -av ~/org/*.html ovh:~/www/. --exclude='*.org'")))) ``` It works, I can run `M-x rsync_html` and the files are get copied over. What I'd now like to do though is have a hook that runs after compiling .org files to HTML that runs this command. I've looked through Documentation for Org hooks, commands and options and found the `org-html-export-as-html` which I am guessing is the command run on export. So I've written... ``` (add-hook 'org-html-export-as-html 'rsync_html) ``` ...but it doesn't seem to work. Before reaching this point I had already tried `(add-hook 'org-babel-after-execute-hook 'rsync_html)` but this tried syncing after processing every chunk which whilst it achieved the desired result because it ran after the last chunk had processed is wasteful/inefficient (particularly if the SSH key isn't loaded into the keyring). I'm unsure how to go about investigating why the hook isn't picked up, perhaps I've chosen the wrong command to hang my hook on but I think its right (if not I'm stumped as to how to see what it should be). Advice and pointers welcome. Thanks. # Answer There is no such hook, but you can write a function that does what you want and execute that instead: ``` (defun ndk/org-export-to-html-and-rsync () (interactive) (org-export-as 'html) (rsync-html)) ``` You can even bind to a key so that you can execute it easily: ``` (define-key org-mode-map (kbd "C-c z") #'ndk/org-export-to-html-and-rsync) ``` Notes: * Hooks are usually added to a function in the *middle* of the code: that way, they allow you to influence the way the function operates without having to rewrite it. That mitigates the need to write many functions, mostly identical except for one little detail in the middle. So they are a way to customize the behavior of a function. * Another way to customize a function is through the advice mechanism: that allows you to run something before, or after, or around a given function, but preserve the name (and e.g. any keybindings that call that function). You could use that here, but it is simpler to just define a new function that composes the two functions that you want to run. * A more general mechanism to do the export and then e.g. send the results to a web server, is the Publishing mechanism that Org mode provides. If your setup becomes more complicated in the future, you might want to investigate that mechanism. * Instead of running shell commands to rsync things to a remote machine, you can use Remote Files through the Tramp mechanism that Emacs provides. The Org mode publishing link above contains examples of that usage. * The usual convention of naming things in Emacs Lisp uses dashes, rather than underscores: `rsync-html` rather than `rsync_html`. Finally, even though they are not needed in this case, here's how I go about finding hooks when I need them. The method depends on the *convention* that hook variables are named `<mumble>-hook` (there are exceptions, mostly for historical reasons, but almost all modern code adheres to that convention). The other important convention is that packages use a prefix for all their interfaces (functions and global variables); e.g. Org mode uses the prefix `org-`. Emacs is self-documenting: you can ask it to give you a lot of information, so you don't need to chase down manuals (at least at first; when you are ready to dig deeper, of course the manuals are indispensable). As an example, let's discover some hooks (N.B. Hooks are *variables*: a hook variable has a value which is a *list* of *functions* \- or `nil` which is the empty list; when a function *runs* the hook, all the functions in the list are evaluated, one after the other.) We can ask Emacs for information about any variable, but in this case we want to ask about a hook variable: `C-h v org-mode-hook RET` \- that gives us the doc string of the `org-mode-hook` variable. If I'm looking for a hook but I don't know its name (or if it even exists), then I can use the documentation facility of Emacs in conjunction with another facility that Emacs provides: *completion*. If I say `C-h v org--hook TAB` then I get a completion buffer containing a list of all the variables that have names of the form `org-<mumble>-hook`: I use this all the time to get the list, eyeball it for candidates and then zero in on the most likely ones: select one to see its doc string. Lather, rinse, repeat for any others in the list. I can be more selective to begin with: `C-h v org-export--hook` will give me all the hooks of the form `org-export-<muble>-hook`; the results here are paltry: just three hooks (that look unpromising for what you wanted to do): `org-export-before-parsing-hook org-export-before-processing-hook org-export-stack-mode-hook` so let's see if there are any HTML-related ones: `C-h v org-html--hook TAB` \- no results on that one, so it doesn't look as if there's a hook to do what you want. As noted, the fact that there is no such hook is no limitation in this case: hooks are for a different purpose. But I hope that the *method* of discovering hooks will be useful to you in the future. For completeness, here are a few more of the "self-documenting" capabilities of Emacs: you can use `C-h f <function-name> RET` to get the doc string of a function, but also to find functions using completion the same way. And do `C-h ?` to get help on help: what else you can type after `C-h` to ask Emacs for useful information. > 1 votes --- Tags: org-mode, hooks, html ---
thread-57585
https://emacs.stackexchange.com/questions/57585
Emacs keyboard macros ? all over
2020-04-04T23:36:56.357
# Question Title: Emacs keyboard macros ? all over I have used keyboard macros for a long time, but moved between companies, systems, and various machines over my career. I used to be able to record macros and `insert-kbd-macro` into my `.emacs` file and they look readable and concise: ``` (fset 'kc-del-blank-lines "M-x flush-lines return ^\s-*$ return") ``` On my latest, cygwin install (windows 10), the same macro gets created like: ``` (fset 'kc-rmbl [?\M-x ?f ?l ?u ?s ?h tab return ?^ ?\\ ?s ?- ?* ?$ return]) ``` Ok, the latter uses a vector (`[...]`) instead of a string (`"..."`). How can I get this install to produce the former results. # Answer `insert-kbd-macro` can insert a number of different forms, but ultimately the definition of the macro can be either a string, a vector, or a lambda. If the macro definition is a string, then it outputs the form you are used to seeing. If it's a vector, then it outputs the form you now get. If the macro definition is a lambda, then the body of the macro will be printed as a call to `kmacro-lambda-form` which builds the same lambda. The last change to the `name-last-kbd-macro` was commit 4f779ff8 in 2017, when it was removed and made an alias of `kmacro-name-last-macro`. `kmacro-name-last-macro` has since 2004 always created a definition which is a lambda containing a vector, like this: ``` (lambda (&optional arg) "Keyboard macro." (interactive "p") (kmacro-exec-ring-item '([19 63 return 102 111 111 5 right] 0 "%d") arg)) ``` (This is the lambda form that `insert-kbd-macro` checks for). Prior to this change `name-last-kbd-macro` simply fset your choosen name with the value of `last-kbd-macro`. `last-kbd-macro` has been a vector of keys since at least 1995. However, in 1999 in commit f8a4db7d code was added to `start-kdb-macro` that checked to see if the current value of `last-kbd-macro` was a string. The comment says "Check the type of last-kbd-macro in case Lisp code changed it.", so perhaps there was some lisp code running around which replaced the value of `last-kbd-macro` with a string instead of a vector. However, this particular code is only used when appending new keystrokes to the end of the most recently-recorded macro, and it converts the string back into a vector. There's just one last place to look: `end_kbd_macro` sets `last-kbd-macro` to the newly-defined macro using a function `make_event_array`. This function creates either a string or a vector. It only creates a string if all the characters are less than 128 after masking off the CHAR\_META bit "and all the bits above it. It's done this since the code was introduced in commit 7146af97 in 1991, so I suppose the comments about checking the type "in case Lisp code changed it" was somewhat mistaken. Here's the code from alloc.c, line 3672: ``` for (i = 0; i < nargs; i++) /* The things that fit in a string are characters that are in 0...127, after discarding the meta bit and all the bits above it. */ if (!FIXNUMP (args[i]) || (XFIXNUM (args[i]) & ~(-CHAR_META)) >= 0200) return Fvector (nargs, args); ``` However, I notice that CHAR\_META *is* the highest bit; all the other modifier bits have lower values than CHAR\_META. CHAR\_META has had the highest value since the constant was introduced in 1993, but prior to that it's really hard to tell. The check against CHAR\_META in `make_event_array` was also added in 1993 (in commit 736471d1); prior to that it accepted any character less than 256. So, I conclude that you either had a really old version of Emacs, or that your memory is faulty, or that there's something else going on (such as modifications to the OSX port of Emacs that you used to use). Emacs has for at least the last 27 years output virtually all keyboard macros as vectors, unless they contained only ascii characters with no modifier keys, and only if the macro had not been named with `kmacro-name-last-macro` (because then it would output the form evaluating to a lambda). You could try patching `make_event_array` to use CHAR\_ALT instead of CHAR\_META, so that it ignores all modifier keys, and see if that improves the situation at all. I'd try it myself, but my emacs build is slightly broken at the moment. > 1 votes --- Tags: keyboard-macros ---
thread-59766
https://emacs.stackexchange.com/questions/59766
How to disable keybinding (`\C-o`) in ido-find-file?
2020-07-21T18:44:41.727
# Question Title: How to disable keybinding (`\C-o`) in ido-find-file? I want to disable key-binding `\C-o` on `ido-find-file`. If I press it generates `^J` and completion does not completed so I want to disable it. I have tried following but it did not work. ``` (defun ido-common-completion-map () "Add my keybindings for Ido." (define-key ido-common-completion-map (kbd "\C-o") 'nil)) (add-hook 'ido-setup-hook #'ido-common-completion-map) ``` --- I have followed for ido-wiki and https://emacs.stackexchange.com/a/3730/18414 > ``` > (defun ido-disable-line-truncation () > (set (make-local-variable 'truncate-lines) nil)) > (add-hook 'ido-minibuffer-setup-hook #'ido-disable-line-truncation) > (defun ido-define-keys () ;; C-n/p is more intuitive in vertical layout > (define-key ido-completion-map (kbd "C-n") 'ido-next-match) > (define-key ido-completion-map (kbd "C-p") 'ido-prev-match)) > (add-hook 'ido-setup-hook 'ido-define-keys) > > ``` # Answer > 1 votes Please follow same approach which I mention in https://emacs.stackexchange.com/a/55607/8426 call `helpful-function` `ido-find-file` It opens clickable bufferm In this buffer, you have to click `C-o` than you will learn which key-map that you are interacting. Next screen after click will tell you which in which map that you have to change. Big possible answer is for you(This keybinding somehow was not defined in my emacs I am not sure): ``` (define-key ido-buffer-completion-map (kbd "\C-o") nil) (define-key ido-file-completion-map (kbd "\C-o") nil) ``` # Answer > 0 votes That key is defined on `ido-file-completion-map`. --- Tags: key-bindings, ido ---
thread-61840
https://emacs.stackexchange.com/questions/61840
How to eval sexp in clojure-mode with cider and write result in current buffer
2020-11-20T08:22:40.287
# Question Title: How to eval sexp in clojure-mode with cider and write result in current buffer For example I have the code: ``` (println "foo") ``` With `cider-pprint-eval-last-sexp-to-comment` I can eval the code and get ``` (println "foo") ;; nil ``` in clojure buffer and also it print `foo` in cider-repl buffer. I would like to get something like this in the current buffer: ``` (println "foo") ;; nil foo ``` How can I do this? # Answer You can use `with-out-str` to capture the output into a string. ``` user> (with-out-str (print "foo")) "foo" ``` Knowing that you can take the `cider-pprint-eval-last-sexp-to-comment` function, copy/paste it and make a small change. ``` (define-key cider-mode-map (kbd "C-c C-p") (lambda () (interactive) (let* ((insert-before nil) (bounds (cider-last-sexp 'bounds)) (insertion-point (nth (if insert-before 0 1) bounds)) (comment-postfix (concat cider-comment-postfix (if insert-before "\n" "")))) (cider-interactive-eval (concat "(with-out-str " (cider-last-sexp) " )") (cider-eval-pprint-with-multiline-comment-handler (current-buffer) (set-marker (make-marker) insertion-point) cider-comment-prefix cider-comment-continued-prefix comment-postfix) bounds (cider--nrepl-print-request-map fill-column))))) ``` This function prints the captured output instead of the value. If you use it on something that doesn't write to `*out*` it will print the empty string. > 2 votes --- Tags: cider ---
thread-62400
https://emacs.stackexchange.com/questions/62400
Emacs' C-tab seems without effect on my server through ssh
2020-12-21T11:43:23.873
# Question Title: Emacs' C-tab seems without effect on my server through ssh (Emacs 27.1) On my local machine `<C-tab>` is linked to `other-window` and works well: `.emacs.d/init.el`: ``` (global-set-key (kbd "<C-tab>") 'other-window) ``` When I install Emacs on a (Debian10-based) server, the same configuration fails. I access Emacs through (LXTerminal) `ssh`. `<C-tab>` does nothing (but calling `M-x other-window` works, as well as `C-x o`, the default shortcut) : no error message, no warning. When starting Emacs, no warning message appears in the `*Messages*` buffer. On my server and on my local machine, `C-h k TAB` returns: ``` TAB runs the command indent-for-tab-command (found in global-map), which is an interactive compiled Lisp function in ‘indent.el’. It is bound to TAB. (indent-for-tab-command &optional ARG) [...] ``` On my local machine, `C-h k <C-tab>` returns: ``` <C-tab> runs the command other-window (found in global-map), which is an interactive compiled Lisp function in ‘window.el’. It is bound to <C-tab>, C-x o. (other-window COUNT &optional ALL-FRAMES) [...] ``` On my server, `C-h k <C-tab>` returns: ``` TAB runs the command indent-for-tab-command (found in global-map), which is an interactive compiled Lisp function in ‘indent.el’. It is bound to TAB. (indent-for-tab-command &optional ARG) [...] ``` See a similar problem with iTerm here and a related post here. --- This is the way I compile Emacs: ``` sudo apt install -y build-essential git apt build-dep -y emacs25 git clone --depth 1 --branch emacs-27 https://git.savannah.gnu.org/git/emacs.git cd emacs ./autogen.sh ./configure make make install cd .. emacs --version ``` # Answer That's correct. Any time you run Emacs inside a terminal, whether ssh is involved or not, you lose the ability to type a control-tab. There is simply no way for the terminal emulator to encode that control-tab was pressed, so all it can send is the tab. Some terminal emulators can be configured to send additional escape sequences for some keys, and you can then add keybindings to Emacs for those escape sequences. Otherwise there are only the 32 ASCII control characters available. That gives you control plus A through Z and the punctuation characters @\[\]^\_. I would recommend running the Emacs GUI locally and then using TRAMP to access files over ssh. https://www.gnu.org/software/tramp/#Using-ssh-and-plink > 2 votes --- Tags: key-bindings, terminal-emacs, term ---
thread-58871
https://emacs.stackexchange.com/questions/58871
Create yasnippet placeholder in lisp expression
2020-06-02T22:17:27.347
# Question Title: Create yasnippet placeholder in lisp expression I am trying to write a snippet to generate different python based on which directory I am in, as in some directories, I am using an older version of python. The snippet is ``` # key: log # name: logger # -- `(if (string-match "/projects/old" default-directory ) "logger.info('$1: {}'.format($1))" "logger.info(f'$1: {$1}')" ) ` ``` This sort of works. It correctly figures out the new/old problem, but yasnippet is not paying attention to the placeholders. An older version using just ``` "logger.info('$1: {}'.format($1))" ``` processed the placeholders as expected, but obviously did not generate both forms. What do I do to enable placeholders inside the return value of a lisp expression? # Answer This was answered on the gitlab site. Duplicating it here in case someone finds this page first. > Yes, yasnippet doesn't support interpreting expanded strings in snippet syntax. I suggest making a # type: command instead: ``` # key: log # name: logger # type: command # -- (yas-expand-snippet (if (string-match "/projects/old" default-directory ) "logger.info('$1: {}'.format($1))" "logger.info(f'$1: {$1}')")) ``` > 0 votes --- Tags: yasnippet ---
thread-18000
https://emacs.stackexchange.com/questions/18000
What linux terminal app is compatible with emacs keybindings?
2015-11-11T12:58:05.103
# Question Title: What linux terminal app is compatible with emacs keybindings? I am using terminal Emacs (`emacs -nw`). Gnome terminal doesn't behave well with it (key bindings break), and KDE's Konsole is even worse. Surprisingly, when I ssh from a windows machine the behavior is much better. Which terminal apps work out of the box without any tweaking for keybindings and mouse support? # Answer > 4 votes No terminal emulator will *default* to supporting all of the key sequences you're asking about, because they are emulating terminals which did not support those sequences. Furthermore, the only emulator I'm aware of which is even *capable* of supporting all the key sequences Emacs recognises is Thomas Dickey's xterm, and configuration is very much non-trivial (I've failed to get it working on the occasions I've tried). (You can, however, get a *subset* of the extended sequences with a fairly minimal config; see the links below.) If anyone does have a working configuration for the fully-extended sequences, I would love to know the details! Here are a couple of related answers: **Edit:** Gilles' answer in the thread Dan has linked to discusses some more recent developments, and looks extremely interesting at first glance. # Answer > 3 votes If you're willing to install an Emacs package and configure your terminal, I wrote an Emacs package which can teach Emacs and terminals how to properly recognize all PC keyboard keys and modifier key combinations: https://github.com/CyberShadow/term-keys Currently, the list of terminal emulators that can be configured with `term-keys` is xterm, urxvt (rxvt-unicode), Konsole/Yakuake, the Linux console, and st. # Answer > 1 votes I used suckless' st and rxvt-unicode in the past with `emacs -nw`, both worked well with no issue. They are both light on resources. St is customizable through its config.h (requiring compilation at every edit, though). Rxvt is customizable through ~/.Xresources. # Answer > 0 votes xterm works great (actually I use uxterm), but I don't usually run emacs inside of it. If you're sshing into another machine to run emacs and edit files there you might consider running emacs locally and using TRAMP mode instead. You can then run emacs as a normal X application rather than with -nw, and not have to worry about the terminal. # Answer > 0 votes Check Spacemacs keybindings, https://develop.spacemacs.org/doc/DOCUMENTATION.html#leader-key If you use evil and leader key, Emacs will work out of box in any terminal. --- Tags: key-bindings, terminal-emacs, term ---
thread-10785
https://emacs.stackexchange.com/questions/10785
Get list of active minor modes in buffer
2015-04-19T22:42:46.273
# Question Title: Get list of active minor modes in buffer How get a list of active minor modes in current buffer? Docs `(info "(elisp)Minor Mode Conventions")` say: ``` Define a variable whose name ends in ‘-mode’. We call this the "mode variable". The minor mode command should set this variable. The value will be ‘nil’ if the mode is disabled, and non-‘nil’ if the mode is enabled. The variable should be buffer-local if the minor mode is buffer-local. ``` I ended with: ``` (dolist (m minor-mode-list) (when (symbol-value m) (push m modes))) ``` `describe-mode` sources have notes that: ``` ;; Older packages do not register in minor-mode-list but only in ;; minor-mode-alist. ``` I don't know if that still valid point... # Answer > 2 votes I tested the `(mapcar #'car minor-mode-alist)` solution, but its length doesn't change after I disable a minor mode (while `M-x describe-mode` reflects this). Moreover, it seems inaccurate as I can't find some minor-modes listed by `M-x describe-mode`. I tried the package manage-minor-mode which allows users to enable/disable a minor-mode through an interface. `manager-minor-mode` doesn't have the issues aforementioned and here is the function it uses to look up active minor-modes: ``` (defun manage-minor-mode--active-list () "Get a list of which minor modes are enabled in the current buffer." (let ($list) (mapc (lambda ($mode) (condition-case nil (if (and (symbolp $mode) (symbol-value $mode)) (setq $list (cons $mode $list))) (error nil))) minor-mode-list) (sort $list 'string<))) ``` # Answer > 19 votes If you're just looking to see what minor modes are being used in a buffer, but don't need to use the list programmatically use: `M-x describe-mode` This command will open a new buffer that begins with a full list of your minor modes, as well as giving a brief description of the major modes, and any parent modes that may have been run. # Answer > 8 votes Try this: ``` (mapcar #'car minor-mode-alist) ``` In fact, you will find that this value often differs from `minor-mode-list`. --- Tags: minor-mode ---
thread-62306
https://emacs.stackexchange.com/questions/62306
How do I make Tramp stop mangling my PATH?
2020-12-16T12:55:59.123
# Question Title: How do I make Tramp stop mangling my PATH? Tramp is very tenacious in overriding the PATH setting of a remote machine. How can I completely disable this, so that Tramp's PATH is identical to what I get when I manually log in with ssh on the terminal? The `~/.bashrc` in my remote machine looks as follows: ``` export PATH1=$PATH # activate some Python virtualenvs, etc... export PATH2=$PATH ``` I want the final PATH to be PATH2. The closest I can get to that is when setting `tramp-remote-path` to the value `'(tramp-own-remote-path)`, in which case my PATH ends up being identical to PATH1. (I'm checking this by doing `M-x compile RET env RET` while editing a remote file.) One interesting solution (with other applications as well) would be to stipulate, as a directory or connection-local variable, an additional rc file on the remote machine that is sourced every time Tramp connects. Is this possible at all? # Answer > 1 votes Short solution: add all PATH-related settings to `~/.profile` instead of `~/.bashrc`, and make sure the former is `sh`-compatible. # Answer > 0 votes Interesting idea. I have added it to the TODO list of Tramp. If you want to discuss further, I invite you to the `<tramp-devel@gnu.org>` mailing list. SX is not intended for longer discussions. --- Tags: tramp, ssh ---
thread-62419
https://emacs.stackexchange.com/questions/62419
What is causing Emacs remote shell to be slow on completion?
2020-12-22T19:57:55.820
# Question Title: What is causing Emacs remote shell to be slow on completion? So basically I am doing the following: * Opening a dired buffer with tramp on a remote. * Opening a shell on the remote (`M-x shell`) Then if I try for example to type any command such as `ls -la` the prompt will display `l` and then take something like 10 seconds to display the remaining input. If I `C-g` when the prompt is stuck at `l` then the hang time will disappear, and the remaining input will be directly displayed. I believe this could be a completion problem, for some reason from my config emacs would be searching for stuff on the remote. As another thread mentioned I tried disabling (global-projectile-mode). I also have company installed. The hard thing for debugging is that no output is displayed in messages. Any ideas on what may be causing this hang time? # Answer > 1 votes Ok so this does the trick (disabling company mode on remote shells): How can I disable company-mode in a shell when it is remote? ``` (defun my-shell-mode-setup-function () (when (and (fboundp 'company-mode) (file-remote-p default-directory)) (company-mode -1))) (add-hook 'shell-mode-hook 'my-shell-mode-setup-function) ``` --- Tags: tramp, shell, completion, performance, company ---
thread-62408
https://emacs.stackexchange.com/questions/62408
Getting consistent colors for terminal and GUI emacs
2020-12-22T01:35:57.203
# Question Title: Getting consistent colors for terminal and GUI emacs I've noticed that color definitions on the terminal and the GUI are not consistent. For example on the GUI, there is a color `DarkOrchid2` defined, however this is not there for the terminal. Instead, the similar color is defined as `color-99` and the named colors are not supported. Is there a way to get the colors consistent? # Answer That's correct. All applications running inside a terminal are at the mercy of what colors the terminal emulator chooses to use. All Emacs can do is ask that some characters be rendered in color 3, and others in color 12. The terminal emulator has a palette of colors that it uses, and this palette is often configurable. You should consult the documentation for your terminal emulator to see how to change that configuration. > 2 votes --- Tags: colors ---
thread-62418
https://emacs.stackexchange.com/questions/62418
How to change "tramp-default-remote-shell" (or any of its descendants)
2020-12-22T19:52:57.907
# Question Title: How to change "tramp-default-remote-shell" (or any of its descendants) Whenever I use the `/ssh:` directive and later open a shell (`M-x` `shell`) while still looking at the remote file/directory, on the remote end it used to open "/bin/bash" and all I had to do was to remove the current path to that file (point is already conveniently placed). Fairly recently, however, (possibly with the introduction of v27.1) the suggested shell is "/bin/sh" and I need to additionally change it back manually to "/bin/bash" every time I run it. While I am the sole user of the computer, I take it that editing "tramp.sh.el.gz" is still not recommended as it may be overwritten by any coming updates. Is there a way to either change the value for `tramp-default-remote-shell` or any of its derivatives to use "/bin/bash" by the time Emacs has started (user `init.el`)? # Answer Set `explicit-shell-file-name` to "/bin/bash". > 5 votes --- Tags: emacs27 ---
thread-62423
https://emacs.stackexchange.com/questions/62423
Forcing Inheritance of Specific Properties in OrgMode
2020-12-23T05:15:47.297
# Question Title: Forcing Inheritance of Specific Properties in OrgMode I am working on an OrgMode Scrum workflow that works well for me. One thing that would make it easier is the ability to designate specific properties as inheritable. This is because in my scheme tasks belong to stories and are represented as sub-headings of story headings. One would like to assign a unique story ID to each story and then have each task inherit the story's ID. I know how to do this for ALL properties by setting `org-use-property-inheritance` to `t` as shown below, and I can confirm that it works. However, I cannot get it to work for just a specific set of properties. Unfortunately, I cannot get my target properties to be inherited by using `org-use-property-inheritance: '(STORYID TASKID)` or any modification such as double quoting `STORYID` and `TASKID`. Per the documentation, you should be able to set `org-use-property-inheritance` to a list of properties. Try the Org doc below. Switch between ``` # -*- mode: Org; org-use-property-inheritance: t -*- ``` and ``` # -*- mode: Org; org-use-property-inheritance: '(STORYID TASKID) -*- ``` or ``` # -*- mode: Org; org-use-property-inheritance: '("STORYID" "TASKID") -*- ``` and refresh the dblock every time by placing the point on the `#+BEGIN:` line and hitting `C-c C-c` to refresh the table. You will notice that only setting `org-use-property-inheritance` works as expected. This may or may not be acceptable behavior in certain use cases. ``` # -*- mode: Org; org-use-property-inheritance: t -*- *** Sample Stories (both active and completed, taken from backlog) :PROPERTIES: :COLUMNS: %TODO(Status) %STORYID %TASKID %30ITEM(Task) %OWNER %Effort{:} %Spent{:} %Date %Sprint %45Alltags(Sprints) :Sprint_ALL: Sprint1 Sprint2 Sprint3 Sprint4 :Owner_ALL: pablo john :END: As you can see below, you can report on all the stories by limiting the detail displayed using the ~:maxlevel~ directive to skip the headings used to report spent effort. #+BEGIN: columnview :hlines 4 :id local :indent t :maxlevel 6 | Status | STORYID | TASKID | Task | OWNER | Effort | Spent | Date | Sprint | Sprints | |--------+---------+---------+----------------------------------------------------------------------+-------+--------+-------+------------------+---------+-------------------| | | | | \_ Sample Stories (both active and completed, taken from backlog) | | 9:30 | 5:30 | | | | |--------+---------+---------+----------------------------------------------------------------------+-------+--------+-------+------------------+---------+-------------------| | TODO | Story1 | | \_ Story 1 | | 4:30 | | | | :Sprint1:Sprint2: | | TODO | Story1 | Task1.1 | \_ Task 1.1 | pablo | 01:00 | | | | :Sprint1:Sprint2: | | TODO | Story1 | Task1.2 | \_ Task 1.2 | john | 02:00 | | | | :Sprint1:Sprint2: | | TODO | Story1 | Task1.3 | \_ Task 1.3 | pablo | 01:30 | | | | :Sprint1:Sprint2: | |--------+---------+---------+----------------------------------------------------------------------+-------+--------+-------+------------------+---------+-------------------| | TODO | Story2 | | \_ Story 2 | | 3:00 | 3:00 | | | :Sprint1:Sprint2: | | TODO | Story2 | Task2.1 | \_ Task 2.1 | pablo | 01:00 | | | | :Sprint1:Sprint2: | | TODO | Story2 | Task2.1 | \_ Task 2.2 | | 01:00 | 3:00 | | | :Sprint1:Sprint2: | | | Story2 | Task2.1 | \_ Report | | 01:00 | 01:00 | [2020-12-20 Sun] | Sprint1 | :Sprint1:Sprint2: | | | Story2 | Task2.1 | \_ Report | | 01:00 | 01:00 | [2020-12-18 Fri] | Sprint2 | :Sprint1:Sprint2: | | | Story2 | Task2.1 | \_ Report | | 01:00 | 01:00 | [2020-12-17 Thu] | Sprint1 | :Sprint1:Sprint2: | | TODO | Story2 | Task2.2 | \_ Task 2.3 | john | 01:00 | | | | :Sprint1:Sprint2: | |--------+---------+---------+----------------------------------------------------------------------+-------+--------+-------+------------------+---------+-------------------| | TODO | Story3 | | \_ Story 3 | | 2:00 | 2:30 | | | :Sprint3:Sprint4: | | | Story3 | Task3.1 | \_ Task 3.1 | pablo | 01:00 | | | | :Sprint3:Sprint4: | | TODO | Story3 | Task3.1 | \_ Task 3.1 | pablo | 01:00 | 2:30 | | | :Sprint3:Sprint4: | | | Story3 | Task3.1 | \_ Report | | 01:00 | 01:00 | [2020-12-20 Sun] | Sprint3 | :Sprint3:Sprint4: | | | Story3 | Task3.1 | \_ Report | | 01:00 | 01:30 | [2020-12-25 Fri] | Sprint2 | :Sprint3:Sprint4: | #+END: You could also create story-specific dblocks to see how effort was spent on a specific story. **** TODO Story 1 :Sprint1:Sprint2: :PROPERTIES: :STORYID: Story1 :END: ***** TODO Task 1.1 :PROPERTIES: :OWNER: pablo :EFFORT: 01:00 :SPRINT: :TASKID: Task1.1 :END: ***** TODO Task 1.2 :PROPERTIES: :OWNER: john :EFFORT: 02:00 :TASKID: Task1.2 :END: ***** TODO Task 1.3 :PROPERTIES: :OWNER: pablo :EFFORT: 01:30 :TASKID: Task1.3 :END: **** TODO Story 2 :Sprint1:Sprint2: :PROPERTIES: :STORYID: Story2 :END: ***** TODO Task 2.1 :PROPERTIES: :OWNER: pablo :EFFORT: 01:00 :TASKID: Task2.1 :END: ***** TODO Task 2.2 :PROPERTIES: :EFFORT: 01:00 :TASKID: Task2.2 :OWNER: pablo :END: :LOGBOOK: - State "TODO" from [2020-12-20 Sun 19:46] :END: ****** Report :PROPERTIES: :SPENT: 01:00 :Date: [2020-12-20 Sun] :SPRINT: Sprint1 :END: ****** Report :PROPERTIES: :DATE: [2020-12-18 Fri] :SPRINT: Sprint2 :SPENT: 01:00 :END: ****** Report :PROPERTIES: :DATE: [2020-12-17 Thu] :SPRINT: Sprint1 :SPENT: 01:00 :END: ***** TODO Task 2.3 :PROPERTIES: :OWNER: john :EFFORT: 01:00 :TASKID: Task2.3 :END: **** TODO Story 3 :Sprint3:Sprint4: :PROPERTIES: :STORYID: Story3 :END: ***** TODO Task 3.1 :PROPERTIES: :OWNER: pablo :EFFORT: 01:00 :SPRINT: :TASKID: Task3.1 :END: :LOGBOOK: - State "TODO" from [2020-12-21 Mon 00:08] :END: ***** TODO Task 3.2 :PROPERTIES: :TASKID: Task3.2 :OWNER: pablo :EFFORT: 01:00 :END: ****** Report :PROPERTIES: :SPENT: 01:00 :DATE: [2020-12-20 Sun] :SPRINT: Sprint3 :END: ****** Report :PROPERTIES: :DATE: [2020-12-25 Fri] :SPRINT: Sprint2 :SPENT: 01:30 :END: ``` # Answer > 7 votes Try ``` # -*- mode: Org; org-use-property-inheritance: ("FOO" "BAR") -*- ``` Property names are *strings*, so you need a list of strings. But when you are setting file local variables either at the top of the file as you do above or in a Local Variables block at the end of the file, you should not quote values. The section of the manual in the link above says: > The values are used literally, and not evaluated. As an example, in the Org mode file ``` # -*- mode: Org; org-use-property-inheritance: ("FOO" "BAR") -*- * foo :PROPERTIES: :FOO: foo :OTHER: other :END: ** foo subtree #+begin_src emacs-lisp :results drawer (org-entry-get (point) "FOO" 'selective) #+end_src #+RESULTS: :results: foo :end: #+begin_src emacs-lisp :results drawer (org-entry-get (point) "OTHER" 'selective) #+end_src #+RESULTS: :results: nil :end: ``` the property `FOO` is inherited from the parent in the subtree, but the property `OTHER` is not. --- Tags: org-mode ---
thread-62398
https://emacs.stackexchange.com/questions/62398
sending the results of org-mode block execution to another buffer
2020-12-21T05:57:17.813
# Question Title: sending the results of org-mode block execution to another buffer I'd like to be emulate something similar to using a repl with clojure/cider using org-mode where the results of the evaluation are not put in directly into the document but sent to the `repl` buffer. Is there a way to be able to configure this? # Answer > 0 votes This works pretty well ``` #+BEGIN_SRC bash :results output silent :cache no :eval yes echo "Hello" #+END_SRC ``` In addition to @NickD's suggestion of `:session` --- Tags: org-mode ---
thread-62437
https://emacs.stackexchange.com/questions/62437
Automatically enable a mode with dir-locals.el
2020-12-23T21:43:01.900
# Question Title: Automatically enable a mode with dir-locals.el I'm trying to achieve the effect of automatically calling `M-x importmagic-mode` whenever I open a python file, but I need to do this in a directory specific way, using `dir-locals.el`. I have this in `dir-locals.el`: ``` ((python-mode . ( (eval . (importmagic-mode 1)) ))) ``` But I still have to `M-x importmagic-mode` every time I open a python file. What am I missing to make this automatic? Is my syntax just wrong? # Answer > 1 votes You don't need the 1. ``` (eval . (importmagic-mode)) ``` via this answer: https://stackoverflow.com/a/63797942/1052117 --- Tags: minor-mode, directory-local-variables ---
thread-29664
https://emacs.stackexchange.com/questions/29664
How to do paredit-kill backwards?
2016-12-29T08:52:59.213
# Question Title: How to do paredit-kill backwards? Most everyone who uses `paredit` has used `paredit-kill` (i.e., `C-k`), which allows one to delete a line forwards whilst keeping delimiters balanced properly. But how does one do this in the reverse direction? When one does `C-0 C-k`, which is something that's typically used to kill the line backwards, `paredit-kill` actually calls the built-in `kill-line` to handle it. Unfortunately, this loses the delimiter-balancing that is otherwise had with `paredit-kill`. Since discovering that `C-0 C-k` does not work quite right, I've tried implementing a `paredit-backward-kill-line` function that will kill backwards *and* balance delimiters a la `paredit-kill`. However, I've not had much luck with this and have only come up with an implementation which uses `paredit-backward-delete` under certain conditions. This solution has only worked marginally well for me thus far. I've also tried reworking some of `paredit`'s functions that relate to killing lines, but it seems that they are all hard-coded to work with forwards deletion. This is making certain functions here significantly difficult to rework. All in all, this seems like a lot of work to get something working that seems like it should be relatively simple, given that `paredit` already works as well as it does. So, I guess my question is: is there a way to do a backwards `paredit-kill` which retains all the delimiter-balancing functionality that is had from a normal, forwards `paredit-kill`? # Answer Since no one here has come up with an answer that is sufficient for my needs, I've continued with my aforementioned implementation which uses `paredit-backward-delete` under certain conditions. What I've come up with isn't very pretty (nor very efficient), but it works well enough and seems to keep true to the spirit of `paredit` from an end-user perspective. Here is the actual function itself, which I named `paredit-backward-delete-line`: ``` (defun paredit-backward-delete-line () "Delete line backwards, preserving delimiters and not adding to the kill ring." (interactive) ;; These variables are set upon invocation. The first one indicates whether this command ;; was invoked inside of a string and the second one is a placeholder variable that will ;; be used later. (setq-local paredit--started-in-string-p (paredit-in-string-p)) (setq-local paredit--backward-region-p nil) ;; If a sexp or a string is behind us, and ;; * it's not an escaped character ;; * it's not a comment ;; * we're not in a string ;; ... (if (or (and (not (paredit-in-char-p (1- (point)))) (not (paredit-in-comment-p)) (eq (char-syntax (char-before)) ?\) )) (and (not (paredit-in-string-p)) (eq (char-syntax (char-before)) ?\" ))) (progn ;; Select the region... (set-mark-command nil) (setq deactivate-mark nil) ;; Do a `paredit-backward'... (paredit-backward) ;; Save the region as a string and indicate that this block of code has been visited. (setq-local paredit--backward-region (buffer-substring (region-beginning) (region-end))) (setq-local paredit--backward-region-p t) ;; Then delete the selected region. (delete-active-region))) ;; If the previous `progn' block has not been run or the region that was selected is only one line... (if (or (null paredit--backward-region-p) (<= (s-count-matches "\n" paredit--backward-region) 1)) ;; Do the following in a loop for the number of the current column... (dotimes (i (current-column)) ;; If a sexp is (still) behind us, recur (this will cause the previous `progn' block to run ;; and get rid of that sexp). (if (and (not (paredit-in-char-p (1- (point)))) (not (paredit-in-comment-p)) (eq (char-syntax (char-before)) ?\) )) (paredit-backward-delete-line)) ;; Otherwise, make sure: we're not in a comment, that the thing behind us isn't an escaped character, ;; that it's the beginning of a form or list, and that we're in an empty form / list. If that check does ;; not pass, see whether we started in a string and if we're in an empty string currently. If either of ;; these checks pass, do nothing. (unless (or (and (not (paredit-in-char-p (1- (point)))) (not (paredit-in-comment-p)) (eq (char-syntax (char-before)) ?\( ) (eq (char-after) (matching-paren (char-before)))) (and paredit--started-in-string-p (eq (1- (point)) (car (paredit-string-start+end-points))) (eq (point) (cdr (paredit-string-start+end-points))))) ;; If neither of those checks pass, delete backwards when we're in a comment or do a `paredit-backward-delete' ;; otherwise. (if (paredit-in-comment-p) (delete-backward-char 1) (paredit-backward-delete 1))))) ;; Finally, clear the echo area (`paredit-backward-delete' can be noisy). (message nil)) ``` Note that it does not *kill* the line backwards, but rather *deletes* it. This is actually the behavior that I really wanted in the first place, but I asked the question with killing in mind because I thought it would be easier for someone to implement that because `paredit-kill` already exists and does this sort of thing. Anyway, I bound this function to `<C-backspace>` like so: `(define-key paredit-mode-map (kbd "<C-backspace>") 'paredit-backward-delete-line)` And now I enjoy backwards deletion of lines which respects delimiters. Feel free to convert this function to utilize killing instead; it would be fairly easy to do. > 1 votes # Answer You could use `lispy`. What you describe can be achieved by marking a sexp (`m` or `M-m`), switching to the different side of the region (`d`), and growing the region by as many sexps as possible (`0>`). At this point you have marked the stuff that you want killed or deleted. Press `C-w` or `C-d` appropriately. > 0 votes # Answer Good question. I've come up with this (still, first) draft. As queried it's about killing line backward from point including keeping `sexp` balance as paredit does watch for it. ``` (defun paredit-kill-backward-from-point () (interactive) (let ((prev-pos (point))) (paredit-backward-up) (paredit-forward-down) (kill-region (point) prev-pos))) ``` > 0 votes # Answer There is a function in Vanilla Emacs for this `backward-kill-sexp`, so I do the following bind: ``` (global-set-key (kbd "C-S-k") (lambda () (interactive) (backward-kill-sexp))) ``` https://www.gnu.org/software/emacs/manual/html\_node/emacs/Expressions.html I don't think it is anymore a standard binding (if somebody knows why it was removed, I would be curious to know, perhaps because it was bound to `C-M-DEL`), but below is the source code: ``` (defun backward-kill-sexp (&optional arg) "Kill the sexp (balanced expression) preceding the cursor. With ARG, kill that many sexps before the cursor. Negative arg -N means kill N sexps after the cursor." (interactive "p") (kill-sexp (- (or arg 1)))) ``` > 0 votes --- Tags: paredit, deletion, kill-text, delimiters ---
thread-62440
https://emacs.stackexchange.com/questions/62440
Auctex hook causes an error when set with use-package :hook versus add-hook?
2020-12-23T22:16:32.127
# Question Title: Auctex hook causes an error when set with use-package :hook versus add-hook? According to the use-package documentation these two are the same: ``` (use-package ace-jump-mode :hook (prog-mode . ace-jump-mode)) (use-package ace-jump-mode :commands ace-jump-mode :init (add-hook 'prog-mode-hook #'ace-jump-mode)) ``` I have the following in my configs: ``` (use-package auctex :ensure t :after latex :init [snip] (add-hook 'TeX-after-compilation-finished-functions #'TeX-revert-document-buffer) :hook ;; (TeX-after-compilation-finished-functions . TeX-revert-document-buffer) ; Causes errors? [snip] ``` If I take out the `add-hook` way and uncomments the `:hook` way then I get the following errors each time I compile a latex document followed by a subsequent pdf buffer revert: ``` error in process sentinel: image-display-size: Invalid image specification: nil error in process sentinel: Invalid image specification: nil ``` Note that when I define the hooks using `add-hook`, that does not produce the errors. Could someone tell what's going on? # Answer > 1 votes You can find out what is going on yourself by putting the cursor after the `use-package` stanza and doing `M-x pp-macroexpand-last-sexp`. You will discover that the `:hook` line expands to ``` (add-hook 'TeX-after-compilation-finished-functions-hook #'TeX-revert-document-buffer) ``` which is not what you wanted. Long story short: `:hook` only does what you want if the `car` of the alist names a hook in a rather simple-minded way. In your case, calling `add-hook` explicitly is the way to go. --- Tags: hooks, use-package ---
thread-62432
https://emacs.stackexchange.com/questions/62432
Export org notes to pdf such that it looks nice
2020-12-23T20:28:07.250
# Question Title: Export org notes to pdf such that it looks nice I have a large number of org-mode files where I took my class notes. I would like to export them as PDF files. However, I like to take notes as in the following example: ``` #+LaTeX_HEADER: \newcommand\RR{\mathbb{R}} #+LaTeX_HEADER: \newcommand{\norm}[1]{\left\lVert#1\right\rVert} * Johnson-Lindenstrauss ** concentration on projection on first $k$ coordinates $u \in S^{d-1}$ uniform, think $u \sim N(0, I)$, but normalized each coordinate concentrates around $\frac{1}{d}$ $g : \RR^d \to \RR^k$ projection to first $k$ coordinates then if $L = \mathbb E \norm{g(u)}^2$, then $L \sim \frac{k}{d}$ and the concentration is very strong: $\mathbb P [L \ge \beta \frac{k}{d}] \le \exp(\frac{k}{2} (1 - \beta + \log \beta) )$ ``` When read with `org-latex-preview`, it is very readable. The issue is, when exported to pdf, it loses all readability: How can I enhance the pdf export to insert linebreaks, and maybe even to render the equations which are in their own lines as if they were in an `align` environment? Can I insert some parser before the export? The pdf output format is not crucial, I just want to be able to send these notes to people who don't use org-mode. # Answer > 2 votes Your main problem seems to be that exporting does not honour your line breaks. There are two simple options to get around that. 1. Do global replace linefeed to two linefeeds, `\n` to `\n\n`, before exporting. Every line will be treated as a paragraph. Added whitespace will be ignored in more structured regions of your file like in headers. On the other hand, the indenting of long lines will not be optimal by default. That can be changed in the LaTex export template. 2. Turn your text lines into unordered, bulleted lists by adding `-` in front. This takes slightly more effort but you can structure the output more with indenting some list items. Your note-taking style seems to favour bulleted lists since you do not write full sentences. Creating lists while you take the notes might be the best solution in the long run. # Answer > 0 votes There is `org-export-before-parsing-hook` whose doc string says: > Hook run before parsing an export buffer. > > This is run after include keywords and macros have been expanded and Babel code blocks executed, on a copy of the original buffer being exported. Visibility and narrowing are preserved. Point is at the beginning of the buffer. > > Every function in this hook will be called with one argument: the back-end currently used, as a symbol. You can try a function that replaces `$` with `$$`, but I doubt that anything automatic will be able to deal with all situations, e.g. you will almost never want `$k$` to become `$$k$$`. I think you'd be better off leaving the export as is, but rephrasing the text of your notes to add the proper "meat" to the prose. IOW, I think the problem is not that that the math expressions are not readable, it's that there are too many words (and some punctuation) missing to make sense of what you wrote. So revising your notes soon after you take them might be beneficial not only to the people you send them to, but also to your future self. --- Tags: org-mode, org-export, latex ---
thread-48072
https://emacs.stackexchange.com/questions/48072
Find cause of cpu-usage?
2019-02-26T12:44:17.710
# Question Title: Find cause of cpu-usage? Is there some way to find out, what in Emacs is causing spurious cpu usage? Since a few days I notice Emacs retaining high CPU usage despite not being used actively, having no subprocesses, and not being in blocking state. `M-: (all-threads)` is empty, except for `(current-thread)`. I also wasn't able to reproduce the issue across sessions. I am using Emacs on Windows 10, so many unix tools will not be applicable. # Answer > 8 votes @npostavs' last comment should give you enough hints to solve the problem. The built-in profiler can tell which function is causing the high CPU usage. Here are simple steps to get started: 1. `M-x profiler-start RET` 2. select 'cpu' 3. wait for a few seconds 4. `M-x profiler-report RET` 5. modify emacs e.g. by disabling the conflicting mode 6. `M-x profiler-stop RET` 7. repeat to continue testing More details in the Profiling Emacs manual page. --- Tags: performance ---
thread-62424
https://emacs.stackexchange.com/questions/62424
Org mode capture template for repeat tasks
2020-12-23T06:28:35.017
# Question Title: Org mode capture template for repeat tasks I want to capture several tasks that will repeat annually from the date on which they are captured. So, I did: ``` (setq org-capture-templates '(("a" "TODO Item that repeats annually" entry (file+headline "~/Documents/todo.org" "Annual") "* TODO %?\n SCHEDULED: %t"))) ``` This adds a TODO with scheduled date as today. How do I get `+1y` added to scheduled? On a more general note, what should the capture template be with schedule for tomorrow, tomorrow recurring annually, etc.? # Answer > 4 votes You can achieve that using template expansion. As `%(EXP)` will expand a lisp expression, you can take advantage of it. Rewriting the template's scheduled part to this will do it ``` SCHEDULED: %(concat \"<\" (format-time-string \"%Y-%m-%d\") \" +1y\>\") ``` Surely there is a more general "org-way" to do it if you dig enough into timestamp objects, but I haven't been able to figure how to make it work with `org-insert-timestamp` as `PRE` and `POST` are inserted out of timestamp; Also, you can use `org-insert-time-stamp`'s (stated but undocumented) `EXTRA` argument to pass it, so: ``` SCHEDULED: %(org-insert-time-stamp nil nil nil nil nil \" +1y\") ``` will do the same. For more complex date choices than current date probably using `org-read-date` will help. --- Tags: org-mode, org-capture ---
thread-42113
https://emacs.stackexchange.com/questions/42113
Customize eshell redirection to buffer
2018-06-19T07:39:57.077
# Question Title: Customize eshell redirection to buffer In eshell I can redirect the output of a command (`foo`) to a buffer (`bar`) by inputting: `foo > #<buffer bar>` I want to customize this syntax the following way: `foo > #bar` Is it possible to customize it? How? **Details** emacs version: `GNU Emacs 24.3.1 (x86_64-redhat-linux-gnu, GTK+ Version 3.22.10) of 2017-09-20 on c1bm.rdu2.centos.org` # Answer To redirect to a buffer, use `#<buffer buffer-name>`, since Emacs 24.4, you can also use the shorthand `#<buffer-name>`. For example, ``` echo hello >>> #<buffer *scratch*> echo world >>> #<*scratch*> ``` It looks like it is possible to customize the syntax via the hook `eshell-parse-argument-hook`, such as supporting `#buffer-name` as well. Here is my attempt, ``` (defun eshell-parse-my-special-reference () (when (and (not eshell-current-argument) (not eshell-current-quoted) ;; Don't overwrite `eshell-parse-special-reference' (not (looking-at "#<\\(\\(buffer\\|process\\)\\s-\\)?")) (looking-at "#\\(\\S-+\\)") (match-string 1)) (goto-char (match-end 0)) ;; Go to the end of the match. (list 'get-buffer-create (match-string 1)))) (add-hook 'eshell-parse-argument-hook #'eshell-parse-my-special-reference) ``` and the following worked as expected ``` echo foobar >>> #*scratch* ``` > 5 votes # Answer May not be a direct answer to your problem. But you can use key binding `C-c` `M-b` to insert the buffer name at the point. With fido-mode enabled, these key binding help me easily choose the buffer name from the mini-buffer and insert in the form which eshell understands. See `Useful Keybindings` section of masteringemacs-mastering-eshell for more details. > 0 votes --- Tags: customize, eshell ---
thread-62452
https://emacs.stackexchange.com/questions/62452
Error when first launching Spacemacs in macOS 11.0.1
2020-12-25T02:03:22.200
# Question Title: Error when first launching Spacemacs in macOS 11.0.1 I am trying to learn Emacs. I successfully installed it and went through the built-in tutorial. I thought that installing Spacemacs would be nice so I gave it a try. I followed a tutorial and now I am stuck. First time I launched Spacemacs I got this When I run `emacs --debug-init`, I get this ``` Debugger entered--Lisp error: (wrong-type-argument stringp async) intern(async) package-desc-from-define(async "20200809.501" "Asynchronous processing in Emacs" '((emacs "24.3")) :commit "14f48de586b0977e3470f053b810d77b07ea427a" :authors (("John Wiegley" . "jwiegley@gmail.com")) :maintainer ("John Wiegley" . "jwiegley@gmail.com") :keywords ("convenience" "async") :url "https://github.com/jwiegley/emacs-async") apply(package-desc-from-define (async "20200809.501" "Asynchronous processing in Emacs" '((emacs "24.3")) :commit "14f48de586b0977e3470f053b810d77b07ea427a" :authors (("John Wiegley" . "jwiegley@gmail.com")) :maintainer ("John Wiegley" . "jwiegley@gmail.com") :keywords ("convenience" "async") :url "https://github.com/jwiegley/emacs-async")) package-process-define-package((define-package async "20200809.501" "Asynchronous processing in Emacs" '((emacs "24.3")) :commit "14f48de586b0977e3470f053b810d77b07ea427a" :authors (("John Wiegley" . "jwiegley@gmail.com")) :maintainer ("John Wiegley" . "jwiegley@gmail.com") :keywords ("convenience" "async") :url "https://github.com/jwiegley/emacs-async")) package-load-descriptor("/Users/dpalma/.emacs.d/elpa/27.1/develop/async-202...") package-load-all-descriptors() package-initialize(noactivate) (if package--initialized nil (setq configuration-layer-rollback-directory (configuration-layer/elpa-directory configuration-layer--rollback-root-directory)) (setq package-user-dir (configuration-layer/elpa-directory configuration-layer--elpa-root-directory)) (setq package-archives (configuration-layer//resolve-package-archives configuration-layer-elpa-archives)) (setq package-enable-at-startup nil) (package-initialize 'noactivate) (if (package-installed-p 'org-plus-contrib) (progn (spacemacs-buffer/message "Initializing Org early...") (configuration-layer//activate-package 'org-plus-contrib)))) configuration-layer/initialize() spacemacs/init() (let ((file-name-handler-alist nil)) (require 'core-spacemacs) (spacemacs/dump-restore-load-path) (configuration-layer/load-lock-file) (spacemacs/init) (configuration-layer/stable-elpa-init) (configuration-layer/load) (spacemacs-buffer/display-startup-note) (spacemacs/setup-startup-hook) (spacemacs/dump-eval-delayed-functions) (if (and dotspacemacs-enable-server (not (spacemacs-is-dumping-p))) (progn (require 'server) (if dotspacemacs-server-socket-dir (progn (setq server-socket-dir dotspacemacs-server-socket-dir))) (if (server-running-p) nil (message "Starting a server...") (server-start))))) (if (not (version<= spacemacs-emacs-min-version emacs-version)) (error (concat "Your version of Emacs (%s) is too old. " "Spacemacs requires Emacs version %s or above.") emacs-version spacemacs-emacs-min-version) (let ((file-name-handler-alist nil)) (require 'core-spacemacs) (spacemacs/dump-restore-load-path) (configuration-layer/load-lock-file) (spacemacs/init) (configuration-layer/stable-elpa-init) (configuration-layer/load) (spacemacs-buffer/display-startup-note) (spacemacs/setup-startup-hook) (spacemacs/dump-eval-delayed-functions) (if (and dotspacemacs-enable-server (not (spacemacs-is-dumping-p))) (progn (require 'server) (if dotspacemacs-server-socket-dir (progn (setq server-socket-dir dotspacemacs-server-socket-dir))) (if (server-running-p) nil (message "Starting a server...") (server-start)))))) eval-buffer(#<buffer *load*> nil "/Users/dpalma/.emacs.d/init.el" nil t) ; Reading at buffer position 1880 load-with-code-conversion("/Users/dpalma/.emacs.d/init.el" "/Users/dpalma/.emacs.d/init.el" t t) load("/Users/dpalma/.emacs.d/init" noerror nomessage) startup--load-user-init-file(#f(compiled-function () #<bytecode 0x1ff1aea2e655>) #f(compiled-function () #<bytecode 0x1ff1aea2e66d>) t) command-line() normal-top-level() ``` I have macOS 11.0.1 and Emacs 27.1. EDIT: This seems to fix the issue. # Answer See Emacs bug # 45415. It has the same backtrace as what you report. But it's apparently a MELPA bug. So I guess you just need to wait till the bug is fixed. > 1 votes --- Tags: spacemacs, package, debugging, package-repositories ---
thread-62460
https://emacs.stackexchange.com/questions/62460
How to list a newly formed emacs minor-mode?
2020-12-26T06:07:56.110
# Question Title: How to list a newly formed emacs minor-mode? With some help from the blog post found here, I have managed to write a small code for a test package (a minor mode) named `niranjan`. It is as follows. ``` (define-minor-mode niranjan-mode "Hello world" :lighter " niranjan" :keymap (let ((map (make-sparse-keymap))) (define-key map (kbd "C-c i") 'insert-niranjan) map)) (add-hook 'text-mode-hook 'niranjan-mode) (provide 'niranjan-mode) ``` I hope this is correct. I saved it in `~/.emacs.d/elpa/niranjan` with the name `niranjan.el`. Now I expect `niranjan-mode` to be listed when I press `M-x`, but unfortunately it isn't. Note that I am opening a new session while pressing `M-x` to use my new mode. What should be done to make a package appear in the normal package/mode list? Is there something to be done to refresh the list of packages? Have I placed the `.el` file in a wrong location? # Answer You are right in assuming that the location is wrong. Emacs does not know about your niranjan directory. You assume that `~/.emacs.d/elpa/` is a special location and that emacs automatically knows how to add packages installed in there. If you look at the contents of the variable `load-path`, you'll see that is not the case. Every package that has been downloaded and installed there in its own directory, have been explicitly, one by one, added to this list variable by your package management programme. Commonly, if you do things manually, you add one directory to your load-path and place bare lisp files in it, e.g.: ``` (add-to-list 'load-path "~/.emacs.d/lisp/") ``` More details in https://www.emacswiki.org/emacs/LoadPath > 3 votes --- Tags: minor-mode, load-path, list-packages ---
thread-62462
https://emacs.stackexchange.com/questions/62462
How to automatically select apropos buffer when it is displayed
2020-12-26T09:47:36.940
# Question Title: How to automatically select apropos buffer when it is displayed It is possible to automatically select `*Help*` buffers when they are displayed by doing `(setq help-window-select t)` (relevant question: How to close help buffer without moving to it?). Is there a similar setting for `*Apropos*` buffers? When I use apropos using `C-h a`, the resulting apropos buffer is not automatically selected. I have to switch to it using `C-x o`. Is there a way to switch to the apropos buffer automatically? # Answer You can add a function to `apropos-mode-hook` that selects the window for the Apropos buffer. ``` (defun my-apropos-select-window () "..." (pop-to-buffer (current-buffer))) (add-hook 'apropos-mode-hook #'my-apropos-select-window) ``` > 1 votes --- Tags: help, focus, selected-window, apropos ---
thread-62472
https://emacs.stackexchange.com/questions/62472
Can't create new branch
2020-12-26T19:36:57.117
# Question Title: Can't create new branch I clone git project. Current branch is **main**. Nice. Now I want to create new branch: **my-branch** **Magit Branch Read Upstream First: Value Menu read upstream first** I try this: ``` magit-branch-create Create branch starting at (default main): my-branch ``` But I get error: ``` Not a valid starting-point: my-branch ``` # Answer > 3 votes Read the pieces of text that you are quoting more carefully. You are being asked to type the name of an existing branch but you type the name of the branch that you want to create. Providing the wrong information results in an error message, which again informs you that you were supposed to enter the name of an existing branch. You are not the only person who finds it more natural to provide the name of the new branch first, so magit provides an option that controls the input order. You have already found it: > Magit Branch Read Upstream First: Value Menu read upstream first Change the value of this option and then you can use the order that you want to use. --- Tags: magit ---
thread-62479
https://emacs.stackexchange.com/questions/62479
remove "-" (soft hyphen) between words
2020-12-27T11:52:12.957
# Question Title: remove "-" (soft hyphen) between words When I try to paste a text from a web page inside Emacs I get this "-" between words. Here is one example: Is there a way to get rid of this (don't know the term..) ? > Aus Sicht vie­ler Deut­scher ist Russ­land ein rät­sel­haf­tes Land. Ich habe elf Jah­re lang von dort für den SPIEGEL be­rich­tet, bis Ende 2009. Bis heu­te ver­fol­ge ich die Ent­wick­lung in dem Land, das ich je­des Jahr be­su­che. # Answer ``` (query-replace-regexp (format "\\b%c\\b" 173) "" ) ``` or in interactive mode `C-M-% \bC-x 8 RET ad RET \b RET RET` the sequence \`C-x 8 RET ad RET' is for generate the SOFT HYPHEN char (#xad =#173). > 2 votes --- Tags: replace, query-replace ---
thread-62412
https://emacs.stackexchange.com/questions/62412
mu4e mime part is sent with multi account setup and german umlaute
2020-12-22T09:46:42.157
# Question Title: mu4e mime part is sent with multi account setup and german umlaute I have a setup with three different accounts on macos, switching works e.g. with the context setup and I am able to send emails with each one of them. An account is a ms exchange account which uses davmail, the other is a gmail account and the third a gmx. Though only with the davmail account I am able to read the mails correctly in the macos mail.app. When sending with the two other accounts I have a wrong display of german umlaute, e.g. ``` Gau=C3=9Fstra=C3=9Fe ``` where it should be ``` Gaußstraße ``` in addition the mime-version info is sent and shown by the mail.app as well, e.g. see below (where you also can see that the signature separator is written as "--=20": ``` --text follows this line-- MIME-Version: 1.0 Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: quoted-printable --=20 ``` Update: I also get ``` --text follows this line-- Vielen Dank und viele =?utf-8?B?R3LDvMOfZSE=?= MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii ``` when it should say: ``` Vielen Dank und viele Grüße ``` No, I see a different charset!? Not sure, if this is relevant... Do you have an idea what is going wrong? This is the setting which I have for gmail ``` (smtpmail-starttls-credentials . (("smtp.gmail.com" 587 nil nil))) (smtpmail-auth-credentials . (expand-file-name "~/.authinfo.gpg")) (smtpmail-default-smtp-server . "smtp.gmail.com") (smtpmail-smtp-server . "smtp.gmail.com") (smtpmail-smtp-service . 587) (smtpmail-stream-type . starttls) (mu4e-sent-messages-behavior . delete) ``` Do you need more information about the setup for each account? ## Here is an update and further information: * I am using spacemacs with emacs 28.0.50 (and I tested it with 27) mu 1.4.13 on macos Using gnus the sending works fine with these settings in .gnus.el ``` (setq send-mail-function 'smtpmail-send-it) (setq smtpmail-smtp-server "smtp.gmail.com") (setq smtpmail-smtp-service 587) ``` This short settings does not result in correct mails with mu4e. When looking in the drafts folder with the mail.app client on my gmail account, I see the message in a correct way. I tried also plenty of other things for setting the encoding... the problem is however that I do not not know in which direction I have to look further e.g. I tried something like: ``` (set-default-coding-systems 'utf-8-unix) (setq mm-coding-system-priorities '(iso-latin-1 utf-8)) ``` and similar settings without success. ## Next Update using msmtp: I was testing the sending with msmtp for all three accounts using mu4e and the context setup. Sending itself works again, but only the davmail account sends correct emails. The other accounts (one is gmail) results in the same problem as above. And testing a plain file with msmtp like this ``` cat test.mail | msmtp -a default <username>@domain.com ``` with something like ``` To: username@domain.com From: username@gmail.com Subject: A test Vielen Dank und viele Grüße ``` works great with gmail as well... but the buffer from mu4e gets sent somehow in a wrong way!? The plain file which I sent in a correct way was encoded as 'unix'; the standard way which mu4e seems to use is 'utf-8' (at least this is chown in the modeline); chaning it to 'unix' as well does not result in a correct mail!? ### msmtp with mutt Tested it and it works as well; just for the record; there I have set: ``` set send_charset = "utf-8:iso-8859-1:us-ascii" set charset = "utf-8" ``` # Answer # solved I had probably an old mutt setting in my emacs config which caused the mentioned behavior. Sorry for the trouble... > 0 votes --- Tags: mu4e ---
thread-62483
https://emacs.stackexchange.com/questions/62483
Open 4 or any number of files in rectangles (dired open all in splits)
2020-12-27T15:38:21.330
# Question Title: Open 4 or any number of files in rectangles (dired open all in splits) When you have a dired buffer open and it's listing 4 files in a directory, is there a way to 'open all' the files, and be able to see all the files as 4 split windows in emacs. # Answer > 1 votes Yes. 1. In Dired, **`F`** (command `dired-do-find-marked-files`) displays and visits each of the marked files, or the next prefix-arg number of files. If you want to mark all of the files then you can use `% m .`. Or if no files are marked then you can just use `t` to mark them all. 2. If you use Dired+ then you can also just use prefix arg `C-u C-u` to act on all files (no need to mark them all). So just \**`C-u C-u F` will do what you want. 3. If you use Dired+ then you can even do the same thing for all files in the current Dired buffer and in all marked subdirs, ... recursively. For that, you use key **`M-+ F`** instead of `F`. (All such recursive-behaving commands are on prefix key `M-+`.) The number of files that can be displayed this way is restricted by the height of the current window and \`window-min-height'. All of the files are visited, but some of them might not be displayed because there's not enough window space. But you can also have `F` or `M-+ F` open the files in separate *frames* (any number of them), by setting or binding option `pop-up-frames` to non-`nil`. --- Tags: dired ---
thread-62485
https://emacs.stackexchange.com/questions/62485
emacs 27 (lucid toolkit) daemon crashes every couple of minutes
2020-12-27T16:35:54.070
# Question Title: emacs 27 (lucid toolkit) daemon crashes every couple of minutes Some variant of this has been asked before - emacs daemon crashing when it has been built with Gtk3 etc - but I couldn't find any solution to this. I've built Emacs 27.1 from source on Xubuntu 20.04 with `--with-x-toolkit=lucid`. I then copied `emacs.service` into `$HOME/.config/system/user/` and ran `systemctl --user start emacs.service`. It ran for a while and crashed with the following message: ``` Job for emacs.service failed because a timeout was exceeded. See "systemctl --user status emacs.service" and "journalctl --user -xe" for details. ``` Note: I don't need to open a file or resize emacs etc. The daemon fails even when I don't start an `emacsclient`. The outputs of both the recommended commands are given below: `journalctl`: ``` anaravi@anaravi-xxxxx:~$ journalctl --user -xe -- Defined-By: systemd -- Support: http://www.ubuntu.com/support -- -- A start job for unit UNIT has finished with a failure. -- -- The job identifier is 249 and the job result is failed. Dec 27 21:37:26 anaravi-xxxxx systemd[2390]: emacs.service: Scheduled restart job, restart counter is at 1. -- Subject: Automatic restarting of a unit has been scheduled -- Defined-By: systemd -- Support: http://www.ubuntu.com/support -- -- Automatic restarting of the unit UNIT has been scheduled, as the result for -- the configured Restart= setting for the unit. Dec 27 21:37:26 anaravi-xxxxx systemd[2390]: Stopped Emacs text editor. -- Subject: A stop job for unit UNIT has finished -- Defined-By: systemd -- Support: http://www.ubuntu.com/support -- -- A stop job for unit UNIT has finished. -- -- The job identifier is 265 and the job result is done. Dec 27 21:37:26 anaravi-xxxxx systemd[2390]: Starting Emacs text editor... -- Subject: A start job for unit UNIT has begun execution -- Defined-By: systemd -- Support: http://www.ubuntu.com/support -- -- A start job for unit UNIT has begun execution. -- -- The job identifier is 265. Dec 27 21:37:26 anaravi-xxxxx emacs[3264]: Loading /home/anaravi/.emacs.d/init.el (source)... Dec 27 21:37:26 anaravi-xxxxx emacs[3264]: Loading /home/anaravi/.emacs.d/config/cfg-custom.el (source)... Dec 27 21:37:26 anaravi-xxxxx emacs[3264]: Loading /home/anaravi/.emacs.d/config/cfg-custom.el (source)...done Dec 27 21:37:27 anaravi-xxxxx emacs[3264]: Loading /home/anaravi/.emacs.d/init.el (source)...done Dec 27 21:37:27 anaravi-xxxxx emacs[3264]: Loading /home/anaravi/.emacs.d/recentf... Dec 27 21:37:27 anaravi-xxxxx emacs[3264]: Loading /home/anaravi/.emacs.d/recentf...done Dec 27 21:37:27 anaravi-xxxxx emacs[3264]: Cleaning up the recentf list... Dec 27 21:37:27 anaravi-xxxxx emacs[3264]: Cleaning up the recentf list...done (0 removed) Dec 27 21:37:27 anaravi-xxxxx emacs[3264]: Starting Emacs daemon. Dec 27 21:37:28 anaravi-xxxxx gnome-keyring-daemon[2403]: asked to register item /org/freedesktop/secrets/collection/login/1, but it's already registered Dec 27 21:37:39 anaravi-xxxxx gnome-keyring-daemon[2403]: asked to register item /org/freedesktop/secrets/collection/login/1, but it's already registered ``` `systemctl`: ``` anaravi@anaravi-xxxxx:~$ systemctl --user status emacs ● emacs.service - Emacs text editor Loaded: loaded (/home/anaravi/.config/systemd/user/emacs.service; disabled; vendor preset: enabled) Active: activating (start) since Sun 2020-12-27 21:35:53 IST; 1min 16s ago Docs: info:emacs man:emacs(1) https://gnu.org/software/emacs/ Main PID: 2890 (emacs) CGroup: /user.slice/user-1000.slice/user@1000.service/emacs.service └─2890 /usr/local/lib/emacs/27.1/bin/emacs --fg-daemon Dec 27 21:35:57 anaravi-xxxxx emacs[2890]: Loading /home/anaravi/.emacs.d/init.el (source)... Dec 27 21:35:58 anaravi-xxxxx emacs[2890]: Loading /home/anaravi/.emacs.d/config/cfg-custom.el (source)... Dec 27 21:35:58 anaravi-xxxxx emacs[2890]: Loading /home/anaravi/.emacs.d/config/cfg-custom.el (source)...done Dec 27 21:36:02 anaravi-xxxxx emacs[2890]: Loading /home/anaravi/.emacs.d/init.el (source)...done Dec 27 21:36:02 anaravi-xxxxx emacs[2890]: Loading /home/anaravi/.emacs.d/recentf... Dec 27 21:36:02 anaravi-xxxxx emacs[2890]: Loading /home/anaravi/.emacs.d/recentf...done Dec 27 21:36:02 anaravi-xxxxx emacs[2890]: Cleaning up the recentf list... Dec 27 21:36:02 anaravi-xxxxx emacs[2890]: Cleaning up the recentf list...done (0 removed) Dec 27 21:36:07 anaravi-xxxxx emacs[2890]: Starting Emacs daemon. Dec 27 21:36:18 anaravi-xxxxx emacs[2890]: unable to open file '/etc/dconf/db/local': Failed to open file “/etc/dconf/db/local”: open() failed: No such file or di> anaravi@anaravi-xxxxx:~$ systemctl --user status emacs ● emacs.service - Emacs text editor Loaded: loaded (/home/anaravi/.config/systemd/user/emacs.service; disabled; vendor preset: enabled) Active: activating (start) since Sun 2020-12-27 21:37:26 IST; 3s ago Docs: info:emacs man:emacs(1) https://gnu.org/software/emacs/ Main PID: 3264 (emacs) CGroup: /user.slice/user-1000.slice/user@1000.service/emacs.service └─3264 /usr/local/lib/emacs/27.1/bin/emacs --fg-daemon Dec 27 21:37:26 anaravi-xxxxx systemd[2390]: Starting Emacs text editor... Dec 27 21:37:26 anaravi-xxxxx emacs[3264]: Loading /home/anaravi/.emacs.d/init.el (source)... Dec 27 21:37:26 anaravi-xxxxx emacs[3264]: Loading /home/anaravi/.emacs.d/config/cfg-custom.el (source)... Dec 27 21:37:26 anaravi-xxxxx emacs[3264]: Loading /home/anaravi/.emacs.d/config/cfg-custom.el (source)...done Dec 27 21:37:27 anaravi-xxxxx emacs[3264]: Loading /home/anaravi/.emacs.d/init.el (source)...done Dec 27 21:37:27 anaravi-xxxxx emacs[3264]: Loading /home/anaravi/.emacs.d/recentf... Dec 27 21:37:27 anaravi-xxxxx emacs[3264]: Loading /home/anaravi/.emacs.d/recentf...done Dec 27 21:37:27 anaravi-xxxxx emacs[3264]: Cleaning up the recentf list... Dec 27 21:37:27 anaravi-xxxxx emacs[3264]: Cleaning up the recentf list...done (0 removed) Dec 27 21:37:27 anaravi-xxxxx emacs[3264]: Starting Emacs daemon. ``` # Answer > 1 votes Found the problem in the configuration status while building: ``` ... Does Emacs use -lotf? yes Does Emacs use -lxft? yes Does Emacs use -lsystemd? no Does Emacs use -ljansson? yes Does Emacs use -lgmp? yes ... ``` Emacs was built without **lsystemd** because I was missing `libsystemd-dev`. Installing that package seems to have solved the problem. --- Tags: debugging, emacs-daemon, systemd-integration ---
thread-62489
https://emacs.stackexchange.com/questions/62489
Why magit use rectangle on origin/master and not only on master?
2020-12-27T22:43:44.840
# Question Title: Why magit use rectangle on origin/master and not only on master? I have done a branch checkout on `master` but magit rectangle is on `origin/master` and not only on master. # Answer > 1 votes Quoting the manual: Magit displays references in logs a bit differently from how Git does it. Local branches are blue and remote branches are green. Of course that depends on the used theme, as do the colors used for other types of references. The current branch has a box around it, as do remote branches that are their respective remote's `HEAD` branch. If a local branch and its push-target point at the same commit, then their names are combined to preserve space and to make that relationship visible. For example: ``` origin/feature [green][blue-] ``` instead of ``` feature origin/feature [blue-] [green-------] ``` --- Tags: magit, git ---
thread-62493
https://emacs.stackexchange.com/questions/62493
Emacs unable to execute shell commands despite them being in the Emacs shell PATH
2020-12-28T01:42:35.247
# Question Title: Emacs unable to execute shell commands despite them being in the Emacs shell PATH I am on Ubuntu. I'm trying to run the `latex` command to run in the Emacs shell. I have done some research, and have already done the following: I noticed that running `env` in the Emacs shell gave a different value for PATH than running `env` in the normal terminal. I installed purcell's `exec-path-from-shell` to solve this. Following the directions, I copied my current terminal `PATH`, went to `.profile`, commented out lines of the kind `PATH = something_new:PATH` and just replaced it all with `PATH=my_whole_copied_path`. I then added `(exec-path-from-shell-initialize)` just after `(package-initialize)` in my `.emacs`. After doing this, running `env` in Emacs shell gives the same `PATH` as running `env` in my terminal. The latex binary lives in `/opt/texbin`, and my current Emacs `PATH` reads: ``` 'PATH=/opt/texbin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin' ``` Still, running latex give `command not found`. What am I missing? Update: I have learned that `/opt/texbin` is actually a symlink to a different location, and I've noticed that I can't `cd` into it in the Emacs shell. Could this be why this isn't working? Can I get shell to understand symlinks with an option? # Answer > 3 votes Solved it: it was because Emacs was installed as a flatpak. For some reason, this mean the Emacs shell had many differences. I wasn't able to `cd` into certain folders. Other folders didn't exist: `/usr/local`, for example. After uninstalling, and re-installing from the Ubuntu repository, everything works as expected. I hope this can be helpful to someone. My `PATH` was setup fine, and I was still running into this problem. I'd love it if someone could explain why installing it as a flatpak caused the Emacs shell to "see" such a different set of directories. --- Tags: shell, shell-command, shell-mode ---
thread-62499
https://emacs.stackexchange.com/questions/62499
:tstart and :tend not having any effect in org-clock-table output?
2020-12-28T11:14:45.033
# Question Title: :tstart and :tend not having any effect in org-clock-table output? I tried to specify `:tstart` and `:tend` in my clocktable block according to the official documentation, e.g. `#+BEGIN: clocktable :scope agenda :maxlevel 6 :stepskip0 t :fileskip0 t :compact t :link t :tstart "<2020-12-27 Sun 06:00>" :tend "<2020-12-28 Mon 06:00>"` I also tried a minimum example of `#+BEGIN: clocktable :tstart "<2020-12-26 Sun 06:00>" :tend "<2020-12-27 Mon 06:00>"` However, only the clock entries from today seem to be produced. The `:tstart` and `:tend` are always ignored, for whatever reason. # Answer > 2 votes I dug around a bit more, and just before I was about to post the question, I realized that I have ``` (setq org-clocktable-defaults '(:scope agenda :maxlevel 6 :stepskip0 t :fileskip0 t :compact t :block today)) ``` I didn't fully understand `org-clocktable-defaults`. I thought it would be the defaults copied to the `#+BEGIN: clocktable` part after you create a new clocktable in any buffer, but apparently this is not how it works. Instead, everything specified here will serve as the default values unless you explicitly override them. In this case, `:block today` is always taking effect, thus overriding the `:tstart` and `:tend` options. --- Tags: org-mode, org-clock, org-clock-table ---
thread-62484
https://emacs.stackexchange.com/questions/62484
get header with todo keyword
2020-12-27T16:12:24.253
# Question Title: get header with todo keyword ``` * one * two ** books *** IN-PROGRESS book1 *** book2 *** book3 * three * four ** five *** books **** book4 ``` How to get: 1. all headings title with todo-'IN-PROGRESS' keyword which are children of heading 'books' # Answer > 3 votes The simplest thing is to use `isearch` and look for `IN-PROGRESS`, then eyeball the heading to see if it's in a `books` hierarchy. Org mode files are plain text, so everything that applies to text applies to them as well. But assuming you want an Org mode specific method, here's a simple example implementation in the context of a slightly augmented version (adding a `TODO` list at the top and two more instances to test the matching) of your file: ``` #+TODO: START IN-PROGRESS | DONE * one * two ** books *** IN-PROGRESS book1 *** book2 *** book3 * three ** IN-PROGRESS book-not-3 * four ** five *** books **** book4 **** IN-PROGRESS book5 * Code :noexport: #+begin_src emacs-lisp :results drawer (defun ndk/select-heading () (if (member "books" (org-get-outline-path)) (org-get-heading t t t t))) (org-map-entries 'ndk/select-heading "/+TODO=\"IN-PROGRESS\"" 'file) #+end_src ``` **Explanation**: * `org-map-entries` takes a function and applies it on all entries that match a criterion in a given scope (here, the entries that match the `TODO` state `IN-PROGRESS` in the scope of the whole file). The matching is explained in the Matchings Tags and Properties section of the Org mode manual. In this case, we match every entry in the file whose `TODO` state is `IN-PROGRESS` and on each one, we apply the function `ndk/select-heading`. * The function `ndk/select-heading` is called at the beginning of each matching entry. It first gets the `breadcrumbs` of the entry, i.e. the path of headings leading from the top level to the entry as a list, and then checks whether `books` is a member of the list, i.e. whether the entry is a sub-entry of a `books` entry. If so, it returns the current heading, shorn of all extras (`TODO` state, tags, etc). If you press `C-c C-c` on the code block to run it, it will return `("book1" nil "book5")`, the first and last entries matching the state and being sub-entries of `books`, while the `nil` comes from an entry matching the state but which is *not* a sub-entry of `books` (the entry `book-not-3` in the file). Two more things: * The match specification has a short-cut form: instead of saying `"+TODO=\"FOO\""`, you can say `/+FOO`. But the match specification also allows the form `/+FOO-BAR` to specify that you want to match `FOO` but *NOT* `BAR`. That precludes your using the short form in your case because `/+IN-PROGRESS` would mean: match `IN` but *NOT* `PROGRESS` which is not what you want. So you have to use the long form or rename your states so that they don't contain dashes. * The search above is tailored to your exact criteria at the cost of hardwiring the values you are looking for into the code. It's not hard to write a more general function that takes these things as arguments, but it does complicate the code a bit, so I'll leave it as an exercise for the reader. If you understand the code above and have a little Lisp under your belt, you should be able to write the generalization easily. * It's also easy to get rid of any `nil` entries in the result if you don't want them: just say `(delete nil (org-map-entries ....))`. Note that `org-map-entries` is a very powerful function: it's a good idea to read its doc string with `C-h f org-map-entries` and also read the Using the Mapping API section in the manual. # Answer > 4 votes Another approach could be using org-ql. Here an example that should match your original question: ``` (require 'org-ql) (org-ql-query :select #'org-get-heading :from "/tmp/so.org" :where '(and (todo "IN-PROGRESS") (parent "books"))) ``` * The `:select` key denotes the function that will be called on each entry matching the predicate in the `:where` condition * `/tmp/so.org` is the name of the file where I saved the content prepared by @NickD --- Tags: org-ql ---
thread-62501
https://emacs.stackexchange.com/questions/62501
Footnote-like custom function for org-roam-insert
2020-12-28T12:51:33.503
# Question Title: Footnote-like custom function for org-roam-insert I am trying to make a custom function for org-roam which inserts footnote-like links in the current note. The idea is to insert links on this way ``` The logistic regression [fn:20200612000001]... * Footnotes [fn:20200612000001] [[file:20200612000001-definition_logistic_regression.org][Logistic regression]] ``` and the linked file has the form ``` :PROPERTIES: :ID: 20200612000001 :END: #+TITLE: Definition Logistic Regression ``` I just copy-pasted the original `org-roam-insert` function and hacked it a little to insert the footnote. The code is here https://gist.github.com/maikol-solis/ed149c16cff16a55492d1acba8c12025. However, after a couple of times using it, emacs crashes completely. I think that is caused by this function because this has never happened before. I used `gdb` to follow the crash and this is the output: ``` Thread 1 "emacs-gtk" received signal SIGSEGV, Segmentation fault. gui_produce_glyphs (it=0x7fff82fc3650) at xdisp.c:29925 29925 struct font *font = face->font; (gdb) next handle_sigsegv (sig=11, siginfo=0xc201f0 <sigsegv_stack+7152>, arg=0xc200c0 <sigsegv_stack+6848>) at sysdep.c:1876 1876 { (gdb) next 1882 if (!fatal && !pthread_equal (pthread_self (), main_thread_id)) (gdb) next 1886 if (!fatal && stack_overflow (siginfo)) (gdb) next 1890 deliver_fatal_thread_signal (sig); (gdb) next Thread 1 "emacs-gtk" received signal SIGSEGV, Segmentation fault. 0x00007fc45ddc1170 in raise () from /lib64/libpthread.so.0 (gdb) next Single stepping until exit from function raise, which has no line number information. [Thread 0x7fc44567f700 (LWP 28923) exited] [Thread 0x7fc4477fe700 (LWP 28922) exited] [Thread 0x7fc447fff700 (LWP 28921) exited] [Thread 0x7fc44df97700 (LWP 28920) exited] Program terminated with signal SIGSEGV, Segmentation fault. The program no longer exists. ``` I appreciate any help to solve this issue. Best. # Answer > 0 votes I updated the code and everything is working now. Around this line https://gist.github.com/maikol-solis/ed149c16cff16a55492d1acba8c12025#file-org-roam-insert-footnote-L47 I added this ``` (find-file target-file-path) (setq target-vector-id (car (org-roam--extract-ids target-file-path))) (kill-current-buffer) ``` I still don't know why occurred the crash, but it works. --- Tags: org-mode, doom, org-roam ---
thread-62506
https://emacs.stackexchange.com/questions/62506
What part of emacs displays parent folders at the top and how can I fix their symbols
2020-12-28T20:53:58.493
# Question Title: What part of emacs displays parent folders at the top and how can I fix their symbols I updated spacemacs and all layers/ packages today. Since then, when in c++-mode at the top of my buffers the current file and its parent folders are displayed, as shown in the image. I'm fine with the functionality but clearly there are some icons missing (as evidenced by the small squares containing "EsCC"). Where must I supply them? This line seems to be a feature of c++ layer as it also displays c++ - specific info like class names and namespaces. Here are all my layers, in case it helps: ``` go systemd javascript rust html yaml vimscript csv markdown auto-completion (python :variables python-backend 'anaconda) octave better-defaults emacs-lisp helm (lsp :variables lsp-ui-doc-enable t lsp-ui-sideline-enable t) (c-c++ :variables c-c++-backend 'lsp-clangd c-c++-lsp-cache-dir ".cache" c-c++-enable-clang-support t clang-format-style "file") (cmake :variables cmake-backend 'lsp cmake-enable-cmake-ide-support t) multiple-cursors spell-checking syntax-checking latex julia restructuredtext json ``` # Answer After ignoring the issue and just working on my project I realized that it must be part of the c++ layer. The solution for me is: You need to install additional fonts. What works, is installing all the fonts in the github repo of all-the-icons. > 1 votes --- Tags: spacemacs, c++ ---
thread-62508
https://emacs.stackexchange.com/questions/62508
Using two programming languages with the same file extension
2020-12-28T23:04:48.247
# Question Title: Using two programming languages with the same file extension I am just starting to set up a perl environment in emacs but the problem is that I already program with prolog and both languages use the `.pl` file extension. I have two directory `~/src/prolog` and `~/src/perl` where I store code for the respective languages. Currently I only have this line in my init: ``` (setq auto-mode-alist (append '(("\\.pl$" . prolog-mode)) auto-mode-alist)) ``` How can I tell emacs that `.pl` files in the `~/src/prolog` directory should use prolog-mode while the `.pl` files in `~/src/perl` should use cperl-mode? # Answer > 2 votes You're lucky that the files for the different languages are segregated by directory like that. You can define directory-local values for variable `auto-mode-alist`. See the Elisp manual, node Directory Local Variables. As the intro text of that node says: > This is useful when the files in the directory belong to some “project” and therefore share the same local variables. --- Tags: directory-local-variables, auto-mode-alist ---
thread-54590
https://emacs.stackexchange.com/questions/54590
pdf-tools asking to be rebuilt when emacs is started
2019-12-30T16:10:33.767
# Question Title: pdf-tools asking to be rebuilt when emacs is started My `init.el` file includes the line `(pdf-tools-install)` Recently whenever I open emacs I get the message `"Need to (re)build the epdfinfo program, do it now" (y or n)` which is rather annoying. I can't quite work out what to do in order to stop this from happening, and I can swear I remember this was not an issue when I originally set up pdf-tools. Has anyone come across this before, and/or know what to do? # Answer just uncomment `;;(pdf-tools-install)` in your `init.el`. If it once installed then it have not to do it every time. That worked for me, had the same problem. > 2 votes # Answer For me, when I looked closely at the messages for the compilation, I noticed that it mentioned that automake 1.16.3 couldn't be installed because an earlier version 1.16.3 was already installed. Even so, it told me that it compiled successfully, which I why I previously never looked at the compilation output very closely. It told me to run `brew upgrade automake`, and after doing so, and recompiling one last time, I no longer get this message. I still have `(pdf-tools-install)` in my .emacs file. > 0 votes --- Tags: pdf-tools ---
thread-54101
https://emacs.stackexchange.com/questions/54101
Elpy, autopep8 and line length
2019-12-02T15:17:54.053
# Question Title: Elpy, autopep8 and line length I'm struggling to get line length correctly setup under Elpy. I found How to customize the line character length in elpy? and have in the past found flycheck cannot find module for pylint. My configuration looks like (I've tried both `autopep8` and `yapf`)... ``` (add-hook 'python-mode-hook (lambda () (setq flycheck-python-pylint-executable "~/.virtualenvs/default/bin/pylint") (setq flycheck-pylintrc "~/.emacs.d/settings/.pylintrc"))) ;; enable autopep8 formatting on save (require 'py-autopep8) (add-hook 'elpy-mode-hook 'py-autopep8-enable-on-save) ;; (require 'py-yapf) ;; (add-hook 'python-mode-hook 'py-yapf-enable-on-save) ``` I have as per the suggestions in autopep8 · PyPI created `~/.config/pycodestyle` which contains... ``` [pycodestyle] max_line_length = 120 ignore = E501 ``` ...and yet on saving a file it doesn't apply the 120 character rule in so much as lines that are \> 120 characters are not auto-formatted and still reports in `*Messages*`... ``` line too long (124 > 79 characters) [E501] [2 times] ``` I've also set the following configuration option ``` (setq-default fill-column 120) ``` ...which I'm unsure whether it will be interfering with things. Any ideas or suggestions on how to configure autopep8 to automatically split lines at 120 characters would be very gratefully received as I feel like I've been going round in circles, despite seemingly trying the suggested solutions (I admit I may have misunderstood how to do this though or just cocked things up!). EDIT 2020-12-29 In light of answer from Chin-Ben I checked `elpy-config` I get... ``` Elpy Configuration Emacs.............: 27.1 Elpy..............: 1.35.0 Virtualenv........: python3_9 (/home/neil/.virtualenvs/python3_9/) Interactive Python: ipython 7.16.1 (/home/neil/.virtualenvs/python3_9/bin/ipython) RPC virtualenv....: rpc-venv (/home/neil/.config/emacs/elpy/rpc-venv) Python...........: python3 3.6.12 (/home/neil/.config/emacs/elpy/rpc-venv/bin/python3) Jedi.............: 0.16.0 (0.18.0 available) Rope.............: 0.16.0 Autopep8.........: 1.5 (1.5.4 available) Yapf.............: 0.29.0 (0.30.0 available) Black............: 19.10b0 (20.8b1 available) Syntax checker....: flake8 (/home/neil/.virtualenvs/python3_9/bin/flake8) Warnings There is a newer version of Jedi available. [Update jedi] There is a newer version of the autopep8 package available. [Update autopep8] There is a newer version of the yapf package available. [Update yapf] There is a newer version of the black package available. [Update black] ``` ...and have duly updated `jedi`/`autopep8`/`yapf`/`black` all of which are from the RPC env, but in doing so I noticed that `pip` was outdated as it reported... ``` You are using pip version 18.1, however version 20.3.3 is available. You should consider upgrading via the 'pip install --upgrade pip' command. ``` There are many versions of `pip` installed on my system in various places, one in `~/.local/bin/pip` along with many other commands (all dated from 2018, possibly from where I did a `pip install --user` before I understood virtual environments correctly). Removing `~/.local/bin/pip` didn't resolve this so its something else out of the many being picked up out of... ``` ❱ locate pip | grep bin | grep 'pip$' /home/user/.config/emacs/elpy/rpc-venv/bin/pip /home/user/.local/bin/pip /home/user/.virtualenvs/elpy-rpc-venv/bin/pip /home/user/.virtualenvs/floow_jobs/bin/pip /home/user/.virtualenvs/python3_9/bin/pip /home/user/.virtualenvs/python3_9/default/bin/pip /home/user/.virtualenvs/tcx2gpx-test/bin/pip /home/user/.virtualenvs/test/bin/pip /usr/bin/pip ``` Its not the system that is being picked up as that is up-to-date, the `elpy-rpc-venv`one is up-to-date too, but the `~/.config/emacs/elpy/rpc-venv/bin/pip` reports an error which is informative... ``` ❱ /usr/bin/pip --version pip 20.3.3 from /usr/lib/python3.8/site-packages/pip (python 3.8) ❱ /home/user/.virtualenvs/elpy-rpc-venv/bin/pip --version pip 20.3.3 from /home/user/.virtualenvs/elpy-rpc-venv/lib/python3.6/site-packages/pip (python 3.6) ❱ /home/user/.config/emacs/elpy/rpc-venv/bin/pip --version zsh: /home/user/.config/emacs/elpy/rpc-venv/bin/pip: bad interpreter: /home/neil/.emacs.d/elpy/rpc-venv/bin/python3: no such file or directory ``` ...and I've been having trouble with Jedi complaining about the EPC Server configuration... ``` Error (jedi): ================================ Failed to start Jedi EPC server. ================================ *** EPC Error *** make client process failed *** EPC Server Config *** Server arguments: ("/home/user/.virtualenvs/python3_9/default/bin/jediepcserver") Actual command: /home/user/.virtualenvs/python3_9/default/bin/jediepcserver VIRTUAL_ENV envvar: "/home/user/.virtualenvs/python3_9/" *** jedi-mode is disabled in #<buffer test.py> *** Fix the problem and re-enable it. *** You may need to run "M-x jedi:install-server". *** This could solve the problem especially if you haven't run the command yet since Jedi.el installation or update and if the server complains about Python module imports. ``` ...which the suggested course of action (`M-x jedi:install-server`) did not resolve. What stands out though is that... ``` ❱ /home/user/.config/emacs/elpy/rpc-venv/bin/pip --version zsh: /home/user/.config/emacs/elpy/rpc-venv/bin/pip: bad interpreter: /home/user/.emacs.d/elpy/rpc-venv/bin/python3: no such file or directory ``` ...indicates that something has gone awry when I moved from keeping my config under `~/.emacs.d` to `~/.config/emacs/` a while back. Suffice to say it looks like my virtual environments/EPC server are not working as intended, but this has been really useful in helping to identify this as I was baffled as to why I couldn't fix things. # Answer > 1 votes According to Elpy README, `flymake-mode` is used for syntax check. Not flycheck. See https://github.com/jorgenschaefer/elpy/blob/4032c7251eb2d74ec8a301a3988b62b7a0f00932/elpy.el#L3703 the line containing `(flymake-mode 1)`. If you prefer flycheck, please turn off `flymake-mode` and make sure **the virtual environment created by elpy is activated**. Steps to set up Elpy, * Please read its README at least once * Install latest Elpy from https://melpa.org * Set up Python environment and copy sample setup code into `~/.emacs` * Start Emacs, Elpy will automatically install all required python packages into a new virtual environment * Run `M-x elpy-config`, you got, * Add `(with-eval-after-load 'elpy (pyvenv-activate "~/.emacs.d/elpy/rpc-venv"))` into `~/.emacs` and restart Emacs. Or activate virtual environment manually by running command `source ~/.emacs.d/elpy/rpc-venv/bin/activate` in bash shell * Run `M-x elpy-config` again, you got, * Continue edit python code as usual. If you want to set up flake8, see https://flake8.pycqa.org/en/latest/user/configuration.html , > Flake8 supports storing its configuration in the following places: > > ``` > Your top-level user directory > In your project in one of setup.cfg, tox.ini, or .flake8. > > ``` You can run `source ~/.emacs.d/elpy/rpc-venv/bin/activate && flake8 --help && deactivate` to list all flake8 options. Extra tip, It's wise to backup all the required python packages in virtual environment, ``` source ~/.emacs.d/elpy/rpc-venv/bin/activate && pip freeze > elpy-requirements.txt && deactivate ``` You can restore the packages, ``` source ~/.emacs.d/elpy/rpc-venv/bin/activate && pip install -r elpy-requirements.txt && deactivate ``` # Answer > 0 votes I am using configuration per project. The configuration file`setup.cfg` is needed at root folder of your project. Below is my setting in setup.cfg. ``` [flake8] max-line-length = 120 [pycodestyle] max_line_length = 120 [yapf] column_limit = 120 ``` --- Tags: elpy ---
thread-62513
https://emacs.stackexchange.com/questions/62513
How to suppress the save buffer message in the minibuffer in Doom Emacs? (using Emacs 27)
2020-12-29T09:48:09.080
# Question Title: How to suppress the save buffer message in the minibuffer in Doom Emacs? (using Emacs 27) I'm using the `super-save` package which saves the buffer when an Emacs frame loses focus and it's spamming the minibuffer with '`file written`' messages, which gets distracting. I want to suppress this message in the minibuffer, so it doesn't appear anymore. I've tried to come up with solutions from this answer but I couldn't get it working. The answers also seem to be quite old, which makes me wonder about a more modern solution. It would be nice if someone could point me in the right direction, specifically for the Doom Emacs distribution using Emacs 27. # Answer I use the following to hide "Wrote ..." messages. I use regular GNU Emacs though. ``` (defun sb/inhibit-message-call-orig-fun (orig-fun &rest args) "Hide messages appearing in ORIG-FUN, forward ARGS." (let ((inhibit-message t)) (apply orig-fun args))) (advice-add 'write-region :around #'sb/inhibit-message-call-orig-fun) ``` I use `super-save` but I do not see the above messages in my minibuffer. You can give the above snippet a try. If the above does not work, you can try adding the following to the above snippet. ``` (advice-add 'save-buffer :around #'sb/inhibit-message-call-orig-fun) ``` > 2 votes --- Tags: doom ---
thread-62465
https://emacs.stackexchange.com/questions/62465
Suggestion/tips on markup for a note/annotation that is a question mixed with other notes?
2020-12-26T13:49:29.573
# Question Title: Suggestion/tips on markup for a note/annotation that is a question mixed with other notes? While using org-mode to take notes, e.g. when learning about something, I often have questions that I write down -- smack in the middle of the main notes. Right now I just use this markup/approach: ``` *** Some topic Lorem ipsum dolor sit amet, consectetur adipiscing elit. - Nisi ut aliquip. - Excepteur sint occaecat cupidatat non proident. - [ ] Q: What markup should I use in org-mode for small/local questions? Sunt in culpa qui officia deserunt mollit anim id est laborum. ``` Is there a better markup or way of doing it? E.g. using headings and tags? Use something like `TODO`? But I think `TODO/DONE` requires adding an extra heading, which affects the subsequent notes. Unless there's a markup to "go up one heading level" that I don't know about...? I'd like to be able to add an answer and mark the question as answered, as well as easily search for unanswered questions. I'm looking for some practical suggestions. To find unanswered questions I search my .org-file for `[ ] Q:`. Answers I sometimes put in as per below: ``` *** Some topic Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. - Nisi ut aliquip. - Excepteur sint occaecat cupidatat non proident. - [X] Q: What markup should I use in org-mode for small/local questions? - A: In practice there's no way that's significantly better than this. Sunt in culpa qui officia deserunt mollit anim id est laborum. ``` Note: Found slightly related question Different colors for questions and answers in org-mode # Answer > 1 votes This is only a partial answer to my own question regarding closing outline sections and introducing **inline tasks**. The question, asked: > But I think TODO/DONE requires adding an extra heading, which affects the subsequent notes. Unless there's a markup to "go up one heading level" that I don't know about...? An org-mode FAQ, https://orgmode.org/worg/org-faq.html#closing-outline-sections, indicates it is not possible to close the current heading level. The FAQ entry says: > The short answer to the question is no. Org-mode adheres to the cascading logic of outlines, in which a section is closed only by another section that occupies an equal or greater level. **inline tasks**: The FAQ entry also gives three workarounds of which the first suggests: "You can use inline tasks to create non-folding subsections. See the documentation in org-inlinetask.el, which is part of the org-mode distribution." In short an inline task might look like this: ``` **************** TODO A small task ``` or like this ``` **************** TODO some small task DEADLINE: <2009-03-30 Mon> :PROPERTIES: :SOMETHING: or other :END: And here is some extra text **************** END ``` I have not yet tested to see if this also solves my actual question. To conclude, I've for completeness extracted some documentation from `org-inlinetask.el` (version 9.4.2): > This module implements inline tasks in Org mode. Inline tasks are tasks that have all the properties of normal outline nodes, including the ability to store meta data like scheduling dates, TODO state, tags and properties. However, these nodes are treated specially by the visibility cycling. > > Visibility cycling exempts these nodes from cycling. So whenever their parent is opened, so are these tasks. This will only work with \`org-cycle', so if you are also using other commands to show/hide entries, you will occasionally find these tasks to behave like all other outline nodes, seemingly splitting the text of the parent into children. > > Special fontification of inline tasks, so that they can be immediately recognized. From the stars of the headline, only last two will be visible, the others will be hidden using the \`org-hide' face. > > An inline task is identified solely by a minimum outline level, given by the variable \`org-inlinetask-min-level', default 15. > > If you need to have a time planning line (DEADLINE etc), drawers, for example LOGBOOK of PROPERTIES, or even normal text as part of the inline task, you must add an "END" headline with the same number of stars. > > As an example, here are two valid inline tasks: ``` **************** TODO A small task ``` > and ``` **************** TODO Another small task DEADLINE: <2009-03-30 Mon> :PROPERTIES: :SOMETHING: another thing :END: And here is some extra text **************** END ``` > Also, if you want to use refiling and archiving for inline tasks, The END line must be present to make things work properly. > > Note that you should not try to use inline tasks within plain list, visibility cycling is known to be problematic when doing so. > > This package installs one new command: > > C-c C-x t Insert a new inline task with END line --- Tags: org-mode ---
thread-7432
https://emacs.stackexchange.com/questions/7432
Make visual-line-mode more compatible with org-mode
2015-01-16T07:02:28.830
# Question Title: Make visual-line-mode more compatible with org-mode `visual-line-mode` is very useful to wrap lines with the window size changing without inserting any newlines. But in `org-mode`, it also wraps the headline and source blocks which is a little bit annoying. So here comes my question: **How can I turn off visual-line-mode for org-heading and source blocks permanently in org-mode?** # Answer > 4 votes The package phscroll written by misohena perfectly solved the problem. It adds overlays to beginning/end of line if the width of elements like `org-table` exceeds the length, while keeps the line-wraps work. Currently it only supports org-table, but theoretically it can be extended to almost all org elements. # Answer > 20 votes Another solution is to use adaptive-wrap-prefix-mode. This way you'll see the full header and source but it will wrap nicely indented. With `visual-line-mode`: With `visual-line-mode` and `adaptive-wrap-prefix-mode`: # Answer > 1 votes This is a good question! The same issue applies when you have an Org table that is wider than `fill-column`. What I do is open the section in an indirect buffer with `org-tree-to-indirect-buffer` i.e. `C-c C-x b`. And in the indirect buffer, I disable visual-line-mode for editing that section. --- Tags: org-mode, line-break ---
thread-62525
https://emacs.stackexchange.com/questions/62525
Can you detect if a byte-compiled elisp file was not compiled by the current emacs?
2020-12-30T17:53:01.213
# Question Title: Can you detect if a byte-compiled elisp file was not compiled by the current emacs? Is there a way to tell if the current `*.elc` files were not compiled with the current Emacs? I am trying to detect an error where emacs is updated, but old `.elc` files are left in the user elpa directory and they are not compatible. # Answer > 1 votes Based on the hint from @Drew about the file header, this seems to work: ``` (defun elc-consistent-p (elc) "Return non-nil if ELC is consistent with current Emacs. ELC is the path to a .elc file. That means it was compiled with the same emacs major and minor version as the current emacs." (string= (with-temp-buffer (insert-file-contents elc) (goto-char (point-min)) (re-search-forward ";;; in Emacs version \\([0-9]\\{2\\}\\.[0-9]+\\)" nil t) (match-string 1)) (format "%s.%s" emacs-major-version emacs-minor-version))) ``` --- Tags: byte-compilation ---
thread-62526
https://emacs.stackexchange.com/questions/62526
Idiomatic way to store and access custom LaTeX code
2020-12-30T17:54:34.573
# Question Title: Idiomatic way to store and access custom LaTeX code I have some latex classes or bunch of packages I use and that I'd like to move out of my `init.el` because it keeps on growing and I want them to be standalone. How can I make them accessible from my init ? For example would the following structure work : ``` .emacs.d/ | |-------------- init.el |-------------- early-init.el |-------------- lisp/ |-------------- snippets/ |-------------- latex/ | |------- templates.el ``` write something (minimal working example) like ``` (require 'ox-latex) (add-to-list 'org-latex-classes '("notes" "\\documentclass[myLanguage]{article} \\usepackage{somePackage} \\usepackage{someOtherPackage}")) (provide 'templates) ``` and then in my `init.el` ``` (use-package ox-latex :after org :defer t :load-path (concat user-emacs-directory "latex/templates.el") :config (more-config-stuff...)) ``` Would that work or am I painting myself into a corner here? # Answer You need to do this: ``` (use-package template :after org :defer t :load-path (lambda () (concat user-emacs-directory "latex")) :config (more-config-stuff...)) ``` `(concat user-emacs-directory "latex")` does not get evaluated in use-package, so you can use a function that returns what you need instead. I am assuming ox-latex is already on your load-path with org-mode, and what you are really trying to do is load templates.el. Alternatively, just do something like this in init.el `(load-file (concat user-emacs-directory "latex/templates.el"))` > 1 votes --- Tags: init-file, use-package ---
thread-62495
https://emacs.stackexchange.com/questions/62495
How can I mark sections of a very large `org-agenda` file as read-only?
2020-12-28T07:31:22.817
# Question Title: How can I mark sections of a very large `org-agenda` file as read-only? I prefer to work in one large `org-agenda` file. I have my appointments and notes in there from the past five years. I do not want to accidentally change any parts of my old entries while adding new information. I do not like to archive entries but keep them as they are. I would like to set some headings as "read only". How can I do that? Or how can I at least make it more difficult for me to make any accidental changes to these headings and their contents, perhaps by "locking" them somehow? I am running Emacs 27 on Windows 10. # Answer > 2 votes Here is some lightly improved code that preserves the modified state when applied.For me tasks that are readonly do get listed in the agenda, but I get a bell error about text being read-only. I guess org-agenda is trying to set some properties on the text or something, and is having trouble because it is read-only. I don't see a real way around that. ``` (defun org-mark-readonly () (interactive) (let ((buf-mod (buffer-modified-p))) (org-map-entries (lambda () (org-mark-subtree) (add-text-properties (region-beginning) (region-end) '(read-only t))) "read_only") (unless buf-mod (set-buffer-modified-p nil)))) (defun org-remove-readonly () (interactive) (let ((buf-mod (buffer-modified-p))) (org-map-entries (lambda () (let* ((inhibit-read-only t)) (org-mark-subtree) (remove-text-properties (region-beginning) (region-end) '(read-only t)))) "read_only") (unless buf-mod (set-buffer-modified-p nil)))) (add-hook 'org-mode-hook 'org-mark-readonly) ``` # Answer > 0 votes I did find one very useful solution since posting my question: Make some org-sections read-only --- Tags: org-mode, org-agenda ---
thread-62534
https://emacs.stackexchange.com/questions/62534
How to make "M-x man" buffers use all the available width of the screen?
2020-12-31T00:00:02.397
# Question Title: How to make "M-x man" buffers use all the available width of the screen? # The problem When opening `man` in a terminal emulator, `man` tries to use as much width as possible. However, when opening `man` inside `emacs`, `man` doesn't use all the width (even after `Man-update-manpage` has been executed.) In the gif shown below, I open the `emacs` manual page in a terminal emulator and we can see that the manual page uses all the available width. However, this doesn't happen when this manual page is opened inside `emacs`. The instance of `emacs` shown in the GIF was opened by executing `emacs -Q`. # The question How can I make `M-x man` display manual pages so that they use all the available width? # Answer > 8 votes Try `(setq Man-width-max 160)`, or `(setq Man-width-max nil)`. The documentation of `Man-width-max` says: ``` This variable was introduced, or its default value was changed, in version 27.1 of Emacs. Maximum number of columns allowed for the width of manual pages. It defines the maximum width for the case when ‘Man-width’ is customized to a dynamically calculated value depending on the frame/window width. If the width calculated for ‘Man-width’ is larger than the maximum width, it will be automatically reduced to the width defined by this variable. When nil, there is no limit on maximum width. ``` --- Tags: buffers, man ---
thread-26699
https://emacs.stackexchange.com/questions/26699
Keycode for `Shift + Return` on OS X iterm2
2016-08-30T22:24:27.947
# Question Title: Keycode for `Shift + Return` on OS X iterm2 I'm currently trying to learn org-mode in OS X. And I found there's a keymap `M-S-RET`. But `S-RET` is not recognized in the iTerm2. * It seems like terminal interpret `S-RET` and `RET` as same. * iTerm2 can bind a `S-RET` in the GUI preference tab. (PREFERENCE-\>PROFILE-\>KEY) * I can bind `S-RET` and send hex value instead of 13. (13 is keycode for RET) But I can't find what's the keycode for the `S-RET`. Actually, I think `Shift` \+ `Enter` does not exist as keycode. However, there must be some key combination that Emacs uses. How can I figure it out? Are there any files containing that information? Thank you for reading. # Answer `C-c C-x M` is an alternative for `M-S-Ret` http://orgmode.org/manual/TTY-keys.html#TTY-keys > 5 votes # Answer As Eric notes above, there is an alternative key binding for `M-S-Ret`: > C-c C-x M is an alternative for M-S-Ret (More precisely, both are bound to `(org-insert-todo-heading)` in org-mode.) You can set iTerm2 to send the hex codes corresponding to the alternative key sequence when you press `M-S-Ret`, thereby invoking the same function and behavior. The required hex codes: * `C-c` is 0x03 * `C-x` is 0x18 * `M` is 0x4D Assuming that you are using the Option key as the Meta key on your Mac keyboard, go to iTerm2 Preferences \> Profiles \> Keys and map `Option-Shift-Return` to send these codes. Now, when you press `Option-Shift-Return` (i.e., `M-S-Ret`), iTerm2 sends `C-x C-x M`. Et voilà. > 2 votes # Answer There isn't really a standard escape sequence for `Shift`+`Return`. You could say that there are two standards, but each of them is only followed by a small number of terminals: * libtermkey: `"\e[13;2u"` * xterm: `"\e[27;2;13~"` But Emacs only activates them if it can figure out that the current terminal sends them. Since iTerm2 doesn't send them by default, Emacs doesn't activate them. You might as well use one of these sequences. To activate them unconditionally, put the following code in your init file (this code is from `terminal-init-xterm` in `term/xterm.el`): ``` (load "term/xterm") (let ((map (copy-keymap xterm-function-map))) (set-keymap-parent map (keymap-parent input-decode-map)) (set-keymap-parent input-decode-map map))) ``` For more information and some explanation of these escape sequences, see Problems with keybindings when using terminal > 1 votes --- Tags: org-mode, key-bindings, keymap ---
thread-62537
https://emacs.stackexchange.com/questions/62537
How can I invoke Flutter "Context commands" interactively (from lsp-dart)
2020-12-31T03:29:26.467
# Question Title: How can I invoke Flutter "Context commands" interactively (from lsp-dart) I was beyond stoked to discover how complete Flutter support is in Emacs these days thanks to the seemingly polished `lsp-dart` (featured prominently in the official "get started" docs for Flutter, awesome). Anyways, when I hover over a Flutter widget while `lsp-ui` is enabled I get this nice yellow list of "Context Actions" hovering off to the right that I can click on to perform the action, just like in Android Studio. I'm trying to figure out how to use those without touching my mouse, but I can't for the life of me figure out what commands they're actually running. I've grepped around my entire elpa directory to no avail. (Yes the time I've spent researching this question has probably already outweighed the time I'll save by not having to touch my mouse, but it's really about comfort and joy, isn't it?) Are these interactive commands that I can run? Alternatively, does anyone know how this hovering list is built in `lsp-ui`? Might help with the source dive. # Answer The LSP server just provides a list of action names that are applicable, and the client must request that the server invoke them. This means that the client doesn't actually know how they're implemented or what the full set of actions will be, and that they cannot be interactive commands. Instead there is only a command that lets you select which action you want to invoke, `lsp-execute-code-action`. If I recall correctly, the default key binding for it is `C-c l a a`. I recommend installing `which-key` mode if you haven't already. If you hesitate after typing a prefix key such as `C-c`, it pops up a menu to remind you what options are available. This makes exploring the labyrinthine recesses of LSP mode easier. > 1 votes --- Tags: lsp, lsp-ui ---
thread-62520
https://emacs.stackexchange.com/questions/62520
How to add a string at nth position of an ordered list of strings
2020-12-29T20:38:11.827
# Question Title: How to add a string at nth position of an ordered list of strings The built-in function `add-to-ordered-list` is for symbols, not strings. I have a list of strings and need to add another string to the list at a specific nth position. How can I accomplish this? **TASK**: Add `"--cleared"` as the *nth 3* position of the ordered list; i.e., `"--cleared"` will become the 4th string in the list of strings. \[I am using the *nth N* terminology to signify that the first position is *nth 0* followed by *nth 1* and so on.\] **BEFORE**: ``` '("%(binary)" "-f" "%(ledger-file)" "--empty" "--depth=3" "--no-total" "--amount" "'($1,000.00*a)/$1,000.00'" "--format" "hello-world" "bal") ``` **AFTER**: ``` '("%(binary)" "-f" "%(ledger-file)" "--cleared" "--empty" "--depth=3" "--no-total" "--amount" "'($1,000.00*a)/$1,000.00'" "--format" "hello-world" "bal") ``` # Answer > 3 votes Here's one way to do this: ``` (let ((l (list "%(binary)" "-f" "%(ledger-file)" "--empty" "--depth=3" "--no-total" "--amount" "'($1,000.00*a)/$1,000.00'" "--format" "hello-world" "bal"))) (push "--cleared" (nthcdr 3 l)) l) ;; => ("%(binary)" ;; "-f" ;; "%(ledger-file)" ;; "--cleared" ;; "--empty" ;; "--depth=3" ;; "--no-total" ;; "--amount" ;; "'($1,000.00*a)/$1,000.00'" ;; "--format" ;; "hello-world" ;; "bal") ``` This relies on the fact that `nthcdr` (and other similar functions) exist predefined as generalised variables; see `(info "(elisp) Generalized Variables")` and its subnodes. **N.B.:** The above example constructs the list using the `list` function to ensure that it is safely mutable (since we subsequently want to modify it). Alternatively, you could pass a constant list literal to `copy-sequence` before modifying it. Modifying a quoted literal list would be wrong because such constants are part of the program and their mutations can persist over multiple evaluations of the same code. In other words, they result in undefined behaviour; see `(info "(elisp) Mutability")`. # Answer > 0 votes @Basil answered your question of how to get done what you want to do. This "answer" is instead to confirm that you *cannot* use `add-to-ordered-list` to do what you request, and to say why that's the case. You correctly said, *"add-to-ordered-list is for symbols, not strings"*. More precisely, it's only for list elements that can be distinguished using `eq` (e.g., not `equal` or `string=`) -- that's the *why*. The implementation of `add-to-ordered-list` uses a hash table to associate an "order" with some or all of the elements of a list. And the `:test` function for the hash table is `eq`. In addition, the function uses `memq` (which is also an `eq` test) to test for list membership. This use of `eq` is hard-coded. I've filed Emacs bug #45539, to allow for other identity-distinguishing predicates besides `eq`. That would let you use `add-to-ordered-list` with strings, etc. --- There's some confusion about what `add-to-ordered-list` does. It's not really about changing the positions of elements of ordinary lists or replacing an element at a particular position with some other value. It's about recording the order of elements in a list that's designed for that purpose: ordering them by some associated recorded number. You can also have other elements in such a list, which have no recorded order. Such elements are placed at the end of the list, after any elements for which you've specified an order. You can think of a specified order as a "score" of some kind. The list elements are placed in increasing numerical order of those scores, and any list elements that have no associated score are placed at the end of the list. If you give multiple elements the same score (recorded "order") then they appear consecutively in the list; that's all. For them, you're in effect saying that the order among them in the list is not important, as they all have the same score. You can *remove* the recorded score for a given element by calling `add-to-ordered-list` with it, and providing *no* `ORDER` argument (or a `nil` argument). That doesn't remove the element from the list; it just stops it from have a recorded (i.e., reserved) order, which moves it after any elements that do have recorded orders. Here is another question (on StackOverflow) about `add-to-ordered-list`, which is similarly confused about it. Hope this helps. See also this StackOverflow question. --- Tags: list, sorting ---
thread-16641
https://emacs.stackexchange.com/questions/16641
What packages are available for modal editing?
2015-09-15T20:03:28.833
# Question Title: What packages are available for modal editing? What packages are available for modal editing in Emacs? What do you use and why? *Let's try to post one package per answer. I propose mention advantages and shortcomings of every package.* --- Here is my definition of modal editing (I couldn't find dedicated Wikipeadia article): *Modal editing* — style of text editing when user periodically switches usually between “normal mode” when keys do not cause inserting of their characters but perform various operations on text and “insert mode” when keys insert corresponding characters. There may be more modes, of course. Most modern editors are not modal. An example of modal text editor is Vi (Vim). # Answer # `evil`, the *E*xtensible *VI* *L*ayer for Emacs Questionable name aside, `evil` is the current state-of-the art when it comes to `vim` emulation in Emacs (and possibly anywhere else, for that matter). It supports a lot of features that other Vim emulation packages eschew, including: * `vim` textobjects * `vim` registers * `vim` keyboard macros * `ex` commands # Advantages * Key compatibility with `vim` means **you don't lose your muscle memory when switching to systems without Emacs.** * Very mature and widely used (lots of community packages, for example) + Many package for `vim` have been ported to `evil`. * `vim` style grammar is modular and lends itself very well to user extension * `evil` itself is very extensible: make your own textobjects, operators, and motions! # Disadvantages * **Will probably require some fiddling to make it play nice with other packages** + Fortunately, `evil` makes the most common use-cases ridiculously easy. * `evil` is a very complex system. Hacking on the evil core can become quite involved. * `vim` keybindings are not necessarily ergonomically optimal. Sometimes, they can feel a little arbitrary when ported to a different system. * Hosted on BitBucket (mercurial) make of this what you will. > 13 votes # Answer There is `god-mode` (https://github.com/chrisdone/god-mode), which uses standard Emacs key bindings but removes the need to hold down modifiers. When god-mode is enabled, `C-...` bindings require no modifier and `M-...` bindings use a prefix rather than a modifier. An example from the GitHub page: > Before: C-p C-k C-n M-^ ) C-j C-y M-r C-x z z M-2 M-g M-g C-x C-s > > After: p k n g ^ ) j y g r . . 2 g g x s > 13 votes # Answer Modalka must be the newest kid on the modal editing block. The github project seems to be all of 10 days old. I don't have enough usage time to comment or evaluate, but here's how it is described: > This is a building kit to help switch to modal editing in Emacs. Main goal of the package is making modal editing in Emacs as natural and native as possible. There is no hack, no corner cases, no emulation — just start edit modally the way you want. The documentation also compares and contrasts Modalka with other common modal solutions, such `evil`, `god-mode`, `boon`, etc. > 7 votes # Answer # Boon Boon is one of less-known packages for modal editing. It doesn't emulate Vi (or Vim) but provides original layout optimized for Colemak keyboard layout. ## Advantages and Design Principles * Spacial allocation first, mnemonics second: the allocation of keys to commands is based in priority on the locations of keys on the keyboard. Whatever is printed on the key cap is a secondary concern. * Easy finger rolls: common combination should either be left/right hand alternation or easy one-hand rolls. * Use of home row and strong fingers for the most used commands * Easy navigation: many commands are bound to navigation. This facilitates moving around. Because movements double up as region-definitions, it makes manipulation commands (operators) more powerful. ## Disadvantages * You need to re-learn how to interact with the editor since collection of editing primitives and their placement on keyboard are quite unique. > 6 votes # Answer Adding my own, thanks @Mark for encouragement. # Xah Fly Keys Designed from the ground up for emacs, with the goal of being the MOST efficient system, from years experience with ergoemacs-mode. Key choices are science based as much as possible, based on statistics of key frequency and key easy-to-press score. Most frequently used commands are mapped to the most easy-to-press keys. Other issues, such as grouping, and keybinding bigram, are also considered from 3 years of weekly experiment. Interesting Points: * All C-x commands are done by sequence of 2 to 3 single keys. In xah-fly-keys, C-x is never necessary. M- is never necessary neither. * Does not conflict with any GNU emacs's keys, because it does not bind Ctrl or Meta (except C-7, C-8, but not essential). You can have xah-fly-keys on in insert mode, and use GNU Emacs the way you normally do. * Also considered what set of commands results in max editing efficiency. So, the package uses ~80 custom editing commands. (for example, copy will copy current line if there's no selection. One single command to toggle letter case, instead of GNU Emacs's ~6 variations of upper/lower/region/no-region.) * The implementation is as simple as possible. No macro, no advice, no complex remapping of keys, only a couple hooks are used. (good or bad?!) * Supports over 10 keyboard layouts, including: QWERTY, dvorak, colemak, colemak-mod-dh, qwerty-abnt, qwertz, azerty, programer-dvorak, workman, norman. Disadvantages: * Like learning vi for the first time, you'll need one month to adopt. * Less well known than evil-mode. * For major modes, you still need to use C-c. (so, you might use other packages such as god-mode or hydra to solve this problem.) I'm the author, so be warned that I may be unconsciously biased. Feel free to comment or correct. > 6 votes # Answer Ergoemacs also supports modal editing. It doesn't emulate vi, but uses Alt key for most frequently used commands. For example, moving cursor is Alt plus right hand inverted T. (On QWERTY it is `Alt`+`j` for `left`, `Alt`+`l` for right, `Alt`+`i` for `up` and `Alt`+`k` for `down`). Deleting char or word is `Alt` with left hand home-row keys. Key choices are based on command frequency and key's position for ease-of-press. * To start modal editing, the user can press `f6`. + Once `f6` was pressed, the most frequently used keys no longer require an alt key combination. + Therefore, on QWERTY, `j` is `left`, `j` is `right`, `i` is `up` and `k` is down). * The modal command mode is exited by pressing `return`, `f6` or `escape`. In addition to the traditional modal paradigm, there is a quasi modal paradigm that allows any `C-x` or `C-c` key combination to be reached without using any modifiers (like god-mode). * The quasi-modal is started with the QWERTY `apps` `f` for `C-c` with the control key pressed down and the QWERTY `apps` `d` for `C-x`. * While completing this key sequence the `apps` key will change the type of modifiers that are assumed to be pressed down. * Once the command has been called, ergoemacs resumes the editing mode. * During any key sequence you can also change the types of keys that are held down. This is by simply pressing the `apps` key again. In addition to changing the command keys, ergoemacs-mode allows you to change things about the key sequence while typing it: * You can edit the prefix argument during the middle of a key sequence by pressing `f2`. * Pressing `backspace` takes back the last key pressed. * `Apps` allows you to change the keys held down during any key sequence. ergoemacs-mode also attempts to respect anything the mode does to the fundamental keys. For example, if org-mode defines a special key for `next-line`, ergoemacs uses this command for `Alt`+`k` when in org-mode. **Advantages:** * Part of GNU Emacs, in ELPA. * Supports “universal” Windows/Linux keys out of the box. e.g. Open (`C-o`), Close (`C-w`), Select all (`C-a`), Copy (`C-c`), Cut (`C-x`), Paste (`C-v`), etc. * Fairly popular. * Supports many layouts, including Qwerty, dvorak, colemak, bepo, and many other international layouts that adjust the keys to make sure they are on the home row (M-i in QWERTY would be M-u in colemak). * Shows an image of your keyboard layout in emacs by describing the theme. * Keys are customizable via a extension system, by creating a theme. * You can setup any arbitrary modal keymap (not yet documented). **Disadvantages:** * Stable is slow on startup. + In the unstable master, the first startup is slow (~5 seconds for minimal setup), (~20 seconds for my startup) + The second second startup is much quicker (for my complex setup it is ~4 seconds). + This is because ergoemacs-mode is changing and caching every active keymap in emacs. On second startup, these settings are saved. * Complex code. See https://github.com/ergoemacs/ergoemacs-mode > 4 votes # Answer Another semi-modal option is Hydra: https://github.com/abo-abo/hydra According to the website Imagine that you have bound C-c j and C-c k in your config. You want to call C-c j and C-c k in some (arbitrary) sequence. Hydra allows you to: * Bind your functions in a way that pressing C-c jjkk3j5k is equivalent to pressing C-c j C-c j C-c k C-c k M-3 C-c j M-5 C-c k. Any key other than j or k exits this state. * Assign a custom hint to this group of functions, so that you know immediately after pressing C-c that you can follow up with j or k. I haven't used it but it seems interesting. > 3 votes # Answer # Meow A new modal editing package which borrows ideas from Kakoune, modalka and god-mode. ### Desgin Principles * Meow has four modes, `INSERT`, `NORMAL`, `MOTION`, `KEYPAD`. * Almost no default keybinding, Meow provides a complete set of commands, user have to build their own keymap. But you will find some recommends in README, which make your customization easy. * Combined navigation & selection commands. Like Kakoune, commands for navigation will also activate the selection(region). You can use `meow-insert`/`meow-append` to insert at beginning or append at end. Meow has much fewer commands, but can still manipulate text quickly. * Provide a MOTION mode to integrate with those special modes, like dired, treemacs, magit, etc, you don't have to write a lot configurations for each package. * KEYPAD mode is a single-shot god-mode, allows you to execute vanilla Emacs command without modifiers. > 2 votes # Answer ## RYO (Roll Your Own) I read this post for inspiration, but ended up using `ryo-modal-mode` It is based on `modalka-mode` and allows for just one command layer that is not preconfigured, so you can add vim-like keys or just **use emacs keys without `Ctrl` key.** On the plus side there are keywords which allow you to use keys only in specific major modes and run functions before or after the key function. I found the **documentation very accessible** on github and on the developers blogpost. There he gives examples on how to use Hydra on top of ryo, too. As a beginner I found this mode easy to setup and configure. > 1 votes --- Tags: key-bindings, prefix-keys ---
thread-62536
https://emacs.stackexchange.com/questions/62536
What does "Making browse-url-browser-function local to *eww* while let-bound!" mean?
2020-12-31T03:08:11.303
# Question Title: What does "Making browse-url-browser-function local to *eww* while let-bound!" mean? I am using SLIME (which includes hyperspec.el). I wanted to view the HyperSpec using Emacs' EWW instead of the desktop web browser (e.g. Firefox, Chromium, etc.). To do this, I added an advice to set the web browser to EWW for looking at the HyperSpec: ``` (advice-add 'hyperspec-lookup :around (lambda (orig-fun &rest args) (let ((browse-url-browser-function 'eww-browse-url)) (apply orig-fun args)))) ``` However, I always get the following message in the `*Messages*` buffer the first time I use `hyperspec-lookup` after starting Emacs. ``` Making browse-url-browser-function local to *eww* while let-bound! ``` Is this an error message? What does it mean? How do I fix it? # Answer The problem can be solved by replacing the let-binding with `setq-local`: ``` (advice-add 'hyperspec-lookup :around (lambda (orig-fun &rest args) (setq-local browse-url-browser-function 'eww-browse-url) (apply orig-fun args))) ``` > 0 votes --- Tags: advice, eww, slime ---
thread-62548
https://emacs.stackexchange.com/questions/62548
How to automatically use rjsx-mode instead of js-jsx-mode
2020-12-31T23:19:02.183
# Question Title: How to automatically use rjsx-mode instead of js-jsx-mode When I work with JSX files Emacs automatically switches to `js-jsx-mode` and acts sluggishly. When I switch it to `rjsx-mode` it works much faster. So the idea is to override one mode with another, so that rjsx-mode is used instead of js-jsx-mode. What is the best way to achieve this effect? # Answer > 1 votes Starting from Emacs 27.1, this will depend on whether or not you want `C-h``v` `js-jsx-detect-syntax` to be taken into account. When that option is enabled, the default `js-mode` will inspect the syntax of Javascript files with a plain `.js` filename extension and decide whether or not to enable JSX support. When that option is NOT enabled (or if you are using Emacs 26), the decision is purely based on whether or not the filename has a `.jsx` extension. If your JSX files will *always* have the `.jsx` extension, then you could do this: ``` ;; Use `rjsx-mode' for .jsx files. ;; `auto-mode-alist' is already taken care of if you've ;; installed `rjsx-mode' as a package. ;; (add-to-list 'auto-mode-alist '("\\.jsx\\'" . rjsx-mode)) ;; Never check for JSX syntax in regular .js files. (setq js-jsx-detect-syntax nil) ``` If there's a chance that the syntax checking is needed, then integrating the two turns out to be a little fiddly, on account of `js-mode` still being an ancestor of `rjsx-mode`. Try the following config: ``` ;; Use `rjsx-mode' for JSX files. ;; `auto-mode-alist' is already taken care of if you've ;; installed `rjsx-mode' as a package. ;; (add-to-list 'auto-mode-alist '("\\.jsx\\'" . rjsx-mode)) (advice-add 'js-jsx-enable :override #'my-js-jsx-enable) (defun my-js-jsx-enable () "Use `rjsx-mode' instead of `js-jsx-mode'." (cl-letf (((symbol-function 'js-jsx--detect-and-enable) (lambda () t))) (rjsx-mode))) ;; Prevent the `rjsx-mode' ancestor `js-mode' from continuing to check ;; for JSX code. (add-hook 'rjsx-mode-hook (lambda () (remove-hook 'after-change-functions #'js-jsx--detect-after-change t))) ``` You might check the issue queue for `rjsx-mode`, and open a new issue if necessary, so that this sort of thing could be addressed by default. Note that in Emacs 27.1 the actual minor mode `js-jsx-mode` is just one of multiple possible ways for `js-jsx-enable` to be called, and consequently there's no benefit to targeting this mode specifically. This *was* different in earlier versions of Emacs, however it looks as if (a) `js-jsx-mode` didn't do very much before Emacs 27.1, and (b) it was only triggered for `.jsx` filenames (which we've already accounted for); so regardless of which Emacs version you're using, I don't believe there's any benefit to messing with `js-jsx-mode` itself. --- Tags: js-mode, jsx, rjsx-mode ---
thread-62543
https://emacs.stackexchange.com/questions/62543
Replace expressions including variable text
2020-12-31T16:35:43.133
# Question Title: Replace expressions including variable text I wish to create a function to put in my `.emacs` (but I am no Elisp expert) in order to perform a certain number of replacements within an Emacs buffer. In particular, I want to: * replace any occurrence of `\pnotes{*}` (where `*` is some variable stuff, e.g. `\pnotes{1.73}`, `\pnotes{1.41}`...) with `\notes` followed by a line break * delete any occurrence of `\ast{*}` (where `*` is some variable stuff, e.g. `\ast{0.03}`, `\ast{.70}`...) * replace any occurrence of `\nextvoice` with the same string preceded by a line break * replace any occurrence of `\ib` with the same string preceded by a line break; * replace any occurrence of `|` with the same character preceded by a line break * replace any occurrence of `&` with the same character preceded by a line break * replace any occurrence of `\en%` with `\en` preceded by a line break How can I achieve that? # Answer All your questions have a solution involving replacements using regular expressions. Browse for ``` (info "(emacs) Regular Expression Search") ``` . You can use M-x re-builder to build a regular expression. For example ``` (query-replace-regexp "\\\\pnotes {[^}] *}" "\\\\notes ") ``` will solve your first question, ``` C-M-% \\pnotes{[^}]*} RET \\notes C-q C-j RET ``` in interactive mode. ``` (query-replace-regexp "\\\\ast{[^}]*}" "") ``` will solve your second. ``` (query-replace-regexp "\\(\\\\nextvoice\\)" " \& ") ``` will solve the third and subsequent ones by replacing \\\\nextvoice with an appropriate expression. In interactive mode, backslashes don't need to be doubled, for example for the last regexp, type ``` C-M-% \(\\nextvoice \) RET C-q C-j \& RET ``` The newline character is inserted by C-q C-j, you will understand. > 0 votes --- Tags: replace ---
thread-62476
https://emacs.stackexchange.com/questions/62476
Toggle between most recent buffers
2020-12-27T03:28:23.417
# Question Title: Toggle between most recent buffers I'm using doom Emacs in case that's relevant. I want a key binding to go back to the most recently used buffer in the window. When I'm in that buffer and hit the key binding, it should go back to the buffer I stared out in. So hitting the key binding repeatedly should toggle between the 2 most recently used buffers. So far I've tried several approaches from what I've found on the internet. `next-buffer` and `privious-buffer` both do nothing. I've also tried this function: ``` (defun switch-to-previous-buffer () (interactive) (switch-to-buffer (other-buffer (current-buffer) 1))) ``` When I call this function, no matter what buffers I've had opened previously, it goes to the scratch buffer (Fallback buffer), and hitting it again does nothing. I'm now looking for an alternative, I'm new to Emacs and a total noob in elisp, so a brief explanation would be appreciated. Edit: The function I gave as an example actually does work, the problem is in fact with doom Emacs, more specifically with org-roam. When org-roam is installed, and I open emacsclient, I don't get a dashboard, which is part of the issue. For now, I've removed org-roam, this has solved the issue. # Answer > 4 votes I use the built-in `mode-line-other-buffer` command to toggle between the two most recent buffers, with a convenient key binding since I use this all the time. You may want to compare what that function is doing with your own attempt. Note that `other-buffer` does what I believe you want without the additional arguments you are passing in your attempt. # Answer > 0 votes Does this do what you want? ``` (defun my-switch-buf (buffer) "Switch to BUFFER. Like `switch-to-buffer', but don't change buffer-list order." (interactive "BBuf: ") (switch-to-buffer buffer 'no-record)) (global-set-key (kbd "C-x b") 'my-switch-buf) ``` `C-h f switch-to-buffer` says this about optional arg `NORECORD` (which you used in your trial command): > If optional argument `NORECORD` is non-`nil`, do not put the buffer at the front of the buffer list, and do not make the window displaying it the most recently selected one. But maybe you don't want to have to hit `RET`. This simple command makes you hit `RET`, to accept the default value. So to go back and forth you'd use `C-x b RET`, not just `C-x b`. # Answer > 0 votes I have this bound to `F8`: ``` (defun ph/flip-window () "Flips to the last-visited buffer in this window." (interactive) (switch-to-buffer (other-buffer (current-buffer)))) ``` --- Tags: buffers ---
thread-62560
https://emacs.stackexchange.com/questions/62560
How to send keyboard interrupt to running program in shell mode?
2021-01-02T08:53:41.790
# Question Title: How to send keyboard interrupt to running program in shell mode? I wish to achieve what a `C-c` (send a keyboardinterrupt) would do in a terminal outside of Emacs. How do I do that in Emacs shell mode? # Answer In Shell mode (and many other modes that run an external command interpreter), press `C-c C-c` (`comint-interrupt-subjob`). That's the `C-c` prefix of mode-specific commmands, followed by `C-c` which is chosen to be like `C-c` in a plain terminal. > 1 votes --- Tags: shell, shell-mode ---
thread-52100
https://emacs.stackexchange.com/questions/52100
Scripted bookmark jump not working after startup
2019-08-10T17:21:58.870
# Question Title: Scripted bookmark jump not working after startup 1. Add the following to .spacemacs: ``` (defun my-bookmark-set (char) (interactive "cPlease enter a bookmark name to set: ") (bookmark-set (char-to-string char))) (defun my-bookmark-jump (char) (interactive "cPlease enter a bookmark name to jump to: ") (bookmark-jump (char-to-string char))) (define-key evil-normal-state-map (kbd "'") 'my-bookmark-jump) (define-key evil-normal-state-map (kbd "m") 'my-bookmark-set) ``` 2. Set a bookmark a with C-x r m a or ma, and quit and restart emacs 3. Navigation to bookmark a fails with "Invalid bookmark a" displayed ``` 'a ``` 4. Navigation to bookmark a succeeds ``` C-x r b a ``` 5. Move cursor to another location 6. Navigation to bookmark a succeeds ``` 'a ``` Why does the action at step 3. fail, when at step 6. and subsequently it succeeds? # Answer > 0 votes Your problem is that `bookmark-jump` doesn't load the bookmark file, and until that happens your bookmark is unknown. If you check the `interactive` declaration for that function, you'll see that it uses `bookmark-completing-read` which in turn calls `bookmark-maybe-load-default-file` which is what you also need to do if you're not going to use the same method of reading the bookmark name. ``` (defun my-bookmark-jump (char) "Jump to bookmark CHAR." (interactive "cPlease enter a bookmark name to jump to: ") (require 'bookmark) (bookmark-maybe-load-default-file) (bookmark-jump (char-to-string char))) ``` # Answer > 0 votes It's not clear what error you're getting, and when. First you say that you get an `Invalid bookmark` error, without providing a recipe. Then you provide a recipe, I think, for the void-function-definition error. What's the real problem/question? --- Anyway, ignoring the invalid-bookmark problem, do you see the same void-function-definition problem if you start Emacs using `emacs -Q` (no init file)? If not, bisect your init file to find the culprit. If you do see the same thing, do `M-x debug-on-entry my-bookmark-jump` and show the Backtrace you get when you invoke `my-bookmark-jump`. --- Tags: debugging, bookmarks ---
thread-62558
https://emacs.stackexchange.com/questions/62558
orgmode - resize inline image in windows
2021-01-02T04:08:13.197
# Question Title: orgmode - resize inline image in windows I have installed emacs27 on windows from official release. when I run orgmode with inline image, the image do not resize according to width attribute (400 as below example)! ``` #+attr_org: :width 400 #+attr_latex: :width 400 #+attr_html: :width 400 [[./sample.png]] ``` Then I search orgmode source code and found below section (lisp/org.el): ``` (defcustom org-preview-latex-process-alist '((dvipng :programs ("latex" "dvipng") ... (imagemagick :programs ("latex" "convert") :description "pdf > png" :message "you need to install the programs: latex and imagemagick." :image-input-type "pdf" :image-output-type "png" :image-size-adjust (1.0 . 1.0) :latex-compiler ("pdflatex -interaction nonstopmode -output-directory %o %f") :image-converter ("convert -density %D -trim -antialias %f -quality 100 %O"))) :group 'org-latex :version "26.1" :package-version '(Org . "9.0") :type '(alist :tag "LaTeX to image backends" :value-type (plist))) ``` I have installed imagick.exe and the convert command should be "magick convert". I need to customize the image-converter to below line: ``` ("magick.exe convert -density %D -trim -antialias %f -quality 100 %O"))) ``` Is it possible to customize it in init.el file? Or any other proper way to call "magick.exe convert" instead of "convert"? # Answer > 1 votes It is probably easier to use `Customize` on the variable: say `C-h v org-preview-latex-process-alist`, click on the `customize` link, scroll down to the `ImageMagick` section, find the `:image-converter` property and change its value; then save the customization for this and future sessions. If you are intent on doing it manually, try the following in your `init.el`: ``` (with-eval-after-load 'org (plist-put (cdr (assq 'imagemagick org-preview-latex-process-alist)) :image-converter '("magick.exe convert -density %D -trim -antialias %f -quality 100 %O"))) ``` Disclaimer: all this shows is how to change the property. I don't run Windows, so I have not tested the command itself. --- Tags: org-mode ---
thread-62565
https://emacs.stackexchange.com/questions/62565
is there a defcustom type for a keymap?
2021-01-02T16:16:35.407
# Question Title: is there a defcustom type for a keymap? I have some defcustom variables that are for keymaps. Is there a way to set the :type in a defcustom to indicate it should be a keymap? Is the right way to do it like this? ``` :type '(restricted-sexp :match-alternatives keymapp) ``` # Answer > 0 votes Almost right. `:match-alternatives` needs to be a *list* of predicates: ``` :type '(restricted-sexp :match-alternatives (keymapp)) ``` And consider maybe also allowing the value to be a keymap variable (depending on what you really want): ``` :type '(restricted-sexp :match-alternatives ((lambda (x) (or (keymapp x) ; Can be a keymap var. (and (symbolp x) (boundp x) (keymapp (symbol-value x))))))) ``` --- Tags: defcustom ---
thread-62563
https://emacs.stackexchange.com/questions/62563
Vim-like EOL behavior in Emacs
2021-01-02T13:09:53.847
# Question Title: Vim-like EOL behavior in Emacs I'm trying to get Emacs to imitate Vim's EOL behavior. Namely at the end of line ("\n"), the cursor comes to a halt instead of progressing to the start of the next line. The following works fine and dandy but the cursor gets stuck before empty lines: ``` (defun make-eol-intangible () (interactive) (add-hook 'post-command-hook (lambda () (when (and (point) (looking-at "\n")) (backward-char)) t t))) ``` I could put an additional condition that tests for (point) looking-back however Emacs docs mention that looking-back should be avoided, and is possibly deprecated. On that note it's probably less optimal to use looking-at either. I would like some suggestions. --- Amended function (doesn't work as expected): ``` (defun make-eol-intangible () (interactive) (add-hook 'post-command-hook (lambda () (when (and (eq (char-before (point)) ?\n) (eq (char-after (point)) ?\.)) (backward-char))))) (make-eol-intangible) ``` # Answer Something along these lines. ``` (defun make-eol-intangible () (interactive) (add-hook 'post-command-hook (lambda () (when (and (eq (char-before (point)) ?\n) (not (eq (line-end-position) (line-beginning-position)))) (left-char))))) ``` --- Found a better solution: ``` (defun my-maybe-right () "Move right if char at point is not a newline." (interactive) (unless (= (following-char) ?\n) (forward-char))) (global-set-key [right] #'my-maybe-right) ``` > 1 votes --- Tags: vim-emulation ---
thread-62302
https://emacs.stackexchange.com/questions/62302
Helm-find-files on org link
2020-12-16T04:07:13.797
# Question Title: Helm-find-files on org link When we call `helm-find-files` on an org link or path, helm is smart enough to autocomplete the path, making it easy for us to navigate from there. Unfortunately, if the link starts with \[\[file:./this/file/name.png\]\], then helm extended actions fail, because helm can't find a file that starts with "file:". Does anyone know how I could advice helm-find-files to trim the "file:" part of a link? # Answer Here's how you can advice helm to strip the `file:` part: ``` (advice-add 'helm-find-files-initial-input :filter-return (lambda (&optional input) (if (string-prefix-p "file:" input) (replace-regexp-in-string "file:\\(.+\\)" "\\1" input) input))) ``` > 1 votes --- Tags: org-mode, helm ---
thread-62577
https://emacs.stackexchange.com/questions/62577
How do I show initial-scratch-message when the *scratch* buffer is recreated?
2021-01-03T17:18:10.573
# Question Title: How do I show initial-scratch-message when the *scratch* buffer is recreated? By default, a `*scratch*` buffer is created when Emacs starts. The initial `*scratch*` buffer contains the following message by default: ``` ;; This buffer is for text that is not saved, and for Lisp evaluation. ;; To create a file, visit it with C-x C-f and enter text in its buffer. ``` This message appears to be set by the variable `initial-scratch-message`. If I kill (`C-x k`) the initial scratch buffer and recreate it using `C-x b *scratch*`, the new scratch buffer will be blank. It will not contain the `initial-scratch-message`. This is not what I want. I want to see the message. How do I configure all scratch buffers to contain `initial-scratch-message` when they are recreated? # Answer The internal function `set-buffer-major-mode` within `buffer.c` will run the function attached to the `initial-major-mode` variable if the buffer-name is `*scratch*`. The Lisp function `window-normalize-buffer-to-switch-to` within `window.el` calls `set-buffer-major-mode`. Therefore, creating a custom function and attaching it to the `initial-major-mode` variable seems like the most appropriate course of action given the desire by the O.P. to use the buffer-name `*scratch*`. Using `substitute-command-keys` in conjunction with the `initial-scratch-message` will transform `\\[find-file]` into `C-x C-f`. ``` (setq initial-major-mode (lambda () (insert (substitute-command-keys initial-scratch-message)) (lisp-interaction-mode))) ``` The default value of the variable `initial-scratch-message` in Emacs 27.1 is: ``` (purecopy "\ ;; This buffer is for text that is not saved, and for Lisp evaluation. ;; To create a file, visit it with \\[find-file] and enter text in its buffer. ") ``` > 0 votes --- Tags: scratch-buffer ---
thread-44570
https://emacs.stackexchange.com/questions/44570
Check box counter function applied to todo items in org-mode
2018-09-05T17:43:13.977
# Question Title: Check box counter function applied to todo items in org-mode In org-mode, is there a function to perform the \[x/y\] counter function on a list of "todo" items, similar to that feature which exists for checkbox? (That is, to automatically count the number of items that are in a non-done state.) # Answer > 1 votes I think comments below your question already provide the answer for your question. But also check here, that guide you how you can make this counter recursive across the hierarchy of nested to-dos. --- Tags: org-mode ---
thread-62586
https://emacs.stackexchange.com/questions/62586
function to search and replace multiple words - necessary to goto-line 1 every time?
2021-01-04T00:40:45.250
# Question Title: function to search and replace multiple words - necessary to goto-line 1 every time? This is a very rudimentary question, but I have a document in which I need to replace many different words fairly frequently, so I created a function that goes like this: ``` (defun chikan () (interactive) (goto-line 1) (replace-string "ichi" "one") (goto-line 1) (replace-string "ni" "two") ) ``` The actual function is a lot longer (the words in the example are just placeholders). I figured out that I had to stick the `(goto-line 1)` before every `(replace-string)` because it was going through the whole doc on the first sweep and then stopping, and not replacing words later in the list. My rudimentary question: is there another way to make it search and replace all words in a document? # Answer > 1 votes How about using `replace-regexp`, which contains optional arguments for `START` and `END`? To control lazy highlighting while the search is being performed, the variable `query-replace-lazy-highlight` can be customized or let-bound to the desired setting; e.g., `nil` for no lazy highlighting. See also the variables `lazy-highlight-initial-delay` and `lazy-highlight-interval`. ``` (defun chikan () "Doc-string." (interactive) (replace-regexp "\\<ichi\\>" "one" nil (point-min) (point-max)) (replace-regexp "\\<ni\\>" "two" nil (point-min) (point-max))) ``` The following example uses an `alist` (similar to the data structure of a Python dictionary), which is an application requested by the O.P. in a follow-up comment underneath the question hereinabove: ``` (defun chikan () "Doc-string." (interactive) (let ((alist '(("ichi" . "one") ("ni" . "two")))) (dolist (elt alist) (replace-regexp (concat "\\<" (car elt) "\\>") (cdr elt) nil (point-min) (point-max))))) ``` Rather than using word boundary delimiters in the first argument as depicted in this example, see the optional argument in `replace-regexp` for DELIMITED which contains a doc-string entry as follows: "*Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace only matches surrounded by word boundaries. A negative prefix arg means replace backward.*" For an answer that deals with regexp matches that excludes surrounding word constituents, see https://stackoverflow.com/a/5941448/2112489 , the text of which is copied hereinbelow for convenience: The regexp `\<foo\>` or `\bfoo\b` matches `foo` only when it's not preceded or followed by a word constituent character (syntax code `w`, usually alphanumerics, so it matches in `foo_bar` but not in `foo1`). Since Emacs 22, the regexp **`\_<foo_bar\_>`** matches `foo_bar` only when it's not preceded or followed by a symbol constituent character. A symbol constituent is either a word constituent or a character with syntax `_`. Most programming mode define `_` to be a symbol constituent. --- Tags: search, replace ---
thread-62573
https://emacs.stackexchange.com/questions/62573
Is it possible to add descriptions for the yas-choose-value choices?
2021-01-03T15:30:11.200
# Question Title: Is it possible to add descriptions for the yas-choose-value choices? I got a simple snippet for the opening a file in PHP: ``` fopen('${1:./filename.txt}', '${2:$$(yas-choose-value '("r" "w" "a" "x" "r+" "w+" "a+" "x+"))}') or die(); ``` So when I get to the choose the file opening mode, r,w,a,x... I get the dropdown: ``` r w a . ``` But I would like to add a description of whats the function of each mode, like: ``` r - Open read only w - Open for write erases content . . ``` Is it possible to do this with `yas-choose-value`? # Answer I would suggest using an alist of choices, with the `car` being the choice`+`description and the `cdr` being the actual choice. There are a variety of options that `yasnippet` offers for user input (see `yas-prompt-functions` with a default value of `yas-dropdown-prompt`, `yas-completing-prompt`, `yas-maybe-ido-prompt`, and `yas-no-prompt`), some of which may not support an alist of choices. As indicated in a comment above, the user is not confined to either `yas-choose-value` or `yas-completing-read`. The key ingredient is `(unless (or yas-moving-away-p yas-modified-p) ...)` with the `...` needing to be replaced with the custom Lisp that does whatever you want. Here is a custom example that uses `ido`: ``` fopen('${1:./filename.txt}', '${2:$$(unless (or yas-moving-away-p yas-modified-p) (require 'ido) (let* ((choices-alist '(("r - Open read only" . "r") ("w - Open for write erases content" . "w") ("a - The 'a' description." . "a") ("x - The 'x' description." . "x") ("r+ - The 'r+' description." . "r+") ("w+ - The 'w+' description." . "w+") ("a+ - The 'a+' description." . "a+") ("x+ - The 'x+' description." . "x+"))) (choice (ido-completing-read "Please choose one: " choices-alist nil 'confirm))) (cdr (assoc choice choices-alist))))}') or die(); ``` --- The following ticket requests that the Emacs team implement support for ido tab completion using an alist collection, and I have provided a draft proof concept for said implementation: http://debbugs.gnu.org/cgi/bugreport.cgi?bug=46091 > 3 votes --- Tags: yasnippet ---
thread-62524
https://emacs.stackexchange.com/questions/62524
Recent files by project rather than recent files and recent projects separately
2020-12-30T15:19:43.280
# Question Title: Recent files by project rather than recent files and recent projects separately **Note**: This question is really about Projectile and Recentf. I'm using them in the context of Spacemacs, so I describe that context, but the question isn't really intended to be Spacemacs-specific. The Spacemacs home buffer, which can be configured via `dotspacemacs-startup-lists`, show by default a number of recent files and projects. They are, however, displayed in two separate lists, so if I've been working with a lot of files in one project, then all the recent files are from one project, even if I set `recents` to a large amount like 24, all the recent files will be from one project. What I'd really like is to see the recent files *by project*. Suppose for example I had a `vegetables` project and a `fruit` project. I would want to see something like: > vegetables > > * vegetables/lettuce.el > * vegetables/squash.el > * vegetables/tomatoes.el > > fruit > > * fruit/apple.py > * fruit/orange.py > * fruit/banana.py How can I achieve this with Recentf/Projectile? Is this a matter of configuration, or of needing to just code up the logic myself? # Answer Seeing that no one offered an answer here, I dug more into the code that Spacemacs is using for this, and it appeared that there was no pre-existing solution; since the code is rather Spacemacs-specific, I doubt there is some existing package out there that does it. As such, I implemented it and submitted a PR to Spacemacs, which has been merged. The feature is available in Spacemacs now, and anyone educated in Emacs Lisp could port it to their own configs if necessary. > 0 votes --- Tags: projectile, recentf ---
thread-61605
https://emacs.stackexchange.com/questions/61605
How can helm be configured to return a nil result when the user cancels?
2020-11-07T00:45:08.667
# Question Title: How can helm be configured to return a nil result when the user cancels? This function selects one of the items in projectile's project list, but when I cancel the select using `Ctrl-G` an item is still returned. Whatever candidate the selection is on is returned even if the dialog is cancelled. Is there some setting to override this behaviour? ``` (defun vh-select-project() (interactive) (let ( (projectlist (with-temp-buffer (save-excursion ;;(insert "(progn\n") (insert-file-contents-literally (expand-file-name "projectile-bookmarks.eld" user-emacs-directory)) (goto-char (point-max)) ;;(insert "\n)") (read (buffer-string))))) (input (progn (helm :sources (list (helm-build-sync-source "Select project:" :candidates projectlist))) (helm-marked-candidates) ))) (when project (insert (car project) "")) ) ) ``` # Answer You're missing the action slot (see the last line): ``` (helm :sources (helm-build-sync-source "Select project:" :candidates projectile-known-projects :action 'insert)) ``` > 1 votes --- Tags: helm, completion ---
thread-57506
https://emacs.stackexchange.com/questions/57506
Open file in orgmode with external application. Check if file exists and create file from template if necessary
2020-04-01T06:09:42.410
# Question Title: Open file in orgmode with external application. Check if file exists and create file from template if necessary I want to create a file with `org-open-at-point` from a template if that file does not exist. If it exists, I want to open it in an external app. In org-mode, file-links are created by `[[file:path-to-file.ext]]`. `Enter` or `C-c C-o` opens that file. This behavior is defined by `org-file-apps` depending on the file extension. According to the docs, `org-file-apps` can take functions as argument: ``` Possible values for the command are: string A command to be executed by a shell; %s will be replaced by the path to the file. function A Lisp function, which will be called with two arguments: the file path and the original link string, without the "file:" prefix. ``` `(add-to-list 'org-file-apps '("\\.svg\\'" . "inkscape %s"))` opens that file in inkscape. I wrote a function to create the file beforhand if it does not exist: ``` (defun inkscape-open (path &optional link) "Open the path in inkscape. Copy template if path does not exist." (unless (file-exists-p path) (shell-command (format "cp /home/jolla/Dropbox/org/sketches/default.svg %s" path))) (shell-command (format "inkscape %s" path)) ) ``` and set it for svg-files: ``` (add-to-list 'org-file-apps '("\\.svg\\'" . inkscape-open)) ``` 1.) This does not work: emacs tells me that the file does not exist. If it exists, emacs opens the file. 2.) I would like to modify my function so that it only creates the file if a specific directory (like Dropbox/org/sketches) is in path. What would I have to do? 3.) How can I switch focus to inkscape after org-open-at-point? --- PS: if I create a new link-parameter like `[[svg:path-to-file.ext]]` like this: ``` (org-link-set-parameters "svg" :follow (lambda (path) (let ((actions '(("find-file" . find-file) ("edit in inkscape" . inkscape-open)))) (funcall (cdr (assoc (completing-read "Action: " actions) actions)) path)))) ``` I can chose `inkscape-open` and the function works as expected. This is also described here. However, I don't want to create a new link type because this would prevent org-mode from showing inline images. # Answer > 0 votes OK, this appears to be quite complicated. I found two solutions, both of which require a good deal of lisp knowledge. 1. `org-open-at-point` pipes the file link to `org-open-file`. This function checks if the file exists first, before handling `org-file-apps`. This behavior is hardcoded in `org.el`. So I would have to change the function to skip the file exists check. 2. I could alternatively add svg-images to the images displayed in org-buffers. This behavior is also hardcoded in `org.el` in `org-display-inline-images`, I think this is the code I would need to change: ``` (file-types-re (format "\\[\\[\\(?:file%s:\\|attachment:\\|[./~]\\)\\|\\]\\[\\(<?file:\\)" (if (not link-abbrevs) "" (concat "\\|" (regexp-opt link-abbrevs))))) ``` I am not literate enough in emacs-lisp to accomplish this. --- As a workaround, I wrote a script for autokey, which espands on `[ink` and asks for a file-name, copies my template, inserts the link and opens inkscape. Here is the code: ``` import shutil retCode, new_file = dialog.input_dialog(title='file name', message='Enter a file name') path = "/home/jolla/Dropbox/org/sketches/" # copy template shutil.copyfile(path + "default.svg", path + new_file + ".svg") # write link output = "[[{}{}.svg]]".format(path, new_file) keyboard.send_keys(output) # open inkscape ret = system.exec_command('inkscape {}{}.svg &'.format(path, new_file), getOutput=False) ``` # Answer > 0 votes What you are asking to do sounded a lot like what Binnema did in mu4e to open attachments at a point in mu4e specifically in the mu4e-view section of his package, like so: ``` (defun mu4e-view-open-attachment-with (msg attachnum &optional cmd) "Open MSG's attachment ATTACHNUM with CMD. If CMD is nil, ask user for it." (let* ((att (mu4e~view-get-attach msg attachnum)) (ext (file-name-extension (plist-get att :name))) (cmd (or cmd (read-string (mu4e-format "Shell command to open it with: ") (assoc-default ext mu4e-view-attachment-assoc) 'mu4e~view-open-with-hist))) (index (plist-get att :index))) (mu4e~view-temp-action (mu4e-message-field msg :docid) index 'open-with cmd))) ``` I suspect that you are working on getting the same thing Dirk-Jan gets from the attatchment link. It seems like it is difficult to organize them in a way to produce images inline effectively in every case, but this works to open the attachments in their native applications, just not in an embedded fashion. I suspect it is better in some cases for you as there is native support for the existing files (like in your svg example) that you don't want to miss out on. You stated that the native support would have to be added to emacs itself, but I think you can add that to an org-mode extension instead of working directly on the built-in application like Binnema does with org-mu4e. --- Tags: org-mode, files, org-link ---
thread-62597
https://emacs.stackexchange.com/questions/62597
Font face (highlighting) of single-quoted strings stopped working after update
2021-01-04T20:21:24.250
# Question Title: Font face (highlighting) of single-quoted strings stopped working after update I'm using a custom mode that I believe is based on `cc-mode`, and it's been working great for years. Recently, I upgraded to Ubuntu 20.04, which brought Emacs to 26.3 (I forget what it was before, maybe 25.2.2), and now, my single-quoted strings are not being highlighted correctly anymore (while double-quoted strings are working fine): How can I fix this? # Answer > 0 votes Well, I didn't want to downgrade emacs for a simple formatting problem, but I suppose that's my option as I wait for a better answer. I didn't find a repo for 20.04 with old emacs 25, so I built it from source. Here's what I did, in case you or I have to do it again: First, remove apt-installed emacs: ``` sudo apt-get remove --purge emacs emacs-gtk ``` Download http://mirrors.ocf.berkeley.edu/gnu/emacs/emacs-25.2.tar.gz \- personally I untarred it in `/opt/` which may require sudo or chown My first `./configure` complained about missing support for gif, tiff, and xpm -- don't care, build without. ``` cd /opt/emacs-25.2 ./configure --with-xpm=no --with-gif=no --with-tiff=no make ``` Finally, symlink this to `/usr/bin/emacs` so it's available system-wide: ``` sudo ln -s /opt/emacs-25.2/src/emacs /usr/bin/emacs ``` And voila, the formatting works again, highlighting single-or-double quoted strings the same: --- Tags: font-lock ---
thread-62611
https://emacs.stackexchange.com/questions/62611
Is it possible to see if a library is loaded after another one?
2021-01-05T19:24:48.377
# Question Title: Is it possible to see if a library is loaded after another one? I am trying to find out if a library has been loaded after another one. For example has the ox-bibtex library been loaded after the org-ref library. I know you can look at `fboundp`, `featurep`, but I need to know the order of loading. I thought I coudl use something like `(seq-position obarray 'org-ref-command)` but obarray seems to have symbols that are not even loaded. The reason for this is in this case, the second library is clobbering something in the first library, and I am looking for a way to see what order things have been loaded. # Answer > 4 votes I remembered `load-history`with that, I came up with this that seems to work. Libraries that are loaded more recently have a smaller position (i.e. closer to the beginning of the list). ``` (let ((org-ref-i (seq-position load-history (assoc (locate-library "org-ref") load-history)) ) (ox-bibtex-i (seq-position load-history (assoc (locate-library "ox-bibtex") load-history)))) (and org-ref-i ox-bibtex-i (> org-ref-i ox-bibtex-i))) ``` --- Tags: load ---
thread-62602
https://emacs.stackexchange.com/questions/62602
How do I keep the indentation on org-babel-tangle?
2021-01-05T09:19:47.897
# Question Title: How do I keep the indentation on org-babel-tangle? In literate programming, I often like to write my code in small snippets and then export them all at once via `org-babel-tangle`. This works great for non-indentation sensitive code (especially with post-processing), but doesn't work quite well with languages like Haskell or Python as `org-babel-tangle` removes the initial whitespace: ``` This is a completely self-contained example of the problem. Copy it into an org-mode buffer and try both =M-x org-export-dispatch= and =M-x org-babel-tangle=. * A simple Python function :PROPERTIES: :header-args:python: :tangle example.py :padline no :END: Here's a small example function in Python: #+begin_src python :shebang "#!/usr/bin/env python" def foo(): #+end_src According to org-mode's documentation[fn:1], we can use `-i' to keep the indentation, so let's do that on the continuation of the aforementioned example: #+begin_src python -i """Says hello!""" print("Hello, world!") #+end_src If we (org-export-dispatch) the file, then everything seems nice. However, if we (org-babel-tangle) the file, then the indentation is gone and thus our Python file invalid. * Footnotes [fn:1] See [[info:org#Literal Examples][info:org#Literal Examples]]. ``` The `-i` switch doesn't seem to work for `org-babel-tangle` at all. While I could use `<<noweb>>` to glue the code together in a hidden, non-exported source block, I would rather like to have org-babel-tangle behave correctly. Is there some hidden option I'm missing? **How can I keep the indentation when I tangle files via org-babel-tangle similarly to the `-i` switch for exporting?** # Answer > 4 votes You can use the variable `org-src-preserve-indentation`. If you set it to `t` before tangling like this: ``` #+begin_src emacs-lisp (setq org-src-preserve-indentation t) #+end_src ``` then the tangle will work as you expect. The variable is defined with a `defcustom` so it is meant to be customized as you wish. You can either set it in your init file as above or customize it by hitting the `customize` link in its docstring, which you get with `C-h v org-src-preserve-indentation`. EDIT: As a couple of comments point out, Emacs provides a **very general** mechanism (it can be used in any file, not just Org mode files) for setting the value of a variable as a *local, per-file* variable. As the documentation of file local variables points out, you can add a section at the very *end* of the file, like this: ``` ... * File local variables :noexport: # Local Variables: # org-src-preserve-indentation: t # End: ``` Tagging the section as `noexport` prevents it from cluttering up any exported material. Alternatively, you can add a single line (as a comment, so that Org mode will ignore it) at the *top* of the file like this: ``` # -*- org-src-preserve-indentation: t -*- ... ``` Local variables are activated when the file is opened, so after adding the local variable, you either have to save and kill the buffer and then reopen the file, or perhaps more conveniently do `M-x normal-mode`. If you get a question about `safe local variables`, you might want to add this variable to the list of safe local variables by pressing `!`. --- Tags: org-mode, indentation, tangle ---
thread-62610
https://emacs.stackexchange.com/questions/62610
magit on Windows over plink tramp
2021-01-05T17:58:53.847
# Question Title: magit on Windows over plink tramp I'm scratching my head on this problem, but I cannot seem to use magit on a project served over plink or plinkx on Windows. What does work: * The windows client can use magit on a project stored locally (e.g. from `C:\`) * The windows client can connect fine to the remote project (`dired` works, as does `find-file`) * A WSL2 Emacs instance works fine from the same laptop, only using ssh instead of plink What happens when I try using plink(x): 1. In a file in a git repository, I run magit-status 2. Instead of the normal buffer, I'm asked for the "Git repository:" in the mini-buffer. The value defaults to the current directory. 3. Whatever I try as a value for "Git repository", I'm presented with "Create repository in $FOO? (y or n) 4. If I select y I'm told "Not inside git repository" Does anyone have any idea what's going on? I'm running `GNU Emacs 27.1 (build 1, x86_64-w64-mingw32) of 2020-08-21` according to `(emacs-version)`. It's not a deal-breaker to me as I'm using WSL2 and an X-Server, but I'm curious and hopefully this will help my understanding of both TRAMP and magit, so any tips appreciated. # Answer I've found the issue. The error messages as posted in the question could have been a little more helpful. The error messages were unambiguous when I ran `(magit-status "/plink:....")` from the scratch buffer: ``` Error (magit): Magit cannot find Git on /plink:$HOST:. First check the value of `magit-git-executable'. Its value is used when running git locally as well as when running it on a remote host. The default value is "git", except on Windows where an absolute path is used for performance reasons. If the value already is just "git" but TRAMP never-the-less doesn't find the executable, then consult the info node `(tramp)Remote programs'. ``` TL;DR: Adding `(setq magit-git-executable "git")` to my .emacs.d/init.el fixed it for me. > 1 votes --- Tags: magit, microsoft-windows, tramp ---
thread-21770
https://emacs.stackexchange.com/questions/21770
Automatically switch focus to new window
2016-04-22T01:35:00.520
# Question Title: Automatically switch focus to new window Is there a way to automatically switch focus to any new windows? For example, if I `C-h f some-function`, that creates a new window. But the focus remains where I was, so when I'm done reading and hit `q`, I just type a `q` in whatever buffer I was in previously. Ideally, I'd like to always switch focus to a new window whenever one is created. Ideas? # Answer > 4 votes ## Help windows Add this to your init.el to automatically focus any help window you see. Then, you'll be able to quit it with Q. ``` (setq help-window-select t) ; Switch to help buffers automatically ``` Alternatively, if you're using use-package, I recommend adding this to your init.el (or appending to an existing `(use-package emacs ...` declaration): ``` (use-package emacs :custom (help-window-select t "Switch to help buffers automatically")) ``` This does not change it for other buffers, such as the buffer that opens when you run pp-macroexpand-last-sexp, though. ## Automatically switch focus to new windows when you make them Add this block of code which I copied from the witchmacs repository: ``` (defun split-and-follow-horizontally () (interactive) (split-window-below) (balance-windows) (other-window 1)) (global-set-key (kbd "C-x 2") 'split-and-follow-horizontally) (defun split-and-follow-vertically () (interactive) (split-window-right) (balance-windows) (other-window 1)) (global-set-key (kbd "C-x 3") 'split-and-follow-vertically) ``` Alternatively, if you're using use-package, I recommend not adding `(global-set-key...)` to your config and using ``` (use-package emacs :bind (:map ctl-x-map ("2" . split-and-follow-horizontally) ("3" . split-and-follow-vertically))) ``` You can also put the function definition into `:config`. ## Changing the behavior globally Add this to your init.el ``` (defadvice split-window (after split-window-after activate) (other-window 1)) ``` # Answer > 2 votes Here is how to solve the problem. The problem you describe has two parts, really. One part is to change focus (like you describe), so the "q" is sent to the *Help* window. The second part is to get back to your original window. I solved the issue by forcing the *Help* window to pop up over top of my current window, so that I can just type "q" to dispatch the help window and return to my original buffer. The method shown below can be extended to any of the usual *whatever* Apropos, Help, etc windows. Good luck. `(add-to-list 'display-buffer-alist '("*Apropos*" display-buffer-same-window)) (add-to-list 'display-buffer-alist '("*Help*" display-buffer-same-window))` --- Tags: window, focus ---
thread-62617
https://emacs.stackexchange.com/questions/62617
How to export an html file with a foldable & dynamic TOC from an org file?
2021-01-06T01:10:12.323
# Question Title: How to export an html file with a foldable & dynamic TOC from an org file? When HTML pages are extended I find it quite useful to have a TOC (table of Content) available all along with your scrolling. A good example of an implementation of such a functionality is the Worg webpages (here is an example), which are generated from org files. So my question is, how is this done? Is it done through a CSS file? If it is, what would the CSS code be? # Answer Following line has to be put on top of your org file: ``` #+HTML_HEAD: <link rel="stylesheet" type="text/css" href="https://orgmode.org/worg/style/worg.css"/> ``` > 1 votes # Answer It's done with a Javascript library called `org-info.js`, written by Sebastian Rose. See the Javascript support section of the Org mode manual. There is also some additional documentation in Worg. > 2 votes --- Tags: org-mode, org-export, html, css ---
thread-62624
https://emacs.stackexchange.com/questions/62624
What parameter in orgtbl-to-latex to set column width?
2021-01-06T06:28:01.603
# Question Title: What parameter in orgtbl-to-latex to set column width? I am trying to set the alignment width of columns in latex. I am using orgtbl's `orgtbl-to-latex` I want to override the resultant ``` \begin{tabular}{lllll} ``` to something like ``` \begin{tabular}{rlccp3 cm)} ``` What is the argument of the translator function `orgtbl-to-latex` that do that? # Answer The `:splice` argument appears to be meant for this purpose. When non-nil, it omits the environment from the table-receiver block, which gives you the opportunity to write it manually. For a minimal example: ``` \documentclass{article} \usepackage{comment} \begin{document} \begin{tabular}{rlccp{3cm}} % BEGIN RECEIVE ORGTBL foo ipsum & curabitur & lacinia & pulvinar & nibh\\ ipsum & curabitur & lacinia & pulvinar & nibh\\ % END RECEIVE ORGTBL foo \end{tabular} \begin{comment} #+ORGTBL: SEND foo orgtbl-to-latex :splice t :skip 0 | ipsum | curabitur | lacinia | pulvinar | nibh | | ipsum | curabitur | lacinia | pulvinar | nibh | \end{comment} \end{document} ``` > 3 votes --- Tags: latex, org-table, orgtbl ---
thread-60624
https://emacs.stackexchange.com/questions/60624
elisp mode set tab width to 2 spaces
2020-09-12T06:46:52.440
# Question Title: elisp mode set tab width to 2 spaces My global `tab-width` is set to 4. But in elisp-mode I get 6 spaces per tab in indentation. So the code after auto indenting looks like this: ``` (defun new-eshell () (interactive) (when (one-window-on-screen-p) (let* ((lines (window-body-height)) (new-window (split-window-vertically (floor (* 0.7 lines))))) (select-window new-window) (buffer-name (eshell "eshell")) ))) ``` How can I set the indentation to 2 spaces? **Update: info for NickD** After I type `C-h m` I get this: ``` Enabled minor modes: Auto-Composition Auto-Compression Auto-Encryption Cl-Old-Struct-Compat Delete-Selection Diff-Auto-Refine Display-Time Eldoc Electric-Indent File-Name-Shadow Font-Lock Global-Eldoc Global-Font-Lock Global-Undo-Tree Ivy Line-Number Menu-Bar Mouse-Wheel Override-Global Pyvenv Shell-Dirtrack Tooltip Transient-Mark Undo-Tree Yas Yas-Global (Information about these minor modes follows the major mode info.) Emacs-Lisp mode defined in ‘elisp-mode.el’: Major mode for editing Lisp code to run in Emacs. ``` Doing the same in `emacs -Q` gives 2 spaces. So, something is wrong with the configs. # Answer > 1 votes The error was here: `(setq lisp-indent-offset 6)`. Changed it to `(setq lisp-indent-offset 2)` and it started to work. --- Tags: indentation ---
thread-62619
https://emacs.stackexchange.com/questions/62619
How to manually define trusted paths for directory local variables '.dir-locals.el'?
2021-01-06T02:13:15.587
# Question Title: How to manually define trusted paths for directory local variables '.dir-locals.el'? I would like to define a list of trusted paths. * Where `dir-locals.el` can be loaded without asking me. * Without having to be concerned with `safe-local-variable-values` *Which isn't very practical if the value contains code which might be edited/modified.* Instead, I would like to have a list of paths, similar to `.gitignore`, which are "trusted" and won't prompt me to trust expressions. # Answer > 1 votes This can be done by advising `hack-local-variables-filter`. ``` (defvar my-trusted-paths (list "/some/path/" "/another/path/")) (defvar my-trusted-paths-prefix (list "/another/prefix/" "/some/prefix/")) (defun my-trusted-paths-filter (dir-name) (catch 'result (dolist (p my-trusted-paths) (when (string-equal p dir-name) (throw 'result t))) (dolist (p my-trusted-paths-prefix) (when (string-prefix-p p dir-name) (throw 'result t))))) (advice-add 'hack-local-variables-filter :around #' (lambda (old-fn &rest args) (pcase-let ((`(,_variables ,dir-name) args)) (if (my-trusted-paths-filter dir-name) (cl-letf (((symbol-function 'safe-local-variable-p) (lambda (&rest _) t))) (apply old-fn args) ;; Always accept paths matching. t) (apply old-fn args))))) ``` --- NOTE: I've since moved to a package that is an alternative to `dir-locals` that allows out-of-source locals called sidecar-locals. --- Tags: directory-local-variables ---
thread-62406
https://emacs.stackexchange.com/questions/62406
Insert text and step
2020-12-21T23:24:58.157
# Question Title: Insert text and step I want to copy text from one buffer to another. With point in the source buffer, I want to insert text in the target buffer. In the target, the text should insert at point, a new line be opened, and the point should move to the beginning of the new line. *When I later switch to the target buffer, the point should be at the start of the new line.* I'm able to do all that except the last bit; when I eventually switch to the target buffer, the point is still on the first line, rather than on the newline. Here's a reduced example. Open two buffers, a `*scratch*` buffer (target) and something else (source). When I run the following in the source buffer, ``` (with-current-buffer "*scratch*" (insert "first") (end-of-line) (newline-and-indent)) (with-current-buffer "*scratch*" (insert "second") (end-of-line) (newline-and-indent)) (with-current-buffer "*scratch*" (insert "third") (end-of-line) (newline-and-indent)) ``` I expect point to be here when I switch to `*scratch*` (target), ``` first second third | <-- point ``` Instead, I get, ``` |first second third ``` When I execute `insert`, `end-of-line` and `newline-and-indent` with `M-:`, the behavior is as expected. Why does it work as expected with `eval-expression` but not when run programmatically? Because there is (legitimate) concern of an X-Y problem, here's everything I'm working with. The problem, so far as I can tell, is in the `with-current-buffer` section, as demonstrated above. Maybe there's another way to insert text and step? ``` (defvar my-on-demand-window nil "Target on-demand window. An on-demand window is one which you wish to return to within the current Emacs session but whose importance doesn't warrant a permanent binding.") (defun my-set-on-demand-window () "Set the value of the on-demand window to current window." (interactive) (setq my-on-demand-window (selected-window)) (message "Set on-demand window to: %s" my-on-demand-window)) (defun my-send-line-or-region (&optional beg end buff) "Send region defined by BEG and END to BUFF. Use current region if BEG and END not provided. If no region provided, send entire line. Default BUFF is the buffer displayed in `my-on-demand-window'." (interactive (if (use-region-p) (list (region-beginning) (region-end) nil) (list nil nil nil))) (let* ((beg (or beg (if (use-region-p) (region-beginning)) nil)) (end (or end (if (use-region-p) (region-end)) nil)) (substr (or (and beg end (buffer-substring-no-properties beg end)) (buffer-substring-no-properties (line-beginning-position) (line-end-position)))) (buff (or buff (window-buffer my-on-demand-window)))) (if substr (with-current-buffer buff (insert substr) (end-of-line) (newline-and-indent)) (error "Invalid selection")))) ``` I am using `GNU Emacs 27.1 (build 1, x86_64-w64-mingw32) of 2020-08-21`. # Answer > 1 votes Per (elisp) Marker Insertion Types, > When you insert text directly at the place where a marker points, there are two possible ways to relocate that marker: it can point before the inserted text, or point after it. You can specify which one a given marker should do by setting its insertion type. Point and mark are buffer local, but the insertion type is controlled by the window. You can use the `window-point-insertion-type` variable to control whether insertions happen before (default) or after point. Therefore, to get the desired behavior, first select the window associated with the target buffer, set the insertion type, and then do the insert: ``` (with-selected-window (get-buffer-window "*scratch*") (setq-local window-point-insertion-type t) (insert "first") (end-of-line) (newline-and-indent)) (with-selected-window (get-buffer-window "*scratch*") (setq-local window-point-insertion-type t) (insert "second") (end-of-line) (newline-and-indent)) ``` --- Tags: insert, newlines ---
thread-62636
https://emacs.stackexchange.com/questions/62636
Creating org-time-stamp on new line
2021-01-06T19:21:46.847
# Question Title: Creating org-time-stamp on new line When I use the org-schedule function the time stamp is inserted below the line it was called from. However, when I call org-time-stamp it is inserted where the cursor is, often being inserted between the last letter and the rest of the word. Is there a way I can make org-time-stamp insert itself on the next line, like org-schedule does? Thanks. # Answer `org-time-stamp` inserts **at point** (see definition of `point` in the Emacs manual) so you are in complete control of where the string is inserted. If it is not inserted where you expect, then you need to move `point` (i.e. your cursor) to the appropriate place. Note that `point` is *between* two characters: the character that your cursor is on and the character *before* it. `org-time-stamp` is also used by other functions (e.g. `org-schedule`) to insert the time stamp, so it does not insert anything extra: if anything extra needs to be added, it is added by the caller either manually or using PRE and POST arguments of `org-insert-time-stamp`, depending where you want to insert the strings. You can define your own function to make it do what you want, e.g.: ``` (defun my/org-time-stamp-on-new-line () (interactive) (end-of-line) (insert "\n") (org-time-stamp nil)) ``` or ``` (defun my/org-time-stamp-on-new-line () (interactive) (end-of-line) (org-insert-time-stamp nil nil nil "\n")) ``` If you don't want to change `point`, you can do this: ``` (defun my/org-time-stamp-on-new-line () (interactive) (save-excursion (end-of-line) (org-insert-time-stamp nil nil nil "\n"))) ``` You call it with `M-x my/org-time-stamp-on-new-line` or you can bind it to a key e.g. ``` (define-key org-mode-map (kbd "C-c z") #'my/org-time-stamp-on-new-line) ``` > 3 votes --- Tags: org-agenda ---
thread-62557
https://emacs.stackexchange.com/questions/62557
Abbrev capitalizes first character
2021-01-02T00:53:55.200
# Question Title: Abbrev capitalizes first character The Qt framework has lots of camel case and pascal case keywords (e.g. `textEdited` or `QWidget`). To avoid pressing Shift constantly, I call `add-global-abbrev` to add a lowercase abbrev and use `abbrev-mode` to automatically expand them. I can then type in lowercase at all times. The problem is that after an abbrev for a camel case word has been expanded once, if expanded again (as happens automatically in `abbrev-mode`), it switches to pascal case. For example, if I write `textEdited` and no abbrev currently exists, I call `C-x a g textedited` to create an abbrev. The corresponding abbrev table then looks like: ``` ;;-*-coding: utf-8;-*- (define-abbrev-table 'global-abbrev-table '( ("textedited" "textEdited" nil :count 0) )) ``` With `abbrev-mode` on, the next time I write `textedited` the following happens. Lets say I forget this is a signal and not a method, so I write a left parenthesis, `textedited(`. It expands to `textEdited(`. That's the expansion I expect, but not the correct syntax. So, I delete the parenthesis and put a dot. The result is `TextEdited.`. The first character of the word is capitalized. Why does deleting the left parenthesis and inserting the dot cause the `t` to capitalize? Is there a way to prevent that? I have tried setting all values of `dabbrev-case-replace` and `case-replace`, but this does not correct the behavior. If I call `write-abbrev-file`, no other abbrevs are written except the global table. I take this to mean no other tables are defined which may be causing the expansion. # Answer **Why does deleting the left parenthesis and inserting the dot cause the "t" to capitalize?** By default, abbrev expansion preserves case. The first expansion happens literally. The key to the expansion rule `("textedited" "textEdited" nil :count 0)` is precisely "textedited". A parenthesis is considered a word-separator, thus "textEdited" is inserted. When the parenthesis is deleted and the dot inserted, a second expansion occurs because period is also a word-separator. In this expansion, however, "textEdited" is acted on and it has a capital letter. (emacs) Dabbrev Customization states, > Normally, dynamic abbrev expansion preserves the case pattern of the dynamic abbrev you are expanding, by converting the expansion to that case pattern. The capital letter indicates to the expansion function that the case should be a particular case pattern. It's not clear to me how Emacs defines these case patterns; does it differentiate camelCase from PascalCase (i.e. StudlyCaps)? It appears not. Hence, the "t" is capitalized. **Is there a way to prevent that?** Yes, several. Using the case-fixed property keyword in the abbrev table definition: ``` ;;-*-coding: utf-8;-*- (define-abbrev-table 'global-abbrev-table '( ("textedited" "textEdited" nil :case-fixed t :count 0) )) ``` This works, but isn't practical for the described use case. The add-global-abbrev command cannot be used to define abbrev properties. You would need to manually edit the abbrev table definition any time an abbrev was added. It turns out that an abbrev table is what's called an obarray. These can have properties themselves. Another solution is to adjust the *table* property so that every entry is case-fixed: ``` (dolist (table abbrev-table-name-list) (abbrev-table-put (symbol-value table) :case-fixed t)) ``` This works, but isn't transparent. The table definition given at the end-user level, that of the define-abbrev-table definition created with write-abbrev-file, won't show the case-fixed property. Further, this applies the case-fixed property to every abbrev in the table. Do you want every table entry to have this property? There are also several options, dabbrev-case-replace, case-replace, dabbrev-case-fold-search, and case-fold-search, described in (emacs) Dabbrev Customization. On my reading, these should help, but they don't. That's either a bug or a misunderstanding by me. So, it appears that case-fixed must be set on an individual abbrev to get the desired behavior. For those already created, just add case-fixed manually. Otherwise, here's a (potentially over-engineered) function to define abbrevs that allows control over the case-fixed property: ``` (defun my-add-table-abbrev (name expansion &optional fixed table interp) "Define abbrev with NAME and EXPANSION for last word(s) before point in TABLE. FIXED sets case-fixed keyword property; default is nil. TABLE defaults to `global-abbrev-table'. Behaves similarly to `add-global-abbrev'. The prefix argument specifies the number of words before point that form the expansion; or zero means the region is the expansion. A negative argument means to undefine the specified abbrev. This command uses the minibuffer to read the abbreviation. Abbrevs are overwritten without prompt when called from Lisp. \(fn NAME EXPANSION &optional FIXED TABLE)" ;; define behavior when called interactively (interactive (let* ((arg (prefix-numeric-value current-prefix-arg)) ; get numeric prefix ;; note negative prefix returns exp as nil (exp (and (>= arg 0) ; positive prefix grabs `arg` previous words (buffer-substring-no-properties (point) (if (= arg 0) (mark) ; zero prefix grabs region (save-excursion (forward-word (- arg)) (point)))))) ;; when exp exists define name to create, otherwise name the one to destroy (name (read-string (format (if exp "Abbev name: " "Undefine abbrev: ")))) ;; when exp, ask user for expansion (expansion (and exp (read-string "Expansion: " exp))) (table (symbol-value (intern-soft (completing-read "Abbrev table (global-abbrev-table): " abbrev-table-name-list nil t nil nil "global-abbrev-table")))) ;; don't ask for fixed case when deleting (fixed (and exp (y-or-n-p (format "Fix case? "))))) ;; send args to function, note last element indicates interactive (list name expansion fixed table t))) ;; end interactive behavior definition, start function definition (let ((table (or table global-abbrev-table)) ; define default table (fixed (or fixed nil))) ; define default case-fixed (set-text-properties 0 (length name) nil name) (set-text-properties 0 (length expansion) nil expansion) (if (or (null expansion) ; there is expansion to set, (not (abbrev-expansion name table)) ; the expansion is not already defined (not interp) ; and we're not calling from ; code (calling interactively) (y-or-n-p (format "%s expands to \"%s\"; redefine? " name (abbrev-expansion name table)))) (define-abbrev table name expansion nil :case-fixed fixed)))) ``` > 1 votes --- Tags: abbrev ---
thread-62640
https://emacs.stackexchange.com/questions/62640
How to show invisible/problematic characters such as TAB and Narrow No-Break Space in an org-mode table?
2021-01-07T02:08:00.487
# Question Title: How to show invisible/problematic characters such as TAB and Narrow No-Break Space in an org-mode table? Is there a way to indicate where you have an "invisible" character that's causing problems in an org-mode table? The character's likely a TAB, but for the general case I'd like to assume it could also be other characters, e.g. a "narrow no-break space" (U+202F). ## Background I just pasted multiple lines into an org-mode table, as per Is it possible to copy /paste multiple lines of text into cells of org-mode table?. First I created an empty table: ``` | | | | | | ``` Then I created some lines in the org-mode buffer. Originally I'd copied text from some web page, but I've found I can reproduce the behaviour with the text below. ``` abcdef abcdef7890 ``` Then I used `C-x r k` and `C-x r y` to insert this into the table. Below is the result, after pressing `C-c C-c` to align the table: ``` | | abcdef | | | abcdef7890 | ``` Note that the rightmost '`|`' aren't correctly aligned. It seems a TAB character was added in the process at the end of the first row. If I do e.g. `ESC SPACE` at the end of the first row and then `C-c C-c`, that row is fixed. In this case it also fixes the entire table: ``` | | abcdef | | | abcdef7890 | ``` However, in my original case I had to go and fiddle with all rows. PS. The focus of this question is how to show the invisible/problematic characters, assuming that's the cause. Why I'm getting the problematic characters should probably go in another question. Update: Created Why is a TAB character added when using kill-rectangle and yank-rectangle to insert multiple rows into an org-mode table? # Answer `highlight-chars` is nice and general, but `whitespace-mode` is better for the common case where you mostly just care about tabs and spaces. You can configure it to change the background color of inappropriate whitespace characters so that they become obvious, or you can use it to show a glyph in their place, or both. The one annoyance that I've had with `whitespace-mode` is that it doesn't react immediately to configuration changes; I always had to close the buffer and reopen it to see the effects of changing the settings. I never did figure out how to fix that, but perhaps it's better these days. > 2 votes # Answer You can use library `highlight-chars.el` to highlight any characters you like. See commands `hc-highlight-chars` and `hc-toggle-highlight-other-chars`. You can specify characters in any of these ways: * individually * using ranges * using character classes (e.g. `[:digit:]`) * using character sets (e.g. `iso-8859-1' or` lao'). Download > 1 votes --- Tags: org-mode, highlighting, highlight-chars ---