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-68534
https://emacs.stackexchange.com/questions/68534
Add custom entry to magit-dispatch
2021-09-16T14:27:23.900
# Question Title: Add custom entry to magit-dispatch One of the commands I find myself running very often is `git grep`. I would really like it to be accessible through the same `magit` menu as other commands. However, from my understanding of `magit.el`, it looks like the items there are hard-coded, and there's no way to add one more, unless I modify the source of this function. Am I wrong? Is there a better way? I read this answer: https://emacs.stackexchange.com/a/12739/563 but I cannot understand what arguments `transient-append-suffix` needs. Also, it looks like the answer is too old / maybe doesn't work anymore. --- ## What I have so far ``` (defun wvxvw-magit-grep (regex &optional args) (interactive (list (read-from-minibuffer "Expression: ") (transient-args 'magit-grep))) (let ((invert "") (extended "")) (while args (let ((val (car args))) (cond ((string-equal val "v") (setq invert "-v")) ((string-equal val "E") (setq extended "-E"))) (setq args (cdr args)))) (grep (format "git --no-pager grep -nH%s%s '%s'" invert extended regex)))) (defclass wvxvw-git-grep-expression-cls (transient-variable) ((scope :initarg :scope) (expression :initarg nil))) (transient-define-infix wvxvw-git-grep-expression-cmd () :class wvxvw-git-grep-expression-cls) (transient-define-prefix magit-grep () "Display git-grep command options." :man-page "git-grep" ["Arguments" ("-v" "Invert match" "-v") ("-E" "Extended regexp" "-E")] ["Actions" ("g" "Grep" wvxvw-magit-grep)]) (define-key magit-mode-map "G" 'magit-grep) ``` There's a thing I don't like about it: This doesn't actually add it to the `magit-dispatcher` menu, so, this isn't available if you press `h` in Magit status buffer. # Answer > 2 votes SECOND EDIT (in response to you edit) To format the expression differently, simply modify the string after the `:argument` keyword in your `magit:--grep-expression` argument definition (e.g. make it `"Expression: "`) To add the prefix to the magit-dispatch popup, simply do it like I explained in the original answer (replace `counsel-projectile-rg` by `magit-grep`) EDIT To bind a command directly in the `magit-status-mode-map`, bind it as follows using `define-key`: ``` (define-key magit-status-mode-map "G" 'counsel-projectile-rg) ``` I have bound it under `G` as `g` is already used as a prefix command in the magit-status buffer. END EDIT You can add a transient suffix with the following line of code: ``` (transient-insert-suffix 'magit-dispatch (kbd "h") '("G" "grep" counsel-projectile-rg)) ``` read the docstring of `transient-insert-suffix` for an explanation. There is also the command `transient-append-suffix` which works similarly. Here I am adding the command `counsel-projectile-rg`, which I use myself for this case (well actually I am just using the Spacemacs key-sequence `SPC /`), and which I can really recommend. There are equally good alternatives for helm, consult and probably more... also for other backends like `grep`, `ag` etc... --- Tags: magit ---
thread-68556
https://emacs.stackexchange.com/questions/68556
How to suppress `Type ‘C-c C-l’ to display results of compilation.` after compiling LaTeX file
2021-09-17T20:04:24.343
# Question Title: How to suppress `Type ‘C-c C-l’ to display results of compilation.` after compiling LaTeX file I am using following solution (https://emacs.stackexchange.com/a/65076/18414) to compile a `LaTeX` file: > ``` > (defun my-run-latex () > "Save all buffers and run LaTeX on the current master." > (interactive) > (let* ((TeX-command-force "LaTeX") > (TeX-clean-confirm t) > (TeX-save-query nil) > (master (TeX-master-file)) > (process (and (stringp master) (TeX-process master)))) > (TeX-save-document master) > (when (and (processp process) > (eq (process-status process) 'run)) > (delete-process process)) > (TeX-command-master))) > > ``` --- After each time when I run `my-run-latex` function I keep seeing the following message in the minibuffer: `Type ‘C-c C-l’ to display results of compilation.` Would it be possible to suppress this message? # Answer > 1 votes If you want to disable display of all `message`s: ``` (defun my-run-latex () "Save all buffers and run LaTeX on the current master." (interactive) (let* ((inhibit-message t) (TeX-command-force "LaTeX") (TeX-clean-confirm t) (TeX-save-query nil) (master (TeX-master-file)) (process (and (stringp master) (TeX-process master)))) (TeX-save-document master) (when (and (processp process) (eq (process-status process) 'run)) (delete-process process)) (TeX-command-master))) ``` Of course, you can set `inhibit-message` only on certain calls if you wanted to keep the message output of other calls. --- Tags: latex ---
thread-68552
https://emacs.stackexchange.com/questions/68552
Org Mode: Sort specific tree and refresh agenda
2021-09-17T17:28:31.953
# Question Title: Org Mode: Sort specific tree and refresh agenda Trying to create a single key that sorts a *specific* tree by date and then refreshes the agenda view. (I have other dependent functions such that I want to sort the actual tree and not just the agenda view.) **Initial state** ``` *Unrelated Tree ** TODO Not Sorted 1 DEADLINE: <2021-09-17> ** TODO Not Sorted 2 DEADLINE: <2021-09-14> * SortThis ** TODO Task A DEADLINE: <2021-09-16> ** TODO Task B DEADLINE: <2021-09-15> ======================= Agenda 09-14 Task: Deadline: TODO Not Sorted 2 Task: Deadline: TODO Task B => <2021-09-15> Task: In 2d: TODO Task A Task: In 3d: TODO Not Sorted 1 ``` **Desired State** after key press ``` *Unrelated Tree ** TODO Not Sorted 1 DEADLINE: <2021-09-17> ** TODO Not Sorted 2 DEADLINE: <2021-09-14> * SortThis ** TODO Task B DEADLINE: <2021-09-15> ** TODO Task A DEADLINE: <2021-09-16> ======================= Agenda 09-14 Task: Deadline: TODO Not Sorted 2 Task: In 1d: TODO Task B Task: In 2d: TODO Task A Task: In 3d: TODO Not Sorted 1 ``` Starting Code based on Sort entire hirearchy in an Org mode buffer ``` (defun sort-all-org-entries-redo () (interactive) (let ((fun #'(lambda nil (condition-case nil (org-sort-entries nil ?d) (user-error t))))) (org-map-entries fun)) (org-agenda-redo ())) (add-hook 'org-agenda-mode-hook (lambda() (local-set-key (kbd "g") 'sort-all-org-entries))) ``` Current issues 1. Sort function works on entire buffer, not a specific tree. How can I make it apply to just a single tree? 2. Function does not work between buffers. g in agenda buffer refreshes the agenda but does not sort the task buffer. M-x sort-all-org-entries performs the sort but does not refresh agenda. Is it even possible for a command to span separate buffers? # Answer > 0 votes Q1: If you look at the description of `org-map-entries` (with `C-h f org-map-entries`), you will see that it takes optional arguments, one of which is `scope`, which can take a bunch of different values, one of which is `tree`. The description says this: ``` SCOPE determines the scope of this command. It can be any of: ‘nil’ The current buffer, respecting the restriction, if any. ‘tree’ The subtree started with the entry at point. ... ``` Forgetting the agenda stuff, try changing the function to this: ``` (defun my/sort-subtree-org-entries () (interactive) (let ((fun (lambda () (condition-case nil (org-sort-entries nil ?d) (user-error t))))) (org-map-entries fun nil 'tree))) ``` Then position the cursor at the start of the subtree you want to sort and say `M-x my/sort-subtree-org-entries`. Note that it is important to be at the right place when you invoke the function. If you place the cursor at the beginning of the "Unrelated tree" and invoke the function, the "Unrelated tree" will be sorted. It is up to you to make sure that you are at the right position in the buffer when you invoke the function. Q2: Of course it is possible for a command to "span separate buffers" as you put it, but it does not happen magically: you (i.e. your function) have to make sure that the context is correct for each operation. You do that by selecting the correct buffer and moving `point` to the right place in the buffer (if necessary). In particular, if you look at the doc string of `org-agenda-redo` with `C-h f org-agenda-redo`, you will see that it says `Rebuild possibly ALL agenda view(s) **in the current buffer**.` IOW, you have to make sure that you are in the agenda buffer when you evaluate the call to `org-agenda-redo`. Similarly, you have to be in the file buffer where the entries to be sorted are, before you invoke `my/sort-subtree-org-entries`. Moreover, you have to be in the **right** place in the file buffer (at the beginning of the subtree to be sorted) before you invoke it. I'll do the easy part: you are in the file buffer and you want to sort a subtree and regenerate the agenda. I don't want to modify the sort function above to do two things, because the one thing that it does is useful and I might want to do that alone, not in combination with the agenda. Instead, I want to write another function that selects the agenda buffer and regenerates the agenda, and a third function that composes these two: it sorts the subtree by calling the first function and then regenerates the agenda by calling the second function. Here's the code: ``` (defun my/switch-to-agenda-and-redo () (with-current-buffer org-agenda-buffer (org-agenda-redo))) (defun my/sort-subtree-regenerate-agenda () (interactive) (my/sort-subtree-org-entries) (my/switch-to-agenda-and-redo)) ``` Now you can put your cursor in the right place at the beginning of the subtree to be sorted and say `M-x my/sort-subtree-regenerate-agenda`. I should point out that if you don't have an agenda buffer open, you are going to get an error: the `my/switch-to-agend-and-redo` function badly needs error handling, but the basic idea is there. Going in the other direction (from the agenda, switch to the file buffer and move to the right point, sort and then regenerate the agenda) is harder, because you have to figure out what file buffer the entry came from, then figure out how far up the tree to go to get to the right place for sorting. I *think* there is enough information in the agenda to determine the file buffer, but I don't think there is enough information to figure out the subtree (let's say you want to sort the second level subtree, but the entry in the agenda is a fourth level entry: how will the function know to go up to the second level and not stop at the third?) So I think your specification of the problem is incomplete: you will somehow have to provide that information to the function. BTW, the code is completely untested. --- Tags: org-mode, org-agenda ---
thread-9955
https://emacs.stackexchange.com/questions/9955
How do I turn off syntax coloring for lines that exceed the word-limit in prelude?
2015-03-12T08:37:25.373
# Question Title: How do I turn off syntax coloring for lines that exceed the word-limit in prelude? I'm using Prelude v 1.0.0. I want to turn off the syntax coloring when my lines exceed a certain word-limit. I don't know where that setting is set. Thanks! EDIT: I should be more precise. Prelude, by default, sets the color of the text from it's "normal" color to a brighter, more annoying color when it exceeds a certain word-limit. I'm trying to figure out where to tweak it in prelude. I'll give the below suggestion a whirl though. # Answer @lawlist is correct: This question is a (not-so-obvious) duplicate of How to change word wrap highlighting in Emacs on StackOverflow. Since we can't close questions against posts on other StackExchange sites, I'm going to repeat the answer that I gave over there: Highlighting of content that exceeds word wrap bounds is provided by `whitespace-mode` (which is actually a built-in mode). The Prelude documentation explains how to disable it: > **Disabling whitespace-mode** > > Although `whitespace-mode` is awesome some people might find it too intrusive. You can disable it in your personal config with the following bit of code: > > `(setq prelude-whitespace nil)` > 6 votes # Answer I know this question is already several years old, but for the benefit of people who have this problem and then find this page while searching for a solution: While looking at some variables (`C-h v whitespace`) that might have been the culprit, I discovered (to make a long story short): 1. `M-x customize-group RET whitespace` 2. Look for the category `Whitespace Style`. 3. Uncheck the box that says, `(Face) Lines, only overlong part`. 4. Finally, reload the major mode of the buffer you're working in (to see the changes right away.) Since Prelude is good about keeping Customize settings in a separate, dedicated file (`personal/custom.el`), this should be an easy-to-implement, working solution. > 1 votes # Answer Something along the liens of following should work: ``` (font-lock-add-keywords nil '(("^.\\{70,\\}$" 0 default prepend))) ``` I'm not sure if it blocks other keywords from considering same line but I'm sure it's possbile. Then you'll need to substitute "." with a word regexp, if it's important and adjust the number 70 according to your sepcification. > 0 votes --- Tags: syntax-highlighting, prelude ---
thread-68562
https://emacs.stackexchange.com/questions/68562
Is there any way to check if I'm under a heading using org-mode API?
2021-09-18T01:03:52.410
# Question Title: Is there any way to check if I'm under a heading using org-mode API? To be more specific, suppose I have an org-mode file with the following contents: ``` Foo * Heading1 Bar #+begin_src elisp (message "code") #+end_src ``` * If my current position is at `Foo`, then I'm not under a heading. * If my current position is at `Bar`, then I'm under a heading. * If my current position is at `(message "code")`, then I'm also under a heading. Is there any way to check it using elisp code? # Answer > 5 votes Sure: ``` (org-current-level) ``` returns `nil` at `Foo`; it returns 1 (or greater depending on the level) at `Bar` and similar places. EDIT: in answer to the OP's question about how I found this function: I knew about it already, so chalk it up to experience :-). That is not going to help, so here are some methods to use emacs to help you find such things. There is an almost universal convention that every package has a unique prefix associated with it; e.g. every function and every variable that Org mode defines starts with the prefix `org-` (there may be exceptions for some things that are meant for internal use only, but they are few and far between: certainly, every function and variable that is meant to be used to customize Org mode and many more besides obey the convention). Org mode also uses a sub-prefix for its major components, e.g Org babel functions are named with the prefix `org-babel-`, export functions use `org-export-` and so on. The next piece of the puzzle is that Emacs has a *fantastic* help system that every Emacs user should be familiar with. In particular, you can say `C-h f <function-name>` or `C-h v <variable-name>` or `C-h a <command-name>` and get information about the named function, named variable or command name (a function that has been marked `interactive` so you can run it with `M-x <command-name>`). The help system also allows access to the manuals, so `C-h i g(org)` displays the manual in Info and you can navigate and search using Info facilities. That is also indispensable to every Emacs user. And, icing on the cake, it also gives you help about *itself*: `C-h i ?` shows you a page of keys (including the above `f`, `v`, `a`) that let you ask Emacs about some aspect of its operation. Emacs has introspective capabilities that put most other software claiming such to shame - and it has had it for 30 years. One more piece that I use very frequently is completion: Emacs allows you to specify something partially and provides ways to complete the specification automatically (usually by pressing TAB or some such). There are many completion systems in use but the simplest is the one that is built into Emacs. In the case of interest, I can ask for information on a function whose name I don't know completely, but perhaps I can guess; e.g. in the case above, I know that the function, if it exists, would start with `org-` but I might also guess that the word `level` might appear in its name, so I say `C-h f org--level TAB` and I get 20 possibilities in a completion buffer, which I can scan quickly and see if something jumps out at me: `org-current-level` is there, so I click on it and I get the doc string of the function as if I had typed `C-h f org-current-level` in the first place. Another possibility is to go to the manual and search the index: `C-h i g (org) i level RET` and then cycle through all the occurrences with `,`. Unfortunately, the function above is not mentioned in the manual (probably because it is not useful to users of Org mode who want to customize it at the top level), so this method does not lead to any results. So it's a matter of luck to some extent, but knowing the above and biasing your search intelligently can allow you to find things easily and quickly. And the more experience you gain using these methods, the easier and quicker it becomes. # Answer > 2 votes That's what `(org-before-first-heading-p)` tells you. --- Tags: org-mode ---
thread-68504
https://emacs.stackexchange.com/questions/68504
Prefix-less superscript in org mode
2021-09-15T12:18:09.093
# Question Title: Prefix-less superscript in org mode I want to write «<sup>n</sup>P<sub>r</sub>» in org mode Now org mode doesn't treat "^" as a superscripting operator if its preceded by a space char. The best I could come up with was ``` \nbsp{}^nP_r ``` where there is a zero width space between the `n` and the `P`. This is quite clunky. Is there any better way? # Answer Well for now `${}^nP_r$` works... sorta kinda... The space between the "n" and the "P" is too much So I am doing `${}^n\!P_r$` > 1 votes --- Tags: org-mode ---
thread-68288
https://emacs.stackexchange.com/questions/68288
Error retrieving: https://elpa.gnu.org/packages/archive-contents
2021-08-27T17:27:02.350
# Question Title: Error retrieving: https://elpa.gnu.org/packages/archive-contents This is with the latest Emacs Version 27.2 (9.0) for Mac OS X: ``` error in process sentinel: Error retrieving: https://elpa.gnu.org/packages/archive-contents (error connection-failed "connect" :host "elpa.gnu.org" :service 443) [2 times] ``` I can access that address in a web browser fine. My `.emacs` file contains a basic package configuration: ``` (require 'package) (add-to-list 'package-archives '("melpa-stable" . "https://stable.melpa.org/packages/") t) (package-initialize) ``` I see others have this issue, but it's a very different issue, the answers suggest this was fixed in Emacs 27+, which I'm already using. Error retrieving: https://elpa.gnu.org/packages/archive-contents (error http 400) # Answer For me, a fix is: ``` (when (equal emacs-version "27.2") (setq gnutls-algorithm-priority "NORMAL:-VERS-TLS1.3")) ``` I found this at Error retrieving: https://elpa.gnu.org/packages/archive-contents (error http 400) EDIT: The problem is only on some platforms, so I've changed that to: ``` (when (and (equal emacs-version "27.2") (eql system-type 'darwin)) (setq gnutls-algorithm-priority "NORMAL:-VERS-TLS1.3")) ``` > 8 votes --- Tags: osx, package-repositories ---
thread-68550
https://emacs.stackexchange.com/questions/68550
How are program arguments handled when a program/script is launched from Emacs?
2021-09-17T16:03:34.573
# Question Title: How are program arguments handled when a program/script is launched from Emacs? I often find myself wondering how people handle program arguments when they are developing with Emacs. Let's say we have a Python script `test.py` and launching it *requires* supplying arguments, e.g. `--fname example.txt`. Most major modes feature a generic function like `python-shell-send-buffer` that effectively launches the script *without* supplying arguments. Of course one solution would be to adapt `test.py` to not take any arguments by hard-coding *default* arguments but this can hardly be considered good practice. How is this issue typically handled? (not necessarily Python-specific) # Answer > 0 votes The general approach is to leverage `compile`. You can find more information in the Emacs manual by evaluating `(info "(emacs) Compilation")`. Here's another good article by Mickey Petersen. --- Tags: python, debugging, major-mode, development ---
thread-68572
https://emacs.stackexchange.com/questions/68572
Get company to sort single underscore before double underscore, specifically with elpy/python-mode
2021-09-18T17:18:22.623
# Question Title: Get company to sort single underscore before double underscore, specifically with elpy/python-mode Edit: this question is a duplicate of this one; I'm leaving it because I got a helpful answer and I didn't find the other one after reasonable amount of searching (so I hope this one being here will double the liklihood of future searchers finding a solution) I use elpy with elpy-module-company as one of its modules. when I type "`self._`", the sorting causes it to propose all the dunders (`__annotations__`, `__class__`, &c) that I don't usually care about. I name some attributes starting with single underscore. I would like to see `self._method_i_wrote` sort before `self.__annotations__` I see that maybe `company-sort-predicate` is what I want, but I don't know how to write the predicate or tell company to use it. Can anyone give an example? I think hooking in the sort predicate I could figure out, but defining the sort predicate is beyond my elisp powers. An i-could-live-with-it solution (for what is admittedly a first world problem) would be a filter that tosses out dunders completely. # Answer > 1 votes You might find what you are looking for here: How to make private python methods the last company-mode choices? Here is a way I got strings to sort the way you described: ``` (sort '("_two" "_one" "__two" "__one" "one") (lambda (s1 s2) (if (and (string-prefix-p "_" s1) (string-prefix-p "_" s2)) ;; sort _ words by number of leading _, then lexically (let ((n1 (progn (string-match "\\(^_+\\)" s1) (length (match-string 0 s1)))) (n2 (progn (string-match "\\(^_+\\)" s2) (length (match-string 0 s2))))) (if (= n1 n2) ;; sort lexically (string< (substring s1 n1) (substring s2 n2)) ;; else by number of _ (< n1 n2))) ;; regular sorting (string< s1 s2)))) ``` This outputs `("_one" "_two" "__one" "__two" "one")` --- Tags: elpy, sorting, company ---
thread-68575
https://emacs.stackexchange.com/questions/68575
Lispy and Racket
2021-09-19T02:35:53.097
# Question Title: Lispy and Racket I'm using lispy with Racket and having a tough time with some forms. Namely, if I with to a `let` or keyword argument I can't seem to type the inner `[` character. For example, I want to define a function: ``` (define (my-func arg1 #:keyword-arg2 [arg2 arg2])) ``` So everything works fine until I get to the `[`. As soon as I press that key, the pointer moves back to the previous set of parentheses. Is there something I am doing wrong? # Answer Type C-q \[ to insert a single square bracket. As noted in the comments type } for a balanced pair of square brackets. > 1 votes # Answer As noted this is the keybindindgdefined by lispy - } is bound to lispy-brackets which inserts the pair \[\] I liked the idea of modes that lispy uses but found the keys too odd - I don't like or try to remember vi:) I found the package lispy-mnemonic useful as it rebinds keys to something that I found easier to remember. However I quickly found issues there and edited that mode heavily. I have kept the line for \[ so using this mode will solve that issue ``` (define-key lispy-mnemonic-mode-map (kbd "[") 'lispy-brackets) ``` So my recommendation is copy lispy-mnemonic and edit it to match your needs. As note in lispy-mnemonics README > Target Audience > If you: > would like to start learning Lispy > have played around with Lispy but not mastered it > haven't burned Vim-style key bindings into your muscle memory > find that mnemonics make it easier to learn and remember new commands and key bindings > ... there is a good chance you'll benefit from using lispy-mnemonic. > 1 votes --- Tags: parentheses, delimiters ---
thread-68578
https://emacs.stackexchange.com/questions/68578
Is there a way to delete the content under selected headers, but not the headers (and subheaders) themselves?
2021-09-19T12:20:27.167
# Question Title: Is there a way to delete the content under selected headers, but not the headers (and subheaders) themselves? Is there a way to delete the content under selected headers, but not the headers (and subheaders) themselves? I.e., ``` ** TOC *** PART 1: VECTORS AND GRAPHICS [[https://livebook.manning.com/book/math-for-programmers/chapter-2?origin=product-toc][READ IN LIVEBOOK]] **** [[https://livebook.manning.com/book/math-for-programmers/chapter-2?origin=product-toc][2DRAWING WITH 2D VECTORS]] [[https://livebook.manning.com/book/math-for-programmers/chapter-3?origin=product-toc][READ IN LIVEBOOK]] ``` to ``` ** TOC *** PART 1: VECTORS AND GRAPHICS **** [[https://livebook.manning.com/book/math-for-programmers/chapter-2?origin=product-toc][2DRAWING WITH 2D VECTORS]] ``` # Answer Here is a way to do that: I collect each heading, then replace the buffer with just the headings. This also preserves properties on headlines: ``` (defun strip-headings () (interactive) (setf (buffer-string) (string-join (cl-loop for headline in (org-element-map (org-element-parse-buffer) 'headline 'identity) collect (progn (goto-char (org-element-property :begin headline)) (buffer-substring (point) (progn (org-end-of-meta-data) (point))))) "\n"))) ``` > 1 votes # Answer It just occurred to me that I can do this with PCRE easily: `perl -ne '/^(?!\*+).*\S+.*/ || print'` I'd still like to see a structural solution that uses org-mode's parse tree, and not regexes. > 0 votes --- Tags: org-mode, regular-expressions, text-editing ---
thread-68547
https://emacs.stackexchange.com/questions/68547
Is it possible automate switch to window *Completions*?
2021-09-17T14:13:48.400
# Question Title: Is it possible automate switch to window *Completions*? Linux Mint 20 Emacs 27.1 Install package: Consult, Vertico, Embark Steps: ``` M-x shell ``` Input ``` cat test. ``` and press **TAB** Open window `*Completions*` with possible candidates. Nice... but the cursor is not focus on this buffer. Cursor is still stay on shell buffer. So as result I need to press `M-<arrow down>` `(windmove-down)` to switch to window `*Completions*` and select desire candidate. It's not very convenient. Is it possible when press `TAB` to **automate** switch to window `*Completions*` ? # Answer > 0 votes Here solution: In my init.el ``` (require 'consult) ;; Auto switch to buffer *Completition* when press TAB. ;; Use `consult-completion-in-region' if Vertico is enabled. ;; Otherwise use the default `completion--in-region' function. (setq completion-in-region-function (lambda (&rest args) (apply (if vertico-mode #'consult-completion-in-region #'completion--in-region) args))) ``` Here help: consult-completion-in-region --- Tags: selected-window, consult ---
thread-68585
https://emacs.stackexchange.com/questions/68585
Dired mode: Toggle show hidden files/folders by keyboard shortcut
2021-09-19T18:33:49.673
# Question Title: Dired mode: Toggle show hidden files/folders by keyboard shortcut I am using Emacs 27.1 (`GNU Emacs 27.1 (build 1, x86_64-pc-linux-gnu, GTK+ Version 3.24.24, cairo version 1.16.0) of 2021-03-28, modified by Debian`) with "default" dired mode. There are no settings or extra packages related to dired mode in my `init.el`. By default I see hidden (dotted) files and folders. Can I toggle that with a key shortcut? # Answer > 3 votes What is your value of option `dired-listing-switches` (press `M-:` and type `dired-listing-switches`)? Customize it to use a value that does not list hidden files. In other words, this is about the switches you tell Dired to use with `ls`. You can also change the switches anytime, for a given Dired buffer, by invoking `dired` with a prefix arg (e.g. `C-u`). For example, removing `a` from `dired-listing-switches` will likely do what you want: prevent listing files whose names start with `.`. # Answer > 5 votes Bind a key to `dired-omit-mode` (you may need to require `dired-x` first) and set `dired-omit-files` something like this: ``` (setq dired-omit-files (rx (or (seq bol (? ".") "#") ;; emacs autosave files (seq bol "." (not (any "."))) ;; dot-files (seq "~" eol) ;; backup-files (seq bol "CVS" eol) ;; CVS dirs )) ``` --- Tags: dired ---
thread-68589
https://emacs.stackexchange.com/questions/68589
In org-mode refresh the numbers in a numbered list
2021-09-19T21:09:50.787
# Question Title: In org-mode refresh the numbers in a numbered list I am in Org Mode and I have a numbered list. ``` 1. Hello 2. World 3. How 4. Ya 5. Doing? ``` I remove the first entry to get the following. ``` 2. World 3. How 4. Ya 5. Doing? ``` Is there a shortcut to refresh the numbering, and to end up with the following? ``` 1. World 2. How 3. Ya 4. Doing? ``` # Answer > 7 votes With point anywhere in the list, press `C-c``C-c`. It runs `org-ctrl-c-ctrl-c` which does many things depending on the context, see its documentation. --- Tags: org-mode ---
thread-68595
https://emacs.stackexchange.com/questions/68595
How to prevent `()` added during company completions
2021-09-20T17:59:17.150
# Question Title: How to prevent `()` added during company completions In company-mode, when I apply `company-complete-selection`, it completes variable but sometimes adds `()` at the end of it. Would it be possible to prevent this in all cases? Example: which completed as: `self.logged_jobs_to_process()` --- my setup: ``` (add-hook 'after-init-hook 'global-company-mode) (setq company-auto-commit t) (setq company-auto-complete t) (global-set-key (kbd "C-c C-k") 'company-complete) (setq company-frontends '(company-pseudo-tooltip-unless-just-one-frontend company-preview-frontend company-echo-metadata-frontend)) ``` --- `M-x company-diag` returns: ``` Emacs 28.0.50 (x86_64-pc-linux-gnu) of 2021-09-01 on home Company 0.9.13 company-backends: (company-bbdb company-semantic company-cmake company-capf company-clang company-files (company-dabbrev-code company-gtags company-etags company-keywords) company-oddmuse company-dabbrev) Used backend: company-capf Value of c-a-p-f: (lsp-completion-at-point) Major mode: python-mode Prefix: "None" Completions: #("None" 0 4 (lsp-completion-item #s(hash-table size 7 test equal rehash-size 1.5 rehash-threshold 0.8125 data ("label" #("None" 0 4 (match-data (0 4 0 1 1 2 2 3 3 4))) "kind" 14 "sortText" "aNone" "insertText" "None" "data" #s(hash-table size 1 test equal rehash-size 1.5 rehash-threshold 0.8125 data ("doc_uri" "file:///home/alper/ebloc-broker/broker/Driver.py")) "_emacsStartPoint" 3652)) lsp-sort-text "aNone" lsp-completion-start-point 3652 lsp-completion-markers (3652 #<marker (moves after insertion) at 3656 in Driver.py>) lsp-completion-prefix "None" match-data (0 4 0 1 1 2 2 3 3 4) face (completions-common-part))) " (Keyword)" ``` # Answer \[UPDATED\] After the output of `M-x company-diag` was posted it became clear, according to the `Value of c-a-p-f: (lsp-completion-at-point)`, that `lsp-mode` is responsible for the completion in this case. Eventually, after contacting both `lsp-mode` and `python-lsp-server` maintainers, it was clarified that this `lsp-mode` setting has to be disabled to prevent completion with parentheses: ``` (setq lsp-enable-snippet nil) ``` \[EARLIER ANSWER, suitable for the `company-clang` backend.\] I assume that the backend in action is `company-clang`. (If not, add the output of `M-x company-diag` to your question.) Then, the addition of the parentheses can be prevented by disabling this `company-clang` *user option*: ``` (setq company-clang-insert-arguments nil) ``` But note that it's going to *disable* insertion of arguments. For example, Completes to only if `company-clang-insert-arguments` is enabled. > 1 votes --- Tags: company ---
thread-68524
https://emacs.stackexchange.com/questions/68524
How do I make `helm` save search results in a grep buffer?
2021-09-15T22:52:47.247
# Question Title: How do I make `helm` save search results in a grep buffer? I do `helm-find-files` (`C-x c C-x C-f`\>), `Tab`, "Grep current directory with AG" (`M-g a`), enter pattern, `Tab`, "Save results in grep buffer" (`F3`). Now, how do I make `M-g M-n`/`M-g M-p` work with `helm` in a sibling buffer, like with `rgrep`? I was able to achieve this with `projectile` \+ `rg` (`C-c p s r`). # Answer > 1 votes I don't see a feature like that in helm-grep. But you should achieve the desired result with a function like this one ``` (defun my/jump-next-grep-result () (interactive) (other-window 1) (next-logical-line) (helm-grep-mode-jump-other-window-forward 1) (other-window -1)) ``` --- Tags: helm, grep, rgrep, ag, ripgrep ---
thread-68606
https://emacs.stackexchange.com/questions/68606
Expand variable and transform it in a quoted list
2021-09-21T19:24:02.903
# Question Title: Expand variable and transform it in a quoted list The function `cycle-themes` have `cycle-themes-theme-list` as a quoted list, e.g., `(setq cycle-themes-theme-list '(tsdh-light wheatgrass whiteboard womba))`. At the same time, `(custom-available-themes)` will return all available themes. How do I apply the `quote` to this expanded list? ``` #+begin_src emacs-lisp (use-package cycle-themes :ensure t :init (setq cycle-themes-theme-list (quote-after-expand (custom-available-themes)))) #+end_src ``` # Answer You just need ``` (setq cycle-themes-theme-list (custom-available-themes)) ``` here (try it!). `cycle-themes-theme-list` just wants a list. The point of the quote in ``` (setq cycle-themes-theme-list '(tsdh-light wheatgrass whiteboard womba)) ``` is to prevent elisp from evaluating the target list (and so treating `tsdh-light` as a function with arguments `wheatgrass`, `whiteboard` and `womba`). > 1 votes --- Tags: quote ---
thread-68561
https://emacs.stackexchange.com/questions/68561
How to activate functions on .org files from within agenda view?
2021-09-17T23:29:13.720
# Question Title: How to activate functions on .org files from within agenda view? From agenda view, is it possible to execute functions on specific .org files? *Example setup: `foo.org` and `bar.org` are source files for agenda* *Example working function from :* Sort entire hierarchy in an Org mode buffer ``` (defun sort-all-org-entries () (interactive) (let ((fun #'(lambda nil (condition-case nil (org-sort-entries nil ?d) (user-error t))))) (org-map-entries fun))) (add-hook 'org-agenda-mode-hook (lambda() (local-set-key (kbd "g") 'sort-all-org-entries))) ``` The example function `sort-all-org-entries` works correctly if `M-x sort-all-org-entries` is activated in the buffer for either foo.org or bar.org. However, when `g` is pressed in the agenda buffer, the function is presumably executed only in the agenda as it presumably does not have a target .org file. **edit** Is there a way to define `g` to execute `sort-all-org-entries` at the beginning of `foo.org`, even though `g` is activated from the agenda buffer? # Answer > 1 votes **Edit: New solution based on comment recommendations** `with-current-buffer` is a useful command for temporarily working within a buffer. This can be used to execute the function without leaving the agenda buffer. ``` (defun sort-all-org-entries () (interactive) (with-current-buffer "foo.org" (let ((fun #'(lambda nil (condition-case nil (org-sort-entries nil ?d) (user-error t))))) (org-map-entries fun)) (org-agenda-redo())) (add-hook 'org-agenda-mode-hook (lambda() (local-set-key (kbd "g") 'sort-all-org-entries))) ``` **Following code also works, but is susceptible to errors as detailed in comments.** `switch-to-buffer` allows selection of a buffer. However, intended use is not for temporary functions. ``` (defun sort-all-org-entries () (interactive) (switch-to-buffer "foo.org") ## active buffer to execute function (let ((fun #'(lambda nil (condition-case nil (org-sort-entries nil ?d) (user-error t))))) (org-map-entries fun)) (switch-to-buffer()) ## returns to previous buffer (agenda) (org-agenda-redo())) ## refreshes agenda to reflect function effect (add-hook 'org-agenda-mode-hook (lambda() (local-set-key (kbd "g") 'sort-all-org-entries))) ``` --- Tags: org-mode, org-agenda, sorting ---
thread-68598
https://emacs.stackexchange.com/questions/68598
Count Words in a Rectangle
2021-09-21T05:19:25.513
# Question Title: Count Words in a Rectangle When I select a rectangle and count the words (`M =`) in the selection it counts as if I had used the normal selection method. Is there a way to count only in the rectangle? # Answer This function will probably suit you ``` (defun rectangle-count-words (start end) "count the words in the delimited rectangular region from start to end" (interactive "r") (let ((rect (mapconcat #'substring-no-properties (extract-rectangle start end) " "))) (with-temp-buffer (insert rect) (princ(count-words (point-min) (point-max)))))) ``` You can bind it to your favorite key. > 3 votes # Answer ``` (defun ph/count-words-in-rectangle (start end) "Count words in rectangle defined by START and END." (interactive "r") (copy-rectangle-as-kill start end) (with-temp-buffer (yank-rectangle) (call-interactively #'count-words))) ``` Still outputs "Region has..." instead of "Rectangle has..." but otherwise does what you want, I think. (This is effectively the same thing that @dalanicolai proposed in a comment above). > 1 votes # Answer I just added command **`count-words-rectangle`** to my little file `misc-cmds.el`. Unlike `count-words` and `count-words-region`, by default this does not count "words" that straddle the beginning or end of a rectangle row. If you use a prefix arg then such partial words at row boundaries are counted. `count-words-region` counts as a "word" a *piece* of a word when the whole word starts before the beginning, or ends after the end, of the region. I think it's more useful, and more likely to be what someone expects, to count only words that are entirely within the region. But that ship has sailed... ``` (defun count-words-rectangle (start end &optional allow-partial-p msgp) "Count words in the rectangle from START to END. This is similar to `count-words', but for a rectangular region. Also: * By default, a word that straddles the beginning or end of a rectangle row is not counted. That is, this counts only words that are entirely within the rectangle. * A prefix arg means count also such partial words at row boundaries. If called interactively, START and END are the bounds of the start and end of the active region. Print a message reporting the number of rows (lines), columns (characters per row), words, and characters. If called from Lisp, return the number of words in the rectangle between START and END, without printing any message." (interactive "r\nP\np") (let ((bounds (extract-rectangle-bounds start end)) (words 0) (chars 0)) (dolist (beg+end bounds) (setq words (+ words (count-words (car beg+end) (cdr beg+end))))) (let (beg end) (dolist (beg+end bounds) (setq beg (car beg+end) end (cdr beg+end)) (unless allow-partial-p (when (and (char-after (1- beg)) (equal '(2) (syntax-after (1- beg))) (char-after beg) (equal '(2) (syntax-after beg))) (setq words (1- words))) (when (and (char-after (1- end)) (equal '(2) (syntax-after (1- end))) (char-after end) (equal '(2) (syntax-after end))) (setq words (1- words)))))) (when msgp (dolist (beg+end bounds) (setq chars (+ chars (- (cdr beg+end) (car beg+end))))) (let ((rows (count-lines start end)) (cols (let ((rpc (save-excursion (rectangle--pos-cols (region-beginning) (region-end))))) (abs (- (car rpc) (cdr rpc)))))) (message "Rectangle has %d row%s, %d colum%s, %d word%s, and %d char%s." rows (if (= rows 1) "" "s") cols (if (= cols 1) "" "s") words (if (= words 1) "" "s") chars (if (= chars 1) "" "s")))) words)) ``` (I wish `count-words` and `count-words-region` optionally did the same - counted only words entirely within bounds. But their code is old and needs to be backward-compatible, and a prefix arg already has a different meaning there, so it's maybe not worth trying to fix that.) --- **Update** I added showing this in the mode-line, whenever a rectangle command is invoked. This is in library `modeline-posn.el`. To choose it, just customize option `modelinepos-rectangle-style`, choosing **Rows, columns, words, chars**, instead of the default, **Rows and columns**. (For this, you also need library `misc-cmds.el`.) > 0 votes --- Tags: rectangle ---
thread-68608
https://emacs.stackexchange.com/questions/68608
command print no results with (interactive "r")
2021-09-21T20:53:05.547
# Question Title: command print no results with (interactive "r") Consider this test function (tested in emacs -q): ``` (defun foo (start end) "for testing purposes" (interactive "r") (when (region-active-p) (cons start end))) ``` Calling `M-x foo` gives no results printed in the minibuffer, even when a region is active. If I evaluate `M-: (call-interactively #'foo)` the cons is printed in the minibuffer. I'd be happy to know why nothing is printed with `M-x foo`. # Answer You're confusing the echoing of the return value by `M-:` with the action of `M-x`. `M-:` expressly evaluates a sexp *and* prints the resulting value. `M-x` invokes a command. Your command does not, itself, print or echo or otherwise display its return value. If you want your command to echo the value, then use function `message`: ``` (when (region-active-p) (let ((val (cons start end))) (message "Result: %S" val) val)) ``` > 3 votes --- Tags: functions, interactive, echo-area, print ---
thread-68593
https://emacs.stackexchange.com/questions/68593
Sorting lines based on numbers in unicode
2021-09-20T05:10:21.207
# Question Title: Sorting lines based on numbers in unicode I want to sort some text in emacs that is based on a field that contains verse numbers in unicode (devanagari). The text is like this: ``` Verse text bla १०.३ #10.3 Verse text blah This is १.१९ #1.19 Verse text ble १०.१३ #10.13 Verse text bleh ६.२७ #6.27 Verse text blu १९.२ #19.2 Verse text bluh ४.७ #4.7 ``` I've added the corresponding arabic numerals with `#` at the end of each line (these will not appear in the original text). I've been able to do with python. Firstly, I wrote a function `get_num()` that converts the unicode text into an arabic decimal. Later, I used `sorted()` with a custom key function for sorting. Is it possible to achieve this level of customized sorting with an elisp function? I looked at `sort-regexp-fields` and `sort-fields` but haven't understood if they are as customizable as python's `sorted()` Below is the python code for reference: ``` In [87]: inp Out[87]: ['Verse text bla १०.३ #10.3 ', 'Verse text blah This is १.१९ #1.19 ', 'Verse text ble १०.१३ #10.13 ', 'Verse text bleh ६.२७ #6.27 ', 'Verse text blu १९.२ #19.2 ', 'Verse text bluh ४.७ #4.7 '] In [88]: myre = re.compile(r'([०१२३४५६७८९]+\.[०१२३४५६७८९]+)') In [90]: def get_num(inp): ...: parts = inp.split('.') ...: p1 = ''.join([str(ord(x) - 2406) for x in parts[0]]) ...: p2 = ''.join([str(ord(x) - 2406) for x in parts[1]]) ...: return '{}.{}'.format(p1, p2) In [91]: sorted(inp, key=lambda x: [int(i) for i in get_num(myre.search(x).group()).rstrip(".").split('.')]) Out[91]: ['Verse text blah This is १.१९ #1.19 ', 'Verse text bluh ४.७ #4.7 ', 'Verse text bleh ६.२७ #6.27 ', 'Verse text bla १०.३ #10.3 ', 'Verse text ble १०.१३ #10.13 ', 'Verse text blu १९.२ #19.2 '] ``` # Answer > 2 votes Use `seq-sort-by` instead of `sort-regexp-fields`. Therewith, you can specify a function to extract the key from the strings and a sort function. In your case `string<` fits as lexicographical sort function when you interpret the numbers as characters in the string. That works if the numbers don't exceed `(max-char)` giving 4194303 in my case. ``` (defun devanagari-to-num (devanagari) "Convert a devanagari-string encoded number into a number. Return 0 if DEVANAGARI is not a devanagari-string encoded number." (condition-case nil (string-to-number (apply #'string (seq-map (lambda (x) (+ x (- ?0 ?०))) devanagari))) (error 0))) ;; Test: (devanagari-to-num "१०") (seq-sort-by (lambda (s) (if (string-match "\\([०१२३४५६७८९]+\\)\\(?:\\.\\([०१२३४५६७८९]+\\)\\)?" s) (string (devanagari-to-num (match-string 1 s)) (devanagari-to-num (or (match-string 2 s) ""))) "")) #'string< (split-string "Verse text bla १०.३ #10.3 Verse text blah This is १.१९ #1.19 Verse text ble १०.१३ #10.13 Verse text bleh ६.२७ #6.27 Verse text blu १९.२ #19.2 Verse text bluh ४.७ #4.7 " "\n")) ``` If the numbers exceed `(max-char)` in your case you need to replace `#'string<`and the call to `string` with appropriate othere functions. # Answer > 2 votes EDIT To also sort the string with the pattern you gave in the comments (but alternated with a variable number of words), you can use the following function to split the strings, and use it('s result) in Tobias his answer: ``` (defun split-string-on-devanagari () (interactive) (let (substrings (start (goto-char (point-min)))) (while (search-forward-regexp "\\([०१२३४५६७८९]+\\)\\(?:\\.\\([०१२३४५६७८९]+\\)\\)?" nil t) (push (buffer-substring-no-properties start (match-end 0)) substrings) (unless (eobp) (forward-char) (setq start (point)))) (nreverse substrings))) ``` END EDIT Well, there are many ways to do this. From your python code (and because they do not appear in the original text), I infer that we should really use the devanagari numbers for sorting. So then one way to achieve this is by first replacing the devanagari numbers by latin numbers, then use `sort-numeric-fields` on the last field (i.e. using negative field number), and then replace back the devanagari numbers. You can achieve that with the following code ``` (require 'cl-lib) (defun replace-all (from to) (goto-char (point-min)) (while (search-forward from nil t) (replace-match to))) (defun sort-lines-by-devanagari-nums () (interactive) ;; create number pairs (uses cl-lib) (let ((num-pairs (cl-mapcar (lambda (x y) (cons x y)) (split-string "0123456789" "" t) ;; create list of devanagari number strings (mapcar 'char-to-string (number-sequence 2406 2415))))) ;; replace (dolist (x num-pairs) (replace-all (cdr x) (car x))) ;; sort (sort-numeric-fields -1 (point-min) (point-max)) ;; replace (dolist (x num-pairs) (replace-all (car x) (cdr x))))) ``` After evaluating the above code, run `M-x sort-lines-by-devanagari-nums` to sort the text in your original buffer (without the latin numbers. Otherwise change -1 to -2, although this would replace the latin numbers also with the devanagari numbers). For an alternative approach, that would be more similar to your given python example, you could hack something using e.g. `seq-sort-by` (see very basic example here). --- Tags: sorting, lines ---
thread-68615
https://emacs.stackexchange.com/questions/68615
error running emacs on macOS big sur, "because Apple cannot check it for malicious software"
2021-09-22T08:05:07.403
# Question Title: error running emacs on macOS big sur, "because Apple cannot check it for malicious software" I recently got an MacBook Pro running MacOS Big Sur and of course the first thing I went to install was emacs. I tried both using Homebrew and MacPorts to do so. Both of them produce the same pop up error box when starting and refuse to run. I haven't yet tried building from sources, and will do so if that will solve this issue. However, if there is another solution before I do that, I will apply that. Some setting in the OS I can apply for instance saying "don't check this for malware". # Answer > 2 votes I found a relevant answer on the AskDifferent exchange: Apps that are not distributed via the AppStore now require Notarization on top of being signed by a paid Apple Developer ID which means the developer must submit their application to Apple for review so that Apple can issue a notarization signature the developer can "staple" apply to the App. Otherwise you will see that warning and the App will not run by default. To work around the problem: Open the /Applications folder with Finder. Right-click the Emacs application icon and select Open. A dialog will appear and you can allow the App to open. The App might immediately quit, try opening the App normally and this time it should work. Send an email to the software vendor and ask them to Notarize their App for the newer macOS versions. At some point in the future, Apple may remove the ability to work around running an App that hasn't been notarized. --- Tags: osx ---
thread-68621
https://emacs.stackexchange.com/questions/68621
Does elisp have a way to jump to (goto) labels in the code, ala common lisp's go?
2021-09-22T15:56:35.520
# Question Title: Does elisp have a way to jump to (goto) labels in the code, ala common lisp's go? Does elisp have a way to jump to (goto) labels in the code, ala common lisp's go? ``` (tagbody (setq val 2) (go lp) (incf val 3) lp (incf val 4)) => NIL val => 6 ``` PS: This is a question about control flow, not jumping to locations in files. # Answer It works exactly the same, we just need to use `cl-tagbody` instead. ``` (cl-tagbody (setq val 2) (go lp) (incf val 3) lp (incf val 4)) val ``` ``` 6 ``` > 3 votes --- Tags: elisp, common-lisp, cl ---
thread-68604
https://emacs.stackexchange.com/questions/68604
How to prevent smartparens slurp from slurping item separator?
2021-09-21T17:56:24.077
# Question Title: How to prevent smartparens slurp from slurping item separator? I am looking into Erlang support for `smartparens` and would like to be able to slurp a string into the current list without including the Erlang statement termination colon in the list. In an `erlang-mode` buffer, with point identified as ∎, if I start with: ``` Name = ∎"Joe". ``` and then type `[` which is paired so I get: ``` Name = [∎]"Joe". ``` If I then execute `sp-forward-slurp-sexp`, the result is: ``` Name = [∎"Joe".] ``` What would be the standard way to update smartparens support to end up instead with the following?: ``` Name = [∎"Joe"]. ``` # Answer > 0 votes I found out that `smartparens` has a similar command that has slightly different behaviour and works better with Erlang or languages that use separators like C. The command is `sp-slurp-hybrid-sexp`. With it I get the result I wanted: ``` Name = [∎"Joe"]. ``` Unfortunately neither command work perfectly to slurp items and handle separator in all cases. Slurping from `[1,2,3], 4, 5` may end up with `[1,2,3 4], 5` or `[1,2,3 4],,5`. I assume that more work is required to properly support Erlang and some extra learning of the implementation logic is required. **Update - To properly fix the issue : use a function that fix the block:** My final solution to this problem was to write a function that checks the validity of the comma separated block and fix it if it's invalid. Then add that function as a post handler for Erlang operation. The function I wrote for this is `pel-syntax-fix-block-content`, available in this answer. The I wrote the following and my init calls `pel-smartparens-setup-erlang` when smartparens cod in an erlang-mode buffer: ``` (defun pel-sp-erlang-handler (_id action _context) "Check validity of block and fix it if it was broken by smartparens. This is a smartparens post-handler and receives 3 arguments: ID, ACTION and CONTEXT." (when (memq action '(slurp-forward barf-forward split-sexp)) (pel-syntax-fix-block-content (- (point) 2)) (forward-char 2))) (defun pel-smartparens-setup-erlang () "Configure smartparens for Erlang. This must be called within the scope of a erlang-mode buffer." (sp-local-pair 'erlang-mode "(" ")" :actions '(insert wrap autoskip navigate) :post-handlers '(pel-sp-erlang-handler)) (sp-local-pair 'erlang-mode "[" "]" :actions '(insert wrap autoskip navigate) :post-handlers '(pel-sp-erlang-handler)) (sp-local-pair 'erlang-mode "{" "}" :actions '(insert wrap autoskip navigate) :post-handlers '(pel-sp-erlang-handler)) (sp-local-pair 'erlang-mode "<<" ">>" :actions '(insert wrap autoskip navigate) :post-handlers '(pel-sp-erlang-handler))) ``` --- Tags: balanced-parentheses, smartparens, erlang-mode ---
thread-68626
https://emacs.stackexchange.com/questions/68626
How to remove an item from a list of unique items, returning true on success?
2021-09-23T01:19:55.063
# Question Title: How to remove an item from a list of unique items, returning true on success? Sometimes a list is known to contain a list of unique items, where it is useful to check if the item exists in the list, removing it if it does. This is an inefficient way to accomplish this: ``` (defmacro if-pop-value (value place) "Destructively remove VALUE from PLACE. With a non-nil result when the value was removed." `(let ((test ,value)) (if (memq test ,place) (progn (setq ,place (delq test ,place)) t) nil))) ``` Assuming `place` refers to a set of unique items, is there a more efficient way to remove the item without 2x lookups? # Answer > 1 votes The problem you have here is an impedance mismatch caused by the return value. Your code returns `t` if the element was removed, and `nil` otherwise. `delq`, on the other hand, returns the new list. Determining the correct return value requires searching either the old list before calling `delq`, or the new list after calling it. Or you could just avoid calling `delq` by iterating over the list yourself: ``` (defmacro if-pop-value (value place) `(let ((test ,value) (list ,place)) (if (null list) nil (if (eq test (car list)) (prog1 t (setf ,place (cdr list))) (let ((rv nil)) (progn (mapl (lambda (l) (when (eq test (cadr l)) (setcdr l (cddr l)) (setq rv t))) list)) rv))))) ``` (The macro you just posted as an answer would work just as well.) Or, alternatively, you could restructure your program so that it doesn’t rely on this return value. That is, it simply removes elements from the list without caring before–hand whether the element is present, or afterwards without caring whether something was removed. This may not always be possible, so I must leave it for you to consider. # Answer > 0 votes This is a macro which removes the value from a list, resulting in `t` on success. ``` (defmacro if-pop-value (value place) "Destructively remove VALUE from PLACE. With a non-nil result when the value was removed." `(let ((test ,value) (iter ,place) (prev nil) (result nil)) (while iter (let ((next (cdr iter))) (cond ((eq test (car iter)) (if prev (setcdr prev next) (setf ,place next)) (setq result t) (setq iter nil)) (t (setq prev iter) (setq iter next))))) result)) ``` --- Tags: list ---
thread-68625
https://emacs.stackexchange.com/questions/68625
How to disable evil insert key in read only mode
2021-09-23T00:19:07.317
# Question Title: How to disable evil insert key in read only mode I want to disable evil insert key such as `a`, `i`, `o` in `read-only` mode (keep navigation key such as `j` and `k`), my idea is to disable these keys in local buffer when enabling `read-only` mode and enable these keys after disabling `read-only` mode. There are two difficulties for me: 1. How to disable evil insert key. 2. How to execute code when enable/disable mode. I notice there is `evil-disable-insert-state-bindings` variable. I try to set it to `t` in local buffer, but `a`, `i` keys still work. I know I can use `(add-hook 'read-only-mode-hook (lambda () (message "read-only-mode changed")))` to detect mode change, but I don't know how to distinguish enabling and disabling mode. # Answer For read-only buffers, Evil provides the Evil specific `motion-state` (see here). You can configure the modes to open in that state by adding/removing the mode names to the list of `evil-motion-state-modes`. If you are using Spacemacs then you can also use the evilified-state in a similar way (or when not using Spacemacs you could try https://github.com/mohsenil85/evil-evilified-state, I guess it works fine, but I have never tested it). Alternatively, I think I would recommend to just use the very well designed evil-collection, although as a Spacemacs user I haven't used it much myself. > 0 votes --- Tags: evil, read-only-mode ---
thread-68592
https://emacs.stackexchange.com/questions/68592
Add CSS class or id tag to individual src blocks
2021-09-20T03:09:26.063
# Question Title: Add CSS class or id tag to individual src blocks I want to style some HTML source block exports differently than others. Say I want the "Hi" block to have a green background and "Bye" to be red: ``` #+COMMENT: -*- org-html-htmlize-output-type: css -*- #+begin_src python print("Hi") #+end_src #+begin_src python print("Bye") #+end_src ``` The relevent HTML export is, ``` <div id="content"> <div class="org-src-container"> <pre class="src src-python"><span class="org-keyword">print</span>(<span class="org-string">"Hi"</span>) </pre> </div> <div class="org-src-container"> <pre class="src src-python"><span class="org-keyword">print</span>(<span class="org-string">"Bye"</span>) </pre> </div> </div> ``` Each block corresponds to a `org-src-container` or `src src-python` and there is no way to differentiate them individually via CSS (unless I'm mistaken). My thought is to assign a class or id tag to an individual block's `div` or `pre`. It seems like `#+ATTR_HTML` might work but the following produces the same output: ``` #+COMMENT: -*- org-html-htmlize-output-type: css -*- #+ATTR_HTML: :class myclass :id myid #+begin_src python print("Hi") #+end_src #+begin_src python print("Bye") #+end_src ``` How can I add a class or id selector to specific block exports? **EDIT** From looking at the Org docs more, it appears that `#+ATTR_HTML` is only for tables and links when used with a source block. Frustratingly, it works exactly how I would like it to for example blocks: Org mode - change code block background color I suppose I could use that, except syntax highlighting doesn't seem to apply to example block exports. I tried advising the `org-html-src-block` to include the desired tags (based off of Generate different markup for not-tangled code blocks in org-mode). Unfortunately, I couldn't find a way to pass information to the function (e.g. such as through a new key-value pair within the `#+begin_src` line). The `info` parameter only contains meta-data. Finally, I tried applying a filter (i.e. regexp replace). This worked for single lines, but I couldn't get it to apply generally, such for multiple lines or to have a generic form. Using the regexp-builder, I could capture the code portion, the CSS tag, and the value with ``` "\\(?1:[^\n]+\\)#\s+\\(?2:[A-Za-z-]+\\):\s+\\(?3:.+\\)" ``` This would correspond to the `print("Hi")`, `background-color`, and `rgb(255, 0, 0)` in ``` #+begin_src python print("Hi") # background-color: rgb(255, 0, 0) #+end_src ``` This was inspired by: https://emacs.stackexchange.com/questions/20417/org-mode-highlight-lines-i$|org-export-derived-backend-p # Answer You can do this with the advice method. It's not the `info` parameter you need, but `src-block`. Use the `org-export-read-attribute` to extract the `#ATTR_HTML` contents. The following advice checks for the `:class` and `:id` keywords in a `#attr_html` line and constructs a div around the source block accordingly. ``` (defun my-org-html-src-block-advice (oldfun src-block contents info) "Add class or id CSS tags to html source block output. Allows class or id tags to be added to a source block using #attr_html: #+ATTR_HTML: :class myclass :id myid #+begin_src python print(\"Hi\") #+end_src " (let* ((old-ret (funcall oldfun src-block contents info)) (class-tag (org-export-read-attribute :attr_html src-block :class)) (id-tag (org-export-read-attribute :attr_html src-block :id))) (if (or class-tag id-tag) (concat "<div " (if class-tag (format "class=\"%s\" " class-tag)) (if id-tag (format "id=\"%s\" " id-tag)) ">" old-ret "</div>") old-ret))) (advice-add 'org-html-src-block :around #'my-org-html-src-block-advice) ``` When applied to the sample Org file, it produces the output: ``` <div class="myclass" id="myid" ><div class="org-src-container"> <pre class="src src-python"><span class="org-keyword">print</span>(<span class="org-string">"Hi"</span>) </pre> </div></div> <div class="org-src-container"> <pre class="src src-python"><span class="org-keyword">print</span>(<span class="org-string">"Bye"</span>) </pre> </div> ``` > 3 votes --- Tags: org-export, html, css ---
thread-68636
https://emacs.stackexchange.com/questions/68636
Filter text of buffer in a grep-like way
2021-09-23T21:55:45.007
# Question Title: Filter text of buffer in a grep-like way I want to filter the text of an emacs buffer, a bit like you can filter text with `grep`. Sounds simple, but I tried googling it and I only get results from people who want to search in a buffer or to grep the filesystem. That is not what I want. I want to *filter* the text of *a buffer*. I want the text not matching the pattern to be gone and I don't want to grep the files in my filesystem. Is this possible? I'm currently saving the output of the buffer to a file and doing this in a `shell`: ``` more file.txt | grep pattern ``` # Answer > I want the text not matching the pattern to be gone * `M-x` `keep-lines` will *delete* lines not matching the pattern (i.e. only keep the lines which match). `flush-lines` does the opposite, deleting lines which *do* match the pattern. * `M-x` `occur` will open a separate buffer showing only the matching lines (which you can use like a compilation error buffer to navigate those positions in the original buffer). This option is the closest to the 'grep' approach. * `C-u``M-x` `occur` will show only the portion of each line which specifically matched the pattern (which is what the quoted part of your question sounds most like). * `M-x` `loccur` from https://elpa.gnu.org/packages/loccur.html hides/unhides the text within the original buffer (which is therefore a bit like a non-destructive `keep-lines`). You can read about those built-in commands, and others, in the manual: `C-h``i``g` `(emacs)Other Repeating Search` Also see `(emacs)Compilation Mode` regarding the convenient navigation using the `next-error` and `previous-error` commands. Finally, note that if you do need to use `grep` itself, you are better off doing *that* inside Emacs as well (not least because you can once again jump from the results to the original locations like in a compilation buffer). There are many Emacs commands which use grep, and you can read about those at: `C-h``i``g` `(emacs)Grep Searching` Tangentially, I'll recommend the third-party grep equivalent to Occur Edit mode, which you can find at https://melpa.org/#/wgrep. > 6 votes # Answer Besides the options mentioned in phils answer, you can use `shell-command-on-region` for this. Select the region you'd like to 'filter' first. When prefixed with a universal argument `C-u`, the sent text gets replaced (you can read its docstring for more info). I don't know your exact usecase, but generally swiper or helm-swoop provide similar and generally more useful functionality. > 1 votes --- Tags: buffers, text-editing, grep ---
thread-68627
https://emacs.stackexchange.com/questions/68627
How to automatically enable `rst-mode` in SciPy documentation via Elpy?
2021-09-23T04:59:41.527
# Question Title: How to automatically enable `rst-mode` in SciPy documentation via Elpy? I am currently trying to make `Elpy` into my ideal Python IDE, and besides inline images in the console, I am mostly there (I don't need much). `C-c C-d` (`M-x elpy-doc`) brings up documentation for the object at point when editing a `.py` file, and after some troubleshooting I have gotten this to work, mostly, for imported modules as well as built-in functions. However, it turns out that `scipy` documentation is written in `ReST` and requires `rst-mode` for syntax highlighting. **I want to automatically enable `rst-mode` whenever I open SciPy documentation via `elpy-doc`, or generally ReST documentation.** However, I cannot automate this because the buffer documentation is displayed in is not connected to a file. It does not seem possible to set any options related to `elpy-doc` to achieve such a thing. Does this make sense, and if so, is there a way to accomplish it? # Answer > 2 votes You can advise `elpy-doc` to achieve this goal. This runs a function after elpy-doc to turn on rst-mode in the *Python Doc* buffer it creates, but only when the word scipy is in the buffer. ``` (defun turn-on-rst-mode () (with-current-buffer "*Python Doc*" (goto-char (point-min)) (when (search-forward "scipy") (rst-mode)))) (advice-add #'elpy-doc :after #'turn-on-rst-mode) ``` # Answer > 1 votes A quick-and-dirty keyboard macro called `pydoc-rst` bound to `C-x C-k 1` and `C-x C-k R` for this purpose: ``` (kmacro-lambda-form [?\C-c ?\C-d ?\C-x ?o ?\M-x ?r ?s ?t ?- ?m ?o ?d ?e return ?\C-x ?o] 0 "%d")) (global-set-key [24 11 82] 'pydoc-rst) (global-set-key [24 11 49] 'pydoc-rst) ``` Let me know if this seems wrong somehow. --- Tags: elpy ---
thread-68642
https://emacs.stackexchange.com/questions/68642
How do I make new bookmarks (`bookmark-set`) be added to the end, not the beginning?
2021-09-24T07:36:50.710
# Question Title: How do I make new bookmarks (`bookmark-set`) be added to the end, not the beginning? How do I make new bookmarks (`bookmark-set`) be added to the end of the bookmark file, not the beginning? # Answer I found a way to do this via monkey patching, and looking at the original code, it doesn't seem like there is any other way to accomplish this. (The changed section is marked by `@monkeyPatched`.) ``` (defun bookmark-store (name alist no-overwrite) "Store the bookmark NAME with data ALIST. If NO-OVERWRITE is non-nil and another bookmark of the same name already exists in `bookmark-alist', record the new bookmark without throwing away the old one." (bookmark-maybe-load-default-file) (let ((stripped-name (copy-sequence name))) (set-text-properties 0 (length stripped-name) nil stripped-name) (if (and (not no-overwrite) (bookmark-get-bookmark stripped-name 'noerror)) ;; Already existing bookmark under that name and ;; no prefix arg means just overwrite old bookmark. (let ((bm (bookmark-get-bookmark stripped-name))) ;; First clean up if previously location was fontified. (when bookmark-set-fringe-mark (bookmark--remove-fringe-mark bm)) ;; Modify using the new (NAME . ALIST) format. (setcdr bm alist)) ;; otherwise just cons it onto the front (either the bookmark ;; doesn't exist already, or there is no prefix arg. In either ;; case, we want the new bookmark consed onto the alist...) ;;; @monkeyPatched ;; (push (cons stripped-name alist) bookmark-alist)) (setf (cdr (last bookmark-alist)) (list (cons stripped-name alist)))) ;;; ;; Added by db (setq bookmark-current-bookmark stripped-name) (setq bookmark-alist-modification-count (1+ bookmark-alist-modification-count)) (if (bookmark-time-to-save-p) (progn (bookmark-save))) (setq bookmark-current-bookmark stripped-name) (bookmark-bmenu-surreptitiously-rebuild-list))) ``` > 0 votes --- Tags: bookmarks ---
thread-68635
https://emacs.stackexchange.com/questions/68635
Effect of doom themes in tabulated list header line is visually confusing
2021-09-23T21:41:19.477
# Question Title: Effect of doom themes in tabulated list header line is visually confusing I am on the process of moving from prelude \[1\] to a stand-alone config I have created from scratch \[2\], though by largely copying other people's `.emacs`. It seems I have inadvertently changed the rendering of the header line in tabulated mode \[3\], but I am struggling to find out how to configure this correctly. When using prelude, instances of tabulated mode are rendered like so (using `doom-dark+` theme): However, in my new .emacs I now get the following: It appears I am now "overriding" the rendering of the header line somehow, but I am unsure as to what is causing this. Any pointers would be very helpful. \[1\] https://github.com/bbatsov/prelude \[2\] https://github.com/mcraveiro/cunene \[3\] https://github.com/emacs-mirror/emacs/blob/master/lisp/emacs-lisp/tabulated-list.el # Answer > 0 votes I haven't completely solved this problem, but I have found more details and a workaround. The gist of it is that doom-themes \[1\] appear to use the same face for the header-line as they do for the modeline, causing this visual confusion. There are several tickets open on this: The workaround as per ticket #320 is: ``` (face-spec-set 'header-line '((t :background "#23214b"))) ``` However, as you can see from the screenshots above, prelude - or my prelude config, not sure just yet - was doing something clever and setting up this face to a more sensible value. I will continue investigating, but this at least makes the theme usable. \[1\] https://github.com/hlissner/emacs-doom-themes **Update** Found a much better solution to this problem. On the Emacs with prelude, I did `customize-face` for face `header-line`. There you can see all the properties for the face. I then did `customize-face` for the same face using my new configuration file, and replicated the configuration I had in prelude, and saved it to my custom file. The generated lisp is as follows: ``` (custom-set-faces ;; custom-set-faces was added by Custom. ;; If you edit it by hand, you could mess it up, so be careful. ;; Your init file should contain only one such instance. ;; If there is more than one, they won't work right. '(header-line ((t (:inherit mode-line :background "#2b2b2b" :foreground "#f0dfaf" :box (:line-width -1 :color "#585858" :style released-button)))))) ``` I could't quite replicate the grey colour on the border of the box, so `#585858` is an approximation. However, the final result is very close: FWIW, the options in custom were as follows: --- Tags: themes, header-line, proced ---
thread-68603
https://emacs.stackexchange.com/questions/68603
Make org-html export not escape special characters
2021-09-21T10:43:43.287
# Question Title: Make org-html export not escape special characters I'm writing an exporter for Remarkup: https://github.com/renatgalimov/org-phabricator. It's similar to Markdown and based on `org-md` which itself is a modification of `ox-html`. Whenever I export, some Unicode sequences get replaced by &something; HTML escape sequences, which is not necessary for remarkup. I'm struggling to find, which function or setting I need to modify to skip the escaping. Example: ``` | ITEM | FOLLOW_CONFIG | |-------------------------------------+---------------| | \_ Enforcing particular resolution | | | \_ No hotplug | | | \_ HDMI mode auto | | ``` Result: ``` <table> <tr> <th>ITEM</th> <th>FOLLOW<sub>CONFIG</sub></th> </tr> <tr> <td>&ensp;&ensp;Enforcing particular resolution</td> <td>&#xa0;</td> </tr> <tr> <td>&ensp;&ensp;&ensp;&ensp;No hotplug</td> <td>&#xa0;</td> </tr> <tr> <td>&ensp;&ensp;&ensp;&ensp;&ensp;&ensp;HDMI mode auto</td> <td>&#xa0;</td> </tr> </table> ``` I want to put (en-space) instead of `&ensp;`s. Thanks # Answer If you don't need any entitites, then you can customize (i.e. include/exclude) the export of entities via the `org-export-with-entities` variable. To set the variable per buffer, you can include the `OPTIONS` keyword with the value `e:nil` at the beginning of your file/buffer. ``` #+OPTIONS: e:nil ``` source: https://orgmode.org/manual/Export-Settings.html (and the variable its docstring) To exclude the `\_` entitites specifically, you can override their values with the `org-entities-user` variable, e.g. as follows: ``` (customize-set-value 'org-entities-user (let (space-entities html-spaces (entity "_")) (dolist (n (number-sequence 1 20) (nreverse space-entities)) (let ((spaces (make-string n ?\s))) (push (list (setq entity (concat entity " ")) (format "\\hspace*{%sem}" (* n .5)) nil (setq html-spaces (concat " " html-spaces)) spaces spaces (make-string n ?\x2002)) space-entities))))) ``` (code taken from `org-entities` value and replaced `&ensp` by a single space) > 2 votes --- Tags: org-mode, org-export, html ---
thread-68641
https://emacs.stackexchange.com/questions/68641
flush-lines: only upper case not working
2021-09-24T07:22:12.873
# Question Title: flush-lines: only upper case not working Here's some text: ``` test HELLO 999 help HOW ARE YOU buy aaa H d ``` I need to remove all lines without uppercase. The result must be ``` HELLO HOW ARE YOU H ``` I tried `M-x flush-lines [a-z] RET` but the output was ``` 999 ``` What am I missing? # Answer I'll solve it using a dual strategy. First we say that case matters. `M-: (setq case-fold-search nil) RET` Then we keep the lines containing upper case. `M-x keep-lines RET [[:upper:]] RET` > 1 votes --- Tags: regular-expressions ---
thread-68647
https://emacs.stackexchange.com/questions/68647
Automatically change encoding of process buffers
2021-09-24T08:22:59.907
# Question Title: Automatically change encoding of process buffers ### Platform Windows 10 with GNU Emacs 26.1 (build 1, x86\_64-w64-mingw32). ### Goal To set the encoding of process buffers to UTF-8. I would like to set the input and output encoding of process buffers, like shell or the R Console (iESS), to UTF-8. By default, the iESS buffer is encoded as `iso-latin-1-dos` for output and `undecided-dos` for input. If I ask Emacs: ``` M-S-: (process-coding-system (get-buffer-process (current-buffer))) ``` I get: ``` (iso-latin-1-dos . undecided-dos) ``` As a result, special characters are mangled in the iESS output (although not in the input): ``` > print("Ä") [1] "Ã\204" > ``` ### What I've tried I can change the encoding by invoking ``` M-S-: (set-buffer-process-coding-system 'utf-8 'utf-8) ``` as described in this thread. The problem goes away, but I would like a permanent solution. So I tried to create hooks for several process buffers in my `.emacs`, like so: ``` ; the hooks below should set the encoding of input to and output from a ; process buffer (like a shell, R console, or REPL) to UTF-8 ; but somehow they don't. (add-hook 'shell-mode-hook (lambda () (set-buffer-process-coding-system 'utf-8 'utf-8))) (add-hook 'eshell-mode-hook (lambda () (set-buffer-process-coding-system 'utf-8 'utf-8))) (add-hook 'iESS-mode-hook (lambda () (set-buffer-process-coding-system 'utf-8 'utf-8))) (add-hook 'inferior-python-mode-hook (lambda () (set-buffer-process-coding-system 'utf-8 'utf-8))) ``` Upon restarting Emacs, however, these settings have no effect. There is no error message, but the iESS and shell buffers still have the "wrong" encoding. ### Questions Ho can I fix the code above so it changes the encoding of the respective process buffer upon mode change? What would be a smarter way to achieve this? Is there a way to set all process buffers to utf-8 encoding without relying on individual hooks? # Answer > 2 votes Just set `default-process-coding-system` to `'(utf-8 . utf-8)`. You can do this by adding this to your init file: ``` (setq default-process-coding-system '(utf-8 . utf-8)) ``` This and other useful variables are described in chapter 33.10.5 Default Coding Systems of the Emacs Lisp manual. You may also be interested in the `process-coding-system-alist` variable. You can open this and other manuals inside Emacs using `C-h i`. --- Tags: shell, process, character-encoding, r ---
thread-68650
https://emacs.stackexchange.com/questions/68650
How to repeat last magit search and modify an option?
2021-09-24T09:44:55.927
# Question Title: How to repeat last magit search and modify an option? Searching through the git log with magit is a breeze. When I do a complex search, I may pass five arguments. If I then realize I want to search again with one option changed, how can I get all search options back? I think a long time ago, this was the default behavior of magit, but these days every search starts with the default arguments. # Answer Ah the manual is better than I thought. I'm not sure if I can get back options of the last search but inside the log buffer, pressing `l` again shows the buffer-local search options. And `L` provides options to save current options as defaults for the future. See https://magit.vc/manual/magit/Refreshing-Logs.html#Refreshing-Logs > 1 votes --- Tags: magit ---
thread-68653
https://emacs.stackexchange.com/questions/68653
Why does my agenda display the top level entry and not the one followed by "SCHEDULED:"? How can 'I change this?
2021-09-24T12:36:21.697
# Question Title: Why does my agenda display the top level entry and not the one followed by "SCHEDULED:"? How can 'I change this? EDIT: By removing the auto-indent, it looks like this: ``` * Work ** Project A SCHEDULED: <2021-10-04 Mon 10:00-12:00 +1w> * Training ** Sport A *** Exercise X SCHEDULED: <2021-10-04 Mon 08:00-09:00 +1w> ``` and this: ``` agenda: 08:00-09:00 Scheduled: Exercise X agenda: 10:00-12:00 Project A ``` BUT still not like this (whether it includes Scheduled or not): ``` agenda: 08:00-09:00 Training: Sport A: Exercise X agenda: 10:00-12:00 Work: Project A ``` I have something like this in my org file: ``` * Work ** Project A SCHEDULED: <2021-10-04 Mon 10:00-12:00 +1w> * Training ** Sport A *** Exercise X SCHEDULED: <2021-10-04 Mon 08:00-09:00 +1w> ``` Now what I see in my agenda is something similar to this: ``` agenda: 08:00-09:00 Training agenda: 10:00-12:00 Work ``` BUT what I would like to see is this: ``` agenda: 08:00-09:00 Training: Sport A: Exercise X agenda: 10:00-12:00 Work: Project A ``` Or at least this: ``` agenda: 08:00-09:00 Exercise X agenda: 10:00-12:00 Project A ``` My question: How can I achieve this? # Answer > 1 votes In order for the asterisks to be interpreted as headline indicators, there should not be any leading space; otherwise, they are interpreted as just text. Try this: ``` * Work ** Project A SCHEDULED: <2021-10-04 Mon 10:00-12:00 +1w> * Training ** Sport A *** Exercise X SCHEDULED: <2021-10-04 Mon 08:00-09:00 +1w> ``` This produces the second, simpler form you specified in your question. To produce the expanded form, you need to add breadcrumbs to `org-agenda-prefix-format`. That is a somewhat complicated variable (see its doc string with `C-h v org-agenda-prefix-format`) but the following works: ``` (setf (car org-agenda-prefix-format) '(agenda . " %i %-12:c%?-12t% s %b ")) ``` The key is the `%b` added at the end: that produces the breadcrumbs (i.e. the sequence of headlines higher up that lead to this particular headline). However, you need to add that to your init file *AFTER* Org mode is loaded, otherwise the variable will not have been defined yet. Probably the easiest thing to do is to add the following two lines to your init file (somewhere towards the end of it): ``` (require 'org-agenda) (setf (car org-agenda-prefix-format) '(agenda . " %i %-12:c%?-12t% s %b ")) ``` --- Tags: org-agenda ---
thread-18054
https://emacs.stackexchange.com/questions/18054
How to set major mode for a file in .dir-locals.el?
2015-11-13T13:42:28.090
# Question Title: How to set major mode for a file in .dir-locals.el? I would like to set the major mode for a file as you would using file-local variables ``` Local Variables: mode: text End: ``` but in `.dir-locals.el` in order not to “pollute” the file in question. Is this possible? # Answer It's possible to specify a string instead of a mode, but this only works for subdirectories. So I'll use `nil` instead to match all modes, then the `eval` key to change the major mode conditionally: ``` ((nil (eval (lambda () (when (string= (file-name-nondirectory buffer-file-name) "file-name.extension") (my-mode)))))) ``` A downside of this approach is that the `eval` key is unsafe, so you'll need to confirm the variable permanently for this to have an effect. > 6 votes # Answer The following `.dir-locals.el` works just fine for me to set the major mode of all files in a directory to `shell-script-mode`: ``` ((nil . ((mode . shell-script)))) ``` The obvious downside is that you can't specify the major mode for only a given subset of files in the directory. **Addendum:** Amusingly, it also has the side effect of setting the major mode of `.dir-locals.el` itself to `shell-script-mode`. **Addendum 2:** Rather more amusingly, it also has the side effect of setting the major mode of Dired buffers to `shell-script-mode`, making it impossible to open any (as an error is thrown during the initialization). > 5 votes # Answer For me accepted answer give error: > (error "Lisp nesting exceeds ‘max-lisp-eval-depth’") Because it tried to apply the mode recursively, when it open a file it executed a mode and if the mode was changed it executed the eval again recursively: For me this works: ``` ((nil (eval (lambda () (when (and (string-match-p "\\.js\\'" buffer-file-name) (not (string= (major-mode) "rjsx-mode"))) (rjsx-mode)))))) ``` For rjsx-mode that I wanted to apply for all js file in project directory. > 0 votes --- Tags: major-mode, directory-local-variables ---
thread-68659
https://emacs.stackexchange.com/questions/68659
How to print a Elisp form with a specific prefix string on each line?
2021-09-24T19:01:31.777
# Question Title: How to print a Elisp form with a specific prefix string on each line? I'd like to pretty-print an Elisp form with some arbitrary prefix string inserted at the beginning of each output line. For example, given the following variable: ``` (setq var '((abc . 11) (def . 22) (ghi . 33))) ``` I'd like something like `(pp-with-prefix var " ---> ")` (or something like it) to be able to add the `" ---> "` prefix string (or anything) so I could get something like the following printed: ``` ---> ((abc . 11) ---> (def . 22) ---> (ghi . 33)) ``` instead of what `(pp var)` would normally print: ``` ((abc . 11) (def . 22) (ghi . 33)) ``` # Answer All that `pp` does is call `pp-to-string` on the object and then it calls `princ` to print the string. So you can use `pp-to-string` in your own function and then manipulate the resulting string any way you want, before printing it out. The `s` string library might be useful for such manipulation. See https://github.com/magnars/s.el > 1 votes --- Tags: pretty-print ---
thread-12532
https://emacs.stackexchange.com/questions/12532
Buffer local idle-timer
2015-05-19T21:56:18.253
# Question Title: Buffer local idle-timer I would like to use an idle timer that is local to the current buffer in one of my packages. However, I can't seem to find out how. How can I create (or fake) the behavior of a buffer local idle timer? Is the only way to call a function that checks `(current-buffer)`? # Answer ``` (defun run-with-local-idle-timer (secs repeat function &rest args) "Like `run-with-idle-timer', but always runs in the `current-buffer'. Cancels itself, if this buffer was killed." (let* (;; Chicken and egg problem. (fns (make-symbol "local-idle-timer")) (timer (apply 'run-with-idle-timer secs repeat fns args)) (fn `(lambda (&rest args) (if (not (buffer-live-p ,(current-buffer))) (cancel-timer ,timer) (with-current-buffer ,(current-buffer) (apply (function ,function) args)))))) (fset fns fn) fn)) ``` > 5 votes # Answer If you mean a way to run some code with idle timer in such a way that the passed code runs in the original buffer, maybe you can adapt the following snippet that I am currently using. Please keep in mind that this snippet assumes that it is placed in an \*.el file with lexical binding. ``` (defun my-delayed-tex-font-lock () (let ((here (current-buffer))) (run-with-idle-timer 10 nil (lambda () (with-current-buffer here (my-tex-font-lock)))))) (add-hook 'TeX-mode-hook 'my-delayed-tex-font-lock) ``` What this snippet does is make my function my-tex-font-lock run after ten seconds of idle time for each TeX file buffer. When I open alice.tex, quickly switch to bob.txt and wait for ten seconds doing nothing, then my-tex-font-lock will kick in and it will affect the alice.tex buffer but not bob.txt. > 0 votes # Answer From looking into this, it's possible for a buffer local minor-mode to manage a global timer. The global timer is disabled when the buffer-local mode becomes inactive and is re-enabled when it becomes active. There is additional logic to ensure a buffer that becomes inactive isn't left in a stale state too. This is done using a global idle timer and `window-state-change-hook` to track changes to the active buffer. The logic to manage timers is under the section `Internal Timer Management`. ``` ;;; my-hl-line.el --- Highlight the current line (example package) -*- lexical-binding: t -*- ;; --------------------------------------------------------------------------- ;; Custom Variables (defgroup my-hl-line nil "Highlight the current line, as an example." :group 'faces) (defcustom my-hl-line-idle-time 0.1 "Time after which to highlight the line." :group 'my-hl-line :type 'float) ;; --------------------------------------------------------------------------- ;; Internal Functions ;; ;; This is sample code, it highlights a line. (defsubst my-hl-line--do-highlight-clear () "Clear current highlight." (remove-overlays (point-min) (point-max) 'my-hl-line t)) (defun my-hl-line--do-highlight-set () "Highlight the current line." (my-hl-line--do-highlight-clear) (pcase-let* ((`(,beg . ,end) (bounds-of-thing-at-point 'line))) (let ((ov (make-overlay beg end))) (overlay-put ov 'face '(:inverse-video t :extend t)) (overlay-put ov 'my-hl-line t)))) ;; --------------------------------------------------------------------------- ;; Internal Timer Management ;; ;; This works as follows: ;; ;; - The timer is kept active as long as the local mode is enabled. ;; - Entering a buffer runs the buffer local `window-state-change-hook' ;; immediately which checks if the mode is enabled, ;; set up the global timer if it is. ;; - Switching any other buffer wont run this hook, ;; rely on the idle timer it's self running, which detects the active mode, ;; canceling it's self if the mode isn't active. ;; ;; This is a reliable way of using a global, ;; repeating idle timer that is effectively buffer local. ;; ;; Global idle timer (repeating), keep active while the buffer-local mode is enabled. (defvar my-hl-line--global-timer nil) ;; When t, the timer will update buffers in all other visible windows. (defvar my-hl-line--dirty-flush-all nil) ;; When true, the buffer should be updated when inactive. (defvar-local my-hl-line--dirty nil) (defun my-hl-line--time-callback-or-disable () "Callback that run the repeat timer." ;; Ensure all other buffers are highlighted on request. (let ((is-mode-active (bound-and-true-p my-hl-line-mode))) ;; When this buffer is not in the mode, flush all other buffers. (cond (is-mode-active ;; Don't update in the window loop to ensure we always ;; update the current buffer in the current context. (setq my-hl-line--dirty nil)) (t ;; If the timer ran when in another buffer, ;; a previous buffer may need a final refresh, ensure this happens. (setq my-hl-line--dirty-flush-all t))) (when my-hl-line--dirty-flush-all ;; Run the mode callback for all other buffers in the queue. (dolist (frame (frame-list)) (dolist (win (window-list frame -1)) (let ((buf (window-buffer win))) (when (and (buffer-local-value 'my-hl-line-mode buf) (buffer-local-value 'my-hl-line--dirty buf)) (with-selected-frame frame (with-selected-window win (with-current-buffer buf (setq my-hl-line--dirty nil) (my-hl-line--do-highlight-set))))))))) ;; Always keep the current buffer dirty ;; so navigating away from this buffer will refresh it. (if is-mode-active (setq my-hl-line--dirty t)) (cond (is-mode-active (my-hl-line--do-highlight-set)) (t ;; Cancel the timer until the current buffer uses this mode again. (my-hl-line--time-ensure nil))))) (defun my-hl-line--time-ensure (state) "Ensure the timer is enabled when STATE is non-nil, otherwise disable." (cond (state (unless my-hl-line--global-timer (setq my-hl-line--global-timer (run-with-idle-timer my-hl-line-idle-time :repeat 'my-hl-line--time-callback-or-disable)))) (t (when my-hl-line--global-timer (cancel-timer my-hl-line--global-timer) (setq my-hl-line--global-timer nil))))) (defun my-hl-line--time-reset () "Run this when the buffer changes." ;; Ensure changing windows doesn't leave other buffers with stale highlight. (cond ((bound-and-true-p my-hl-line-mode) (setq my-hl-line--dirty-flush-all t) (setq my-hl-line--dirty t) (my-hl-line--time-ensure t)) (t (my-hl-line--time-ensure nil)))) (defun my-hl-line--time-buffer-local-enable () "Ensure buffer local state is enabled." ;; Needed in case focus changes before the idle timer runs. (setq my-hl-line--dirty-flush-all t) (setq my-hl-line--dirty t) (my-hl-line--time-ensure t) (add-hook 'window-state-change-hook #'my-hl-line--time-reset nil t)) (defun my-hl-line--time-buffer-local-disable () "Ensure buffer local state is disabled." (kill-local-variable 'my-hl-line--dirty) (my-hl-line--time-ensure nil) (remove-hook 'window-state-change-hook #'my-hl-line--time-reset t)) ;; --------------------------------------------------------------------------- ;; Public Functions ;;;###autoload (define-minor-mode my-hl-line-mode "Idle-Highlight Minor Mode." :group 'my-hl-line :global nil (cond (my-hl-line-mode (my-hl-line--time-buffer-local-enable)) (t (my-hl-line--time-buffer-local-disable) (my-hl-line--do-highlight-clear)))) (provide 'my-hl-line-mode) ;;; my-hl-line-mode.el ends here ``` > 0 votes --- Tags: emacs-internals, idle-timer ---
thread-33433
https://emacs.stackexchange.com/questions/33433
Is there continuous scrolling and double page viewing in pdf-tools?
2017-06-10T10:40:14.973
# Question Title: Is there continuous scrolling and double page viewing in pdf-tools? pdf-tools jumps from the end of one page to the next page. Is there a ways to activate some kind of smooth scrolling? Also is there a way to display a double sided layout on my screen? # Answer > 5 votes Currently, this is not possible. Several feature requests have been submitted on the project's GitHub page: Feature request: continuous view #27, and more recently, Double pages layout #303. Apparently, this will not be fixed soon, quoting the package author in one of his replies to issue #27: > Generally speaking, there are two issues: > > * Large parts of the software (including image-mode) assume a one-to-one correspondence between a displayed page and its window. > * Emacs is not easily convinced to scroll an image, such that its display starts in the middle of it, in case would completely fits into the window. # Answer > 2 votes Maybe a bit late, but there is a fix that works for me, see here: https://github.com/politza/pdf-tools/issues/55 The second-to-last post has a fix which works for me. Place the functions somewhere in your Emacs config and bind them to `C-M-v` or `C-M-S-v` respectively. Not a pretty hack, but works so far for me - at least with pdf-tools. # Answer > 1 votes This package does that https://github.com/dalanicolai/pdf-continuous-scroll-mode.el Since it is not available in melpa **use-package** can not be used, but the following elisp will first install quelpa and then install the package. (use-package quelpa :ensure t) ``` (use-package pdf-tools :ensure t :config (pdf-tools-install t) (quelpa '(pdf-continuous-scroll-mode :fetcher github :repo "dalanicolai/pdf-continuous-scroll-mode.el")) (add-hook 'pdf-view-mode-hook 'pdf-continuous-scroll-mode)) ``` --- Tags: pdf-tools ---
thread-68571
https://emacs.stackexchange.com/questions/68571
(Org) TikZ for exporting both LaTeX and HTML/MathJax
2021-09-18T17:01:00.020
# Question Title: (Org) TikZ for exporting both LaTeX and HTML/MathJax I'm exporting an Org Mode project both to LaTeX and to HTML (with MatJax). Now I need to add a TikZ picture which can be exported nativelly on LaTeX and must be rendered in svg for HTML. Writing the TikZ env in Org directly works for LaTeX and even for HTML with dvipng/dvisvg, but not with MatJax: ``` #some org \begin{tikzpicture} % some tikz \end{tikzpicture} # some org ``` I tried embedding that in a `LaTeX` special block: ``` #some org #+BEGIN_LaTeX \begin{tikzpicture} % some tikz \end{tikzpicture} #+END_LaTeX # some org ``` but the result was the same. (BTW I read this syntax is now deprecated) I tried with a babel block: ``` ;; without this the tikz env is exported as verbatim code (org-babel-do-load-languages 'org-babel-load-languages '((latex . t))) ``` ``` #some org #+BEGIN_SRC latex :file myfile.svg :imagemagick :results (if (org-export-derived-backend-p org-export-current-backend 'latex) "latex" "file") \begin{tikzpicture} % some tikz \end{tikzpicture} #+END_SRC # some org ``` and in this case it ignores the header: it tries to export to a temporary pdf file, regardless of the options of `file` and `results`. I tried also with the `#+header:` syntax. # Answer I found a solution: ``` (defvar is-latex (org-export-derived-backend-p org-export-current-backend 'latex)) ``` ``` #+BEGIN_SRC latex :file (unless is-latex "myfile.svg") :imagemagick (not is-latex) :results (if is-latex "latex" "graphics file") ``` This works in a sample file I made (gist), but: * It does not include the packages provided in `org-latex-packages-alist`: you have to use the `:headers` property to pass usepackages * Even if in my example I used two normal LaTeX blocks, when trying the same file with batch emacs and an minimal init file it complains the generated file is an HTML and not an SVG. It does not do this if the latex block contains a tikzpicture (the tikz package will be included by default) There is another strange thing: with `graphics` in results header option the svg file is generated (even if in https://orgmode.org/manual/Results-of-Evaluation.html is said the contrary) but without `graphics` it is not included in the html. > 0 votes --- Tags: org-mode, org-export, latex, org-babel, html ---
thread-15029
https://emacs.stackexchange.com/questions/15029
Create new major mode from cc-mode that allows comments with two dashes
2015-08-25T08:26:44.697
# Question Title: Create new major mode from cc-mode that allows comments with two dashes It is possible and relatively easy to create a new major mode, deriving from c-mode, and just add two dashes '--' to work as comments too? I have checked many resources, but couldn't find anything similar. I tried some approaches, but I'm pretty novice with emacs-lisp programming, and c-mode seemed overwhelming for my knowledge. Any hints will be appreciated. # Answer > 3 votes I asked this question in Xah Lee emacs blog entry, and he gave me these suggestions: > i think it can be done, without much trouble. Read the elisp chapter on syntax table. basically, add the -- to the syntax table as comment. Note: syntax table is hard to work with, especially when specifying comment chars. Also, by default it only supports a few. I'm not sure you can have -- // /\* \*/ all together. See my tutorial about comment linked on this page. But, if it can be done, then that's all you need to do. But if it cannot be done, you can still do so by trying to add the syntax for comment as text properties. (you'll need to learn about text properties) I went through the elisp syntax table chapter, that I found pretty hard to grasp, and through Xah Lee comments tutorial and tried these lines, just like his lines for regular // c++ style comment. ``` (define-derived-mode my-mode c-mode "my mode" (modify-syntax-entry ?- ". 12b" c-mode-syntax-table) (modify-syntax-entry ?\n "> b" c-mode-syntax-table) ) (provide 'my-mode) ``` It seems that this was enough for what I needed. # Answer > 1 votes In order for your derived mode to not modify the c-mode syntax table directly, you should define your own syntax table which is based on the c-mode syntax table. Also, it is often helpful to modify the `comment-start` and `comment-end` variables to match the preferred comment style for the mode: ``` (require 'cc-langs) (defvar c-like-syntax-table (let ((table (make-syntax-table))) (c-populate-syntax-table table) (modify-syntax-entry ?- ". 12b" table) table) "The syntax table for my mode called `c-like-mode'") (define-derived-mode c-like-mode c-mode "C-Like" "Major mode that is like `c-mode' but with \"--\" as a comment" :syntax-table c-like-syntax-table (setq comment-start "-- ") (setq comment-end "")) (provide 'c-like-mode) ``` It is worth noting that, given this syntax table, comments that start with `--` are of the same comment style as comments that start with `//`. A side effect of this is that any combination of those characters will result in a comment. In other words, `//`, `--`, `/-`, and `-/` will all mark the beginning of a comment. # Answer > 1 votes To expand on the answers above, this link explains why we need to add `". 12b"`. In summary, `.` means that your symbol is punctuation (note that if you instead put `<` the character becomes a single comment delimiter), whereas the integer flags act as follows (copied from the link): ``` The flags for a character c are: `1' means c is the start of a two-character comment start sequence. `2' means c is the second character of such a sequence. `3' means c is the start of a two-character comment end sequence. `4' means c is the second character of such a sequence. `b' means that c as a comment delimiter belongs to the alternative "b" comment style. Emacs supports two comment styles simultaneously in any one syntax table. This is for the sake of C++. Each style of comment syntax has its own comment-start sequence and its own comment-end sequence. Each comment must stick to one style or the other; thus, if it starts with the comment-start sequence of style "b", it must also end with the comment-end sequence of style "b". The two comment-start sequences must begin with the same character; only the second character may differ. Mark the second character of the "b"-style comment start sequence with the `b' flag. A comment-end sequence (one or two characters) applies to the "b" style if its first character has the `b' flag set; otherwise, it applies to the "a" style. The appropriate comment syntax settings for C++ are as follows: `/' `124b' `*' `23' `\n' `>b' Thus `/*' is a comment-start sequence for "a" style, `//' is a comment-start sequence for "b" style, `*/' is a comment-end sequence for "a" style, and newline is a comment-end sequence for "b" style. `p' identifies an additional "prefix character" for Lisp syntax. These characters are treated as whitespace when they appear between expressions. When they appear within an expression, they are handled according to their usual syntax codes. The function backward-prefix-chars moves back over these characters, as well as over characters whose primary syntax class is prefix (`''). ``` --- Tags: major-mode, cc-mode ---
thread-54409
https://emacs.stackexchange.com/questions/54409
Doom Emacs does not display wordcount
2019-12-16T16:51:46.110
# Question Title: Doom Emacs does not display wordcount Running Doom Emacs 2.0.9. If I make a selection, I can see the word-count. This is as expected because `doom-modeline-enable-word-count` is set to t. However, I was expecting to see a word-count as I edit on org file because `doom-modeline-continuous-word-count-modes` is set to `markdown-mode, gfm-mode, org-mode`. But I do not see the word-count. How do I get this working? # Answer You can select a region or the whole document (`ggvG$` if you use Evil), then use `M-=`. Emacs will display the number of lines, words, and characters. > 1 votes # Answer I made it works as expected by using: ``` (use-package! doom-modeline :custom (doom-modeline-enable-word-count t) (doom-modeline-continuous-word-count-modes '(markdown-mode gfm-mode org-mode text-mode))) ``` > 0 votes --- Tags: org-mode, mode-line, words ---
thread-68674
https://emacs.stackexchange.com/questions/68674
Turning off indentation for goto labels
2021-09-26T17:26:34.183
# Question Title: Turning off indentation for goto labels I'm using the `ellemtel` style for my C code. This mode indents goto labels like this: ``` void f(int x) { if (x) { goto LABEL0; } else { goto LABEL1; } LABEL0: printf("x is zero\n"); return; LABEL1: printf("x isn't zero\n"); return; } ``` I'd like to turn off indentation for goto labels entirely. So that my code would look like this: ``` void f(int x) { if (x) { goto LABEL0; } else { goto LABEL1; } LABEL0: printf("x is zero\n"); return; LABEL1: printf("x isn't zero\n"); return; } ``` The documentation for C-mode wasn't very helpful nor was a Google search. # Answer Indentation is configured in `c-offsets-alist`, which is set by a style. You need to change the indentation for the `label` syntactic symbol from the default (2, unchanged in the `ellemtel` style) to 0. Define your own style based on `ellemtel` with your preferences and make it the default. Based on your sample, it should also change `c-basic-offset` to 2 (from 3 in `ellemtel`). ``` (defconst tkf-c-style '("ellemtel" (c-basic-offset . 2) (c-offsets-alist (label . 0)))) (defun my-after-load-cc-styles () (c-add-style "tkf" tkf-c-style)) (eval-after-load "cc-styles" (my-after-load-cc-styles)) (setq c-default-style "tkf") ``` > 1 votes --- Tags: indentation, cc-mode ---
thread-24859
https://emacs.stackexchange.com/questions/24859
Highlight *other* occurrences of symbol
2016-07-27T02:08:39.213
# Question Title: Highlight *other* occurrences of symbol I've found that using the `highlight-symbol-mode` provided by highlight-symbol works very nicely for highlighting all occurrences of the symbol at point, **automatically** (without my pressing anything). However, I would like to highlight all **other** occurrences of the symbol at point: that is, the actual symbol point is on should **not** be highlighted. I can't find anything in `customize-group highlight-symbol` or in highlight-symbol.el for this. Through Google, I haven't found any reference to other packages that support the functionality I want. How can I get automatic highlighting of all **other** occurrences of the symbol at point? # Answer See: idle-highlight-mode which has an option `idle-highlight-exclude-point` to exclude highlighting the symbol at the point. > 1 votes --- Tags: highlighting ---
thread-68673
https://emacs.stackexchange.com/questions/68673
Mark activate -> delete text. Can't store region to Registers
2021-09-26T16:15:11.637
# Question Title: Mark activate -> delete text. Can't store region to Registers Linux Mint 20 Emacs 27.2. I want to store text to the Emacs Registers. So here steps: 1. Some text to mark. 2. Mark activate by C-SPC 3. Fn-\> arrow right to select whole line 4. Now I want to save region to Register. I try this C-x r 5. But the whole line **is gone**. As result nothing to store in the Register # Answer I found the problem. I use: (cua-mode t). After disable "cua mode" the problem is gone. And now "C-x r s" success work > 1 votes --- Tags: registers ---
thread-68640
https://emacs.stackexchange.com/questions/68640
Characters in unicode-smp charset have no glyphs in Emacs 27.1, debian buster, using MesloLGS NF font
2021-09-24T06:28:38.230
# Question Title: Characters in unicode-smp charset have no glyphs in Emacs 27.1, debian buster, using MesloLGS NF font I'm using **Gnu Emacs 27.1 GTK** on **Debian 10 from buster-backports.** I'm also using the **MesloLGS NF** font that ships with zsh powerlevel10k, and has a heck of a lot of unicode characters. Nonetheless, Emacs does not bother to display most the characters in the **unicode-smp** charset, all I see are the classic boxes with hex code in them. E.g., the character (0x1f512) renders just fine in my terminal using the same font, but does not in Emacs. I tried googling for the solution, but nothing I found so far helped. E.g., I tried calling `set-fontset-font` and tell it to use the default font for the entire range, to no avail. What I *don't* want to do is to install several other fonts and use a mixed font set to display all the characters, just give me what MesloLGS offers (which is a lot). I also do not see how the package unicode-fonts would help, but I tried it nonetheless, without success. I double checked and Emacs seems to be using cairo and harfbuzz just finem the backend being used is `ftcrhb`. Here is the output of `describe-char` for Greek alpha, for example: ``` position: 3 of 5 (40%), column: 0 character: α (displayed as α) (codepoint 945, #o1661, #x3b1) charset: unicode-bmp (Unicode Basic Multilingual Plane (U+0000..U+FFFF)) code point in charset: 0x03B1 script: greek syntax: w which means: word category: .:Base, G:2-byte Greek, L:Left-to-right (strong), c:Chinese, g:Greek, h:Korean, j:Japanese to input: type "C-x 8 RET 3b1" or "C-x 8 RET GREEK SMALL LETTER ALPHA" buffer code: #xCE #xB1 file code: #xCE #xB1 (encoded by coding system utf-8-unix) display: by this font (glyph code) ftcrhb:-PfEd-MesloLGS NF-normal-normal-normal-*-15-*-*-*-m-0-iso10646-1 (#x2F6) ``` The same kind of output for the lock icon, however: ``` position: 1 of 5 (0%), column: 0 character: (displayed as ) (codepoint 128274, #o372422, #x1f512) charset: unicode (Unicode (ISO10646)) code point in charset: 0x1F512 script: symbol syntax: w which means: word category: .:Base to input: type "C-x 8 RET 1f512" or "C-x 8 RET LOCK" buffer code: #xF0 #x9F #x94 #x92 file code: #xF0 #x9F #x94 #x92 (encoded by coding system utf-8-unix) display: no font available ``` My Emacs of course, contrary to your browser, does not display the lock symbols in the second row, only the boxes. And it beats me why it keeps saying "no font available". After several hours of searching and trying, I gave up. Any help would be greatly appreciated! **Update:** With Noto Color Emoji and adding this line to my .emacs: ``` (set-fontset-font t 'symbol "Noto Color Emoji" nil) ``` The special characters render just fine. I would still like to figure out why Emacs is unable to use the same characters from MesloLGS NF, though. **2nd update:** it appears that the MesloLGS font does not include emojis after all. It is more tricky than meets the eye to find a program which shows you which characters appear in a font and which don't. I'm closing this issue as resolved now, since using Noto Color Emoji solves the primary issue. # Answer It appears that the *MesloLGS NF* font does not include emojis after all. It is more tricky than meets the eye to find a program which shows you which characters appear in a font and which don't. Using an emoji font like *Noto Color Emoji* solves the primary issue. > 1 votes --- Tags: fonts, unicode, display, characters, emacs27 ---
thread-68681
https://emacs.stackexchange.com/questions/68681
org-mode and export programming
2021-09-27T11:13:39.717
# Question Title: org-mode and export programming Is it possible to program the export in org-mode in the following way? Say you'd like to export some org-mode text in latex or html but you'd like to program a kind of limited text loop with an increasing index, something like (with some invented pseudo-code with a novel "for-export" bloc) ``` #+begin_src for-export i=1..3 hello number $i #+end_src ``` would export into ``` hello number 1 hello number 2 hello number 3 ``` Is there anything in org-mode that allows us to make this? In one or another form? Many thanks. # Answer I don't think you can do exactly what you want. But there are a few options that come close. If you don't want the source block included in your output, you can do this with the following block: ``` #+begin_src bash :exports results :results verbatim for i in 1 2 3 do echo hello number $i done #+end_src ``` This will generate: ``` #+RESULTS: : hello number 1 : hello number 2 : hello number 3 ``` This uses a bash script, but you can use any language you like. Setting `:exports results` in the header suppresses the source block from your export. Depending on your intent, you may also want to use `:results output raw`, or otherwise configure the presentation of the resulting text. You can't put the loop in the header, but you can assign the variables there: ``` #+begin_src bash :results verbatim :var vals="1 2 3" for i in $vals do echo hello number $i done #+end_src ``` Another approach is to use noweb syntax. In this case, you define the code block you want to insert, here named 'loop', and then you refer to it at the location you want it to appear. This would allow you to reuse the same structure with different values throughout your document: ``` #+name: loop #+begin_src bash :exports none :results raw :var vals="1 2 3" for i in $vals do echo hello number $i done #+end_src #+begin_src text :noweb yes <<loop(vals="1 2 3")>> #+end_src #+begin_src text :noweb yes <<loop(vals="a b c")>> #+end_src #+begin_src text :noweb yes <<loop(vals="apple orange banana")>> #+end_src ``` This generates the following pdf: For more details, see the org mode manual, Working with Source Code, NoWeb Reference Syntax, > 4 votes --- Tags: org-mode, org-export, programming ---
thread-68680
https://emacs.stackexchange.com/questions/68680
How can I develop in Go with IDE capabilities for large projects
2021-09-27T11:10:02.547
# Question Title: How can I develop in Go with IDE capabilities for large projects I am trying to migrate from GoLand to Emacs as my primary IDE for working with Go. I've gone through the standard advice online: company-go, go-mode, lsp, all that stuff. It was hell, it took forever, and I have to say I'm disappointed. Most of all, what I *need* to work is proper completion/ displaying of documentation. Either there is a whole other layer to configuring company-mode, or this just doesn't cut it. Take this generic example: ``` import ( "<path/to/module/because/it/is/a/very/large/project>/logger" "fmt" ) logger.| ``` "|" is where the cursor is now. I'd expect all the public functions in logger to be displayed the same way `fmt.|` shows them, but no. Whatever completion I can find and run simply doesn't go that far. And I should mention in some cases, which I haven't been able to properly identify, the `fmt.|` thing doesn't work either. Similarly, if I have a type declaration: ``` type thingA struct { varB thingB } var varA thingA varA = ... varA.varB.| ``` this should offer me all the methods on type `thingB`, but it doesn't. I get no errors (unless you count the occasional > The connected server(s) does not support method textDocument/... which also only happens sometimes). It just doesn't do anything. I can't properly look for usages of a function even after running `lsp`, probably because the function is declared and used in other files than the one I have open. No simple overview of struct fields. No real support for structured text like "" and () that appear as you type the opening brace or quote, and doesn't overwrite the closing one when you type it, unless you use paredit, which isn't very good for c-like languages in my experience. I could go on, but you get the idea. I want to actually work professionally, with the tools that are necessary for managing a project of this size and not have to define every one of these things myself. I hope I'm not asking for more than Emacs is for, but I don't think I am. There's probably going to be a stupid little thing that I'm not doing that'll make everything work. # Answer The whole point of using the Language Server Protocol is that your editor does not need to know any of the details of the language you are editing. That is instead the job of the Language Server. The capabilities of that server matter a lot, because they determine how completion works and so on. You need to determine what language server you are using, what features it has, and which commands it does or does not support. It is likely that fixing your problem will not involve any Emacs configuration changes at all. Incidentally, you should quote the whole error message rather than chopping it off in the middle of the command name. Edit: if you don’t know what LSP server you are using, run `M-x lsp-describe-session` and it will tell you. `lsp-mode` also maintains a log in the `*lsp-log*` buffer; you might check it for error messages. > 0 votes --- Tags: golang, ide ---
thread-68679
https://emacs.stackexchange.com/questions/68679
Company-anaconda works with root level Python installation but stops working when switching to conda environment with conda.el
2021-09-27T08:43:36.833
# Question Title: Company-anaconda works with root level Python installation but stops working when switching to conda environment with conda.el I am on Arch Linux and use anaconda-mode with company-anaconda (here is a minimal init.el with which I can replicate the issue). I have Python installed both at root level from the primary package manager (pacman) and locally through Anaconda ~/anaconda3. When I use no environment, company works well giving me suggestions. On the other hand, when I do `conda-env-activate` and switch to the base conda environment (or any other environment), company stops giving any suggestion. With `company-diag` I see "Completions: none(error fetching)". I still get suggestions when running IPython in inferior mode, but I see that company uses company-capf as a backend in that case, as opposed to company-anaconda. I am a noob with both Emacs and Anaconda, and have been trying to fix this for a while. My first thought was that company-anaconda could have been relying on some Python package not available in the conda environment which I am not aware of, thus falling back to the root installation for that specific package and causing issues, but I have no idea if that is a realistic explanation. # Answer I solved the issue by creating a new conda environment and installing jedi-0.18.0, parso-0.8.2, and service\_factory-0.1.6, which are the versions which appear as compatible with anaconda-mode, along with python-3.9.7. With this environment company works well. To see the versions I checked the file anaconda-mode.py located in the folder .emacs.d/elpa/anaconda-mode/. Actually, anaconda-mode installs those packages itself in .emacs.d/anaconda-mode/0.1.14-py3/ so maybe the issue is caused by an incompatibility of those versions with the python version used by the default Anaconda installation. > 0 votes --- Tags: python, company-mode, anaconda-mode ---
thread-55923
https://emacs.stackexchange.com/questions/55923
Indent drawers in plain lists (Org Mode)
2020-03-04T21:04:08.920
# Question Title: Indent drawers in plain lists (Org Mode) I use drawers in Org Mode plain lists, which I insert by hitting `C-c C-x d` after a list entry. With this I get ``` 1. [X] This task is completed. The task description spans two lines.(here I hit C-c C-x d) :myDrawer: (Point is here) :END: ``` I find it annoying that the drawer is always inserted so that it is aligned with the list item (`1.` in my example above). How to make it automatically indent itself to the item content? I would like to have ``` 1. [X] This task is completed. The task description spans two lines.(here I hit C-c C-x d) :myDrawer: (Point is here) :END: ``` Note: I use `org-indent-mode` but it is of no help. # Answer > 0 votes Actually indentation happens automatically provided `C-c C-x d` is executed **after** a new line: ``` 1. An item.(hit return here) ``` The new cursor position takes indentation into account: ``` 1. An item. (Cursor ends up here; hit C-c C-x d) ``` One gets: ``` 1. An item. :myDrawer: (Cursor is here) :END: ``` So just remember to first hit return before inserting a drawer. --- Tags: org-mode ---
thread-64970
https://emacs.stackexchange.com/questions/64970
How can I disable lsp-headerline?
2021-05-23T14:43:51.733
# Question Title: How can I disable lsp-headerline? I'm using centaur tabs, and when lsp-headerline enables my tabs hides. I want to disable that headerline using `lsp-headerline-bradcrumb-mode` in a hook ``` (use-package lsp-mode :commands (lsp lsp-deferred) :init (setq lsp-keymap-prefix "C-c l") :config (lsp-enable-which-key-integration t) :hook (lsp-mode . lsp-headerline-breadcrumb-mode) ) ``` Something like this. But it does not work. also I tryed to set `lsp-headerline-breadcrumb-enable` to nil in the config of my plugin, but it gives me an error `lsp-headerline-breadcrumb-enable is not defined` EDIT: Other possible fix to this issue is find a way to keep visible and functional my tabs if it not possible to hide the bradcrumb. Note: In the breadcrumb after the file name it says \*invalid\* # Answer I removed lsp-mode package and reinstaled, after that I can use (setq lsp-headerline-breadcrumb-enable nil) and everything works fine now, thanks to Lorem Ipsum for the help. ``` (use-package lsp-mode :commands (lsp lsp-deferred) :init (setq lsp-keymap-prefix "C-c l") :config (setq lsp-headerline-breadcrumb-enable nil) (lsp-enable-which-key-integration t) ;;(lsp-mode . pao/lsp-mode-setup)) ) ``` > 1 votes # Answer There appears to be a bug in `lsp-mode` which causes `lsp-headerline-breadcrumb-enable` to not work as expected. I believe the following workaround should result in the desired behavior (no breadcrumb): ``` (add-hook 'lsp-mode-hook #'lsp-headerline-breadcrumb-mode) ``` This will call `lsp-headerline-breadcrumb-mode` each time `lsp` mode is enabled. Because of the breadcrumb bug, I believe breadcrumbs are enabled by default (regardless of `lsp-headerline-breadcrumbe-enable`'s value). Calling breadcrumb mode should therefore disable breadcrumbs. There are many other `lsp` hooks to use if this one isn't ideal. > 1 votes # Answer This seemed to work for me. I don't use `use-package` and the other `lsp-mode-hook` answer wasn't working. ``` (add-hook 'lsp-mode-hook (lambda() ;;; other stuff... (setq lsp-headerline-breadcrumb-enable nil))) ``` > 0 votes --- Tags: lsp-mode, lsp, header-line ---
thread-63825
https://emacs.stackexchange.com/questions/63825
How do I suppress messages in the echo area (e.g. `Fill column set to 80 (was 80)`)?
2021-03-10T14:04:37.343
# Question Title: How do I suppress messages in the echo area (e.g. `Fill column set to 80 (was 80)`)? When I open a Python file I keep seeing `Fill column set to 80 (was 80)` message in the echo area. I know I have set it this limit , but I don't want to be keep reminded about it. Is it possible to suppress this message? my setup: ``` (add-hook 'python-mode-hook (lambda () (setq indent-tabs-mode nil) (setq python-indent 4) (set-fill-column 80) (setq tab-width 4))) ``` # Answer > 8 votes @NickD answered the question well. But you can also do this, just to inhibit showing messages for `set-fill-column`: ``` (add-hook 'python-mode-hook (lambda () (setq indent-tabs-mode nil python-indent 4 tab-width 4) (let ((inhibit-message t)) (set-fill-column 80)))) ``` Or this: ``` (defun my-set-fill-column (arg) (let ((inhibit-message t)) (set-fill-column arg))) (add-hook 'python-mode-hook (lambda () (setq indent-tabs-mode nil python-indent 4 tab-width 4) (my-set-fill-column 80))) ``` # Answer > 3 votes Regarding the specific example case... `set-fill-column` is a command which is *only* intended to be used interactively. To set the fill column programmatically, just do this: `(setq fill-column 80)` Which is exactly what `set-fill-column` would do, after validating that `80` was a valid argument and displaying the message -- but you don't need anything to validate `80` as a fill column, and you don't want the message. --- Tags: python, echo-area, message, fill-column, inhibit-message ---
thread-50253
https://emacs.stackexchange.com/questions/50253
How to jump to a heading in a date tree
2019-05-01T00:53:16.667
# Question Title: How to jump to a heading in a date tree What's the easiest way to jump to a heading in a datetree programmatically? I basically want: whenever I open my org file with `file+olp+datetree` structure to jump to a current day, if there's no heading for the current day, then the latest available one. # Answer What this function does is it checks for a headline that matches the current date and jumps to it when it finds. I'm assuming recent entries are placed at the beginning of the file. If that's not the case you may want to start parsing from the end of the file. ``` (defun datetree-jump () (let ((point (point))) (catch 'found (goto-char (point-min)) (while (outline-next-heading) (let* ((hl (org-element-at-point)) (title (org-element-property :raw-value hl))) (when (string= title (format-time-string "%F %A")) (org-show-context) (setq point (point)) (throw 'found t))))) (goto-char point))) ``` --- Here's a more thorough attempt at solving both parts of your problem. The first function returns a list of fallback dates starting from today (defaults to one year). The second function jumps to the first headline in the buffer matching any of the fallback dates. ``` (defun datetree-dates () (let (dates (day (string-to-number (format-time-string "%d"))) (month (string-to-number (format-time-string "%m"))) (year (string-to-number (format-time-string "%Y")))) (dotimes (i 365) (push (format-time-string "%F %A" (encode-time 1 1 0 (- day i) month year)) dates)) (nreverse dates))) (defun datetree-jump () (let ((point (point))) (catch 'found (goto-char (point-min)) (while (outline-next-heading) (let* ((hl (org-element-at-point)) (title (org-element-property :raw-value hl))) (when (member title (datetree-dates)) (org-show-context) (setq point (point)) (throw 'found t))))) (goto-char point))) ``` > 1 votes # Answer As suggested in the accepted answer, it can be useful to parse the buffer from the bottom up in case the headlines with later dates are further in the buffer. Here is the version of the `datetree-jump` function that does this. I also added `(interactive)` to be able to bind it to a key combination. ``` (defun datetree-jump () (interactive) (let ((point (point))) (catch 'found (goto-char (point-max)) (while (outline-previous-heading) (let* ((hl (org-element-at-point)) (title (org-element-property :raw-value hl))) (when (member title (datetree-dates)) (org-show-context) (setq point (point)) (throw 'found t))))) (goto-char point))) ``` NB: Only these two lines had to be changed: ``` (goto-char (point-min)) (while (outline-next-heading) ``` > 1 votes --- Tags: org-mode ---
thread-68682
https://emacs.stackexchange.com/questions/68682
How can I make `forward-sexp` handle other balanced character-pairs such as < and > or << and >>?
2021-09-27T15:28:28.903
# Question Title: How can I make `forward-sexp` handle other balanced character-pairs such as < and > or << and >>? I am trying to find an easy and efficient way to modify the behaviour of `forward-sexp` to handle balanced pairs of characters not normally supported by it, such as balanced `<` and `>` and balanced `<<` and `>>`. My specific case is to enhance the support of Erlang but I believe it could apply to a lot of scenarios. The implementation of `forward-sexp` allows the use of a `forward-sexp-function` which means I could implement such a function. I am also aware of the SMIE library and will look into it. However I was hoping to find a variable that the C-implemented `scan-sexp` could use to define the matching pair but have not succeeded so far. It would seem the easiest and most efficient way of implementing such handling of balanced pair would be done there. Is there a variable one can use to augment or modify the behaviour of `scan-sexp`? # Answer I have been able to get `forward-sexp` to recognize the `<` and `>` pair by modifying the syntax table the erlang-mode uses: The erlang.el file has a function that sets the syntax table when the erlang-mode takes effect. It does the following: ``` (modify-syntax-entry ?< "." table) (modify-syntax-entry ?> "." table) ``` but it should be this instead: ``` (modify-syntax-entry ?< "(>" table) (modify-syntax-entry ?> ")<" table) ``` Since I can't modify erlang.el, a hook has to be used to modify the erlang.el syntax table variable: `erlang-mode-syntax-table` somewhere in initialization code I used something like this: ``` (with-eval-after-load 'erlang (defvar erlang-mode-syntax-table) ; prevent byte compiler warning (add-hook 'erlang-mode-hook (lambda () "Add < > pair matching." (modify-syntax-entry ?< "(>" erlang-mode-syntax-table) (modify-syntax-entry ?> ")<" erlang-mode-syntax-table))) ``` The `defvar` is there to prevent byte-compiler warnings only. The `with-eval-after-load 'erlang` delays execution of the code after erlang.el has loaded to ensure the hook is not over-written. **Alternative (but more complex)** An alternative, which also works but requires much more code would have been to write a function `my-erlang-forward-sexp` that handles the pairing it self and behaves as a replacement for `forward-sexp`, and then place the following inside the hook function instead: ``` (setq-local forward-sexp-function (function my-erlang-forward-sexp)) ``` It would set `forward-sexp-function` to `my-erlang-forward-sexp` only in buffers using the erlang-mode and would not modify the behaviour of other major modes. However writing that function is more complex. Modifying the syntax table is much simpler to do and takes less code. > 2 votes --- Tags: navigation, syntax, balanced-parentheses, sexp, parsing ---
thread-63985
https://emacs.stackexchange.com/questions/63985
Poly-Markdown+R does not find the right version of R for R code chunks
2021-03-20T01:59:01.837
# Question Title: Poly-Markdown+R does not find the right version of R for R code chunks I am working on a Rmarkdown document and I have R 4.0.4 running in a buffer. I try to export the document with `M-n e` and it finds R 3.6.3 ``` sessionInfo() ``` R version 3.6.3 This meant that I had a lot of trouble with packages not being found before I saw the underlying problem. I have a distribution R 3.6.3 in `/usr/bin` and a more recent R in `/use/local/bin`. poly-R may be using absolute path names but I can't see how to configure it. # Answer Polymode uses ESS to interact with R. Your locally-installed version of R in `/usr/local/bin` is probably not on the exec path. You can configure this via the variable `ess-rterm-version-paths`. You may also need to check the values in `ess-r-runner-prefixes` to make sure it includes `R-4`. These configurations have changed in the past few years, so it will be helpful to know which version of Emacs, ESS and polymode you are using, and also your OS. > 1 votes --- Tags: ess, r, polymode ---
thread-68694
https://emacs.stackexchange.com/questions/68694
magit equivalent of gitk's "touching paths"
2021-09-28T13:00:26.260
# Question Title: magit equivalent of gitk's "touching paths" I'd like to find commits touching specified path in a magit-log buffer. Gitk has this as a filter "touching paths". Is there a way to do this in Magit? I usually run `gitk --all` or `gitk mybranch otherbranch` when I need to find something in a repo; ie) while debugging and looking for some clue. Anyway, after I run `gitk` I decide to filter, say, by a directory. So, I insert the name of the directory in the filter text box, and select "touching paths" to highlight the commits touching the path. Because a successive commit not touching the path often time gives me a hint, I don't want to hide the commits by the filter. Even without hiding, I can easily jump from a commit to another commit by "↓" or "↑". # Answer From the magit status buffer, after pressing `l` once, you can configure the log. To filter for 'touching paths' you can use `--` and type (part of) the path for which you want commits touching it to be included in the log. After you have finished configuring, you can press `l` again to show the log. > 3 votes --- Tags: magit ---
thread-52579
https://emacs.stackexchange.com/questions/52579
Write a function that runs another function after adding a hook
2019-09-09T04:11:34.740
# Question Title: Write a function that runs another function after adding a hook I want to run some function `f` after adding a hook to a mode and after running `f` remove the hook that I added, returning the result of `f` if there is one. Here is a non-working version that I hope makes the intent clear: ``` (defun run-function-with-hook (mode-hook hook-fn fn) (add-hook mode-hook hook-fn) (message (concat "mode hooks before running: " (prin1-to-string (symbol-value mode-to-slowdown)))) (funcall fn) (remove-hook mode-hook hook-fn)) (run-function-with-hook 'org-mode-hook (message "opening org file") (message "opened org file")) ``` Is this a better fit for a macro? If so, perhaps the right answer to this is an answer using a macro instead. # Answer It looks like I had things mostly correct besides a variable I forgot to rename. The issue was that I needed to wrap the functions in `lambda` calls: ``` (defun run-function-with-hook (mode-hook hook-fn fn) (add-hook mode-hook hook-fn) (message (concat "mode hooks before running: " (prin1-to-string (symbol-value mode-hook)))) (funcall fn) (remove-hook mode-hook hook-fn)) (run-function-with-hook 'org-mode-hook (lambda () (message "opening org file")) (lambda () (message "opened org file"))) ``` > 0 votes # Answer I do this all the time with let-binding. For example, here I temporarily define the value of an org-mode hook. It automatically reverts outside the let definition. ``` #+BEGIN_SRC emacs-lisp (let ((org-export-before-parsing-hook '(org-ref-cite-natmove))) (org-open-file (org-latex-export-to-pdf))) #+END_SRC ``` or in this example, I temporarily remove the org-mode hook while opening a file: ``` (let* ((filename (pop org-db-queue)) (org-mode-hook '()) (enable-local-variables nil) (already-open (find-buffer-visiting filename)) (buf (find-file-noselect filename))) (org-db-log "Updating %s" filename) (with-current-buffer buf (org-db-update-buffer force)) (unless already-open (kill-buffer buf))) ``` > 0 votes --- Tags: hooks ---
thread-63399
https://emacs.stackexchange.com/questions/63399
Pass a table's colnames to an R block
2021-02-14T16:31:35.767
# Question Title: Pass a table's colnames to an R block I have an org file with this content: ``` #+name: my-table | *Type* | *Value* | |---------+---------| | Web | 744 | | Checks | 520 | | Cash | 105 | |---------+---------| | *Total* | 1369 | #+TBLFM: @5$2=vsum(@I..@II) ``` I would like to add an R script to draw a bar chart of the result so I tried: ``` #+NAME: barchart #+begin_src R :results output graphics file :colnames yes :session :exports none :var data=my-table[0:-2] :file my-table.png library(tidyverse) ggplot(data = data) + geom_bar(mapping = aes(x = X.Type., y = X.Value.), stat = "identity") #+end_src ``` This results in: I like the result except the "X.Value." and "X.Type." to label each axis. 1. Is what I'm doing the standard way to pass a table with column names to R? 2. Is the R script written appropriately? 3. Is there a way to use my column names (i.e., "Type" and "Value") instead of "X.Value." and "X.Type."? Alternatively, can I change the axis label in R? # Answer > 1 votes Your problem comes from an interaction between R and org syntax. The strings `*Type*` and `*Value*` are fine for org mode columns, but are invalid object names (or column names) in R. Consequently, when you pass them to R, the leading `*` is converted to `X.`, and the trailing `*` is converted to `.`. You can fix this by removing the asterixes (asterii?) from your table: ``` #+name: my-table | Type | Value | |---------+---------| | Web | 744 | | Checks | 520 | | Cash | 105 | |---------+---------| | Total | 1369 | #+TBLFM: @5$2=vsum(@I..@II) ``` And then changing the column names in your `aes()` directive to match: ``` #+NAME: barchart #+begin_src R :results output graphics file :colnames yes :session :exports none :var data=my-table[0:-2] :file my-table.png library(tidyverse) ggplot(data = data) + geom_bar(mapping = aes(x = Type, y = Value), stat = "identity") #+end_src ``` This produces the following figure: --- Tags: org-mode, org-babel, ess, r ---
thread-68703
https://emacs.stackexchange.com/questions/68703
`M-[` causes emacs to print weird (possibly escape) sequences
2021-09-28T21:30:12.770
# Question Title: `M-[` causes emacs to print weird (possibly escape) sequences I am using emacs from a remote ssh session. So I `ssh remote` in a terminal and launch it from there with `emacs`. When I set the following key binding ``` (global-set-key (kbd "M-[") 'backward-paragraph) ``` And I press keys starting with `<f5>` to `<f12>`, I get weird characters printed. For example pressing `<f5>` prints `15~` and also move cursor in some location. # Answer You’re in complicated territory. A terminal emulator listens for key events from the operating system, and translates them into characters. It then sends those characters to the running application (which in this case is Emacs, but the terminal doesn’t know or care what application it is). There are used to be a lot of different terminals in the world, and most of them were incompatible with each other. Exactly how they translated key events into characters was one of the incompatible things about them. In the modern era of terminal emulators, we mostly emulate the VT100, plus sometimes features from later terminals such as the VT220 or VT420. You don’t say what terminal emulator you are using, but in practice most of them just default to doing whatever xterm does. You can read in excrutiating detail exactly what xterm does, but I will try to summarize. By default, xterm pretends that your Alt key is a Meta key, and then does what the VT100 did, which is to translate any key press with a Meta modifier into an escape character followed by the modified key. Thus `M-a` becomes 0x1b 0x41, `M-b` becomes 0x1b 0x42, and so on. It follows then that `M-[` must be 0x1b 0x5b. So far this is not complicated. So what happens for the function keys? There is no character that corresponds to the F5 key directly, so it has to be translated into some sequence of bytes. Here is the relevant table from that document I linked to: ``` Key Escape Sequence ---------+----------------- F1 | SS3 P F2 | SS3 Q F3 | SS3 R F4 | SS3 S F5 | CSI 1 5 ~ F6 | CSI 1 7 ~ F7 | CSI 1 8 ~ F8 | CSI 1 9 ~ F9 | CSI 2 0 ~ F10 | CSI 2 1 ~ F11 | CSI 2 3 ~ F12 | CSI 2 4 ~ ``` SS3 and CSI are of course defined way earlier in the document: ``` … ESC O Single Shift Select of G3 Character Set (SS3 is 0x8f), VT220. This affects next character only. … ESC [ Control Sequence Introducer (CSI is 0x9b). … ``` So anywhere the document says that it sends SS3, it is really going to send an escape followed by an “O”, or 0x1b 0x4f. And any time it says that it will send CSI, it will actually send an escape followed by an “\[”, or 0x1b 0x5b. You may now begin to see the problem. Every time you hit `<f5>`, your terminal sends the bytes 0x1b 0x5b 0x31 0x35 0x7E. The first two bytes trigger your key binding, moving the cursor backwards by a paragraph. The the next three bytes all invoke `self-insert-command` and type their corresponding character, inserting a `15~` into the buffer. In fact, Emacs already had something bound to `M-[`. When Emacs starts up inside of a terminal it puts a key map there that handles all of the interesting escape sequences that it might receive, so that your arrow keys and function keys and whatnot will work. > 14 votes --- Tags: key-bindings, terminal-emacs ---
thread-10933
https://emacs.stackexchange.com/questions/10933
How to change faces of org-mode links depending on the link type?
2015-04-26T09:36:23.960
# Question Title: How to change faces of org-mode links depending on the link type? Org-mode offers a variety of different link types (\[http\], \[file\], \[bibtex\], \[magit\]...). However, they all get the same look defined by the face value for org-link. Is it possible to e.g. change the background color depending on the type of link? So that http links would have a yellow background and file links a blue one? # Answer > 2 votes Starting from Org-Mode version 9.x. Thanks to John Kitchin's answer in Fontify broken links in org-mode, I applied different faces for id-links and file-links with a code similar to this: ``` (defface org-link-id '((t :foreground "#50fa7b" :weight bold :underline t)) "Face for Org-Mode links starting with id:." :group 'org-faces) (defface org-link-file '((t :foreground "#ff5555" :weight bold :underline t)) "Face for Org-Mode links starting with file:." :group 'org-faces) (org-link-set-parameters "id" :face 'org-link-id) (org-link-set-parameters "file" :face 'org-link-file)) ``` # Answer > 1 votes I would make this a comment, but I don't have enough rep so here goes: Check out this function: org-activate-plain-links (in org.el). You can modify the function around the 'add-text-properties', doing a match on each link using a cond for instance. I have student supervision now, but if you don't succeed in doing this, I'll add more information later. # Answer > 1 votes See https://github.com/jkitchin/org-ref/blob/651d24df5f52bb3f0d31c71ebdb604ce356fe674/org-ref.el#L484 I use that code to change the appearance of links in org-ref using font lock at https://github.com/jkitchin/org-ref/blob/651d24df5f52bb3f0d31c71ebdb604ce356fe674/org-ref.el#L742 --- Tags: org-mode, faces, hyperlinks ---
thread-66803
https://emacs.stackexchange.com/questions/66803
How can I access the python documentation for the thing at cursor?
2021-07-22T15:48:38.357
# Question Title: How can I access the python documentation for the thing at cursor? ``` with open("foo.txt", mode="create") as f: print(file, text[0:300], file=f) ``` `ValueError: invalid mode: 'create'` Now pointint the cursor on =open=, followed by hitting `,` `h` offers: * **helm-pydoc** which asks to select one of the imported modules * **lsp-describe-thing-at-point** which displays amongst others `..mode:OpenTextMode =...` * **pylookup-lookup** which offers a large list where the word open appears None does help me understand the problem, nor lead to the documentation of **mode** How can I access the python documentation for the thing at point? # Answer > 1 votes One good solution that works here is by using simply `pydoc` (not `helm-pydoc`). Put your cursor somewhere on `open` and do `M-x pydoc-at-point-no-jedi`. Of course, you can bind some shortcut for it also. --- Tags: spacemacs, python ---
thread-68687
https://emacs.stackexchange.com/questions/68687
How can I color horizontal lines in org mode?
2021-09-27T18:11:49.773
# Question Title: How can I color horizontal lines in org mode? Both markdown mode and Org mode allow you to insert a number of dashes on an otherwise empty line (at least three in markdown mode, at least five in Org mode), that are rendered as horizontal rules in the exported output. In markdown mode, the dashes become green in the markdown buffer. Would it be possible to obtain the same behavior in an `org-mode` buffer, where the dashes become colorful? --- https://orgmode.org/manual/Horizontal-Rules.html > 12.9 Horizontal Rules: A line consisting of only dashes, and at least 5 of them, is exported as a horizontal line. # Answer > 1 votes Please see the Professor John Kitchin\`s original solution from: https://list.orgmode.org/87h7e5dtbb.fsf@ucl.ac.uk/T/#t --- > you can add a rule like this in an org-mode hook: ``` (add-hook 'org-mode-hook (lambda () (font-lock-add-keywords nil '(("^-\\{5,\\}" 0 '(:foreground "green" :weight bold)))))) ``` > that will make a line starting with at least 5 - be green and bold in color. --- Tags: org-mode ---
thread-68702
https://emacs.stackexchange.com/questions/68702
Use of defvar in straight.el's bootstrapping
2021-09-28T21:28:31.800
# Question Title: Use of defvar in straight.el's bootstrapping The package `straight.el` requires the following bootstrapping code in your emacs config: ``` (defvar bootstrap-version) (let ((bootstrap-file (expand-file-name "straight/repos/straight.el/bootstrap.el" user-emacs-directory)) (bootstrap-version 5)) (unless (file-exists-p bootstrap-file) (with-current-buffer (url-retrieve-synchronously "https://raw.githubusercontent.com/raxod502/straight.el/develop/install.el" 'silent 'inhibit-cookies) (goto-char (point-max)) (eval-print-last-sexp))) (load bootstrap-file nil 'nomessage)) ``` The use of `defvar` to initialize `bootstrap-version` was a little confusing to me, given that it's only used in a `let` statement that could have also just as easily initialized and defined it. However, it is invoked later in the `install.el` file that is retrieved into the buffer later. I'm not confident I fully understand the use of `defvar`, but is it the case that initializing `bootstrap-version` using a `defvar` statement makes it available to `install.el`? Would it not be accessible otherwise? If that's not the case, why is this variable initialized in this way instead of in the `let` expression? # Answer > 3 votes The form `(defvar bootstrap-version)` doesn't set the value of `bootstrap-version`, and will not over-write the value of `bootstrap-version` if it was already set. It is also not necessary to make the variable "available" to `straight.el` or any of the files it includes. The only thing the defvar accomplishes here is to declare `bootstrap-version` as "special", meaning that it is treated as a dynamic variable. `straight.el` uses lexical binding, so without this declaration `bootstrap-version` would be lexically bound. To understand the difference, you might find Dynamic vs Lexical Binding helpful. --- Tags: variables, defvar, straight.el ---
thread-68701
https://emacs.stackexchange.com/questions/68701
debugging why emacs is autoformatting on save hook
2021-09-28T21:23:10.993
# Question Title: debugging why emacs is autoformatting on save hook I'm currently facing an issue where I am trying to save a file, but some save hook is triggering an auto formatting the file in a way that I do not want. I am not sure how to debug this issue. Ideally, I would be able to see all the events being executed when the `save-hook` is triggered. Specifically, I want to edit a config file that looks something like this ``` # # my_config # SOMETHING=foo ``` When I save this file, emacs autoformats the document and adds a space before and after `=`. I do not want this behavior and I am trying to figure out why on earth it's happening. example gif of this issue: I am opening the buffer in `text-mode`. These are the minor mode emacs reports are enabled: ``` Enabled minor modes: Auto-Composition Auto-Compression Auto-Encryption Auto-Insert Blink-Cursor Column-Number Company Dap Dap-Auto-Configure Dap-Tooltip Dap-Ui Dap-Ui-Controls Dap-Ui-Many-Windows Electric-Indent File-Name-Shadow Flx-Ido Flycheck Flyspell Font-Lock Global-Auto-Revert Global-Company Global-Eldoc Global-Flycheck Global-Font-Lock Global-Git-Commit Ido-Everywhere Ido-Vertical Line-Number Lsp-Treemacs-Sync Magit-Auto-Revert Mouse-Wheel Projectile Recentf Save-Place Savehist Shell-Dirtrack Show-Paren Tooltip Transient-Mark Treemacs-Filewatch Treemacs-Follow Treemacs-Fringe-Indicator Treemacs-Git Visual-Line Which-Key Yas Yas-Global ``` I am at a loss as to how I can debug this issue. Is there a clever way to see what emacs is doing when the `save-hook` is triggered? # Answer > 1 votes The main save hooks are `before-save-hook` and `after-save-hook`. You can see the current value of these via e.g. `C-h v before-save-hook`. You may see something useful in the resulting output that you can search for in your config. You may also find your problem by search through your configuration for the names of the hooks themselves. Beyond that, you may need to bisect your config to narrow down the source of the problem, as described in this question. --- Tags: debugging, hooks, text-editing ---
thread-48646
https://emacs.stackexchange.com/questions/48646
How can I use the #+OPTIONS: broken-links: option to ignore broken links, in a specific way?
2019-03-29T05:27:07.260
# Question Title: How can I use the #+OPTIONS: broken-links: option to ignore broken links, in a specific way? I have a very large orgmode document that has internal links to many different parts of the document. If I try to export a subtree that has an internal link that points to a part of the document outside of the subtree exported, I get an error ``` Unable to resolve the link: "Determinism" ``` to get around this, I've written ``` #+OPTIONS: broken-links:auto ``` which makes it so that when I export the subtree, it can export *but* in the export the link's title isn't exported, it's simply a blank spot. Basically in the original document's subtree I'll have this internal link that points to outside of the subtree like this ``` Philosophers love [[determinism]] ``` but upon export It becomes ``` Philosophers love ``` and what I want in the export is ``` Philosophers love determinism ``` I'm wondering if this is achievable. I'm using spacemacs on MacOS, Mojave. # Answer > 3 votes As of org version `9.5-dev` in 2021 (and possibly earlier), the option ``` #+OPTIONS: broken-links:mark ``` Produces nearly the desired behaviour: ``` #+OPTIONS: broken-links:mark * Test Philosophers love [[determinism]] ``` The documentation for the customization option `org-export-with-broken-links` is: ``` org-export-with-broken-links is a variable defined in ‘ox.el’. Its value is nil You can customize this variable. This variable was introduced, or its default value was changed, in version 26.1 of Emacs. Non-nil means do not raise an error on broken links. When this variable is non-nil, broken links are ignored, without stopping the export process. If it is set to ‘mark’, broken links are marked as such in the output, with a string like [BROKEN LINK: path] where PATH is the un-resolvable reference. This option can also be set with the OPTIONS keyword, e.g., "broken-links:mark". ``` There is no option to customize the appearance of the broken link. However, the function involved is `org-export-data` in the file `ox.el`, and it would be relatively straightforward to over-write the function if you want to tweak things. --- Tags: org-mode, org-export, spacemacs ---
thread-38183
https://emacs.stackexchange.com/questions/38183
How to exclude a file from agenda
2018-01-18T22:40:28.530
# Question Title: How to exclude a file from agenda I have a set of org files all in one directory, as follows ``` '(org-agenda-files (quote ("~/GTD/ActiveProjects/"))) ``` I would like to have an agenda that excludes one file `Home.org` so that I don't see it when I'm at work. Here is my current custom agenda setup ``` '(org-agenda-custom-commands (quote (("n" "Today's agenda and all next actions for current projects" ((agenda "" ((org-agenda-ndays 1) (org-agenda-time-grid nil))) (tags-todo "CALL|URGENT" ((org-agenda-overriding-header "Urgent Home tasks") (org-agenda-files (quote ("~/GTD/OtherAORs/Home.org"))))) (tags-todo "-NEXTMONTH-SOMEDAY-SCHEDULED-DEADLINE" ((org-agenda-overriding-header "All next actions except those under NEXTMONTH or SOMEDAY ")))) ((org-agenda-compact-blocks t)) ("~/Dropbox/org-mode/work-agenda.txt"))))) ``` This does what I want it to do, that is it shows me all the work TODOs in the last command, and in the second-last command it shows TODOs from Home.org but only CALLs and URGENTs. But I would like to have the `Home.org` (for re-fileing into it) in the same folder as the other org files, and set the org-agenda-files to all org files in the `~/GTD/ActiveProjects/` directory except Home.org I've read about `seq-filter` and `remove-if` and to use them in a custom org-agenda-files something like this: ``` (tags-todo "-NEXTMONTH-SOMEDAY-SCHEDULED-DEADLINE" ((org-agenda-overriding-header "All next actions except those under NEXTMONTH or SOMEDAY ")) (org-agenda-files (quote ("~/GTD/OtherAORs/Home.org"))))) ``` What's the easiest way to do this? # Answer # Do the following steps: ### 1. Tag all entries in the *Home.org* file. This can be done the easiest with a `FILETAGS`, which applies the tag on all entries in the given file. This can be achieved by adding the following at the top of the *Home.org* file: ``` #+FILETAGS: HOME ``` ### 2. Create a custom agenda command to filter out tagged entries: ``` (custom-set-variables '(org-agenda-custom-commands '(("c" "Custom agenda, ignore HOME tag" ((agenda "")) ((org-agenda-tag-filter-preset '("-HOME")))))) ``` With this, when you open the `org-agenda` next time, you can use the `c` shortcut to load the custom agenda, where all entries with the `:HOME:` tag are being filtered out. > 7 votes # Answer Here's another way to do this (it excludes `home.org` from the list of all `.org` files in `tasks/` folder of `org-directory`): ``` (agenda "" ((org-agenda-files (--remove (s-matches? "home.org$" it) (f-glob "tasks/*.org" org-directory))))) ``` It requires libraries `dash.el`, `f.el` and `s.el`. > 1 votes # Answer To exclude a file from a directory of org files, just remove it: ``` (remove "/path/to/file" org-agenda-files) ``` Here is my custom command for excluding everything from ~/Dropbox/org/work.org: ``` (setq org-agenda-custom-commands '(("n" "Non-work" ;; Show all todos and everything due today, except work related tasks. ((agenda "" ( ;; Limits the agenda to a single day (org-agenda-span 1) )) (todo "TODO")) ((org-agenda-files (remove "~/Dropbox/org/work.org" org-agenda-files)))))) ``` > 1 votes # Answer Take a look at the variable `org-agenda-files`: ``` The files to be used for agenda display. If an entry is a directory, all files in that directory that are matched by org-agenda-file-regexp will be part of the file list. If the value of the variable is not a list but a single file name, then the list of agenda files is actually stored and maintained in that file, one agenda file per line. In this file paths can be given relative to org-directory. Tilde expansion and environment variable substitution are also made. Entries may be added to this list with M-x org-agenda-file-to-front and removed with M-x org-remove-file. ``` So you could create a file, /wherever/org\_files.org, and include everything except the file(s) you want to exclude. You could also modify the org-agenda-file-regexp to exclude file(s). Or use `M-x org-remove-file` when you have the file you want to remove opened. When testing, `M-x org-remove-file` modifies the value of `org-agenda-files` to be all the current org agenda files, minus the one you just removed. When I added a new file to my org directory, the value of `org-agenda-files` was not updated to add that file, so I'm hesitant to seriously suggest `M-x org-remove-file`. Same with pointing `org-agenda-files` at a file, you'd have to manually update that file every time you add a new file in your org directory. So it seems to me that the best solution is to update the regex. > 0 votes --- Tags: org-mode, org-agenda ---
thread-12121
https://emacs.stackexchange.com/questions/12121
Org mode - Parsing rich HTML directly when pasting?
2015-05-04T10:57:59.180
# Question Title: Org mode - Parsing rich HTML directly when pasting? Currently, for notetaking tools like `Evernote` and `Quiver`, I can directly copy HTML content from my favorite browser and then paste them into the app, with all the formatting + link preserved. However in orgmode it seems that all the formatting info is lost. I've seen somebody suggest using `eww` to browse the web and copy the content via `eww-org`. However that is really tedious(I don't think there would be a lot of people browsing the web using `eww` instead of modern browsers nowadays. I'll have to open that link again in `eww` and do the copying, not to mention sometimes `eww` doesn't render the contents nicely). Is it possible to let `Emacs` directly parse the copied HTML when pasting? Even if there's no existing tool for that yet, is it feasible to make one? This is almost the only thing that stops me from switching to `orgmode` from other notetaking tools. # Answer > is it feasible to make one? Since this is emacs, **yes**. My approach is to use a 3rd party tools that can take HTML and convert to plain text or even directly to Org format. I think this is an ugly hack, and there may be better ways to do this, but it looks like it works for my test cases. ``` (defun kdm/html2org-clipboard () "Convert clipboard contents from HTML to Org and then paste (yank)." (interactive) (kill-new (shell-command-to-string "osascript -e 'the clipboard as \"HTML\"' | perl -ne 'print chr foreach unpack(\"C*\",pack(\"H*\",substr($_,11,-3)))' | pandoc -f html -t json | pandoc -f json -t org | sed 's/ / /g'")) (yank)) ``` Unfortunately, HTML is incredibly complex now - no longer some simple hand-written tags. This complex HTML tagging requires the complicated shell command above. It does the following: 1. `osascript` gets the HTML text from the clipboard. It is hex encoded, so 2. perl converts the hex to a string 3. We could convert that HTML to Org directly with pandoc, but the HTML is full of complicated tags and therefore produces a ton of Org code. In order to simply the HTML to the minimal set of tags needed to capture the formatting, I 4. Convert the HTML to json, and then 5. Convert the json to Org (these two steps simplify the HTML). 6. Replace non-standard spaces with standard ones. Note that `osascript` is for MacOS. To modify steps 1-2 for Linux, replace the argument of shell-command-to-string with ``` "xclip -o -t text/html | pandoc -f html -t json | pandoc -f json -t org" ``` In any case, the output of the `pandoc` command is returned to emacs, and inserted into the buffer. Bind the new Emacs command to a key similar to "paste" but that means "paste-and-convert-from-html" to you, and it should work. Alternatively, if you don't want to think about which paste command to use, here is a Linux version that will convert HTML when that is available on the clipboard and will otherwise fall back to plain text: ``` "xclip -o -t TARGETS | grep -q text/html && (xclip -o -t text/html | pandoc -f html -t json | pandoc -f json -t org) || xclip -o" ``` > 21 votes # Answer I wrote an add-on Copy as Org-Mode for Firefox which can do this in browser directly (copying the rich HTML directly, instead of copying the raw HTML code), it even can handle HTML tables into Org-mode format. > 3 votes # Answer Short answer: consider using `org-web-tools-read-url-as-org`. Long answer: If you just want to parse html, you can use dom module for example: ``` (let* ((dom (with-temp-buffer (insert html) (libxml-parse-html-region (point-min) (point-max)))) (title (cl-caddr (car (dom-by-tag dom 'title))))) ``` If you want to automatically render html into something more or less readable, you can use eww, w3m and other text browsers. Personally I prefer to convert web documents into org mode. I know several tools of converting html to org mode: already mentioned `pandoc`, org-web-tools and html2org. My favorate tool is `org-web-tools`, because `pandoc` and `html2org` are converting the hole document. `org-web-tools` conversly detect potential poorly-rendered parts and removes it. Below is short description of how it is done: `org-web-tools-read-url-as-org` function loads html from specified url, converts it into org-mode document and then loads it in selected window. The main advantage of this approach is that its code `org-web-tools--url-as-readable-org -> org-web-tools--eww-readable -> eww-score-readability` calculates score for document parts and removes parts that are probably not worth viewing (adds, poorly rendered menu). By the way `html2org` is extremely simple tool, which probably can be easily hacked to render specific parts of html page. > 0 votes # Answer Assuming macOS, to get the clipboard as HTML, install: ``` git clone https://github.com/chbrown/macos-pasteboard cd macos-pasteboard make install ``` Then you can use the function ``` function pbpaste-html() { command pbv public.html public.utf8-plain-text } ``` Together with pandoc: ``` input="$(gmktemp)" pbpaste-plus > "$input" pandoc --wrap=none --from "html" --to "org" "$input" -o "-" | pbcopy ``` Then paste the result in emacs. > 0 votes --- Tags: org-mode, copy-paste, formatting, html ---
thread-68719
https://emacs.stackexchange.com/questions/68719
How to merge overlapping ranges given a list of (min . max) cons cells?
2021-09-30T06:01:31.737
# Question Title: How to merge overlapping ranges given a list of (min . max) cons cells? Given a list of cons cells, what is an efficient way to merge overlapping ranges? When any values minimum or maximum are within the bounds (inclusive) of any of the other cons cells in the list, these should be merged until there are no more cells to merge. Either into a new list or destructively modifying the list. ``` (merge-overlapping-ranges nil) => nil (merge-overlapping-ranges '((0 . 1))) => '((0 . 1)) (merge-overlapping-ranges '((0 . 5) (6 . 9))) => '((0 . 5) (6 . 9)) (merge-overlapping-ranges '((0 . 5) (5 . 9))) => '((0 . 9)) (merge-overlapping-ranges '((5 . 9) (0 . 5))) => '((0 . 9)) (merge-overlapping-ranges '((1 . 9) (3 . 8))) => ((1 . 9)) (merge-overlapping-ranges '((0 . 9) (0 . 9))) => ((0 . 9)) (merge-overlapping-ranges '((1 . 2) (3 . 4) (5 . 6) (7 . 8) (1 . 100))) => '((1 . 100)) ``` # Answer This is a function to merge overlapping ranges, although it's possible there is a more efficient way to do this. ``` (defun merge-overlapping-ranges (ranges) "Destructively modify and return RANGES with overlapping values removed. Where RANGES is an unordered list of (min . max) cons cells." (cond ((cdr ranges) ;; Simple < sorting of cons cells. (setq ranges (sort ranges (lambda (x y) (or (< (car x) (car y)) (and (= (car x) (car y)) (< (cdr x) (cdr y))))))) ;; Step over `ranges', de-duplicating & adjusting elements as needed. (let ((ranges-iter ranges) (ranges-next (cdr ranges))) (while ranges-next (let ((head (car ranges-iter)) (next (car ranges-next))) (cond ((< (cdr head) (car next)) (setq ranges-iter ranges-next) (setq ranges-next (cdr ranges-next))) (t (when (< (cdr head) (cdr next)) (setcdr head (cdr next))) (setq ranges-next (cdr ranges-next)) (setcdr ranges-iter ranges-next))))) ranges)) (t ;; No need for complex logic single/empty lists. ranges))) ``` ``` (defun test-merge-ranges (args) (princ (format "(merge-overlapping-ranges %s) => %S\n" (format "%S" args) (merge-overlapping-ranges args) #'external-debugging-output))) (test-merge-ranges nil) (test-merge-ranges '((0 . 1))) (test-merge-ranges '((0 . 5) (6 . 9))) (test-merge-ranges '((0 . 5) (5 . 9))) (test-merge-ranges '((5 . 9) (0 . 5))) (test-merge-ranges '((1 . 9) (3 . 8))) (test-merge-ranges '((1 . 9) (3 . 8))) (test-merge-ranges '((0 . 9) (0 . 9))) (test-merge-ranges '((1 . 2) (3 . 4) (5 . 6) (7 . 8) (1 . 100))) ``` When run as a script produces: `emacs --script merge-overlapping-ranges.el` ``` (merge-overlapping-ranges nil) => nil (merge-overlapping-ranges ((0 . 1))) => ((0 . 1)) (merge-overlapping-ranges ((0 . 5) (6 . 9))) => ((0 . 5) (6 . 9)) (merge-overlapping-ranges ((0 . 5) (5 . 9))) => ((0 . 9)) (merge-overlapping-ranges ((5 . 9) (0 . 5))) => ((0 . 9)) (merge-overlapping-ranges ((1 . 9) (3 . 8))) => ((1 . 9)) (merge-overlapping-ranges ((0 . 9) (0 . 9))) => ((0 . 9)) (merge-overlapping-ranges ((1 . 2) (3 . 4) (5 . 6) (7 . 8) (1 . 100))) => ((1 . 100)) ``` > 2 votes --- Tags: list ---
thread-68122
https://emacs.stackexchange.com/questions/68122
How to adjust the search in file behavior in spacemacs?
2021-08-16T02:50:04.053
# Question Title: How to adjust the search in file behavior in spacemacs? Currently, when I using vim searching "/searchforsth" with "n" to search for words. After navigating through the words on this page, the next word that is not on the current page will appear at the bottom. But I am used to the behavior that this word will display on top or middle of this page, just like pressing "zt" or "zz". So I can see the following code of this searched pattern. Is there a way to define this behavior by myself? Thanks in advance. # Answer > 1 votes You can achieve this by advising `evil-ex-search` as follows: ``` (advice-add 'evil-ex-search :after #'recenter) ``` --- Tags: spacemacs, search ---
thread-66600
https://emacs.stackexchange.com/questions/66600
Spacemacs, using a package not found in melpa
2021-07-06T08:36:14.770
# Question Title: Spacemacs, using a package not found in melpa I want to use the package `ox-ipynb` in spacemacs. I tried adding under `dotspacemacs-additional-packages`, but I guess since it's not on melpa, spacemacs couldn't find it. I've also tried downloading the ox-ipynb.el file itself and loading it directly in my org-mode buffer like this: ``` #+BEGIN_SRC emacs-lisp (load-file "~/emacs/ox-ipynb.el") #+END_SRC ``` which gave me: `load-with-code-conversion: Symbol’s value as variable is void: Skip` Any suggestions? And in general, how do I make spacemacs install packages that are not on melpa? # Answer > 0 votes You can do this by using a quelpa recipe under `dotspacemacs-additional-packages` in your dotfile as follows: ``` (ox-ipynb :location (recipe :fetcher github :repo "jkitchin/ox-ipynb"))) ``` Currently, this possibility is only described in the docs about 'configuration layer development\` Alternatively, you can install my small update of benneti's spacemacs jupyter layer. I once started that update, but probably I did not consider it finished as I did not push it to github (I guess I just wanted to add some things to the README). But as far as I know it is fully functional (not tested), so I pushed it now. --- Tags: org-mode, spacemacs, package-repositories ---
thread-68723
https://emacs.stackexchange.com/questions/68723
The property ORDERED does not prevent switching TODO state
2021-09-30T07:16:37.320
# Question Title: The property ORDERED does not prevent switching TODO state a minimal example to get my question clear (copied from the Org Manual to my org file, only changed the last line): ``` * Parent :PROPERTIES: :ORDERED: t :END: ** TODO a ** TODO b, needs to wait for (a) ** DONE c, needs to wait for (a) and (b) ``` In my understanding setting the last line from TODO to DONE state should not be possible because of the ORDERED property. But in my org file I can do this. I did not find the variable where I can control this behaviour, so I would kindly ask for help. # Answer > 1 votes The variable is mentioned just above the example. So you should set/customize `org-enforce-todo-dependencies` to `t`. --- Tags: org-mode, todo ---
thread-68706
https://emacs.stackexchange.com/questions/68706
unexpected "Visit tags table (default TAGS)" prompt when looking up definitions with lsp-mode and gopls
2021-09-29T10:44:27.060
# Question Title: unexpected "Visit tags table (default TAGS)" prompt when looking up definitions with lsp-mode and gopls I'm using **company-mode** with **lsp-mode** as lsp client and **gopls** as lsp backend in order to lookup function and variable definitions in go projects. On some repositories, when I want to lookup a definition (`M-.`) I get an unexpected: ``` "Visit tags table (default TAGS):..." ``` ...instead of jumping to the function definition. For instance: How can I fix this? Thanks! # Answer > 1 votes As mentioned in the comments, a workaround for this issue is to start emacs on a folder (or on nothing) instead of on a single source file. This was discussed for VScode with gopls as backend here: https://stackoverflow.com/a/49977881/497180 --- Tags: company-mode, lsp-mode, lsp, golang, tags ---
thread-47444
https://emacs.stackexchange.com/questions/47444
Org mode - Copy cells from a remote org-table with shifted columns
2019-01-27T18:18:06.783
# Question Title: Org mode - Copy cells from a remote org-table with shifted columns I want to copy the values of a shifted range of cells from a remote table. Example: ``` #+NAME: TBL1 | 1 | 2 | 3 | 4 | | | | | | #+NAME: TBL2 | | 5 | 6 | 7 | 8 | | | | | | | ``` The table TBL1 should look like this in the end: ``` #+NAME: TBL1 | 1 | 2 | 3 | 4 | | 5 | 6 | 7 | 8 | ``` I'm currently doing this with a dedicated function for each of 15+ cells, which makes the `#+TBLFM:` line super long and is not maintainable. An efficient way to accomplish this is by using the lisp function `identity`: ``` #+NAME: TBL1 | 1 | 2 | 3 | 4 | | | 5 | 6 | 7 | #+TBLFM: @2$1..@2$4='(identity remote(TBL2, @1$$#)) ``` Problem is, that this function looks for values in the cells `@1$1..@1$4`. I want to shift the cells to look at to the right (`@1$2..@1$5`). This has to be done via the REF value for the remote function, (`@1$$#`). If I understand the syntax correctly, `$$#` is pointing to the current column of the cell which is going to be filled with the remote value (e.g. for cell `@2$1` in `TBL1`, `$$#` becomes `$1`). So this has to be shifted to the right with something like `$$#+1`. What is the correct reference for my example? # Answer > 2 votes You can use the `org-table-get-remote-range` function with some string manipulation, although it's not pretty: ``` #+NAME: TBL1 | 1 | 2 | 3 | 4 | | 5 | 6 | 7 | 8 | #+TBLFM: @2='(org-table-get-remote-range "TBL2" (concat "@" "1$" (number-to-string (+ $# 1)))) ``` Care must be taken to not write a reference literal in the lisp code to avoid immediate substitution of the table contents into the code before it is evaluated. For this reason the "@" is separate from the "1" in the `concat` function call. --- Tags: org-mode, org-table ---
thread-68733
https://emacs.stackexchange.com/questions/68733
Delete duplicates from company popups
2021-09-30T13:37:56.713
# Question Title: Delete duplicates from company popups I use the following snippet to set up `company-mode` for text files and derived modes. I use a curated word list as the source for `company-ispell`. ``` (progn (defun sb/company-text-mode () "Add backends for text completion in company mode." (setq-local company-minimum-prefix-length 2) (set (make-local-variable 'company-backends) '(company-files ;; FIXME: Delete duplicates ;; Give priority to dabbrev completions over ispell (:separate company-dabbrev company-ispell) ))) (dolist (hook '(text-mode-hook)) ; Extends to derived modes like `markdown-mode' and `org-mode' (add-hook hook #'sb/company-text-mode))) ``` How can I avoid duplicates from appearing in `company` popups in cases where `company-dabbrev` returns a value? Thanks. # Answer You may try out setting `company-transformers` to `delete-dups`, as was suggested in one of the `Company` threads: ``` (setq-local company-transformers '(delete-dups) company-backends '(company-files (:separate company-dabbrev company-ispell))) ``` It'd be interesting to know if you get any performance implications in case of large `ispell` backend candidates list. > 1 votes --- Tags: company-mode, company ---
thread-68725
https://emacs.stackexchange.com/questions/68725
Interchange Foreground and Background Colors when highlighting selected text
2021-09-30T08:06:01.787
# Question Title: Interchange Foreground and Background Colors when highlighting selected text I use something like this to control the background color of my selected text: ``` (region ((t (:background ,green)) (t :inverse-video t))) ``` However some foreground colors don't go well with my background color and the text becomes hard to read. So I experimented with different background colors for `region`, but the results have not been satisfactory. Now I wish for this behavior: **Interchange the background and foreground colors on my selected text.** The following images are for illustration of what I want: 1. Without Selection: 2. With Selection: With this I feel, I will be able to demarcate the selected text all the while retaining my syntax highlighting along with readability. How do I accomplish this within Emacs? # Answer Perhaps I don't understand. Just customizing face `region` to (only) use inverse-video gives you what you're asking for, as far as I can see. So just get rid of the imposition of a green background: > 0 votes --- Tags: faces, colors, region, highlighting ---
thread-68734
https://emacs.stackexchange.com/questions/68734
How can I add minor modes to the temporary buffers used to edit org-src-blocks?
2021-09-30T16:14:15.207
# Question Title: How can I add minor modes to the temporary buffers used to edit org-src-blocks? I would like to chose which extra-modes would be turned on in temporary buffers, which are dedicated to editing code, through `org-edit-special` (`C-x '`). For an example, `auto-complete-mode` and `rainbow-delimiters-mode` in every `org-edit-special buffer` etc. # Answer `org-edit-special` turns on `org-src-mode`, a minor mode, whose mode hook is called when entering (or exiting) the mode. So you can turn on your minor modes in the `org-src-mode` hook: ``` (add-to-hook 'org-src-mode-hook (lambda () (auto-complete-mode 1) (rainbow-delimiters-mode 1) ...)) ``` The doc string for `org-src-mode-hook` says: ``` org-src-mode-hook is a variable defined in ‘org-src.el’. Its value is (org-src-babel-configure-edit-buffer org-src-mode-configure-edit-buffer) Original value was nil This variable may be risky if used as a file-local variable. You can customize this variable. Hook run after Org switched a source code snippet to its Emacs mode. This hook will run: - when editing a source code snippet with ‘C-c '’ - when formatting a source code snippet for export with htmlize. You may want to use this hook for example to turn off ‘outline-minor-mode’ or similar things which you want to have when editing a source code file, but which mess up the display of a snippet in Org exported files. ``` Untested, but (dare I say it?) it should work :-) > 1 votes --- Tags: org-mode ---
thread-68689
https://emacs.stackexchange.com/questions/68689
(Org-Beamer Exporter) I would like to have a LaTeX snippet inbetween frames
2021-09-28T00:15:51.920
# Question Title: (Org-Beamer Exporter) I would like to have a LaTeX snippet inbetween frames I would like to change the beamer presentation background. To that end, I have to issue the following command between two frames (that is, outside any frame) ``` \usebackgroundtemplate{\includegraphics[height=\paperheight]{../Apresetacoes/Apres1/img/5.png}} ``` As frames are continuous in orgmode - either content are in the last or the next header - , I'm unable to have this piece of code in between frames. ``` *** Quadrado rotativo :PROPERTIES: :BEAMER_COL: 1 # :BEAMER_ENV: block :END: Something #+beamer: \framebreak #+beamer: \usebackgroundtemplate{\includegraphics[height=\paperheight]{../Apresetacoes/Apres1/img/5.png}} *** :PROPERTIES: :BEAMER_opt: standout :END: \begin{modern-quote-env} \begin{modern-quote} \color{red} \textbf{Perguntas?} \rule{\linewidth}{0.5mm} \end{modern-quote} \end{modern-quote-env} ``` Gives: ``` \begin{frame}[label={sec:orgc82c151}]{Quadrado rotativo} something \framebreak %% Trying to end the frame! (Not working) \usebackgroundtemplate{\includegraphics[height=\paperheight]{../Apresetacoes/Apres1/img/5.png}} \end{frame} \begin{frame}[label={sec:org008ba0c},standout]{} \begin{modern-quote-env} \begin{modern-quote} \color{red} \textbf{Perguntas?} \rule{\linewidth}{0.5mm} \end{modern-quote} \end{modern-quote-env} \end{frame} ``` But, I want to achieve this export: ``` \begin{frame}[label={sec:orgc82c151}]{Quadrado rotativo} something \end{frame} \usebackgroundtemplate{\includegraphics[height=\paperheight]{../Apresetacoes/Apres1/img/5.png}} \begin{frame}[label={sec:org008ba0c},standout]{} \begin{modern-quote-env} \begin{modern-quote} \color{red} \textbf{Perguntas?} \rule{\linewidth}{0.5mm} \end{modern-quote} \end{modern-quote-env} \end{frame} ``` # Answer > 1 votes For this I use a "fake" headline at the chosen level with the :ignore: tag, and insert the content under this headline. The headline is not considered, but the content is. A working example (with a fake headline at the first level) : ``` #+OPTIONS: H:2 toc:nil #+LaTeX_CLASS: beamer * First part ** Slide 1 Something * Fake headline :ignore: #+beamer: \usebackgroundtemplate{\includegraphics[]{./Images/background.png}} * Second part ** Slide 2 Something else ``` Result: --- Tags: org-mode, latex, beamer ---
thread-68730
https://emacs.stackexchange.com/questions/68730
org-table-iterate not working for tables with named columns
2021-09-30T11:02:53.853
# Question Title: org-table-iterate not working for tables with named columns I have the following two tables: ``` | ! | slope | intercept | xval | yval | |---+-------+-----------+-------+------| | | 1.2 | -5 | 1.4 | | | | 2.4 | 2 | -5 | | | | -5.6 | -3 | 2.2 | | | | -0.2 | 4 | 2.718 | | | | .56 | 3.14 | -0.5 | | #+TBLFM: $5=$2*$4+$3 | | slope | intercept | xval | yval | |---+-------+-----------+-------+------| | | 1.2 | -5 | 1.4 | | | | 2.4 | 2 | -5 | | | | -5.6 | -3 | 2.2 | | | | -0.2 | 4 | 2.718 | | | | .56 | 3.14 | -0.5 | | #+TBLFM: $5=$2*$4+$3 ``` The only difference between these tables is that the first has named columns while the second doesn't. For both tables, I can calculate values in the last column one at a time by doing `M-x org-table-recalculate` or `C-c *`, but iteratively updating the table using `M-x org-table-iterate` or `C-u C-u C-c *` only works for the second table. For the first table, if I run `org-table-iterate`, I get the message "Table was already stable." Is this a bug, or am I not understanding how named columns are supposed to work? I am running Org 9.4.6 and Emacs 27.2 on Windows 10 # Answer > 1 votes The documentation (`C-h i g(org)Advanced Features`) says: > ``` > Important: Please note that for these special tables, recalculating > the table with ‘C-u C-c *’ only affects rows that are marked ‘#’ or > ‘*’, and fields that have a formula assigned to the field itself. > The column formulas are not applied in rows with empty first field. > > ``` So e.g. this works: ``` | ! | slope | intercept | xval | yval | |---+-------+-----------+-------+--------| | * | 1.2 | -5 | 1.4 | -3.32 | | * | 2.4 | 2 | -5 | -10. | | * | -5.6 | -3 | 2.2 | -15.32 | | * | -0.2 | 4 | 2.718 | 3.4564 | | * | .56 | 3.14 | -0.5 | 2.86 | #+TBLFM: $5=$2*$4+$3 ``` --- Tags: org-mode, org-table ---
thread-61725
https://emacs.stackexchange.com/questions/61725
Create orgmode agenda from remote directory recursively over ssh
2020-11-13T15:32:52.160
# Question Title: Create orgmode agenda from remote directory recursively over ssh I've set up a vserver with my directory containing various `.txt` files used as Org files and other files. Now I am trying to get my local Emacs build an agenda gathering all data from the remote files scattered in different subfolders of my remote directory `nexus`. So I found this ``` (setq org-agenda-files (mapcar 'abbreviate-file-name (split-string (shell-command-to-string "find ~/org -name \"*.org\"") "\n"))) ``` I customized it to ``` (setq org-agenda-files (mapcar 'abbreviate-file-name (split-string (shell-command-to-string "ssh foo@11.111.11.11 \"find ~/nexus -name \"*.txt\"\"") "\n"))) ``` to filter `.txt` files for agenda items (`.txt` files work for my agenda locally - I've managed to do that). But it still won't work. My guess: I did not write the shell query correctly. Also, I am wondering if this would be a suited approach to check my agenda remotely from different devices. For example, it is planned to setup orgzly and termux later to also access those files. Additional info: The size of the nexus is about a few thousand different files and a few hundred text files with org content stretching for 500 to 5000 lines. # Answer This worked for myself ``` (shell-command-to-string "ssh myhost \"find Org -name *.org\"") ``` > 0 votes --- Tags: org-mode, eshell ---
thread-68728
https://emacs.stackexchange.com/questions/68728
Org Tangle if file does not exist
2021-09-30T10:19:29.367
# Question Title: Org Tangle if file does not exist I've been trying to work out if it's possible to tangle a file if it's not existent on the system. I came across Can Org Babel conditionally tangle code blocks based on system-type? which gave me a starting point, however when I do the following `#+begin_src shell :tangle (when (not (file-exists-p "~/bin/eto")) ~/bin/eto)` I get `Wrong type argument: stringp, nil` when I try to tangle the src block. What am I doing wrong? # Answer > 3 votes @dalanicolai's answer is correct but you still have a problem: the legal values of the `:tangle` header are the strings `yes`, `no` or a filename, (IOW, the argument *always* has to be a string), so your elisp snippet has to be more complicated: ``` #begin_src shell :tangle (if (not file-exists-p "foo") "foo" "bar") ... ``` Your original snippet returns `nil` if the file exists, but `nil` is not a string. The modified snippet returns the string `foo` if `foo` does not exist, but it returns the string `bar` otherwise, so the `:tangle` header *always* gets a string argument and everybody is happy. EDIT: The OP in a comment to the question mentions that the tangling should only happen the first time (i.e. when the file does not exist) and never again. So the header should read: ``` #begin_src shell :tangle (if (not file-exists-p "foo") "foo" "no") ... ``` # Answer > 1 votes From the org-documentation we find that the filename should be passed as a string (see section FILENAME), so you should place the latter ~/bin/eto between double quotes also. --- Tags: org-babel, emacsclient ---
thread-68750
https://emacs.stackexchange.com/questions/68750
How do you copy text with hyperlinks (text is not the link, the link is embedded (href style)), with the links into org mode?
2021-10-01T10:08:17.427
# Question Title: How do you copy text with hyperlinks (text is not the link, the link is embedded (href style)), with the links into org mode? I am copying text from a browser (from an email) which has hyperlinks such as link text \- but the links do not get hyperlinked as in the email. I just see 'link text' when I paste to my org file. How do I achieve this? I'm on doom emacs # Answer > 2 votes If you were looking at the email in emacs itself (using e.g. gnus or mu4 or one of the other email programs in emacs) and you had set up the suggested global keybindings in Org mode, you could visit the link in emacs (e.g. using `eww`), then `C-c l` to remember it and then `C-c C-l` in the Org mode file to insert it (with the choice to give it a label as well). You can set up `org-protocol` in a browser (see e.g. the description in the manual and some setup instructions here \- N.B. I have not tried them, so I don't know how well they work: YMMV), so that you could save links and arbitrary text, but that does take some fiddling to set it up, different browsers require different setup and IME it often breaks. OTOH, I haven't tried it in some years and so things might have improved since then. But you can always do it manually: copy the link in your browser (e.g. bring up the context menu by right-clicking on the link and select "Copy Link" in Firefox), then paste it into your emacs and surround it with `[[...]]`, e.g. `[[https:///www.duckduckgo.com]]` \- in Org mode, everything is just text after all - Org mode makes it *look* pretty (and does some other pretty amazing things as well) but you can always just type it in. You can prettify it a bit, by giving it a description: `[[https:///www.duckduckgo.com][Search]]`. You can even *type* the link by hand if you want as I did here, so this method, although somewhat tedious, is completely general. --- Tags: org-mode, org-link ---
thread-68754
https://emacs.stackexchange.com/questions/68754
dired-recent - not show correct recent visited directories
2021-10-01T12:43:02.947
# Question Title: dired-recent - not show correct recent visited directories ``` Linux Mint 20 Emacs 27 dired, dired-recent ``` Steps: ``` 1. "recentf-mode" is turn on 2. Go to directory "Download". Use "Jump to bookmark" (C-x r b). Input "Download" 3. As result in Dired mode open folder "/home/alexeij/Downloads/" 4. Go to directory "Temp". Use "Jump to bookmark" (C-x r b). Input "Temp" 5. As result in Dired mode open folder "/home/alexeij/Temp/" 6. Go to directory "dev". Use "Jump to bookmark" (C-x r b). Input "dev" 7. As result in Dired mode open folder "/home/alexeij/dev/" ``` Nice. Now I want to see history of recent visited directories **in chronological way**. So I use: ``` dired-recent-open ``` But in minibuffer show another directories. Why? # Answer You might want to try Dired+. It offers these commands for use with recentf: * diredp-add-file-to-recentf * diredp-add-this-to-recentf * diredp-dired-recent-dirs `C-x D r` * diredp-dired-recent-dirs-other-window `C-x 4 D r` * diredp-dired-recent-files `C-x D R` * diredp-dired-recent-files-other-window `C-x 4 D R` * diredp-do-add-to-recentf * diredp-do-remove-from-recentf * diredp-remove-file-from-recentf * diredp-remove-this-from-recentf In particular, `diredp-dired-recent-dirs` should do what I think you're looking for: > **`diredp-dired-recent-dirs`** is an interactive compiled Lisp function in `dired+.el`. > > It is bound to `menu-bar subdir diredp-dired-recent-dirs`, `C-x D r`. > > `(diredp-dired-recent-dirs BUFFER &optional ARG FILES)` > > Open Dired in `BUFFER`, showing recently visited directories. > > Like `diredp-dired-recent-files`, but limited to recent directories. A directory is recent if any of its files is recent. The doc of `diredp-dired-recent-files`, which the above refers to, tells you about using a prefix arg. Note that `C-u` or `0` as prefix arg prompts you for the `ls` switches to use, and **you can specify chronological order** with the switches (e.g. switch `t`). You can also just use option `diredp-default-sort-arbitrary-function` to sort the entries however you want. > **`diredp-dired-recent-files`** is an interactive compiled Lisp function in `dired+.el`. > > It is bound to `C-x D R`. > > `(diredp-dired-recent-files BUFFER &optional ARG FILES)` > > Open Dired in BUFFER, showing recently visited files and directories. > > You are prompted for `BUFFER` (default: `Recently Visited Files`). > > With a numeric prefix arg you can enter names of recent files to include or exclude. > > No prefix arg or a plain prefix arg (`C-u`, `C-u C-u`, etc.) means list all of the recently used files. > > **With a prefix arg:** > > * **If 0, `-`, or plain (`C-u`) then you are prompted for the `ls` switches to use.** > * If not plain (`C-u`) then: > * If \>= 0 then the files to include are read, one by one. > * If \< 0 then the files to exclude are read, one by one. > > When entering files to include or exclude, use `C-g` to end. > > The file listing is **sorted by option `diredp-default-sort-arbitrary-function`**, if non-`nil`. If `nil` (the default) then the listing is in reverse chronological order of opening or writing files you access. > > Use `g` to revert the buffer, as usual. If you use it without a prefix arg then the same files are relisted. A prefix arg is handled as for `C-x D R` itself. > > When called from Lisp: > > * `ARG` corresponds to the raw prefix arg. > * `FILES` is passed to `diredp--dired-recent-files-1`. It is used only when the command is used as part of the `revert-buffer-function`. > 0 votes --- Tags: dired, recentf ---
thread-68761
https://emacs.stackexchange.com/questions/68761
How do I Include plain text file org-mode as is for LaTeX export?
2021-10-01T18:57:44.637
# Question Title: How do I Include plain text file org-mode as is for LaTeX export? I'm using #+INCLUDE: "./file.txt" to organize documents but including files this way is messing with linefeeds on org-mode export to LaTeX/Pdf. Is there a property or attribute that could tell org-mode to read from these included files as is. I've already converted the newlinews to unix standard, but since LaTeX interprets newlines as two lines separated by one blank line, the text is messy. # Answer > 1 votes `orgmode` exports to pdf using `LaTeX`. LaTeX ignores single line breaks normally, which can be confusing. When you're importing a plain text file into org, you can wrap it in an `example` block to indicate that you want it exported 'as-is', without the normal LaTeX treatment of linebreaks: ``` #+include: file.txt example ``` For more details see (org) Include Files and (org) Example blocks in LaTeX export. --- Tags: org-mode, org-export, latex, pdf, text ---
thread-68757
https://emacs.stackexchange.com/questions/68757
How to support `<` and `>` as balanced parens without impacting ability to use them as comparison operators?
2021-10-01T15:27:18.793
# Question Title: How to support `<` and `>` as balanced parens without impacting ability to use them as comparison operators? Languages like Erlang and Elixir use `<< >>` for binaries and bit-string syntax, but they also use the classical `<` and `>` for comparison operators as well as `->` and `<-` in list comprehensions. Emacs syntax-table has the ability to identify pairs of characters. The `( )`, `[ ]` and `{ }` character pairs are identified in the syntax table as character pairs. This allows the following very handy behaviours: * `forward-sexp` and `backward-sexp` commands to navigate to the matching pair, * `er/expand-region` to quickly mark all text with the pair. Adding the `< >` pair in the syntax table causes problems with the other uses of the `<` and `>` characters because Emacs will see unbalanced pairs in statements such as `if (a < 3)`. **Question:** Is there a way to solve this problem and get the ability to use commands such as `forward-sexp` and `er/expand-region` to see the `<< >>` as balanced pairs when they are working on them, without adding balanced pair-syntax to `<` and `>`? For instance, to overcome the problem, would it be a good idea to dynamically change the syntax of `<` and `>` by modifying the syntax table just around the execution of these commands when they are applied on those characters (using advice or re-writing a function that calls them)? # Answer Yes. The syntax of a character in a buffer defaults to the value indicated by the buffer's syntax table, but this can be overridden by setting the `syntax-table` text property on a character in a buffer, provided that `parse-sexp-lookup-properties` is true. And you can set `syntax-propertize-function` to a function that applies this property as needed to a stretch of text. Modes written for older versions of Emacs that didn't have `syntax-propertize-function` could use font locking or custom post-change hooks for that. For simple cases, the `syntax-propertize-rules` macro can generate a suitable `syntax-propertize-function`. It's similar to font lock keywords, but sets character syntaxes rather than faces. The example below (untested) makes the outer characters in `<<…>>` matching balanced open-close characters. ``` (defconst foo-mode-syntax-propertize-function (syntax-propertize-rules ("\\(<\\)<" (1 "(>")) (">\\(>\\)" (2 ")<")))) (defun foo-mode () … (make-local-variable 'parse-sexp-lookup-properties) (setq parse-sexp-lookup-properties t) (make-local-variable 'syntax-propertize-function) (setq syntax-propertize-function foo-mode-syntax-propertize-function) ) ``` For a working, real-world example of making `<<…>>` balanced, see Erlang mode. It only sets the syntax when inserting `<` or `>` explicitly, which is very limited. I guess this code was written a long time ago before `syntax-propertize-function` made it more convenient. There are several examples of using `syntax-propertize-function` as intended in modes distributed with Emacs. For example, bat mode uses `syntax-propertize-rules` to make things like the word `rem` be a multi-character content starter. Fortran mode has a somewhat more complicated rule to recognize the `C` comment marker in the proper column. For a much more example, look at the various things Perl mode does to accommodate some of Perl's syntactic complexity. If you want to see a *really* complex example, explore how CC mode makes `<…>` balanced where warranted in C++. > 2 votes --- Tags: major-mode, syntax, balanced-parentheses, erlang-mode ---
thread-68746
https://emacs.stackexchange.com/questions/68746
Any existing function to fix comma-separated list in parens-pair?
2021-09-30T19:16:16.943
# Question Title: Any existing function to fix comma-separated list in parens-pair? I am looking a way to programatically fix invalidly formatted code for programming languages that use relatively simple list expression of elements separated by commas (ie, not in C++). For example I'd like to be able to perform the following transformations: * `[abc, def,, ghi,]` ---\> `[abc, def, ghi]` * `[abc def ghi]` ---\> `[abc, def, ghi]` * `(abc [11, 12,, 13,] def ghi,)` ---\> `(abc, [11, 12, 13], def, ghi)` essentially imposing that each element uses one comma separator and supporting various parens pairs: `( )`, `[ ]`, `{ }` and `< >`. Does something like that already exists? # Answer > 0 votes I did not find anything to do that so I wrote my own. Here's a slightly modified copy. The last function is the one to use: `pel-syntax-fix-block-content`: ``` ;; Predicates ;; ---------- (defun pel-inside-string-p (&optional pos) "Return non-nil if POS, or point, is inside a string, nil otherwise." (nth 3 (syntax-ppss pos))) ;; Utilities ;; --------- (defun pel-syntax-matching-parens-position (&optional parens-pos) "Return the parens position that match PARENS-POS." (setq parens-pos (or parens-pos (point))) (save-excursion (let ((parens-char (char-after (goto-char parens-pos)))) (if (memq parens-char '(?\( ?\[ ?\{ ?<)) (progn (forward-sexp) (backward-char)) (if (memq parens-char '(?\) ?\] ?\} ?>)) (progn (forward-char) (backward-sexp)) (error "Invalid sexp character: %S" parens-char))) (point)))) ;; Block syntax fixer ;; ------------------ ;; (defun pel-syntax-block-text-at (&optional pos) "Return text of block at POS or current point. Return a list of (open-position close-position text)." (setq pos (or pos (point))) (let* ((syntax (syntax-ppss pos)) (open-p-pos (car (nth 9 syntax))) (close-p-pos (pel-syntax-matching-parens-position open-p-pos))) (list open-p-pos close-p-pos (buffer-substring-no-properties open-p-pos (+ 1 close-p-pos))))) (defun pel-syntax-skip-string (&optional pos) "Move point to character just after end of string. Start from POS or current point." (goto-char (or pos (point))) (while (and (pel-inside-string-p) (not (eobp))) (forward-char))) (defun pel---replace-with (from replacer) "Replace text in current buffer. FROM is the regex identifying the text to change. REPLACER is a closure that identifies the new text, the REPLACER has access to the information from a `re-search-forward' such as the result of `match-string'. The function returns the number of replacements done." (let ((found-pos nil) (change-count 0)) (while (progn (goto-char (point-min)) (setq found-pos (re-search-forward from nil :noerror)) ;; if found item is in string, skip the string and search again: ;; do not transform the content of strings. (while (and found-pos (pel-inside-string-p found-pos)) (pel-syntax-skip-string found-pos) (setq found-pos (re-search-forward from nil :noerror))) (when found-pos (replace-match (funcall replacer) :fixedcase :literal) (setq change-count (1+ change-count)) t))) change-count)) (defmacro pel-replace (from &rest to) "Replace text in buffer. FROM must be a regex string. TO must be a form that produces a replacement string. That form runs in the context of the string replacement code performed by the function `re-search-forward'." `(pel---replace-with ,from (lambda () ,@to))) ;; -- (defun pel-syntax-fix-block-content (&optional pos) "Comma-separate all expressions inside the block-pair at POS or point. Does not transform text inside any string located inside the matched-pair block, but it may transform other text. Returns the number of text modifications performed." (save-excursion (save-restriction (let* ((open.close.text (pel-syntax-block-text-at pos)) (open-pos (nth 0 open.close.text)) (close-pos (nth 1 open.close.text)) (total-changes 0) (changes 1)) (narrow-to-region open-pos (1+ close-pos)) (while (> changes 0) (setq changes 0) ;; -> ensure one space between comma and next element. ;; Also eliminate multiple commas between 2 symbols. (cl-incf changes (pel-replace "\\(\\w\\),+\\(\\w\\)" (format "%s, %s" (match-string 1) (match-string 2)))) ;; -> remove spaces between word, closing parens or quotes and the ;; following comma (cl-incf changes (pel-replace "\\(\\w\\|\\s)\\|\\\"\\|'\\) +," (format "%s," (match-string 1)))) ;; -> replace multiple commas by a single one (cl-incf changes (pel-replace "\\(\\w\\),,+ " (format "%s, " (match-string 1)))) ;; -> add a comma after word or closing parens if there is none ;; before the next word or opening parens (cl-incf changes (pel-replace "\\(\\w\\|\\s)\\) +\\(\\w\\|\\s(\\)" (format "%s, %s" (match-string 1) (match-string 2)))) ;; -> remove trailing commas placed just before the closing parens (cl-incf changes (pel-replace ",\\s-*\\(\\s)\\)" (match-string 1))) ;; -> replace multiple spaces after a comma by 1 space after comma (cl-incf changes (pel-replace ", +\\([^ ]\\)" (format ", %s" (match-string 1)))) ;; -> remove isolated commas not separating anything (cl-incf changes (pel-replace ", +," ",")) ;; -> In erlang buffers move period after closing parens ;; if it is before (when (eq major-mode 'erlang-mode) (cl-incf changes (pel-replace "\\.\\(\\s)\\)" (format "%s." (match-string 1))))) ;; (cl-incf total-changes changes)) total-changes)))) ``` --- Tags: list, balanced-parentheses, delimiters ---
thread-47254
https://emacs.stackexchange.com/questions/47254
Update the org-agenda-daily-view automatically on background
2019-01-18T13:58:37.473
# Question Title: Update the org-agenda-daily-view automatically on background The org-agenda-daily-view is fancily helpful as a review, Additionally, I want to append a real-time now line as time elapsed. This could be achieved by a work around solution, repeatedly kill and open the daily agenda buffer . Is it possible to make it update automatically say every five minutes? # Answer You can use timers for this. `run-with-timer` allows you to run a command every `N` seconds. `run-with-idle-timer` is similar but the command runs only after Emacs has been idle for a number of seconds. An argument to both functions will cause the timer to repeat instead of just firing once. I prefer idle timers so they don't interrupt my typing. To regenerate the default agenda view (with command "a") every 5 minutes (300 seconds): ``` (run-with-idle-timer 300 t (lambda () (org-agenda nil "a")) ) ``` > 4 votes # Answer erikstokes's answer will only run the command one time with 300s delay every time the user becomes idle: > Emacs becomes idle when it starts waiting for user input, and it remains idle until the user provides some input. If a timer is set for five seconds of idleness, it runs approximately five seconds after Emacs first becomes idle. **Even if repeat is non-nil, this timer will not run again as long as Emacs remains idle, because the duration of idleness will continue to increase and will not go down to five seconds again.** (source) To make it automatically update every five minutes (even during idle), we can do something like this (reference: the code in https://www.gnu.org/software/emacs/manual/html\_node/elisp/Idle-Timers.html): ``` (defvar refresh-agenda-time-seconds 300) (defvar refresh-agenda-timer nil "Timer for `refresh-agenda-timer-function' to reschedule itself, or nil.") (defun refresh-agenda-timer-function () ;; If the user types a command while refresh-agenda-timer ;; is active, the next time this function is called from ;; its main idle timer, deactivate refresh-agenda-timer. (when refresh-agenda-timer (cancel-timer refresh-agenda-timer)) (org-agenda nil "a") (setq refresh-agenda-timer (run-with-idle-timer ;; Compute an idle time break-length ;; more than the current value. (time-add (current-idle-time) refresh-agenda-time-seconds) nil 'refresh-agenda-timer-function))) (run-with-idle-timer refresh-agenda-time-seconds t 'refresh-agenda-timer-function) ``` > 2 votes --- Tags: org-mode ---
thread-68762
https://emacs.stackexchange.com/questions/68762
How to see all recent directories?
2021-10-01T19:31:24.497
# Question Title: How to see all recent directories? Linux Mint 20 Emacs 27 package: dired, diredp (https://www.emacswiki.org/emacs/dired%2b.el) 1. Jump to bookmark. Input Temp 2. Press ENTER. As result open folder **MyFolder** 3. Press ENTER. As result open folder **MySubfolder\_1** 4. `M-x diredp-dired-recent-dirs` 1.Why in buffer *Recently Visited Directories* not show recently visited folders? ``` MyFolder MySubfolder_1 ``` 2. Is it possible to show recent visited directories in the minibuffer? # Answer Dired+ just uses your `recentf-list` of files and directories. It is library `recentf.el` that controls what file and dir names to record there. For that, library `recentf.el` provides several user options, which filter out certain file and dir names, etc. That's no doubt what you're running into. --- Your second question isn't clear to me (and you really should pose only one question per question). Perhaps you're asking how you can echo the list of recent directories to the echo area (same space as the minibuffer, but for output, not input). For that, you can use this command: ``` (defun foo () (interactive) (message "Recent dirs: %S" (diredp-recent-dirs nil))) ``` (If you want a different sort order, let-bind variable `diredp-default-sort-arbitrary-function` to a function that sorts the way you want.) > 2 votes --- Tags: dired, recentf ---
thread-68768
https://emacs.stackexchange.com/questions/68768
What is the meaning of the `\(?1::\)` Emacs string syntax regexp?
2021-10-02T02:07:54.567
# Question Title: What is the meaning of the `\(?1::\)` Emacs string syntax regexp? The bat-mode.el defines the following regexp used by `re-search-forward`: `"^[ \t]*\\(?:\\(@?r\\)em\\_>\\|\\(?1::\\):\\).*"` What is the meaning of the `1` in `\\(?1::\\)` inside the regexp? AFAIK `\\(?: ⋯ \\)` represents a *shy*, non-capturing, group. But I did not see a description that identifies a number (a group number?) could be placed there. # Answer > 2 votes It’s an explicitly–numbered group. From chapter 34.3.1.3 Backslash Constructs in Regular Expressions of the Emacs Lisp manual: ``` ‘\(?: ... \)’ is the “shy group” construct. A shy group serves the first two purposes of an ordinary group (controlling the nesting of other operators), but it does not get a number, so you cannot refer back to its value with ‘\DIGIT’. Shy groups are particularly useful for mechanically-constructed regular expressions, because they can be added automatically without altering the numbering of ordinary, non-shy groups. Shy groups are also called “non-capturing” or “unnumbered groups”. ‘\(?NUM: ... \)’ is the “explicitly numbered group” construct. Normal groups get their number implicitly, based on their position, which can be inconvenient. This construct allows you to force a particular group number. There is no particular restriction on the numbering, e.g., you can have several groups with the same number in which case the last one to match (i.e., the rightmost match) will win. Implicitly numbered groups always get the smallest integer larger than the one of any previous group. ``` For the given example, there are two possibilities for "group 1" (the first being implicitly numbered, and the second explicitly) but only one of them will be present in any given match for the overall regexp. In such a case you can be certain that the subsequent code is doing something with the text for "group 1", which will be *whichever* of those groups actually matched something. In this case the call to `syntax-propertize-rules` is declaring that the match for group 1 should have syntax `<` (meaning "comment starter"). --- Tags: regular-expressions ---
thread-68772
https://emacs.stackexchange.com/questions/68772
How to show recent directories on separate lines in echo area?
2021-10-02T08:05:01.687
# Question Title: How to show recent directories on separate lines in echo area? Linux Mint 20, Emacs 27.2 Install package dired, dired+ I want to show recent directories visited in the minibuffer. Something like this: I tried this: ``` (defun my-recent-dir () (interactive) (message "Recent dirs: %S" (diredp-recent-dirs nil))) ``` with this result: But I instead want to see each directory on its own line in the echo area. # Answer ``` (defun bar () (interactive) (let ((dirs (diredp-recent-dirs nil))) (message "Recent dirs: \n%s" (mapconcat #'identity dirs "\n")))) ``` > 1 votes --- Tags: dired, echo-area, message, recentf ---
thread-68775
https://emacs.stackexchange.com/questions/68775
How not select dot and double dots in dired mode
2021-10-02T17:31:47.370
# Question Title: How not select dot and double dots in dired mode Linux Mint 20 Emacs 27 package dired, dired+ In folder **Downloads** I has: **one** folder and **two** files. I want to delete all content of folder **Downloads** So as result on Dired mode I press **t**. Here result: As you can see marked also dot and double dots. So as result I can't delete all. I press **D** and get error: ``` Cannot operate on '.' or '..' ``` So as result I need MANUAL mark files by press **m** and only then I can delete all content of folder **Downloads** So the question is: Is it possible when press **t** (in dired mode) to not mark dot and double dots? # Answer With Dired+, try this replacement for command `dired-toggle-marks`. You can then use `C-u` to prevent `.` and `..` from toggling. (FYI: toggling them is part of a fix for Emacs bug #48883.) ``` (defun dired-toggle-marks (&optional except-dot+dot-dot-p) "Toggle marks: marked files become unmarked, and vice versa. Marks (such as `C' and `D') other than `*' are not affected. Hidden subdirs are also not affected. By default, this toggles also `.' and `..' (see Emacs bug #48883). With a prefix arg it does not toggle `.' and `..'." (interactive "P") (save-excursion (goto-char (point-min)) (let ((inhibit-read-only t)) (while (not (eobp)) (or (dired-between-files) (and except-dot+dot-dot-p (member (dired-get-filename t t) '("." ".."))) (apply 'subst-char-in-region (point) (1+ (point)) (if (eq ?\ (following-char)) (list ?\ dired-marker-char) (list dired-marker-char ?\ )))) (forward-line 1))))) ``` > 1 votes --- Tags: dired ---
thread-58281
https://emacs.stackexchange.com/questions/58281
Melpa obsolete packages
2020-05-05T02:08:40.203
# Question Title: Melpa obsolete packages Using Emacs 26.3, suddenly any package I install from Melpa shows `Available Obsolete from melpa -- Install`. All used to be fine. What is causing this? # Answer That message confused me too. It turns out it's just a poor choice of words for saying that there's a new version available. https://lists.gnu.org/archive/html/help-gnu-emacs/2019-02/msg00082.html Once you update the list of packages with `M-x package-refresh-contents`, then you can type `U x` and it will upgrade all installed packages that have a more recent version available. Once that is one, the message you see when you open the description of an updated package will be: > Package x is installed. > 1 votes --- Tags: package-repositories ---
thread-68771
https://emacs.stackexchange.com/questions/68771
is it possible to execute a command on specific set of files upon exiting emacs
2021-10-02T05:16:39.407
# Question Title: is it possible to execute a command on specific set of files upon exiting emacs I use emacs as my editor with mutt. I would like to run a python code on the /tmp/mutt-\* files upon exit (that is called email-process, and that is written and works). For instance, in the case of vim, it is possible to have the following set up in the .vimrc to do this. ``` augroup autocom autocmd! " " executes my command on quit autocmd VimLeave /tmp/mutt-* !/home/username/bin/email-process % augroup END ``` Is it possible to do the same for emacs? If so, how do I set this up in my .emacs file? The following has some similarity with my question: Execute external script upon save when in a certain mode? However, I am interested in executing the command when I exit and only for /tmp/.mutt\* files for now. I looked up `kill-emacs-hook` and `start-process` and `call-process` suggested below but I could not tell how to use it. I am not very familiar with emacs configuration files. From the example here, Can I call a python script from emacs? it seems to me that I should define my script as something like: ``` (defun email-process () "Process cpmposed outgoing email" (when (equal file-name "/tmp/mutt-*") (shell-command "pathname"))) (add-hook 'kill-hook #'email-process) ``` However, when I do this, I am unable to get out of the compose window, and indeed I get: ``` Symbol's value as a variable is void: file-name ``` So, it appears to me that there is something wrong with how I am checking for the filename to activate the kill-hook on. Any suggestions? Thanks for your help, and please feel free to let me know if my question needs more clarification. # Answer What @lawlist is describing in the comment can be implemented by writing a function to do whatever it it that you want to do and then by modifying the `kill-emacs-hook` to execute the function when the hook is run. # TL;DR Add this to your emacs init file: ``` ;; define a function that runs the given command line (defun email-cleanup () (call-process-shell-command "/home/username/bin/email-process /tmp/mutt-*")) ;; add the above function to the hook (add-hook 'kill-emacs-hook #'email-cleanup) ``` Although I copied the path of the executable from your question, you will probably have to modify it (at least the `username` part) to fit your setup. I've tested with a dummy script and it works; but if you run into problems, let me know in a comment and I'll try to sort it. # A more detailed explanation Hooks are variables whose value is a list of functions. `Running the hook` evaluates each function in the hook in sequence. Emacs defines *many* different hooks for different operations. You can get a list by saying `C-h v -hook TAB` (and maybe wait a few seconds: it's a *long* list). Each of those hooks is run under very specific circumstances. It is one of the most important methods of customizing emacs behavior, so it is worth familiarizing yourself with them. In this particular case, you want to find a hook that is run when emacs exits. Look in the `Exiting Emacs` section of the Emacs manual: the best way to do that is by asking Emacs itself: `C-h i g(emacs)Exiting` \- learning how to use the built-in documentation is probably the best thing you can do to make your life easier and more pleasant while using Emacs. See where it says > To further customize what happens when Emacs is exiting, see \*note (elisp)Killing Emacs::. That is a link so you can click on it. You'll see the description of `kill-emacs-hook` on that page. That's how you find (or at least that's one way to find) the hook you want. Once you've found the hook, the next thing is to write a function to do what you want. In this case, you want to write a function that executes a shell command: that's why @lawlist in the comment mentions `start-process` and `call-process`: they are ways to execute an external program from inside emacs (similar to vi's `!` mechanism). In this case however, you will want to run a shell in order to expand the glob in the argument to a full list of matching files. The best function to use then is `call-process-shell-command` (see its doc string with `C-h f call-process-shell-command`): the more basic ones (`call-process` and `start-process` exec the program directly, so there is no shell to do the expansion). So the function `email-cleanup` defined above runs a shell and gives it the command line in the function. The shell expands the glob and runs the program with that expanded list of arguments. Then all we have to do is add the function to the hook. **EDIT**: It turns out that the OP's script only handles one file for each invocation, so it cannot be invoked from the shell as `email-process /tmp/mutt-*` and expect to handle more that one file. It has to be invoked as `for f in /tmp/mutt-* ;do email-process $f ;done`. It also overwrites its input file with its output (which is generally a bad idea IMO, but I'm not addressing that in this comment). So try with this function: ``` (defun email-cleanup () (call-process-shell-command "for f in /tmp/mutt-* ;do /home/username/bin/email-process $f ;done")) ``` Personally, I would change the script to loop over its arguments and go back to the first form of the function, but that's out of scope for this question. If this still does not work, then please tell me the exact form of the command you execute in the shell so that it does what you want. All of this has nothing to do with emacs of course: it is how your script has to be invoked from the shell. > 2 votes --- Tags: init-file, hooks, shell-command ---
thread-68782
https://emacs.stackexchange.com/questions/68782
Open org-src code edit buffer automatically upon starting edit
2021-10-03T04:41:45.530
# Question Title: Open org-src code edit buffer automatically upon starting edit Editing src blocks directly in org file is nice but you cannot benefit from all minor modes that would be enabled in dedicated code edit buffer, more then that for a big babel file the performance struggles. Usually I forget to do this additional keystroke and end up editing in org. Is there any out-of-the-box option or simple workaround this can be made automatic - e.g. whenever I hit edit command the buffer is opened automatically and gets activated with all input continuing there? p.s. I'm using evil - one thing that came to my mind was capturing some evil-into-insert-mode-hook and checking if I'm inside a src block, but this is does not cover all cases of course # Answer Ok, figured that out on my own - at least, for **evil**: ``` (add-hook 'org-mode-hook (lambda() (make-local-variable 'evil-insert-state-entry-hook) ;; making this hook act only locally in the buffer where org-mode-hook has been called (add-hook 'evil-insert-state-entry-hook #'org-edit-src-code))) ``` > 0 votes --- Tags: org-mode, org-babel ---
thread-7171
https://emacs.stackexchange.com/questions/7171
paste html into org mode
2015-01-08T15:35:26.343
# Question Title: paste html into org mode Is there any easy way to copy/paste text from a browser window into an org file, automatically converting links into \[\[\]\[\]\] org-mode links? thanks! # Answer > 10 votes # Copying html in org format from `eww` This requires emacs 24.4 or later. 1. Configure the `org-eww` module. It's not part of org, you'll have to pull the repo into some folder (`git clone https://orgmode.org/org-mode.git`) or manually copy the file into some package folder, although git is recommended as it helps you keep things up to date. 2. Then add the contribute folder into your path and say that org-eww is required. If you cloned from git, the `org-eww.el` file will be in `/path/where/you/cloned/org-mode/contrib/lisp/`. `(add-to-list 'load-path "/dir/path/containing/org-eww.el/")` `(require 'org-eww)` 3. Open a web-page in `eww` (eww is a browser in emacs, `M-x eww`). You can get emacs to open links in eww via: `(setq browse-url-browser-function 'eww-browse-url)`. This is useful in combination with helm-google + eww). 4. Select the region you want to copy from the html page and do `M-x org-eww-copy-for-org-mode`. If no region is selected, the whole webpage is copied (including links to images). As of now the `o` key is not bound to the `eww-mode-map`. For convenience, this command can be bound to that key in that mode map: `(define-key eww-mode-map (kbd "o") #'org-eww-copy-for-org-mode)` 5. Then use `C-y` to paste into your org mode file/buffer. With `iimage-mode` you can even see the images from the website and links are converted to the org-mode format. # Answer > 5 votes I wrote an add-on Copy as Org-Mode for Firefox which can do this in browser directly, it even can convert HTML tables into Org-mode format. # Answer > 4 votes late to the party, but as @xji said, `org-eww-copy-for-org-mode` doesn't preserve formatting, it only does links. if you want to actually end up with org headings and preserved formatting, try https://github.com/alphapapa/org-web-tools. From `eww`, hit `w` to copy URL of current page (or copy from another browser), then run `org-web-tools-read-url-as-org`. further details are in the readme. --- Tags: org-mode ---
thread-68786
https://emacs.stackexchange.com/questions/68786
Lambda triggering error when executed
2021-10-03T11:49:48.633
# Question Title: Lambda triggering error when executed I'm setting up a mechanism that allows me to conveniently specify minor modes in a list that should not take up space in the modeline. At the bottom of the following code snippet, this list is iterated and, for each mode, a hook is setup which, when invoked should call `(diminish 'mode)`. I'm getting an error when the hook is invoked, however, and I'm unsure what I'm doing wrong here. I went with a lambda hook function as a way of circumventing lexical binding constraints. ``` (setq my/diminished-modes '(projectile-mode ivy-mode eldoc-mode auto-fill-mode yas-minor-mode)) (defun add-suffix-to-symbol (sym suffix) "Add a suffix to a symbol name." (intern (concatenate 'string "" (symbol-name sym) suffix))) ;; This fails with the following error: ;; Symbol’s value as variable is void: mode (dolist (mode my/diminished-modes) (add-hook (add-suffix-to-symbol mode "-hook") `(lambda () (diminish ',mode)))) ``` # Answer Turns out the solution was to `(quote ,mode)` rather than `',mode`. Unsure why. ``` (setq my/diminished-modes '(projectile-mode ivy-mode eldoc-mode auto-fill-mode yas-minor-mode)) (dolist (mode my/diminished-modes) (add-hook (add-suffix-to-symbol mode "-hook") `(lambda () (diminish (quote ,mode))))) ``` > 0 votes --- Tags: init-file ---
thread-68784
https://emacs.stackexchange.com/questions/68784
Store the cursor position relative to surrounding text, make edits, then insert text at the stored location
2021-10-03T09:12:01.850
# Question Title: Store the cursor position relative to surrounding text, make edits, then insert text at the stored location I have some insert functions that take some time (e.g., doing network IO). I like to store the current point position, and then insert the text at the stored point. This should be robust to some small edits. I think `bookmarks.el` already has such a 'fuzzy' point storing machinery, but I am not sure if it's the best way to do this (or how to use `bookmarks.el`'s presumably private API). # Answer From your description, you don't want to return to a particular *buffer* position. You want to return to a particular *text* position, that is, a position in *context*, a position relative to the text surrounding the original position. As @NickD suggested in a comment, what you want to do is to create and store a **marker** at the original location. Markers move along with the surrounding text. ``` (let ((opt (point-marker))) ;; DO STUFF (goto-char opt)) ``` Read about markers in the Elisp manual, node Markers. > 3 votes --- Tags: point, marker ---
thread-68797
https://emacs.stackexchange.com/questions/68797
How can I query replace region from top case-sensitively?
2021-10-04T12:41:42.583
# Question Title: How can I query replace region from top case-sensitively? I am using following answer to search and replace a word in the entire buffer: > <pre><code>(defun query-replace-region-or-from-top () > (interactive) > (progn > (let ((orig-point (point))) > (if (use-region-p) > (call-interactively 'query-replace) > (save-excursion > (goto-char (point-min)) > (call-interactively 'query-replace))) > (message "Back to old point.") > (goto-char orig-point)))) > > (global-set-key "\C-x\C-r" 'query-replace-region-or-from-top)``` > </code></pre> --- When I apply `query-replace-region-or-from-top`, for example `emacs` into `emacs_world` it also changes `EMACS` into `EMACS_WORLD`. How can I make `query-replace-region-or-from-top` case-sensitive? # Answer You need to let-bind `case-fold-search` to nil: ``` (defun query-replace-region-or-from-top () (interactive) (let ((case-fold-search nil)) (progn ... (goto-char orig-point))))) ``` See the doc string for `case-fold-search` with `C-h v case-fold-search`: > case-fold-search is a variable defined in ‘src/buffer.c’. > > Its value is t > > Automatically becomes buffer-local when set. You can customize this variable. Probably introduced at or before Emacs version 18. > > Non-nil if searches and matches should ignore case. > 3 votes --- Tags: replace, case-folding ---
thread-68796
https://emacs.stackexchange.com/questions/68796
Extract link from ORG header and insert as property?
2021-10-04T11:56:57.497
# Question Title: Extract link from ORG header and insert as property? supposing I have following ORG header ``` * [[http://...][Description]] ``` How do I extract the link and insert it as a property? My desired outcome should look like: ``` * Description :PROPERTIES: :URL: http://... :END: ``` Till now I only found how to remove the link from the header: ``` (defun afs/org-replace-link-by-link-description () "Replace an org link by its description or if empty its address" (interactive) (if (org-in-regexp org-link-bracket-re 1) (save-excursion (let ((remove (list (match-beginning 0) (match-end 0))) (description (if (match-end 2) (org-match-string-no-properties 2) (org-match-string-no-properties 1)))) (apply 'delete-region remove) (insert description))))) ``` # Answer You need to save the URL from the match in some variable (say `url`) and then do `(org-entry-put nil "URL" url)`: ``` (defun afs/org-replace-link-by-link-description () "Replace an org link by its description or if empty its address" (interactive) (if (org-in-regexp org-link-bracket-re 1) (save-excursion (let ((remove (list (match-beginning 0) (match-end 0))) (description (if (match-end 2) (org-match-string-no-properties 2) (org-match-string-no-properties 1))) (url (org-match-string-no-properties 1))) (apply 'delete-region remove) (insert description) (org-entry-put nil "URL" url))))) ``` See the doc string of the function with `C-h f org-entry-put` and also see the Using the Property API section of the manual, which you can get to from inside Emacs with `C-h i g(org)Using the Property API`. > 0 votes --- Tags: org-mode, hugo ---
thread-68794
https://emacs.stackexchange.com/questions/68794
load user-written minor mode in a specific major mode
2021-10-04T05:55:37.177
# Question Title: load user-written minor mode in a specific major mode I'm trying to use a very simple minor mode I've written to personnalize the appearance of the buffer when I'm running R in ESS. Basically, I've set the linespacing in my init file to increase it and want this line spacing be turned to `nil` when I load ESS. Here is the `.el` file I've written so far. ``` (define-minor-mode ess_XXX-mode "Personal configuration of ESS'" :lighter " ess_XXX") (setq line-spacing 1) (set-face-attribute 'default nil :height 110) (add-to-list 'minor-mode-alist '(ess_XXX-mode " ess_XXX")) (provide 'ess_XXX-mode) ``` When I eval the buffer, this works but on all buffers. When I run Emacs, I'm not able to load the minor-mode... I've added the following in my init file ``` (require 'ess_XXX-mode) (add-hook 'iESS-mode-hook 'ess_XXX-mode) ``` but again this works on all the buffers without any restriction. It seems Emacs cannot find the minor mode (I've stored the `.el` file in my `.emacs.d/` directory). # Answer You don't need a minor mode to customize the appearance of a major mode. You can do that more simply with a function called from the mode hook: ``` (defun my-ess-hook () (setq line-spacing 1)) (add-hook 'iESS-mode-hook 'my-ess-hook) ``` `(set-face-attribute 'default ...)` will change the default face for the whole Emacs frame, it doesn't apply to a single mode or buffer alone. I'm not sure there is a straightforward way to customize the default face for one buffer or mode only. > 4 votes # Answer Your `ess_XXX-mode.el` file needs to be in a directory which is present in your `C-h``v` `load-path` list. Your `~/.emacs.d` directory is not present in that list by default (and you should not add it). If necessary, create a new directory such as `~/.emacs.d/lisp` and add that to your `load-path`. ``` (add-to-list 'load-path (expand-file-name "~/.emacs.d/lisp")) ``` > 2 votes # Answer See the doc string for `define-minor-mode`: `(define-minor-mode MODE DOC [KEYWORD VAL ... &rest BODY])`. IOW, the code that should be executed when the mode is enabled (and *also when the mode is disabled*) has to be included as the `BODY` in the `define-minor-mode` form. Something like this: ``` (define-minor-mode ess_XXX-mode "Personal configuration of ESS'" ; DOC :lighter " ess_XXX" ; KEYWORD-VALUE pairs ;; here comes the BODY (cond (ess_XXX-mode ;; mode was turned on ... code to execute when the mode is turned on ... ) (t ;; mode was turned off ... code to execute when the mode is turned off ... ))) ``` Many minor modes do not need a `BODY` at all, but since you are modifying global variables, it seems to me that yours does. > 2 votes --- Tags: major-mode, minor-mode ---