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-68270
https://emacs.stackexchange.com/questions/68270
Setting :prologue in header args as elisp has "scope" problems when running (org-sbe), "wrong" `org-element-context`?
2021-08-26T16:34:48.673
# Question Title: Setting :prologue in header args as elisp has "scope" problems when running (org-sbe), "wrong" `org-element-context`? To cut down on some repetitive boilerplate, I'm attempting to make my header arguments more "dynamic", but I have run into what I believe is a "scope" issue, that I cannot yet get around. I would like to move the `:prologue` arg from the `cfg_*` source code blocks into the `:header-args:` of the parent section. Here's an MVE for the context: ``` * CFG Generation #+NAME: Platforms | platform | arch | subarch | modelname | |------------+-------+---------+-----------------------| | ar300m | ath79 | generic | glinet_gl-ar300m-lite | | archerC7V5 | ath79 | generic | tplink_archer-c7-v5 | #+NAME: cfg-mk-dev-header #+BEGIN_SRC emacs-lisp :var dev="devsoc" platforms=Platforms :tangle no (format "Long String generated from the above table\n") #+END_SRC ** Devices :PROPERTIES: :header-args: :noweb yes :header-args+: :tangle (concat "cfg." (substring (org-element-property :name (org-element-context)) 3) ".gen") :END: *** ar300m - Device friendly name #+NAME: cfg_ar300m #+HEADER: :prologue (org-sbe cfg-mk-dev-header (dev '"ar300m")) <<cfg_gcc_binutils>> # ... <<cfg_misc_options>> #+END_SRC *** archerC7V5 - Friendly Name #+NAME: cfg_archerC7V5 #+HEADER: :prologue (org-sbe cfg-mk-dev-header (dev '"archerC7V5")) ... ``` The problematic line is: ``` #+HEADER: :prologue (org-sbe cfg-mk-dev-header (dev '"ar300m")) ``` When I move this line into the `:header-args:`, and replace the static part `'"ar300m"` with `(substring (org-element-property :name (org-element-context)) 3)` like for `:tangle`, I then get ``` :prologue (org-sbe cfg-mk-dev-header (dev (substring (org-element-property :name (org-element-context)) 3))) ``` But when tangling the name-lookup fails, and I get the "default string" inserted in all config file. Edit: Solved: I had the offset wrong-by-one (3 instead of 4). Many thanks to @NickD for helping with the initial issue of "lisp max nesting", and then pointing me to the "bug", which requires to wrap the result of the name lookup in `(format "\"%s\"" ...)` # Answer > 2 votes For the `Lisp nesting` problem, make sure that your `cfg-make-device-header` block is **NOT** under the influence of those properties, otherwise when the block is evaluated to e.g. calculate the prologue of the other block, the headers apply to it as well, so you recurse infinitely. And there is a quoting problem because... I don't know, I couldn't figure it out. It's probably a bug in `org-sbe` where it fails to protect its argument when it is a string, since the code block seems to return it without double quotes. But the following structure seems to work for me: ``` #+name: cfg-make-device-header #+begin_src shell :var dev="foo" echo $dev #+end_src * Devices :PROPERTIES: :header-args: :noweb yes :header-args+: :prologue (org-sbe "cfg-make-device-header" (dev (format "\"%s\"" (substring (org-element-property :name (org-element-context)) 3)))) :header-args+: :tangle (concat "config." (substring (org-element-property :name (org-element-context)) 3) ".gen") :END: ** Device frobuzz #+name: frobuzz #+begin_src sh echo foo #+end_src ``` Note that the value of `dev` in the prologue has to be formatted with double quotes in order for this to work. But frankly, this seems way too fragile and debugging it is almost impossible: there are too many layers in the onion. I'd rethink the approach and probably replace the `cfg-make-devices-header` block with a lisp function, so as to avoid using `org-sbe`. --- Tags: org-mode, org-babel ---
thread-68274
https://emacs.stackexchange.com/questions/68274
Is there a way to display breadcrumbs in C mode in a headerline or another window
2021-08-27T04:35:09.603
# Question Title: Is there a way to display breadcrumbs in C mode in a headerline or another window I am using emacs (GNU Emacs 25.3.2) on Ubuntu. I was wondering if its possible to display short breadcrumbs or selected compound statement in a headerline (even another window is fine). Probably I am not able to describe it properly using words, let me try example, assuming I have some code like following: ``` Line:1 while (condition 1) { Line:10 ....... Line:60 some code... Line:61 if (condition 2) { Line:62 cursor is here now ``` When I am on line 62 header line should display `while(condition 1)->if(condition 2)` Or I can select to display this summary from say line 61 onward only. Basically summary of compound statements at a glance. I am have tried using \[1\] but somehow it just displays tag (function) name in the headerline. \[1\] https://www.emacswiki.org/emacs/SemanticIdleBreadcrumbsMode # Answer Yes, I think it's possible, and I think your question is clear. As for how: You'll need to parse the C code to some extent around/before point, to get the breadcrumb pieces you want to show. Then, as you say, put them in a header line. I added breadcrumbs to Info this way. You might check the code for that (in standard library `info.el`). Just search for `Info-breadcrumbs`. (Obviously, the code to get the breadcrumbs pieces is different for Info than for your use case, but the idea is the same, and using the header can be the same. --- You can also check my library \`info+.el. There I have a user option for whether to show breadcrumbs in the header line, and a toggle command for that, and an option for whether to show breadcrumbs in the mode-line. > 0 votes --- Tags: c, header-line, breadcrumbs ---
thread-68263
https://emacs.stackexchange.com/questions/68263
How to avoid paste to system clipboard when use Emacs For Mac OS X?
2021-08-26T05:28:01.717
# Question Title: How to avoid paste to system clipboard when use Emacs For Mac OS X? When use Emacs For Mac OS X, copy a string from browser(E.g. `B`) then paste into it, it works. But if use `ciw`(vim mode) on a string(it's the same as copy a string inside the tool, E.g. `A`), then `Ctrl + v` to paste the previous string again, it will show the one cut in the tool(`A`). I hope it can take `B` here. This case doesn't happened when use emacs in terminal. # Answer > 1 votes I'll try to guess what you mean ;-) and suggest using `M-x yank-pop` (bound by default to `M-y` normally) instead of `M-x yank` (bound to `s-v` and `C-y` by default in my setup on Mac OS, but possibly `Ctrl + v` is bound to `yank` in your case). The exact behavior of the `yank-pop` may depend on the version of Emacs you're using (this function was updated not so long ago). You can read more about this command usage in installed Emacs with `C-h f yank-pop` and `M-x info-apropos <RET> yank-pop`. On Emacs 28.0.50, after hitting `M-y` (`M-x yank-pop`) I currently get this nicely looking kills (cuts) history selection interface in the minibuffer: \[Use `C-s` and `C-r` to switch to the next/previous item.\] Another way to use `M-x yank-pop` is to call it right after pasting with the `M-x yank` command (`s-v`/`C-y` binding), such as: 1. `C-y` inserts the most recent item from the kill ring. 2. Then `M-y` replaces just inserted item with the earlier available killed item (going further back in the kill history on each `M-y` hit). Hope my guess is right and this answer helps you. --- Tags: osx, gui-emacs ---
thread-68279
https://emacs.stackexchange.com/questions/68279
How to read an s-expression at load-time
2021-08-27T11:43:24.413
# Question Title: How to read an s-expression at load-time Why does it seem impossible to read an s-expression at load-time? Given this and only this s-expression in my init file: ``` (save-excursion (end-of-defun) (beginning-of-defun) (setq beg (point)) (setq form (funcall load-read-function (current-buffer))) (setq end (point)) (message "BEG: %s" beg) (message "FORM: %s" form) (message "END: %s" end)) ``` On startup, I receive the error: ``` End of file during parsing: /home/user/.emacs.d/init.el ``` --- Now, also curiously, if I comment out the erroneous lines: ``` (save-excursion (end-of-defun) (beginning-of-defun) (setq beg (point)) ;; (setq form (funcall load-read-function (current-buffer))) (setq end (point)) (message "BEG: %s" beg) ;; (message "FORM: %s" form) (message "END: %s" end)) ``` On startup, I get this output in the Messages buffer: ``` BEG: 1 END: 1 For information about GNU Emacs and the GNU system, type C-h C-a. ``` No matter where I place that s-expression `(point)` will always be `1`. Why's that? # Answer > 1 votes > On startup, I get this output in the Messages buffer: > > ``` > BEG: 1 > END: 1 > For information about GNU Emacs and the GNU system, type C-h C-a. > > ``` > > No matter where I place that s-expression (point) will always be 1. Why's that? Notwithstanding that you've called `(beginning-of-defun)` and then set both `beg` and `end` to that same value, you're also processing an empty buffer by default, so those values could be expected to be `1`. Are you expecting that Emacs would visit your init file source code in a buffer, and select that buffer by default, while it evaluates your init code? ``` (message "%S (%S)" (current-buffer) (buffer-string)) ``` gives me: `#<buffer *scratch*> ("")` if I evaluate it on start-up. If you specify a file argument when you start Emacs, then you would be processing one of those buffers, so maybe this does what you want? `emacs ~/.emacs.d/init.el` --- Tags: init-file, load, read ---
thread-68252
https://emacs.stackexchange.com/questions/68252
Org export theorem with caption and number in HTML
2021-08-25T14:55:33.493
# Question Title: Org export theorem with caption and number in HTML With ``` #+CAPTION: my-caption [[file:image.png]] ``` I get a caption (with a number) both in LaTeX and in HTML. The same with tables and src blocks (which become listings in LaTeX) But with a theorem, definition, ... and all other mathematical environments I cannot get a title and a number. ``` #+ATTR_LATEX: :options [my-theorem] #+BEGIN_theorem .... #+END_theorem ``` works for LaTeX, but in HTML I don't get the caption (and most importantly the number). This instead breaks also LaTeX because inserts a `\caption` macro inside the environment: ``` #+CAPTION: my-theorem #+BEGIN_theorem .... #+END_theorem ``` How can I create a new special block which takes care of numbering also for HTML (like for figures, tables and listings)? For the caption the solution is very simple: ``` #+ATTR_LATEX: :options [my-theorem] #+BEGIN_theorem @@html:<span class="theorem-title">my-theorem</span>@@ .... #+END_theorem ``` so the difficult part is taking care of the numbering. **UPDATE** With org-special-block-extras I achieved this: ``` (defvar special-block-definition-counter 0) (defblock definition (title nil) (label nil unnumbered nil) "Definition special block." (unless unnumbered (cl-incf special-block-definition-counter)) (format (cond ((org-export-derived-backend-p org-export-current-backend 'latex) (concat "\\begin{definition" (when unnumbered "*") "}{%s}{%s}\n" "%s" "\\end{definition" (when unnumbered "*") "}")) ((org-export-derived-backend-p org-export-current-backend 'html) (concat "<p class=\"admonition-title definition\">Definizione" (unless unnumbered (format " %d" special-block-definition-counter)) (when title ": ") "%s</p>" "<div id=\"%s\" class=\"special-block definition\">%s</div>"))) (or title "") (or label "") contents)) ``` and ``` #+BEGIN_definition Definition title :label def:example .... #+END_definition ``` To export correctly for ePub a patch is needed (for more info: https://github.com/alhassy/org-special-block-extras/issues/12): ``` (add-to-list 'org-export-filter-parse-tree-functions (lambda (tree backend info) (when (eq backend 'epub) (org-element-map tree 'export-block (lambda (el) (when (string= (org-element-property :type el) "EPUB") (org-element-put-property el :type "HTML"))))) tree)) ``` Now I have only to manage the internal links (label/reference). # Answer I finally solved using `org-special-block-extras`: 1. Define a macro to define a new theorem type (calls `defblock`) and its link. This also takes count in a list of all the labels to get numbers and links. ``` (defmacro special-block-labels-push (name label) (let ((labels (format "special-block-%s-labels" name)) (labels-cdr (format "special-block-%s-labels-cdr" name))) `(let ((label (list (format "%s" ,label)))) (setq ,(intern labels-cdr) (if ,(intern labels-cdr) (setcdr ,(intern labels-cdr) label) (setq ,(intern labels) label)))))) (defmacro defspeciallink (name prefix) `(progn (defvar ,(intern (format "special-block-%s-labels" name)) '()) ; to store this theroem labels (defvar ,(intern (format "special-block-%s-labels-cdr" name)) nil) (defblock ,prefix (ref nil) () ,(format "Reference a %s special block." name) (format (cond ((org-export-derived-backend-p org-export-current-backend 'latex) ,(format "\\ref{%s:%%s}" prefix)) ; use standard ref in LateX ((org-export-derived-backend-p org-export-current-backend 'html) ,(format "<a href=\"#%s:%%s\">%%d</a>" prefix))) ; in HTML the number has to be print manually, finding the position of the label in the list ref (1+ (cl-position (format "%s" ref) ,(intern (format "special-block-%s-labels" name)) :test 'equal)))))) ; sum one because lists are zero based (defmacro deftheorem (name display-name prefix &optional tcb) "Defines a new theorem type called NAME (rendered as DISPLAY-NAME in HTML) which labels start with PREFIX. If TCB is not nil, in LaTeX the tcbtheorem syntax is used. Usage: ,#+BEGIN_name Title :label lbl .... ,#+END_name As can be seen in [[prefix:lbl]] " `(progn (defspeciallink ,name ,prefix) (defblock ,name (title nil) (label nil unnumbered nil) ,(format "Define %s special block." name) (unless unnumbered (special-block-labels-push ,name label)) ; add label to list (format (cond ((org-export-derived-backend-p org-export-current-backend 'latex) (concat ,(format "\\begin{%s" name) (when unnumbered "*") "}" ,(if tcb "{%s}{%s}" (format "[%%s]\\label{%s:%%s}" prefix)) ; tcbtheorem or standard "\n%s" ,(format "\\end{%s" name) (when unnumbered "*") "}")) ((org-export-derived-backend-p org-export-current-backend 'html) (concat ,(format "<p class=\"admonition-title %s\">%s" name display-name) (unless unnumbered (format " %d" (length ,(intern (format "special-block-%s-labels" name))))) (when title ": ") "%s</p>" ,(format "<div id=\"%s:%%s\" class=\"special-block %s\">%%s</div>" prefix name)))) (or title "") (or label "") contents)))) ``` It works both with standard LaTeX theorems and tcbtheorems (using the last parameter. 2. Add new theorems using the previous macro: ``` (deftheorem definition "Definizione" def) (deftheorem theorem "Teorema" thm) (deftheorem postulate "Postulato" pos) (deftheorem axiom "Assioma" axi) (deftheorem proposition "Proposizione" pro) (deftheorem corollary "Corollario" cor) (deftheorem lemma "Lemma" lem) (deftheorem principia "Principio" pri t) (deftheorem alg "Algoritmo" alg t) ``` 3. (OPT) add new LatTeX theorems: ``` \newtcbtheorem[auto counter,number within=chapter]{principia}{Principio}{propstyle}{pri} \newtcbtheorem[auto counter,number within=chapter]{alg}{Algoritmo}{algstyle}{alg} ``` 4. Add CSS style (I based on `ReadTheOrg`): ``` /* BLOCKS */ #content .special-block { padding: 12px; line-height: 24px; margin-bottom: 24px; } #content .special-block p:last-child { margin-bottom: 0; } #content .admonition-title { color: #fff; font-weight: bold; display: block; padding: 6px 12px; margin-bottom: 0px; } /* Definition: green */ #content .definition {background-color: #dbfaf4;} #content p.admonition-title.definition {background-color: #1abc9c;} /* Theorem: orange */ #content .theorem, #content .postulate, #content .axiom, #content .corollary, #content .lemma {background-color: #ffedcc;} #content p.admonition-title.theorem, #content p.admonition-title.postulate, #content p.admonition-title.axiom, #content p.admonition-title.corollary, #content p.admonition-title.lemma {background-color: #f0b37e;} /* Proposition: blue*/ #content .proposition, #content .principia {background-color: #e7f2fa;} #content p.admonition-title.proposition, #content p.admonition-title.principia{background-color: #6ab0de;} /* Algorithm: gray */ #content .alg {background-color: #ddd;} #content p.admonition-title.alg {background-color: #333;} ``` 5. Use it in Org mode: ``` #+BEGIN_theorem My theorem :label test .... #+END_theorem ... As said in theorem [[thm:test]] ``` > 0 votes --- Tags: org-mode, org-export ---
thread-32761
https://emacs.stackexchange.com/questions/32761
execute named org-bable source block from elisp
2017-05-13T07:18:38.310
# Question Title: execute named org-bable source block from elisp I want to execute selected source blocks in the active buffer. For example for the following org-mode file, ``` #+NAME: snippet1 #+BEGIN_SRC emacs-lisp (message "snippet 1") #+END_SRC #+NAME: snippet2 #+BEGIN_SRC emacs-lisp (message "snippet 2") #+END_SRC ``` I can use ``` (org-babel-execute-buffer) ``` to execute both blocks from elisp, but how can I execute snippet1 without executing snippet2? I found the following related functions that might help. ``` org-babel-get-src-block-info org-babel-execute-src-block ``` Any pointers to relevant documentation is very much appreciated. # Answer > 3 votes The documentation for org-babel is available at http://org-babel.readthedocs.io/en/latest/. And the snippet to interactively select and execute a named block in the current buffer: ``` (save-excursion (goto-char (org-babel-find-named-block (completing-read "Code Block: " (org-babel-src-block-names)))) (org-babel-execute-src-block-maybe)) ``` # Answer > 1 votes Much easier than the AA: Using the built-in function `(org-sbe ...`: ``` * Example using (org-sbe): #+NAME: snippet1 #+BEGIN_SRC emacs-lisp :var txt="snippet1 was called" (message txt) #+END_SRC If you want to run the above SCB, you could just place the curson on the closing bracket ")" of “(org-sbe "snippet1")”, and just run that with CTRL-x CTRL-e , and here once more “(org-sbe "snippet1" (txt $"otherMessage"))” with parameters. Documentation e.g. here: http://doc.endlessparentheses.com/Fun/org-sbe.html ``` --- Tags: org-mode, org-babel ---
thread-7268
https://emacs.stackexchange.com/questions/7268
package.el asks whether I want to save modified files before package installation. How to disable this?
2015-01-11T10:01:01.913
# Question Title: package.el asks whether I want to save modified files before package installation. How to disable this? When I run `M-x package-install` to install a package, I get asked whether I want to save files, that have been modified since the last save (`Save file /a/b/c.txt? (y, n, !, ., q, C-r, d or C-h)` in the minibuffer). I get this prompt for each modified file, and, if installing multiple packages from the `*Packages*` buffer, I get asked multiple times! This is incredibly frustrating, especially as the files that I am asked about have nothing to do with compilation, and could, in fact, be any files at all, including ordinary text files. I did a bit of sleuthing, and found that, at the end of the day, package.el runs `package-unpack` to install a package, which runs `package--compile`, which runs `byte-recompile-directory`. I have therefore set the following in my init.el (even though I don't think I should have to do that(!)): `(setq compilation-ask-about-save nil)` No improvement. Frankly, I thought this must be a side-effect of some customization of mine, since in no way would I consider this to be desirable behavior...until I ran `emacs -Q` to reproduce this without my config, and, to my surprise, ran into the very same thing. While this seems baffling, it also offers me some hope that perhaps someone has figured out a way to disable this super-annoying prompt? # Answer > 3 votes As the help text tells you when you type `C-h` (as prompted by `save-some-buffers`, which is the function responsible for the query), you can skip all remaining queries with a simple `RET` or `q`. I certainly don't find myself in this situation so frequently that doing that is an onerous task, so this might be sufficient for you. p.s. `compilation-ask-about-save` is related to running external compiler processes, and not to elisp byte-compilation. **Edit:** One option would be binding `noninteractive` ("Non-nil means Emacs is running without interactive terminal.") around `package--compile` with advice, as `byte-recompile-directory` won't trigger `save-some-buffers` in that case; but I think that's going to have some undesirable consequences further down. Redefining `save-some-buffers` for the duration seems like a safer option: ``` (defadvice package--compile (around no-byte-recompile-saves) "Inhibit `save-some-buffers' when byte-compiling packages." (require 'cl-lib) (cl-letf (((symbol-function 'save-some-buffers) 'ignore)) ad-do-it)) (ad-activate 'package--compile) ``` # Answer > 0 votes I have been suffering this as well: in long Emacs sessions with multiple Tramp connections, I am prompted to save buffers in remote machines when I grep my local sources. Since Emacs 28 (currently, this is the master branch), Emacs has added the value `save-some-buffers-root` for the option `save-some-buffers-default-predicate`. With this value, Emacs will prompt to save only those modified buffers inside the current project. For instance, at the Emacs sources, if you call `save-some-buffers` from dir: ``` ~/emacs_source/lisp ``` then, you'll be also prompted for a modified buffer at: ``` ~/emacs_source/src ``` but you won't be prompted for a modified buffer at: ``` ~/foodir ``` In case Emacs cannot find a project, then Emacs will only ask for buffers whose `default-directory` is in a subdir of the directory where `save-some-buffers` is invoked. For example, If you call it at: ``` ~/foo/ ``` you'll be prompted to save buffers at both: ``` ~/foo/ ~/foo/bar/ ``` but you won't be prompted to save buffers at: ``` ~/qux ``` --- Tags: package ---
thread-36805
https://emacs.stackexchange.com/questions/36805
All arrow keys in dired+ buffer mapped to M-O
2017-11-11T16:43:41.780
# Question Title: All arrow keys in dired+ buffer mapped to M-O For some reason when I press Up, Down, Left or Right keys on keyboard in dired+ mode, emacs reads them all as `M-O` key, which I found out by `describe-key` command in dired+ buffer. I have no config regarding diredp in my config, just that: ``` (use-package dired+ :ensure t) ``` Also, when pressing arrow keys in diredp in minibuffer appears `change owner of auto-save-list`, and depending on Up, Down, Left, Right, character appear in input field are A, B, D, C, which is even more confusing. In ordinary `dired` buffer arrow keys appears normally. Also I'm working in `emacs-nox` session. # Answer I was able to solve this by configuring `dired+` followingly: ``` (use-package dired+ :config ;; This binding messes with the arrow keys, for some reason. (unbind-key "M-O" dired-mode-map)) ``` > 1 votes # Answer There is a user option, **`diredp-bind-problematic-terminal-keys`**, that has this effect: > `diredp-bind-problematic-terminal-keys` is a variable defined in `dired+.el`. > > Its value is `t` > > Documentation: > > Non-`nil` means bind some keys that might not work in a text-only terminal. > > This applies to keys that use modifiers Meta and Shift together. If you use Emacs in text-only terminal and your terminal does not support the use of such keys then customize this option to nil. > > You can customize this variable. You might try customizing that option to `nil`. The Dired+ doc has this prominent section (in the Commentary of `dired+.el`): > ## If You Use Dired+ in Terminal Mode > > By default, Dired+ binds some keys that can be problematic in some terminals when you use Emacs in terminal mode (i.e., `emacs -nw`). This is controlled by option `diredp-bind-problematic-terminal-keys`. > > In particular, keys that use modifiers Meta and Shift together can be problematic. If you use Dired+ in a text-only terminal, and you find that your terminal does not support such keys, then you might want to customize the option to set the value to `nil`, and then bind the commands to some other keys, which your terminal supports. > > The problematic keys used by Dired+ include these: > > ``` > `M-M` (aka `M-S-m`) - `diredp-chmod-this-file` > `M-O` (aka `M-S-o`) - `diredp-chown-this-file` > `M-T` (aka `M-S-t`) - `diredp-touch-this-file` > `C-M-B` (aka `C-M-S-b`) - `diredp-do-bookmark-in-bookmark-file` > `C-M-G` (aka `C-M-S-g`) - `diredp-chgrp-this-file` > `C-M-R` (aka `C-M-S-r`) - `diredp-toggle-find-file-reuse-dir` > `C-M-T` (aka `C-M-S-t`) - `dired-do-touch` > `M-+ M-B` (aka `M-+ M-S-b`) - `diredp-do-bookmark-dirs-recursive` > `M-+ C-M-B` (aka `M-+ C-M-S-b`) - `diredp-do-bookmark-in-bookmark-file-recursive` > `M-+ C-M-T` (aka `M-+ C-M-S-t`) - `diredp-do-touch-recursive` > > ``` > > (See also `(info "(org) TTY keys")` for more information about keys that can be problematic in a text-only terminal.) HTH. Sorry for any trouble. > 0 votes --- Tags: key-bindings, dired, emacs-nox ---
thread-68241
https://emacs.stackexchange.com/questions/68241
"Failed to download ‘melpa’ archive" when I run package-refresh-contents
2021-08-25T05:05:45.010
# Question Title: "Failed to download ‘melpa’ archive" when I run package-refresh-contents Have started seeing this error after I installed a new version of Emacs. My package code in init file is ``` (require 'package) (setq package-archives '(("gnu" . "http://elpa.gnu.org/packages/") ("melpa" . "http://melpa.org/packages/"))) (package-initialize) ``` This also fails if I use https. What do I need to do to fix this? # Answer > 0 votes Reinstalling Emacs 27.2.2 fixed this. I am not sure why it is working now and did not work before. # Answer > 2 votes Make sure to follow the `MELPA` Getting started instructions precisely and then read `Known Issues` sections. I got the error message "Failed to download ‘MELPA’ archive" on an earlier version of `Emacs`. In my case, it was fixed at that time by applying described in the `Known Issues` configuration: ``` (setq gnutls-algorithm-priority "NORMAL:-VERS-TLS1.3") ``` --- Tags: package, package-repositories ---
thread-29131
https://emacs.stackexchange.com/questions/29131
Get contents of a named source block
2016-12-06T01:30:03.407
# Question Title: Get contents of a named source block The other day I wanted to put the contents of a source code block into a header argument of another block. I couldn't find any ready to use function to do that though, so I came up with this: ``` (defun extract-src-content (name) (save-excursion (org-babel-goto-named-src-block name) (car (nthcdr 21 (cadr (org-element-at-point)))))) ``` But that doesn't seem to be right. First my elisp experience is not that vast so I don't know how to extract the value for the `:value` key out of `(cadr (org-element-at-point))` so I just took the 21th element which can't be right and will probably break at the next org update. Second I still think there should be an org-function available to extract the contents of a named source code block, since it has to have a way to do that for export or editing. Someone has an answer to either question? * What's the right way to extract the value after `:value` out of `(cadr (org-element-at-point))`? * Is there a ready to use org-function (or even org-syntax) to accomplish the same thing? Bonus question * I tried to ask this on the #org-mode irc channel, but even though there are a lot of joined users it seems to be dead. Why is it still linked on http://orgmode.org/community.html then? # Answer > 10 votes Sometimes it helps to formulate a question to realize the answer. I did another look into the org-mode sources and found `org-element-property` so I can do ``` (org-element-property :value (org-element-at-point)) ``` instead of `(car (nthcdr 21 (cadr (org-element-at-point))))` which is much better and according to John Kitchin also the built in way to do it. # Answer > 4 votes I would just use the builtin noweb functionality: set the option `:noweb yes` and refer to the quoted code by `<<`*blockname*`>>` in the other block: ``` #+NAME: sine #+BEGIN_SRC python import math x=math.sin(math.pi) #+END_SRC #+BEGIN_SRC python :noweb yes :results output :exports results text=""" <<sine>> """ print text #+END_SRC #+RESULTS: : : import math : : x=math.sin(math.pi) : ``` --- Edit: To supress the two linebreaks (before and after the code) that are introduced by having the `"""` in separate lines, you can use ``` #+BEGIN_SRC python :noweb yes :results output :exports results text="""\ <<sine>> """[:-1] print text #+END_SRC ``` But this is a python detail -- and python wizards surely know a more elegant way. Other languages might need other solutions, or will be fine directly (not every language complains when a string goes over a line break). Just note, that anything before the `<<` will be repeated for every source line, so you can easily comment out this for example. # Answer > 1 votes I was led to my preferred answer to that question by a comment (Thank you! @Mutbuerger ) : > You may use `(cadr (org-babel-lob--src-info NAME))` from `ob-lob` instead. This brought me to: `(org-babel-expand-noweb-references (org-babel-lob--src-info NAME))` The other solution with `(org-element-at-point)` didn't feel "idiomatic" for cases, where you are not with point at the desired src-block, and thus have to `(save-excursion (org-babel-goto-named-src-block ...`, which is "Remember, where you are, virtually move the cursor to the wanted source, and only then read. Sure, the approach from AA works, but I looked for a solution, that "doesn't move the cursor" (or at least does it transparently), and feels more "idiomatic". Since comments can disappear, I'm using this to make the `org-babel-lob--src-info`-solution from @Mutbuerger more (permanently) visible. This will also expand `noweb`-refs, if enabled for the src-block. --- Tags: org-mode, org-babel ---
thread-68295
https://emacs.stackexchange.com/questions/68295
How to lists all shortcuts available for currently active major mode?
2021-08-28T06:57:50.067
# Question Title: How to lists all shortcuts available for currently active major mode? I simply want to get the list of shortcuts. For example, when my cursor is in Treemacs, I press '?' and then mini-buffer opens which show all available shortcuts. But same thing isn't true for other major modes like 'eww' etc. I simply don't want to navigate to documentation everytime. I use 'helm' if it helps! Thank you! # Answer Normally I use `C-h m` (`M-x describe-mode`) for this task. The opened *\*Help\** buffer lists currently used modes, and then short information on each of the modes, starting with the major one and usually providing a list of available key bindings. Additionally, in some major modes, `?` and/or `C-h` output the most - expectedly - useful key bindings. Also, there's a very useful `M-x describe-keymap` command, available since `Emacs 28.1` (current development snapshot 28.0.50). I often use it when I'd like to explore a particular keymap without going to the source (so *not only* the currently active major-mode's bindings). For example, `M-x describe-keymap <RET> dired-mode-map`. P.S. You *might* also find it helpful to take a look at `C-h ?` for the list of the most useful **help bindings**. `C-h m` is currently listed as the first one (in my setup). > 1 votes --- Tags: key-bindings, helm ---
thread-68249
https://emacs.stackexchange.com/questions/68249
How to ignore specific flycheck warning messages for Python in lsp-mode?
2021-08-25T13:09:48.047
# Question Title: How to ignore specific flycheck warning messages for Python in lsp-mode? My goal is to configure `lsp` in order to ignore warning messages for `flycheck` in Python version. When lsp is not in use, flycheck reads from my `~/.pylintrc` file in order to ignore warning messsages. But when I enable `lsp-mode` it does not ignore the warning messages that I set in `~/.pylintrc` file. **minimal.el**: ``` (defun flycheck-python-setup () (flycheck-mode)) (require 'flycheck) (require 'flycheck-mypy) (add-hook 'after-init-hook #'global-flycheck-mode) (add-hook 'after-init-hook #'global-flycheck-mode) (add-to-list 'flycheck-disabled-checkers 'python-flake8) (add-hook 'python-mode-hook (lambda () (setq flycheck-python-pylint-executable "~/venv/bin/pylint") (setq flycheck-pylintrc "~/.pylintrc") (setq indent-tabs-mode nil python-indent-offset 4 tab-width 4) (let ((inhibit-message t)) ))) (use-package python :ensure nil) (add-hook 'python-mode-hook #'flycheck-python-setup) (flycheck-add-next-checker 'python-flake8 'python-pylint 'python-mypy) ``` Having following lines in order to enable `lsp-mode`, changes the result for `helm-flycheck`. ``` (add-hook 'python-mode-hook 'lsp) (add-hook 'python-mode-hook #'lsp-deferred) ``` --- ``` ❯ cat ~/.pylintrc disable=D100, C0305, C0303, W291, C0111, R0801, W0703, C0103, ``` Related: flycheck cannot find module for pylint, https://www.reddit.com/r/emacs/comments/b5lvx6/how\_do\_i\_force\_lspui\_to\_use\_flake8/ > ``` > (add-hook 'python-mode-hook > (lambda () > (setq flycheck-python-pylint-executable "<your path to>/pylint") > (setq flycheck-pylintrc "/home/tools/.pylintrc"))) > > ``` # Answer > 2 votes Your `python-lsp-server`, named further `pylsp` as in `lsp-pylsp.el` file, can use `pylint` if it is enabled - you need the following code lines to be added to your lsp configuration block: ``` ;; Adding pylint as linter for pylsp (require 'lsp-pylsp) (setq lsp-pylsp-plugins-pylint-enabled t) (setq lsp-pylsp-plugins-pylint-args ["--rcfile=/<absolute-path-to-home-dir/.pylintrc"]) ;; or path to your project. ``` Please note the lsp servers have their own checkers, and consequently when used, `flycheck` module should not be configured/used in any specific way - you should remove your posted configuration. One note: your item D100 posted in your `.pylintrc` file belongs to `flake8` \- you may have a `.flake8rc` file in your path. This can be corrected also at the lsp-pylsp level, see this: https://emacs-lsp.github.io/lsp-mode/page/lsp-pylsp/#lsp-pylsp-plugins-flake8-filename \- configure the variable `lsp-pylsp-plugins-flake8-ignore`. --- Tags: python, flycheck, lsp ---
thread-68296
https://emacs.stackexchange.com/questions/68296
Cons interpolation
2021-08-28T07:05:54.397
# Question Title: Cons interpolation I want to be able to write a cons with some of the cells being placeholders for later evaluation. I know I can use backquote constructs, but it tries to evaluate the cons immediately. To clarify, provided I have a variable `my-value`, I could do: `(setq my-cons `(my-key ,my-value))` But this won't satisfy my needs, as it's evaluated immediately. I can't use my-cons, without knowing about its structure, to create another cons like `'(my-key "another-value")`. I need to be able to provide the structure as a variable, and fill it with real data later. Think about `format` function: We define a string, with some placeholders, and then use `format` to inject our data into the string. What I need, is analogous to a format string, but for cons. Detailed use-case: I want to convert a org-mode todo entry to a Jira ticket. org-jira and ejira, both have a shortcoming: they only read some basic data (project, ticket type summary). Since Jira is customizable, each project could have its different set of required fields. A useful org-todo-to-jira would allow you to define a mapping between org properties, and Jira fields. I want my org DEADLINE to be interpreted as ``` { duedate: "deadline-value-here" } ``` and my :estimation: to be interpreted as ``` { estimation: { originalEstimation: "estimation-value-here" } } ``` But a user might want another mapping. The cleanest thing that I thought of, was an alist defined by defcustom: the car of each cell being a property, and the cdr being another cons, defining the structure for that field: telling us how that field should be converted to a json. The car lets me know where to find that property in org todo entry, and the cdr lets me know where should I put that value in my json. # Answer I ended up doing this: If I set a `my-cons` variable like this: `(setq my-cons '`(my-key ,placeholder))` Whenever I want to replace placeholder with something else, I could do`(eval my-cons))` ``` (let ((placeholder "my-value")) (print (eval my-cons))) ;; prints (my-key "my-value") ``` > -1 votes --- Tags: backquote ---
thread-32881
https://emacs.stackexchange.com/questions/32881
Enabling minibuffer pinentry with Emacs 25 and GnuPG 2.1 on Ubuntu Xenial
2017-05-17T13:59:28.513
# Question Title: Enabling minibuffer pinentry with Emacs 25 and GnuPG 2.1 on Ubuntu Xenial *I had to do quite some diving and hunting through documentation and forums, so I figured I might as well do a Q&A here for others:* How do I enable GnuPG passphrase prompting in the minibuffer? The Emacs 25.1 changelog says: > \** pinentry.el allows GnuPG passphrase to be prompted through the minibuffer instead of a graphical dialog, depending on whether the gpg command is called from Emacs (i.e., INSIDE\_EMACS environment variable is set). This feature requires newer versions of GnuPG (2.1.5 or later) and Pinentry (0.9.5 or later). To use this feature, add "allow-emacs-pinentry" to "~/.gnupg/gpg-agent.conf" and reload the configuration with "gpgconf --reload gpg-agent". Doing just that, I just get an error message now and not even the graphical passphrase prompt. This is GNU Emacs 25.2.2 on Lubuntu (Ubuntu Xenial) with GnuPG 2.1.11. # Answer You also have to 1. Explicitely enable loopback mode for pinentry in your gpg-agent.conf. 2. Configure epa to use loopback for pinentry. 3. Start the pinentry server in emacs, ## 1. Enable Emacs pinentry and loopback mode for gpg-agent Put this in your ~/.gnupg/gpg-agent.conf: ``` allow-emacs-pinentry allow-loopback-pinentry ``` Then tell gpg-agent to load this configuration with `gpgconf` in a shell: ``` gpgconf --reload gpg-agent ``` ## 2. Configure EasyPG Assistant to use loopback for pinentry In emacs, **either** do ``` M-x customize-group RET epa RET ``` Then set “Epa Pinentry Mode” to ‘loopback’ and apply. **Or** put this in your ~/.emacs file: ``` (setq epa-pinentry-mode 'loopback) ``` **Note**: `epa-pinentry-mode` is deprecated since 27.1, **either** do ``` M-x customize-group RET epg RET ``` Then set “Epg Pinentry Mode” to ‘loopback’ and apply. **Or** put this in your ~/.emacs file: ``` (setq epg-pinentry-mode 'loopback) ``` Finally, in Emacs, do ``` M-x pinentry-start RET ``` This starts the server for the current session. To start it in each new Emacs instance, put this into your .emacs: ``` (pinentry-start) ``` > 30 votes # Answer For setups with `GnuPG >= 2.1`, `pinentry` package is not needed anymore. Quote from the `Emacs` `News.26` file: ``` ** The pinentry.el library has been removed. That package (and the corresponding change in GnuPG and pinentry) was intended to provide a way to input passphrase through Emacs with GnuPG 2.0. However, the change to support that was only implemented in GnuPG >= 2.1 and didn't get backported to GnuPG 2.0. And with GnuPG 2.1 and later, pinentry.el is not needed at all. So the library was useless, and we removed it. GnuPG 2.0 is no longer supported by the upstream project. To adapt to the change, you may need to set 'epa-pinentry-mode' to the symbol 'loopback'. Alternatively, leave 'epa-pinentry-mode' at its default value of nil, and remove the 'allow-emacs-pinentry' setting from your 'gpg-agent.conf' configuration file, usually found in the '~/.gnupg' directory. Note that previously, it was said that passphrase input through minibuffer would be much less secure than other graphical pinentry programs. However, these days the difference is insignificant: the 'read-password' function sufficiently protects input from leakage to message logs. Emacs still doesn't use secure memory to protect passphrases, but it was also removed from other pinentry programs as the attack is unrealistic on modern computer systems which don't utilize swap memory usually. ``` See also a discussion on why pinentry was removed from `Emacs` core. So a setup may now consist of: 1. In `Emacs'` `user-init-file`: ``` (require 'epg) (setq epg-pinentry-mode 'loopback) ``` 2. In `~/.gnupg/gpg-agent.conf`: ``` allow-emacs-pinentry # on Mac OS pinentry-program /usr/local/bin/pinentry-mac ``` > 6 votes --- Tags: gpg, passwords, epa ---
thread-68275
https://emacs.stackexchange.com/questions/68275
Is there a way to get the line of the currently executing s-expression?
2021-08-27T05:25:01.830
# Question Title: Is there a way to get the line of the currently executing s-expression? Say I have a some code in my init file (line numbers are marked on the left-side margin): ``` 1. 2. 3. 4. 5. (let ((a 1)) 6. (message "a%s steak sauce" a)) 7. 8. 9. 10. => "a1 steak sauce" ``` Is there a function to get the line of the currently executing s-expression (something like the following)? ``` 1. 2. 3. 4. 5. (let ((a 1)) 6. (message "a%s steak sauce" a) 7. (message "currently executing s-expression on line: %s" 8. (get-currently-executing-s-expression-line))) 9. 10. => "currently executing line: 5" ``` # Answer > 2 votes I agree that this is probably an X-Y problem. It is also likely that you have solved problems like this in the past by using the `__LINE__` macro in C, or something analogous, and you’re reaching for the familiar solution. Sometimes the familiar solutions are not the best! However, I will try to answer the question. The short answer is just “No”. The long answer is much more interesting. First, your example is somewhat problematic, because it says that “line 5” is being executed while actually the sexps on lines 5, 7, and 8 are all on the stack at that point. You seem to want it to print line 5 because that is the current top–level form. I think it would be more natural to print “line 8”, because that is the current inner–most form that you would care about (assuming you don’t want to see a line number from whatever file contains the definition of `get-currently-executing-s-expression-line`.) I don’t know very many details about how Emacs keeps track of what code it is currently executing, but I assume that there must be a stack. (Can you name any systems that don’t have a stack?! I think they all went extinct.) Ok, I kinda lied. I have already used the Emacs debugger once or twice before, and I know that it shows you the stack in a buffer. Therefore there must be some code in Emacs which puts the details about the stack into the buffer. We can read that code, therefore we can easily figure out how it works. First let’s take a look at that stack, to remind ourselves what it looks like. Try putting this in the `*scratch*` buffer and executing it: ``` (let ((a 1)) (message "a%s steak sauce" a) (message "currently executing s-expression on line: %s" (debug))) ``` Calling `debug` just dumps you straight into the debugger; there are other ways to get into the debugger, but this is the most useful for this example. Here’s the stacktrace that I see: ``` Debugger entered: nil (message "currently executing s-expression on line: %s" (debug)) (let ((a 1)) (message "a%s steak sauce" a) (message "currently executing s-expression on line: %s" (debug))) eval((let ((a 1)) (message "a%s steak sauce" a) (message "currently executing s-expression on line: %s" (debug))) nil) elisp--eval-last-sexp(nil) eval-last-sexp(nil) funcall-interactively(eval-last-sexp nil) #<subr call-interactively>(eval-last-sexp nil nil) apply(#<subr call-interactively> eval-last-sexp (nil nil)) call-interactively@ido-cr+-record-current-command(#<subr call-interactively> eval-last-sexp nil nil) apply(call-interactively@ido-cr+-record-current-command #<subr call-interactively> (eval-last-sexp nil nil)) call-interactively(eval-last-sexp nil nil) command-execute(eval-last-sexp) ``` The bottom 9 lines are all about me calling `eval-last-sexp` (bound to `C-x C-e` by default). Then that calls eval on my source code, and the top two lines are the ones we actually care about. If we could get line numbers for those frames, then we could pick among them to answer your question. Now we can look at the code that generated this buffer. I decided to start with the `debug` function. `C-x h f` asks for a function name, so I typed in `debug` and hit enter. This got me a description of the function, and most importantly, a link to the source code. I clicked that link. I saw that `debug` is a long and complicated function, but right in the middle I saw a call to `debugger-setup-buffer`. That sounded promising, so I put the point on it and hit `M-.` to jump to the definition. The first thing that `debugger-setup-buffer` does is set the variable `backtrace-frames` to the result of calling `backtrace-get-frames`. This seems very promising indeed! `backtrace-get-frames` calls `mapbacktrace`, passing in am anonymous function that pushes something into a local variable. Eliding some of the details, this is what I see: ``` (let ((frames nil)) (mapbacktrace (lambda (…) (push … frames)) …) …) ``` So this is using `mapbacktrace` to copy the details of each frame into an ordinary Lisp list. Presumably that list is folded, spindled, and mutilated before finally getting printed out. If we pull that out into the `*scratch*` buffer, edit it slightly, run it with `C-u C-x C-e`, and then edit the result for readability, this is what we get: ``` (#s(backtrace-frame t mapbacktrace ((lambda ... ...)) nil nil nil nil) #s(backtrace-frame nil let ((...) (mapbacktrace ...) (setq frames ...) frames) nil nil nil nil) #s(backtrace-frame t eval ((let ... ... ... frames) nil) nil nil nil nil) #s(backtrace-frame t elisp--eval-last-sexp (nil) nil nil nil nil) …) ``` It’s a longish list of `backtrace-frame` objects that hold onto the details about each frame. `mapbacktrace` gives us all the information about the frame, and we could do with that what we want; we don’t have to use `backtrace-frame` objects if we don’t want to. You have probably noticed that the filename and line number are not shown. `mapbacktrace` gives us the form being called and any arguments to it, but nothing about the file or line number. Emacs just does not keep the file name and line number around like you would expect. It doesn’t need to in most cases; instead it keeps around the result of parsing the file. That “result of parsing” is an ordinary Lisp list that can be printed out or examined at any time; you can see it included in the backtrace objects above. In other languages this would be called an Abstract Syntax Tree. Lisp predates the invention of that name, so we just call it a list. So whatever it was you were trying to do is going to need an unfamiliar solution, rather than a familiar one. If all you want to do is step through your init file, put a (debug) at the top and then single–step the debugger by pressing `d` repeatedly. (`C-h m` will tell you about other commands available in the debugger). If you want to print out a report about functions that were called, then perhaps tracing is a better choice. You can call `trace` on any function and every call to that function will generate a log message in the `*Trace*` buffer. The log messages will include the argument values and return value, and if a traced function calls other traced functions, the log messages will be nested to make that plain. I recommend asking one or more high–level questions that are quite explicit about the exact features you want. We may be able to recommend existing features or packages that can do the job, but until you ask those questions we’ll be left guessing. --- Tags: init-file ---
thread-68315
https://emacs.stackexchange.com/questions/68315
Call an interactive function and pass argument to it in elisp without user input
2021-08-30T13:29:29.450
# Question Title: Call an interactive function and pass argument to it in elisp without user input * I am new to elisp and am trying to write an Elisp function that calls `org-pandoc-export-to-html5-pdf-and-open`. * `org-pandoc-export-to-html5-pdf-and-open` is an interactive function that will write to a file, and when called via `M-x`, it prompts the user for a filename to enter in the minibuffer. * I want to pass a default value for the filename so that the user does not have to enter the name manually. The file and its path is `/tmp/tmp.html`. **What is the simplest way for me to do this?** I want to acknowledge that many versions of this question have been asked before, if someone automatically marks this as a duplicate. Below is a table, with some comments. I think question 4 comes closest in spirit to this question, but it wasn't answered, and marked as a duplicate of a question which is similar in the way that *australiopithecus* is similar to *homo sapiens sapiens* \- similar at root level but there is a meaningful difference. Otherwise, my question is one of approach: * Qs 1,6 suggest `minibuffer-setup` usage * Q 7 suggests `thing-at-point`. * I have tried various combinations of `funcall`, `commandp`, `command-execute`, but the user prompt remains. * I have read some of the manual describing interactive calls here, and have done `C-h f` on the function at hand, but can't quite translate what little I understand from the manual to the desired functionality. | Question | Function/topic | Resolved? (And probable solution?) | Useful in this case? | | --- | --- | --- | --- | | 1. Call a function and insert text in minibuffer prompt | `ivy-switch-buffer` insert yank into minibuffer | Yes, `(add-hook 'minibuffer-setup-hook 'foo)` | Maybe | | 2. Call function interactively and set initial content | Default value when calling `find-file` | Yes, `let ((default-directory "/home/")` | No | | 3. How to call an interactive function and pass arguments to it from within Elisp? | Use `call-interactively` or `command-execute` for `describe-package`, pass value `xref` | Yes-ish - wrong argument type passed | No | | 4. Call an interactive function without asking for user input \[duplicate\] | Call e.g. `projectile-test-project` with a predefined argument, without user asking anything | No, marked as duplicate of 5 | Maybe - same question, unresolved | | 5. How to use 'interactive' arguments when calling the command from code | Call an interactive function which takes user input | Yes, trivially: `(call-interactively 'test)` | No, and not sure how it answers 4! | | 6. Inserting Text into an Active Minibuffer | Insert text into minibuffer after external command is run (like Q1) | Yes, `(add-hook 'minibuffer-setup-hook 'foo)` | Maybe - statement that `minbuffer-setup-hook` is the "idiomatic way" | | 7. emacs interactive commands with default value | Default values for interactive commands, `thing-at-point` | Yes | Maybe - `thing-at-point-usage`? | | 8. call write-file interactively with prompting | Use `write-file` with default file name | Yes, `condition-case-nil` to fallback to default value | Maybe, another answer suggests `(call-interactively 'write-file (vector path))` | | 9. emacs how to use call-interactively with parameter | Call `wg-save`, then switch window config | Yes, with `(call-interactively 'my-fn t (vector arg1 arg2))` | Maybe | # Answer Eh, messing with the minibuffer or the window config is the wrong way to go. Any solution like that would be messy, fragile, and ugly. The right thing to do is examine the source code of the function you’re calling and understand it’s features and limitations. Incidentally, I’m assuming that the function you care about is from the `ox-pandoc` melpa package. I’ve never used it before, but it looks pretty straight forward. `org-pandoc-export-to-html5-and-open` just calls `org-pandoc-export` with a couple of the options already specified. `org-pandoc-export` fills in a couple more arguments and calls `org-export-to-file`. One of those arguments is the file name, so we don’t need to follow that chain any further. To determine the file name, it calls `org-export-output-filename` (which incidentally is part of `org-mode` rather than `ox-pandoc`). `org-export-output-filename` picks a filename automatically if it can, and only prompts the user if it cannot. It prompts the user by calling `read-file-name` as is right and proper. Amongst its many virtues, `read-file-name` takes an optional argument that specifies the default file name to use if the user leaves the prompt empty. Sadly, `org-export-output-filename` specifies `nil` for this argument. There are three ways that it can determine the file name automatically. The cursor could be on a subtree with a `EXPORT_FILE_NAME` property, the document could have a `#+EXPORT_FILE_NAME` keyword, or the buffer could be an indirect buffer in which case the export will overwrite the file visited by the buffer’s base buffer (?! I’m going to ignore that one.). Adding an #+EXPORT\_FILE\_NAME keyword to the top of your org files seems like a really easy solution to this problem, but let’s assume that that it’s not an option for some reason. You could very easily modify `org-export-output-filename`. You could just copy it into your init file and edit the copy so that it specifies the default file name when calling `read-file-name`. You could advise it so that it specifies a default file name, but you might not know about advise so copy–and–paste would be easier. Also, given the way this function is written, the advise would have to duplicate the body of the function anyway. Either way, you could also send your modification back to the author of `org-mode`, if you make it in such a way that the modification is usable by others. If you added a variable called `org-export-default-output-filename`, and then used it in the `org-export-output-filename` function, the caller could set that variable just before kicking off an export and all exporters would do the right thing. Here’s the code you would want: ``` (defvar org-export-default-output-filename nil) (defun org-export-output-file-name (extension &optional subtreep pub-dir) "Return output file's name according to buffer specifications. EXTENSION is a string representing the output file extension, with the leading dot. With a non-nil optional argument SUBTREEP, try to determine output file's name by looking for \"EXPORT_FILE_NAME\" property of subtree at point. When optional argument PUB-DIR is set, use it as the publishing directory. Return file name as a string." (let* ((visited-file (buffer-file-name (buffer-base-buffer))) (base-name (concat (file-name-sans-extension (or ;; Check EXPORT_FILE_NAME subtree property. (and subtreep (org-entry-get nil "EXPORT_FILE_NAME" 'selective)) ;; Check #+EXPORT_FILE_NAME keyword. (org-with-point-at (point-min) (catch :found (let ((case-fold-search t)) (while (re-search-forward "^[ \t]*#\\+EXPORT_FILE_NAME:[ \t]+\\S-" nil t) (let ((element (org-element-at-point))) (when (eq 'keyword (org-element-type element)) (throw :found (org-element-property :value element)))))))) ;; Extract from buffer's associated file, if any. (and visited-file (file-name-nondirectory visited-file)) ;; Can't determine file name on our own: ask user. (read-file-name "Output file: " pub-dir org-export-default-output-filename nil nil (lambda (n) (string= extension (file-name-extension n t)))))) extension)) (output-file ;; Build file name. Enforce EXTENSION over whatever user ;; may have come up with. PUB-DIR, if defined, always has ;; precedence over any provided path. (cond (pub-dir (concat (file-name-as-directory pub-dir) (file-name-nondirectory base-name))) ((file-name-absolute-p base-name) base-name) (t base-name)))) ;; If writing to OUTPUT-FILE would overwrite original file, append ;; EXTENSION another time to final name. (if (and visited-file (file-equal-p visited-file output-file)) (concat output-file extension) output-file))) ``` With that in your init file, you could then write your function something like this: ``` (defun my-export-function () (interactive) (let ((org-export-default-output-filename "/tmp/tmp.html")) (org-pandoc-export-to-html5-pdf-and-open …))) ``` Once you’ve verified that it works, head over to https://orgmode.org/contribute.html for information about sending them a patch. > 2 votes --- Tags: functions, interactive, call-interactively ---
thread-50216
https://emacs.stackexchange.com/questions/50216
org-mode code block parentheses mismatch
2019-04-29T15:39:22.583
# Question Title: org-mode code block parentheses mismatch Here's some emacs-lisp code in a babel block: ``` #+begin_src emacs-lisp (defun factor (number) (labels ((*factor (divisor number) (if (> (* divisor divisor) number) (list number) (if (= (mod number divisor) 0) (cons divisor (*factor divisor (/ number divisor))) (*factor (+ divisor 1) number))))) (*factor 2 number))) #+end_src ``` So in the org buffer I get a parentheses matching problem, i.e., that very last ) at the bottom is flagged as one too many. It flashes red and `check-parens` flags it as well. Trouble is, this is not an error, i.e., the same code in *scratch* is perfectly paren-matched, likewise when I bring it up in the Org Source `C-c '` window. BTW, this code compiles and runs giving good output. Any ideas what org-mode is doing here? I've got `(show-paren-mode 1)`. When I turn it off, obviously, no problem because no highlighting matching parens. # Answer > 4 votes Here is a potential solution: ``` (defun org-mode-<>-syntax-fix (start end) (when (eq major-mode 'org-mode) (save-excursion (goto-char start) (while (re-search-forward "<\\|>" end t) (when (get-text-property (point) 'src-block) ;; This is a < or > in an org-src block (put-text-property (point) (1- (point)) 'syntax-table (string-to-syntax "_"))))))) (add-hook 'org-mode-hook (lambda () (setq syntax-propertize-function 'org-mode-<>-syntax-fix) (syntax-propertize (point-max)))) ``` This basically just changes the syntax table for \<\> inside src blocks I think. It seems to solve the problem. --- The code above depends on source blocks already propertized with `src-block`. The `src-block` property is put on source blocks by `org-fontify-meta-lines-and-blocks` during keyword fontification through `font-lock`. But, syntax fontification comes before keyword fontification. So maybe the following function is better. For easier copy-paste the full code is given. The main change is the search for source blocks by `re-search-backward`. We set `syntax-propertize-function` as a buffer-local variable to avoid unforeseen consequences outside of our org-mode buffers, such as in `cc-mode`'s check for `syntax-table` functionality, which otherwise fails and prevents HTML exports of org-mode buffers. ``` (defun org-mode-<>-syntax-fix (start end) "Change syntax of characters ?< and ?> to symbol within source code blocks." (let ((case-fold-search t)) (when (eq major-mode 'org-mode) (save-excursion (goto-char start) (while (re-search-forward "<\\|>" end t) (when (save-excursion (and (re-search-backward "[[:space:]]*#\\+\\(begin\\|end\\)_src\\_>" nil t) (string-equal (downcase (match-string 1)) "begin"))) ;; This is a < or > in an org-src block (put-text-property (point) (1- (point)) 'syntax-table (string-to-syntax "_")))))))) (defun org-setup-<>-syntax-fix () "Setup for characters ?< and ?> in source code blocks. Add this function to `org-mode-hook'." (make-local-variable 'syntax-propertize-function) (setq syntax-propertize-function 'org-mode-<>-syntax-fix) (syntax-propertize (point-max))) (add-hook 'org-mode-hook #'org-setup-<>-syntax-fix) ``` # Answer > 3 votes The *reason* for the mismatch is the code contains an angled bracket ("\>") which is treated as a matching paren. I don't know the solution for how to specify that orgmode emacs-elisp should ignore angled brackets when matching parens (but I would like to know a solution). Note: I posted this as an "answer" because I don't have enough reputation points to post it as a comment in the OP. # Answer > 2 votes Since I never use \<\> as brackets in org mode documents, I have these two lines in my org mode hook function: ``` (modify-syntax-entry ?< ".") (modify-syntax-entry ?> ".") ``` No need to play around with properties etc. Of course, if you use XML or HTML, you may wish to avoid this. # Answer > 2 votes A small variation of eric's answer that works for me: ``` (defun org-syntax-table-modify () "Modify `org-mode-syntax-table' for the current org buffer." (modify-syntax-entry ?< "." org-mode-syntax-table) (modify-syntax-entry ?> "." org-mode-syntax-table)) (add-hook 'org-mode-hook #'org-syntax-table-modify) ``` --- Tags: org-mode, org-babel, parentheses ---
thread-68146
https://emacs.stackexchange.com/questions/68146
How to suppress `Wrote /home/user/.emacs.d/recentf` message in minibuffer
2021-08-17T13:43:19.503
# Question Title: How to suppress `Wrote /home/user/.emacs.d/recentf` message in minibuffer In the minibuffer I keep seeing: ``` Wrote /home/user/.emacs.d/recentf ``` Would it be possible to suppress this message? (Only for file name `recentf` file) --- my minimal.el: ``` (setq recentf-max-saved-items 50) (setq recentf-max-menu-items 50) (setq recentf-exclude '("^/var/folders\\.*" "[/\\]\\.elpa/" "COMMIT_EDITMSG\\'" "\\TODO_archive\\'" )) (run-at-time nil (* 5 60) 'recentf-save-list) (add-hook 'delete-terminal-functions (lambda (terminal) (recentf-save-list))) (recentf-load-list) (setq recentf-save-file (recentf-expand-file-name "~/.emacs.d/.recentf")) (setq recentf-auto-cleanup 10) (recentf-mode 1) ``` # Answer > 5 votes This should do it. ``` (defun no-msg (function) "Prevent FUNCTION from showing `Wrote <FILE>' messages. \(The messages are still logged to `*Messages*'.)" (let ((inhibit-message t)) (funcall function))) (advice-add 'recentf-save-list :around 'no-msg) ``` To see the messages again, use `(advice-remove 'recentf-save-list 'no-msg)`. --- Tags: minibuffer, advice, message, recentf, nadvice ---
thread-68314
https://emacs.stackexchange.com/questions/68314
How to show an Info mode manual entirely on one page
2021-08-30T13:12:08.703
# Question Title: How to show an Info mode manual entirely on one page Using `C-h R elisp` brings up the Emacs Lisp Reference Manual in Info mode. How can I show the manual entirely on one page? Something akin to https://www.gnu.org/software/emacs/manual/html\_mono/elisp.html? # Answer > 9 votes If you use Info+ then you can easily get a whole manual, or any node together with its subnodes, in a single, fully functional Info buffer. Command **`Info-merge-subnodes`**, bound to **`+`** in `Info-mode`, integrates the current Info node with its subnodes (the nodes in its Menu), perhaps recursively. Use it to extract a self-contained report (possibly the whole manual) from an Info manual. The report is itself an Info buffer, with hyperlinks and normal Info behavior. There are various prefix-argument possibilities that govern just how subnodes are treated (recursively or not, for instance). There are a few user options that let you customize the report appearance. Here's what `C-h k +` tells you: > **`+`** runs the command **`Info-merge-subnodes`** (found in `Info-mode-map`), which is an interactive compiled Lisp function in **`info+.el`**. > > It is bound to `+`, `menu-bar Info Merge Subnodes`. > > `(Info-merge-subnodes &optional RECURSIVE-DISPLAY-P RECURSIVE-CALL-P)` > > Integrate current node with nodes referred to in its Menu. > > Displays the current Info node, together with the nodes in its Menu. Buffer `*Info: NODE*` is used for the display, where `NODE` is the name of the current node. The contents of this node's subnodes (the nodes named in this node's Menu) are included in the buffer, following the contents of the current node. > > Optional arg `RECURSIVE-DISPLAY-P` (prefix arg if interactive) governs the way menus of subnodes are treated: > > * If `nil`, nothing additional happens. Subnode menus are not explored. Only the current node and its immediate subnodes are documented, in the single display buffer `*Info: NODE*`. > * If non-`nil`, then the subnodes of a node are treated in the same way as the parent node, recursively: If any of them has, itself, a Menu, then that menu's subnodes are also explored, and so on. > > + If `RECURSIVE-DISPLAY-P` is zero, then a single display buffer is used for all of the nodes explored. Otherwise, a separate display buffer is used for each subnode that has a Menu (see next). > > Use this when you want a single, flat compilation of the current node and all of its subnodes. It is less appropriate when the current node has several levels of subnodes: The flattened result can be difficult to read. > + If `RECURSIVE-DISPLAY-P` is positive, then the contents of each subnode are displayed twice: once in the parent node's display, and once in the subnode's own display. > > Use this when the current node has several levels of subnodes and you want each display buffer to be self-contained. > + If `RECURSIVE-DISPLAY-P` is negative, then there is no redundancy: A subnode's contents are only displayed in its parent's buffer. The subnode's own display buffer only contains the contents of its own subnodes. > > Use this when the current node has several levels of subnodes and you want no redundancy between the display buffers. > > The user option (variable) `Info-subtree-separator` is a string to be inserted by `Info-merge-subnodes` just before the title of each node (preceding its description). By default it is `"\n* "`, producing a node title resembling a menu item. Setting this to `"\f\n* "` will cause a page break before each node description. For more on setting this variable, type `C-h v Info-subtree-separator`. > > --- > > Optional second arg `RECURSIVE-CALL-P` is only for internal use. It is used to indicate whether (non-`nil`) or not (`nil`) this is a recursive (i.e. not a top-level) call to `Info-merge-subnodes`. Non-`nil` means that this is a subnode, and that its contents should only be included in the present display if `RECURSIVE-DISPLAY-P` is also non-`nil`. For proper operation when `RECURSIVE-DISPLAY-P` is zero, the non-`nil` value of `RECURSIVE-CALL-P` should be the node name of the top-level call to `Info-merge-subnodes`. # Answer > 5 votes The info buffers already contain the whole manual. They just use narrowing to show one section at a time. If you want to see the whole thing, just do `C-x n w` to widen the buffer. No need for packages. EDIT: Since Info-mode re-narrows the buffer when following links, one can use an advice to keep the buffer wide: ``` (defun widen-after-info-follow (&rest _) (widen)) (advice-add 'Info-follow-nearest-node :after 'widen-after-info-follow) ``` --- Tags: info ---
thread-68322
https://emacs.stackexchange.com/questions/68322
can't make vm run in emacs > 25;
2021-08-30T21:34:23.157
# Question Title: can't make vm run in emacs > 25; My life depends on the vm email reader in emacs, and I'm currently using vm 8.2.0b under emacs 25.2.2. When trying to upgrade emacs, I run into problems. In emacs 26.3, I get the message "Symbol's function definition is void, defun\*" -- the asterisk after 'defun' is key here, I believe. # Answer > 2 votes `defun*` is an alias for `cl-defun`, which is a macro defined in `cl-macs.el`. Prior to loading a library that uses `defun*`, consider expressly loading the `cl-...` libraries with `(require 'cl)`. Some important changes were made to the `cl-...` libraries in Emacs 26, which differ from those of Emacs 25. If the O.P. encounters problems with the `cl-...` libraries that were not present in Emacs 25, then it may be necessary to invest time debugging to track down the relevant changes .... --- Tags: emacs26 ---
thread-68330
https://emacs.stackexchange.com/questions/68330
Pass arguments captured from minibuffer to shell command in a function
2021-08-31T16:43:20.677
# Question Title: Pass arguments captured from minibuffer to shell command in a function I'm struggling with passing arguments read from the minibuffer to a shell command in a elisp function. I've written the following so far: ``` (defun perlclean (review clean) "Script PERL blablabla" (interactive "Foriginal: \nFclean: ") (with-current-buffer (shell-command "perl -pe 's/\\q\{.*} ( \{ ( (?: [^}{]+ | (?1))*+ ) \} )/$2/gx' %s\\ \\>\\ %s" review clean))) ``` The idea is to pass the first file (called `review`) through this `perl` command to get the so-called clean file. I want to specify the name of both files (that could not exist, that's why I used `F`). The present version of this script asks me for both paths/names but ended with `Wrong type argument: stringp,255`. I work on Linux-Ubuntu. # Answer There are a couple of problems here. You're using `with-current-buffer`, which expects its first argument to be either a buffer, or the name of a buffer. In your function, this will be the value returned by `shell-command`, which is neither a buffer or the name of a buffer. You've also used the strings `return` and `clean` as the arguments for `OUTPUT-BUFFER` and `ERROR-BUFFER`. Neither of these variables are buffers or buffer names, so I'm not sure what you're expecting to happen here, but it's not surprising there's an error. To answer your actual question, it's straightforward to collect arguments from the minibuffer and pass them to a shell command: ``` (defun perlclean (review clean) "Script PERL blablabla" (interactive "Foriginal: \nFclean: ") (shell-command (format "echo Review: %s Clean: %s" review clean))) ``` Running this command, you'll see the output of the `echo` command in the minibuffer, and also in a new buffer called `* Shell Command Output*`. > 1 votes # Answer The error message is confusing, but you’re passing a string to something that expects something else. Specifically, the `shell-command` function takes these arguments: ``` (shell-command COMMAND &optional OUTPUT-BUFFER ERROR-BUFFER) ``` It takes the command to run followed by two buffers to use for the output and any errors the command produces. You’re passing in strings instead of buffers. I suspect that you wanted to interpolate those strings into the command, but `shell-command` doesn’t do that for you. I recommend using functions like `shell-quote-argument` or `combine-and-quote-arguments` to build the command. See chapter 38.2 Shell Arguments of the Emacs Lisp manual for more information. > 0 votes --- Tags: shell-command, interactive ---
thread-68311
https://emacs.stackexchange.com/questions/68311
Org-ref-like interface in reftex
2021-08-29T23:11:45.207
# Question Title: Org-ref-like interface in reftex I am currently typesetting my Ph.D. thesis with `AucTeX` and `RefTeX` and I would like to be able to interact with my citations in a way that is similar to what happens in `org-mode`with `org-ref`e.g. being able to open the correponding PDF file or annotations right from the in-text citekey. Currently I can bypass the problem by searchig the publication in `helm-bibtex` through its citekey, but I would be interested in knowing if a more direct solution is possible. # Answer > 1 votes One strategy that is very simple is to define a function, and bind it to a convenient key. Here is one example. You just type C-o on a key, this function finds the key, then uses bibtex-completion to open it. ``` (require 'bibtex-completion) (defun open-key-at-point () (interactive) (let (start end key) (save-excursion (setq start (progn (re-search-backward "{\\|,") (match-end 0)) end (progn (re-search-forward "}\\|,") (match-beginning 0)) key (buffer-substring-no-properties start end))) (bibtex-completion-show-entry (list key)) (bibtex-beginning-of-entry))) (define-key tex-mode-map (kbd "C-o") #'open-key-at-point) ``` To get org-ref open on click behavior, you need to use font-lock to add properties to the citations. There is some code at https://github.com/jkitchin/org-ref/blob/org-ref-3/org-ref-latex.el that might work for you. It is not heavily tested. this version will eventually replace what is in the master branch. # Answer > 0 votes The package bibtex-utils provides the function `bu-jump-to-doc` which takes you from a bibtex citation in a document to the pdf of that document. You'll need to bind it to a convenient key. For more details, and some related functions for dealing with Bibtex databases, see the home page for the package linked above. If you use bibtex keys in different modes (i.e., markdown, org, latex), you might want to bind this to a key in the global map: ``` (global-set-key [f9] 'bu-jump-to-doc) ``` Otherwise, you can bind it to a key in whichever mode you want to access it from. --- Tags: org-ref, reftex-mode ---
thread-63066
https://emacs.stackexchange.com/questions/63066
Org mode + Gnu Octave session
2021-01-29T16:53:22.963
# Question Title: Org mode + Gnu Octave session I interact with the Gnu Octave's inferior mode and everything seems to be working fine there: ``` octave> pkg load symbolic octave> syms x g = (x+1)/sqrt(x^2 - 1) simplify(diff(g,x)) octave> g = (sym) x + 1 ─────────── ________ ╱ 2 ╲╱ x - 1 octave> ans = (sym) -1 ─────────────────── ________ ╱ 2 (x - 1)⋅╲╱ x - 1 ``` Now I do the same using org mode and babel where I get an error: ``` #+begin_src octave :session :eval never-export :results verbatim pkg load symbolic syms x g = (x+1)/sqrt(x^2 - 1) ans = simplify(diff(g,x)) #+end_src ``` And when I evaluate the above code, I see the following error in the inferior mode's octave session: ``` octave> > > error: fprintf: wrong type argument 'class' error: called from dlmwrite at line 195 column 7 ``` Any idea on what I'm doing wrong ? # Answer So I have found an workaround by playing around with different header arguments. This works for me: ``` #+begin_src octave :session :eval never-export :results value verbatim output replace pkg load symbolic syms x g = (x+1)/sqrt(x^2 - 1) ans = simplify(diff(g,x)) #+end_src #+RESULTS: #+begin_example octave> g = (sym) x + 1 ─────────── ________ ╱ 2 ╲╱ x - 1 ans = (sym) -1 ─────────────────── ________ ╱ 2 (x - 1)⋅╲╱ x - 1 #+end_example ``` > 0 votes # Answer ## The Error ``` octave> > > error: fprintf: wrong type argument 'class' error: called from dlmwrite at line 195 column 7 ``` This is because you assigned a value of type `sym` to the variable `ans`. `fprintf()`, which is a part of wrapping code while Org Babel is evaluating it, is trying to write the given `ans` but because the value of `ans` isn't class `char` and it complains about it. See `org-babel-octave-wrapper-method` in `ob-octave.el` for the wrapping code. The Org Manual 9.4 `(info "(org) Results of Evaluation")` says: > ## Collection > > Collection options specify the results. Choose one of the options; they are mutually exclusive. > > **value** > > Default for most Babel libraries(1). Functional mode. Org gets the value by wrapping the code in a function definition in the language of the source block. That is why when using `:results value`, code should execute like a function and return a value. For languages like Python, an explicit `return` statement is mandatory when using `:results value`. Result is the value returned by the last statement in the code block. > > When evaluating the code block in a session (see \*note Environment of a Code Block::), Org passes the code to an interpreter running as an interactive Emacs inferior process. Org gets the value from the source code interpreter’s last statement output. Org has to use language-specific methods to obtain the value. For example, from the variable `_` in Ruby, and the value of `.Last.value` in R. > > **output** > > Scripting mode. Org passes the code to an external process running the interpreter. Org returns the contents of the standard output stream as text results. > > When using a session, Org passes the code to the interpreter running as an interactive Emacs inferior process. Org concatenates any text output from the interpreter and returns the collection as a result. For Octave, with **value**, you either * a) assign the value you want to return to Org buffer to the variable `ans`, or * b) evaluate without assigning it to any variable so that the interpreter assign your value to the automatic variable `ans`. Unfortunately, the current `ob-octave` doesn't parse class `sym` well. This leaves you to use **output** instead. With **output**, you just get everything back from the interpreter. ## Getting a Result Thus, with the following code block: ``` #+begin_src octave :session :results output pkg load symbolic syms x g = (x+1)/sqrt(x^2 - 1) simplify(diff(g,x)) #+end_src ``` You get this ``` #+RESULTS: #+begin_example octave> g = (sym) x + 1 ─────────── ________ ╱ 2 ╲╱ x - 1 ans = (sym) -1 ─────────────────── ________ ╱ 2 (x - 1)⋅╲╱ x - 1 #+end_example ``` ## Result Types Unfortunately, the current Babel Octave doesn't support result types. Thus, `verbatim`, or any other type, doesn't work at all. ## Remarks These might change in the future if someone fixed them. This result was produced with ``` (org-version nil t) "Org mode version 9.4.6 (release_9.4.6-628-g366444 @ /home/yashi/src/org-mode/lisp/)" ``` > 1 votes --- Tags: org-mode, org-babel, octave ---
thread-68334
https://emacs.stackexchange.com/questions/68334
Is it possible to install GccEmacs for Emacs 27.2
2021-08-31T21:59:48.110
# Question Title: Is it possible to install GccEmacs for Emacs 27.2 For installing `GccEmacs`, I have followed: https://www.emacswiki.org/emacs/GccEmacs > ``` > git clone git://git.savannah.gnu.org/emacs.git > cd emacs > ./autogen.sh > ./configure --with-native-compilation > make -j$(nproc) > > ``` which installs: `GNU Emacs 28.0.50`. As I understand its an experimental / developmental version of Emacs not yet released to the general public. Instead how can I build `GccEmacs` for Emacs'sreleased version, I believe for Emacs 27.2? I have tried `it checkout tags/emacs-27.2` , but it gives following error: `configure: WARNING: unrecognized options: --with-native-compilation` # Answer You cannot do what you want -- GccEmacs is being developed for Emacs 28. > For installing GccEmacs, I have followed: https://www.emacswiki.org/emacs/GccEmacs which installs: GNU Emacs 28.0.50. As I understand its an experimental / developmental version of Emacs not yet released to the general public. The native compilation feature is in an equally experimental / developmental state, so even if you could make it work with Emacs 27, you would be acting contrary to your stated motivation for avoiding Emacs 28. Lots of people use Emacs 28 with native compilation on a daily basis, so "developmental" doesn't mean "crashing constantly"; but you should still assume you'll encounter some issues when using unstable builds. > 1 votes --- Tags: gccemacs ---
thread-54971
https://emacs.stackexchange.com/questions/54971
Associate (and save) macro with current file (+/- evil spacemacs)
2020-01-17T08:41:32.043
# Question Title: Associate (and save) macro with current file (+/- evil spacemacs) After edit : --- I am using evil-mode. I often record macros very specific to the file I am editing with `qq` or `qw`. Is there a way to autosave those macros and the key associated to them when saving the file ? In order to make those macros working when the file is opened again. # Answer > 3 votes Try this: ``` (defun insert-kbd-macro-in-register (register) "insert macro from register. prompt for register key if no argument passed. you may need to revise inserted s-expression." (interactive "cthe register key:") (let* ((macro (cdr (assoc register register-alist))) (macro-string (with-temp-buffer (setf last-kbd-macro macro) (insert-kbd-macro '##) (buffer-string)))) (insert macro-string))) ``` If you do not care the ugly output, just call `(insert (format "%s" (cdr (assoc register-key register-alist))))`. if you have not record the other macro, you can save the last macro with `M-x insert-kbd-macro RET`. with empty string as macro name, `insert-kbd-macro` will insert the last macro. if you want to advice the evil's `p` command: ``` (defun evil-paste-kbd-macro-advice (&rest argv) "make evil paste kbd-macro if register content is a macro. this function check whether content macro by: 1. equal to `last-kbd-macro' 2. is a vector but not string 3. contain unprintable character" (if (and (>= (length argv) 2) (second argv)) (let* ((register (second argv)) (register-pair (assoc register register-alist)) (content (if register-pair (cdr register-pair)))) (if (and content (or (eq last-kbd-macro content) (vectorp content) (string-match "[^\t[:print:]\n\r]" content))) (let ((last-kbd-macro content)) (forward-line) (beginning-of-line) (insert-kbd-macro '##) (forward-line -2) (search-forward "setq last-kbd-macro") (replace-match "execute-kbd-macro") t))))) (advice-add 'evil-paste-after :before-until 'evil-paste-kbd-macro-advice) ``` In vim, macro in register is just plain text, so you can paste it `"wp`. In emacs, macro is a vector of key. however, if there are return or backspace in macro, they are stored as symbol. A vector of characters is string, but a vector contain symbols is not string, so it can not be *paste* with evil's paste command. The advice above will detect whether the register's content is string. If it is not, the advice will insert it as macro, or it will do nothing, and evil will paste it as ordinary string. --- Tags: keyboard-macros ---
thread-68342
https://emacs.stackexchange.com/questions/68342
Ignore timestamps in org-agenda my manually adding a tag to the timestamp?
2021-09-01T07:44:06.930
# Question Title: Ignore timestamps in org-agenda my manually adding a tag to the timestamp? Is there a way to ignore specific timestamps in org-agenda view? In my specific case, say I have two files `file1.org` and `file2.org` which both are org agenda files, but contain the same timestamp. Lets say for example, both contain a timestamp for the beginning of the summer holidays. So is there a way to add manually something like a tag to the timestamp in `file2.org` such that this timestamp is ignored in the org-agenda view? # Answer Instead of tagging, you could turn one of them into an inactive timestamp, which prevents from showing up in the agenda. With point on the timestamp: ``` C-c ! ``` You can also toggle with point on the delimiter of the timestamp ( `< or [` ) and press `<S-up>` or `<S-down>` > 1 votes --- Tags: org-mode ---
thread-30807
https://emacs.stackexchange.com/questions/30807
Cperl-mode syntax highlighting breaks when inserting a newline into a here doc
2017-02-17T20:33:18.627
# Question Title: Cperl-mode syntax highlighting breaks when inserting a newline into a here doc in `cperl-mode`, here docs are colored with a `font-lock-string-face`. However if you used any function that inserts a newline on a blank line (e.g. `M-: (insert "\n")`) it will cause all code after the newline to be highlighted with `font-lock-comment-face`. The only way to fix it is try and "mess with" here doc tags so that cperl re-parses and corrects the font-lock. I have a feeling this may have something to do with this issue since it is also dealing with multi-line syntax highlighting. Is there an expert out there who can help me find a way to fix this? ``` #!/usr/bin/env perl my $here_doc = <<'_HERE_'; this is here doc line <--- call (insert "\n") when cursor is here _HERE_ ``` # Answer Eventually this bug has been fixed in the Emacs repository. You can use cperl-mode.el directly from that repository with Emacs 26.1 or newer. The fix does what could have been done in font-lock-extend-region-functions as suggested by wasamasa and now uses the same method as perl-mode.el to mark here-documents. > 1 votes # Answer The package highlight-refontification visualizes how font-lock refontifies a buffer. In this case, it starts at the line where the point is. One way to handle this is to add a function to `font-lock-extend-region-functions` to expand the region to include the full heredoc comment. One thing that is curious is that the highlighting becomes correct when pressing `return` but not when evaluating `(insert "\n")`, something I have no explanation for. > 2 votes --- Tags: major-mode, font-lock, syntax-highlighting, string, perl ---
thread-66214
https://emacs.stackexchange.com/questions/66214
Minimizing imenu for cperl mode
2021-06-08T10:43:53.700
# Question Title: Minimizing imenu for cperl mode Suppose we have a `Spec_pages.pm` file that looks like this: ``` package WWW::Spec_pages; sub new sub get_news sub spec_page sub spec_page_subtype ``` When I run `M-x imenu`, I get this: ``` *Rescan* +Unsorted.List+... +Packages+... +Hierarchy+... WWW::Spec_pages::new WWW::Spec_pages::get_news WWW::Spec_pages::spec_page WWW::Spec_pages::spec_page_subtype ``` Is it possible to remove the unnecessary information and just keep the list of functions: ``` new get_news spec_page spec_page_subtype ``` Maybe, it's also possible to sort them by name? # Answer > 1 votes cperl-mode does not (yet) strip the package name from subroutines. I think this would be a good idea to add to cperl-mode, at least when there's only one package in the file. Do you want to report-emacs-bug? As for sorting: cperl-mode honors the value of imenu-sort-function, which can be customized to sort alphabetically. --- Tags: imenu, perl ---
thread-68238
https://emacs.stackexchange.com/questions/68238
(Spacemacs) pressing SPC to replace a match during query-replace does not work
2021-08-24T16:05:00.390
# Question Title: (Spacemacs) pressing SPC to replace a match during query-replace does not work (Spacemacs) `M-%` starts `query-replace`, and when a match is found, `?` shows help, which indicates: > Type Space or ‘y’ to replace one match, Delete or ‘n’ to skip to next, However, pressing `Space` simply inserts a space rather than replacing text (`y` still works). As a long time emacs user, this is a frustrating loss of functionality. Any suggestions on how it can be reinstituted? # Answer > 2 votes It seems to be a recent Spacemacs change of the Emacs defaults. Either set dotspacemacs-use-SPC-as-y to t in your dotspacemacs/init ``` (defun dotspacemacs/init () (setq-default ... ;; all the other dospacemacs-* variables ;; Accept SPC as y for prompts if non nil. (default nil) dotspacemacs-use-SPC-as-y t)) ``` or do (define-key query-replace-map " " 'act) in your dotspacemacs/user-config to return to the classic behavior. --- Tags: spacemacs, query-replace ---
thread-62261
https://emacs.stackexchange.com/questions/62261
How to remove menu with easymenu?
2020-12-13T20:45:10.457
# Question Title: How to remove menu with easymenu? Easymenu is great for creating menus, but how can you remove a top-level menu that was created with it? Here's an example. A minor mode might create the following menu: ``` (easy-menu-define some-minor-mode-menu some-minor-mode-map "Menu keymap for some minor mode." '("Menu" ["Item" command t] ...)) ``` How would you remove this menu from the menubar using easymenu's own commands? Unfortunately, easymenu is poorly documented and all the available documentation is about how to *add* menus and submenus. (I have been able to remove this sort of menu by adding `(define-key some-minor-mode-map [menu-bar Menu] nil)` to the major mode's hook, but is that the only way to do it? Does easymenu provide no facilities for this?) # Answer > 1 votes I found an easy solution: use the `:visible` or `:active` properties of the fourth parameter of `easy-menu-define`. Say you have defined a menu like this: ``` (easy-menu-define org-glaux-menu global-map "Org-glaux" (list "Org-glaux" ... )) ``` You can disable it with: ``` (easy-menu-define nil global-map nil (list "Org-glaux" :visible nil)) ``` Replacing `:visible` to `:active` also works. It would not be too hard to warp it into a function: ``` (defun my/easy-menu-remove (maps menu-name) "Remove MENU-NAME from the current menu bar." (easy-menu-define nil maps nil (list menu-name :visible nil))) ``` See the documentation of `easy-menu-define`: > The first element of MENU must be a string. It is the menu bar item name. It may be followed by the following keyword argument pairs: > > ... > > :visible INCLUDE > > ``` > INCLUDE is an expression. The menu is visible if the > expression evaluates to a non-nil value. ‘:included’ is an > alias for ‘:visible’. > > ``` > > :active ENABLE > > ``` > ENABLE is an expression. The menu is enabled for selection > if the expression evaluates to a non-nil value. ‘:enable’ is > an alias for ‘:active’. > > ``` A relevant comment from the documentation of `easy-menu-remove`: > (easy-menu-remove MENU) > > This function is obsolete since 28.1; use ‘ignore’ instead. This function does not change global state, including the match data. > > Remove MENU from the current menu bar. Contrary to XEmacs, this is a nop on Emacs since **menus are automatically (de)activated when the corresponding keymap is (de)activated**. --- Tags: menus, easy-menu ---
thread-68352
https://emacs.stackexchange.com/questions/68352
Snippets aren't working emacs-lsp / company-mode
2021-09-01T21:41:03.763
# Question Title: Snippets aren't working emacs-lsp / company-mode For whatever reason, snippets aren't working. I am getting the placeholders but I cannot navigate between them. This is the type of snippet completion that I am getting: ``` for ${1:index}, ${2:value} in ipairs(${3:t}) do $0 end ``` I can see the syntax for using snippets but they aren't working. This is my configuration for lsp and company mode. ``` (use-package lsp-mode :ensure t :hook (go-mode . lsp-deferred) (js-mode . lsp-deferred) (haskell-mode . lsp-deferred) (lua-mode . lsp-deferred) :commands (lsp lsp-deferred) :config (define-key lsp-mode-map (kbd "C-l C-l") lsp-command-map)) #+end_src - also using lsp-ui to give more of an IDE feel to emacs #+begin_src elisp (use-package lsp-ui :ensure t) #+end_src - the documentation of what I am using can be found [[https://emacs-lsp.github.io/lsp-mode/page/main-features/][here]] *** Company-mode - this mode allows for an autocomplete window to popup as you code - i had it enabled in all buffers but was not a huge fan of this so I bound it to the vim COC control space keybinding to initialize it #+begin_src elisp (use-package company :ensure t :bind ("C-SPC" . company-mode)) ;;(add-hook 'after-init-hook 'global-company-mode) not a fan of it in every mode #+end_src - the "recommended settings" #+begin_src elisp (setq company-minimum-prefix-length 1 company-idle-delay 0.0) ;; default is 0.2 (setq company-selection-wrap-around t) #+end_src ``` # Answer I had to configure yasnippet for it to work it is working now. > 0 votes --- Tags: lsp ---
thread-36094
https://emacs.stackexchange.com/questions/36094
Using ggtags tag lookup along with centered-cursor-mode
2017-10-11T23:32:33.830
# Question Title: Using ggtags tag lookup along with centered-cursor-mode I am using centered-cursor-mode to center the cursor at 10 lines above center at all times. I am trying to have ggtags respects this setup after each tag lookup. When I have the cursor at any point on screen doing M-x recenter takes it to 10 lines above center. However, executing recenter inside a lambda doesn't have the same effect instead takes the cursor to the center. This is my setup: ``` (use-package centered-cursor-mode :ensure t :diminish 'centered-cursor-mode :init (defcustom ccm-vpos-init '(round (window-text-height) 2) "This is the screen line position where the cursor initially stays." :group 'centered-cursor :tag "Vertical cursor position" :type '(choice (const :tag "Center" (round (window-text-height) 2)) (const :tag "Golden ratio" (round (* 21 (window-text-height)) 34)) (integer :tag "Lines from top" :value 10) (const :tag "10 Lines above center" (- (round (window-text-height) 2) 10)))) ;; where the center line starts (change with C-M-0/-/+) (setq ccm-vpos-init (quote (- (round (window-text-height) 2) 10))) :config (global-centered-cursor-mode) (setq ccm-recenter-at-end-of-file t ;; recenter at end of file ccm-ignored-commands '() ;; Fixed hangs on big org files ) (define-key ggtags-mode-map (kbd "M-.") (lambda () (interactive) (call-interactively 'ggtags-find-tag-dwim) (recenter))) ) ``` # Answer This worked. ``` (add-hook 'ggtags-find-tag-hook #'ccm-position-cursor) ``` > 3 votes # Answer There is a vanilla way to achieve what centered cursor mode does, somewhat: ``` (setq scroll-preserve-screen-position t scroll-conservatively 0 maximum-scroll-margin 0.5 scroll-margin 99999) ``` Found here. As far as I can see, the window is centered after ggtags look-up. I'm not sure how to modify it to get your offset of 10 rows, but it's a start. The person who wrote the post above seems to be unhappy with the performance of centered cursor mode anyway. For my part, I couldn't make it work on my version of emacs, which is why I found this. > 0 votes --- Tags: scrolling, cursor, gtags ---
thread-68363
https://emacs.stackexchange.com/questions/68363
Changing Terminal Emacs Theme
2021-09-02T19:58:45.587
# Question Title: Changing Terminal Emacs Theme I have to run some C and Fortran programs over SSH, and need to edit the source files on the shell. I think Emacs is the right tool for such a task, and it was preinstalled on the server. Though when I open a Fortran source file (ending with .f08) in emacs, I find the syntax highlighting is just illegible (dark blue and dark purple text over black background). Now I can change the theme by `M-x customize-themes` or `M-x load-theme`, but I have to do it each time I start emacs from the terminal. For instance if I make a small modification to the source, return to shell to compile, and come back to make another small modification (say correct an error) to my source file, I have to change themes twice over. Hence my question is basically: Where do I configure emacs to load a particular theme every time it is opened in the terminal? The server has GNU Emacs 24.3.1, and runs CentOS Linux release 7.1.1503 (Core). # Answer > 1 votes For an emacs running on the remote machine, you can put your config in `~/.emacs.d/init.el` **on the remote machine**, not on your local computer. You may find that Tramp is a better option. With Tramp, you run Emacs on your local machine, and it can open files on the remote computer for editing. This means you have all your local customizations and packages, and you can continue to use GUI emacs even with a text-only connection. In addition, Tramp only sends data over the network when you save the file, so it may be less laggy than running Emacs on the remote machine. --- Tags: themes, terminal-emacs ---
thread-68360
https://emacs.stackexchange.com/questions/68360
Adding a function call after a builtin runs
2021-09-02T13:31:37.297
# Question Title: Adding a function call after a builtin runs I always want to run `reposition-window` after `c-beginning-of-defun`. --- I've tried this: ``` (advice-add 'c-beginning-of-defun :after #'reposition-window) ``` it results in this at execution: ``` Variable binding depth exceeds max-specpdl-size ``` --- I've considered hooks, but I don't know how to find a hook for `c-beginning-of-defun`. I don't think hooks are the way to go if it's not for modes. --- I've tried redefining `c-beginning-of-defun`, but then I need to call to the previous version, and I get infinite recursion. --- I've tried implementing my own function: ``` (defun my-beginning-of-defun () (interactive) (beginning-of-defun) (reposition-window)) (global-set-key (kbd "C-M-a") 'my-beginning-of-defun) ;;; This doesn't bite! ``` but this doesn't work in C, because its major mode overrides `C-M-a` with the C version of the function. I could make my own version of the C function as well, and bind `C-M-a` in my own c-mode-hook, but... It seems like doing work that advises are designed to do. # Answer > 3 votes `reposition-window` calls `beginning-of-defun` to compute the window boundaries. So you get an infinite recursion when calling `reposition-window` from `c-beginning-of-defun`. You can add the following guard for avoiding that recursion: ``` (defvar c-beginning-of-defun-after-hook nil "Functions to be run after `c-beginning-of-defun'.") (advice-add 'c-beginning-of-defun :after (lambda (&rest _args) (run-hooks 'c-beginning-of-defun-after-hook))) (defun resposition-window-for-c-beginning-of-defun (&rest args) "Deactivate `c-beginning-of-defun-after-hook' and call `resposition-window'." (let (c-beginning-of-defun-after-hook) (reposition-window))) (add-hook 'c-beginning-of-defun-after-hook #'resposition-window-for-c-beginning-of-defun) ``` --- Tags: hooks, advice, nadvice ---
thread-21454
https://emacs.stackexchange.com/questions/21454
"sudo emacs" Doesn't Work
2016-04-06T01:05:33.333
# Question Title: "sudo emacs" Doesn't Work I am trying to use `sudo emacs` with no luck so far. When I run with `--debug-init` I get the following. ``` Debugger entered--Lisp error: (file-error "Cannot open load file" "no such file or directory "web-mode") ``` Why would it be different when I am using `sudo emacs`? Regular `emacs` runs fine. # Answer > 11 votes `sudo emacs` runs as the root user. One consequence is Emacs won't look for your .emacs in the home directory of your normal user, it will look in root's home directory instead. So none of your config will be loaded, and you don't have access to any packages installed by your normal user. As mentioned in a comment, you should run Emacs as your normal user, and use tramp to open files as root. If you're trying something more arcane, we'll need more info to help you. # Answer > -1 votes What worked to me after upgrading Ubuntu from 16 to 20: 1. make sure variable `package-user-dir` is pointing to place with elpa packages (smth like `"~/.emacs.d/elpa"` or wherever it is) and make sure is set in user's `~/.emacs` file 2. make symlinks in root home dir > ``` > sudo ln -s ~/.emacs /root > sudo ln -s ~/.emacs.d /root/ > > ``` 3. make sure `~/.emacs.d/` directory and children has "read" rights to non-user (like `chmod 755`) After that running `sudo emacs` seems to read all configs right --- Tags: sudo ---
thread-68370
https://emacs.stackexchange.com/questions/68370
How can I assign labels/milestones when creating an issue/MR in Magit Forge?
2021-09-03T18:23:15.393
# Question Title: How can I assign labels/milestones when creating an issue/MR in Magit Forge? Is there a way to assign labels and/or milestones when creating an issue or merge request in Magit Forge? I currently have to create the topic, and then edit it twice (once for labels, then for milestones). Every one of those steps requires a new fetch. I was hoping for a way to do all that in the same buffer for topic creation (and do a single topic fetch). # Answer > 3 votes No, Forge provides no UI for assigning anything to these fields before sending the issue off to the server. However, some of the supported forges support commands that you can insert into the body of a new issue or merge request. Gitlab calls them “quick actions”; you’ll have to look through your forge’s help to see what they support. On Gitlab, putting “/label ~foo” in the body of a new issue will cause the Gitlab server to add the label called “foo” to the issue. If that’s not available on your forge, you’ll need to view the issue or merge request after creating it, then put the point on the field you would like to edit (“Milestone”, “Labels”, “Marks”, a comment, etc), and type `C-c C-e` to edit it. This is all documented in chapter 4.3.4 Editing Topics and Posts of the Forge manual. The manual is also available inside Emacs using the Info viewer (`C-h i`). Doing this should not require refetching the issue; it certainly doesn’t when I use Forge to create issues on Gitlab. --- Tags: magit, forge ---
thread-68371
https://emacs.stackexchange.com/questions/68371
How can I copy the faces of a window's mode-line to its header-line?
2021-09-03T19:08:48.537
# Question Title: How can I copy the faces of a window's mode-line to its header-line? I want to move my mode-line to the top of each window. So, I've copied its contents into the header-line. ``` (setq-default header-line-format mode-line-format) (setq-default mode-line-format nil) ``` But, I'm using the modus themes, so the selected window's mode-line shows with different faces. How can I copy the faces of a window's mode-line to its header-line? # Answer Customize face `header-line`, to make it inherit from face `mode-line`. **`M-x customize-face header-line`** You can do the same with face `header-line-highlight`, inheriting from face `mode-line-highlight`. Actually, such face inheritance is done by default. But some other face attributes are also set by default. You can undefine (unselect) those. > 0 votes --- Tags: faces, mode-line, header-line ---
thread-68351
https://emacs.stackexchange.com/questions/68351
Pandoc-mode does not find pandoc-main-hydra/body
2021-09-01T21:37:56.760
# Question Title: Pandoc-mode does not find pandoc-main-hydra/body In my org and tex files pandoc-mode shows up as an enabled minor mode. However, when I try to run: "pandoc-main-hydra/body" emacs complains that ‘pandoc-main-hydra/body’ is not a valid command name. (When I run this command using a shortcut, it states: "Wrong type argument: commandp, pandoc-main-hydra/body"). I've been trying to find what is the problem for a while but without any luck. Any help would be appreciated # Answer \[Summarizing the comments as an answer\] Versions of `pandoc-mode` before April 1, 2015 did not include a hydra. The `hydra` branch was merged in version 2.12 of pandoc-mode. So if an earlier version of `pandoc-mode` is installed, then the hydra-related stuff (including `pandoc-main-hydra/body`) would just not be present. That was certainly the case for me (I had a version from 2012 - I neglected to record the version number) and apparently also for the OP. I had a very old pandoc-mode installed that did not use the hydra. Now that I've cleaned up the old version and installed latest from Melpa, I get the hydra and `pandoc-main-hydra/body` is defined for me. To clean up the files, find the location of the `pandoc-mode` files that you are using, by doing `M-x locate-library` RET `pandoc-mode`. Delete them and then install `pandoc-mode` from MELPA (or from the Github site https://github.com/joostkremers/pandoc-mode). BTW, you can't query for the version of `pandoc-mode` from emacs: it is just a string like `Version: 2.31` at the top of the `pandoc-mode.el` file, so you just have to visit the file to get it. > 1 votes --- Tags: pandoc ---
thread-34429
https://emacs.stackexchange.com/questions/34429
Select Within Quotes
2017-07-26T16:45:11.487
# Question Title: Select Within Quotes Supposing I have my cursor resting somewhere in a bunch of text within quotes, is there a key binding that will mark or highlight just the text within the quotes so I can delete it? This would be ideal for web-mode. Perhaps, if there's not already an emacs way of doing this, then maybe there's a way of doing in web-mode. # Answer You can use the expand-region or emacs-surround packages to select the text and then delete it. Watch an intro to expand-region on: Emacs Rocks. Or take a look at the examples of emacs-surround on its README file. > 3 votes # Answer ``` (defun select-text-in-delimiters () "Select text between the nearest left and right delimiters." (interactive) (let (start end) (skip-chars-backward "^<>([{\"'") (setq start (point)) (skip-chars-forward "^<>)]}\"'") (setq end (point)) (set-mark start))) ``` > 0 votes --- Tags: web-mode, mark ---
thread-68378
https://emacs.stackexchange.com/questions/68378
How start Emacs only with specific packages?
2021-09-04T15:02:49.143
# Question Title: How start Emacs only with specific packages? Linux Mint 20, Emacs 27.1 In my init.el file I loaded many packages. But sometime I need to load only some specific packages. E.g. ``` emacs -Q and only vertico+marginalia+theme ``` The question is: How I can start Emacs only with specific packages? P.S. Example of my init.el ``` (require 'package) (add-to-list 'package-archives '("melpa" . "https://melpa.org/packages/") t) (require 'dired-narrow) (dired-recent-mode 1) (add-to-list 'load-path "~/.emacs.d/elpa/dired+") (require 'dired+) (require 'highlight-symbol) ``` # Answer > 1 votes If you use `require` in your init file, then Emacs must load the package. If you don’t use `require`, then Emacs doesn’t need to load anything. The mistake most people make is to `require` every package that they want to use. 99% of the time you can configure any package you want (by setting its variables, for example), without ever `require`ing the package. The package will not actually be loaded until you start calling any of the functions it defines. Emacs has a big list of `autoload`ed functions that tells it what files to load when one of them is called. --- Tags: package, autoload, require ---
thread-68382
https://emacs.stackexchange.com/questions/68382
preview and edit side-by-side, maybe by syncronizing buffers?
2021-09-04T16:53:37.033
# Question Title: preview and edit side-by-side, maybe by syncronizing buffers? Many major modes provide a function to switch between editing and preview rendering a file. I am specifically looking at `ps-mode` but an answer that applies to others would be nice. I can open the same buffer in two windows, but switching between render and edit (`C-c C-c` in `ps-mode`) causes both windows to change. I want to see both the text and the rendering in different windows on the same frame at the same time, preferably with real-time updates. My instinct is to create two buffers backed by the same file, and a hook so that changes to the editing buffer update the text behind the rendering buffer. Maybe even `auto-revert-mode` but I'm hoping for something slightly more elegant. # Answer Partial answer: you can have two buffers with the same content but different buffer-specific settings, such as different cursor positions (that aren't forgotten if the buffer isn't displayed in a window), different major modes, etc. This is called indirect buffers. Press `C-x 4 c` to create an indirect buffer for the current buffer and show it in a window. You can have one of them render the Postscript and the other show the source: `C-c C-c` only applies to the current buffer. There are limitations of indirect buffers. For example, they both use the same font-lock settings. As a consequence, `C-c C-c` in one buffer removes syntax coloring from the other buffer, though you can get it back by turning font-lock mode on and off in the buffer showing the source. To automatically update the preview buffer, you could set up an idle timer or an after change function in the source buffer that re-renders the preview. There is no automatic synchronization between the position in the two buffers. When you're viewing a PDF file rendered from a source (e.g. LaTeX), there are ways to embed backreferences so that when you click in the PDF, the editor jumps to the corresponding place in the source. However, I don't know if that's possible with Postscript, and even if it is, it would require the Postscript source to contain those backreferences, which is probably not feasible if you're editing the Postscript manually. > 2 votes --- Tags: buffers, gui-emacs, previewing ---
thread-34840
https://emacs.stackexchange.com/questions/34840
How to define yasnippet templates using elisp instead of the file system?
2017-08-12T07:05:32.607
# Question Title: How to define yasnippet templates using elisp instead of the file system? I would like to use YASnippet template system to expand abbreviations. (I don't want to use abbrev-mode which use space or symbols for expansion.) It is not convenient to create a new file for each of my abbreviation. Could I define yasnippet templates using elisp (in init.el) instead of using the YASnippet files structure? # Answer > 2 votes Source: https://web.archive.org/web/20080319085637/http://code.google.com/p/yasnippet/wiki/HowtoDefineSnippet You can use yas-define-snippets to define a bunch of snippet for a mode at a time. The basic syntax is: ``` (yas-define-snippets MODE SNIPPETS) ``` Here's an example: ``` (yas-define-snippets 'text-mode '(("email" "`user-mail-address`" "User's email address") ("time" "`(current-time-string)`" "Current Time") ("foo" "blablablabla"))) ``` # Answer > 1 votes ``` (use-package yasnippet-snippets :defer 2 :hook (prog-mode . yas-minor-mode) :config (yas-define-snippets 'js-mode '(("clg" "console.log('$1: %s (%s)',$2);" "pX console.log()") ("cle" "console.error('$1: %s (%s)',$2);" "pX console.error()") ("Js" "JSON.stringify($1)" "pX JSON Stringification") ("i" "if ($1) {\n$2\n\t} else {\n$3\n\t}\n" "Standard if") ("time" "`(current-time-string)`" "Current Time") ("if" "if ($1) {\n\t$2\n}" "pX if"))) (yas-define-snippets 'sh-mode '(("if" "if [ $1 ] ; then\n\t$2\nelse\n\t$3\nfi " "pX if")))) ``` Optional: ``` (use-package company :defer 2 :after prog-mode :hook (prog-mode . company-mode) :bind (:map company-active-map ([(tab)] . company-auto-complete)) :custom (company-dabbrev-ignore-case t) (company-etags-ignore-case t) (company-selection-wrap-around t) (company-minimum-prefix-length 1) (company-idle-delay 0.0) :config (eval-after-load 'company '(add-to-list 'company-backends '(company-yasnippet company-dabbrev-code company-capf)))) ``` --- Tags: yasnippet ---
thread-68340
https://emacs.stackexchange.com/questions/68340
Is it possible Emacs automate to do many steps after restart Emacs?
2021-09-01T06:50:48.787
# Question Title: Is it possible Emacs automate to do many steps after restart Emacs? Given: ``` Linux Mint 20.2 Emacs 27.1 3 monitors ``` After restart Emacs I every time do the next steps: ``` 1. make-fram-on-monitor (in full screen mode) -> DP1 2. make-fram-on-monitor (in full screen mode) -> DP2 3. make-fram-on-monitor (in full screen mode) -> DP2 4.Switch to monitor DP1 and do the next steps: 4.1. tab-new 4.2. Open dired-mode. 4.3. Go to folder /home/myuser/dev/myProject 4.4. M-x vterm 4.5. M-x rename-buffer -> my_buffer_name 4.6. tab-new 4.7. M-x shell 5. Switch to monitor DP2 and switch to buffer *scratch* 6.Switch to monitor DP3 and do the next steps: 6.1. tab-new 6.2. Open dired-mode. 6.3. M-x find-file "to.do.org" 6.4. tab-new 6.5. M-x find-file "my.work.org" ``` To do this every time after restart Emacs **is not very convenient**. It's routine work. So the quesion is: Is it possible Emacs automate to do all this steps after restart Emacs? Or I need to write little script (e.g. myBoot.el) and Emacs will start it every time after restart? # Answer Something like this for DP1. You can `M-x my/init` after your Emacs starts. If you really want to do this automatically, put it in your `init.el`. You can write your own function for DP2 and put it in `my/init`. There are plenty of good tutorials on the net. If you get any specific question, ask it here on Emacs Slack Exchange. ``` (setq my/init-shell-vterm-name "my_buffer_name") (setq my/init-shell-dirs '("~/src/emacs" "~/src/linux")) (defun my/init-shells (dirs) (progn (tab-bar-new-tab) (shell (expand-file-name (car dirs))) (tab-bar-new-tab) (let* ((default-directory (expand-file-name (cadr dirs))) (vterm-buffer-name my/init-shell-vterm-name) (buf (vterm))) (switch-to-buffer buf)))) (defun my/init () (interactive) (my/init-shells my/init-shell-dirs)) ``` You can create a frame with `make-frame` but I don't think there is a way to know which frame is on which display. If someone know how to do it, please let me know. > 1 votes # Answer Emacs has a built-in feature for this, called deskto-save-mode. It saves your buffer list and even the frame positions on your screens in a file so that when you close emacs and reopen it next time, everything is exactly as you left it. It even remembers which frames were on which screen. Also check out the following link for more information: How to restore Emacs' windows and buffers from the last session? where another package is introduced as well. Try it out and you will not want to miss it anymore > 0 votes --- Tags: init-file ---
thread-68381
https://emacs.stackexchange.com/questions/68381
Cannot get a symbol's value for the first time when using `setq-default`
2021-09-04T16:02:59.110
# Question Title: Cannot get a symbol's value for the first time when using `setq-default` I can use `setq-default` to set a symbol's default value, as follows: ``` (with-temp-buffer (make-local-variable 'bar) (setq-default bar "xyz") (symbol-value 'bar)) ``` When I first executed the above code, I got an error: ``` Symbol’s value as variable is void: bar ``` But when I tried executing it again, I got the expected return value: "xyz". Why did I got an error the first time but succeeded the second time? # Answer > 2 votes Put the `make-local-variable` after the `setq-default`: ``` (with-temp-buffer (setq-default bar "xyz") (make-local-variable 'bar) (symbol-value 'bar)) ``` `setq-default` sets the global value. Doing what you did says there is a local value for `bar`, but it doesn't set that local value. And neither does `setq-default` set that local value. Doing it with what I wrote first sets the global value, then says that there's a local value. And the local value is just the same as the global value. As the doc string of `make-local-variable` tells you, you can also use `(set (make-local-variable 'bar "abc"))`. (But that doesn't set the global value.) --- Tags: variables, buffer-local, setq, setq-default ---
thread-40834
https://emacs.stackexchange.com/questions/40834
Open the same file in two frames
2018-04-04T08:54:50.960
# Question Title: Open the same file in two frames With long files, I like to have two buffers that display the same file but at different positions. However, since I have two physical displays, I'd like to have two Emacs buffer, each on its own monitor, and then I could open 3, or even 4 copies of the same file! In theory... In practice, when I try `C-x 5 b` or `C-x 5 f`, instead of opening the file / creating a new buffer with the same content in another frame, the focus goes back into original frame, original buffer... Any thoughts? --- OK, I now realized that I can create a new frame, which will then automatically show the currently selected buffer: `M-x``new-frame`. But what about existing frames? # Answer > 6 votes Three different things come to mind, depending on just what you want. Perhaps one or more of them will help. 1. `C-x 5 2` (new frame for the current buffer). 2. `C-x 3` (or `C-x 2`), followed by `M-x follow-mode <RET>`. But that shows the buffer in separate windows, not separate frames. 3. Indirect buffers. Each such buffer can be dedicated to a different part of the same buffer (and those parts can overlap). See Narrow Indirect (library `narrow-indirect.el`). # Answer > 3 votes You can you `C-x <LEFT>` and `C-x <RIGHT>` to cycle among all open buffers in the current window. It's not perfect, but it's the only way I've found to change the buffer in an existing frame to one that's open in another frame. # Answer > 1 votes Have you tried `C-x 5 2`? It is `make-frame-command` that should do what you want as far as I understand. For my needs I have created similar function to make new frame with current buffer having the same frame-width and frame-height: ``` (defun haba/make-new-frame () (interactive) (make-frame `((width . ,(frame-width)) (height . ,(frame-height))))) ``` PS Or maybe you want smth else? Maybe you want to duplicate current frame with all windows opened there? I have read your question 4 times... :) PS2 What I think happens 1. You open a new frame with `C-x 5 b` 2. Then you want to open another buffer in that frame and again use `C-x 5 b` By default `C-x 5 b` will search for a buffer in list of displayed buffers in all frames and will switch to it in another existing frame instead of creating a new one. Just use regular `C-x b` in a new frame: 1. `C-x 5 2` to open current buffer in a new frame 2. `C-x b` to open any buffer in selected frame (in your case you are in a new frame) # Answer > 1 votes Here is an example using the `display-buffer` family of functions, based upon a more complicated example: https://stackoverflow.com/questions/18346785/how-to-intercept-a-file-before-it-opens-and-decide-which-frame . As stated in that related thread, there are several different ways to do this, including, but not limited to let-binding the `display-buffer-alist`. In this example, we just use the function `my-frame-fn` in the second argument to `display-buffer`. We can of course get fancy by examining all of the frame names and add a consecutive numeric digit to the frame name; or, not change the frame name at all; or ... the sky is the limit. We can also add additional frame parameters to place the top / left coordinates wherever we want. We can also adjust the frame size upon frame creation including pixelwise (https://emacs.stackexchange.com/a/17354/2287), or after the fact (https://www.gnu.org/software/emacs/manual/html\_node/elisp/Size-and-Position.html). And, we could always programmatically set/select the original frame/buffer instead of the new one if we wanted to .... I do not like to use `select-frame-set-input-focus` in my setup because it will cause frames on OSX to acquire focus and steal away focus from another program that I might be using; e.g., in the case of a long running Emacs function. So, instead I use the combination of `select-frame` and `raise-frame`. Please feel free to substitute `select-frame` for `select-frame-set-input-focus` and remove `raise-frame` if that is needed for your OS or you simply prefer it like that. USAGE (1 of 2): `(display-buffer (current-buffer) '(my-frame-fn))` USAGE (2 of 2): `(display-buffer (find-file-noselect FILENAME) '(my-frame-fn))` ``` (defun my-frame-fn (buffer alist) "Display the incoming BUFFER in a frame that does not already display it. Use up the existing frames first, before deciding to create a new frame." (let (target-frame) (catch 'break (dolist (the-frame (frame-list)) (when (not (get-buffer-window buffer the-frame)) (throw 'break (progn (setq target-frame the-frame) (modify-frame-parameters the-frame (list (cons 'name "OLD")))))))) (when (null target-frame) (setq target-frame (make-frame (list (cons 'name "NEW"))))) (select-frame target-frame 'norecord) (set-window-buffer (get-largest-window) buffer) (select-window (get-buffer-window buffer)) (raise-frame target-frame))) ``` # Answer > 1 votes **Try this:** Pressing `C-x 4 c` (edit: thanks to @krupan, C-x 4 c stands for M-x clone-indirect-buffer) in a buffer e.g. myFile.txt creates a new indirect buffer and opens it in a window with the same contents and appends \<2\> to the filename as new buffer name, e.g. myFile.txt\<2\> Go to the window with e.g. myFile.txt\<2\> and create a new frame with `C-x 5 2`. The indirect buffer should be displayed in the new frame. Now you can go back to the first frame and close the window and you have the desired result. You can edit and navigate the new indirect buffer as if it is another file, all changes are saved to the original file. You can even rename the indirect buffer for easier navigation between buffers: `M-x rename-buffer` or simply create the new indirect buffer with `C-u C-x 4 c` and specify a name. # Answer > 0 votes It looks like you can M-x clone-indirect-buffer and then open the clone in the other frame. I haven't played with this a lot yet, but so far so good. --- Tags: buffers, frames ---
thread-68389
https://emacs.stackexchange.com/questions/68389
How do I drop to Emacs mode for one command in Evil mode?
2021-09-05T03:38:51.363
# Question Title: How do I drop to Emacs mode for one command in Evil mode? In vim, I can do `C-O` in insert mode and drop to normal mode for one command. Is there a way I can do this in evil, except dropping to Emacs mode for one command? e.g. `C-Q C-x C-f` where `C-Q` is in vim mode and `C-x C-f` is in emacs mode. # Answer In normal and visual state, `\` is bound to `evil-execute-in-emacs-state`, which does exactly what you're looking for. For instance, `\ C-t` in normal state will run `transpose-chars` and remain in normal state afterwards. > 2 votes --- Tags: evil ---
thread-68328
https://emacs.stackexchange.com/questions/68328
general.el error Key sequence starts with non-prefix key
2021-08-31T09:50:18.207
# Question Title: general.el error Key sequence starts with non-prefix key I am having a problem with `general.el` package. I have `SPC` set as a prefix and then other keys as sub-prefix, then some other keys as actions, like how `Doom Emacs` has. ``` (nvmap :states '(normal visual) :keymaps 'override :prefix "SPC" "SPC" '(find-file :which-key "Find file") . . . "m" '(:ignore t :which-key "Org") ``` All this works.. But when I add this line, ``` "m i" '(:ignore t :which-key "Insert") "m i i" '(org-insert-item :which-key "Org toggle item")) ``` It gives error saying, > "Key sequence SPC m i i starts with non-prefix key SPC m i" I basically want `SPC m` to be a preifx for `Org` related actions, then `i` for `Org` insert related actions. # Answer > 1 votes Run `(general-auto-unbind-keys)`. From the readme (https://github.com/noctuid/general.el#automatic-key-unbinding): > ## Automatic Key Unbinding > > To automatically prevent `Key sequence starts with a non-prefix key` errors without the need to explicitly unbind non-prefix keys, you can add `(general-auto-unbind-keys)` to your configuration file. This will advise `define-key` to unbind any bound subsequence of the `KEY`. Currently, this will only have an effect for `general.el` key definers. The advice can later be removed with `(general-auto-unbind-keys t)`. --- Tags: key-bindings, prefix-keys ---
thread-68396
https://emacs.stackexchange.com/questions/68396
How to pass a string argument to a function from global-set-key definition inside .emacs
2021-09-05T11:33:58.897
# Question Title: How to pass a string argument to a function from global-set-key definition inside .emacs Inside my `.emacs` file I have these two functions: ``` (defun bh/switch-to-vs () (interactive) (universal-argument) (shell "*vs*")) (defun bh/switch-to-android () (interactive) (universal-argument) (shell "*android*")) ``` I bind keys to those two methods like this: ``` (global-set-key [f1] 'bh/switch-to-vs) (global-set-key [f2] 'bh/switch-to-android) ``` All working fine, but I prefer defining a function which takes the name of the shell as an argument. I need something like this: ``` (defun bh/switch-to (shell_name) (interactive) (universal-argument) (shell shell_name)) ``` However, I have trouble calling this method from inside `(global-set-key [f1] 'bh/switch-to vs)` // not sure how to call it, getting various errors. How to make this work? # Answer ``` (defun example-one (&optional shell-name) "Example where `current-prefix-arg' is hard-coded to be non-nil." (interactive) (let ((current-prefix-arg t) (shell-name (or shell-name (read-string "Shell Name: ")))) (shell shell-name))) (defun example-two (&optional shell-name) "Example where the user has the option of using a universal argument: C-u" (interactive) (let ((shell-name (or shell-name (read-string "Shell Name: ")))) (shell shell-name))) (global-set-key [f1] 'example-one) (global-set-key [f2] 'example-two) ``` > 1 votes --- Tags: shell, interactive, defun ---
thread-68398
https://emacs.stackexchange.com/questions/68398
Regexp replacement features
2021-09-05T19:23:15.370
# Question Title: Regexp replacement features In the replacement part of `:s` in `evil` I can add commands like `\l` to lowercase the next char and `\L` to lowercase everything that follows, but I am unable to find documentation for that anywhere. I would have expected it to be documented at https://www.gnu.org/software/emacs/manual/html\_node/elisp/Syntax-of-Regexps.html but that only talks about matching, not replacing. What I found however, is that its support seems to match this list: https://www.boost.org/doc/libs/1\_44\_0/libs/regex/doc/html/boost\_regex/format/perl\_format.html Is there documentation on this? # Answer > 1 votes When searching for replacement features of `evil`, I often start with a search related to `Vim`. For example, the `\l` and `\L` `evil` syntaxes definitely have something to do with the `Vim` ones (see Changing case with regular expressions) as `evil` tries to emulate the main features of `Vim`. --- Tags: evil, regular-expressions, replace ---
thread-68395
https://emacs.stackexchange.com/questions/68395
always show archived tasks in org-agenda
2021-09-05T10:54:20.630
# Question Title: always show archived tasks in org-agenda Good day! I have this line of code in my .emacs: ``` (require 'org-agenda) (setq org-agenda-archives-mode t) ``` Basically I want agenda items to be extracted from archive file. As soon as I start emacs and invoke agenda, I can see the files from my archive files. **Problem:** However, if I close the agenda window and open it again using the same command, I can see agenda entries, but without the ones from the archive. If I restart emacs, I can see the archived task once again, only for the first time and then they dont show up again. As I understand I need to invoke that command every time I want it to be activated. But is there a way to activate in a way so it works all the time, I invoke it or not? Thanks! # Answer The variable `org-agenda-archives-mode` is not meant to be a customizable option: it is meant to be set from the agenda dispatcher for the duration of that agenda. So Org mode feels free to reset the value at will, as @lawlist mentions in a comment. Assuming that you have followed the suggestion in the manual to bind the Org agenda dispatcher to `C-c a` in the global keymap, then the way it is meant to be used is with `C-c a a` to bring up the weekly/monthly/whatever agenda and then `v A` to enable `org-agenda-archives-mode`. I don't think there is an option to set it once and forget it. > 0 votes --- Tags: init-file, org-agenda, archive-mode ---
thread-68390
https://emacs.stackexchange.com/questions/68390
Emacs Org mode export to PDF headines become bold
2021-09-05T05:01:38.633
# Question Title: Emacs Org mode export to PDF headines become bold Good day! New emacs user here. I am writing a contract in org mode and exporting it to PDF *(assume that currently **no** latex plugins or settings are applied(in my org file heading) to the document as they do not affect the output of the PDF)*. Most of the things are going good, however, I am having a little issue with org headings. ``` * Heading 1 ** Heading 2 *** Heading 3 *** Heading 3 *** Heading 3 *** Heading 3 *** Heading 3 *** Heading 3 ** Heading 2 ** Heading 2 ``` As you might guess, the heading 1 gets bold. The heading 2 gets bold as well. But what makes me struggle is the third heading, I don't want it to be bold, because this heading doesn't act as a heading in my file, it is where the text goes. Org-pdf export output looks like this: So far, the workaround was to make the Heading 3 into a bullet list. It is not made bold, but also I don't get the numbering, which doesn't look professional. I can live without numbers, but still would be curious to know if I can get normal (i.e. not bold) headings. Thanks! *Btw, the text in the document is Lithuanian :)* **EDIT** **Attempt 1** According to the comment, trying to use plain lists. Doesn't do the job. **Attempt 2** Trying to use this This method, however, as it says in the manual, after using in my case: ``` #+OPTIONS: H:2 ``` The \*** headings become ordinary list items and start from 1 instead of 1.1.1. as so: **Attempt 3** Thanks to NickD, the problem was solved. I really recommend looking into that answer just for the sake of learning something new about what org-mode and latex is capable of, even if you don't have my particular problem. I can now fix my whole document and happily present it to the client :) I am glad I persisted with Emacs and didn't just switch to Word as soon as things got tough. I like emacs. I like this community. Be happy y'all! # Answer I don't know what you mean by "assume that current\[l\]y no latex plugins or settings are applied to the document as they do not affect the output of the PDF" but taking it literally, it is not true: Org mode converts the Org mode file to a TeX file first and then processes the TeX file through some processor (e.g. `pdflatex`) to produce the PDF file. So even if there are no settings in the Org mode file that modify the TeX output, the default LaTeX exporter applies plenty of settings that do affect the PDF output: check the TeX file that is produced and you will see what I mean. That said, Org mode with the default `H:3` setting and the default `article` class turns top level headings into sections, 2nd-level headings into subsections and 3rd-level headings into subsubsections. By default, LaTeX formats section headings in bold, so you get what you have described. You can affect the output by e.g. changing the default class to one of the other standard LaTeX classes (e.g. `book` or `report`) by adding an options setting to your Org mode file: ``` #+LATEX_CLASS: report ``` or (as you have found out already) by changing the level at which the sectioning stops: ``` #+OPTIONS: H:2 ``` making 3rd-level headings not into subsubsections but plain lists. All these ways are limited: there is a conventional way that Org mode exports to LaTeX and if you are happy with that (or with the simple extensions above), then you don't have to know any LaTeX. But if you want to change the format in ways that the various options cannot accommodate, you can still do so but you have to know some LaTeX. In this particular case, you can tell LaTeX to just not use a **bold font** for `\subsubsection` headings, by redefining the `\subsubsection` command. First, you have to find where the command is defined for the class in question. For the default `article` class, use the following command to find the class file: ``` $ kpsewhich article.cls /usr/share/texlive/texmf-dist/tex/latex/base/article.cls ``` Then visit the file that `kpsewhich` told you and find the definition of the `\subsubsection` macro: ``` \newcommand\subsubsection{\@startsection{subsubsection}{3}{\z@}% {-3.25ex\@plus -1ex \@minus -.2ex}% {1.5ex \@plus .2ex}% {\normalfont\normalsize\bfseries}} ``` The final macro, `\bfseries`, selects the **bold font**, so all you have to do is redefine `\subsubsection` without it. The best way to redefine LaTeX commands is to create your own style file. So create a file called (say) `mysubsubsection.sty` in the same directory as your Org mode file and add the following contents: ``` \renewcommand\subsubsection{\@startsection{subsubsection}{3}{\z@}% {-3.25ex\@plus -1ex \@minus -.2ex}% {1.5ex \@plus .2ex}% {\normalfont\normalsize}} ``` All I did was to get rid of the `\bferies` macro call and to change `\newcommand` to `\renewcommand` since I am redefining an existing macro. That's it for the LaTeX part. Now you have to make sure that the style file is used when processing your Org mode document. You do that by adding the following at the top of your file: ``` #+LATEX_HEADER: \usepackage{mysubsubsection} ... ``` Now when you export your Org mode file to PDF, it is going to be converted to a LaTeX file first (be sure to examine the `.tex` file produced and see that the only difference is that there is an extra `\usepackage` line near the top). Now when LaTeX processes the `.tex` file to a `.pdf` file, it will use the new definition of `\subsubsection` and produce normal (i.e. not bold) headings for them. This is a powerful way to change the appearance of your PDF document (it is not going to do anything if you export to HTML, or ODF or anything else), but you have to know a bit about LaTeX in order to use it effectively. But IMO, you *have* to know a bit about LaTeX in order to be able to write your documents in Org mode effectively without much LaTeX fiddling: that sounds contradictory but I am convinced it is true. I hope that the answer is useful, despite the fact that it is mostly about LaTeX, not about Org mode: but it's the connection to the latter that I am interested in, so I hope it's not off-topic for Emacs SE. > 3 votes --- Tags: org-mode, org-export, latex, pdf ---
thread-68282
https://emacs.stackexchange.com/questions/68282
Using yaml src block in following python src block
2021-08-27T14:16:02.767
# Question Title: Using yaml src block in following python src block I am trying to use multiple src blocks to explain a yaml config file usage in python. Below is my org file, ``` #+name: config.yaml #+begin_src yaml name: john why: check # below is a dict example # see it allows comments too full_name: first_name: john last_name: smith #+end_src Now, let us load this into a python script #+begin_src python :var input=config.yaml import yaml with open(input, 'r') as f: cfg = yaml.load(f, Loader=yaml.FullLoader) print(cfg) #+end_src #+RESULTS: ``` But when I do `C-c C-c`, I see `No org-babel-execute function for yaml!`. Can anyone help me identify the error and how to fix it? Environment: macOs, doom emacs # Answer > 1 votes Not an exact solution, but I was able to get around with shell src block printing the yaml text which then was consumed by the python src block as a variable. Here are the contents of my org file now. ``` #+name: config.yaml #+begin_src sh :exports results :results output echo """ name: john why: check # below is a dict example # see it allows comments too full_name: first_name: john last_name: smith """ #+end_src Now, let us load this into a python script #+begin_src python :var zzz=config.yaml :results output import yaml x = yaml.load(zzz) print(x) #+end_src #+RESULTS: : {'name': 'john', 'why': 'check', 'full_name': {'first_name': 'john', 'last_name': 'smith'}} ``` # Answer > 0 votes It looks like yaml as a language is not supported in source code blocks. At least it is not listed in the Languages Section of the org-manual. The error message usually means that the language is not loaded by org-babel and you have to load it in your emacs config file (.emacs or init.el) like so: ``` '(org-babel-load-languages '((python . t) (emacs-lisp . t))) ``` Adding an option `(yaml . t)` did not work for me. I might be wrong here, so correct me if I'm wrong. I'm curious though, did execution of a yaml source code block ever work for you or is it simply not working in the context above? --- Tags: org-mode, org-babel, doom ---
thread-68403
https://emacs.stackexchange.com/questions/68403
How to use calendar-compare-date?
2021-09-06T01:38:48.843
# Question Title: How to use calendar-compare-date? I want to compare today's date with a saved date to see if the saved date is today's or before it. `calendar-date-compare` seems to be the function I need. The documentation `C-h f calendar-date-compare` reads, ``` calendar-date-compare is a compiled Lisp function. (calendar-date-compare DATE1 DATE2) Return t if DATE1 is before DATE2, nil otherwise. The actual dates are in the car of DATE1 and DATE2. ``` But what are the types of of `DATE1` & `DATE2`? I don't understand what to pass here! `calendar-current-date` returns a list that looks like this `(9 5 2021)` but that is not what `calendar-date-compare` expects as arguments. Could someone help? # Answer > 1 votes The last sentence in the doc string is the hint you need: `The actual dates are in the car of DATE1 and DATE2`. IOW, `DATE1` and `DATE2` are lists: each list's `car` (i.e. its first element) is the actual date; the rest of the elements in the list does not matter in the comparison, but presumably the `calendar` package defines the function this way for its own nefarious purposes. So here is an example of its use: ``` (setq date1 '((9 5 2021) foo)) (setq date2 '((9 6 2021) bar)) (calendar-date-compare date1 date2) ===> t ``` where `foo` and `bar` are other elements of the lists that don't matter for the date comparison. For your purposes, you can just leave them out. What you cannot leave out is the extra set of parens: that's what makes each value a list whose `car` is the date (which is a list of three numbers: the month, the day and the year). --- Tags: calendar ---
thread-68410
https://emacs.stackexchange.com/questions/68410
Emacs magit does not seem to push (No changes on github web. Tried both https and ssh)
2021-09-06T17:28:13.303
# Question Title: Emacs magit does not seem to push (No changes on github web. Tried both https and ssh) In a local repo, I staged all my changes and added a commit message. Then, I pushed my commits using `magit-push` and pushed to my branch upstream `origin/master`. Right after I do that, the mini-buffer said something like `Git<1> finished`. I have tried to setup the repo to use both https and ssh. When I use ssh, magit would ask for the passphrase like the example below. When I use https, it did not ask. Either way, both does not seem to push to github. In the `magit-process` buffer, the log looks like this: ``` Pushing to github.com:username/reponame.git Enter passphrase for key '......bla blah To github.com:username/reponame.git =[up to date] master -> master updating local tracking ref 'refs/remotes/origin/master' Everything up-to-date ``` I then checked my github via web, and the changes are not pushed. After 5-10 minutes, the changes are still not pushed. Back to emacs, the `magit-process` buffer still said the same thing "Everything up to date". There are no messages/warnings in the `message` buffer. If I try to forcefully quit emacs, I would get an error that an active process is running. There is another buffer that pops up and shows the process * name: git * PID number * status: run * buffer (magit-process) * command it runs is: `git --no-pager --literal-pathspecs -c core.preloadIndex=true -c log.showSignature=false -c color.ui=false -c color.diff=false commit --` I have to forcefully quit emacs with `xkill` on Linux to close it. Otherwise, emacs would just stay there and try to run the above command (`git --no-pager blah blah`). Note that if I try this on a Terminal, with your typical: * `git add .` * `git commit -m "Some messages"` * git push Then it works for both ssh and https and I can see the updated changes on my github web. Any help is greatly appreciated. # Answer > 1 votes Are you sure you finished the commit correctly? That command that is still running is `git commit` with some extra options, and the log indicates that `git push` didn’t have to update anything; the remote already had all the commits. How did you start the commit, and how did you finalize it? Edit: From the comments, I see that you saved the commit message, but you didn’t actually commit. Saving with `C-c C-s` does indeed save the message to disk, but only `C-c C-c` actually tells git to create the commit. --- Tags: magit, github ---
thread-68391
https://emacs.stackexchange.com/questions/68391
How to search for words separated by arbitrary whitespace?
2021-09-05T09:17:16.993
# Question Title: How to search for words separated by arbitrary whitespace? The question is general, but here's a specific case: In LaTeX source files, it doesn't matter if two words are separated by one space character, multiple space characters, or even a linebreak - in the compiled document, the two words are just separated by one space. Many people will insert linebreaks to do manual line wrapping when writing LaTeX. If I want to search a phrase containing multiple words inside the LaTeX source file, is Emacs able to disregard the white space ambiguities described above when searching? # Answer Following the link of @Basil, here's the needed ELisp code. ``` (setq search-whitespace-regexp "[[:space:]\n]+")) ``` To enable this whenever I edit LaTeX documents, I added the following code to my init file. ``` (defun my-latex-search-setting () (setq search-whitespace-regexp "[[:space:]\n]+")) (add-hook 'latex-mode-hook #'my-latex-search-setting) ``` Now if I press Ctrl-s to search for `hello world`, Emacs will match e.g. ``` hello world ``` as well as ``` hello world ``` > 2 votes --- Tags: latex, search, whitespace ---
thread-36563
https://emacs.stackexchange.com/questions/36563
Ask for saving contents if scratch buffer is modified before exit
2017-11-02T11:37:54.943
# Question Title: Ask for saving contents if scratch buffer is modified before exit I had made some random notes in my scratch buffer. By mistake, I pressed `C-x C-c` and killed the Emacs session. All my content in the scratch buffer was gone. **Question:** When I try to close Emacs when the scratch buffer had been edited, I want Emacs to ask for a confirmation (offer to save or something) before it exits the current session. How can this be done? I'm not conversant with eLisp. I searched the manual and there seems to be no way to change this behaviour. **Not duplicate:** My question is not duplicate to the question "never close scratch" in that, the other user is referring to killing the scratch buffer intentionally using kill-buffer `C-x C-k`. In my case, I unexpectedly exit out of Emacs either by closing the window or giving `C-x C-c` command. # Answer > 2 votes `persistent-scratch` is another package which saves and restores the contents of the `*scratch*` buffer. The following is a possible setup. ``` (use-package persistent-scratch :ensure t :commands persistent-scratch-setup-default :hook (after-init . persistent-scratch-setup-default)) ``` # Answer > 2 votes This is a commonly asked question. It might be a duplicate here (dunno). There are various tweaks or libraries that some users use to provide what you are asking - you will likely get some answers pointing to them. But my suggestion is to not use `*scratch*` the way you are using it - maybe not use it at all. Instead, use `C-x C-f foo.el` or whatever, which tells Emacs that you might want to save whatever you're doing in that buffer. Emacs will also automatically save your work periodically after you do save it, if you do. And you need not save if you don't ever want to. IOW, you get all of the liberty of buffer `*scratch*` (throw it away when done), but with the advantage that Emacs will do just what you requested: let you know before you exit that you have unsaved changes in that buffer. And you can put the buffer in any mode you like - it need not be `emacs-lisp-mode`. And `emacs-lisp-mode` gives you as much Lisp support as the default mode for `*scratch*` provides (in my opinion). `*scratch*` really is for stuff that you intend to toss. # Answer > 2 votes You could use the (bundled) savehist package to save and restore the scratch contents: ``` (use-package savehist :init (savehist-mode) :config (defun my-savehist-scratch () (with-current-buffer (startup--get-buffer-create-scratch) (setq initial-scratch-message (buffer-string)))) (add-hook 'savehist-save-hook #'my-savehist-scratch) (add-to-list 'savehist-additional-variables 'initial-scratch-message)) ``` then you don't have to worry about it being killed, it'll be saved in ~/.emacs.d/history anyway. EDIT: Thanks Y.E. for mentioning that this package will also give you persistent minibuffer histories (e.g. regex replaces, occur's and so on). I was already using savehist for that, but if you don't want to save minibuffer histories you may want to find a different solution. # Answer > 0 votes After trying *many* different approaches I tend to agree that the accepted answer to the mentioned never close scratch is a way to go and may be adapted to the topic of this question too. So, in my configuration I *currently* use this approach to ask for confirmation before killing Emacs or \*scratch\* buffer, if the latter is not empty: ``` ;; Prompts on non-empty *scratch* buffer. (defun yet-prompt-on-not-empty-scratch-buffer (question) "Prompt if *scratch* buffer is not empty. Appends a confirmation QUESTION to the prompt message. If *scratch* buffer is empty, returns true without prompting." (let ((scratch (get-buffer "*scratch*"))) (if (and scratch (> (buffer-size scratch) 0)) (y-or-n-p (format (concat "Warning: *scratch* buffer is not empty. " question))) t))) ;; Call prompting function on Emacs kill. (defun yet-verify-emtpy-scratch-on-emacs-kill () "Require confirmation to kill Emacs if *scratch* buffer is not empty." (yet-prompt-on-not-empty-scratch-buffer "Really kill Emacs?")) (add-to-list 'kill-emacs-query-functions #'yet-verify-emtpy-scratch-on-emacs-kill) ;; Call prompting function on a buffer kill. (defun yet-verify-emtpy-scratch-on-buffer-kill () "Require confirmation to kill *scratch* buffer if it is not empty." (if (equal "*scratch*" (buffer-name)) (yet-prompt-on-not-empty-scratch-buffer "Really kill *scratch* buffer?") t)) (add-to-list 'kill-buffer-query-functions #'yet-verify-emtpy-scratch-on-buffer-kill) ``` --- Tags: saving, exit, scratch ---
thread-68409
https://emacs.stackexchange.com/questions/68409
Key chord for org refresh buffer?
2021-09-06T15:41:52.417
# Question Title: Key chord for org refresh buffer? Due to my Ubuntu 21.04 Wayland being flaky (I suspect), I can't always get the org menu to drop down properly, and I like to do a "Refresh setup current buffer" often. How could I do this with a key chord? Help/Apropos doesn't reveal any likely candidates. # Answer > 1 votes You could restart org-mode with `M-x org-mode-restart` and bind it to a key. --- Tags: org-mode, buffers ---
thread-68424
https://emacs.stackexchange.com/questions/68424
Define new key binding for new minor mode
2021-09-07T20:34:25.140
# Question Title: Define new key binding for new minor mode I am writing my first minor mode, and would like to understand how to bind a key to an action in that mode. ``` (define-minor-mode hello-mode "My Mode" :init-value nil :lighter " Hello" :keymap (let ((map (make-sparse-keymap))) (define-key map (kbd "M-p") (lambda () (interactive) (message "HI!!!"))) map) :group 'hello) ``` After running this followed by `M-x hello-mode` (or `(hello-mode t)`), I would hope that hitting `M-p` would display `"HI!!!"` in the echo area, but Emacs tells me `M-p` is still undefined. What else is needed to bind a key to a function when my minor mode is active? # Answer > 5 votes Your code works perfectly, for me. Did you try it in `emacs -Q` (no init file)? And if I load library `help-fns+.el` and then use `M-k hello-mode-map` it shows me that `M-p` is bound to an (anonymous) command. However, I recommend that you give your keymap a name (a symbol). That helps users (and yourself) more. --- (If you have an Emacs 28 preview then you also have that command, `describe-keymap` \- it's been added to Emacs itself.) --- Tags: key-bindings, keymap, minor-mode ---
thread-68423
https://emacs.stackexchange.com/questions/68423
Remove space autocomplete from M-x
2021-09-07T19:48:20.467
# Question Title: Remove space autocomplete from M-x Is there a way to disable space trigging autocomplete for M-x? It'd be nice to still have it, just not bound to space. I can get something like what I want with: ``` (define-key minibuffer-local-completion-map " " nil) ``` Checking the documentation, it looks like space corresponds to minibuffer-complete-word, so I guess I just need to rebind that within the minibuffer key map? I use Plover steno (https://www.openstenoproject.org/) with Emacs (i.e. mapping key strokes to words/phrases). Plover automatically puts spaces either before or after words. This causes a Catch-22. Using spaces before requires lots of manual adjustments to prevent leading spaces. Using spaces after causes problems with M-x since spaces are interpreted as autocomplete. My preference would be to use spaces after. Here's what happens with spaces after. Writing PAO-EU/THOPB for "python" sends `p-i-e-<space>-<backspace>-<backspace>-<backspace>-t-h-o-n` to Emacs. The space is interpreted as autocomplete, so that instead of "python", I get "ython". # Answer The behavior of space completion within the minibuffer is controlled by the `minibuffer-local-completion-map`. This can be redefined with something like: ``` ;; replace space tab completion with insertion of a space character (define-key minibuffer-local-completion-map " " 'self-insert-command) ;; remap what space was (i.e. `minibuffer-complete-word`) to tab (define-key minibuffer-local-completion-map "<tab>" 'minibuffer-complete-word) ;; remap what tab was (i.e. `minibuffer-complete`) to shift-tab (define-key minibuffer-local-completion-map "S-<tab>" 'minibuffer-complete) ``` Or, if you use general.el: ``` (general-def :keymaps 'minibuffer-local-completion-map "SPC" 'self-insert-command ;; now inserts a space character "<tab>" 'minibuffer-complete-word ;; previously was space "S-<tab>" 'minibuffer-complete ;; previously was tab ) ``` > 1 votes # Answer Usually better than this: ``` (define-key minibuffer-local-completion-map " " nil) ``` is this: ``` (define-key minibuffer-local-completion-map " " 'self-insert-command) ``` It lets `SPC` chars be self-inserting. That means you can type a space char to match against a completion candidate that contains a space char (duh). This should, IMHO, be the default behavior for Emacs, but it's not. > 2 votes --- Tags: completion ---
thread-68361
https://emacs.stackexchange.com/questions/68361
How can I set the ls program dired uses only for local directories
2021-09-02T14:14:58.593
# Question Title: How can I set the ls program dired uses only for local directories I have set the ls program dired uses via ``` (setq insert-directory-program "gls")) ``` (so that I can specify `--group-directories-first` in `dired-listing-switches`). Trouble is when I browse a remote directory, TRAMP seems to use the same variable `insert-directory-program`, but on arbitrary remote machines the `gls` command might not be available. How can I set the `ls` program dired uses to `gls` only for local directories? # Answer > 0 votes Elaborating on the comments form @NickD there seems to be no separate way to configure the used `ls` command used used for TRAMP directories vs local directories. So the remaining option is to symlink the local `gls` (at least for Emacs) to `ls` and keep Emacs' default of `insert-directory-program` as `"ls"`. ### Update 28 Sep 2021: Also, it is important to use no non-standard switches in `dired-listing-switches`, because they are used for the remote dired buffers as well! So stick with something like `"-alhF"` and don't use GNU's `--group-directories-first`, beacuse your TRAMP dired buffere will be empty when the remote system for example plain BSD. --- Tags: dired, tramp, remote ---
thread-28735
https://emacs.stackexchange.com/questions/28735
Magit diff side by side
2016-11-18T09:46:06.717
# Question Title: Magit diff side by side I would like to know if there is a way to get the standard side by side `diff` view in `magit`. That is, instead of seeing the old code chunk and the new one one after the other, I'd like to see them on the same horizontal alignment. # Answer > 33 votes The Emacs package for doing this is named Ediff and Magit supports Ediff. To get started press `e` on the change for which you want to see the side-by-side comparison. You might also have to use `E` occasionally to tell Ediff/Magit explicitly what you want to compare. Also see the Ediff manual and the node about Ediff in the Magit manual. # Answer > 2 votes Using Emacs and Magit on Windows, I didn't find it intuitive to get side by side diffs (with 2 windows instead of 3) even with the above answer. Adding this in case it helps others. Here's what I did to get it working for me. * Install **cygwin** and add the **bin** directory to **PATH** (this makes the `ediff` tool available to Emacs - can probably ignore this on non-Windows platforms) * Add the below to **~/.emacs** to get 2 instead of 3 windows in the diff (ignore this if you want 3 windows) (setq magit-ediff-dwim-show-on-hunks t) * Add the below to **~/.emacs** to have it default to side by side (custom-set-variables '(ediff-split-window-function (quote split-window-horizontally))) * Press **E** then **E** when over a changed file, this opens Ediff and shows a separate frame (top level Window) running Ediff, *make sure that the Ediff frame has focus when entering commands* * Press **SPACE/BACKSPACE** to move around through the differences (and press **?** to toggle the Ediff frame between minimal and a larger size which shows all the commands) * Press **q** to exit the Ediff session and respond to the prompts back in the main Emacs frame --- Tags: magit, diff ---
thread-33326
https://emacs.stackexchange.com/questions/33326
How do I cut and paste effectively between applications while using EXWM?
2017-06-05T21:45:06.970
# Question Title: How do I cut and paste effectively between applications while using EXWM? For example, I am trying to copy the URL line from Firefox into an org mode buffer. The usual cut and paste keys for Firefox (C-c C-v) do not work, and neither does (M-w C-y). To copy from Firefox (in this example), I have to use the right mouse button context menu and select "Copy" which is suboptimal to say the least. I've googled and gone through the documentation but can't seem to find any reference to the kill buffer. Any help would be appreciated. # Answer **Long answer**: There are three modes\* in `EXWM`. **I**. Sending all the keys to the apps except the global bindings (for e.g. this is a global `(exwm-input-set-key (kbd "s-c") #'list-processes)`. `EXWM` calls this `char-mode` **II**. Sending all the keys to the apps with some simulations. `EXWM` calls this `line-mode`. You can define simulations like. ``` (exwm-input-set-simulation-keys '(([?\C-b] . left) ([?\C-f] . right))) ``` Now in this mode if I press `C-f` apps receive `right` arrow key. **III**. Not sending any key to the apps, instead Emacs receives all the keys. So you can use normal operations like `C-x 2` or `C-x 3` to split the window.`EXWM` calls this `line-mode` too. `C-c` and `C-v` doesn't work because you're in mode **III**. Here are some of the helper functions that I use. ``` (defun fhd/exwm-input-line-mode () "Set exwm window to line-mode and show mode line" (call-interactively #'exwm-input-grab-keyboard) (exwm-layout-show-mode-line)) (defun fhd/exwm-input-char-mode () "Set exwm window to char-mode and hide mode line" (call-interactively #'exwm-input-release-keyboard) (exwm-layout-hide-mode-line)) (defun fhd/exwm-input-toggle-mode () "Toggle between line- and char-mode" (interactive) (with-current-buffer (window-buffer) (when (eq major-mode 'exwm-mode) (if (equal (second (second mode-line-process)) "line") (fhd/exwm-input-char-mode) (fhd/exwm-input-line-mode))))) ``` To make it globally available with `s-i` ``` (exwm-input-set-key (kbd "s-i") #'fhd/exwm-input-toggle-mode) ``` This toggles between modes **I** and either mode **II** or **III**. Switching between mode **II** and mode **III** depends on `exwm-input-line-mode-passthrough`. Another helper function I use: ``` (defun fhd/toggle-exwm-input-line-mode-passthrough () (interactive) (if exwm-input-line-mode-passthrough (progn (setq exwm-input-line-mode-passthrough nil) (message "App receives all the keys now (with some simulation)")) (progn (setq exwm-input-line-mode-passthrough t) (message "emacs receives all the keys now"))) (force-mode-line-update)) ``` And to bind it globally ``` (exwm-input-set-key (kbd "s-p") 'fhd/toggle-exwm-input-line-mode-passthrough) ``` I used `(force-mode-line-update)` in this function since I have an indicator in my mode-line to show if emacs receives all the keys (mode **III**) or apps receive all the keys with some simulations (mode **II**) if mode-line is hidden it means we are in mode **I** and apps receive all the keys without any simulations. To make sure apps open in mode **II** you can use `(setq exwm-input-line-mode-passthrough nil)`. If you want all the apps to open in mode **I** (that is `char-mode` in `EXWM` terminology) you can use: ``` (add-hook 'exwm-manage-finish-hook (lambda () (call-interactively #'exwm-input-release-keyboard) (exwm-layout-hide-mode-line))) ``` \*The word "mode" is used loosely, it doesn't mean in `EXWM` there are actually three modes. **Short answer** Call `exwm-input-release-keyboard` function. It switches to `char-mode` which means firefox receives all the key events. > 6 votes # Answer I'm reading the guide and seems it's also possible to prefix all the usual shortcuts with `C-c C-q` (`exwm-input-send-next-key`) without switching to `char-mode`. So instead of `C-a`/`C-c`/`C-v` use `C-c-q-a`/`C-c-q-c`/`C-c-q-v`. > 1 votes # Answer If the above approach don't work for you(mine did not), try it this way. First, we set to open all application in `char-mode` by default. ``` ;; The code from user - fhdhsni (add-hook 'exwm-manage-finish-hook (lambda () (call-interactively #'exwm-input-release-keyboard) (exwm-layout-hide-mode-line))) ``` Then if you want to go back to `line-mode`, just do `exwm-reset`. The default keybinding is - `s-r` > 0 votes --- Tags: copy-paste, exwm ---
thread-68434
https://emacs.stackexchange.com/questions/68434
Search for tags in the future
2021-09-08T18:14:26.650
# Question Title: Search for tags in the future I would like to create a custom agenda view for future entries with a given tag (e.g. LABEL). I've tried something like: ``` (setq org-agenda-custom-commands '(("l" tags "+LABEL +TIMESTAMP >= \"<now>\""))) ``` but it still display tagged entries from the past. What would be the right query? **Note** It's really for tags, not todo-tags, scheduled or deadlines. # Answer The problem is the spaces. Try `"+LABEL+TIMESTAMP>=\"<now>\""`. And of course make sure that the entries you are interested in contain `LABEL` as a tag and also contain a "bare" timestamp: ``` * New Year :resolution: <2022-01-01> I resolve to get organized ``` Assuming the entry is in one of your agenda files, it should be found with ``` (setq org-agenda-custom-commands '(("t" "future resolutions" tags "+resolution+TIMESTAMP>=\"<now>\""))) ``` The space is a boolean `OR` operator - see the section "Matching tags and properties" in the manual, which you can get to with `C-h i g (org)matching tags and properties`. > 1 votes --- Tags: org-agenda, org-tags ---
thread-68440
https://emacs.stackexchange.com/questions/68440
How to toggle the *Python* buffer?
2021-09-09T07:23:02.313
# Question Title: How to toggle the *Python* buffer? When working on python code in `elpy`, I like to have the python shell open. Often I don't want the `*Python*` buffer to be visible, especially with several buffers with Python code or long Python files open. I found the package eshell-toggle which is basically doing the same for `eshell` buffers what I would find useful for the `*Python*` buffer. 1. If eshell-toggle’d buffer is already visible in frame for current buffer then select (toggled) eshell window. 2. If current window is (toggled) eshell itself then hide it. Is there a good way to toggle the `*Python*` buffer? # Answer I'm not so familar with `elisp`, but as aadcg pointed out that `elpy-shell-switch-to-shell` and `delete-window` might work I gave it a try. ``` (defun python-toggle () (interactive) (cond ((equal (buffer-name) "*Python*") (delete-window)) ((get-buffer "*Python*") (elpy-shell-switch-to-shell)) ((derived-mode-p 'python-mode) (run-python)) (t (message "Not in python-mode.")))) ``` With this function toggling the `*Python*` buffer works. If you want to bring the `*Python*` buffer to front when sending code via any `elpy-shell-send-*` function, you need to set `(setq elpy-shell-display-buffer-after-send t)` But as I'm not familiar with `elisp` this code can probably be improved quite a bit. > 2 votes --- Tags: python, elpy ---
thread-68441
https://emacs.stackexchange.com/questions/68441
evil: Make `%s/x/y/gc` use case insensitive matching but do case sensitive replaces
2021-09-09T08:26:20.843
# Question Title: evil: Make `%s/x/y/gc` use case insensitive matching but do case sensitive replaces How do I make `%s/x/y/gc` use case insensitive matching but do case sensitive replaces? In emacs terms, I want `case-fold-search` but not `case-replace`. # Answer Looking at the code of `evil-ex-substitute` (using `C-h f`), the value for `case-replace` is set to the value of `case-fold-search` in the `let*` form. So it looks like there is no configuration option provided for this by default. But of course you can just replace the `case-fold-search` with `(not case-fold-search)` after the `case-replace` in that `let*` and (re)evaluate the `evil-ex-substitute` function definition. NOTE how the value of `case-fold-search` is set via `evil-ex-pattern-ignore-case`. This a.o. means that you can use vim style patterns to set the value for `case-fold-search` (using `\c/\C` as explained e.g. in this SE-answer). > 2 votes --- Tags: evil, regular-expressions, vim-emulation, query-replace-regexp ---
thread-45299
https://emacs.stackexchange.com/questions/45299
Adjust font weight for LaTeX fragment preview in Org-mode
2018-10-11T15:16:11.050
# Question Title: Adjust font weight for LaTeX fragment preview in Org-mode The default font weight after rendered for LaTeX fragment is too thin compared to the body text. Is there any way to adjust this? It seems `org-format-latex-options` does not have this option, I am newbie to LaTeX, tried to set `org-format-latex-header` but failed... # Answer > 3 votes I think an easier approach is through an advice. Here we use an around advice to modify the string that gets used to make the fragment, and then calling the original function with the new string. It allows you to put new latex before and after the equation if you want. Just make sure the code has a \n at the end like this: ``` (plist-put org-format-latex-options :latex-fragment-pre-body "\\mathversion{bold}\n") (defun org-inject-latex-fragment (orig-func &rest args) "Advice function to inject latex code before and/or after the equation in a latex fragment. You can use this to set \\mathversion{bold} for example to make it bolder." (setf (car args) (concat (or (plist-get org-format-latex-options :latex-fragment-pre-body) "") (car args) (or (plist-get org-format-latex-options :latex-fragment-post-body) ""))) (apply orig-func args)) (advice-add 'org-create-formula-image :around #'org-inject-latex-fragment ) ``` # Answer > 2 votes It looks like the way to do this in LaTeX is to add this in the document body: ``` \mathversion{bold} ``` It doesn't look there is a way to do this out of the box with org, the document template is hard-coded in org-create-formula image. You can modify that function like this to achieve what you want. You can put this in your init file. ``` (defun org-create-formula-image (string tofile options buffer &optional processing-type) "Create an image from LaTeX source using external processes. The LaTeX STRING is saved to a temporary LaTeX file, then converted to an image file by process PROCESSING-TYPE defined in `org-preview-latex-process-alist'. A nil value defaults to `org-preview-latex-default-process'. The generated image file is eventually moved to TOFILE. The OPTIONS argument controls the size, foreground color and background color of the generated image. When BUFFER non-nil, this function is used for LaTeX previewing. Otherwise, it is used to deal with LaTeX snippets showed in a HTML file." (let* ((processing-type (or processing-type org-preview-latex-default-process)) (processing-info (cdr (assq processing-type org-preview-latex-process-alist))) (programs (plist-get processing-info :programs)) (error-message (or (plist-get processing-info :message) "")) (use-xcolor (plist-get processing-info :use-xcolor)) (image-input-type (plist-get processing-info :image-input-type)) (image-output-type (plist-get processing-info :image-output-type)) (post-clean (or (plist-get processing-info :post-clean) '(".dvi" ".xdv" ".pdf" ".tex" ".aux" ".log" ".svg" ".png" ".jpg" ".jpeg" ".out"))) (latex-header (or (plist-get processing-info :latex-header) (org-latex-make-preamble (org-export-get-environment (org-export-get-backend 'latex)) org-format-latex-header 'snippet))) (latex-compiler (plist-get processing-info :latex-compiler)) (image-converter (plist-get processing-info :image-converter)) (tmpdir temporary-file-directory) (texfilebase (make-temp-name (expand-file-name "orgtex" tmpdir))) (texfile (concat texfilebase ".tex")) (image-size-adjust (or (plist-get processing-info :image-size-adjust) '(1.0 . 1.0))) (scale (* (if buffer (car image-size-adjust) (cdr image-size-adjust)) (or (plist-get options (if buffer :scale :html-scale)) 1.0))) (dpi (* scale (if buffer (org--get-display-dpi) 140.0))) (fg (or (plist-get options (if buffer :foreground :html-foreground)) "Black")) (bg (or (plist-get options (if buffer :background :html-background)) "Transparent")) (log-buf (get-buffer-create "*Org Preview LaTeX Output*")) (resize-mini-windows nil)) ;Fix Emacs flicker when creating image. (dolist (program programs) (org-check-external-command program error-message)) (if use-xcolor (progn (if (eq fg 'default) (setq fg (org-latex-color :foreground)) (setq fg (org-latex-color-format fg))) (if (eq bg 'default) (setq bg (org-latex-color :background)) (setq bg (org-latex-color-format (if (string= bg "Transparent") "white" bg)))) (with-temp-file texfile (insert latex-header) (insert "\n\\begin{document}\n" "\\definecolor{fg}{rgb}{" fg "}\n" "\\definecolor{bg}{rgb}{" bg "}\n" "\n\\pagecolor{bg}\n" "\n{\\color{fg}\n" (or (plist-get options :latex-body-options) "") string "\n}\n" "\n\\end{document}\n"))) (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)) (unless (string= fg "Transparent") (setq fg (org-dvipng-color-format fg)))) (if (eq bg 'default) (setq bg (org-dvipng-color :background)) (unless (string= bg "Transparent") (setq bg (org-dvipng-color-format bg)))) (with-temp-file texfile (insert latex-header) (insert "\n\\begin{document}\n" (or (plist-get options :latex-body-options) "") string "\n\\end{document}\n"))) (let* ((err-msg (format "Please adjust `%s' part of \ `org-preview-latex-process-alist'." processing-type)) (image-input-file (org-compile-file texfile latex-compiler image-input-type err-msg log-buf)) (image-output-file (org-compile-file image-input-file image-converter image-output-type err-msg log-buf `((?F . ,(shell-quote-argument fg)) (?B . ,(shell-quote-argument bg)) (?D . ,(shell-quote-argument (format "%s" dpi))) (?S . ,(shell-quote-argument (format "%s" (/ dpi 140.0)))))))) (copy-file image-output-file tofile 'replace) (dolist (e post-clean) (when (file-exists-p (concat texfilebase e)) (delete-file (concat texfilebase e)))) image-output-file))) ``` Then, you can specify the latex-body-options in your init file with ``` (plist-put org-format-latex-options :latex-body-options "\\mathversion{bold}\n") ``` That may get you what you want. You may also want to use a different font, in which case you can either add it to org-latex-default-packages-alist, e.g. ``` (add-to-list 'org-latex-default-packages-alist '("" "fourier" t) t) ``` or you can add it to the latex header. Below I set the font to be fourier. I had to add it last, maybe because I have some other font package ``` (setq org-format-latex-header "\\documentclass{article}\n\\usepackage[usenames]{color}\n[PACKAGES]\n[DEFAULT-PACKAGES]\n\\usepackage{fourier}\n\\pagestyle{empty} % do not remove\n% The settings below are copied from fullpage.sty\n\\setlength{\\textwidth}{\\paperwidth}\n\\addtolength{\\textwidth}{-3cm}\n\\setlength{\\oddsidemargin}{1.5cm}\n\\addtolength{\\oddsidemargin}{-2.54cm}\n\\setlength{\\evensidemargin}{\\oddsidemargin}\n\\setlength{\\textheight}{\\paperheight}\n\\addtolength{\\textheight}{-\\headheight}\n\\addtolength{\\textheight}{-\\headsep}\n\\addtolength{\\textheight}{-\\footskip}\n\\addtolength{\\textheight}{-3cm}\n\\setlength{\\topmargin}{1.5cm}\n\\addtolength{\\topmargin}{-2.54cm}") ``` # Answer > 0 votes While John Kitchin certainly has a very elegant advice. The drawback of `\mathversion{bold}` is that every symbol looks like bold type vectors. I would suggest a one-liner: `#+latex_header: usepackage{arev}` This would change your math font into "Arev", probably the easiest math font on the eyes. You can also checkout a survey of free math fonts on Ctan https://ctan.org/pkg/free-math-font-survey?lang=en , most of them require only `\userpackage` to change your math font --- Tags: org-mode, preview-latex ---
thread-68443
https://emacs.stackexchange.com/questions/68443
How to define font for Greek text
2021-09-09T11:35:35.580
# Question Title: How to define font for Greek text On my Emacs 27 on MacOS ("GNU Emacs 27.2 (build 1, x86\_64-apple-darwin19.6.0, NS appkit-1894.60 Version 10.15.7 (Build 19H1030)) of 2021-05-17") I use ETBembo 18pt as font for org-mode. However Greek text in org-mode appears to use the font `mac-ct:-*-Helvetica Neue-thin-normal-normal-*-18-*-*-*-p-0-iso10646-1 (#x42C)` which I find too thin. I suppose this font is chosen because ETBembo doesn't have Greek. However, I wonder why 'Helvetica Neu thin' is chosen. If I copy/paste the text in a normal Emacs buffer (where Monaco 13pt is the default font) the Greek text uses `mac-ct:-*-Helvetica-normal-normal-normal-*-13-*-*-*-p-0-iso10646-1 (#x464)`, i.e. a normal Helvetica, which I find much better. Does anyone know why the 'Helvetica Neu thin' was chosen in the first case and how to overrule this? # Answer > 1 votes I found an answer myself. I still don't know why the 'Helvetica Neue thin' was chosen, but I suppose it just looks for a font that has the Greek characters, and this was what came up first. That still doesn't explain why 'Helvetica normal' was chosen in the other case. However, this incantation makes it always use my own choice: ``` (set-fontset-font t 'greek (font-spec :family "Helvetica" :weight 'normal :height 0.75)) ``` The 0.75 is to make it a similar size as the ETBembo, which looks a bit smaller than Helvetica. --- Tags: fonts ---
thread-17056
https://emacs.stackexchange.com/questions/17056
What is the origin of the term "yank"?
2015-10-01T14:49:53.973
# Question Title: What is the origin of the term "yank"? I'm interested in learning how the term "yank" got its name. I'm also interested in why Emacs "yank" differs from vi/vim "yank". See also: dual question about Vi, also on Unix & Linux; # Answer > 8 votes "Yank" is just English. You are "pulling" some text into the current buffer at point. Note that the more common term "paste" (no, it is not quite the same thing) is no clearer in this regard. There is no glue involved. --- Note too that the verb "copy" has two meanings that can confuse its use. One of them means to make an invisible copy, which can later be used to make a visible copy. The other means to duplicate. When you "copy" text but you do not paste it you do the first of these. When you "copy" a file you do the second. # Answer > 2 votes **Yank**'s meaning comes from English language's action verbs similar to jerk, pull, draw, force, etc. It is a more active verb than copy, paste, and other modern synonyms GUIs use. Please refer to other other responses to this question for its semantic history. There is one important functional history of **yank** that many modern uses of copy-and-paste ignore or oblivious to. It is the selective integration with the operating system's clipboard. `Ctrl`-`y` is the default **yank** command that normally retrieves the most recent entry from the \*kill\** ring. However on GUIs, emacs **yank**s from the system clipboard if there happens to be a more recent entry than on the application **kill** ring. **Yank** also plays nice with primary and secondary selections in GUIs like X-Windows. It is this level of selective integration that sets **yank** in emacs apart from other cut-copy-paste operations in other apps. # Answer > 1 votes Based on the comment given earlier: `Emacs` version 1 already used **kill**/**yank**, which it inherited from `TECO`. `TECO` dates back to 1962 but it's unclear if the first version already had these commands. Some `PDP-8` manuals mentioned the **yank** command, but they may not be the original `PDP-8`. Nonetheless, it seems that the word **paste**, which became the standard when ordinary people got `GUI`s, was chosen at `Xerox` in the mid-1970s. --- Tags: yank, history ---
thread-68455
https://emacs.stackexchange.com/questions/68455
How to properly execute `gif-screencast-stop` before `save-buffers-kill-emacs`?
2021-09-10T14:32:09.520
# Question Title: How to properly execute `gif-screencast-stop` before `save-buffers-kill-emacs`? I am running Emacs 27.1 on Ubuntu. I have installed `gif-screencast` and have gotten it to start recording whenever i start Emacs by adding ``` (gif-screencast) ``` to my `init.el`. So far, so good. The problem is saving the recording when killing Emacs. I have tried to add both ``` (add-hook 'kill-emacs-hook 'gif-screencast-stop) ``` and ``` (setq confirm-kill-emacs 'gif-screencast-stop) ``` to my `init.el`, but none of them manage to stop the recording and save it *before* Emacs asks me whether I want to kill running processes. When I answer 'yes', it will, of course, kill the `gif-screencast` process before ending it properly. My current solution, arrived at by trial and error, is to add ``` (advice-add 'save-buffers-kill-emacs :before #'gif-screencast-stop) ``` to `init.el`. This works when killing Emacs by using the GUI menu, but not when using `C-x C-c` from within Emacs. When I try the latter, i get `Wrong number of arguments: (0.0), 1`. When I do the former, it correctly saves the `gif-screencast` recording before giving me the `Save file ...?` prompt and then killing Emacs. Edit: it gives me 2 prompts: First, it gives me `Active processes exist; kill them and exit anyway?`, then it gives me `Save file ...?`. The first one of these is the one that has to wait until after `gif-screencast` has properly finished. My syntax is wrong somehow, but I'm not experienced enough with `elisp` to figure it out. How do I make this execute correctly also when killing Emacs with `C-x C-c`? # Answer > 0 votes I think your advice function should have the same signature as `save-buffer-kill-emacs`, i.e. it should take an optional argument (which it can go ahead and ignore of course): ``` (defun my/gif-screencast-shutdown (&optional arg) (gif-screencast-stop)) (advice-add 'save-buffers-kill-emacs :before #'my/gif-screencast-shutdown) ``` That should take care of the `Wrong number of arguments` message (although I don't understand why/how it works from the GUI and not when called with `C-x C-c`). This is all untested and may be completely wrong, but try it and see. --- Tags: ubuntu ---
thread-68459
https://emacs.stackexchange.com/questions/68459
Elisp function to remove commas in the region
2021-09-10T20:06:57.713
# Question Title: Elisp function to remove commas in the region I'm learning writing Elisp functions to perform small tasks and get to a place where executing a function on the region will replace it with the value returned by the function. Below is a short function that aims to split the region text by commas and and concatenate the resulting substrings. The code fails with `Wrong type argument, characterp` etc. After fixing this function, how can it be modified so that the string stored in `final` *replaces* the region? ``` (defun myconcat() "Split selected buffer and concatenate all words." (interactive) (progn (setq x (buffer-substring (mark) (point))) (setq final "") (setq list (split-string x ",")) (while list (setq final (concat final y))))) ``` EDIT: Added image from running function. Strangely, the function seems to be working on an old selected buffer, but not what I currently selected. EDIT: Another image with running `myconcat` after relaunching emacs # Answer > 2 votes Your question isn't a great one for this site. Instead of "Please debug this for me" you should ask a simple, specific how-to question. Anyway, this will get you started. ``` (defun myconcat(start end) "Split region on `,' chars and concatenate the substrings." (interactive "r") (let* ((x (buffer-substring start end)) (final "") (y (split-string x ","))) (while y (setq final (concat final (car y)) y (cdr y))) (message "FINAL: %S" final) (delete-region start end) (insert final) final)) ``` I'm assuming you really want to replace the active *region* (the selected text), not the whole *buffer*. You say "selected buffer", which doesn't mean anything (unless the whole buffer is selected). If you really want to replace the whole buffer by the selected text with its `,` chars removed, then just replace `(delete start end)` by `(delete (point-min) (point-max))` in the code here. Things to note: 1. You never defined `y`. Presumably your vars `list` and `y` were meant to be the same. 2. No need for `progn`. The body of a function is an implicit `progn`. 3. Don't use global vars (especially undeclared - no `defvar`). Use `let` or `let*`. 4. Use the `interactive` spec to give you the region limits. 5. `split-string` returns a list of substrings. You need to iterate over that list, which means provide a substring to `concat` in each iteration. 6. Your loop never diminished the list of substrings. 7. You never deleted the original region or inserted the calculated text. This is a bit better - the above tried to retain as much as possible of your approach, so you could more easily see the fixes. ``` (defun myconcat(start end) "Split region on `,' chars and concatenate the substrings." (interactive "r") (let ((final "")) (dolist (str (split-string (buffer-substring start end) ",")) (setq final (concat final str))) (message "FINAL: %S" final) (delete-region start end) (insert final) final)) ``` The answer above was accepted. But if what's wanted is really just to remove the comma chars (`,`) in the region then there are better ways. Here's one: ``` (defun remove-commas-in-region (start end) "Remove the commas in the region." (interactive "r") (save-excursion (save-restriction (narrow-to-region start end) (goto-char 1) (while (search-forward "," nil t) (replace-match ""))))) ``` --- Tags: region, string ---
thread-44958
https://emacs.stackexchange.com/questions/44958
Can I insert a prefix to Org Babel source code lines on export?
2018-09-25T17:59:39.523
# Question Title: Can I insert a prefix to Org Babel source code lines on export? Like, say I have a shell script source code block. ``` #+BEGIN_SRC shell echo 'Hello World!' #+END_SRC ``` On export, I want the code text to pick up a dollar sign, so `$ echo 'Hello World!'`. But I only want this to happen to shell script blocks, not any other language blocks. I know there are switches like `-n` that cause a code block to pick up line numbers on export, but it seems to me there’s no easy way to add a new switch or modify an old one to do what I want. I hoped I could advise an appropriate function, but I can’t find the right function to hook into either. # Answer As NickD points out, there is a hook that allows this. It falls under Advanced Configuration in the Org manual. Specifically, > The export process executes two hooks before the actual exporting begins. The first hook, `org-export-before-processing-hook`, runs before any expansions of macros, Babel code, and include keywords in the buffer. The second hook, `org-export-before-parsing-hook`, runs before the buffer is parsed. I think the `before-parsing` hook is the better fit for this problem, but I’m not sure. The manual doesn’t mention this, but the hook is actually an abnormal hook, so its functions must take an argument (the exporting backend). It's also worth mentioning that these functions don't execute in the context of the org buffer you're exporting from. Like all export transformations, they run in a temporary buffer that starts with a copy of the org buffer's text. --- To do the prefix insertion, use `org-babel-map-src-blocks` and take advantage of how it dynamically binds useful context variables like the source block language and the beginning / end of the code body. ``` (defun my-insert-shell-prompt (_backend) (org-babel-map-src-blocks nil ; nil implies current buffer (let (;; capture macro-defined variables (lang lang) (beg-body beg-body) (end-body end-body) ;; other variables (shell-langs '("sh" "shell")) (prefix "$ ")) (when (member lang shell-langs) (goto-char beg-body) (skip-chars-forward "\n\s-" end-body) (while (< (point) end-body) (insert prefix) (end-of-line) (skip-chars-forward "\n\s-" end-body))))))) (add-hook 'org-export-before-parsing-hook #'my-insert-shell-prompt) ``` > 6 votes # Answer In case anyone else finds it useful, here's a slight modification to the great answer by @purple\_arrows to skip the "$ " prefix for continuation lines (i.e., following lines that end in "\\"). ``` (defun org-export-insert-shell-prompt (_backend) (org-babel-map-src-blocks nil ; nil implies current buffer (let (;; capture macro-defined variables (lang lang) (beg-body beg-body) (end-body end-body) ;; other variables (shell-langs '("sh" "shell")) (prefix "$ ") (is-contd-from-prev-line nil)) ; t if prev line ends in '\'; nil otherwise (when (member lang shell-langs) (goto-char beg-body) (skip-chars-forward "\n\s" end-body) ; not sure why OP included '-' (while (< (point) end-body) (if (not is-contd-from-prev-line) ; skip prefix if continuing previous line (insert prefix)) (end-of-line) (if (eq ?\\ (char-after (- (point) 1))) ; check if statement continues in next line (setq is-contd-from-prev-line t) (setq is-contd-from-prev-line nil)) (skip-chars-forward "\n\s" end-body)))))) ``` > 1 votes # Answer Just to add *complementary* information, there is an `org-babel-shell-names` variable defined in `ob-shell.el` that you can use instead of defining your own list ``` (defun org-export-insert-shell-prompt (_backend) (org-babel-map-src-blocks nil ; nil implies current buffer (let (... ... ... (shell-langs org-babel-shell-names) ... ...) (when ... ...)) ``` It's value is: `("sh" "bash" "zsh" "fish" "csh" "ash" "dash" "ksh" "mksh" "posh")` on `doom-emacs` > 0 votes --- Tags: org-export, org-babel ---
thread-68448
https://emacs.stackexchange.com/questions/68448
How to I replace several texts like (1), (2), (3) etc. with fixed text (1), fixed text (2), fixed text (3) in one go?
2021-09-09T16:23:37.423
# Question Title: How to I replace several texts like (1), (2), (3) etc. with fixed text (1), fixed text (2), fixed text (3) in one go? My text contains several occurrences like "(1)", "(2)", "(3)". I want to replace these with the general format like "fixed text (1)", "fixed text (2)", "fixed text (3)" using *Search and Replace*. Can I do this in one go using perhaps regular expressions? # Answer > 2 votes `M-C-% \(([[:digit:]]+)\) RET fixed text \1 RET !` `RET` means to press the return key. ## Some Explanation * M-C-% runs the command query-replace-regexp in a typical Emacs. * `\(([[:digit:]]+)\)` is the regexp for the occurances to be found like e.g. (1), (2) or (42). + `[:digit:]` is the character class for digits. See e.g. the Elisp info pages for more. + `[[:digit:]]` stands for any single digit in the regexp like `[0-9]`. + `[[:digit:]]+` stands for any sequence of digits. + `([[:digit:]]+)` stands for any sequence of digits within parenthesis. + And the surrounding quoted parenthesis define group 1 for each match which allows to reference the match in the replacement part. See below. * `fixed text \1` is the replacement part which consists of the fixed text and + `\1` which is the way to reference the group 1 match. * The final `!` let's Emacs replace all further occurances in one go. ## Further Note the hint in the comments about `\&`. `\&` in the replacement part stands for the whole match. This is applicable in the given case. Explicit grouping is not necessary here. Concretely one could use `M-C-% ([[:digit:]]+) RET fixed text \& RET !` for the given task. The explicit grouping is more flexible, tho. --- Tags: regular-expressions, replace ---
thread-42537
https://emacs.stackexchange.com/questions/42537
ESS R error: searching for program
2018-07-11T12:53:58.383
# Question Title: ESS R error: searching for program I have installed emacs on windows 10 working ok so far. Installed R and ESS. Set system and user path to Rterm.exe as read in some forums. Restarted and opened a R file in emacs. Syntax coloring is Ok, emacs entered ESS-R-mode but I cannot evaluate R code. Using `C-c C-n` to evaluate the current line / selection, gives me a message: ``` "Searching for program: No such file or directory, R" ``` `M-x R` prompt for starting project directory, but same message is shown. Double checked system PATH and everything seems ok. Checked emacs variable "getenv" and path is properly set to Rterm.exe folder. I can open a shell inside emacs and run R prompt with no issue. any hint? UPDATE: tried setting (inferior-R-program-name "C:/Users/joe/R/bin/x64/Rterm") and (inferior-ess-r-program "C:/Users/joe/R/bin/x64/Rterm.exe") to .emacs file and now emacs is stuck on blank screen after asking for R starting project directory. The only way to close it is Task Manager - kill process # Answer It's no longer required to use Rterm.exe; you can just use R.exe directly. To configure the program name that emacs/ESS uses, set the variable in your .emacs like this: ``` (setq inferior-ess-r-program "R") ``` Alternatively, press `C-h v`, select the `inferior-ess-r-program` variable, and use the Customize interface to set and save the setting. If you don't have the Windows Path set correctly to include the R/bin folder, you can specify the full path in the setting. ``` (setq inferior-ess-r-program "C:/Program Files/R/R-3.5.3/bin/R.exe") ``` > 3 votes # Answer If `(executable-find "R")` returns `nil`, you can add the R location to `exec-path` through Customize. On my system, `C:\Program Files\R\R-4.1.1\bin\x64`. This will resolve the issue. The easiest way to do this is to `C-h v exec-path` and then click through the "customize" option link. (Note that `exec-path` is both a variable and a function, and you want the variable.) > 0 votes --- Tags: ess, r ---
thread-68473
https://emacs.stackexchange.com/questions/68473
Searching text in images?
2021-09-12T17:57:20.273
# Question Title: Searching text in images? Is it possible to search through text in images in emacs? I have searched for a tool, but i could not find anything. I want to scan all my documents and then search the images with emacs to find my document. For example: i scan a documnent, which shows "hello world", then i want to find this image, when searching in a folder full of images with that image in the folder. # Answer You need to wire up an optical character recognition program (e.g. https://github.com/tesseract-ocr/tesseract) to read the text from images, and then couple that with a search tool. See https://kitchingroup.cheme.cmu.edu/blog/2015/07/24/Indexing-text-in-screenshots-so-they-are-searchable/ for an example of how it might work. If you have a lot of images, I guess you would want to cache the results somehow, so you don't have to find all the images, then do OCR, then search each time. Here is a proof of concept that is lightly tested. This finds images (png and jpg) in the current directory (and below), runs each one through tesseract and captures the string, and then uses completion to search (I use ivy, which makes it pretty easy), then opens the image you select. ``` (require 'f) (let* ((candidates (cl-loop for f in (f-files "." (lambda (f) (member (file-name-extension f) '("png" "jpg"))) t) collect (cons (shell-command-to-string (format "tesseract %s -" f)) f))) (choice (completing-read "Query: " candidates))) (find-file (cdr (assoc choice candidates)))) ``` I would not use this on your file system, it would probably take a long time to do that. Instead, you would want to save the strings to some intermediate database, and then search the database. > 7 votes --- Tags: images ---
thread-68472
https://emacs.stackexchange.com/questions/68472
File local variables doesn't work
2021-09-12T17:23:39.910
# Question Title: File local variables doesn't work I tried putting a local file variable in an org mode file: ``` # -*- mode:org; coding:utf-8; org-duration-format: h:mm; -*- ``` but when I open this file the variable has the original value and not the one I set. Also `file-local-variables-alist` is `nil`. I tried with only:`# -*- org-duration-format: h:mm; -*-`, with another variables and also with a plain text file, but never the file local variables made any effect. The value of `enable-local-variables` is `:safe`, as default. # Answer As explained by @NickD, `org-duration-format` isn't a safe variable: ``` (get 'org-duration-format 'safe-local-variable) ; nil ``` So there are two ways: 1. Set `enable-local-variables` to `t` for getting asked if to trust that variable when the file is opened: ``` (setq enable-local-variables t) ``` 2. Push `org-duration-format` into `safe-local-variable-values`: ``` (add-to-list 'safe-local-variable-values '(org-duration-format . h:mm)) ``` > 3 votes --- Tags: doom, file-local-variables ---
thread-68476
https://emacs.stackexchange.com/questions/68476
Is there a way to see a log of the backend commands issued by VC commands?
2021-09-12T21:53:39.627
# Question Title: Is there a way to see a log of the backend commands issued by VC commands? I'd like to see the what commands are issued by the child process used by the various VC commands. Is there a way to log them or collect them without modifying the VC code? For example, I'd like to see what Git command(s) are issued when the `C-x v ~` key is typed to execute the `vc-revision-other-window` command for a Git backend. # Answer > 2 votes `C-h``v` `vc-post-command-functions` will probably get you the majority of them, but not necessarily all of them. For instance, I note that `vc-git.el` uses its own internal `vc-git--call` for a handful of things (where presumably there was some problem with going via the standard channel). --- Tags: vc, vc-mode ---
thread-68479
https://emacs.stackexchange.com/questions/68479
How can I restore "hlt-highlight" after reopening a file?
2021-09-13T07:46:18.597
# Question Title: How can I restore "hlt-highlight" after reopening a file? Linux Mint 20.2 Emacs 27.1 package: highlight ver. 20210318.2248 I want to highlight specific region. So here my steps: ``` 1. hlt-choose-default-face ``` 2. Select region 3. `M-x hlt-highlight` 4. And here result. Nice. Now I kill the buffer `C-x k` And again open the same file. Here result As you can see the text *Hello, how are you?* **is not highlighting**. The question is: Is it possible to restore highlighting after reopen file? # Answer > 3 votes The answer is yes and no. If you want highlighting that is automatically re-created in a regular way then you typically want to just use `font-lock-keywords` (`font-lock-defaults`, `font-lock-add-keywords`) for the mode you're interested in. Or you can put code that does the highlighting using `highlight.el` in your init file (or some other file you load), to do the highlighting. Apart from `enriched-mode`, highlighting is not saved *with your file*. Something - some code - needs to reestablish the highlighting after you reopen your file. Anything you do interactively to highlight something is actually done by code. You can rerun such code in another session or after reopening a file. You just need to have created the code to use. See this section of the `highlight.el` doc: Temporary or Permanent Highlighting. > To save highlighting permanently, do the following: > > 1. `M-x enriched-mode`, to put your file buffer in minor mode ‘enriched-mode’. You see ‘Enriched’ in the mode line. > 2. Choose text-property highlighting, not overlay highlighting, by setting option `hlt-use-overlays-flag` to `nil`. To do this using Customize, choose menu item Highlight using text properties, not overlays. > 3. Choose the highlight face to use: `M-x hlt-choose-default-face`. > 4. Highlight in any way provided by library `highlight.el`. For example, use `hlt-highlighter` to drag-highlight as if using a marker pen. > 5. Save your file. Note that, although highlighting in enriched-text mode modifies the buffer, it does not appear modified to Emacs (check the beginning of the mode line), so if you make no other changes then using `C-x C-s` does not save your highlighting changes. To remedy this, just do something besides highlighting — e.g., add a space and delete it — so that `C-x C-s` saves to disk. > > When you reopen your file later, it is automatically in enriched mode, and your highlighting shows. However, be aware that font-locking can interfere with enriched mode, so you might want to use it on files where you don’t use font-locking. --- Tags: highlighting ---
thread-55199
https://emacs.stackexchange.com/questions/55199
What are these prefix commands that start with s-l?
2020-01-30T17:24:53.643
# Question Title: What are these prefix commands that start with s-l? I'm using lsp-mode, and I see these weird prefix commands that start with `s-l`. How do I type them? ``` `lsp-mode' Minor Mode Bindings: key binding --- ------- s-l Prefix Command C-S-SPC lsp-signature-activate <C-down-mouse-1> lsp-find-definition-mouse <C-mouse-1> ignore <mouse-3> lsp-mouse-click s-l = Prefix Command s-l F Prefix Command s-l G Prefix Command s-l T Prefix Command s-l a Prefix Command s-l g Prefix Command s-l h Prefix Command s-l r Prefix Command s-l s Prefix Command s-l G g lsp-ui-peek-find-definitions ``` # Answer > 28 votes For historical reasons, Emacs supports key bindings for the 'super' and 'hyper' modifier keys, which you probably do not have on your keyboard. See Modifier Keys in the Emacs manual for more information. So the key bindings you are looking at use super+l as a prefix. You can simulate these additional keys with some built-it sequences: > C-x @ h adds the Hyper flag to the next character, C-x @ s adds the Super flag Depending on your operating system, you may have built-in bindings (on a Mac, Super is the Command key) and can customize using appropriate variables (`ns-*-modifier` variables on Mac, `w32-*-modifier` variables on Windows). For example on a Mac you might have `ns-command-modifier` set to map Command to Super. See Windows Keyboard or Mac Basics for more. # Answer > 0 votes If you have a Windows keyboard, the Windows key is the super key. --- Tags: key-bindings, lsp-mode ---
thread-59399
https://emacs.stackexchange.com/questions/59399
Show only one or two lines of a buffer
2020-07-02T08:15:05.560
# Question Title: Show only one or two lines of a buffer I need to check numbers in a buffer each on a line against an external paper sheet To make this easier I would like to make the window very narrow to see only *one* (or max. *two*) lines. However `shrink-window` stops at *three* lines. Any way to overcome this limitation of `shrink-window`? # Answer > 1 votes The following shows one line of content and the modeline for me: ``` (setq window-safe-min-height 0) (setq window-min-height 0) ``` I would love to have a way to make the content completely collapse for an acme editor style. Sadly I haven't found the way. # Answer > 2 votes `C-h``v` `window-min-height` > The minimum total height, in lines, of any window. The value has to accommodate one text line, a mode and header line, a horizontal scroll bar and a bottom divider, if present. A value less than ‘window-safe-min-height’ is ignored. The value of this variable is honored when windows are resized or split. I found this with `M-x` `apropos-variable` `RET` `height` `RET` # Answer > 1 votes Would it suit your purpose if you had a command which searched for the next line in the buffer which has a number in it and then showed you just that line? ``` (defun go-to-next-line-with-number () (interactive) (widen) (unless (bobp) (end-of-line)) (when (search-forward-regexp "[0-9]" nil 0) (save-excursion (narrow-to-region (progn (beginning-of-line) (point)) (progn (end-of-line) (point)))))) ``` Assign this command to a key, then go to the beginning of the buffer. Calling this command will go to the first line with a number and show you only this line. When you have done whatever editing you need to do to this line, call it again to go to the next line with a number and so on until you reach the end of the buffer. If this is close but not precisely what you need, tell me more exactly what would help. --- Tags: window, lines ---
thread-68485
https://emacs.stackexchange.com/questions/68485
vc-mode doesn't evaluate when mode-line-format is set with setq-default
2021-09-13T22:07:48.603
# Question Title: vc-mode doesn't evaluate when mode-line-format is set with setq-default I've this code in my `init.el` ``` (setq-default mode-line-format (list (propertize " %b " 'face 'bufname) (propertize (concat " " vc-mode " ") 'face 'gitmode))) ``` This evaluates `vc-mode` to "" while evaluating the same thing with `setq` instead of `setq-default` results in the desired string "Git:nixos". But I need to use `setq-default` here to modify the `mode-line-format`. Why does this happen and how to fix it? # Answer When the code in your init file runs, there are no open files at all. `vc-mode` is only set when a file is finally opened and determined to be in version–controlled. This means that when it runs your init file and evaluates `vc-mode`, it puts the `nil` value into the list that goes into `mode-line-format`. That `nil` is then skipped whenever the mode line is displayed. Instead, you should put the symbol `'vc-mode` into the `mode-line-format`. Then, when the mode line is displayed, it will know to put the current value of the variable named by that symbol into the mode line instead. Like this: ``` (setq-default mode-line-format (list (propertize " %b " 'face 'bufname) (propertize " " 'face 'gitmode) (propertize 'vc-mode 'face 'gitmode) (propertize " " 'face 'gitmode))) ``` The `'` in front of the name is called a quote, and it quotes whatever lisp form follows it so that it is treated literally instead of evaluated. The `propertize` function, for example, wants the symbol `'face` rather than the value of a variable that happens to be called `face`, so it too is quoted. It also doesn’t matter whether you use `setq` or `setq-default` in your init file, since at that point there are no open buffers and so setting any variable will set the default value of that variable rather than the buffer–local value. Finally, the mode line machinery has a lot of useful things that can simplify your code quite a bit, like this: ``` (setq mode-line-format '((:propertize " %b " face bufname) (:propertize (" " vc-mode " ") face gitmode))) ``` You should read chapter 23.4.2 The Data Structure of the Mode Line of the Emacs Lisp manual, which details everything that can go into the mode line. This manual is also available inside of Emacs. You can open the Info viewer with `C-h i`; this starts you out at a menu of all the manuals installed on your system. > 3 votes --- Tags: mode-line, mode-line-format, setq, vc-mode, setq-default ---
thread-68480
https://emacs.stackexchange.com/questions/68480
How to open full path of a file in ido-find-file?
2021-09-13T11:52:13.420
# Question Title: How to open full path of a file in ido-find-file? I am looking to open a full path as fast as possible.Using `ido-find-file` makes it difficult. When I apply `ido-find-file`, following line show up. ``` Find file: ~/folder/work ``` Here I have a full path(ex: `/home/user/folder_1/work/file.py`) and I want to open it. In `helm-find-files` I can do `C-a` , `C-k` and paste the full path and enter to open it. But in `ido-find-file`, `C-a` does not jump to beginning of the line. Also when I remove everything `/` at the beginning remains, so pasting full path causes: `//home/user/folder_1/work/file.py` When I play around, I found out `C-e` opens `[EDIT]` section and I can do `C-a`, `C-k` and paste full line. Than enter does not open the file right away, it jumps to ido selection menu and I have to press enter again. Maybe can it open the file right away on the `EDIT` section. --- `RET` `RET` # Answer > 1 votes I'm turning my own comment and answer to the follow-up question into this post. `ido-mode`, among other things, remaps `Emacs` default key binding `C-x C-f` (`M-x find-file`) to its own function for files opening `M-x ido-find-file`. With all the conveniences provided by `ido-find-file`, there're still cases when this function "gets in the way". One of such cases you had described. To overcome such obstacles, `ido-mode` allows to fallback to the `Emacs` default (non-Ido) `find-file`, by hitting additional `C-f`. Hence, the full key binding for opening a file with `find-file` when `ido-mode` is enabled would be `C-x C-f C-f`. Note, that you could achieve the same result by calling `M-x find-file` directly (without a key binding). To learn more about the bindings for falling back (and other, as they call it, "magic" actions) in `ido-mode` see `C-h f ido-magic-(forward|backward|delete)-char`. Answering your comment > Is it possible to make C-x C-f to run C-x C-f C-f? supposedly it's more clear now this, kind of, wouldn't make sense with enabled `ido-mode`. I'd suggest using one of the methods described above or disabling `ido-mode` when you don't need it. --- Tags: ido, ido-find-file ---
thread-68478
https://emacs.stackexchange.com/questions/68478
Does "desktop-save-mode" work for multiple monitors?
2021-09-13T06:53:42.637
# Question Title: Does "desktop-save-mode" work for multiple monitors? Linux Mint 20.2 Emacs 27.1 On my desktop computer pluggin 3 monitors. So I want to open 3 frames on every monitor. So my steps: ``` - (desktop-save-mode 1) - restart Emacs - Open frame on DP-2 - make-frame-on-monitor, select DP-1 - make-frame-on-monitor, select DP-3 ``` As result on every monitor has one frame. Nice. After restart Emacs I'm suppose that layout of this 3 frames will be restore. Restart Emacs And the result is the next: ``` On DP-1 open 2 frames On DP-2 open 1 frame On DP-3 not open frame. ``` The question is: Does "`desktop-save-mode`" work for multiple monitors? # Answer > 1 votes On Linux it’s not as straight–forward as that. First, when a program asks the X server for a window the X server must first talk to the Window Manager. The Window Manager can then choose where and how the window should be displayed. Finally, the X server sends information about the new window back to the application that requested it. This lets users choose a Window Manager that acts how they prefer. For example, some Window Managers ask the user to draw a rectangle on the screen and then place the new window inside it. Others reconfigure all existing windows so that the windows tile instead of overlapping. Some don’t care much, or have only very subtle conventions, such as opening all new windows on the same monitor where the mouse cursor is located. Second, the X server handles monitors differently than you might expect. Each display handled by the server will have one or more monitors attached to it. The dimensions of the display are only loosely related to the dimensions of those monitors. These days most of the time the dimensions of the display will be the sum of the dimensions of the monitors along one axis, and the maximum of the dimensions along the other. Thus with two 1920×1080 monitors you will generally end up with a 3840×1080 display. However, this is only a default rather than a requirement. The user might configure the monitors to overlap, or to be separated by a gap; parts of the display might go to more than one monitor or to no monitor at all. The display might be larger than can be displayed on the monitors, with the user panning around to view different parts of it. Or it could be smaller than the monitors, and scaled up. The orientation of the monitors might be different than that of the display. These details may or may not change between sessions, or at any time during a session. The X server normally deals only with coordinates within the boundaries of the display, without reference to the monitors at all. This greatly simplifies things for the applications, because they don’t have to handle any of the complexity if they don’t want to. When they do want to, they can use an X extension called `xrandr` to query information about the connected monitors. There is also a command–line tool called `xrandr` which will do this and print the information out for you; very useful for debugging. Here is an excerpt of what it shows for my simple setup: ``` Screen 0: minimum 8 x 8, current 3840 x 1080, maximum 16384 x 16384 DVI-I-0 disconnected (normal left inverted right x axis y axis) DVI-I-1 connected 1920x1080+0+0 (normal left inverted right x axis y axis) 509mm x 286mm DVI-D-0 connected primary 1920x1080+1920+0 (normal left inverted right x axis y axis) 509mm x 286mm ``` As you can see, my screen is 3840×1080. The monitor attached to DVI-I-1 is 1920×1080 and it’s upper–left corner is located at 0×0 in the display. The other monitor, connected to DVI-D-0, is also 1920×1080 but is located at 1920×0 in the display. This puts them side–by–side with no gap between them. What `make-frame-on-monitor` does is platform dependent, but on Linux with X windows it queries `xrandr` for the list of monitors, asks the user to pick one, then tries to position the new frame within the boundaries of that monitor. However, once this is done Emacs remembers only the position of the frame, not which display it is supposed to be associated with. You can see this by opening up your desktop save file and looking at the frame parameters stored within. You’ll find something like this: ``` … (left . 1919) (top . 26) (display . ":1") (pixel-width . 1920) (pixel-height . 1024) (fullscreen . maximized) (visibility . t) … ``` Although the details may of course be quite different on your computer. When `desktop-save-mode` goes to restore the frames, it does use that saved position to try and place the windows at their correct location. However, the Window Manager does not have to allow this. For example, most will at least try to prevent windows from being moved past the edges of the display, and a tiling window manager might refuse to allow the window to move at all. You should look into how the Window Manager that you are using is configured. It may have many knobs you can tune to get exactly the behavior you prefer. --- Tags: desktop ---
thread-61303
https://emacs.stackexchange.com/questions/61303
Convert orgmode to Rmd
2020-10-19T13:26:22.227
# Question Title: Convert orgmode to Rmd As the title says, I have an `orgmode` file I have been using with `ess` and exporting to `TeX` which has been going very well. However, I need to now export to `html` for reasons out of my control, and was wondering if there is a clean way to obtain an `Rmd` file from the `org` file. Note that this is **not** the same as obtaining a `markdown` file. To clarify the workflow as requested from the comments. The situation is as follows: 1. I have a set of `orgmode` files which were used to analyze data (via `ess`) 2. Typically I would export these to `hugo-markdown` for `html` output downstream (with `ox-hugo`, e.g. this file) and `polymode-org-mode` for `TeX` which works great However, now I **do** need to edit the files in an `.Rmd` setting (hiding code chunks and adding some more analysis). Currently one approach is to export to `markdown` and then copy out what I need, but that seems inefficient. Similarly, the idea of manually messing with my `html` files is also not appealing. The current issue is that `orgmode` export isn't clean enough to work as an `Rmd` file (though the `pandoc-orgmode` one is close). The workflow I'm looking for is then: 1. Load an R-session and work in an `orgmode` file 2. Tangle (??) to an `.Rmd` so other people can muck around I'm not really interested in the inverse route, since I don't really mind working in `Rmd` either (and I can connect to the same R-session), I'd just rather not hand-convert my existing files. Note that in the current setup, the `orgmode` file has a *lot* of extra `LATEX_HEADER` options, since I was mostly just exporting to `TeX`. These options also mess with the output when working with the standard exporters. # Answer > 2 votes The best way to generate an Rmd file from an org file is to use ox-ravel. I use it all the time to generate the Rmd and then the html file using `rmarkdown::render`. It is great to share results with non-emacs users. It handles inline images, code, inline tables, you can add interactive images with `plotly`, interactive networks with `networkviz` etc. The one thing that I don't like is that it can become very slow in some situations. --- Tags: org-babel, r, markdown ---
thread-68490
https://emacs.stackexchange.com/questions/68490
How to set title for org-alert for notification?
2021-09-14T07:12:19.717
# Question Title: How to set title for org-alert for notification? I use org-alert to send notifications about my agenda to `libnotify`, so I can see the notifications via `Dunst`. All works well but everytime the notification pops up, its title is pretty generic. I have Todo in multiple org files, so I am trying to differentiate between them, i.e. Work todo, Home todo....etc. Digging into the `org-alert.el`, this line seems to change the title: ``` (defvar org-alert-notification-title "*org*" "Title to be sent with notify-send.") ``` You can see the default action is to set the title as ***org**. How do I set it to be the name of the buffer where I have the notified Todo list? I tried: ``` (defvar org-alert-notification-title (current-buffer) ) ``` with no luck. Any help is appreciated. # Answer > 1 votes Assuming you have the current version of `org-alert`, I think the best way to do it is to redefine the `org-alert--dispatch` function so that the title is dynamically generated by calling a function to calculate it, instead of using the value of a variable: ``` (defvar org-alert-notification-title-function nil) (defun org-alert-notification-title () "If `org-alert-notification-title-function' is defined and is a function, call it and return what it returns; otherwise return the value of the variable `org-alert-notification-title'" (cond ((null org-alert-notification-title-function) org-alert-notification-title) ((not (functionp org-alert-notification-title-function)) org-alert-notification-title) (t (funcall org-alert-notification-title-function)))) (defun org-alert--dispatch () (let* ((entry (org-alert--parse-entry)) (head (car entry)) (time (cadr entry))) (when (org-alert--check-time time) (alert (concat time ": " head) :title (org-alert-notification-title))))) ``` All of these would be changes to `org-alert.el` (IOW, you are forking `org-alert.el`: if this works for you, I might submit the changes as a PR to the github site): the first two definitions are additions to the file, but the third is a *replacement* The above does not change the current behavior: it redefines `org-alert--dispatch` to call a function `org-alert-notification-title` (instead of using the variable of the same name directly - btw, emacs lisp allows the same name to be used for a variable *and* a function: if the name appears in a function context, the function value is used, otherwise the variable value is used). When that function is called, it checks a (new) variable `org-alert-notification-title-function`: if that variable is nil or is not a function, then the value of the variable `org-alert-notification-title` is returned, which reproduces the current behavior. But if you redefine `org-alert-notification-title-function` to have a function that returns a string as its value, the function is called and the returned string is the return value of the call to the `org-notification-title` function. The point is that the function is called when the notification is needed, so it can take advantage of its context to return information of interest (like the file name of the buffer in which it is evaluated: it just so happens that it is evaluated in exactly the buffer of the file that contains the entry that gives rise to the notification - phew!) So you can customize the behavior by defining your own function and setting it as the value of the variable `org-alert-notification-title-function` in your init file: ``` (defun ndk/org-alert-notification-title () (concat "*ORG* " (let ((fn (buffer-file-name))) (if fn (file-name-base fn) "no file?")))) (setq org-alert-notification-title-function #'ndk/org-alert-notification-title) ``` BTW, there is a bug in `org-alert.el`: it only recognizes `DEADLINE` or `SCHEDULED` timestamps - it does not recognize plain timestamps. See this Important note in the manual for why this is a serious omission. In addition, `org-alert`'s error handling is not particularly robust: if `org-alert--parse-entry` does not recognize a time, then a `nil` is passed to `org-alert-check--time` and the latter keels over and dies. --- Tags: org-mode, notifications ---
thread-68496
https://emacs.stackexchange.com/questions/68496
Org mode: How to get results from a code block with :session header?
2021-09-14T20:00:25.953
# Question Title: Org mode: How to get results from a code block with :session header? First question: How does one catch the results out of the second code block below? ``` #+begin_src python :session :results silent band = "ABBA" #+end_src #+begin_src python :session return band #+end_src #+RESULTS: ``` Running `C-c C-c` on both of them consecutively yields to empty results. However they both seem to run properly as there's no error for undefined variable `band` in the latter block. For example the code below gives results as expected. ``` #+begin_src python return "ABBA" #+end_src #+RESULTS: : ABBA ``` Secondly, I recall reading somewhere in the documentation that the sessions can be named and run in isolated environments. How does that work? There seems to be no examples of such behaviour. # Answer Unfortunately, session evaluation for python code blocks works differently from non-session evaluation and requires changes to the code blocks to make them do the same thing. AFAIK, python is unique among Babel languages in this respect. For non-session evaluation, Org babel implicitly wraps the body of the block in a function: that's why you need to `return` the value. No such wrapping takes place for session evaluation, so adding a `return` generates an error - look in the `*Python*` buffer which is the default name of the session: you'll see that it says `SyntaxError: 'return' outside function`. So for session evaluation, try these two blocks: ``` #+begin_src python :session :results silent band = "ABBA" #+end_src #+begin_src python :session band #+end_src #+RESULTS: : ABBA ``` The value of the block is the value of the expression (here just a variable) on the last line of the block. > 3 votes --- Tags: org-mode, python ---
thread-41242
https://emacs.stackexchange.com/questions/41242
How to autoscroll a window to always show the end of a growing buffer?
2018-04-26T15:05:59.213
# Question Title: How to autoscroll a window to always show the end of a growing buffer? Context: I have a window that shows the output of a shell command. As new lines are added, I'd like the window to always show the most recent lines. Example: ``` (let ((temp-window (or (get-buffer-window "*test*") (split-window-below -10)))) (start-process-shell-command "test-process" "*test*" "sleep 1; ps -ax") (set-window-buffer temp-window "*test*")) ``` For reasons that I don't understand, the window scrolls the first time this code is executed but not the second time (when the buffer already exists). I'm on Emacs 26.0.60 on Ubuntu 16.04. # Answer > 2 votes How about? ``` (let ((temp-window (or (get-buffer-window "*test*") (split-window-below -10)))) (set-window-buffer temp-window "*test*") (select-window temp-window) (goto-char (point-max)) (start-process-shell-command "test-process" "*test*" "sleep 1; ps -ax")) ``` The most common way to do this is to select the target window and place point at point-max to continue scrolling automatically. There are other ways to do this by selecting the window temporarily and going back to another window, but this example should be sufficient to convey the general concept. See also a related function `set-window-point` ... # Answer > 3 votes Does it help to customize option `comint-scroll-to-bottom-on-output`? `C-h v` tells us: > **`comint-scroll-to-bottom-on-output`** is a variable defined in `comint.el`. Its value is `nil` > > This variable is an alias for `comint-move-point-for-output`. > > Documentation: > > Controls whether interpreter output moves point to the end of the output. > > If `nil`, then output never moves point to the output. (If the output occurs at point, it is inserted before point.) > > If `t` or \`all', move point in all windows showing the buffer. > > If `this`, move point only the selected window. > > If `others`, move point only in other windows, not in the selected window. > > The default is `nil`. > > See the variable `comint-scroll-show-maximum-output` and the function `comint-postoutput-scroll-to-bottom`. > > This variable is buffer-local in all Comint buffers. > > You can customize this variable. # Answer > 2 votes Here the solution a use for my compilation log buffer ``` (let ((buf (get-buffer "*Compile-Log*"))) (set-window-point (get-buffer-window buf) (buffer-size buf))) ``` # Answer > 1 votes Try `compilation-scroll-output`. Just came across it in: Automatically scroll \*compilation\* window, beside source-buffer window. Only works for compilation buffers obviously. --- Tags: window, shell, scrolling ---
thread-68499
https://emacs.stackexchange.com/questions/68499
Automatically Uniquify Certain Buffers
2021-09-14T21:50:36.217
# Question Title: Automatically Uniquify Certain Buffers Emacs does a wonderful job of disambiguating buffer names when I have several files with the same name open. That is, if I open a single `main.cpp`, the buffer is simply called `main.cpp`, but if I open two of them, then one will be `main.cpp<foo>` and the other `main.cpp<bar>` (where `foo` and `bar` are directories). This is all fine and good. But there are some file names that are, frankly, worthless on their own. If I'm writing a Python project, `__init__.py` tells me nothing about what file I'm looking at, and I probably have a couple hundred files with that name in my repo, so I've often had the thought that it would be nice if `__init__.py` buffers *always* showed the directory they're in. Likewise, Rust has `mod.rs` which serves the same purpose and is, as a filename, equally useless. Is there a whitelist or a regexp that I can use to tell Emacs to *always* include the directory in the buffer name for files with certain names, even if it's the only file with that name I happen to have open? # Answer > 9 votes Since `Emacs 28.1`, customize `uniquify-buffer-name-style` user option: ``` ** User option 'uniquify-buffer-name-style' can now be a function. This user option can be one of the predefined styles or a function to personalize the uniquified buffer name. ``` This change was added on `Tue Sep 15 12:50:33 2020`, so on `Emacs`es built after that date, `C-h v uniquify-buffer-name-style` outputs (among the rest of things): ``` The value can be set to a customized function with two arguments BASE and EXTRA-STRINGS where BASE is a string and EXTRA-STRINGS is a list of strings. For example the current implementation for post-forward-angle-brackets could be: (defun my-post-forward-angle-brackets (base extra-string) (concat base \"<\" (mapconcat #'identity extra-string \"/\") \">\")) ``` Optionally, one may also take `uniquify--create-file-buffer-advice` function as an example for writing a custom `advice` function to be applied around `create-file-buffer`. For those who don't need *that* much of the flexibility, the following configuration can be commonly recommended (and used on earlier version of Emacs): ``` (setq uniquify-buffer-name-style 'forward uniquify-min-dir-content 3) ``` \[It may be also recommended to look at the documentation of these variables with `C-h v` and tweak the values per exact need.\] --- Tags: buffers, filenames, uniquify ---
thread-41786
https://emacs.stackexchange.com/questions/41786
Update spacemacs packages from the command line
2018-06-01T14:34:31.340
# Question Title: Update spacemacs packages from the command line I'm trying to write a shell function to launch (spac)emacs, update packages, and then restart emacs in daemon mode. I tried this, but it hangs: `emacs --daemon && emacsclient -e '(progn (configuration-layer/update-packages))'` # Answer > 4 votes I ended up with the following: `emacs --daemon -f configuration-layer/update-packages` # Answer > 10 votes Instead of trying to start emacs in daemon mode first and asking it to execute the package update, I'd recommend doing that after performing a scripted upgrade of the packages. To update the packages non-interactively, use the following: ``` emacs --batch -l ~/.emacs.d/init.el --eval="(configuration-layer/update-packages t)" ``` The key here is the `--batch` switch for performing non-interactive operations via the emacs command. The `-l` switch loads the emacs configuration (including the Spacemacs library and configuration). Without this, emacs would not know what the `configuration-layer/update-packages` function is. The `--eval` switch passes emacs a function you want to execute. In this case, passing `(configuration-layer/update-packages t)` will call the `configuration-layer/update-packages` function from Spacemacs with the argument `t`. Passing the argument skips the interactive package update confirmation; it's only important that the argument be a truthy value. Note that because of the manner in which Spacemacs updates packages, it will only *prepare* the packages for update when this command is run. The next time that emacs is started, it will actually go through the process of installing the packages, so if you run `emacs --daemon` directly after this function, it may take longer than usual for the system to start up. This is also why I recommend not starting emacs in daemon mode and having it evaluate the `configuration-layer/update-packages` function: the package updates will only take effect when a new daemon is started. # Answer > 0 votes **To update and quit emacs** Put this function in your init.el ``` (defun updateandquit () (configuration-layer/update-packages t) (spacemacs/kill-emacs)) ``` Then call ``` emacs --batch -l ~/.emacs.d/init.el --eval="(updateandquit)" ``` --- Tags: spacemacs, command-line-arguments ---
thread-68505
https://emacs.stackexchange.com/questions/68505
How to disable holiday display in Calendar
2021-09-15T12:22:07.453
# Question Title: How to disable holiday display in Calendar I'd like to completely disable the holiday feature in Calendar, and only show events from my only "diary" file. How can I do this? # Answer > 2 votes `diary-show-holidays-flag` is a variable defined in `calendar.el`. Its \[default\] value is `t`. You can customize this variable. **Documentation**: ``` Non-nil means include holidays in the diary display. The holidays appear in the mode line of the diary buffer, or in the fancy diary buffer next to the date. This slows down the diary functions somewhat; setting it to nil makes the diary display faster. ``` --- The variable `calendar-holidays` can be customized also, to add or remove holidays as needed. --- Tags: calendar ---
thread-68509
https://emacs.stackexchange.com/questions/68509
How to make csv-align-mode default in tsv-mode?
2021-09-15T14:19:35.603
# Question Title: How to make csv-align-mode default in tsv-mode? I'm editing tab separated file with Emacs and csv-mode.el. When the document is open, I can align the columns with `M-x csv-align-mode`. How to make it automatically aligned when I open the file? Both `~/.emacs` and `.dir-locals.el` based solutions are fine. I'm pretty new with Emacs so this might be generic elisp question but I'm not sure. PS. An example of .tsv file # Answer > 1 votes Add `(add-hook 'csv-mode-hook 'csv-align-mode)` to `~/.emacs` and it works. Note: It's *csv*, not *tsv*, even though editing .tsv files. My skills don't yet suffice to make it in `.dir-locals.el`. --- Tags: init-file, hooks, directory-local-variables ---
thread-65143
https://emacs.stackexchange.com/questions/65143
Copy files from share Windows network folders?
2021-06-03T09:27:53.520
# Question Title: Copy files from share Windows network folders? CentOS, Emacs 27.2 In local network have Windows machine with name **someWindowsHost**. This machine share folder **\shared\some\_windows\_folder**. And if I want to copy some files from this share folder I start my Windows Virtual machine(on VirtualBox). On my Windows open **File explorer** and in address input smt like this: ``` \\someWindowsHost\shared\some_windows_folder ``` As result open content of this network shared folder. And now I can copy files that I need. Nice... but it's to many steps. The question is: Is it possible from Linux (CentOS) machine by Emacs copy files from this share Windows folder? # Answer Yes. If you want to do this from Emacs, read the Tramp documentation, with special attention to the section on SMB. Dired works over Tramp, so you can copy files that way. Alternatively, if you are using Gnome or KDE, your file manager should be able to open SMB URL paths like smb://someWindowsHost/someShare/someWindowsFolder/. > 1 votes --- Tags: remote ---
thread-68506
https://emacs.stackexchange.com/questions/68506
funcall inside local-set-key
2021-09-15T13:30:53.307
# Question Title: funcall inside local-set-key Programming Perl in cperl-mode I often use `_` symbol, so I decided to remap it with `/` symbol, so I could type faster. I created the following functions: ``` (defun add-underscore () (interactive) (insert "_")) (defun add-backslash () (interactive) (insert "/")) (defun my-cperl-mode () "Perl mode customisations." (local-set-key (kbd "/") 'add-underscore) (local-set-key (kbd "_") 'add-backslash) ) (add-hook 'cperl-mode-hook 'my-cperl-mode) ``` Then I decided to merge similar functions into one and created this: ``` (defun output-symbol (symbol) (interactive) (insert symbol)) (defun my-cperl-mode () "Perl mode customisations." (local-set-key (kbd "/") (funcall output-symbol ?\_)) (local-set-key (kbd "_") (funcall output-symbol ?\/)) ) ``` Unfortunately, it doesn't work. What is wrong? # Answer > 1 votes In most Lisp dialects, including Emacs Lisp, symbols have a value as a variable which is independent of their function definition. `(funcall output-symbol …)` refers to the variable-value of `output-symbol`, not to the function. You could refer to the function instead by passing the symbol itself to `funcall`: if you pass a symbol to `funcall`, it uses that symbol's function definition. This means quoting the symbol: `(funcall 'output-symbol …)`. But this won't work because… You run `(funcall …)` at the time you define the key binding. This is pointless. `(funcall 'output-symbol ?_)` is just a complicated way of writing `(output-symbol ?_)`. (The reason `funcall` exists is when you want to call a function reference stored in a variable.) You want to delay the call to `output-symbol`, so you need to put it inside a function — you need to *add* a layer of function abstraction, not remove one: `(local-set-key (kbd "/") (lambda () (output-symbol ?_)))`. But this won't work because… A key can only be bound to a command, i.e. a function that has an `interactive` specification. A function that calls a function that has an `interactive` specification isn't good enough. You need `(local-set-key (kbd "/") (lambda () (interactive) (output-symbol ?_)))`. You don't really save anything with the `output-symbol` function, but it does work. By the way, the `interactive` specification in the definition of `output-symbol` is useless: it specifies that `output-symbol` receives zero arguments when called interactively, so an interactive call would fail. Before I go further, let me mention that calling `local-set-key` in a mode hook is weird: you're doing the keymap customization each time the mode starts. This is weird but ok for your own use; it wouldn't be acceptable in a package because you'd be overriding the user's customizations. The normal way to customize key bindings in a particular mode is to use `define-key` on that mode's keymap. Do this after the `cperl` module is loaded, by registering a function with `eval-after-load`. ``` (defun my-cperl-mode-customizations () (define-key cperl-mode-map (kbd "_") (lambda () (interactive) …)) ) (eval-after-load "cperl-mode" '(my-cperl-mode-customizations)) ``` You can avoid repeating the interactive specification by using a function that builds a command, instead of using an auxiliary function. ``` (defun make-insert-command (text) (lexical-let ((text text)) #'(lambda () (interactive) (insert text)))) (defun my-cperl-mode-customizations () (define-key cperl-mode-map (kbd "_") (make-insert-command "/")) (define-key cperl-mode-map (kbd "/") (make-insert-command "_")) ) (eval-after-load "cperl-mode" '(my-cperl-mode-customizations)) ``` The `make-insert-command` command isn't very nice. Here are a few ways to improve it: * Add `*` to the interactive specification so that the command errors out if the buffer is read-only. * Add `p` to the interactive specification to allow inserting the character multiple times with a prefix argument. The function needs a count argument to receive the prefix argument. * Call `undo-auto-amalgamate` so that typing `foo_bar` will be a single undo action, as it is when `_` is an ordinary key. ``` (defun make-insert-command (text) (lexical-let ((text text)) #'(lambda (&optional n) (interactive "*p") (undo-auto-amalgamate) (or n (setq n 1)) (let ((i 0)) (while (< i n) (setq i (1+ i)) (insert text)))))) (defun my-cperl-mode-customizations () (define-key cperl-mode-map (kbd "_") (make-insert-command "/")) (define-key cperl-mode-map (kbd "/") (make-insert-command "_")) ) (eval-after-load "cperl-mode" '(my-cperl-mode-customizations)) ``` This is still not very nice because the binding for `_` and `/` will appear as some unreadable Lisp code in help. Anonymous commands are possible, but for this reason (as well as other reasons that don't matter here — some aspects of interactive commands depend on the command symbol's property list, and that requires the command to be a symbol bound to an interactive function and not directly an interactive function). # Answer > 1 votes 1. You're missing a quote: `(funcall 'output-symbol ?\_)` If you want to call the `symbol-function` of the symbol `output-symbol` then you need to pass that symbol. To do that, quote it, so evaluating returns the symbol. 2. But you don't need to do that. To call a function whose name you already have, just call it directly: `(output-symbol ?\_)`. 3. But that's no good, because you need to bind a key to a *command*, that is, (1) a function that (2) has an `interactive` spec. ``` (defun output-symbol (symbol) (insert symbol)) (defun my-cperl-mode () "Perl mode customisations." (local-set-key (kbd "/") (lambda () (interactive) (output-symbol ?\_))) (local-set-key (kbd "_") (lambda () (interactive) (output-symbol ?\/)))) ``` Or just what you had in the beginning. Or just ``` (defun my-cperl-mode () "Perl mode customisations." (local-set-key (kbd "/") (lambda () (interactive) (insert ?_))) (local-set-key (kbd "_") (lambda () (interactive) (insert ?/)))) ``` --- Tags: key-bindings, symbols, funcall ---
thread-68515
https://emacs.stackexchange.com/questions/68515
How to programatically detect if a minor mode is global or local?
2021-09-15T16:05:11.350
# Question Title: How to programatically detect if a minor mode is global or local? Is there a way to programatically detect (in Elisp) if a minor mode is a global minor mode or a local minor mode? For instance I'd like to be able to detect that `show-paren-mode` is a global minor mode and that smart-dash-mode is a local minor mode. # Answer > 1 votes That information isn't stored, unfortunately. You *can* check whether the mode variable `show-paren-mode` is global or buffer-local: ``` (local-variable-if-set-p 'show-paren-mode) ``` That's not a guarantee (there's nothing stopping you giving a global mode a buffer-local value), but it's a reasonable heuristic. You might deal with that issue with: ``` (with-temp-buffer (local-variable-if-set-p 'show-paren-mode)) ``` # Answer > 0 votes In addition to Phils' answer, I noted that: * When checking if a minor-mode is local or global inside a function invoked for a major-mode by a hook, the code must **first** check if the mode variable is bound before doing the check with either `local-variable-if-set-p` or `local-variable-p`. Otherwise if the minor-mode is auto-loaded and not yet loaded, then both `local-variable-if-set-p` and `local-variable-p` return nil even if the minor-mode is a local minor-mode. I wanted to verify the validity of automatic minor-mode activation done by a hook for major-mode and generate a warning if a global minor-mode was activated via a hook meant to activate only local minor-modes (and vice-versa). If the minor-mode is auto-loaded and a major-mode is activated early (like when you start Emacs and open a file in that major mode right away) then the check would fail and warning generation was not reliable. Ideally the code would also detect that the variable is auto-loaded, load the file and check again. But that's out of the scope of the current question. --- Tags: minor-mode ---
thread-68520
https://emacs.stackexchange.com/questions/68520
How to programatically detect if a unbound symbol is part of an autoloaded file and what file that is?
2021-09-15T22:33:07.047
# Question Title: How to programatically detect if a unbound symbol is part of an autoloaded file and what file that is? Given a variable or a function symbol not currently bound, what would be the variable that holds the auto-loading association I could use to search for the symbol and find out what file would get loaded when it is invoked? # Answer You can use `symbol-function` to get the function associated with a symbol. If the function hasn’t been loaded yet, then this will be a list starting with the symbol `autoload` rather than an actual function object. The other elements in this list mean other things; in particular, the second element of the list is the name of the file to load. For example, if you run `(symbol-function '5x5)`, you may see something like this: ``` (autoload "5x5" 810998 t nil) ``` `autoloadp` will check that first element and return `t` if it is `'autoload`, but as far as I know the rest of the elements don’t have named accessor functions. Just use `cadr` or `second` or `(nth 2 …)` or whatever you prefer. > 2 votes # Answer Neither variable nor function. Autoloads are defined in (one or more) files. The default file for this is **`loaddefs.el`**, provided with Emacs. This is explained in the Elisp manual, node **`Autoload`**: > The command `M-x update-file-autoloads` writes a corresponding autoload call into `loaddefs.el`. (The string that serves as the autoload cookie and the name of the file generated by `update-file-autoloads` can be changed from the above defaults, see below.) Building Emacs loads `loaddefs.el` and thus calls autoload. `M-x update-directory-autoloads` is even more powerful; it updates autoloads for all files in the current directory. So you can have autoloads in any file you like, if you generate (or update) the file. Packages can provide an autoloads file as part of their recipe, for example. But the main - the default - autoloads file is `loaddefs.el`. --- If you or some program has never updated `loaddefs.el` then it is no doubt in the state in which it was delivered as part of Emacs. If you install some *packages* then likely associated autoloads files exist for some of them, and those autoload files are loaded when you install those packages. Then, when you invoke something that's autoloaded via one of those autoload files, the associated package gets loaded. If you know the package of some object (function, var, or other) you're interested in, then look for that package's autoloads file (e.g. in the package's directory). It contains the autoload associations you're asking about (for that package). --- On the other hand, if you just want to know if something is an autoload object (function or variable or sexp), use predicate `autoloadp`. > 0 votes --- Tags: autoload ---
thread-40817
https://emacs.stackexchange.com/questions/40817
Emacs picking the wrong browser
2018-04-03T17:11:42.290
# Question Title: Emacs picking the wrong browser I'm working under org-mode. When I click on a \[http://example.com\] link, it opens a tab in Firefox as expected. The `.emacs` config is: `'(browse-url-browser-function (quote browse-url-firefox))` However, for links in the form `file:///localdir/myfile.html` it depicts the message `running /usr/bin/sensible-browser` and starts Opera. Why would emacs do that? Why does it not use Firefox or defaults to my system default browser? # Answer > 4 votes Well, in a sense `sensible-browser` *is* a system default browser:-) I believe that you need to use the `update-alternatives` system to set that system default. As to why Org mode is using `sensible-browser` instead of the browse-URL functionality, I suspect it's because for file URLs it tries to be clever. # Answer > 2 votes `/usr/bin/sensible-browser` is a shell script. `/usr/bin/gnome-www-browser` has a high priority. File `sensible-browser`: ``` if test -n "$DISPLAY"; then if test -n "$GNOME_DESKTOP_SESSION_ID"; then if test -x /usr/bin/gnome-www-browser; then .... elif test -x /usr/bin/x-www-browser; then .... elif test -x /usr/bin/gnome-terminal && test -x /usr/bin/www-browser; ...... ``` So you can use ``` sudo update-alternatives --config gnome-www-browser ``` or ``` sudo update-alternatives --config x-www-browser ``` to select the default browser that org mode uses. # Answer > 1 votes There are lots of good reasons why it might not be useful to open a given `file:` URL in a web browser, so org has a distinct mechanism for handling them and deciding what to do with them. `M-x` `customize-option` `RET` `org-file-apps` `RET` But in practice, Bob Uhl's answer is probably what you want? If Firefox is your preferred browser, then you should probably have it set as your system default, rather than customizing multiple independent Emacs settings to override the system default in the same way. (Caveat: I don't know how `sensible-browser` makes its decision, so the situation might not be as simplistic as I've assumed.) --- Tags: html, web-browser ---
thread-28646
https://emacs.stackexchange.com/questions/28646
How to automatically highlight all the words same with selection just like Notepad++
2016-11-14T07:13:11.303
# Question Title: How to automatically highlight all the words same with selection just like Notepad++ For example when I select a word I want the same words to be automatically highlighted just like it in Notepad++: When I select the word "install" in Notepad++ (all other "install" are highlighted"): I'm using `spacemacs`. I tried the package `auto-highlight-symbol` and also the package `highlight-symbol`. Set mode to 1 in `.spacemacs`. But when I select a word no other same words highlighted: # Answer > 1 votes Use package highlight-symbol. ``` (use-package highlight-symbol :ensure t :init (add-hook 'prog-mode-hook 'highlight-symbol-mode)) ``` # Answer > 0 votes There are multiple packages that do this: They all perform the basics well enough. Although `idle-highlight` was the only package that worked well on large buffers. # Answer > 0 votes You don't need to use any external package. Take a look at the functions `isearch-forward-symbol-at-point` and `isearch-forward-symbol`. To find out if they're bound to a key on Spacemacs, evaluate `(where-is 'isearch-forward-symbol)`. --- Tags: syntax-highlighting, highlighting ---
thread-17283
https://emacs.stackexchange.com/questions/17283
Is it possible to get prettified symbols in Org-mode source blocks?
2015-10-10T20:18:50.487
# Question Title: Is it possible to get prettified symbols in Org-mode source blocks? I have a few symbols in `prettify-symbols-alist` that improve the appearance of elisp code in my configuration file. I am migrating my configuration file from Elisp to Org-mode and I would like to keep the prettified symbols. Is this possible to achieve in Org mode 8.3? # Answer > 4 votes If you want the symbols to be prettified in the whole org file, just define `prettify-symbols-alist` in the buffer and enable `prettify-symbols-mode`. But a better solution would ensure that these symbols are prettified **only** in the src blocks (and according to the language mode). Note that they are when editing the source block through `org-edit-src-code` (since the src block is copied in a buffer in the corresponding major mode). Looking at how src block fontification works (function `org-src-font-lock-fontify-block` in file `org-src.el`: 1. extract block as a string 2. insert it in a dedicated buffer 3. set language major mode 4. call font-lock-fontify-buffer 5. copy 'face properties from buffer to org buffer 6. mark text in org buffer as font-lock-fontified And seeing (function `enter prettify-symbols-mode` in file `prog-mode.el`) that symbol prettification relies on `'composition` properties, one can deduce we just need to change `org-src-font-lock-fontify-block` to make it copy `'composition` properties as well. Here is the modified function (see marked 'Addition' part): ``` (defun org-src-font-lock-fontify-block (lang start end) "Fontify code block. This function is called by emacs automatic fontification, as long as `org-src-fontify-natively' is non-nil." (let ((lang-mode (org-src--get-lang-mode lang))) (when (fboundp lang-mode) (let ((string (buffer-substring-no-properties start end)) (modified (buffer-modified-p)) (org-buffer (current-buffer)) pos next) (remove-text-properties start end '(face nil)) (with-current-buffer (get-buffer-create (concat " org-src-fontification:" (symbol-name lang-mode))) (delete-region (point-min) (point-max)) (insert string " ") ;; so there's a final property change (unless (eq major-mode lang-mode) (funcall lang-mode)) ;; Avoid `font-lock-ensure', which does not display fonts in ;; source block. (font-lock-fontify-buffer) (setq pos (point-min)) (while (setq next (next-single-property-change pos 'face)) (put-text-property (+ start (1- pos)) (1- (+ start next)) 'face (get-text-property pos 'face) org-buffer) (setq pos next)) ;; Addition: also copy 'composition info for prettified symbols (setq pos (point-min)) (while (setq next (next-single-property-change pos 'composition)) (put-text-property (+ start (1- pos)) (1- (+ start next)) 'composition (get-text-property pos 'composition) org-buffer) (setq pos next)) ;; End addition ) (add-text-properties start end '(font-lock-fontified t fontified t font-lock-multiline t)) (set-buffer-modified-p modified))))) ``` You have to ensure this is loaded after the definition in `org-src.el`. # Answer > 1 votes Org has native pretty symbol mode that you can enable with `C-c C-x C-\`. # Answer > 1 votes The correct command for org-mode native prettify symbols, `org-toggle-pretty-entities`, is `C-c C-x \` --- Tags: org-mode, prettify-symbols-mode ---
thread-68538
https://emacs.stackexchange.com/questions/68538
How to perform a multi-file regex-search with a regexp that encompass several lines?
2021-09-16T17:34:38.210
# Question Title: How to perform a multi-file regex-search with a regexp that encompass several lines? **Scenario**: I want to detect all `defcustom` sexp that have a `:set` or `:initialize` keyword in all Emacs Lisp files inside a directory tree. Searching for newline can be problematic depending of the regexp engine and the tool that uses it. Despite the following, I did not find something that works for several files: * `[^\0]` when back references and look-around are allowed. Unfortunately tools like deadgrep do not support them. * `C-q C-j` is another way but again several tools will not accept multiline regexp. * I have been able to use `"defcustom [[:ascii:]]+:\(\(type\)\|\(initialize\)\)"` with re-builder to validate that this works inside one file. It won't match text that includes non-ASCII characters, but that's probably OK. I guess I could write code that iterate across all files and use that expression or something like that. I would like to find an *Emacs-based* tool that would allow me to write a regexp that support identifying text spread across multiple lines and search for that in all files inside a directory tree without having to write my own. Does such an *Emacs-based* tool exist? # Answer I don't think you want to just use a single regexp to search for `defcustom`s that have either `:set` or `:initialize`, with (or without) any of those things possibly being on different lines. Why? Because a single regexp to find either `:set` or `:initialize`, or both, in either order, is complicated. Instead, you want to use Lisp syntax: find `(defcustom` but search the text between the beginning of that match and the **end of the `defcustom` sexp**. Search it for `:set`, then search it for `:initialize`, without worrying about which might come first or what lines they might be on. No complicated regexp. IOW, I'd suggest writing a function (command, if you like), that does something like this, in a loop for the file contents (starting from `(point-min)`, with that loop being within a loop over the files you want to search (e.g. `directory-files` or whatever): 1. `search-forward` for `(defcustom`. 2. Go to beginning of the match (`(match-beginning 0)`), and record that position (e.g. in a `let` var). 3. `forward-sexp` to get to the end of the `(defcustom...)` sexp, and record that position. 4. `save-restriction` and `narrow-to-region`. 5. `search-forward` from `(point-min)` for `:set`. If found, accumulate the region bounds as one of your search results, and loop for another search. If not found, go to step 6. 6. Do step 5, but with `:initialize` in place of `:set`. If you want to allow for whitespace between the `(` and the `defcustom`, then use `re-search-forward` with an appropriate regexp that allows for it. > 2 votes --- Tags: regular-expressions, search, newlines ---
thread-38836
https://emacs.stackexchange.com/questions/38836
How to run blocks/cells of python code in emacs?
2018-02-15T01:56:40.173
# Question Title: How to run blocks/cells of python code in emacs? https://i.stack.imgur.com/TIxlR.png The picture shows what I mean by "block" - I mean a cell of code that is delimited by some sequence of characters, in this case '#%%', that can be executed by the python/IPython console when the user types some keybinding while the cursor is in that cell. It's very useful for interactive/explorative work because you can break your code up into logical chunks where each part can be worked on iteratively without running the entire script each time. So if one part of my code ingests a large data frame and another part analyzes it, I can put each part in different cells so that while I'm playing around with how to best interpret the data I don't have to keep reloading the data frame on each iteration. If emacs can do this kind of block/cell execution, I will wholly devote myself to its religion. Right now I know of a few possible ways in vim, but suffice it to say they are all terrible. # Answer > 2 votes You can open a python process with `M-x run-python` or `C-c C-p`. Select the region (block) you want to execute and do a `M-x python-shell-send-region` or `C-c C-r` # Answer > 2 votes This package might be of use to you: https://github.com/astoff/code-cells.el It offers the ability to highlight cell borders, execute code cell-by-cell with the `#%%` syntax used to delimit cells, and some similar options. Doesn't have *everything* \- you seemingly cannot run a cell and move to the same cell in the same keystroke - and the `C-c %` prefix is a handful to say the least, but it works as far as I can tell. # Answer > 1 votes I use `ein`, which stands for emacs ipython notebook. It is the `jupyter notebook` implementation for emacs. See ein doc. Just like jupyter you execute cells and get back the output. The cells are saved in the notebook, so it is very useful and functional. You can also use org-babel, look at babel-doc And so save the cells in org files, also very functional. # Answer > 0 votes I've not personally done this with python, but there are several options. Org-mode lets you create a file containing source-code blocks and allows you to execute those blocks on demand. See chapter 14 of the org-mode manual for all of the details. You can mix source blocks of many languages in a single file, which is often nice. There are other ways to access a more traditional Python REPL inside of Emacs, however. The Emacs Wiki has much information on this and related subjects. I'm sure one of these can meet your needs. --- Tags: python, ipython ---
thread-68544
https://emacs.stackexchange.com/questions/68544
How note emacs shortcuts in kbd-style?
2021-09-17T08:32:06.547
# Question Title: How note emacs shortcuts in kbd-style? Emacs keyboard shortcuts are often written as inline code like `C-c C-p`. How should this be written in kbd-style? 1. `C-c` `C-p` 2. `C-c C-p` 3. `C-c`+`C-p` 4. `C`+`c` `C`+`p` 5. `Ctrl`+`c` **\>** `Ctrl`+`p` 6. or something else? Version 5 is taken from https://keycombiner.com/collections/emacs/ # Answer > 2 votes > 1. `C-c` `C-p` This is my preference. You can generate it easily with this: ``` (defun my-insert-kbd (keyseq) "Read key sequence, and insert it with <kbd> markup." ;; Simplified from https://emacs.stackexchange.com/a/2208 (interactive "kType key sequence: ") (insert "<kbd>" (mapconcat (lambda (s) (replace-regexp-in-string "<" "&lt;" s)) (split-string (help-key-description keyseq nil)) "</kbd><kbd>") "</kbd>")) ``` > 2. `C-c C-p` Still understandable. > 3. `C-c`+`C-p` Understandable, but no longer like the Emacs notation. > 4. `C`+`c` `C`+`p` Gosh, no. Certain to cause confusion. > 5. `Ctrl`+`c` **\>** `Ctrl`+`p` Fairly understandable, but nothing like the Emacs notation. Emacs notation should be used for consistency, so that's (1) or (2). --- Tags: keyboard ---