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-42137
https://emacs.stackexchange.com/questions/42137
EIN : Width of output cells in notebook
2018-06-20T15:41:55.370
# Question Title: EIN : Width of output cells in notebook I'm using ein to view and work with Jupyter Notebooks. I'd like to be able to set the cell width to that of the window so that text wraps as little as possible. In a browser this can be done with... ``` from IPython.core.display import display, HTML display(HTML("<style>.container { width:100% !important; }</style>")) ``` ..but since this isn't HTML and doesn't work under EIN in Emacs. Nothing in the docs suggests a way of controlling this. Any pointers to documentation on how to do this or suggestions would be very much appreciated. # Answer > 3 votes Pandas is sufficient, try: ``` pd.set_option("display.width", 120) ``` --- Tags: ein, jupyter ---
thread-48342
https://emacs.stackexchange.com/questions/48342
messages buffer is spammed with tramp
2019-03-14T16:31:38.187
# Question Title: messages buffer is spammed with tramp I am connecting regularly to servers via tramp. Sometimes everything works fine but often times my messages buffer gets spammed full of ``` Tramp: Waiting for prompts from remote shell...done Tramp: Found remote shell prompt on ‘134.60.29.152’ Tramp: Opening connection for 123.630.239.152 using ssh...done ``` everytime I type something in a .py file. If I log into a different machine (same setup Ubuntu 18.04) it does not occur. I use build in tramp and did not specify anything with respect to tramp. If I open on the remote machine e.g. .bashrc this problem does not happen. does anyone know what the problem is? thanks in advance # Answer > 1 votes This error seems very similar to an issue I am seeing\[\]. Do you use VC? Are the (remote) files backed by some version control system? I notice using the following options with TRAMP cause a number of issues similar to what you describe: ``` (setq-default auto-revert-check-vc-info t) (setq-default auto-revert-remote-files t) ``` I have since set these values to `nil`. I have also set `tramp-verbose` to `1`, instead of the default of `3`. ``` (setq-default tramp-verbose 1) (setq-default auto-revert-check-vc-info nil) (setq-default auto-revert-remote-files nil) ``` You can check what is causing the messages by running `M-x debug-on-entry RET message RET` while connected to the remote files, and see what function in Emacs, whether it's flycheck/flymake\` or, like in my case, VC. Since it's VC for me and it's for a repository I don't care to ever interact with, I use the following to disable SVN: ``` (setq-default vc-handled-backends '(Git)) ``` But this may be a little too aggressive or undesired. I don't have a better solution than perhaps disabling certain features when connected to remote files or increasing some of the refresh timers. --- Tags: tramp, message ---
thread-5719
https://emacs.stackexchange.com/questions/5719
How do I demote/promote selected subtrees?
2014-12-25T02:24:32.530
# Question Title: How do I demote/promote selected subtrees? (current as of org 8.2.10) I have a thing (shameless plug) that outputs a simple snippet of org-headings in a single file that look like this: ``` * little boys - snakes - snails - puppy dog tails * little girls - sugar - spice - everything nice ** addendum - etc. ``` These are meant to go into another file through `org-insert` functions, specifically, a subheading of that other file. In order to do that I have to demote all of the headings so that they slide nicely into place. How can I do that? I tried: * `C-x r t` to prepend asterisks; this adds asterisks to every line * `C-x h M-S-<right>` to try demoting the whole selection; this only demoted the first line ### Further issue: org-metaright does not demote subtrees Commenters were correct that `C-x h M-<right>` (`org-metaright`) promotes or demotes visible selections. However, this ignores their subtrees, resulting in reordering of their substructure. The same behavior occurs with `org-do-demote` called on a selection. # Answer Org headlines are simply lines starting with a `*`. So you can cycle through all of them and manually insert an `*` on each one to get the effect you want. ``` (defun endless/demote-everything (number beg end) "Add a NUMBER of * to all headlines between BEG and END. Interactively, NUMBER is the prefix argument and BEG and END are the region boundaries." (interactive "p\nr") (save-excursion (save-restriction (save-match-data (widen) (narrow-to-region beg end) (goto-char (point-min)) (let ((string (make-string number ?*))) (while (search-forward-regexp "^\\*" nil t) (insert string))))))) ``` At first you might be worried this would catch undesired edge cases, such as a `#+SRC_BLOCK` where one of the lines starts with a `*`. But `org-mode` itself uses this method to identify headlines, so no org buffer should ever contain a `*` as the first char of a line unless it's a headline. > 2 votes # Answer If I understand it correctly, you have a list of subtrees ``` * A ** A1 *** A1a * B ** B1 ``` and want to insert them into another subtree ``` * First ** First Sub * Second ``` at the right level: ``` * First ** First Sub *** A **** A1 ***** A1a *** B **** B1 * Second ``` As this is Emacs (and org-mode of course), there is a function for this ;-) Just use `org-paste-subtree` like so: 1. save your new list in the kill ring (select and `M-w`) 2. enter `***` after *First Sub* 3. call `org-paste-subtree` The function is described as > Paste the clipboard as a subtree, with modification of headline level. and will work for demoting **and** promoting the subtree in the kill ring. org-mode can even be configured to use this style of yank every time a subtree is yanked into a subtree. Customize the variable `org-yank-adjusted-subtrees` and you can use `C-y` instead of `org-paste-subtree` in the example above. For me this was especially useful when I wanted to promote all subtrees under one toplevel. > 6 votes # Answer The problem you described can also be solved with the functions `outline-promote` and `outline-demote`. EDIT: Thanks for the feedback. Just adding to my answer, I've discovered that there also exist functions `org-promote-subtree` and `org-demote-subtree`. > 5 votes # Answer Whether or not the subtrees are visible, if you * position the cursor at the beginning of the first headline, * you are running with `Transient-Mark` mode enabled (the default), * mark the whole thing as your region so that it is highlighted, * do `M-right`, all of the headlines (and their subtrees) should be demoted one level. If that is not how your setup is working, something is broken: you should investigate the situation and fix it. > 4 votes # Answer Latest release (develop branch) of Spacemacs has the functions `org-promote-subtree` and `org-demote-subtree` that works perfectly. They can be triggered via `, s h` and `, s l`, respectively, by keeping cursor on the root of the sub-tree. I also find it convenient to select region in org file and promote/demote outlines within scope of selection. This can be done by using `org-do-promote` and `org-do-demote` functions. > 0 votes --- Tags: org-mode ---
thread-54287
https://emacs.stackexchange.com/questions/54287
Display only not-DONE-yet items in agenda
2019-12-10T14:26:51.570
# Question Title: Display only not-DONE-yet items in agenda I have several agenda commands set up, one of which gives me a block agenda, others give me specific searches. Since many of my TODOs are hanging around inside of projects, where I only archive the project when the whole thing is done, my system always has a bunch of DONE items hanging around. So many of my searches result in screens that are 60-80% DONE items, with some TODOs scattered among them. What I want to do, is to filter it out so I only see non-DONE items in these searches. I've done web searches and read the manual and tutorials and used C-h, all in vain. What I did manage to figure out is that the answer is probably in the settings field in `org-agenda-custom-commands`... but I seem to be unable to find documentation about that, that is good enough to help me figure it out. Please will someone point me in the right direction here. How do I make `org-agenda-custom-commands` show me only non-DONE items? My current setup for that variable is as follows: ``` (setq org-agenda-custom-commands (quote (("d" "Daily Planning Agenda + Next Actions" ((agenda "" ((org-agenda-span (quote day)))) (tags "URGENT" nil "mygtd.org") (todo "WAITING" nil) (todo "STARTED" nil) (todo "TODO" nil)) nil) ("h" tags "@home") ("w" tags "@work" nil) ("o" tags "@onlinebanking" nil) ("e" tags "@errands" nil) ("f" . "Agendas with individuals and groups") ("fh" "H..." tags "AGENDA=\"H... W...\"" nil) ("fH" "H..." tags "AGENDA=\"H... B...\"" nil) ("fl" "L..." tags "AGENDA=\"L... M...\"" nil) ("fp" "P..." tags "AGENDA=\"P... S...\"" nil) ("fm" "M..." tags "AGENDA=\"M... M...\"" nil) ("fr" "R..." tags "AGENDA=\"R... B...\"" nil) ("fM" "M..." tags "AGENDA=\"M... P...\"" nil)))) ``` # Answer > 5 votes You asked: > How do I make `org-agenda-custom-commands` show me only non-DONE items? You can add `-TODO=\"DONE\"` to the **match** string of your tag search. This is described in the seciton 11.3.3. Matching tags and properties of the Org manual. There is even an example there which contains the string `-TODO​="DONE"`. So you can search for it there. The following example demonstrates that match string. It is marked by the comment `;; match`. ``` (add-to-list 'org-agenda-custom-commands '("x" ;; key "Testing tags for negating DONE" ;; desc tags ;; type "-TODO=\"DONE\"" ;; match nil ;; settings nil ;; no files )) ``` # Answer > 3 votes Instead of using a `tags` type agenda, which shows all entries regardless of TODO state, use a `tags-todo` type which only shows non-closed TODO items. If you need a `tags` view so you can also see entries without a keyword, add `-TODO="DONE"` to your query. For an `agenda` type view, the relevant variables are: `org-agenda-skip-scheduled-if-done`, `org-agenda-skip-deadline-if-done`, `org-agenda-skip-timestamp-if-done`. Setting these to `t` will had the corresponding entries from your agenda. --- Tags: org-mode, org-agenda ---
thread-54293
https://emacs.stackexchange.com/questions/54293
How to resolve TRAMP spamming empty messages
2019-12-10T17:18:03.613
# Question Title: How to resolve TRAMP spamming empty messages Connecting to a remote machine with tramp that may have VC (subversion) related files, I tend to see a large number of repeated messages in the `*Messages*` buffer. For example: ``` Type "q" in help window to restore previous buffer. [2 times] Mark saved where search started [69 times] Mark saved where search started ... Quit mwheel-scroll: Beginning of buffer [7 times] [7 times] Quit [2 times] ... Quit [14 times] Mark set [2 times] Mark set Mark set Mark set [3 times] ``` Debugging this has been a pain and it's been very difficult to even get to understanding that the issue is some interaction with TRAMP and VC. Namely, I understood that in other emacs sessions, I didn't have repeated messages. Obviously the issue doesn't exist in `emacs -Q` either. Furthermore, I tried the classic emacs configuration bisection, e.g., comment out all configuration and slowly introduce sections until the error appears. However, I was unable to uncover the issue with any of these methods. Finally, I discovered some Emacs debugger functionallity for Emacs LISP. I tried `M-x RET trace-function RET message RET`. However, all I received was quickly filling buffer of empty calls to `message`. ``` ====================================================================== 1 -> (message nil) 1 <- message: nil ====================================================================== 1 -> (message "%s" "") 1 <- message: "" ====================================================================== 1 -> (message nil) 1 <- message: nil ====================================================================== 1 -> (message "Mark set") 1 <- message: "Mark set" ====================================================================== 1 -> (message "Mark set") 1 <- message: "Mark set" ====================================================================== 1 -> (message "%s" "") 1 <- message: "" ====================================================================== 1 -> (message "%s" "Mark set") 1 <- message: "Mark set" ====================================================================== 1 -> (message "%s" "") 1 <- message: "" ====================================================================== 1 -> (message "%s" "Mark set") 1 <- message: "Mark set" ====================================================================== 1 -> (message "%s" "") 1 <- message: "" ====================================================================== 1 -> (message "%s" "Mark set") 1 <- message: "Mark set" ====================================================================== 1 -> (message "Mark set") 1 <- message: "Mark set" ====================================================================== ``` Which *is* the issue as described, but doesn't point to *where* the issue is coming from. I knew I needed the function call trace, as that will tell me what function is calling `message`. Next, I tried using `debug-on-entry` on `message`. Finally, I have something! (Actual file names changed for reasons). ``` Debugger entered--entering a function: * message("%s" "") tramp-sh-handle-vc-registered(#("/ssh:remote-host:/some/svn/file" 1 4 (helm-ff-file t) 5 24 (helm-ff-file t))) apply(tramp-sh-handle-vc-registered #("/ssh:remote-host:/some/svn/file" 1 4 (helm-ff-file t) 5 24 (helm-ff-file t))) tramp-sh-file-name-handler(vc-registered #("/ssh:remote-host:/some/svn/file" 1 4 (helm-ff-file t) 5 24 (helm-ff-file t))) apply(tramp-sh-file-name-handler vc-registered #("/ssh:remote-host:/some/svn/file" 1 4 (helm-ff-file t) 5 24 (helm-ff-file t))) tramp-file-name-handler(vc-registered #("/ssh:remote-host:/some/svn/file" 1 4 (helm-ff-file t) 5 24 (helm-ff-file t))) vc-registered(#("/ssh:remote-host:/some/svn/file" 1 4 (helm-ff-file t) 5 24 (helm-ff-file t))) vc-backend(#("/ssh:remote-host:/some/svn/file" 1 4 (helm-ff-file t) 5 24 (helm-ff-file t))) vc-refresh-state() #f(compiled-function () #<bytecode 0x215bf89>)() auto-revert-handler@bug21559(#f(compiled-function () #<bytecode 0x215bf89>)) apply(auto-revert-handler@bug21559 #f(compiled-function () #<bytecode 0x215bf89>) nil) auto-revert-handler() #f(compiled-function () #<bytecode 0x215bffd>)() apply(#f(compiled-function () #<bytecode 0x215bffd>) nil) auto-revert-buffers() apply(auto-revert-buffers nil) timer-event-handler([t 24045 51629 615589 5 auto-revert-buffers nil nil 963000]) ``` But, what is the solution to resolve this? I have set `tramp-verbose` to `1`. However, this might be hiding the particular behaviour instead of spamming a load of messages about how TRAMP is performing VC refreshing. For now, since this is issue is being caused by some files under SVN control that I have no interest in interacting with, i.e., it's not my repository and I don't have write access anyways, I'm simply disabling the VC backend\[\]: ``` (setq-default vc-handled-backends '(Git)) ``` However, I would like to have a better solution in case I do ever need to interact with SVN (hopefully not, but this feels very hacky). This had led to the following commit on my dotfiles, which also has some other variables that may be in the middle of the interplay: ``` (setq-default auto-revert-check-vc-info nil) (setq-default auto-revert-remote-files nil) ``` How might I more "properly" resolve this issue? # Answer I don't know a solution yet, but I can explain a little bit. Your back-trace tells us, that the message call happens in `tramp-sh-handle-vc-registered`. And indeed, its body is wrapped by ``` (with-temp-message "" ...) ``` This is done in order to preserve the recent message in the echo area while running `tramp-sh-handle-vc-registered`, which has an own progress reporter. Your back-trace tells us also, that this happens during `auto-revert-buffers`. Well, I agree with you that a progress reporter might not be helpful during auto-revert. This shall be suppressed in either Tramp or auto-revert. An sx question is not appropriate to discuss possible solutions. I encourage you therefore to write a bug report, using `M-x report-emacs-bug`. **Edit**: I've just committed http://git.savannah.gnu.org/cgit/emacs.git/commit/?id=8aaa92a4b648aef137eb9a7054fdffaed04328ff to the Emacs git repo. This might solve the problem. > 1 votes --- Tags: debugging, tramp, vc ---
thread-30650
https://emacs.stackexchange.com/questions/30650
Symbol's function definition is void: insert-string
2017-02-12T08:27:06.920
# Question Title: Symbol's function definition is void: insert-string ``` ;; Specify the startup banner. Default value is `official', it displays ;; the official spacemacs logo. An integer value is the index of text ;; banner, `random' chooses a random text banner in `core/banners' ;; directory. A string value must be a path to an image format supported ;; by your Emacs build. ;; If the value is nil then no banner is displayed. (default 'official) dotspacemacs-startup-banner 'random ``` When I set `dotspacemacs-startup-banner` to `'random` in my dot file, I got the following warning message when executing `emacs --debug-init`: ``` Debugger entered--Lisp error: (void-function insert-string) (insert-string (let ((temp-buffer (generate-new-buffer " *temp*"))) (save-current-buffer (set-buffer temp-buffer) (unwind-protect (progn (insert-file-contents file) (let ((banner-width 0)) (while (not ...) (let ... ...) (forward-line 1)) (goto-char 0) (let (...) (while ... ... ...))) (buffer-string)) (and (buffer-name temp-buffer) (kill-buffer temp-buffer)))))) spacemacs-buffer/insert-ascii-banner-centered("/Users/sunqingyao/.emacs.d/core/banners/000-banner.txt") (if (image-type-available-p (intern (file-name-extension banner))) (spacemacs-buffer//insert-image-banner banner) (spacemacs-buffer/insert-ascii-banner-centered banner)) (progn (spacemacs-buffer/message (format "Banner: %s" banner)) (if (image-type-available-p (intern (file-name-extension banner))) (spacemacs-buffer//insert-image-banner banner) (spacemacs-buffer/insert-ascii-banner-centered banner)) (spacemacs-buffer//inject-version)) (if banner (progn (spacemacs-buffer/message (format "Banner: %s" banner)) (if (image-type-available-p (intern (file-name-extension banner))) (spacemacs-buffer//insert-image-banner banner) (spacemacs-buffer/insert-ascii-banner-centered banner)) (spacemacs-buffer//inject-version))) (progn (if banner (progn (spacemacs-buffer/message (format "Banner: %s" banner)) (if (image-type-available-p (intern (file-name-extension banner))) (spacemacs-buffer//insert-image-banner banner) (spacemacs-buffer/insert-ascii-banner-centered banner)) (spacemacs-buffer//inject-version))) (spacemacs-buffer//insert-buttons) (spacemacs//redisplay)) (let ((banner (spacemacs-buffer//choose-banner)) (buffer-read-only nil)) (progn (if banner (progn (spacemacs-buffer/message (format "Banner: %s" banner)) (if (image-type-available-p (intern (file-name-extension banner))) (spacemacs-buffer//insert-image-banner banner) (spacemacs-buffer/insert-ascii-banner-centered banner)) (spacemacs-buffer//inject-version))) (spacemacs-buffer//insert-buttons) (spacemacs//redisplay))) spacemacs-buffer/insert-banner-and-buttons() (save-excursion (if (> (buffer-size) 0) (progn (set (quote save-line) (line-number-at-pos)) (let ((inhibit-read-only t)) (erase-buffer)))) (spacemacs-buffer/set-mode-line "") (setq spacemacs-buffer--note-widgets nil) (spacemacs-buffer/insert-banner-and-buttons) (if (and (boundp (quote spacemacs-initialized)) spacemacs-initialized) (progn (configuration-layer/display-summary emacs-start-time) (if dotspacemacs-startup-lists (progn (spacemacs-buffer/insert-startupify-lists))) (spacemacs-buffer//insert-footer) (spacemacs-buffer/set-mode-line spacemacs--default-mode-line) (force-mode-line-update) (spacemacs-buffer-mode)) (add-hook (quote emacs-startup-hook) (quote spacemacs-buffer//startup-hook) t))) (save-current-buffer (set-buffer (get-buffer-create spacemacs-buffer-name)) (page-break-lines-mode) (save-excursion (if (> (buffer-size) 0) (progn (set (quote save-line) (line-number-at-pos)) (let ((inhibit-read-only t)) (erase-buffer)))) (spacemacs-buffer/set-mode-line "") (setq spacemacs-buffer--note-widgets nil) (spacemacs-buffer/insert-banner-and-buttons) (if (and (boundp (quote spacemacs-initialized)) spacemacs-initialized) (progn (configuration-layer/display-summary emacs-start-time) (if dotspacemacs-startup-lists (progn (spacemacs-buffer/insert-startupify-lists))) (spacemacs-buffer//insert-footer) (spacemacs-buffer/set-mode-line spacemacs--default-mode-line) (force-mode-line-update) (spacemacs-buffer-mode)) (add-hook (quote emacs-startup-hook) (quote spacemacs-buffer//startup-hook) t)))) (progn (setq spacemacs-buffer--banner-length (window-width) spacemacs-buffer--last-width spacemacs-buffer--banner-length) (save-current-buffer (set-buffer (get-buffer-create spacemacs-buffer-name)) (page-break-lines-mode) (save-excursion (if (> (buffer-size) 0) (progn (set (quote save-line) (line-number-at-pos)) (let ((inhibit-read-only t)) (erase-buffer)))) (spacemacs-buffer/set-mode-line "") (setq spacemacs-buffer--note-widgets nil) (spacemacs-buffer/insert-banner-and-buttons) (if (and (boundp (quote spacemacs-initialized)) spacemacs-initialized) (progn (configuration-layer/display-summary emacs-start-time) (if dotspacemacs-startup-lists (progn (spacemacs-buffer/insert-startupify-lists))) (spacemacs-buffer//insert-footer) (spacemacs-buffer/set-mode-line spacemacs--default-mode-line) (force-mode-line-update) (spacemacs-buffer-mode)) (add-hook (quote emacs-startup-hook) (quote spacemacs-buffer//startup-hook) t)))) (if save-line (progn (goto-char (point-min)) (forward-line (1- save-line)) (forward-to-indentation 0)) (spacemacs-buffer/goto-link-line)) (switch-to-buffer spacemacs-buffer-name) (spacemacs//redisplay)) (if (or (not (eq spacemacs-buffer--last-width (window-width))) (not buffer-exists) refresh) (progn (setq spacemacs-buffer--banner-length (window-width) spacemacs-buffer--last-width spacemacs-buffer--banner-length) (save-current-buffer (set-buffer (get-buffer-create spacemacs-buffer-name)) (page-break-lines-mode) (save-excursion (if (> (buffer-size) 0) (progn (set (quote save-line) (line-number-at-pos)) (let (...) (erase-buffer)))) (spacemacs-buffer/set-mode-line "") (setq spacemacs-buffer--note-widgets nil) (spacemacs-buffer/insert-banner-and-buttons) (if (and (boundp (quote spacemacs-initialized)) spacemacs-initialized) (progn (configuration-layer/display-summary emacs-start-time) (if dotspacemacs-startup-lists (progn ...)) (spacemacs-buffer//insert-footer) (spacemacs-buffer/set-mode-line spacemacs--default-mode-line) (force-mode-line-update) (spacemacs-buffer-mode)) (add-hook (quote emacs-startup-hook) (quote spacemacs-buffer//startup-hook) t)))) (if save-line (progn (goto-char (point-min)) (forward-line (1- save-line)) (forward-to-indentation 0)) (spacemacs-buffer/goto-link-line)) (switch-to-buffer spacemacs-buffer-name) (spacemacs//redisplay))) (let ((buffer-exists (buffer-live-p (get-buffer spacemacs-buffer-name))) (save-line nil)) (if (or (not (eq spacemacs-buffer--last-width (window-width))) (not buffer-exists) refresh) (progn (setq spacemacs-buffer--banner-length (window-width) spacemacs-buffer--last-width spacemacs-buffer--banner-length) (save-current-buffer (set-buffer (get-buffer-create spacemacs-buffer-name)) (page-break-lines-mode) (save-excursion (if (> (buffer-size) 0) (progn (set ... ...) (let ... ...))) (spacemacs-buffer/set-mode-line "") (setq spacemacs-buffer--note-widgets nil) (spacemacs-buffer/insert-banner-and-buttons) (if (and (boundp ...) spacemacs-initialized) (progn (configuration-layer/display-summary emacs-start-time) (if dotspacemacs-startup-lists ...) (spacemacs-buffer//insert-footer) (spacemacs-buffer/set-mode-line spacemacs--default-mode-line) (force-mode-line-update) (spacemacs-buffer-mode)) (add-hook (quote emacs-startup-hook) (quote spacemacs-buffer//startup-hook) t)))) (if save-line (progn (goto-char (point-min)) (forward-line (1- save-line)) (forward-to-indentation 0)) (spacemacs-buffer/goto-link-line)) (switch-to-buffer spacemacs-buffer-name) (spacemacs//redisplay)))) spacemacs-buffer/goto-buffer() spacemacs/init() (if (not (version<= spacemacs-emacs-min-version emacs-version)) (message (concat "Your version of Emacs (%s) is too old. " "Spacemacs requires Emacs version %s or above.") emacs-version spacemacs-emacs-min-version) (load-file (concat (file-name-directory load-file-name) "core/core-load-paths.el")) (require (quote core-spacemacs)) (spacemacs/init) (spacemacs/maybe-install-dotfile) (configuration-layer/sync) (spacemacs-buffer/display-info-box) (spacemacs/setup-startup-hook) (require (quote server)) (if (server-running-p) nil (server-start))) eval-buffer(#<buffer *load*> nil "/Users/sunqingyao/.emacs.d/init.el" nil t) ; Reading at buffer position 1302 load-with-code-conversion("/Users/sunqingyao/.emacs.d/init.el" "/Users/sunqingyao/.emacs.d/init.el" t t) load("/Users/sunqingyao/.emacs.d/init" t t) #[0 "\205\266 \306=\203\307\310Q\202? \311=\204\307\312Q\202?\313\307\314\315#\203*\316\202?\313\307\314\317#\203>\320\321\322!D\nB\323\202?\316\324\325\324\211#\210\324=\203e\326\327\330\307\331Q!\"\325\324\211#\210\324=\203d\210\203\247\332!\333\232\203\247\334!\211\335P\336!\203\201\211\202\214\336!\203\213\202\214\314\262\203\245\337\"\203\243\340\341#\210\342\343!\210\266\f?\205\264\314\325\344\324\211#)\262\207" [init-file-user system-type delayed-warnings-list user-init-file inhibit-default-init inhibit-startup-screen ms-dos "~" "/_emacs" windows-nt "/.emacs" directory-files nil "^\\.emacs\\(\\.elc?\\)?$" "~/.emacs" "^_emacs\\(\\.elc?\\)?$" initialization format-message "`_emacs' init file is deprecated, please use `.emacs'" "~/_emacs" t load expand-file-name "init" file-name-as-directory "/.emacs.d" file-name-extension "elc" file-name-sans-extension ".el" file-exists-p file-newer-than-file-p message "Warning: %s is newer than %s" sit-for 1 "default"] 7]() command-line() normal-top-level() ``` # Answer See this issue. This problem should be fixed in the next release. **Quick fix:** Change the function `insert-string` to `insert` in `~/.emacs.d/core/core-spacemacs-buffer.el`, and everything works well. > 7 votes # Answer Other packages besides just spacemacs may use `insert-string`. A more general fix is to add to your `.emacs` file: `(or (fboundp 'insert-string) (defalias 'insert-string 'insert))` > 1 votes --- Tags: init-file, spacemacs, osx, functions, error-handling ---
thread-54312
https://emacs.stackexchange.com/questions/54312
Insert "indent" regardless of mode
2019-12-11T10:07:37.663
# Question Title: Insert "indent" regardless of mode When typing docstring in python-mode, I always have issue with indentation. If I am at this point (`|` is the cursor): ``` def fn(): """ Args:|""" ``` If I press `Enter`, the cursor will move right below the `A`, and if I press `TAB`, the cursor will circle between the beginning of the line and right below `A`, while I want it indented: ``` def fn(): """ Args: |""" ``` Currently, I am just pressing `SPACE` 4-times (I am using 4-spaces indent) after pressing `ENTER`, but I would like to know if there is a shortcut in emacs to forcefully insert an indentation (4 spaces) regardless of the mode? I found out that `M-RIGHT` inserts 4 spaces but when at the beginning of the line, it inserts 4 spaces without moving the cursor, which is pretty annoying. # Answer > 1 votes `C-u space` should insert 4 spaces at point. Beyond this: python-mode.el provides a command `py-edit-docstring`. This opens the docstring in an own buffer. Which permits to run other text-modes while editing. python-mode.el is available from Melpa. --- Tags: indentation ---
thread-54277
https://emacs.stackexchange.com/questions/54277
File tags prevent autocomplete of global tags
2019-12-10T01:17:19.707
# Question Title: File tags prevent autocomplete of global tags I amended `.emacs` as shown below. Then `M-x load-file ~/.emacs`. What I want to do in `test.org` is add `MEntal` tags to each of the two entries, for example `Read` and `Reminder`, respectively. Using the column view I type 'e' in the tags column of the first entry, then 'R'. I expect 'Read' to autocomplete, instead I get '\[No match\]'. Is there something wrong with the global tag hierarchy defined in `.emacs`? `~/.emacs`: ``` (setq org-tag-alist '( (:startgrouptag) ("ACTivities") (:grouptags) ("MEntal") ("PHysical") ("TRansact") (:endgrouptag) (:startgrouptag) ("MEntal") (:grouptags) ("Read") ("Write") ("Reminder") (:endgrouptag) ) ) ``` `test.org`: ``` #+TAGS: [ editor : emacs ] * 2019 ** 2019-12 December *** 2019-12-01 Sunday **** TODO [#C] [[http://tuhdo.github.io/helm-intro.html][Helm-intro]] :emacs: - State "TODO" from [2019-12-01 Sun 17:31] **** `C-u C-c C-q` to realign tags :emacs: Entered on [2019-12-01 Sun 20:29] ``` # Answer > 1 votes This was suggested to me through the `org-mode` mailing list: replace ‘org-tag-persistent-alist’ instead of `org-tag-alist` in ~/.emacs. I tried it: autocomplete works for both the local and global tag lists. --- Tags: auto-complete-mode, tags ---
thread-48057
https://emacs.stackexchange.com/questions/48057
Sending email with attachment and using 'recipient-filename'
2019-02-25T16:33:44.410
# Question Title: Sending email with attachment and using 'recipient-filename' I am using `message-send-and-exit` (with mu4e) to send an email with an attachment. I would like to rename the file so that in the email it appears with a different name than my local file. According to the docs, I should be able to do that with `recipient-filename`. I also tried setting `name`. ``` <#part type="application/pdf" filename="old-name.pdf" recipient-filename="new-name.pdf" name="new-name.pdf" disposition=attachment> <#/part> ``` However, upon testing, this doesn't seem to work. When I receive the email I get in the header ``` Content-Type: application/pdf; name="old-name.pdf" Content-Description: old-name.pdf Content-Disposition: attachment; filename="old-name.pdf" ``` What is the way to achieve this? # Answer > 0 votes This seems to have been solved with this commit, but I think it has not yet been released. --- Tags: email, mu4e, attachment ---
thread-54307
https://emacs.stackexchange.com/questions/54307
How to cycle among all live buffers?
2019-12-11T04:49:42.837
# Question Title: How to cycle among all live buffers? Emacs 26.2 `M-C-L` is bound to `switch-to-next-buffer`. I have many files open but it's simply flopping between two. On my old XEmacs the same key cycled through all of them (and `S-M-C-L` did so backwards). I can't use that any more to find the exact function it was bound to. Do I need a different function? Or does this function need an argument? (It seems to have no documentation.) (To be clear: I have only one window open and it is not split in two.) # Answer Emacs provides two built-in functions named `next-buffer` with a default binding of `C-x <RIGHT>` and `previous-buffer` with a default binding of `C-x <LEFT>`: https://www.gnu.org/software/emacs/manual/html\_node/emacs/Select-Buffer.html > 1 votes # Answer Try using `bs-cycle-previous`, `bs-cycle-next` which come with emacs. These use cycling rules you can configure, check their help to see options. > 0 votes --- Tags: buffers ---
thread-54311
https://emacs.stackexchange.com/questions/54311
Can emacs show formatted backtraces?
2019-12-11T08:58:05.370
# Question Title: Can emacs show formatted backtraces? When getting an Elisp error and trying to debug the problem, the backtrace buffer is quite hard to read with its long lines. Is there a way to get a pretty-printed backtrace buffer? # Answer > Is there a way to get a pretty-printed backtrace buffer? There is, but you'll have to wait for Emacs 27 to be released or get a build of it in the meantime. Quoth its `etc/NEWS` file: ``` * Changes in Specialized Modes and Packages in Emacs 27.1 ** Debugger *** The Lisp Debugger is now based on 'backtrace-mode'. Backtrace mode adds fontification and commands for changing the appearance of backtrace frames. See the node "(elisp) Backtraces" in the Elisp manual for documentation of the new mode and its commands. * New Modes and Packages in Emacs 27.1 ** Backtrace mode improves viewing of Elisp backtraces. Backtrace mode adds pretty printing, fontification and ellipsis expansion to backtrace buffers produced by the Lisp debugger, Edebug and ERT. See the node "(elisp) Backtraces" in the Elisp manual for documentation of the new mode and its commands. ``` And quoth `"(elisp) Backtraces"`: ``` In backtraces, the tails of long lists and the ends of long strings, vectors or structures, as well as objects which are deeply nested, will be printed as underlined “...”. You can click with the mouse on a “...”, or type <RET> while point is on it, to show the part of the object that was hidden. To control how much abbreviation is done, customize ‘backtrace-line-length’. Here is a list of commands for navigating and viewing backtraces: ‘+’ Add line breaks and indentation to the top-level Lisp form at point to make it more readable. ‘-’ Collapse the top-level Lisp form at point back to a single line. ``` Here's an example of the new functionality. Let's say you insert the following into the `*scratch*` buffer: ``` (progn (setq debug-on-error t) (+ (mapcar (lambda (n) (cons n (number-to-string n))) (number-sequence 0 7)))) ``` and then evaluate it by typing `C-x``C-e`. You should be greeted by the following backtrace: ``` Debugger entered--Lisp error: (wrong-type-argument number-or-marker-p ((0 . "0") (1 . "1") (2 . "2") (3 . "3") (4 . "4") (5 . "5") (6 . "6") (7 . "7"))) +(((0 . "0") (1 . "1") (2 . "2") (3 . "3") (4 . "4") (5 . "5") (6 . "6") (7 . "7"))) (progn (setq debug-on-error t) (+ (mapcar #'(lambda (n) (cons n (number-to-string n))) (number-sequence 0 7)))) (progn (progn (setq debug-on-error t) (+ (mapcar #'(lambda (n) (cons n (number-to-string n))) (number-sequence 0 7))))) eval((progn (progn (setq debug-on-error t) (+ (mapcar #'(lambda (n) (cons n ...)) (number-sequence 0 7))))) t) elisp--eval-last-sexp(nil) eval-last-sexp(nil) funcall-interactively(eval-last-sexp nil) call-interactively(eval-last-sexp nil nil) command-execute(eval-last-sexp) ``` If you then type `+` (`backtrace-multi-line`), the first line will be pretty-printed as follows: ``` Debugger entered--Lisp error: (wrong-type-argument number-or-marker-p ((0 . "0") (1 . "1") (2 . "2") (3 . "3") (4 . "4") (5 . "5") (6 . "6") (7 . "7"))) +(((0 . "0") (1 . "1") (2 . "2") (3 . "3") (4 . "4") (5 . "5") (6 . "6") (7 . "7"))) (progn (setq debug-on-error t) (+ (mapcar #'(lambda (n) (cons n (number-to-string n))) (number-sequence 0 7)))) (progn (progn (setq debug-on-error t) (+ (mapcar #'(lambda (n) (cons n (number-to-string n))) (number-sequence 0 7))))) eval((progn (progn (setq debug-on-error t) (+ (mapcar #'(lambda (n) (cons n ...)) (number-sequence 0 7))))) t) elisp--eval-last-sexp(nil) eval-last-sexp(nil) funcall-interactively(eval-last-sexp nil) call-interactively(eval-last-sexp nil nil) command-execute(eval-last-sexp) ``` Typing `-` (`backtrace-single-line`) will return the trace to its original formatting. --- ### Edit Here's a quick way to toggle between folding and unfolding all frames in the current backtrace: ``` (define-minor-mode my-backtrace-multi-line-mode "Toggle pretty-printing of all sexps in the current backtrace." :group 'debugger (if (not (derived-mode-p #'backtrace-mode)) (progn (message "Not in a Backtrace mode buffer") (setq my-backtrace-multi-line-mode nil)) ;; Save some information in order to return to original form. (let ((idx (backtrace-get-index)) ;; If idx is nil we are either on the first line or at EOB. (eob (eobp)) (fun (if my-backtrace-multi-line-mode #'backtrace-multi-line #'backtrace-single-line))) (goto-char (point-min)) (while (ignore-errors (funcall fun) (backtrace-forward-frame) t)) (cond (idx (while (/= (backtrace-get-index) idx) (backtrace-backward-frame))) (eob (goto-char (point-max))) (t (goto-char (point-min)) (let ((eol (line-end-position))) (search-forward ":" eol t) (search-forward " " eol t))))))) ``` (Defining a full-blown minor mode for this is overkill but it saved me having to write the handy toggling logic.) Here's how you could bind it to, say, `=` in `*Backtrace*` buffers: ``` (with-eval-after-load 'debug (define-key debugger-mode-map "=" #'my-backtrace-multi-line-mode)) ``` > 7 votes # Answer I haven't used it myself, but there is this gist born from this reddit post. A comment on the reddit post includes this screen shot. Maybe it meets your needs. > 1 votes --- Tags: debugging, backtrace, pretty-print ---
thread-54331
https://emacs.stackexchange.com/questions/54331
How to replace the buffer without slowing down the undo system?
2019-12-12T03:59:39.323
# Question Title: How to replace the buffer without slowing down the undo system? Say I have a command that operates on the entire buffer. The simple solution is to: * Run the command taking the entire buffer as input. * Store the output. * Clear the current buffer. * Insert the new contents. The problem with this is it's quite slow and it seems the undo system stores a lot of data for this operation. In cases where only a few changes are made - is there a way to only apply changes - in a way doesn't require the heavy operation of replacing the entire contents? Something like creating a diff and applying it, instead of replacing the entire buffer, however it need not use the diff format. Or do I need to write my own code to detect differences and apply them as edits? # Answer Emacs-26 introduced `replace-buffer-contents` specifically to do that job. But use it with care: it works well when there are few differences, but if the new content happens to be completely different from the old it can be a lot more costly. > 5 votes --- Tags: buffers, text-editing ---
thread-54292
https://emacs.stackexchange.com/questions/54292
Copy results of `org-export` directly to clipboard
2019-12-10T16:37:03.840
# Question Title: Copy results of `org-export` directly to clipboard I often find myself doing this: * Selecting a region of text in an `org` file. * Calling `org-md-export-as-markdown`. * Selecting the converted text in the temporary buffer (can't just do `mark-whole-buffer` since for these purposes I'm obviously not interested in the empty Table of Contents I get). * Killing the temporary buffer and going back to where I was. **EDIT**: Here is my **question**: How can I write a function that will, after selecting a region of text, do all of that for me? In other words, I want a function which will take a region from an `org` file, copy the result of `org-md-export-as-markdown` to the clipboard, and return to the `org` file I called the function from. **Some related attempts**: *John Kitchin* has a post where he does something similar to what I'm doing. But he uses `texutil`, since he wants the output in a format that `org` won't export to. I'm assuming what I need would be much simpler than that. *Oleh Krehel* has a function that copies the converted `html` from a region as part of his emacs config (see here). But he uses `xclip` which I believe is not available for macOS. Abo-abo's function is here ``` (defun ora-org-to-html-to-clipboard () "Export region to HTML, and copy it to the clipboard." (interactive) (org-export-to-file 'html "/tmp/org.html") (apply 'start-process "xclip" "*xclip*" (split-string "xclip -verbose -i /tmp/org.html -t text/html -selection clipboard" " "))) ``` I presume I can modify something like this by replacing ``` xclip -verbose -i /tmp/org.html -t text/html -selection clipboard ``` with ``` pbcopy < /tmp/org.html ``` but I can't quite get it to work. **My own, failed attempt so far:** This was my blind attempt at adapting the function `ora-org-to-html` to use `pbcopy` instead. (Adapting it to use `org-md-export-to-markdown` would be fairly straightforward, I think.) ``` (defun org-to-html-to-clipboard () "Export region to HTML, and copy it to the clipboard." (interactive) (org-export-to-file 'html "/tmp/org.html") (apply 'start-process "pbcopy" "*pbcopy*" (split-string "pbcopy < /tmp/org.html"))) ``` Running this does create the file `/tmp/org.html` but the contents aren't sent to the clipboard. Further, the `html` file contains the entirety of the buffer I run the function from (which I gather is what the original function was supposed to do) rather than just the selected region. Finally, this function requires creating a temporary file, rather than just using the temporary buffer that `org-mode` generates with the `*-export-as-*` functions. --- *I'm completely illiterate when it comes to `elisp` so any suggestions, no matter how elementary they seem, would be most welcome.* # Answer I'm posting this here in case it helps anyone else. Following a suggestion by u/ImmediateCurve over at Reddit, I ended up with the following function, which does what I want (it uses `simpleclip.el` since I mostly rely on it for interacting with the system clipboard on macOS): ``` (defun apc/org-md-to-clipboard () (interactive) (save-window-excursion (let ((org-export-with-toc nil)) (let ((buf (org-export-to-buffer 'md "*tmp*" nil nil t t))) (save-excursion (set-buffer buf) (simpleclip-set-contents (buffer-string)) (kill-buffer-and-window) ))))) ``` > 0 votes --- Tags: org-mode, org-export ---
thread-54316
https://emacs.stackexchange.com/questions/54316
Omit ~ before the \ref command (with RefTeX+AUCTeX)
2019-12-11T15:11:07.637
# Question Title: Omit ~ before the \ref command (with RefTeX+AUCTeX) The default behaviour of `C-c )` is to insert `\ref` and prefix it with`~`. I don't need the tilde after `\S` (i.e. I need the output to look like `\S\ref{label}`, rather than `\S~\ref{label}`). Is there a short code to insert into `.emacs` without copy pasting the whole `reftex-reference` function and adding exceptions there? # Answer Here's a different answer along the lines of my comment: don't worry about what reftex inserts but clean up as you save the buffer. The idea is to use the `before-save-hook` to call a function that you define, just before the buffer is saved. The function will use the programmatic equivalent of `replace-regexp` to do the clean-up: it'll search for all occurrences of `\S~\ref` and replace each one by `\S\ref`. First, here's the function: ``` (defun jabot-cleanup () (goto-char (buffer-end -1)) (while (re-search-forward (regexp-quote "\\S~\\ref{")) (replace-match "\\S\\ref{" t t))) ``` The function goes to the beginning of the buffer and then searches for the pattern repeatedly until it gets to the end of the buffer. Each time the loop finds a match, it replaces it with the replacement text. Backslashes have to be escaped in strings, which is why they are doubled. There are a couple of subtle points here (the use of `regexp-quote` to simplify the search pattern, the use of optional arguments to `replace-match` to maintain the case of the original and to simplify the replacement pattern, ignoring narrowing complications...) that would take too long to explain. You will need to consult the documentation for all the hairy details. Once you have a function (and you have tested it), then you can add it to the `before-save-hook` which will ensure that the function will be called when you say `M-x save-buffer`. The function will be called just before the buffer is written out to a file. There is also an `after-save-hook` (and many others in all parts of emacs: they are one very common way of customizing behavior) but we don't use it here. To add the function to the hook, say: ``` (add-hook 'before-save-hook #'jabot-cleanup) ``` You can add both the definition of the function and the `add-hook` line to your .emacs if you want to make this permanent. > 0 votes # Answer `reftex-reference` inserts the string using the following piece of code: ``` (insert (if reftex-format-ref-function (funcall reftex-format-ref-function label form reftex-refstyle) (format form label label))) ``` So you can define your own `reftex-format-ref-function` to format the label any way you want. The doc string of `reftex-format-ref-function` says: > Function which produces the string to insert as a reference. Normally should be nil, because the format to insert a reference can already be specified in ‘reftex-label-alist’. > > This hook also is used by the special commands to insert e.g. ‘\vref’ and ‘\fref’ references, so even if you set this, your setting will be ignored by the special commands. > > The function will be called with three arguments, the LABEL, the DEFAULT FORMAT, which normally is ‘~\ref{%s}’ and the REFERENCE STYLE. The function should return the string to insert into the buffer. Here's a very simple (and probably inadequate) function, but it may be enough to start with. The function just erases any `~` in the format, before using it to format the final output: ``` (setq reftex-format-ref-function (lambda (label fmt ref-style) (let ((fmt (replace-regexp-in-string "~" "" fmt))) (format fmt label label)))) ``` You can add this to your `.emacs` (and if you don't like it or see strange results, you can delete it or comment it out and then restart your emacs - so you should probably test it in a separate session). Note that this is an anonymous function that is "assigned" to the variable `reftex-format-ref-function`. The reason for this is somewhat technical, so I'm not going to explain it here. > 0 votes --- Tags: auctex, reftex-mode ---
thread-54330
https://emacs.stackexchange.com/questions/54330
Enabling `flyspell-prog-mode` starts `flyspell-mode` instead
2019-12-12T03:52:23.537
# Question Title: Enabling `flyspell-prog-mode` starts `flyspell-mode` instead I've been playing with `flyspell` lately and with my recently established setup for spell-check, I wanted to enable it for all modes. I found that `flyspell-mode` and `flyspell-prog-mode` are best for `text-mode` and `prog-mode` respectively and found in an answer to a similar question that it can be done as: ``` (add-hook 'text-mode-hook 'flyspell-mode) (add-hook 'prog-mode-hook 'flyspell-prog-mode) ``` I've done the same thing but have noticed that for both the cases, `flyspell-mode` gets enabled and the `flyspell-prog-mode` doesn't get enabled at all. My code can be found here and it's the exact same as suggested. Any help would be appreciated. # Answer > 2 votes To help answer this question, we can perform the following steps: 1. Load the `flyspell.el` library by typing `M:` aka `M-x eval-expression`, and then `(require 'flyspell)` 2. Locate the source code for the function `flyspell-prog-mode` by typing: `M-x find-function RET flyspell-prog-mode RET` Step two leads us to the source code of the function `flyspell-prog-mode`, which looks like this in Emacs 26: ``` (defun flyspell-prog-mode () "Turn on `flyspell-mode' for comments and strings." (interactive) (setq flyspell-generic-check-word-predicate #'flyspell-generic-progmode-verify) (setq-local flyspell--prev-meta-tab-binding (or (local-key-binding "\M-\t" t) (global-key-binding "\M-\t" t))) (flyspell-mode 1) (run-hooks 'flyspell-prog-mode-hook)) ``` Based upon our review of the source code, we now know that `flsypell-mode` is activated when calling `flyspell-prog-mode`, which is the second to the last line that reads: `(flyspell-mode 1)`. And, we see that two variables are expressly set when calling `flyspell-prog-mode`; i.e., `flyspell-generic-check-word-predicate` and `flyspell--prev-meta-tab-binding`. We observe that `flyspell--prev-meta-tab-binding` is set on a buffer-local basis with `setq-local`. We see that `flyspell-generic-check-word-predicate` is set with `setq` and we wonder to ourselves whether that variable is buffer-local already or whether the value is being modified on a global basis. To satisfy our curiosity, we look up the variable with `C-h v` aka `M-x describe-variable`. We read the `*Help*` buffer and see that this variable was already buffer-local and we surmise that this is the reason why `setq` was used when setting the aforementioned variable in the function `flyspell-prog-mode` -- the `*Help*` buffer states in relevant part: "*Automatically becomes buffer-local when set.*" **CONCLUSION**: `flyspell-prog-mode` is not really a mode *per se*; i.e., it is not a minor-mode and it is not a major-mode. Instead, it is just `flyspell-mode` *plus* the setting of two variables on a buffer-local basis; i.e., `flyspell-generic-check-word-predicate` and `flyspell--prev-meta-tab-binding`. `flyspell-generic-check-word-predicate` is set with the value of a *function* named `flyspell-generic-progmode-verify`. `flyspell--prev-meta-tab-binding` is a keyboard shortcut. The hook `flyspell-prog-mode-hook` has no default value, but we could add anything that is appropriate; e.g., `(add-hook 'flyspell-prog-mode-hook (lambda () (message "Turned on flyspell-prog-mode ...")))` --- Tags: flyspell, ispell ---
thread-51915
https://emacs.stackexchange.com/questions/51915
I-search - case sensitive
2019-07-30T08:13:28.447
# Question Title: I-search - case sensitive windows 10, emacs 26.1 When I use `I-search`, then Emacs ignore case sensitive. but I need case sensitive `I-search` # Answer You can toggle case sensitivity during incremental search by typing `M-c`. Documentation here. > 3 votes # Answer `C-s M-c` **C-s** for isearch and when in minibuffer type **M-c** > 1 votes --- Tags: isearch, case-folding ---
thread-54163
https://emacs.stackexchange.com/questions/54163
How to move the cursor to the next instance of the text the cursor is currently on?
2019-12-04T21:14:57.680
# Question Title: How to move the cursor to the next instance of the text the cursor is currently on? Suppose your code looks like this: ``` 1. term_cursor_is_on = 500 2. cursory_next_line = 42 [...] 101. next_instance_line = term_cursor_is_on ``` And suppose that your cursor is on line 1 (unimportant, but suppose it is between 'c' and 'u') and you want to jump to the next instance of "term\_cursor\_is\_on" on line 101. Naively, you can do an I-search for "term\_cursor\_is\_on" and press ctrl+s. But this seems inefficient, since it requires you to type the currently-hovered-over term into I-search. Is there a better way to jump to the next instance of the term? Either a package, or some shortcut to auto-paste the hovered-over-term into I-search? # Answer > 9 votes I think what you're looking for is `isearch-forward-symbol-at-point` which is bound to `M-s .` Here's its documentation: > (isearch-forward-symbol-at-point) > > Do incremental search forward for a symbol found near point. Like ordinary incremental search except that the symbol found at point is added to the search string initially as a regexp surrounded by symbol boundary constructs \_\< and \_\>. See the command ‘isearch-forward-symbol’ for more information. # Answer > 3 votes Alternatively, you can use `C-s C-w` to search for some text the cursor is on. # Answer > 1 votes I use and recommend package `highlight-symbol`. It not only does what you want, but highlights every occurrence of the term you want. One command highlights all the matches, another cycles through them forwards, another backwards. Not only that, but it highlights each term you search for in a different color, and the colors persist until you close or revert (reload) the buffer. It also gives you the command `highlight-symbol-query-replace`, which lets you do a search-and-replace for the symbol at point ("point" is the Emacs vocabulary for what you're referring to as "the cursor") with every target pre-highlighted. This is the easiest way I've found so far for this very common programming requirement. I have the commands all bound to F4 with and without various modifiers: `F4`, `C-F4`, `M-F4`, `S-F4`, `C-M-F4`, etc. I love it! http://nschum.de/src/emacs/highlight-symbol/ --- Tags: navigation ---
thread-54349
https://emacs.stackexchange.com/questions/54349
How do I install An Introduction to Programming in Emacs Lisp?
2019-12-13T05:21:58.190
# Question Title: How do I install An Introduction to Programming in Emacs Lisp? This may sound odd, but when I type `C-h i m Emacs Lisp Intro` -- it's not there. I'm on Ubuntu 19.10 with Emacs 26.3. I tried `apt-get install emacs-lisp-intro` as the EmacsWiki said, but there's no such thing in the Ubuntu world. How can I get it installed? # Answer > 2 votes I am not a Ubuntu user, on Debian this Elisp intro come from emacs-common-non-dfsg. I think that should do it : https://packages.ubuntu.com/search?lang=en&keywords=emacs-common-non-dfsg --- Tags: help, ubuntu ---
thread-54351
https://emacs.stackexchange.com/questions/54351
How to run a custom formatting tool on save?
2019-12-13T07:45:52.020
# Question Title: How to run a custom formatting tool on save? While there are packages that format on save, I'd like to be able to run a custom command that auto-formats a file on save. Upon saving it runs an external process that: * Takes the buffer as `stdin`. * Outputs to a temporary file. After that: * The output is used to replace the current buffer which is then saved. * Any errors from the `stderr` are reported as errors. * Any output from the `stdout` is printed as messages. --- For the purpose of testing, this could be the auto-formatting command: It converts the text to title-caps. ``` python -c "with open(__import__('sys').argv[-1], 'w') as fh: fh.write(__import__('sys').stdin.read().title())" -- /tmp/TEMP_FILE_FROM_EMACS.txt ``` ... where `/tmp/TEMP_FILE_FROM_EMACS.txt` is a generated temp file name. --- *I realize this may be an involved answer. If this seems like too much hassle to answer, I'll investigate and post an answer myself, since I think it's useful to have a general function to handle this.* # Answer This can be done using: * `call-process-region` to run the command and catch the stdout/stderr. * `replace-buffer-contents` to update the region without causing the entire buffer to be replaced. This is important to avoid this to be seen as one very large undo-step which risks loosing your undo history for example. This code used clang-format package as a reference. ``` (defun mycustom-fmt-buffer () (interactive) (let ((this-buffer (current-buffer)) (my-command "python") (temp-buffer (generate-new-buffer " *mycustom-fmt*")) ;; Use for format output or stderr in the case of failure. (temp-file (make-temp-file "mycustom-fmt" nil ".el")) ;; Always use 'utf-8-unix' & ignore the buffer coding system. (default-process-coding-system '(utf-8-unix . utf-8-unix))) (condition-case err (unwind-protect (let ((status (progn (apply #'call-process-region nil nil my-command nil ;; stdout is a temp buffer, stderr is file. `(,temp-buffer ,temp-file) nil ;; arguments. ` ("-c" "with open(__import__('sys').argv[-1], 'w') as fh: fh.write(__import__('sys').stdin.read().title())" ,temp-file)))) (stderr (with-temp-buffer (unless (zerop (cadr (insert-file-contents temp-file))) (insert ": ")) (buffer-substring-no-properties (point-min) (point-max))))) (cond ((stringp status) (error "(mycustom-fmt killed by signal %s%s)" status stderr)) ((not (zerop status)) (error "(mycustom-fmt failed with code %d%s)" status stderr)) (t ;; Include the stdout as a message, ;; useful to check on how the program runs. (let ((stdout (with-current-buffer temp-buffer (buffer-substring-no-properties (point-min) (point-max))))) (unless (string-equal stdout "") (message "%s" stdout))))) ;; Load the temp file into a temp buffer ;; & replace this-buffers contents. (with-temp-buffer (insert-file-contents temp-file) (let ((temp-buffer (current-buffer))) (with-current-buffer this-buffer (replace-buffer-contents temp-buffer)))))) ;; Show error as message, so we can clean-up below. (error (message "%s" (error-message-string err)))) ;; Cleanup. (delete-file temp-file) (when (buffer-name temp-buffer) (kill-buffer temp-buffer)))) (defun mycustom-fmt-save-hook-for-this-buffer () (add-hook 'before-save-hook (lambda () (progn (mycustom-fmt-buffer) ;; Continue to save. nil)) nil ;; Buffer local hook. t)) ;; Example for elisp, could be any mode though. (add-hook 'emacs-lisp-mode-hook (lambda () (mycustom-fmt-save-hook-for-this-buffer))) ``` > 5 votes --- Tags: formatting, subprocess ---
thread-54314
https://emacs.stackexchange.com/questions/54314
roll back org-mode version
2019-12-11T13:42:37.623
# Question Title: roll back org-mode version I have a scimax based configuration and my source block fontification is broken. I suspect it has to do with the release of Org-mode 9.3 which I am currently using. Thats why I am trying to roll-back the org version. How can I install org-plus-contrib (or even just org 9.2) ? Thanks in advance # Answer > 1 votes There is currently no builtin roll-back available from emacs builtin package manager, so you have to do it manually. You could follow the install instructions in the org-mode manual: 1. Go to Org-mode homepage 2. Click on browse the development version from code.orgmode.org 3. Click on releases 4. download the release you'd like to use in you case, probably version 9.2.6 5. unpack this downloaded archive into your home directory (i.e. `~/.emacs.d/org-mode`) and remember that location! 6. enter that location from within a command line and run `make autoloads` 7. edit your emacs init files and add the lines at the end of this post 8. open package list with `M-x list-packages` and uninstall org-mode version 9.3 9. restart emacs Optional: run `make doc` same way like you did with `make autoloads` to generate info and pdf manuals. --- How to revert those changes to use a recent version of org-mode again: 1. remove the aditional lines from your emacs init files 2. reinstall org-mode from package manager `M-x list-packages` 3. restart emacs 4. remove the older downloaded org-mode version (i.e. `rm ~/.emacs.d/org-mode`) Thats it. --- lines to add to emacs init files (with example path): ``` (add-to-list 'load-path "~/.emacs.d/org-mode/lisp") (add-to-list 'load-path "~/.emacs.d/org-mode/contrib/lisp" t) ``` --- Tags: org-mode ---
thread-54319
https://emacs.stackexchange.com/questions/54319
how to display target of an org-mode link in the echo area or as tooltip?
2019-12-11T16:29:06.247
# Question Title: how to display target of an org-mode link in the echo area or as tooltip? In org mode when I hover over a link, I get a tooltip that shows the target of the link. But I'd like to see the target when I just move point onto a link, either as a tooltip or in the echo area. For example, with: ``` * a headline and a [[https://orgmode.org/][link to orgmode.org]]. And an internal link [[id:20191211T100231.972516][to a headline in this file]]. * another headline with an ID property :PROPERTIES: :ID: 20191211T100231.972516 :END: content ``` If point is somewhere in the "link to orgmode.org" text, I'd like to see something like `LINK: https://orgmode.org` displayed in the echo area, or as a tooltip. Similarly for the internal link: it would be cool if the displayed text actually went and looked up the headline title and displayed `LINK: "another headline with an ID property"` Is there a way to do this? # Answer tl;dr: do `M-x customize-variable` for the variable `help-at-pt-display-when-idle` and set its value to `t`. (Or "always", which is what the Customize buffer says.) What was initially confusing here is that there's the mouse pointer, and also the cursor (which here on emacs.sx we call *point*). As mentioned above, `org-mode` by default sets the `:help-echo` property for links, which works with emacs' built-in *mouse* tooltip support. The idea of a "point tooltip" is separate, and, fortunately, is a solved problem: quoth 10.10 Help on Active Text and Tooltips: > On terminals that don't support mouse-tracking, you can display the help text for active buffer text at point by typing `C-h .` (`display-local-help`). This shows the help text in the echo area. To display help text automatically whenever it is available at point, set the variable `help-at-pt-display-when-idle` to `t`. Note that `help-at-pt-display-when-idle` doesn't immediately work if you enable it with `M-x set-variable`; from the variable's documentation: > This variable only takes effect after a call to `help-at-pt-set-timer`. The help gets printed after Emacs has been idle for `help-at-pt-timer-delay` seconds. You can call `help-at-pt-cancel-timer` to cancel the timer set by, and the effect of, `help-at-pt-set-timer`. > > When this variable is set through Custom, `help-at-pt-set-timer` is called automatically, > 6 votes --- Tags: org-mode, org-link, echo-area, tooltip ---
thread-54360
https://emacs.stackexchange.com/questions/54360
Why does `make-symbol` work in macro expansion, just as `gensym` works?
2019-12-13T18:31:25.633
# Question Title: Why does `make-symbol` work in macro expansion, just as `gensym` works? In the dash library I noticed the use of `make-symbol` to avoid symbol conflicts during macro expansion. ``` (defmacro --filter (form list) "Anaphoric form of `-filter'. See also: `--remove'." (declare (debug (form form))) (let ((r (make-symbol "result"))) `(let (,r) (--each ,list (when ,form (!cons it ,r))) (nreverse ,r)))) ``` From what I read in common lisp books, `gensym` is used for things like this to create a unique symbols via. ``` (let ((r (cl-gensym "result"))) ...) ``` I'm confused because when I macro expand this kind of form. ``` (let ((result '(1 2 3 4))) (--filter (> 2 it) result)) ``` I get this and it looks like the symbol created with `make-symbol` named `result` is indeed conflicting with the `result` that contains `'(1 2 3 4)`. In fact, when I copy the result of this macroexpansion and run it myself I get what I expect: nil. ``` (let ((result '(1 2 3 4))) (let (result) (--each result (when (> 2 it) (!cons it result))) (nreverse result))) ``` But this seems to work. Instead of returning nil as I would expect from the macroexpansion. Why is this? ``` (let ((result '(1 2 3 4))) (--filter (> 2 it) result)) ;; => (1) ``` # Answer > 4 votes It's not the same symbol, even though it has the same name. This returns `(nil foo)`, because the interned symbol `foo` created by reading `'foo` is *not the same symbol* as the uninterned symbol `foo` returned by `make-symbol`. ``` (let ((res (make-symbol "foo"))) (list (eq res 'foo) res)) ``` `C-h f make-symbol` says: > `make-symbol` is a built-in function in `C source code`. > > `(make-symbol NAME)` > > Return a newly allocated **uninterned** symbol whose name is `NAME`. > > Its value is void, and its function definition and property list are `nil`. This function does not change global state, including the match data. `cl-gensym` also creates an uninterned symbol. As the Common Lisp doc for `gensym` says: > Creates and returns a *fresh*, *uninterned* *symbol*, as if by calling `make-symbol`. (The only difference between `gensym` and `make-symbol` is in how the *new-symbol*'s *name* is determined.) > > The *name* of the *new-symbol* is the concatenation of a prefix, which defaults to `"G"`, and a suffix, which is the decimal representation of a number that defaults to the *value* of `*gensym-counter*`. Unfortunately, the Elisp doc for `gensym` does not include the helpful info about its similarity and difference from `make-symbol`. The Common Lisp doc is better, in this case. --- As for your related question in the comments: "Why would anyone use `gensym`, since the names are not meaningful?": * You can programmatically produce the symbol names with `gensym`. If you just need a few such symbols (e.g. hand-coding) then you can of course use `make-symbol`, to have meaningful names. * Sometimes you don't care what the names are, or there may be a lot of them - again, especially when the code is generated by program. The second case is akin to using `x1`, `x2`,... and `y1`, `y2`,... versus using `x`, `y`, `z`,... (But the numerals need to be unique across the Emacs session.) Another analogy would be GUIDs. `gensym` does let you provide a *name prefix*, and that can be meaningful, e.g., for a group of symbols having something in common. --- Tags: elisp, symbols, macroexpansion ---
thread-54362
https://emacs.stackexchange.com/questions/54362
auto-fill-mode without automatic indentation
2019-12-13T23:03:34.573
# Question Title: auto-fill-mode without automatic indentation Is it possible to prevent `auto-fill-mode` from automatically indenting new lines according to the previous? I would like new lines to begin at column 0 regardless of the previous line's indentation. # Answer > 1 votes Presumably, you want to use `paragraph-indent-text-mode` or `paragraph-indent-minor-mode` which are resp. major and minor modes to use when editing text where paragraphs are separated by having the first line be indented and the rest of the paragraph start in column 0. --- Tags: indentation, auto-fill-mode ---
thread-34651
https://emacs.stackexchange.com/questions/34651
How can I create custom org-mode templates?
2017-08-03T21:16:17.833
# Question Title: How can I create custom org-mode templates? I use `org-mode` to maintain my personal site. Whenever I create a new `.org` file in my website, I find myself retyping the following ``` #+TITLE: #+OPTIONS: html-postamble:nil whn:nil toc:nil nav:nil #+HTML_HEAD: #+HTML_HEAD_EXTRA: ``` Is it possible to bind this template to a keystroke? # Answer You can use the templating system of org-mode. If you insert the following lines at the end of your `init.el` file: ``` (add-to-list 'org-structure-template-alist '("P" "#+TITLE:\n#+OPTIONS: html-postamble:nil whn:nil toc:nil nav:nil\n#+HTML_HEAD:\n#+HTML_HEAD_EXTRA:\n\n? ")) ``` After you restart emacs or source your `init.el` file, you only have to type `<P` at the beginning of your org-mode file, then the `<TAB>` key and this will automatically integrate the desired code. See http://orgmode.org/manual/Easy-templates.html for the documentation of the template mechanism. > 6 votes # Answer You may want to check out this example wherein the author suggests this `define-skeleton`: ``` (define-skeleton org-skeleton "In-buffer settings info for a emacs-org file." "Title: " "#+TITLE:" str " \n" "#+AUTHOR: Your Name\n" "#+email: your-email@server.com\n" "#+INFOJS_OPT: \n" "#+BABEL: :session *R* :cache yes :results output graphics :exports both :tangle yes \n" "-----" ) (global-set-key [C-S-f4] 'org-skeleton) ``` Customize to please. But like so many things in the Emacs world, I don't know if this is "best practice." There is also `autoinsert` which will insert lines whenever you create a new file. Here's what I have in my init: ``` (use-package autoinsert :ensure t :init ;; Don't want to be prompted before insertion: (setq auto-insert-query nil) (setq auto-insert-directory (locate-user-emacs-file "templates")) (add-hook 'find-file-hook 'auto-insert) (auto-insert-mode 1) :config (define-auto-insert "\\.org?$" "default-org.org")) ``` Note the last line `(define-auto-insert "\\.org?$" "default-org.org")` So the file `default-org.org` (in my `.emacs.d` directory) contains my customized in-buffer settings, which will be automatically inserted at the top whenever I create a file with an `org` ending. Unfortunately, I could not figure out how to plant variables and expanding things in this template, as is supposedly possible. (See this cry for help.) > 2 votes --- Tags: org-mode, template ---
thread-54371
https://emacs.stackexchange.com/questions/54371
Accessing regular expression groups outside a buffer
2019-12-14T15:49:27.600
# Question Title: Accessing regular expression groups outside a buffer The code from here accesses groups of a regular expression match in a buffer in interactive mode: ``` (let ((re (concat "\\([ \t]*" org-clock-string " *\\)" "\\([[<][^]>]+[]>]\\)\\(-+\\)\\([[<][^]>]+[]>]\\)" "\\(?:[ \t]*=>.*\\)?"))) (when (looking-at re) (let ((indentation (match-string 1)) (start (match-string 2)) (to (match-string 3)) (end (match-string 4)) (use-start-as-default (equal end-as-default nil))) ``` But `match-string n` fails with in non-interactive mode, for example in the `*scratch*` buffer: ``` (string-match "\\([0-9]?[0-9]\\):\\([0-9]\\{2\\}\\)" "09:20") 0 (match-string 0) #("save" 0 4 (fontified nil face font-lock-comment-face)) ``` How can I access regular expression groups outside a buffer? **Update**: after reading Strange behaviour of match-string/string-match adding the optional argument to `match-string` doesn't help and I get an error: ``` (string-match "\\([0-9]?[0-9]\\):\\([0-9]\\{2\\}\\)" "09:20") 0 (match-string 0 "09:20") ;; Debugger entered--Lisp error: (args-out-of-range "09:20" 9 15) ``` When I run it again, then the last expression returns `"09:20"`, even after I restart Emacs (\[this thread from the comments\]. When I run the code in `emacs -q -nw`, then I get the error above. # Answer > 2 votes The doc string of `match-string` says: > (match-string NUM &optional STRING) > > This function does not change global state, including the match data. > > Return string of text matched by last search. NUM specifies which parenthesized expression in the last regexp. Value is nil if NUMth pair didn’t match, or there were less than NUM pairs. Zero means the entire text matched by the whole regexp or whole string. **STRING should be given if the last search was by ‘string-match’ on STRING.** If STRING is nil, the current buffer should be the same buffer the search/match was performed in. (emphasis added) IOW, when you are doing `match-string` after doing `string-match`, *you have to pass the string that you searched in as an argument to `match-string`*. `match-string` only knows about beginning and ending indices: if you don't give it the string argument, it assumes that you did a search in the buffer and gets a substring out of the buffer (probably somewhere near the beginning). It does not know that you did a `string-match` unless you tell it by passing to it the string argument. As @Stefan points out in the comments, it is important to take precautions not to trash the match data (trashing the match data is easy to do: basically, most emacs functions do not try to preserve the match data, so you need to save the various matches you are interested in as soon as possible after the match data are calculated and before any such functions are called - as Stefan points out, typing an expression into the `*scratch*` buffer and evaluating it, and then typing another expression and evaluating it is going to run a lot of emacs code between - and during - the code evaluations that might very well trash the match data produced in the first evaluation). And, as in the accepted answer to match-data fails to consider only last search with string-match and persists across sessions, you should test the match before using match-data: > match-string is stateful and "can" persist on consecutive searches even if your next string-match search returns nil. The following should work: ``` (when (string-match "\\([0-9]?[0-9]\\):\\([0-9]\\{2\\}\\)" "09:20") ;; <-- skip when string fails to match (setq group-zero (match-string 0 "09:20") group-one (match-string 1 "09:20") group-two (match-string 2 "09:20"))) "20" ;;<--- the value of the "when" is the value that the last setq returned since the string matched and all the setq's wer executed. ;; now that they are saved, we can examine them at leisure group-zero "09.20" group-one "09" group-two "20" ``` --- Tags: regular-expressions, interactive ---
thread-54370
https://emacs.stackexchange.com/questions/54370
Regular expression gives different results as variable and as literal
2019-12-14T15:43:44.460
# Question Title: Regular expression gives different results as variable and as literal In the Emacs `*scratch*` buffer, I get different results when I use the same regular expression as a variable compared to a literal: ``` (setq splitter-string "9:20") "9:20" (string-match "[0-9]?[0-9]:[0-9][0-9]" splitter-string) 0 (defvar org-clock-split-absolute-time-regexp "[0-9]?[0-9]:[0-9][0-9]" "Regular expression to match an absolute time to split at.") org-clock-split-absolute-time-regexp (string-match org-clock-split-absolute-time-regexp splitter-string) nil ``` What is the difference between a variable and a literal for regular expressions? **Update**: The problem stems from the inability to overwrite a variable defined with `defvar`, as below in the scratch buffer: ``` (defvar pattern "some pattern" "Some regular expression") pattern pattern "some pattern" (defvar pattern "[a-z]*" "Some regular expression") pattern pattern "some pattern" (string-match "[a-z]*" "abcdefg") 0 (string-match pattern "abcdefg") nil ``` I would not do this in final code, but may do it in the scratch buffer during development. The problem is about `defvar`, and a duplicate of this question, and not about regular expressions (I knew about the different syntaxes with `re-builder` and suspected it was about that). # Answer That's not what I see. They both return 0, for me, starting with `emacs -Q` (no init file). If you haven't already, try starting Emacs with `emacs -Q`. If that works then bisect your init file to find the problem. --- **Updated after your update** (which really poses a separate question -- you should pose only one question per post). * You can evaluate a `defvar` by putting your cursor on it somewhere and using `C-M-x`. * The reason that `defvar` doesn't do anything just by evaluating it normally, if the variable already has a value, is to allow you to use a `defvar` in your own code (e.g. init file) to override any `defvar` for the same variable that might get evaluated when loading some library after you have set the variable value. See the Emacs manual, node Lisp Eval. It describes the behavior this way: > The `eval-defun` command is bound to **`C-M-x`** in Emacs Lisp mode. It evaluates the top-level Lisp expression containing or following point, and prints the value in the echo area. In this context, a top-level expression is referred to as a “defun”, but it need not be an actual `defun` (function definition). In particular, this command treats `defvar` expressions specially. > > *Normally, evaluating a `defvar` expression **does nothing if the variable it defines already has a value**. **But this command unconditionally resets** the variable to the initial value specified by the `defvar`; this is convenient for debugging Emacs Lisp programs.* `defcustom` and `defface` expressions are treated similarly. Note that the other commands documented in this section do not have this special feature. > 1 votes --- Tags: regular-expressions, variables ---
thread-54368
https://emacs.stackexchange.com/questions/54368
How can I turn off magit's warning that a commit message has a second line that is non empty?
2019-12-14T15:28:10.910
# Question Title: How can I turn off magit's warning that a commit message has a second line that is non empty? Every time I have a second line in a commit message, magit prompts/warns me when commiting... Is there a way I can turn this off warning? I've found the following in the docs https://magit.vc/manual/magit.html#Initiating-a-Commit: > Function: git-commit-check-style-conventions Check for violations of certain basic style conventions. For each violation ask the user if she wants to proceed anyway. This makes sure the summary line isn’t too long and that the second line is empty. Which is a function defined here: https://github.com/magit/magit/blob/4b97f23ace4132b3313a1bca73dcbbcd06bb4b9b/lisp/git-commit.el#L624 Any thoughts how I can override / disable it? # Answer > 10 votes You *can* disable it, but you really shouldn't. A near-universal<sup>1</sup> git convention is to use blank lines to separate paragraphs, including separating the commit summary from the extended description. This is recommended in the `man` page and online documentation for `git commit`: > The text up to the first blank line in a commit message is treated as the commit title, and that title is used throughout Git. One place you'll notice this is `magit-log-current` (and the other magit log functions), where all lines up to the first blank line will be included (just like in `git log --oneline`). But note that other tools, including GitHub, do not include the additional lines in the summary. Therefore, limiting the summary to one line and leaving the second line blank seems to be the best style. --- To answer your question, though, if you really want to turn off the warning, just remove `non-empty-second-line` from the `git-commit-style-convention-checks` list. ``` (setq git-commit-style-convention-checks (remove 'non-empty-second-line git-commit-style-convention-checks)) ``` This also works, but potentially clobbers other settings as well: ``` (setq git-commit-style-convention-checks nil) ``` --- <sup>1</sup> While I'm not going to go so far as to analyze every commit on GitHub, I'll note that every commit style I found by searching "git commit style" (on both Google and DuckDuckGo includes this recommendation (except for one that only talked about using emoji in the summary and didn't mention the description at all). --- Tags: magit ---
thread-54379
https://emacs.stackexchange.com/questions/54379
How to handle multiple kinds of errors with condition-case?
2019-12-14T23:39:45.627
# Question Title: How to handle multiple kinds of errors with condition-case? With `condition-case`, is there a way to handle multiple kinds of errors? Currently I have `user-error` and `error` both being handled. Is there a way to de-duplicate these checks to handle any kind of error? ``` (condition-case err (some-code) (user-error (message "%s" (error-message-string err))) (error (message "%s" (error-message-string err)))) ``` # Answer According to the manual `error` handles all kinds of errors. So, adapting your example, this is what you'd do to catch them all. ``` (condition-case err (some-code) (error (message "%s" (error-message-string err)))) ``` > 1 votes --- Tags: error-handling ---
thread-54384
https://emacs.stackexchange.com/questions/54384
How can I show a quick menu for the user from Emacs Lisp?
2019-12-15T08:30:56.550
# Question Title: How can I show a quick menu for the user from Emacs Lisp? I found EasyMenu and and I tried the example: ``` (easy-menu-define my-menu global-map "My own menu" '("My Stuff" ["One entry" my-function t] ("Sub Menu" ["My subentry" my-obscure-function t]))) ``` But when I try to show the menu with `M-x my-menu` then it says: ``` my-menu must be bound to an event with parameters ``` So it apparently should be added to a keymap, so the user can activate it. But how can I show this menu from elisp? (like `(my-menu)` or something) So how can I programmatically show a simple menu like the above? **I prefer built in solutions, so without external packages like Hydra and similiar.** # Answer > 3 votes A quick text menu can be shown with `tmm-prompt`: ``` (tmm-prompt my-menu) ``` A graphical menu can also be shown: ``` (x-popup-menu (list '(200 200) (selected-window)) my-menu) ``` --- Tags: menus ---
thread-50485
https://emacs.stackexchange.com/questions/50485
Copy or paste between terminal emacs 26 and Mac apps
2019-05-13T13:24:30.290
# Question Title: Copy or paste between terminal emacs 26 and Mac apps I am using terminal emacs a lot, and the method from Copy text from Emacs to OS X clipboard works for a long time. But after upgrading to Emacs 26, if I kill a string like "你好" from emacs, and paste here in the browser, it will be "‰Ω†Â•Ω". If I kill a string here "你好" and paste it in terminal emacs, it will be "??". In short, the encoding is problematic. My emacs version is: GNU Emacs 26.2 (build 1, x86\_64-apple-darwin18.2.0, NS appkit-1671.20 Version 10.14.3 (Build 18D109)) of 2019-04-13 ``` (describe-coding-system) Coding system for saving this buffer: Not set locally, use the default. Default coding system (for new files): U -- utf-8 (alias: mule-utf-8 cp65001) Coding system for keyboard input: U -- utf-8-unix (alias: mule-utf-8-unix cp65001-unix) Coding system for terminal output: U -- utf-8-unix (alias: mule-utf-8-unix cp65001-unix) Coding system for inter-client cut and paste: U -- utf-8-unix (alias: mule-utf-8-unix cp65001-unix) Defaults for subprocess I/O: decoding: U -- utf-8-unix (alias: mule-utf-8-unix cp65001-unix) encoding: U -- utf-8-unix (alias: mule-utf-8-unix cp65001-unix) Priority order for recognizing coding systems when reading files: 1. utf-8 (alias: mule-utf-8 cp65001) 2. iso-2022-7bit 3. iso-latin-1 (alias: iso-8859-1 latin-1) 4. iso-2022-7bit-lock (alias: iso-2022-int-1) 5. iso-2022-8bit-ss2 6. emacs-mule 7. raw-text 8. iso-2022-jp (alias: junet) 9. in-is13194-devanagari (alias: devanagari) 10. chinese-iso-8bit (alias: cn-gb-2312 euc-china euc-cn cn-gb gb2312) 11. utf-8-auto 12. utf-8-with-signature 13. utf-16 14. utf-16be-with-signature (alias: utf-16-be) 15. utf-16le-with-signature (alias: utf-16-le) 16. utf-16be 17. utf-16le 18. japanese-shift-jis (alias: shift_jis sjis) 19. chinese-big5 (alias: big5 cn-big5 cp950) 20. undecided ``` Any hint? # Answer > 1 votes The solution is simple. 1. for fish-shell user ``` set -x LC_ALL "en_US.UTF-8" ``` 2. for bash/zsh shell user ``` export LC_ALL=en_US.UTF-8 ``` --- Tags: osx, terminal-emacs, character-encoding, emacs26 ---
thread-54390
https://emacs.stackexchange.com/questions/54390
In org mode, how can I hide body text but show drawer contents?
2019-12-15T16:05:12.287
# Question Title: In org mode, how can I hide body text but show drawer contents? Using spacemacs I would like to be able to display an org mode document such that: 1. all headings are visible 2. all drawers are open and their contents visible 3. all other body text is invisible It would also be acceptable if instead point 2. read "all comments (lines starting # or delimited by #+BEGIN\_COMMENT / #+END\_COMMENT) are visible" # Answer > 1 votes You can add overlays with the `invisible` property to everything except headlines and drawers (see overlay properties section of the manual). In the code below I use the org element api to traverse the org file and add overlays with the `invisible` property to everything except headlines and drawers. I put the relevant code in the function `+org/toggle-hide-all-except-headlines-and-drawers` (aptly named if a bit verbose) so that you could toggle this because I figure you'll likely want to go back and forth. One caveat is that when you fold a heading the folding looks scrunched up (there's no separation between headings). But I think this is a separate problem having to do with how org implements overlays. In any case, in my tests everything was hidden except headlines and properties. ``` (defvar +org-hide-all-except-headlines-and-drawers nil) (defun +org/toggle-hide-all-except-headlines-and-drawers (&optional reveal) (interactive) (setq +org-hide-all-except-headlines-and-drawers (not +org-hide-all-except-headlines-and-drawers)) (org-element-map (org-element-parse-buffer) (cl-remove-if (lambda (it) (member it '(headline property-drawer drawer section node-property))) org-element-all-elements) (lambda (elt) (let ((beg (org-element-property :begin elt)) (end (org-element-property :end elt))) (if +org-hide-all-except-headlines-and-drawers (overlay-put (make-overlay beg end) 'invisible t) (remove-overlays beg end 'invisible t)))))) ``` --- Tags: org-mode, spacemacs ---
thread-54294
https://emacs.stackexchange.com/questions/54294
Insert Org or Markdown code blocks with Babel in org-mode?
2019-12-10T17:22:02.440
# Question Title: Insert Org or Markdown code blocks with Babel in org-mode? In org-mode, if I do something like this: ``` #+begin_src org ## What does this PR do? - Updates the Dockerfile to make the `dev` service connect to a shared network at startup - Registers the `create_docker_network` and `remove_docker_network` `gogo` commands - Advertises new `gogo` networking commands - Bumps `gobase` version in the service's Jenkinsfile - Provides a script to create the network at build time - Adds a Jenkins step to run the script to create the network ## How to test *Remember you have to download the latest `gogo` version!* ### To watch it fail 1. Run `gogo start` * It will fail because most likely the network doesn't exist #+end_src ``` The result gets rendered like this: What can I do to make it render correctly as code? # Answer > 1 votes The problem is that ``` * It will fail because most likely the network doesn't exist ``` is interpreted as Org mode heading. That also breaks the source block. Just add a comma before those lines as in: ``` ,* It will fail because most likely the network doesn't exist ``` The comma at the beginning of a line in a source block acts as an escape sequence escaping Org syntax. Note that the line ``` *Remember you have to download the latest `gogo` version!* ``` does not match the syntax of an Org heading because of the missing space behind the leading star (sequence). Therefore, you do not need to escape that line. # Answer > 0 votes As Tobias said, the "It will fail because most likely..." part is the conflicting part. I tried prepending a comma but that resulted in the literal comma exported in the code block so, instead of using that, I changed the `*` for a `-` which yield the same result in most Markdown implementations and avoided this issue. I'll leave the question open in case someone finds a more satisfying solution to this issue. --- Tags: org-mode, spacemacs, org-babel ---
thread-54376
https://emacs.stackexchange.com/questions/54376
How to make gdb mode send proper filename to gdbserver? Running gdb from pure terminal works
2019-12-14T17:54:13.910
# Question Title: How to make gdb mode send proper filename to gdbserver? Running gdb from pure terminal works I am trying to debug an application on a remote environment. Ofcourse running Tramp over gdb works as in https://www.gnu.org/software/emacs/manual/html\_node/tramp/Remote-processes.html, but you miss out on source code linking. The frame/stacktrace buffer for example... now you can't click on a frame and go to source code on host machine. \[Host\] (Source code) -\> compiled binary -\> scp binary to remote -\> Debug On Remote. So I tried making gdbserver work. Firstly I made both versions of gdb/gdbserver on both host and remote machine same. 8.3 latest. Now running from terminal: In Terminal Remote: ``` $ cd /path/to/folder/ $ gdbserver --multi :44421 ``` `gdbserver` starts listening. Also tried entire exercise with `gdbserver --no-shell-on-startup --multi :44421` but it results in same thing. In Host machine TERMINAL: ``` $ gdb /file/to/executable gdb> target extended-remote <remote>:44421 gdb> set remote exec-file ./executable gdb> set args -c config.xml gdb> r ``` ^This works as expected. Or atleast it starts and i am able to get debug output. BUT In emacs GBD mode it doesn't work: In HOST machine. EMACS: ``` M-x gdb RET gdb -i=mi /file/to/executable gdb> target extended-remote <remote>:44421 gdb> set remote exec-file ./executable gdb> set args -c config.xml gdb> r ``` ^This doesn't work. I get output: In Remote Machine: ``` $ gdbserver... ... /bin/sh: /path/to/executable/folder/executable: No such file or directory ... ``` How do I solve this? * Emacs: 26.3 * GDB: 8.3 * Both machines are centos 7. * Using spacemacs develop branch as emacs frontend. Since I do frequently copy executable from host to remote, I do want gdbserver to simply run forever, hence the `--multi <port>` use case. And I can do `k` from gdb when i need to copy the binary over. # Answer > 1 votes I made this work by passing argument when launching gdb. ``` M-x gdb RET gdb -i=mi -ex "target extended-remote <remote>:44421" -ex "set remote exec-file ./executable" --args "-c config.xml" ``` Then in gdb launched i also had to set `set non-stop off`. I ran `gdbserver` as `gdbserver --multi :44421` in the folder on remote where executable was. It worked. But the emacs bug exists though. --- Tags: debugging, tramp, gdb ---
thread-54402
https://emacs.stackexchange.com/questions/54402
How to impliment a “with-undo-collapse” macro using change group feature?
2019-12-16T07:46:19.063
# Question Title: How to impliment a “with-undo-collapse” macro using change group feature? Recently emacs has a feature `undo-amalgamate-change-group` which can be used to merge multiple actions into a single undo step. How can this be used to make a `with-undo-collapse` macro similar to this one, which: * Handles errors. * Forwards the result of the body of the macro. This is a basic version, however I'm not sure how it should work when there is an error in the body of the code which runs in this block. ``` (defmacro with-undo-collapse (&rest body) "Execute body, then collapse any resulting undo boundaries." (declare (indent 0)) `(let ((cg (prepare-change-group))) (progn ,@body) (undo-amalgamate-change-group cg))) ``` # Answer Edit: emacs 29 supports `(with-undo-amalgamate &rest BODY)` which is very close to the answer below. --- The command `atomic-change-group` fits all the requirements except for collapsing the undo history. This is `atomic-change-group` with a one line change, adding `undo-amalgamate-change-group`. ``` (defmacro with-undo-collapse (&rest body) "Like `progn' but perform BODY with undo collapsed." (declare (indent 0) (debug t)) (let ((handle (make-symbol "--change-group-handle--")) (success (make-symbol "--change-group-success--"))) `(let ((,handle (prepare-change-group)) ;; Don't truncate any undo data in the middle of this. (undo-outer-limit nil) (undo-limit most-positive-fixnum) (undo-strong-limit most-positive-fixnum) (,success nil)) (unwind-protect (progn (activate-change-group ,handle) (prog1 ,(macroexp-progn body) (setq ,success t))) (if ,success (progn (accept-change-group ,handle) (undo-amalgamate-change-group ,handle)) (cancel-change-group ,handle)))))) ``` > 2 votes # Answer I'm not entirely sure, but you are possibly trying to reimplement the `atomic-change-group` macro? ``` atomic-change-group is a Lisp macro in `subr.el'. (atomic-change-group &rest BODY) Perform BODY as an atomic change group. This means that if BODY exits abnormally, all of its changes to the current buffer are undone. This works regardless of whether undo is enabled in the buffer. This mechanism is transparent to ordinary use of undo; if undo is enabled in the buffer and BODY succeeds, the user can undo the change normally. ``` --- > I'm not sure how it should work when there is an error in the body of the code which runs in this block. I think you're looking for: ``` unwind-protect is a special form in `C source code'. (unwind-protect BODYFORM UNWINDFORMS...) Do BODYFORM, protecting with UNWINDFORMS. If BODYFORM completes normally, its value is returned after executing the UNWINDFORMS. If BODYFORM exits nonlocally, the UNWINDFORMS are executed anyway. ``` > 0 votes --- Tags: undo ---
thread-7558
https://emacs.stackexchange.com/questions/7558
How to collapse undo history?
2015-01-19T22:38:21.023
# Question Title: How to collapse undo history? I'm working on an Emacs mode that lets you control Emacs with speech recognition. One of the problems I've ran into is that the way Emacs handles undo doesn't match how you would expect it to work when controlling by voice. When the user speaks several words and then pauses, that's called an 'utterance.' An utterance may consist of multiple commands for Emacs to execute. It's often the case that the recognizer recognizes one or more commands within an utterance incorrectly. At that point I want to be able to say "undo" and have Emacs undo *all actions* done by the utterance, not just the last action within the utterance. In other words, I want Emacs to treat an utterance as a single command as far as undo is concerned, even when an utterance consists of multiple commands. I'd also like point to go back to exactly where it was before the utterance, I've noticed normal Emacs undo doesn't do this. I have setup Emacs to get callbacks at the beginning and end of each utterance, so I can detect the situation, I just need to figure out what to have Emacs do. Ideally I'd call something like `(undo-start-collapsing)` and then `(undo-stop-collapsing)` and anything done inbetween would be magically collapsed into one record. I did some trawling through the documentation and found `undo-boundary`, but it's the opposite of what I want -- I need to collapse all the actions within an utterance into one undo record, not split them up. I can use `undo-boundary` between utterances to make sure insertions are considered separate (Emacs by default considers consecutive insert actions to be one action up to some limit), but that's it. Other complications: * My speech recognition daemon sends some commands to Emacs by simulating X11 keypresses and sends some via `emacsclient -e` so, if there were say an `(undo-collapse &rest ACTIONS)` there's no central place I can wrap. * I use `undo-tree`, not sure if this makes things more complicated. Ideally a solution would work with `undo-tree` and Emacs' normal undo behavior. * What if one of the commands within an utterance is "undo" or "redo"? I'm thinking I could change the callback logic to always send these to Emacs as distinct utterances to keep things simpler, then it should be handled just like it would if I were using the keyboard. * Stretch goal: An utterance may contain a command that switches the currently active window or buffer. In this case it's fine to have to say "undo" once separately in each buffer, I don't need it to be that fancy. But all the commands in a single buffer should still be grouped, so if I say "do-x do-y do-z switch-buffer do-a do-b do-c" then x,y,z should be one undo record in the original buffer and a,b,c should be one record in the switched to buffer. Is there an easy way to do this? AFAICT there is nothing built-in but Emacs is vast and deep... Update: I ended up using jhc's solution below with a little extra code. In the global `before-change-hook` I check if the buffer being changed is in a global list of buffers modified this utterance, if not it goes into the list and `undo-collapse-begin` is called. Then at the end of the utterance I iterate all the buffers in the list and call `undo-collapse-end`. Code below (md- added before function names for namespacing purposes): ``` (defvar md-utterance-changed-buffers nil) (defvar-local md-collapse-undo-marker nil) (defun md-undo-collapse-begin (marker) "Mark the beginning of a collapsible undo block. This must be followed with a call to undo-collapse-end with a marker eq to this one. Taken from jch's stackoverflow answer here: http://emacs.stackexchange.com/a/7560/2301 " (push marker buffer-undo-list)) (defun md-undo-collapse-end (marker) "Collapse undo history until a matching marker. Taken from jch's stackoverflow answer here: http://emacs.stackexchange.com/a/7560/2301" (cond ((eq (car buffer-undo-list) marker) (setq buffer-undo-list (cdr buffer-undo-list))) (t (let ((l buffer-undo-list)) (while (not (eq (cadr l) marker)) (cond ((null (cdr l)) (error "md-undo-collapse-end with no matching marker")) ((eq (cadr l) nil) (setf (cdr l) (cddr l))) (t (setq l (cdr l))))) ;; remove the marker (setf (cdr l) (cddr l)))))) (defmacro md-with-undo-collapse (&rest body) "Execute body, then collapse any resulting undo boundaries. Taken from jch's stackoverflow answer here: http://emacs.stackexchange.com/a/7560/2301" (declare (indent 0)) (let ((marker (list 'apply 'identity nil)) ; build a fresh list (buffer-var (make-symbol "buffer"))) `(let ((,buffer-var (current-buffer))) (unwind-protect (progn (md-undo-collapse-begin ',marker) ,@body) (with-current-buffer ,buffer-var (md-undo-collapse-end ',marker)))))) (defun md-check-undo-before-change (beg end) "When a modification is detected, we push the current buffer onto a list of buffers modified this utterance." (unless (or ;; undo itself causes buffer modifications, we ;; don't want to trigger on those undo-in-progress ;; we only collapse utterances, not general actions (not md-in-utterance) ;; ignore undo disabled buffers (eq buffer-undo-list t) ;; ignore read only buffers buffer-read-only ;; ignore buffers we already marked (memq (current-buffer) md-utterance-changed-buffers) ;; ignore buffers that have been killed (not (buffer-name))) (push (current-buffer) md-utterance-changed-buffers) (setq md-collapse-undo-marker (list 'apply 'identity nil)) (undo-boundary) (md-undo-collapse-begin md-collapse-undo-marker))) (defun md-pre-utterance-undo-setup () (setq md-utterance-changed-buffers nil) (setq md-collapse-undo-marker nil)) (defun md-post-utterance-collapse-undo () (unwind-protect (dolist (i md-utterance-changed-buffers) ;; killed buffers have a name of nil, no point ;; in undoing those (when (buffer-name i) (with-current-buffer i (condition-case nil (md-undo-collapse-end md-collapse-undo-marker) (error (message "Couldn't undo in buffer %S" i)))))) (setq md-utterance-changed-buffers nil) (setq md-collapse-undo-marker nil))) (defun md-force-collapse-undo () "Forces undo history to collapse, we invoke when the user is trying to do an undo command so the undo itself is not collapsed." (when (memq (current-buffer) md-utterance-changed-buffers) (md-undo-collapse-end md-collapse-undo-marker) (setq md-utterance-changed-buffers (delq (current-buffer) md-utterance-changed-buffers)))) (defun md-resume-collapse-after-undo () "After the 'undo' part of the utterance has passed, we still want to collapse anything that comes after." (when md-in-utterance (md-check-undo-before-change nil nil))) (defun md-enable-utterance-undo () (setq md-utterance-changed-buffers nil) (when (featurep 'undo-tree) (advice-add #'md-force-collapse-undo :before #'undo-tree-undo) (advice-add #'md-resume-collapse-after-undo :after #'undo-tree-undo) (advice-add #'md-force-collapse-undo :before #'undo-tree-redo) (advice-add #'md-resume-collapse-after-undo :after #'undo-tree-redo)) (advice-add #'md-force-collapse-undo :before #'undo) (advice-add #'md-resume-collapse-after-undo :after #'undo) (add-hook 'before-change-functions #'md-check-undo-before-change) (add-hook 'md-start-utterance-hooks #'md-pre-utterance-undo-setup) (add-hook 'md-end-utterance-hooks #'md-post-utterance-collapse-undo)) (defun md-disable-utterance-undo () ;;(md-force-collapse-undo) (when (featurep 'undo-tree) (advice-remove #'md-force-collapse-undo :before #'undo-tree-undo) (advice-remove #'md-resume-collapse-after-undo :after #'undo-tree-undo) (advice-remove #'md-force-collapse-undo :before #'undo-tree-redo) (advice-remove #'md-resume-collapse-after-undo :after #'undo-tree-redo)) (advice-remove #'md-force-collapse-undo :before #'undo) (advice-remove #'md-resume-collapse-after-undo :after #'undo) (remove-hook 'before-change-functions #'md-check-undo-before-change) (remove-hook 'md-start-utterance-hooks #'md-pre-utterance-undo-setup) (remove-hook 'md-end-utterance-hooks #'md-post-utterance-collapse-undo)) (md-enable-utterance-undo) ;; (md-disable-utterance-undo) ``` # Answer > 5 votes Edit: emacs-29.1 adds a `with-undo-amagamate` macro see commit. --- Here is an `with-undo-amalgamate` macro that uses Emacs-26 change-groups feature. This is `atomic-change-group` with the following changes: * Added `undo-amalgamate-change-group`. * Removed call to `cancel-change-group` on failure. It has the advantages that: * It doesn't need to manipulate the undo data directly. * It ensures undo data isn't truncated. ``` (defmacro with-undo-amalgamate (&rest body) "Like `progn' but perform BODY with amalgamated undo barriers. This allows multiple operations to be undone in a single step. When undo is disabled this behaves like `progn'." (declare (indent 0) (debug t)) (let ((handle (make-symbol "--change-group-handle--"))) `(let ((,handle (prepare-change-group)) ;; Don't truncate any undo data in the middle of this, ;; otherwise Emacs might truncate part of the resulting ;; undo step: we want to mimic the behavior we'd get if the ;; undo-boundaries were never added in the first place. (undo-outer-limit nil) (undo-limit most-positive-fixnum) (undo-strong-limit most-positive-fixnum)) (unwind-protect (progn (activate-change-group ,handle) ,@body) (progn (accept-change-group ,handle) (undo-amalgamate-change-group ,handle)))))) ``` # Answer > 15 votes Interestingly enough, there appears to be no built-in function to do that. The following code works by inserting a unique marker on the `buffer-undo-list` at the beginning of a collapsible block, and removing all boundaries (`nil` elements) at the end of a block, then removing the marker. In case something goes wrong, the marker is of the form `(apply identity nil)` to ensure that it does nothing if it remains on the undo list. Ideally, you should use the `with-undo-collapse` macro, not the underlying functions. Since you mentioned that you cannot do the wrapping, make sure that you pass to the low-level functions markers that are `eq`, not just `equal`. If the invoked code switches buffers, you must ensure that `undo-collapse-end` is called in the same buffer as `undo-collapse-begin`. In that case, only the undo entries in the initial buffer will be collapsed. ``` (defun undo-collapse-begin (marker) "Mark the beginning of a collapsible undo block. This must be followed with a call to undo-collapse-end with a marker eq to this one." (push marker buffer-undo-list)) (defun undo-collapse-end (marker) "Collapse undo history until a matching marker." (cond ((eq (car buffer-undo-list) marker) (setq buffer-undo-list (cdr buffer-undo-list))) (t (let ((l buffer-undo-list)) (while (not (eq (cadr l) marker)) (cond ((null (cdr l)) (error "undo-collapse-end with no matching marker")) ((null (cadr l)) (setf (cdr l) (cddr l))) (t (setq l (cdr l))))) ;; remove the marker (setf (cdr l) (cddr l)))))) (defmacro with-undo-collapse (&rest body) "Execute body, then collapse any resulting undo boundaries." (declare (indent 0)) (let ((marker (list 'apply 'identity nil)) ; build a fresh list (buffer-var (make-symbol "buffer"))) `(let ((,buffer-var (current-buffer))) (unwind-protect (progn (undo-collapse-begin ',marker) ,@body) (with-current-buffer ,buffer-var (undo-collapse-end ',marker)))))) ``` Here's an example of usage: ``` (defun test-no-collapse () (interactive) (insert "toto") (undo-boundary) (insert "titi")) (defun test-collapse () (interactive) (with-undo-collapse (insert "toto") (undo-boundary) (insert "titi"))) ``` # Answer > 3 votes Some changes to the undo machinery "recently" broke some hack `viper-mode` was using to do this kind of collapsing (for the curious, it's used in the following case: when you press `ESC` to finish an insertion/replacement/edition, Viper wants to collapse the whole change into a single undo step). To fix it cleanly, we introduced a new function `undo-amalgamate-change-group` (which corresponds more or less to your `undo-stop-collapsing`) and reuses the existing `prepare-change-group` to mark the beginning (i.e. corresponds more or less to your `undo-start-collapsing`). For reference, here's the corresponding new Viper code: ``` (viper-deflocalvar viper--undo-change-group-handle nil) (put 'viper--undo-change-group-handle 'permanent-local t) (defun viper-adjust-undo () (when viper--undo-change-group-handle (undo-amalgamate-change-group (prog1 viper--undo-change-group-handle (setq viper--undo-change-group-handle nil))))) (defun viper-set-complex-command-for-undo () (and (listp buffer-undo-list) (not viper--undo-change-group-handle) (setq viper--undo-change-group-handle (prepare-change-group)))) ``` This new function will appear in Emacs-26, so if you want to use it in the mean time, you can copy its definition (requires `cl-lib`): ``` (defun undo-amalgamate-change-group (handle) "Amalgamate changes in change-group since HANDLE. Remove all undo boundaries between the state of HANDLE and now. HANDLE is as returned by `prepare-change-group'." (dolist (elt handle) (with-current-buffer (car elt) (setq elt (cdr elt)) (when (consp buffer-undo-list) (let ((old-car (car-safe elt)) (old-cdr (cdr-safe elt))) (unwind-protect (progn ;; Temporarily truncate the undo log at ELT. (when (consp elt) (setcar elt t) (setcdr elt nil)) (when (or (null elt) ;The undo-log was empty. ;; `elt' is still in the log: normal case. (eq elt (last buffer-undo-list)) ;; `elt' is not in the log any more, but that's because ;; the log is "all new", so we should remove all ;; boundaries from it. (not (eq (last buffer-undo-list) (last old-cdr)))) (cl-callf (lambda (x) (delq nil x)) (if (car buffer-undo-list) buffer-undo-list ;; Preserve the undo-boundaries at either ends of the ;; change-groups. (cdr buffer-undo-list))))) ;; Reset the modified cons cell ELT to its original content. (when (consp elt) (setcar elt old-car) (setcdr elt old-cdr)))))))) ``` --- Tags: emacsclient, undo, undo-tree-mode ---
thread-54400
https://emacs.stackexchange.com/questions/54400
Export a docx file to org using pandoc but without the property drawers
2019-12-16T06:45:31.647
# Question Title: Export a docx file to org using pandoc but without the property drawers If I export a docx file to org using Pandoc as follows ``` pandoc -s test.docx -o test.org ``` I get a nice org file with markup. However, I also get unwanted properties with each heading in the file, generated from the headings. For example: ``` * Heading One :PROPERTIES: :CUSTOM_ID: heading-one :END: ``` I don't want all these heading properties. Can I export without these drawers? I found a similar article but this did not help me: in org-mode, a function to delete all properties drawers? Otherwise, I would like to be able to strip the exported org file of all of its property drawers. Is this possible? # Answer The drawers are added only if a header has additional attributes. One can use a simple Lua filter to remove all attributes from headers in pandoc's internal document format: ``` function Header (header) return pandoc.Header(header.level, header.content, pandoc.Attr()) end ``` Write the above to a file named `remove-header-attr.lua` and call pandoc with the additional parameter `--lua-filter=remove-header-attr.lua`. > 9 votes # Answer I think this is best solved on the level of pandoc conversion, with a pandoc filter. Create a file, say `noattrs-filter.hs` containing: ``` import Text.Pandoc.JSON main = toJSONFilter noAttrs noAttrs :: Block -> Block noAttrs (Header n _ i) = Header n nullAttr i noAttrs (Div _ b) = Div nullAttr b noAttrs b = b ``` Compile the file with ghc: ``` ghc noattrs-filter.hs ``` and run your conversion with: ``` pandoc -s --filter ./noattrs-filter test.docx -o test.org ``` In order to compile the pandoc filter, you need to have the relevant libraries. For instance, on Ubuntu, you'd need the `libghc-pandoc-types-dev` package (`sudo apt-get install libghc-pandoc-types-dev`). More generally, you could also try installing via `cabal` (`cabal install pandoc`). ### To understand the haskell filter The relevant hackage documentation is here and here. Adding comments to the code (starting with `--` and hopefully useful for somebody not used to haskell): ``` import Text.Pandoc.JSON main = toJSONFilter noAttrs -- Type signature (convert a block into a slightly modified block) noAttrs :: Block -> Block -- Header constructors have the form: -- Header Int Attr [Inline] -- _ means we ignore the attribute (Attr), since we're discarding it, anyway -- nullAttr is, as the name suggests, an attribute containing no info noAttrs (Header n _ i) = Header n nullAttr i -- Div constructors have the form: -- Div Attr [Block] noAttrs (Div _ b) = Div nullAttr b -- for completeness could also deal with 'CodeBlock's, which can also -- have an attribute — left as an exercise for the reader. -- -- we need a fallthrough noAttrs b = b ``` (This is based on my own answer to a relatively similar question here.) > 4 votes --- Tags: org-mode, pandoc ---
thread-54406
https://emacs.stackexchange.com/questions/54406
ERC, opening query messages in the same frame
2019-12-16T14:45:38.757
# Question Title: ERC, opening query messages in the same frame I use to have diferent frames for diferent tasks... I'd like to get new private message windows open in the same frame that the rest of the ERC stuff, not in the current focused frame. I'm searching for a long time, and I can't find any way to get this... Any idea? # Answer > 0 votes Does this work? ``` (defun my-major-mode-frame-p (mode frame) "Return non-nil if FRAME displays any buffer in major mode MODE." (catch 'window (walk-windows (lambda (w) (and (window-live-p w) (eq mode (buffer-local-value 'major-mode (window-buffer w))) (throw 'window w))) 'nomini frame))) ;; Always display ERC buffers in the same frame. (let ((ercframep (apply-partially #'my-major-mode-frame-p 'erc-mode))) (add-to-list 'display-buffer-alist (cons (lambda (buffer alist) (with-current-buffer buffer (derived-mode-p 'erc-mode))) (cons #'display-buffer-use-some-frame `((inhibit-switch-frame . nil) (inhibit-same-window . nil) (frame-predicate . ,ercframep)))))) ``` --- Tags: frames, erc ---
thread-54421
https://emacs.stackexchange.com/questions/54421
How can I link the source code .org file when exporting it?
2019-12-17T12:34:13.527
# Question Title: How can I link the source code .org file when exporting it? I have an .org file in which I want to insert the source code that generated the web page when is exported to HTML, this is, the .org file itself, but when I do it's changed to the .html file. How can I achieve this? This is the code of the link: ``` [[./documentation.org][Download .org source file]] ``` # Answer > 1 votes I found the solution in the org-mode manual: Links in HTML export, I only had to add to my init.el file the following sentence ``` (setq org-html-link-org-files-as-html nil) ``` --- Tags: org-mode, org-export ---
thread-42032
https://emacs.stackexchange.com/questions/42032
View command does not open pdf while in AUCTeX mode
2018-06-14T07:54:31.893
# Question Title: View command does not open pdf while in AUCTeX mode Sometimes, after havin applied latex to my .tex file, instead of executing ``` okular --unique my.pdf ``` emacs tried to execute ``` okular --unique my.pdf#src:332#("/folderToMyTex/my.tex" 0 61 (org-attr nil)) ``` and the pdf is not opened. What is the reason for this and how to prevent it? # Answer The default configuration for Okular looks like: ``` ("Okular" ("okular --unique %o" (mode-io-correlate "#src:%n%a")) "okular") ``` What it's trying to do for you is to open the pdf at the location corresponding to your current point in the tex file. If you wanted Emacs to simply execute `okular --unique my.pdf`, and only care to use Okular, then doing something like: ``` (setq TeX-view-program-list '("okular" "okular --unique %o")) ``` should work as a better workaround, but doesn't solve the root problem of the `%a` not expanding appropriately. > 1 votes # Answer It seems to be a bug. When opening a teX-file from within an org-file, the command `C-c-v`, to open the corresponding pdf, does not work. Closing the teX-file which was opened from within the org-file and re-opening it from dired allows to open the pdf file as usual. > 0 votes --- Tags: latex, auctex, pdf ---
thread-54308
https://emacs.stackexchange.com/questions/54308
bad signature "dash-2.12.0.tar.sig"
2019-12-11T06:03:25.570
# Question Title: bad signature "dash-2.12.0.tar.sig" I am getting the following error while startup ``` Failed to verify signature dash-2.12.0.tar.sig: No public key for 066DAFCB81E42C40 created at 2019-09-21T23:24:49+0530 using RSA Command output: gpg: WARNING: unsafe permissions on homedir `c:/Users/sreekumar.14CPU0014/AppData/Roaming/.emacs.d/elpa/gnupg' gpg: Signature made Sat Sep 21 23:24:49 2019 IST using RSA key ID 81E42C40 gpg: Can't check signature: public key not found ``` I don't know what is the reason and how to correct it? **Updated part of init file** ``` (require 'package) (add-to-list 'package-archives '("melpa-stable" . "https://stable.melpa.org/packages/") t) (add-to-list 'package-archives '("org" . "http://orgmode.org/elpa/") t) (add-to-list 'package-archives '("melpa" . "http://melpa.milkbox.net/packages/") t) ) ``` # Answer This seems to be related to the GPG key update for the ELPA archive: new packages are signed with the new key. # Solution 1 Download the package `gnu-elpa-keyring-update`. This will install the public key for `066DAFCB81E42C40`, which you are missing. # Solution 2 Upgrade to at least Emacs 26.3, which comes with the new GPG key. > 1 votes --- Tags: init-file ---
thread-37083
https://emacs.stackexchange.com/questions/37083
Autocompletion with tide or tern
2017-11-25T05:02:36.460
# Question Title: Autocompletion with tide or tern Autocompletion doesn't work with tide or Tern, I have to `M-x company-complete-common`. I would like for it to keep suggesting with a dropdown menu as I type, but I can't manage to. It works just fine with elpy and go-mode. I am using emacs 25.3.1 and I have these init lines regarding to js2-mode with tern: ``` (require 'js2-mode) (add-to-list 'auto-mode-alist '("\\.js\\'" . js2-mode)) ;; Better imenu (add-hook 'js2-mode-hook #'js2-imenu-extras-mode) (require 'js2-refactor) (require 'xref-js2) (add-hook 'js2-mode-hook #'js2-refactor-mode) (js2r-add-keybindings-with-prefix "C-c C-r") (define-key js2-mode-map (kbd "C-k") #'js2r-kill) ;; js-mode (which js2 is based on) binds "M-." which conflicts with xref, so ;; unbind it. (define-key js-mode-map (kbd "M-.") nil) (add-hook 'js2-mode-hook (lambda () (add-hook 'xref-backend-functions #'xref-js2-xref-backend nil t))) (require 'company) (require 'company-tern) (add-to-list 'company-backends 'company-tern) (add-hook 'js2-mode-hook (lambda () (tern-mode) (company-mode))) ;; Disable completion keybindings, as we use xref-js2 instead (define-key tern-mode-keymap (kbd "M-.") nil) (define-key tern-mode-keymap (kbd "M-,") nil) ``` regarding tide: ``` ;; tide (defun setup-tide-mode () (interactive) (tide-setup) (flycheck-mode +1) (setq flycheck-check-syntax-automatically '(save mode-enabled)) (eldoc-mode +1) (company-mode +1)) ;; aligns annotation to the right hand side (setq company-tooltip-align-annotations t) ;; formats the buffer before saving (add-hook 'before-save-hook 'tide-format-before-save) (add-hook 'typescript-mode-hook #'setup-tide-mode) ``` There is no error on init, and company-mode is enabled on these modes as expected, it just doesn't start suggesting as typing goes, instead only works for manual completion. # Answer I asked around and what solved it for me was setting `company-idle-delay` to 0! Previously it was `nil`, since it still worked on other modes I believe they don't follow a standard in processing this variable. I will add this to my init.el. edit: I went through my init file with a fine comb and I found why `company-idle-delay` was set to nil, it was a line that I put there a year or so ago. > 0 votes # Answer You should try with ``` (setq company-minimum-prefix-length 1) ``` Its default value is 3, so you have to type 3 chars before autocompletion pop-up appears. > 0 votes --- Tags: company-mode, auto-complete-mode, js2-mode ---
thread-54428
https://emacs.stackexchange.com/questions/54428
No org-babel-execute function for js!
2019-12-17T17:31:15.810
# Question Title: No org-babel-execute function for js! I'm using org-mode in Spacemacs and have this code block: ``` #+BEGIN_SRC js :var payload=access-token-payload let parsedPayload = JSON.parse(access-token-payload); return parsedPayload.access_token; #+END_SRC ``` Expected behavior: The code executes when I press `C-c` `C-c` Actual behavior: I get an error saying `No org-babel-execute function for js!`. This should be supported since org-babel is present. I code a lot of Node and Javascript applications so Node is in my path. # Answer You need to enable evaluation of js code. "Section 16.9" of org manual states: > By default, only 'emacs-lisp' is enabled for evaluation. To enable or disable other languages, customize the \`org-babel-load-languages' variable either through the Emacs customization interface, or by adding code to the init file as shown next: > In this example, evaluation is disabled for 'emacs-lisp', and enabled for 'R'. > ``` > (org-babel-do-load-languages > > ``` ``` 'org-babel-load-languages '((emacs-lisp . nil) (R . t))) ``` The provided example is not totally clear IMHO but that works. Another way to enable a language is to `require` the org babel module for the language, eg here: ``` M-: (require 'ob-js) ``` > 3 votes --- Tags: org-mode, spacemacs, org-babel ---
thread-54410
https://emacs.stackexchange.com/questions/54410
Use helm fuzzy search inside ranger inside spacemacs
2019-12-16T17:44:30.880
# Question Title: Use helm fuzzy search inside ranger inside spacemacs I am using ranger within spacemacs. One useful feature an explorer in windows (directory opus) I used has, is that by pressing keys it automatically starts to filter files with names corresponding to the keys. Is there a way to use helms fuzzy search as the default mode inside ranger windows, which then filters the files and directories according to the fuzzy input and to be able to toggle the mode off when desired? # Answer **EDIT START** It is more reliable to add advice to `ranger` and `deer` to try to ensure that `helm-find-files` is always enabled when ranger and dired are called (as opposed to adding a hook to `ranger-mode-hook` which is only called once the buffer is created). This should fix the problem of `helm-find-files` sometimes not being called immediately. ``` (with-eval-after-load 'ranger (advice-add #'deer :after #'+enable-helm-find-files) (advice-add #'ranger :after #'+enable-helm-find-files)) ``` **EDIT END** # activate from newly created ranger buffers `helm-find-files` might be what you're looking for. You can add it as a hook to `ranger-mode-hook`. I recommend naming it as I did so (1) you can easily remove it and (2) the hooks contents are more readable. ``` (defun +call-helm-find-files () (interactive) (call-interactively #'helm-find-files)) (add-hook 'ranger-mode-hook #'+call-helm-find-files) ``` # system to switch buffers Adding a hook to `ranger-mode-hook` does not answer your original question which was to enable fuzzy searching whenever you *switch* to a ranger buffer. Adding a hook will only work when `ranger-mode` is enabled. In practice, this means when you call ranger mode (`M-x ranger` or `M-x deer`) and ranger creates a brand new ranger buffer. However if you're switching from a buffer to an existing ranger buffer `ranger-mode-hook` will not be run and therefore `helm-find-files` will not be called. To call `helm-find-files` upon switching to a ranger buffer and to do it in a thorough, not as hacky way, I would recommend adapting some of the code from doom-emacs. Currently, there is no hook that runs after switching a buffer. This code sets up such a hook. I adapted it here. ## switch hook ``` (defvar +after-switch-to-buffer-hook nil "Hook run after switched to buffer.") ``` ## advice to `switch-to-buffer` ``` (defun +run-switch-buffer-hooks (orig-fn buffer-or-name &rest args) "Run ‘+after-switch-buffer-hook’." (if (or +inhibit-switch-buffer-hooks (eq (current-buffer) (get-buffer buffer-or-name)) (and (eq orig-fn #'switch-to-buffer) (car args))) (apply orig-fn buffer-or-name args) (let ((+inhibit-switch-buffer-hooks t)) (when-let (buffer (apply orig-fn buffer-or-name args)) (with-current-buffer (if (windowp buffer) (window-buffer buffer) buffer) (run-hooks '+after-switch-to-buffer-hook)) buffer)))) ``` ## advice to `previous-buffer` and `next-buffer` ``` (defun +run-prev-or-next-buffer-hooks (orig-fn &rest args) (if +inhibit-switch-buffer-hooks (apply orig-fn args) (let ((+inhibit-switch-buffer-hooks t)) (when-let (buffer (apply orig-fn args)) (with-current-buffer buffer (run-hooks '+after-switch-to-buffer-hook)) buffer)))) ``` ## inhibit switch-buffer hooks ``` (defvar +inhibit-switch-buffer-hooks nil "Letvar for inhibiting `+after-switch-buffer-hook'. Do not set this directly.") ``` ## toggle I checked this code and it worked for me. But my checking was not exhaustive so I wrote this function so you can enable and disable the switch buffer hook. ``` (defvar +enable-switch-buffer-hooks nil "Whether to enable switch buffer hooks.") (defun +toggle/switch-window-advice () (interactive) (setq +enable-switch-buffer-hooks (not +enable-switch-buffer-hooks)) (if +enable-switch-buffer-hooks (progn (message "disabled switch buffer hooks.") (advice-remove #'switch-to-buffer #'+run-switch-buffer-hooks) (advice-remove #'display-buffer #'+run-switch-buffer-hooks) (advice-remove #'switch-to-next-buffer #'+run-prev-or-next-buffer-hooks) (advice-remove #'switch-to-prev-buffer #'+run-prev-or-next-buffer-hooks)) (message "enabled switch buffer hooks") (advice-add #'switch-to-buffer :around #'+run-switch-buffer-hooks) (advice-add #'display-buffer :around #'+run-switch-buffer-hooks) (advice-add #'switch-to-next-buffer :around #'+run-prev-or-next-buffer-hooks) (advice-add #'switch-to-prev-buffer :around #'+run-prev-or-next-buffer-hooks))) ``` # disable all In case something goes wrong, you can disable everything with this. ``` (defun +disable-helm-find-files-all () "Disable the whole thing." (interactive) (setq +enable-switch-buffer-hooks nil) (+toggle/switch-window-advice) (remove-hook 'ranger-mode-hook #'+call-helm-find-files)) ``` # inhibited files This list is for the buffers you disable with `+toggle/find-file-inhibited`. ``` (defvar +inhibited-find-file-buffers nil "List of ranger buffers that shouldn’t do ‘helm-find-files’ on switch.") ``` # toggle inhibited This is the toggling functionality you requested. You can call this while on a ranger buffer and that buffer will not trigger `helm-find-files` when you switch to it. ``` (defun +toggle/find-file-inhibited () "Make current buffer not call ‘helm-find-files’." (interactive) (push (current-buffer) +inhibited-find-file-buffers)) ``` # activate `helm-find-files` when entering buffer This is the hook to actually call `helm-find-files`. It checks to see if the current buffer is a ranger buffer and whether its not a member of those in `+inhibited-find-file-buffers`. ``` (defun +enable-helm-find-files () "Enable ‘helm-find-files’ in ranger buffers." (when (and (eq major-mode 'ranger-mode) (not (member (current-buffer) +inhibited-find-file-buffers))) (call-interactively #'helm-find-files))) (add-hook '+after-switch-to-buffer-hook #'+enable-helm-find-files) ``` > 1 votes --- Tags: spacemacs, helm, fuzzy-search, ranger ---
thread-54232
https://emacs.stackexchange.com/questions/54232
Mac OS Catalina random crash
2019-12-07T17:17:17.610
# Question Title: Mac OS Catalina random crash I've been experiencing a weird problem. Ever since updating to catalina my emacs crashes at random intervals. It seems that there is no rule (or I cannot see it) to when it happens. The frequency is quite high but there is no specific thing I do before it happens. I have tried removing parts of my config which could be responsible but so far no matter what I remove it keeps on happening. I tried different versions of emacs: emacs for mac OS, emacs installed via homebrew and I'm now using a version I built myself, on all those versions the problem persists. It is probably unrelated but when using neotree the color higlight on cursor hover lags behind the cursor - it should ever only higlight the filename the cursor currently hovers over but instead it also highlight the ones it hover over previously. Below is the stack trace from the crash. Any help would be appreciated. ``` Thread 0 Crashed:: Dispatch queue: com.apple.main-thread 0 libsystem_kernel.dylib 0x00007fff6ab1c49a __pthread_kill + 10 1 libsystem_pthread.dylib 0x00007fff6abd96cb pthread_kill + 384 2 libsystem_c.dylib 0x00007fff6aa343a2 raise + 26 3 org.gnu.Emacs 0x000000010d6bd319 terminate_due_to_signal + 153 4 org.gnu.Emacs 0x000000010d6bdc5b emacs_abort + 15 5 org.gnu.Emacs 0x000000010d685bf0 ns_term_shutdown + 80 6 org.gnu.Emacs 0x000000010d57bab4 shut_down_emacs + 340 7 org.gnu.Emacs 0x000000010d6bd2e6 terminate_due_to_signal + 102 8 org.gnu.Emacs 0x000000010d59acae 0x10d4bd000 + 908462 9 libsystem_platform.dylib 0x00007fff6abceb1d _sigtramp + 29 10 ??? 000000000000000000 0 + 0 11 com.apple.CoreFoundation 0x00007fff334f436b __CFRunLoopServiceMachPort + 322 12 com.apple.CoreFoundation 0x00007fff334f3907 __CFRunLoopRun + 1695 13 com.apple.CoreFoundation 0x00007fff334f2fe3 CFRunLoopRunSpecific + 499 14 com.apple.HIToolbox 0x00007fff3207a67d RunCurrentEventLoopInMode + 292 15 com.apple.HIToolbox 0x00007fff3207a3bd ReceiveNextEventCommon + 600 16 com.apple.HIToolbox 0x00007fff3207a147 _BlockUntilNextEventMatchingListInModeWithFilter + 64 17 com.apple.AppKit 0x00007fff306ff864 _DPSNextEvent + 990 18 com.apple.AppKit 0x00007fff306fe5d4 -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 1352 19 com.apple.AppKit 0x00007fff306f8d76 -[NSApplication run] + 658 20 org.gnu.Emacs 0x000000010d685dad 0x10d4bd000 + 1871277 21 org.gnu.Emacs 0x000000010d684a11 ns_select + 897 22 org.gnu.Emacs 0x000000010d654292 wait_reading_process_output + 3570 23 org.gnu.Emacs 0x000000010d4c4f08 sit_for + 312 24 org.gnu.Emacs 0x000000010d5841c6 read_char + 5222 25 org.gnu.Emacs 0x000000010d5811da 0x10d4bd000 + 803290 26 org.gnu.Emacs 0x000000010d57f9dc command_loop_1 + 1308 27 org.gnu.Emacs 0x000000010d6065d7 internal_condition_case + 263 28 org.gnu.Emacs 0x000000010d58fa80 0x10d4bd000 + 862848 29 org.gnu.Emacs 0x000000010d605deb internal_catch + 267 30 org.gnu.Emacs 0x000000010d6bd6e5 0x10d4bd000 + 2098917 31 org.gnu.Emacs 0x000000010d57eac3 0x10d4bd000 + 793283 32 org.gnu.Emacs 0x000000010d57e9f3 recursive_edit_1 + 115 33 org.gnu.Emacs 0x000000010d57ec4b Frecursive_edit + 347 34 org.gnu.Emacs 0x000000010d57d827 main + 7431 35 libdyld.dylib 0x00007fff6a9cd2e5 start + 1 ``` # Answer The Emacs macOS port maintainers have found a work-around, but the problem seems to be deep inside macOS. See this bug report for details and a patch: https://debbugs.gnu.org/cgi/bugreport.cgi?bug=38618 Hopefully this will make its way into the macOS releases soon, but for now you can do a local build and apply the patch. On 10.15 you'll need to `export LIBXML2_CFLAGS="-I/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/libxml2"` before running `./configure` for the build to work. > 2 votes --- Tags: osx, crash ---
thread-54436
https://emacs.stackexchange.com/questions/54436
How to get absolute file names, to use with `cd`?
2019-12-18T02:03:25.770
# Question Title: How to get absolute file names, to use with `cd`? I have this function: ``` ;; needs work in case of spaces in filenames (cl-defun filename-from-buffer (&key get-ext get-abs) "Returns the absolute name, with or without extension, of the file that is open in the current buffer." (let ((filename (buffer-name)) (absname (buffer-file-name))) (cond ((and get-ext get-abs) absname ) (get-abs (file-name-sans-extension absname )) (get-ext filename) (t (file-name-sans-extension filename))))) ``` You can test it with something like this, ``` (global-set-key (kbd "C-l t") (lambda () (interactive) (insert (filename-from-buffer :get-ext t :get-abs t)) ;; /Nuskha/With Space/file.ext (insert "\n") (insert (filename-from-buffer)) ;; file (insert "\n") (insert (filename-from-buffer :get-ext t)) ;; file.ext (insert "\n") (insert (filename-from-buffer :get-abs t)))) ;; /Nuskha/With Space/file ``` It works fine, but when there are spaces in the name, as shown in the comments above, the names are not such that you could take them verbatim and use with the `cd` command. ``` $ cd /Nuskha/With Space/file bash: cd: too many arguments ``` I want a function that returns something like this `/Nuskha/With\ Space/file`. How could this be done? # Answer Use quotes to make `cd` think `/Nuskha/With Space/file` is one single argument, not two, e.g., ``` $ cd "/Nuskha/With Space/file" $ cd '/Nuskha/With Space/file' ``` You can also use `shell-quote-argument`: ``` (shell-quote-argument "/Nuskha/With Space/file") ;; => "/Nuskha/With\\ Space/file" ``` > 4 votes --- Tags: filenames ---
thread-54434
https://emacs.stackexchange.com/questions/54434
How to show colours and clear when running React development server in eshell?
2019-12-18T00:56:04.657
# Question Title: How to show colours and clear when running React development server in eshell? Here is how the usual Ubuntu terminal looks when you run the React development serving using `npm start` and make changes to your source: Say the server was already running and you tried to do `npm start` again, you get notified in a colourful message: And, if you say no, it exits cleanly. However, I use eshell. This is how the same thing (the react dev. server) looks in eshell: Observe how the output is appended onto the previous contents instead of clearing the screen. The colours are also missing. If the server is already running, this is how the eshell prompt looks like: This is kind of a mess. Once you say no, it does not exit cleanly but shows the same message again before exiting. My question is, is there a way to make eshell more like the ubuntu terminal? Is there a modern terminal package for Emacs that could handle these kind of things? # Answer > 0 votes FWIW, color handling works out of the box for me with eshell Anything more complicated than that is the task of a terminal emulator, not a shell. Eshell is a replacement for shells, like bash, zsh, you name it, its original purpose was a more familiar environment for developers using Emacs on Windows. If you want a terminal emulator which runs a shell (like bash or zsh) and handles these escape sequences, your choices are term.el with the `M-x term` and `M-x ansi-term` commands and more recently, the vterm package. It might work better for you as it has greater compatibility with xterm (for some reason lots of software in the node.js ecosystem assumes you're using xterm) due to its strategy of letting libvterm handle all the hard work. This means however that you'll need Emacs with dynamic modules support and have to compile the module yourself. --- Tags: shell, eshell, colors, term ---
thread-54418
https://emacs.stackexchange.com/questions/54418
Efficient workflow to write a book in Org-mode
2019-12-17T09:13:32.633
# Question Title: Efficient workflow to write a book in Org-mode I plan to write a short statistics textbook using Org-mode. Even if some textbooks have been written using equivalent systems (e.g., the R package bookdown), I have no examples in mind of books directly written in Org-mode. The LaTeX guidelines of all major editors (e.g., CRC, Springer, Wiley) do not seem to facilitate the use of Org-mode, or at least, they require to build an appropriate workflow I cannot figure out on my own. (I am still a beginner in Org-mode.) Indeed, they require any part, chapter, appendix, acknowledgments, etc., to be submitted in a separate .tex file, with some precise requirements for each file. A master .tex file then gathers all those files and produce the final output. (Example: Springer class here.) Has someone already managed to set up an appropriate workflow for this kind of "constraint"? I can imagine two options: 1. Should I export a series of separate `foreword.tex`, `chapterXX.tex` files, `partXX.tex` files and so on, from one single `book.org` file? And how to do so automatically each time `book.org` is exported? (Is it even possible to respect the Springer guidelines by doing so?) 2. Should I create a series of separate `foreword.org`, `chapterXX.org` files, `part.org` files and so on, export them separately (and manually?) in LaTeX, and finally use the master TeX file from Springer to generate the whole book? Unfortunately, in both cases, I do not see how to preview easily the whole book when exporting my org file(s), like any other org document. Getting/previewing the final book seem to require several manual operations each time, which would make this workflow really difficult to use. Sorry for this rather vague question, but I cannot figure out how to proceed to respect those guidelines. # Answer > 11 votes I think you are actually looking for publishing of projects. This does not only work for HTML but also for LaTeX. Projects are managed in `org-publish-project-alist`. Each entry of that list is one project. There you specify things like project path, publishing path, whether to create latex files that can be translated separately or body only files that can be included into some main LaTeX file. Example for a project with Org source files in the project directory `~/Book` and publishing directory `~/Book/Publish`: ``` (add-to-list 'org-publish-project-alist '("My First Project" :base-directory "~/Book" :publishing-directory "~/Book/Publish" :publishing-function org-latex-publish-to-latex :body-only t :makeindex t )) ``` In this case you must manage yourself the main latex file which just includes the exported LaTeX files. You can also create a project with two subprojects where one subproject manages the main file (with setting `:body-only nil`) and the other is for the org files with the contents of the chapters (with setting `:body-only t`). This way you let Orgmode generate the LaTeX header. Then use a LaTeX block with the `\include` commands for the chapters. EDIT: 1. Do not use `:auto-sitemap t` but let LaTeX generate the table of contents. --- Tags: org-mode, latex, org-babel, writing ---
thread-41524
https://emacs.stackexchange.com/questions/41524
Add note on reschedule ONLY for one reschedule
2018-05-18T05:25:44.907
# Question Title: Add note on reschedule ONLY for one reschedule I can add: ``` #+STARTUP: lognotereschedule ``` and it will prompt me to insert a note every time I reschedule using `C-c C-s`. But I want to enter a note only on one (or a few) reschedules. How do I achieve that? # Answer You can add notes at will independently of TODO state changes and rescheduling. `org-add-note` (bound to `C-c C-z` will prompt for a note to add to the current TODO item. Similarly, in the agenda display, typing `z` will call `org-agenda-add-note`. > 3 votes # Answer I have the following in my `.emacs`: ``` (defun org-schedule-force-note () "Call org-schedule but make sure it prompts for re-scheduling note." (interactive) (let ((org-log-reschedule "note")) (call-interactively 'org-schedule))) (define-key org-mode-map (kbd "C-c C-S-s") 'org-schedule-force-note) (defun org-deadline-force-note () "Call org-deadline but make sure it prompts for re-deadlining note." (interactive) (let ((org-log-redeadline "note")) (call-interactively 'org-deadline))) (define-key org-mode-map (kbd "C-c C-S-d") 'org-deadline-force-note) ``` So whenever I want to take a note on why I re-scheduled something or moved a deadline, I use `C-c C-S` or `C-c C-D` instead of `C-c C-s` or `C-c C-d`. --- **EDIT 2019-12-31**: As it is somewhat related to this: I recently wanted to force note taking on re-scheduling for a certain important headline even if I were to forget using the corresponding command. According to the documentation on `org-log-reschedule` this should be possible by setting the `LOGGING` property of this headline to `note`. However, this does not work for me. Will check back if I ever get it to work. > 2 votes --- Tags: org-mode ---
thread-54430
https://emacs.stackexchange.com/questions/54430
How to move point to an invisible line (to access an org property when heading is folded)?
2019-12-17T20:00:17.153
# Question Title: How to move point to an invisible line (to access an org property when heading is folded)? I wrote some code to reschedule all headings under a subtree, but it was failing to get the scheduled date of heading in invisible lines, even though it could access other properties such as the name of the heading. I debugged it with `edebug` and noticed that the value of `(point)` was always the same, even though different heading names were appearing in the `*Messages*` buffer. I used a quick fix of showing the full buffer with `(org-shifttab 3)` and wrapping the last function inside a `(org-save-outline-visibility t ...)`, but this seems inelegant and over the top. I wonder if `search-forward` that I am using in `org-get-scheduled-timestring-at-point` does not move point to invisible lines, even though it forces lines with a match to become visible when used interactively. Here is a minimal example with an Org-buffer: ``` * heading ** TODO task 1 SCHEDULED: [2019-12-26 Thu] *** DONE task 0 SCHEDULED: [2019-12-09 Mon] *** TODO sub task SCHEDULED: [2019-12-01 Thu] ** TODO task 2 SCHEDULED: [2020-01-01 Wed] ``` and the code: ``` (defun my-org-get-end-of-subtree () "Gets the index at the end of the subtree." (save-excursion (ignore-errors (outline-end-of-subtree) (point)))) (defun my-org-get-property () "Returns whether the scheduled date of the heading at point is in the past." (interactive) (save-excursion (org-back-to-heading) (message "Point is at %d" (point)) (search-forward (concat org-scheduled-string " ")) ; move point to the scheduled entry (buffer-substring (point) (line-end-position)))) (defun my-org-test-fails () (interactive) (let ((end (my-org-get-end-of-subtree))) (when end (save-excursion (org-back-to-heading) (while (and (outline-next-heading) (< (point) end)) (message (my-org-get-property))))))) (defun my-org-test-works () (interactive) (let ((end (my-org-get-end-of-subtree))) (when end (org-save-outline-visibility t (save-excursion (org-shifttab 3) (org-back-to-heading) (while (and (outline-next-heading) (< (point) end)) (message (my-org-get-property)))))))) ``` The result in the `*Messages*` buffer of running `org-test-fails` and then `org-test-works` is: ``` task 1 Point is at 68 [2019-12-26 Thu] done task Point is at 68 [2019-12-26 Thu] sub task Point is at 68 [2019-12-26 Thu] task 2 Point is at 68 [2019-12-26 Thu] ... task 1 Point is at 79 [2019-12-26 Thu] done task Point is at 123 [2019-12-09 Mon] sub task Point is at 171 [2019-12-01 Thu] task 2 Point is at 218 [2020-01-01 Wed] ``` How can I move point to a line that matches text and is invisible? Or how can I get the text of the `SCHEDULED` property of an invisible heading just like I am able to get its heading text? # Answer You should check out the Using the Property API section of the manual. In particular, doing `(org-entry-get (point) "SCHEDULED")` with `point` at the beginning of the headline returns the scheduled date of the entry, whether the headline is folded or not -- or even hidden: try hiding everything and execute ``` (org-entry-get 12 "SCHEDULED") ``` on the tree you show above when everything is folded. I get the scheduled date of the headline "task 1": `[2019-12-26 Thu]`. > 2 votes --- Tags: org-mode, code-folding, point ---
thread-54372
https://emacs.stackexchange.com/questions/54372
Tools to develop and debug ELISP code
2019-12-14T16:04:18.753
# Question Title: Tools to develop and debug ELISP code I have some experience in Emacs-LISP. Today I spent 6 hours writing LISP code that I guess-timate would have taken 1h30 to write in Python because my workflow to develop and debug is very clunky. In Python I would log successive values with `print("Stage N: " + value)` at different stages. I am looking for something better. I give two examples below. I'm sure other people are more productive given the high reputation of LISP. What workflows do coders use for development and debugging in Emacs-LISP? ## One example Automated testing with ERT does not indicate the line of an error. This is so strange that I made it into its own question). ## Another example In debugging a function with an optional argument, I was unable to log that value to the `*Messages*` buffer as I could not find how to convert `t` and `nil` to string. In the `*scratch*` buffer: ``` (message (concat "Value is: " (string t))) ;; concat: Wrong type argument: characterp, t (message (concat "Value is: " (string nil))) ;; concat: Wrong type argument: characterp, nil (message (concat "Value is: " t)) ;; message: Wrong type argument: sequencep, t (message (concat "Value is: " nil)) "Value is: " ``` # Answer Here is the beginnings of a list of useful techniques culled from the comments. Please add any others that you find useful by editing this answer: * The elisp analog of sprinkling printfs in a program to show values of variables: `(message "Value is %s" whatever)`. * Using a debugger: possibilities include the Lisp Debugger, and edebug. > 1 votes --- Tags: debugging, programming, debug ---
thread-54453
https://emacs.stackexchange.com/questions/54453
Don't open a HTML link if drag-and-dropped to Emacs
2019-12-19T10:15:26.003
# Question Title: Don't open a HTML link if drag-and-dropped to Emacs I keep my notes in Markdown. Often I would like to collect various links by drag-and-dropping them from the browser. However, Emacs opens them instead. I know that this is probably what most people want, but is there any way to disable this, so Emacs will not open a link but just insert it as a text # Answer You can customize the Drag and Drop behavior using the variable `dnd-protocol-alist`. The ultimate fallback is inserting the link as text, so this is what you want: ``` (setq dnd-protocol-alist nil) ``` The following is the default value, you can also remove `http` only ``` (("^file:///" . dnd-open-local-file) ("^file://" . dnd-open-file) ("^file:" . dnd-open-local-file) ("^\\(https?\\|ftp\\|file\\|nfs\\)://" . dnd-open-file)) ``` By the way, you can do interesting thing with `dnd-protocol-alist`, such as, drag a html url into a markdown buffer and insert it as markdown link automatically. One existing cool use of it is Dired, when you drag a file into a dired buffer, the file will be copy&paste into that directory. > 1 votes --- Tags: html, hyperlinks, drag-and-drop ---
thread-46524
https://emacs.stackexchange.com/questions/46524
Org-Mode How to position tables correctly when exporting to Latex?
2018-12-10T19:45:18.627
# Question Title: Org-Mode How to position tables correctly when exporting to Latex? I have a document I have written in org-mode which contains several tables. The tables all have the following attributes. ``` #+begin_table #+LATEX: \caption{Initial risk List} #+LATEX: \label{tab:risk-list} #+LATEX: \centering #+LATEX: \adjustbox{max width=\textwidth}{ #+ATTR_LATEX: :center t :placement [h] |Col1|Col2| |----+----| | 1 | 2 | |----+----| #+end_table ``` The configuration is to allow my tables to scale correctly for my document without running off the page which works, however, the `[h]` argument isn't being read by LaTeX as all the tables get places on one page together in the pdf document instead of being at their positions in the text where I want them. Am I passing the wrong latex configuration or is it just not picking it up during the parsing? I am using spacemacs by the way I'm not sure if that changes anything. After looking at the tex file org produced it seems there is no placement values put into the document. # Answer > 3 votes After looking at the problem for a while I found this solution. ``` #+LATEX: \begin{adjustbox}{width={\textwidth},keepaspectratio} #+ATTR_LATEX: :placement [!h] #+LATEX: \centering |Col1|Col2| |----+----| | 1 | 2 | |----+----| #+LATEX: \end{adjustbox} ``` While also including ``` #+LATEX_HEADER: \usepackage{adjustbox} ``` At the top of the document. # Answer > 0 votes Add this to header: ``` #+LATEX_HEADER: \usepackage{float} #+LATEX_HEADER: \restylefloat{table} ``` And then write your tables like this: ``` #+CAPTION: ML Algorithms #+NAME: ml-algos-table #+ATTR_LATEX: :center t :placement [H] |----+----| |Col1|Col2| |----+----| | 1 | 2 | |----+----| ``` Also refer this and this --- Tags: org-mode, org-export, org-table ---
thread-54461
https://emacs.stackexchange.com/questions/54461
How to check the change log of a Spacemacs layer's update
2019-12-20T00:30:22.687
# Question Title: How to check the change log of a Spacemacs layer's update I update my Spacemacs layers very often. How can we see the git log for those updates? For example, the most recent `haskell-mode` layer has a bug, and I want to check it. # Answer > 1 votes Found an answer: How to get release note of updated package in Spacemacs Though it's not clear how to read the source code in each commit. --- Tags: spacemacs ---
thread-54469
https://emacs.stackexchange.com/questions/54469
Looking up values in an org spreadsheet
2019-12-20T09:14:22.520
# Question Title: Looking up values in an org spreadsheet I imagine it would be possible, with the tables ``` | food | kcal/hg | |---------+---------| | sausage | 281 | ``` and ``` | food | g | kcal | |---------+-----+------| | sausage | 100 | | ``` that is, with a table of food names and kcal/hg values and a table of names and g values, automatically to calculate the kcal values in the second list. But how exactly is that to be done? # Answer You could use the lisp function `memq` for the lookup as demonstrated in the Org example below. I use the Literal mode switch `L`. This imposes the restriction that there are only one-word identifier in the `food` column. Furthermore I use `quote` to avoid evaluation of the symbols in the table formula. Please, use the table debugger to see what is going on (`Tbl` menu item `Debug Formulas`). ``` #+NAME: kcal_per_hg | food | kcal/hg | |-----------+---------| | sausage | 281 | | something | 100 | | other | 200 | and | food | g | kcal | |---------+-----+-------| | sausage | 100 | 281.0 | | other | 123 | 246.0 | #+TBLFM: $3='(* 0.01 $2 (cadr (memq (quote $1) (quote (remote(kcal_per_hg,@I$1..@II$2))))));L ``` Note that this solution is tailored to your special problem since the words are actually looked-up in the full table `kcal_per_hg`. There follows a more general but also more complicated variant. It only searches the first column of the two-column table `kcal_per_hg` for food. ``` #+NAME: kcal_per_g | food | kcal/g | |-----------+--------| | something | 100 | | sausage | 281 | | other | 200 | and | food | g | kcal | |---------+-----+-------| | other | 123 | 246.0 | | sausage | 100 | 281.0 | #+TBLFM: $3='(* $2 0.01 (cl-loop for p on (quote (remote(kcal_per_g,@I$1..@II$2))) by #'cddr if (eq (quote $1) (car p)) return (cadr p)));L ``` If each row of the table to be searched has `N` columns instead of two you can replace `cddr` with `(apply-partially #'nthcdr N)`. > 2 votes --- Tags: org-mode, spreadsheet ---
thread-38375
https://emacs.stackexchange.com/questions/38375
where to put .el files on Windows10 for loading at startup
2018-01-26T16:33:05.447
# Question Title: where to put .el files on Windows10 for loading at startup I'm using emacs as a bog-standard program in Windows, and also from the command line in cygwin. They both use the same installation of emacs. I just grabbed `yaml-mode.el` off the net but I can't get it to load at start-up. Where should I put it? Initially I thought I'd put it in the emacs installation directory `emacs/site-lisp/` but then I noticed there's also an `emacs/25.3/site-list/`. Neither of those works for emacs from the cygwin command line. It complains at startup due to the lisp in my `.emacs`. I also put it in `~/.emacs.d` but that didn't work either. Ideally I would like to have it one place so that it works in Windows and cygwin, and is in a directory on my Microsoft One Drive (because that's the only place on my workstation which gets backed up). I can make pointers to wherever I need to, which work for the `.emacs` file. # Answer The way I managed it seems slightly clunky, but ain't it always like that: ``` (add-to-list 'load-path "/cygdrive/c/Users/adam/OneDrive/.emacs.d") (add-to-list 'load-path "c:/Users/adam/OneDrive/.emacs.d") ``` So I entered it twice, once with Windows10 format file path, once with cygwin. Thanks @Drew for the comment > 0 votes # Answer I suppose your Window and Cygwin Emacs shares the same setup under `~/.emacs.d`; If not, you need setup environment variable `HOME` in Windows, make it point to the parent directory of `.emacs.d`. Insert below code into beginning of `~/.emacs` or `~/.emacs.d/init.el`: ``` (eval-when-compile (require 'cl)) (if (fboundp 'normal-top-level-add-to-load-path) (let* ((my-lisp-dir "~/.emacs.d/site-lisp/") (default-directory my-lisp-dir)) (progn (setq load-path (append (loop for dir in (directory-files my-lisp-dir) unless (string-match "^\\." dir) collecting (expand-file-name dir)) load-path))))) ``` Then any sub-directory under `~/.emacs.d/site-lisp/` is automatically recognized by Emacs. In your case, you only need create the directory of `~/.emacs.d/site-lisp/yaml-mode` and place `yaml-mode.el` under the directory `~/.emacs.d/site-lisp/yaml-mode`. Please note the above code is copied from Steve Purcell's setup (https://github.com/purcell/emacs.d) > 0 votes # Answer Once upon a time I used to do this: > Launch NTEmacs via Cygwin > > If you want to launch NTEmacs via Cygwin (in order that it inherits your Cygwin environment variables – particularly useful if your bash profile does things like managing a ssh-agent), then you can use a shortcut like the following to enable this, while maintaining consistency with the standard (for NTEmacs) HOME directory: > > ``` > C:\cygwin\bin\bash.exe --login -c "env HOME=\"`cygpath '%APPDATA%'`\" /cygdrive/c/emacs/emacs-23.2/bin/runemacs.exe" > > ``` -- https://www.emacswiki.org/emacs/NTEmacsWithCygwin > 0 votes --- Tags: init-file, microsoft-windows, cygwin, site-lisp ---
thread-39080
https://emacs.stackexchange.com/questions/39080
Org-mode #+include: -- ignore configuration lines from included file
2018-02-25T18:14:20.970
# Question Title: Org-mode #+include: -- ignore configuration lines from included file How can I have org #+INCLUDE: ignore configurations from the included files? I'm thinking of cases where I don't want Latex Classes to be messed up. For example, if I have two org files book.org and chapter.org that look like the following: book.org ``` #+LATEX_CLASS: book * Chapter 1 #+INCLUDE: chapter.org ``` chapter.org ``` #+LATEX_CLASS: report * Results ``` Then on export (to another Org file) I get the following: ``` #+LATEX_CLASS: book * Chapter 1 #+LATEX_CLASS: report ** Results ``` This is not good because a latex-export may get messed up (the last latex\_class takes precedence, so I would end up with a report and not a book). What is the recommended way to avoid these issues? # Answer > 1 votes Use the include directive's option: :only-contents t (https://orgmode.org/manual/Include-files.html), for example in book.org: ``` * Chapter 1 ** Results #+INCLUDE: "chapter.org::*Results" ``` Then only the contents below the header Results in chapter.org is included. If you are specifying your latex class in an export property in chapter.org, like below ``` :PROPERTIES: :EXPORT_LaTeX_CLASS: some class :END: ``` then you can also include the whole org file ``` #+include: "chapter.org" :only-contents t ``` # Answer > 1 votes I would reorg the files a bit: the `chapter1.org` and `report.org` files should not specify any configuration. You can then include them in `Book.org`: ``` #+LATEX_CLASS: book #+INCLUDE: chapter1.org #+INCLUDE: report.org ``` or in `Report.org` (note the capital R: I'm assuming your filesystem is case sensitive): ``` #+LATEX_CLASS: report #+INCLUDE: report.org ``` This requires a bit more effort and discipline, but it *is* flexible. --- Tags: org-mode, org-export, latex ---
thread-54460
https://emacs.stackexchange.com/questions/54460
Is it possible to revert a hunk in diff-mode?
2019-12-20T00:24:00.143
# Question Title: Is it possible to revert a hunk in diff-mode? With viewing a diff for a modified working copy, is there a way to revert the hunk under the cursor? That is, reverse the change shown in the diff, making the changes to source-file the diff refers to. Ideally it would refresh the diff too, although I could handle that myself. --- Currently I'm navigating to the hunk using `diff-goto-source`, then using `git-gutter:revert-hunk` from the `git-gutter` package, however I would like to perform this inside the diff. # Answer If you `C-c``C-a` (`diff-apply-hunk`) on a hunk which has *already* been applied, diff-mode will detect this and ask whether you wish to reverse that change. You can also request this directly by passing a prefix argument to the command. In cases where the context is insufficient to tell whether or not the patch has been applied, the latter method would be necessary. > 9 votes # Answer There are `R` in `diff-mode`. > `R` runs the command `diff-reverse-direction` > > Reverse the direction of the diffs. So first `R` and then `C-c C-a` to apply reversed diff. It is possible to revert individual hunk without reversing whole diff by invoking `diff-aply-hunk` with prefix argument. So another solution is `C-u C-c C-a`. > 5 votes # Answer Adding own answer, since `diff-apply-hunk` didn't do exactly what I wanted. This is a stripped down `diff-apply-hunk` with some modified behavior, to revert hunks without changing the context. * The buffer is saved after reverting. * The hunk is removed. * No new windows open. It allows for quickly navigating over a diff and reverting hunks, without having to switch buffers and save each time. ``` (defun diff-apply-hunk-reverse-and-save (&optional _arg) "Revert the current hunk, removing it from the diff, saving the buffer immediately." (interactive "P") (diff-beginning-of-hunk t) (pcase-let ( (`(,buf ,line-offset ,pos ,_old ,new ,switched) (diff-find-source-location nil t))) ;; last arg is 't for always reversed. (cond ((null line-offset) (error "Can't find the text to patch")) (switched (error "Patch is already removed")) (t ;; Apply the hunk (with-current-buffer buf (goto-char (car pos)) (delete-region (car pos) (cdr pos)) (insert (car new)) (save-buffer)) (diff-hunk-kill))))) ``` > 2 votes --- Tags: diff-mode ---
thread-54475
https://emacs.stackexchange.com/questions/54475
Applying formatting from within tables
2019-12-20T16:59:04.853
# Question Title: Applying formatting from within tables It seems that `^c ^c` applies table formatting only when point is on the formatting line (the one beginning in `#+tblfm:`). Is it possible to have `^c ^c` apply formatting even when point is in the table itself? Or is one supposed to do something else from within the table? It's a bit laborious every time to have to place point at the formatting line before pressing `^c ^c`. # Answer > 1 votes The `#+tblfm:` line is for table formulas, not formatting. Pressing `M-Q` anywhere on the table reformats the whole table, this is called *table-align*. The same happens when tabbing through cells, or when pressing `C-C C-C` anywhere on the table. If, however, you want to recalculate all formulas (which is what happens when `C-C C-C` on the formula definitions), you can call `C-c *` and its variants. References: --- Tags: org-table ---
thread-54477
https://emacs.stackexchange.com/questions/54477
YASnippet: Remove parts of expanded snippet when exiting the current active area based on condition
2019-12-20T20:10:10.323
# Question Title: YASnippet: Remove parts of expanded snippet when exiting the current active area based on condition I want to write a snippet for LaTeX sum that behaves like this: I write "sum" and trigger snippet expansion. "sum" becomes "\sum\_{$1}^{$2} $0", with $1 being the first entry point, $2 the second one and $0 the exit point. If I write nothing inside $1, I want to have the "\_{}" part deleted and proceed to $2. Likewise with $2. Is such a thing possible with YASnippet or any other snippet engine? I tried putting an Elisp function that deletes the needed part if exiting with no input made but it breaks the snippet. # Answer > 1 votes You can do this with an extra step (see "Nested placeholder fields" in the manual): ``` \sum${1:_{${2:}}}^{$3} $0 ``` With the optional field: `TAB, TAB, insert field 1, TAB, insert field 2, TAB to exit.` Without the optional field: `TAB, C-d, insert field 2, TAB to exit.` Another option is to use a function that deletes the empty field in case it finds one: ``` \sum_{$1}^{$2} ${0:$$(yas-delete-if-empty)} (defun yas-delete-if-empty () (save-excursion (when (re-search-backward "\\\\sum\\(_{}\\)^{.+}" (line-beginning-position) t) (replace-match "" t t nil 1)))) ``` --- Tags: yasnippet ---
thread-54449
https://emacs.stackexchange.com/questions/54449
Emacs terminal - the location before the command prompt
2019-12-18T22:41:58.140
# Question Title: Emacs terminal - the location before the command prompt My emacs terminal is currently displaying ;0user@Ubuntu: ~user@Ubuntu:~$". This happened after my friend was using my laptop, and is persisting after uninstalling and reinstalling emacs, as well as deleting .emacs related files. I have tested the terminal on emacs on different accounts on my laptop, and it is not suffering from this, so migrating my files is an option, but annoying. Does anyone have a way of fixing the terminal on emacs? I'm running Ubuntu as well. # Answer The problem ended up being in my .bashrc file in my home directory. The issue was the PS1 value under the `case "$TERM" in` clause had somehow been modified. I changed this value to `PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '` to reset it back to the default. > 1 votes --- Tags: terminal-emacs, linux, ubuntu ---
thread-54484
https://emacs.stackexchange.com/questions/54484
How to disable code blocks in an Emacs org-mode init file
2019-12-21T15:47:38.070
# Question Title: How to disable code blocks in an Emacs org-mode init file My dot emacs config consists of a short init.el file and a very large org file in which I have created dozens of emacs-lisp code-blocks. This works very well for me, especially in terms of organization. Every now I then I wish to temporarily disable one of these code blocks without having to delete the blocks in part or altogether. Is there a more elegant way of doing this? At present I tend to archive the code blacks to another file. However, I would like to keep them in the same file, and activate them if I need them. Is there a tag that might do this? # Answer Set the state of a header to COMMENT: ``` ** COMMENT This will not be tangled #+BEGIN_SRC elisp (foo) #+END_SRC ``` `C-c ;` runs the command `org-toggle-comment`. > 4 votes --- Tags: org-mode, init-file, org-babel, tags ---
thread-54478
https://emacs.stackexchange.com/questions/54478
Implementing my own incremental search
2019-12-20T22:40:27.633
# Question Title: Implementing my own incremental search What would be the best way to implement an Emacs Lisp command that pops up the minibuffer, lets the user edit a search string there, and runs code to update the search results after each keystroke (or other command) that changes the minibuffer contents? To be specific, I'm asking about how to run a Lisp function in response to text changes; running a Lisp function in response to each keystroke may be close enough. I'm talking about something that resembles the well-known incremental search (I-search) commands built into Emacs. `isearch.el` shows that I-search itself sets up `isearch-mode-map` such that each ASCII/multibyte character is manually mapped onto the `isearch-printing-char` command. (It loops over all the numerical character codepoints and assigns the same command to each codepoint). If possible, it would probably be easier to have normal minibuffer editing, and simply have a hook function that gets called after every keystroke (or other command) that changes the minibuffer contents. # Answer > 4 votes The minibuffer is a normal buffer, so you can use `post-command-hook` or `after-change-functions` (or both) to react to edits. You can use `minibuffer-with-setup-hook` to set them up: ``` (minibuffer-with-setup-hook (lambda () (add-hook 'post-command-hook #'my-minibuf-after-cmd nil 'local) (add-hook 'after-change-functions #'my-minibuf-after-edit nil 'local)) (read-string ...)) ``` Using both can be useful: it's often a good idea to limit the amount of code run in `after-change-functions` either for performance reasons (a single command (such as filling a paragraph) can sometimes cause thousands of individual changes) or to avoid undesired interactions (`after-change-functions` is run right when the change takes place, before the command is finished, so it might run in an unusual context). In constrast `post-command-hook` is only run once per user interaction and "at top-level", so it is customary to limit `after-change-functions` to record the change in some global variable, and then use that var in `post-command-hook`. --- Tags: keymap, isearch ---
thread-54487
https://emacs.stackexchange.com/questions/54487
Add timestamp to repeating task when marked DONE
2019-12-21T19:35:41.343
# Question Title: Add timestamp to repeating task when marked DONE Say I have this task: ``` * TODO Task SCHEDULED: <2019-12-21 Sat 13:00 +1w> ``` and I mark it done the day after. Then, the timestamp becomes `<2019-12-28 Sat +1w>` and I lose the previous entry, ie when looking at the agenda on Dec 20th, I will not see the task. Even with log-mode on, I will not see it on Dec 20th, but on Dec 21st (the day I marked it DONE). In the manual for Repeated tasks, it says: > As a consequence of shifting the base date, this entry will no longer be visible in the agenda when checking past dates, but all future instances will be visible. Is there a way to get around this? Maybe an active timestamp of the current timestamp could be added automatically when marked DONE and the date is shifted into the future. Something like this: ``` * TODO Task <2019-11-30 Sat 13:00> <2019-12-07 Sat 13:00> <2019-12-14 Sat 13:00> SCHEDULED: <2019-12-21 Sat 13:00 +1w> ``` # Answer If you mark something done the day after, you could instead mark it done with `org-todo-yesterday` or `org-agenda-todo-yesterday` which will give it the correct timestamp. Or, when you mark it done, add a note with the timestamp you want in the note. See `org-log-done` or `(setq org-log-done 'note)`. > 1 votes --- Tags: org-mode ---
thread-54391
https://emacs.stackexchange.com/questions/54391
Easily update dates for a recurrent set of TODOs in org mode
2019-12-15T18:53:14.813
# Question Title: Easily update dates for a recurrent set of TODOs in org mode Every semester I teach the same course and for every semester there are several TODOs that should, at least initially, have the same dates *relative to* the starting date (i.e. the first day of class). How can I take the previous semester's course.org and easily update all of the TODO dates? To exemplify with a MWE, imagine these were my TODOS this semester (I actually have plenty more) ``` ** TODO prepare and distribute syllabus (first day of class: Sept 03, 2019) SCHEDULED: <2019-09-03 Tue> ** TODO explain group project (two weeks after classes started) SCHEDULED: <2019-09-17 Tue> ** TODO Create groups (on the Wednesday, three weeks after classes started) SCHEDULED: <2019-09-25 Wed> ``` How can I update these dates for this semester (where the first class falls, say, on January 13, 2020?) (I am also happy to just create some sort of template (though preferably not a 'capture template') with variables for the initial dates and use a macro to fill them in). # Answer I'm guessing one way to shift all scheduled dates relative to a starting date is to calculate the difference in time between the new and old starting dates. Adding the result to the scheduled date should return the new date. ``` (defvar new-start-date "2020-01-13 Mon") (defun shift-date (date old-start-date) (let* ((encode (lambda (d) (apply #'encode-time (org-parse-time-string d)))) (date (funcall encode date)) (old-start-date (funcall encode old-start-date)) (new-start-date (funcall encode new-start-date)) (time (org-time-add date (org-time-subtract new-start-date old-start-date)))) (format-time-string "<%F %a>" time))) (defun reschedule-entries () (interactive) (let ((re (concat org-scheduled-string " *<\\([^>]+\\)>")) date old-start-date) (save-excursion (goto-char (point-min)) (when (re-search-forward re nil t) (setq old-start-date (match-string 1)) (replace-match new-start-date t t nil 1))) (org-map-entries (lambda () (when (re-search-forward re (save-excursion (outline-next-heading) (point)) t) (setq date (match-string 1)) (unless (string= date new-start-date) (org-schedule nil (shift-date date old-start-date))))) "TODO=\"TODO\""))) ``` --- Here's another version based on the comments. Please test and report back. ``` ** TODO prepare and distribute syllabus (first day of class: Sept 03, 2019) SCHEDULED: <2019-09-03 Tue> :PROPERTIES: :RELATIVE-DATE: 0 week :END: ** TODO explain group project (two weeks after classes started) SCHEDULED: <2019-09-17 Tue> :PROPERTIES: :RELATIVE-DATE: 2 week :END: ** TODO Create groups (on the Wednesday, three weeks after classes started) SCHEDULED: <2019-09-25 Wed> :PROPERTIES: :RELATIVE-DATE: 3 week wed :END: ``` ``` (defvar initial-date "<2020-01-13 Mon>") (defun get-dow (date &optional n) "Return the day of the week from DATE and shift it by N days." (let ((date (org-time-string-to-time date))) (format-time-string "%a" (if n (org-time-add date (* 86400 n)) date)))) (defun shift-to-dow (date dow) "Shift DATE to the next DOW (day of the week)." (let (newdate (dow (capitalize dow))) (cl-loop for i from 1 to 7 if (string= dow (get-dow date)) collect (setq newdate (org-time-string-to-time date)) else when (string= dow (get-dow date i)) collect (setq newdate (time-add (org-time-string-to-time date) (* 86400 i)))) (format-time-string "<%F %a>" newdate))) (defun reschedule-entries () (interactive) (org-map-entries (lambda () (when (assoc "RELATIVE-DATE" (org-entry-properties)) (let* (newdate (elt (org-element-at-point)) (reldate (split-string (org-element-property :RELATIVE-DATE elt) " ")) (value (string-to-number (cl-first reldate))) (unit (intern (cl-second reldate))) (dow (cl-third reldate))) (with-temp-buffer (insert initial-date) (forward-line 0) (if (eq unit 'week) ;; no 'week in org-timestamp-change so change it to days (org-timestamp-change (* value 7) 'day) (org-timestamp-change value unit)) (setq newdate (buffer-substring (point-min) (point-max)))) (org-schedule nil (if dow (shift-to-dow newdate dow) newdate))))) "TODO=\"TODO\"")) ``` > 1 votes # Answer I am not sure how to properly answer the question, but I have an idea that may help someone more capable to answer the question. The trick may be to use two properties/variables: 1) A global variable with the initial date (`InitialDate`), and 2) a variable local to each `TODO` that specifies the relative difference with respect to the initial date (`relativeDate`). As I imane it `RelativeDate` would be a string in the format used by `org-schedule to take advantage of this function's functionality.` One would feed the initial date and the relative difference to a function that relies on `org-schedule`. Here is an example of how the file with the schedule would look like ``` :PROPERTIES: #+MACRO: InitialDate 2020-01-13 ** TODO prepare and distribute syllabus (first day of class: Sept 03, 2019) SCHEDULED: <2021-01-13 Mon> :PROPERTIES: #+MACRO: RelativeDate +0 ** TODO explain group project (two weeks after classes started) SCHEDULED: <2021-01-27 Wed> :PROPERTIES: #+MACRO: RelativeDate +2w ** TODO Create groups (on the Wednesday, three weeks after classes started) SCHEDULED: <2019-12-31 Tue> :PROPERTIES: #+MACRO: RelativeDate +3Wed ``` > 0 votes --- Tags: org-mode, time-date ---
thread-54500
https://emacs.stackexchange.com/questions/54500
How to add a locally override the message function?
2019-12-23T00:07:09.710
# Question Title: How to add a locally override the message function? I would like to add a suffix to a message reported by a function called in some source I don't maintain. Is there a way to locally override the `message` function so I can manipulate it before it's displayed? *(add a prefix or suffix for example).* I know I can read the message log and log new message, but I'd rather avoid flooding the log, or manipulate the message buffer. # Answer > 4 votes This macro adds support for adding a suffix to messages. Using advice allows this to be nested, so multiple functions can add their own suffixes which accumulate onto the end. ``` (defmacro with-temp-advice (fn-orig where fn-advice &rest body) (declare (indent 3)) (let ((function-var (gensym))) `(let ((,function-var ,fn-advice)) (unwind-protect (progn (advice-add ,fn-orig ,where ,function-var) ,@body) (advice-remove ,fn-orig ,function-var))))) (defmacro with-message-suffix (suffix &rest body) "Add text after the message output. Argument SUFFIX is the text to add at the start of the message. Optional argument BODY runs with the message suffix." (declare (indent 1)) `(with-temp-advice 'message :around (lambda (fn-orig arg &rest args) (apply fn-orig (append (list (concat arg "%s")) args (list ,suffix)))) ,@body)) ``` --- Tags: advice, message ---
thread-54507
https://emacs.stackexchange.com/questions/54507
How does org-mode implement syntax highlighting for code blocks?
2019-12-23T18:37:39.793
# Question Title: How does org-mode implement syntax highlighting for code blocks? How does org-mode implement syntax highlighting for code blocks? More specifically, for a C file, does it use `cc-mode` or does it have its own algorithm? For example, if I have this org file: **test.org**: ``` * Example source code in C: #+BEGIN_SRC c #include <stdio.h> int main() { printf( "Hello world\n" ); return 0; } #+END_SRC ``` I get the following highlighting: --- But if have the same pure C file (using `cc-mode`) **test.c**: ``` #include <stdio.h> int main() { printf( "Hello world\n" ); return 0; } ``` I get: --- --- Notice that `printf` has different face color in the two files. So it seems like `org-mode` has its own syntax highlighting. It is not using `cc-mode` to do the highlighting, is that correct? # Answer > 5 votes It uses cc-mode. It copes the text to a temporary buffer, highlights it using the major mode that is associated with the language, and copies back the highlighting. In addition, it makes everything not highlighted grey. In addition to the difference you spotted in `printf`, this is also visible in other places like the braces and parentheses. --- Tags: org-mode, syntax-highlighting ---
thread-54515
https://emacs.stackexchange.com/questions/54515
Evaluate allows for combinations whose operators are compound expressions
2019-12-24T07:49:33.197
# Question Title: Evaluate allows for combinations whose operators are compound expressions I find the amazing power of scheme in sicp > Exercise 1.4. Observe that our model of evaluation allows for combinations whose operators are compound expressions. Use this observation to describe the behavior of the following procedure: ``` #+BEGIN_SRC scheme (define (a-plus-abs-b a b) ((if (> b 0) + -) a b)) (a-plus-abs-b 9 4) #+END_SRC #+RESULTS: : 13 ``` Try to rewrite it as ``` #+begin_src emacs-lisp :session sicp :lexical t (defun a-plus-abs-b(a b) ((if (> b 0) + -) a b)) (a-plus-abs-b 9 4) #+end_src ``` report error "invalid function" Alternatively with ``` #+begin_src emacs-lisp :session sicp :lexical t (defun a-plus-abs-b(a b) (funcall (if (> b 0) + -) a b)) (a-plus-abs-b 9 4) #+end_src ``` Error reported as ``` funcall: Symbol’s value as variable is void: + ``` How could write it correctly in elisp? # Answer `funcall` takes a function as its first argument, so you need `if` to return a function symbol. You can do that by sharp-quoting its return value: ``` (defun a-plus-abs-b (a b) (funcall (if (> b 0) #'+ #'-) a b)) (a-plus-abs-b 9 4) ; => 13 ``` Elisp is a Lisp-2, which means each symbol can have a function value and a variable value. When you don't quote the return value of `if`, you're asking it to return the variable value of `+` or `-`, which you could actually do if you want to: ``` (setq - "testing") (- 1 1) ; => 0 - ; => "testing" (+ 1 1) ; => 2 + ; => void variable "+" ``` See: > 2 votes --- Tags: functions, variables, funcall ---
thread-54495
https://emacs.stackexchange.com/questions/54495
eval-after-load doesn't work
2019-12-22T16:49:32.003
# Question Title: eval-after-load doesn't work I am trying to re-define two functions in `two-column.el.gz`, namely `2C-split` and `2C-merge`. Both of those are declared with `;;;###autoload`. I gathered I should use `(eval-after-load "two-column" ...)`, because Linux (Ubuntu) won't let me change the original file. I have this `eval-after-load` body in my `.emacs` file, more precisely in a `settings.org` file which I load from the `.emacs`. I have all my code here. When I do `find-function` after startup, I am shown this file (inside the `eval-after-load` bit). But then, when I do `C-x 6 s`, it's the original function which is called, not mine. And after that `find-function` sends me to the `two-column.el.gz` file. I tried `with-eval-after-load`, I tried the full file path instead of "two-column", but nothing seems to work. `after-load-alist` doesn't even show my new functions, unless I specifically load the `(eval-after-load ...)` with `C-x C-e` \- then there is an entry for it. My questions are both how to load my functions without having to load the file explicitly (which also didn't quite work, but that's a different problem), and why this is happening. I simply do not understand. # Answer It's hard to give a precise answer because you don't show the actual shape of your code, but it's quite possible that the problem is that your code is simply not being evaluated. I have a side-answer to provide, tho: you might prefer to use `advice-add` to modify existing functions. This can be done before the function is defined, so no need for `eval-after-load` or similar and it can still defer to the original definition, which is often very useful: ``` (advice-add '2C-split :around #'my-2C-split) (defun my-2C-split (original-definition &optional arg) ...) ``` > 1 votes # Answer In the end I ended up remapping the key for `2C-split` instead. There was a problem with `2C-merge` afterwards, as in the 2C-mode, `2C-merge` is redefined again, so remapping keys didn't work. I used `advice-add` as per Stefan's answer to change the behaviour of the original function. I still don't know what the original problem was. > 0 votes --- Tags: eval-after-load ---
thread-54508
https://emacs.stackexchange.com/questions/54508
How to set extra frames in size?
2019-12-23T18:43:54.733
# Question Title: How to set extra frames in size? Whenever I open an info entry in emacs (`C-h i`) an additional frame pops up. On my system, it is too small and I'd love to have it in the top left corner, being wider and longer as it was created by default. The new frame is labeled "\*info". The same applies to the frame, that rises, whenever I use emacs various help functions (`C-h k`, `C-h v`, `C-h f`, ...). Those new frames are labaled "Help". This frame has a similar position and size, as the "*info*" frames. I have defined a `default-frame-alist` as well as an `initial-frame-alist` in my `~.emacs` file. ``` (setq initial-frame-alist '((top . 35) (right . 5) (width . 200) (height . 55) )) (setq default-frame-alist '( ;(scroll-bar-foreground-color . "yellow") (vertical-scroll-bar . right) (scroll-bar-width . 17) (internal-border-width . 2) (top . 20) (left . 10) (width . 120) (mouse-color . "yellow") (cursor-color . "red") )) ``` Those new frames are obviously not the initial frame. Therefore, it is okay to me, that the don't use the dimensions given in the 'initial-frame-alist'. **EDIT** This image shows the location of the two frames, after having pressed `C-h i`. AS you can see, a new frame "\* info \*" was opened on top of the initial frame (which is now in the background). Please notice also, the width of the new frame is not sufficient, to view the text, without breaking some longer lines. Furthermore, I'd love to have the new frame on the left screen side. But I'd like to define the dimensions as well. That would save me to use the mouse, to correct their size and location. Something like this is desired: (Obviously, I picked the frame with the mouse, moved it to its desired location and resized it with the mouse. I'd love to avoid using the mouse, instead I want to add some lisp code to my `~/.emacs` to do this changes for me! If I press than `C-h k TAB` I get another frame as shown here. This should also open on the left screen side (and not on the right side, as shown here). What do I have to add, to my '~.emacs' file, in order to define the size ('width' x 'height') and location ('left' and 'top') of this kind of frames. Something like this (pseudocode) ``` (setq info-frame-alist '((top . 5) (left . 5) (width . 100) (height . 25) )) (setq help-frame-alist '((top . 7) (left . 7) (width . 75) (height . 20) )) ``` Any suggestions? --- **EDIT** When I `eval` some functions in the new frames, I do get this kind of information: ``` (frame-root-window) ; => #<window 7 on *info*> ``` the number ("7" in this case) depends on how many buffers I have opened in the actual running emacs. But the text "*info*" is exact the title of the frame in question. # Answer > 3 votes My suggestion would be to specify that `*Help*` and `*info*` buffers be *special-display* buffers. You can customize option **`special-display-buffer-names`**, to specify that these buffers should be shown in their own frames at specific screen locations. You can also use option **`special-display-regexps`**, to handle multiple buffers `*info*`, `*info<2>*`,... Simple example (but it's better to use `M-x customize-option` to set option values - that goes for `default-frame-alist` too): ``` (setq special-display-frame-alist '((left . 100) (top . 50))) (add-to-list 'special-display-buffer-names "*Help*") (add-to-list 'special-display-regexps "[*]info[*]\\(<[0-9]+>\\)?") ``` You can do more-complicated things, of course, such as putting the Help and Info frames at different locations or giving them other properties that are different. --- \[Be aware that the Emacs docs tell you that `special-display-*` things are considered deprecated, since you can do more, in much more complicated ways, using `display-buffer-alist`. When that was added to Emacs it was touted as a replacement for `special-display-*`, because it's more general. I don't consider `special-display-*` deprecated, personally. It's simple to use, to do a relatively simple job.\] --- Tags: init-file, frames ---
thread-54521
https://emacs.stackexchange.com/questions/54521
Mac stopped binding CMD-Up, which I use in Emacs and Racket
2019-12-25T09:08:43.047
# Question Title: Mac stopped binding CMD-Up, which I use in Emacs and Racket CMD/up, used in both Dr Racket and Portacle (Emacs) to retrieve the last command in the buffer, has stopped working for both programs. Other combinations with CMD do work, such as CMD/P, and CMD/X, CMD/+ I am using OS X, on a Macbook Pro This seems to be related to a previous question (set-mark-command (C-SPC) not recognised/broken), however the stated solution for that question did not work (System Preferences \> Keyboard \> Shortcuts \> Input Sources \> Select the previous input source and uncheck). That question had assumed this was on the Emacs level but found it was on the OS level. That is obviously the case for me, as it affects more than one program. I would greatly appreciate any help. # Answer Fixed -- I apologize to take up the space after having fixed it so fast, but I think it's worth documenting for the next person who runs into this: The basic solution (outlined in set-mark-command (C-SPC) not recognised/broken) does work, but I hadn't unchecked the right shortcut. I overlooked the fact that my particular error was due to another combination being overwritten by the keyboard shortcuts. In this case, it was "Mission Control" that was bound to CMD/up. Unchecking that in Keyboard Preferences \> Shortcuts, did the trick. > 1 votes --- Tags: key-bindings, osx ---
thread-54519
https://emacs.stackexchange.com/questions/54519
org-cycle in Doom Emacs: 2 instead of 3 states
2019-12-25T00:52:36.157
# Question Title: org-cycle in Doom Emacs: 2 instead of 3 states I recently installed Doom and noticed that in org-mode the Tab key (used for local/subtree visibility cycling) only cycles between 2 states ('folded' and 'children') as opposed to 3 states I'm used to from vanilla Emacs ('folded', 'children' and 'subtree'). I can't seem to find the reason for that. Tab is bound to `org-cycle`, the documentation of which clearly mentions 3 states. Invoking the function "manually" through `M-x` never unfolds the entire subtree either. What am I missing here? # Answer > 2 votes I figured it out. Removing `+org-cycle-only-current-subtree-h` from the `org-tab-first-hook` list of hooks restores 3-state cycling: ``` (setq org-tab-first-hook (delete '+org-cycle-only-current-subtree-h org-tab-first-hook)) ``` --- Tags: org-mode, cycling ---
thread-54526
https://emacs.stackexchange.com/questions/54526
Python src block sets tabs
2019-12-25T18:18:14.447
# Question Title: Python src block sets tabs Emacs 26.3, Org 9.3 When using python src block, it changes 8 spaces to tab. When tangling this, python errors with "inconsistent use of tabs and spaces in indentation". How fix it? # Answer > 1 votes From documentation: > ‘org-src-preserve-indentation’ > > Default is ‘nil’. Source code is indented. This indentation applies during export or tangling, and depending on the context, may alter leading spaces and tabs. When non-‘nil’, source code is aligned with the leftmost column. No lines are modified during export or tangling, which is very useful for white-space sensitive languages, such as Python. So, I've set this variable as local for buffer in the end of the file ``` ;;; Local Variables: ;;; org-src-preserve-indentation: t ;;; End: ``` --- Tags: org-babel ---
thread-54505
https://emacs.stackexchange.com/questions/54505
How to highlight digit groups of 3 in numerals?
2019-12-23T18:04:31.417
# Question Title: How to highlight digit groups of 3 in numerals? I find it very useful to visually distinguish every 3 digit group of numbers in source code so that I can read it. For example something if I see 1**000**000 it is fairly easy to see that this is 1M rather than 10M or 100k. Basically I want to made digits 4-6, 10-12... look different from the others. In vim I could do this via a custom syntax rule. ``` match SpellRare /\d\{1,3}\ze\%(\%(\d\{3}\)\{2}\)*\d\{3}\>/ ``` This relies on zero-length lookaheads to work. Emacs highlighting doesn't appear to have these so the best I could do was multiple `highlight-regexp` calls. ``` (add-hook 'prog-mode-hook (lambda () (highlight-regexp "\\([0-9]\\{1,3\\}\\)\\([0-9]\\{3\\}\\|\\)\\>" font-lock-warning-face 1) (highlight-regexp "\\([0-9]\\{1,3\\}\\)[0-9]\\{9\\}\\>" font-lock-warning-face 1) (highlight-regexp "\\([0-9]\\{1,3\\}\\)[0-9]\\{15\\}\\>" font-lock-warning-face 1) (highlight-regexp "\\([0-9]\\{1,3\\}\\)[0-9]\\{21\\}\\>" font-lock-warning-face 1) (highlight-regexp "\\([0-9]\\{1,3\\}\\)[0-9]\\{27\\}\\>" font-lock-warning-face 1) (highlight-regexp "\\([0-9]\\{1,3\\}\\)[0-9]\\{33\\}\\>" font-lock-warning-face 1) (highlight-regexp "\\([0-9]\\{1,3\\}\\)[0-9]\\{39\\}\\>" font-lock-warning-face 1))) ``` This mostly works for the number lengths I have defined (although it doesn't always update correctly when editing the number). Is there a better solution to this? # Answer > 3 votes You can simulate the `\ze` construct using repeated matching. See also `(info "(elisp) Search-based Fontification")`. ``` (defun my-matcher (limit) (when (re-search-forward "\\([0-9]\\{1,3\\}\\)\\(?:[0-9]\\{6\\}\\)*\\(?:[0-9]\\{3\\}\\)\\_>" limit t) (goto-char (match-beginning 1)) (re-search-forward "[0-9]+" (match-end 1)))) (font-lock-add-keywords nil '((my-matcher 0 font-lock-warning-face))) ``` --- Tags: regular-expressions, font-lock, syntax-highlighting ---
thread-54530
https://emacs.stackexchange.com/questions/54530
Unattended install of a set of packages
2019-12-25T23:14:42.103
# Question Title: Unattended install of a set of packages Given a `requirements.txt` file describing a Python virtual environment, one can run `pip install requirements.txt`, go for a coffee, then come back to find that the packages in `requirements.txt` have been installed. Is there a mechanism in Emacs (25.x, 26.x) to install a list of packages without attending to the installation by running a sequence of M-x `package-install`? # Answer One can use `use-package`. In a file (which *could* be your init file, but doesn't have to be): ``` (require 'package) (add-to-list 'package-archives '("melpa" . "https://melpa.org/packages/") t) (package-initialize) (setq package-archives (seq-remove (lambda (element) (equal "gnu" (car element))) package-archives)) (add-to-list 'package-archives '("gnu" . "https://elpa.gnu.org/packages/")) ;; bootstrap use-package, so I can use it to manage everything else (unless (package-installed-p 'use-package) (package-refresh-contents) (package-install 'use-package)) (eval-when-compile (require 'use-package)) (use-package use-package :config (setq use-package-always-ensure t)) ``` Then you can set up all your packages as follows: ``` (use-package package1) (use-package package2) ``` When this file is evaluated (which, if it's your init file, is on startup), Emacs will install all the packages you've set up this way. If a package is already installed, use-package will skip the installation; it won't be updated to the latest. You can use other features of use-package to configure each installed package. > 1 votes --- Tags: package, package-repositories ---
thread-54533
https://emacs.stackexchange.com/questions/54533
Org-mode: blocks incorrectly parsed as org-mode markup
2019-12-26T04:02:08.187
# Question Title: Org-mode: blocks incorrectly parsed as org-mode markup I noticed a really weird behavior related to `#+begin_xxx`/`#+end_xxx` block. It turns out that contents inside those blocks are parsed as org-mode markup. That is, inside a block: * `*` at the beginning of a line is considered as a heading. A direct impact is that `org-global-cycle` fold/unfold incorrectly sectioning. * `[[not a link]]` is considered as an org-mode link. Export to pdf (`org-latex-export-to-pdf`) the org file will raise the error `Unable to resolve link: "not a link"` as it would fail to resolve unexisting links. * and probably more... # MWE `emacs-version = 26.3` `org-version = 9.2.6` ``` * H1 ** H2 #+begin_example * Should not be rendered as a heading! [[Should be avoided when exporting]] #+end_example #+begin_src c * sp = "Should not be rendered as a heading!" // [[Should be avoided when exporting]] #+end_src ``` ## Issue: `org-cycle` (`Tab`) ## Issue: `org-global-cycle` (`Shift`+`Tab`) ## Issue: `org-export-latex-to-pdf` # Related question # Answer > 1 votes You must escape such constructs in example blocks. The Literal Examples section of the manual states: > There is one limitation, however. You must insert a comma right before lines starting with either ‘`*`’, ‘`,*`’, ‘`#+`’ or ‘`,#+`’, as those may be interpreted as outlines nodes or some other special syntax. Org transparently strips these additional commas whenever it accesses the contents of the block. ``` #+BEGIN_EXAMPLE ,* I am no real headline #+END_EXAMPLE ``` And it turns out that escaping the "fake" headline also solves the link export problem. Try exporting this: ``` * H1 ** H2 #+begin_example ,* Should not be rendered as a heading! [[Should be avoided when exporting]] #+end_example #+begin_src c ,* sp = "Should not be rendered as a heading!" // [[Should be avoided when exporting]] #+end_src ``` --- Tags: org-mode, org-export ---
thread-34290
https://emacs.stackexchange.com/questions/34290
How to suppress the interpretation of double brackets in org mode?
2017-07-20T07:01:29.570
# Question Title: How to suppress the interpretation of double brackets in org mode? How to suppress the interpretation of double brackets in org mode? Some of my text heavily used the double brackets but org-mode defined it to be links. Can I suppress the interpretation of double brackets, or more conveniently, temporarily suppress it where I do not need it to be interpreted as links. I've tried quote (~~ ==) it as code but it does not work. The only way I found is to embedded them into an EXAMPLE or SRC. Are there any other methods, maybe some OPTIONS? Thanks very much! # Answer You can use `M-x org-toggle-link-display` to only disable the collapsing of the double brackets, although this still formats the text within the brackets as a link (blue, underlined). The formatting of bracketed links can be disabled entirely by changing `org-highlight-links`, which is set to `'(bracket angle plain radio tag date footnote)` by default. By removing `bracket` from this list, bracketed items will not be treated as links anymore. This can be done by `setf`ing the variable, or via `M-x customize`. When you change this list, you have to use `M-x org-mode-restart` for the changes to take effect (see `C-h v org-highlight-links` for more details). > 3 votes # Answer You can also customize the variable `org-activate-links` with a local value by putting this line at the beginning of the file: ``` ;; -*- mode: org; org-activate-links: '(angle plain radio tag date footnote); -*- ``` > 1 votes --- Tags: org-mode ---
thread-54481
https://emacs.stackexchange.com/questions/54481
Difference between pcase-let & cl-destructuring-bind?
2019-12-21T11:32:56.923
# Question Title: Difference between pcase-let & cl-destructuring-bind? I noticed both `pcase-let` and `cl-destructuring-bind` seem to perform the same operation. Is there any difference or reason to use one instead of the other? eg: ``` (pcase-let ((`(,filename ,buf) (pop filename-and-buffer-list))) ;; do stuff. ) ``` Seems to behave the same as: ``` (cl-destructuring-bind (filename buf) (pop filename-and-buffer-list) ;; do stuff. ) ``` # Answer > 9 votes `cl-destructuring-bind` was designed more or less specifically to destructure data made of cons cells. `pcase-let` on the other hand is just a special case of `pcase` which was designed to handle arbitrary data and be extensible (and be able to discriminate rather than only destructure). So `cl-destructuring-bind` has a slightly more concise syntax for the simple cases like the one you show, whereas `pcase-let` imposes a more verbose syntax in exchange for the ability to destructure other data types such as structs, hash-tables, ... Another difference is that `pcase-let` allows you to perform several such bindings, as in ``` (pcase-let ((PAT1 EXP1) (PAT2 EXP2) ...) ..) ``` whereas `cl-destructuring-bind` focuses on the single-pattern case, so you'd have to use ``` (cl-destructuring-bind PAT1 EXP1 (cl-destructuring-bind PAT2 EXP2 ...)) ``` which again makes `cl-destructuring-bind` less verbose in the simple case. As the designer&implementer of `pcase` I consider that the added verbosity cost of `pcase-let`s generality is minor (compared to the advantage of having a single syntax of patterns that works both for simple and complex cases). --- Tags: elisp, let-binding, cl, elisp-conventions ---
thread-54537
https://emacs.stackexchange.com/questions/54537
How to use `next-error` and `previous-error` without the compilation buffer visible
2019-12-26T15:53:06.973
# Question Title: How to use `next-error` and `previous-error` without the compilation buffer visible I want to be able to use grep to find matching lines and to be able to jump through them using `next-error` and `previous-error` however I don't feel the need to have the match list on screen and it takes up considerable space. I would like to find a way to get similar functionality without having to have the window visible. I managed to avoid showing the window using `(setq-default display-buffer-alist '(("\\*grep\\*" (display-buffer-no-window))))` however when the buffer is not in a visible window I get an error when using `next-error`. ``` Debugger entered--Lisp error: (wrong-type-argument window-live-p nil) #<subr select-window>(nil nil) ad-Advice-select-window(#<subr select-window> nil) apply(ad-Advice-select-window #<subr select-window> nil) select-window(nil) rustc-scroll-down-after-next-error() run-hooks(next-error-hook) next-error-found(#<buffer *grep*> #<buffer controller.rs>) next-error(nil) funcall-interactively(next-error nil) call-interactively(next-error nil nil) command-execute(next-error) ``` Manually making the window visible then running `next-error` works, so it isn't broken but something assumes the window is visible for some reason. # Answer > 1 votes You say that for you `next-error` doesn't work unless the buffer with the "error" messages is visible (i.e., in a visible window). I don't see that. Can you repro the problem starting with `emacs -Q` (no init file)? If not, bisect your init file to find the culprit. When I use `emacs -Q` (with any Emacs version), and then I grep or whatever, to get some "error" messages in a buffer, and then I delete the window showing that buffer, `next-error` works just fine. --- Tags: debugging, compilation-mode, grep ---
thread-54543
https://emacs.stackexchange.com/questions/54543
How to give user free rein to edit a buffer in the middle of lisp code?
2019-12-26T20:24:32.423
# Question Title: How to give user free rein to edit a buffer in the middle of lisp code? I'm trying to run some code, a little like this: ``` (defun myfun () (message "one") (user-does-things) (message "two") ``` I would like the code to do this: 1. display "one" 2. let the user edit in another buffer 3. When the user is done editing, display "two" All my attempts so far have just displayed "one" and "two", leaving the user to do his editing after the code has finished running. I'm also OK with a more disconnected approach, such as "I launch a buffer with a custom keymap so the user is able to do whatever they want in emacs until they hit a keybinding which calls back to my custom code" - I could use some help to do this as well though :D # Answer The question is not too clear. But I think maybe what you're saying is that you want to: 1. Show message `one`. 2. Let the user start doing some arbitrary editing, in any buffer. No limits on what she can do. 3. Let the user indicate when she's done. 4. Show message `two`. If that, or similar, is the case, then one way to realizes steps 2 and 3 is to use a recursive edit. A recursive edit can be initiated by program or interactively -- in either case using function/command **`recursive-edit`**. And a user can exit the current recursive edit using **`C-M-c`** (command `exit-recursive-edit`). You can exit all levels of recursive editing, returning to the top-level of Emacs, using `C-]` (command `abort-recursive-edit`). For a start, you could do this, for example: ``` (defun myfun () (message "one") (save-excursion (recursive-edit)) ; User does things (message "two")) ``` --- Library **`rec-edit.el`** (code) can help with recursive editing. * It gives you a single key (**`C-M-c`**) to both enter and exit a recursive edit. * It optionally highlights the mode-line indication, **`[...]`**, to make clear that you are in a recursive edit, and what the recursion level is. > 6 votes --- Tags: buffers, recursive-edit ---
thread-14337
https://emacs.stackexchange.com/questions/14337
column-marker skips blank lines; how to fix?
2015-07-29T18:31:42.590
# Question Title: column-marker skips blank lines; how to fix? I installed column-marker.el. I like the highlighting style better than fci-mode. Unfortunately, column-marker does not highlight bits of the window where the actual line is not 80 chars or more (or whatever its set to). Can this be fixed, so that there's a continuous highlighted strip at column 80? I saw that this issue used to exist in fci-mode, but was fixed. I didn't investigate carefully. I suppose it's possible to configure fci-mode to display like column-marker, but I haven't investigated this carefully either. # Answer Library `vline.el` (`vline.el`) does what you're requesting. * If you want the current column to be highlighted as you move around, then turn on `vline-mode`. (`C-u` turns it off.) Use `vline-global-mode` to do this everywhere. * If you instead want a particular column to be highlighted and stay highlighted then use function (not command) `vline-show`. (Function `vline-clear` clears it.) * See option `vline-style` for different ways to highlight. > 1 votes --- Tags: highlighting ---
thread-54546
https://emacs.stackexchange.com/questions/54546
org-babel - Use specific python path and command line option
2019-12-27T02:08:04.697
# Question Title: org-babel - Use specific python path and command line option Since different python version installed on my system, how can I use specific python and option to run it? For example,below test.py file will print hello output. ``` #!/opt/anaconda3/bin/python --myoptions print("hello") ``` I want to get a equivalent by org-babel, maybe something like below: ``` #+BEGIN_SRC python :results :cmd /opt/anaconda3/bin/python :option --myoptions print("hello") #+END_SRC ``` Do we have such option to config that? # Answer > 3 votes In Org 9.2.3 function `org-babel-execute:python` contains following `let`-assignment: ``` (org-babel-python-command (or (cdr (assq :python params)) org-babel-python-command)) ``` Therefore, the header argument you are looking for is (at least in that Org version): `:python /opt/anaconda3/bin/python --myoptions` Those lines have been introduced in Org at commit e527e49c38. Note, that those lines are also part of the newest release on 2019-12-27, i.e., Org 9.3.1. --- Tags: org-babel ---
thread-54548
https://emacs.stackexchange.com/questions/54548
Find out, which mode is in use
2019-12-27T11:07:01.013
# Question Title: Find out, which mode is in use Suppose I want to code something like this ``` case mode in lisp-mode) do-something ;; shell-mode) do-other ;; latex-mode) do-different ;; esac ``` What would be the best way to do this in lisp? Especially, how to find out, which mode is in use? # Answer See `major-mode` variable to find out major mode: > Symbol for current buffer’s major mode. See `cond` function to do something depending on mode: > Try each clause until one succeeds. > > Each clause looks like (CONDITION BODY...). CONDITION is evaluated and, if the value is non-nil, this clause succeeds: then the expressions in BODY are evaluated and the last one’s value is the value of the cond-form. If a clause has one element, as in (CONDITION), then the cond-form returns CONDITION’s value, if that is non-nil. If no clause succeeds, cond returns nil. E.g. ``` (cond ((eq major-mode 'lisp-interaction-mode) (message "lisp interaction mode")) ((eq major-mode 'text-mode) (message "text mode"))) ``` Also see `derived-mode-p` function: > (derived-mode-p &rest MODES) > > Non-nil if the current major mode is derived from one of MODES. > 9 votes --- Tags: major-mode, lisp ---
thread-54497
https://emacs.stackexchange.com/questions/54497
How to set TAB behavior in Org-mode source-blocks when the language isn't supported?
2019-12-22T19:37:47.730
# Question Title: How to set TAB behavior in Org-mode source-blocks when the language isn't supported? How can I set a default `TAB` behavior (i.e. 4 spaces instead of tab) in an Org source-block when the language **is not** supported? Example: ``` #+begin_src xyz lkjsdf iouqweou #+end_src ``` Using TAB within the source-block gives me the following error message: > org-edit-src-code: No such language mode: xyz-mode I've already added ``` (setq-default indent-tabs-mode nil) (setq-default tab-width 4) ``` to the top of my init-file, and I'm loading org-mode via *use-package* ``` (use-package org :ensure org-plus-contrib :mode (("\\.org\\'" . org-mode)) :hook (org-mode . variable-pitch-mode) (org-mode . visual-line-mode) :config (setq org-src-preserve-indentation t) (setq org-src-tab-acts-natively t)) ``` # Answer > 2 votes The `org-tab-first-hook` hook runs as the first action when TAB is pressed, so you need a function that checks if (1) the point is inside a src block and (2) the language is not found. If both conditions are true, indent to column 4. To insert 4 spaces literally, change the `indent-to` expression to `(insert (make-string 4 ?\s))`. ``` (add-hook 'org-tab-first-hook (lambda () (when (org-in-src-block-p t) (let* ((elt (org-element-at-point)) (lang (intern (org-element-property :language elt))) (langs org-babel-load-languages)) (unless (alist-get lang langs) (indent-to 4)))))) ``` --- Tags: org-mode ---
thread-53570
https://emacs.stackexchange.com/questions/53570
Elisp function to get path to file link target
2019-11-05T16:42:09.410
# Question Title: Elisp function to get path to file link target With the cursor on a file link, I'd like to set up an org-capture template which inserts the template into the target of the link. I guess I add something like ``` (setq org-capture-templates '(("m" "Topic" entry (file (get-path-to-link-target-at-point)) "\n* Topic %?"))) ``` to my init.el in order to achieve what I'm looking for. But I'm not able to code such a function `get-path-to-link-target-at-point`. So how do I get the file path of a link target at my cursor location? # Answer > 1 votes The content of `org-capture-templates` is basically a series of forms that are not evaluated. That is why you put the quote. This means that in order to call that function you would need to add a comma to unquote and possibly a backtick. This is what I do in mine code usually: ``` (setq org-capture-templates `(("m" "Topic" entry (file ,(get-path-to-link-target-at-point)) "\n* Topic %?"))) ``` Hope it helps. --- Tags: org-capture, org-link ---
thread-54464
https://emacs.stackexchange.com/questions/54464
SMIE and backward-up-list
2019-12-20T04:03:43.963
# Question Title: SMIE and backward-up-list Though SMIE seems to be indenting my little language very nicely, and `forward-sexp` also works well, I don't get `backward-up-list` working as desired. My grammar: ``` (defvar holscript-smie-grammar (smie-prec2->grammar (smie-bnf->prec2 '((id) (decl ("Theorem" id ":" quotedmaterial "Proof" tactic "QED") ("Definition" id ":" quotedmaterial "Termination" tactic "End") ("Definition" id ":" quotedmaterial "End") ("Datatype:" quotedmaterial "End")) (quotedmaterial) (tactic (tactic ">>" tactic) (tactic "\\\\" tactic) (tactic ">-" tactic) (tactic ">|" tactic))) '((assoc ">>" "\\\\" ">-" ">|"))))) ``` If I have my cursor inside a `Theorem` (at `*` below, say): ``` Theorem name: statement Proof tactic1 `*` >> tactic2 QED ``` then I can navigate along the tactics nicely. If I have the cursor on `Theorem` I can use `C-M-b` to navigate a sequence of `Theorem`s nicely too. But if I'm between the `Proof` and `QED` keywords (or the `Theorem` and `Proof` keywords), I can't use `backward-up-list` to get me to the top level of that phrase. Instead, I get a `Scan error: "Unbalanced parentheses"`, and I shoot to the top of the whole file. It seems to me as if the grammar is defining the `Theorem`-`Proof`-`QED` syntax as a sexp-like thing (and wrt to `forward-sexp` this also seems true), but `backward-up-list` doesn't seem to agree... # Answer It's a known bug (aka limitation) of SMIE's support for `(backward-)up-list`. To fix it right we need to make changes to `(backward-)up-list`, or otherwise redirect those commands to SMIE versions of them. IIRC, you can partly avoid the problem by replacing things like ``` (decl ... ("Theorem" id ":" quotedmaterial "Proof" tactic "QED") ...) ``` with something like: ``` (decl ... ("Theorem" theorem-contents "QED") ...) (theorem-contents (theorem-head "Proof" tactic)) (theorem-head (id ":" quotedmaterial)) ``` > 1 votes --- Tags: smie ---
thread-38843
https://emacs.stackexchange.com/questions/38843
Spacemacs change line background color when has comment
2018-02-15T13:52:28.673
# Question Title: Spacemacs change line background color when has comment I currently have a strange behave when my code has comment on Spacemacs. Making it bad to read a file with a lot of comments Anyone knows how to change this behave? I tried to search about it and I failed. Thanks a lot # Answer > 1 votes I went to the comment line and enter `M-x customize-face` and changed the `font-lock-comment-face` with the same background used by the default lines. # Answer > 0 votes I've gotten this to work in my config ``` (defun dotspacemacs/user-init () (setq spacemacs-theme-comment-bg nil) .... ) ``` --- Tags: spacemacs, faces, themes, colors ---
thread-54560
https://emacs.stackexchange.com/questions/54560
`Alt-f` or `Alt-b` then `d` deletes the forward word rather than putting character 'd' in front of the word. Why does emacs behave in this way?
2019-12-28T13:40:08.287
# Question Title: `Alt-f` or `Alt-b` then `d` deletes the forward word rather than putting character 'd' in front of the word. Why does emacs behave in this way? I was doing some editing in Emacs. I was using `Alt-f` and `Alt-b` to traverse by word. I wanted to add the character `d` in front of a word. So I pressed `Alt-b` to get to the front of the word and then pressed `d`. Oops! It deleted the word rather than putting `d` in front of the word. Is the expected behavior of Emacs? # Answer `ALT-d` is normal for delete word, so my guess is that you pressed the d key before releasing the `ALT` key. Don't forget you can check any keystroke combinations by using `C-h c`, that is `C-h` then release the Control key and press `c`. Enter the key strokes. > 2 votes --- Tags: text-editing, keystrokes ---
thread-18180
https://emacs.stackexchange.com/questions/18180
emacs-snapshot: Could not find simple.el or simple.elc
2015-11-18T08:39:24.013
# Question Title: emacs-snapshot: Could not find simple.el or simple.elc I tried to install emacs-snapshot through their PPA on a fresh Ubuntu 14.04 LTS: ``` sudo apt-add-repository ppa:ubuntu-elisp/ppa sudo apt-get update sudo apt-get install emacs-snapshot ``` But when i try to start it, it gives me this error: ``` emacs-snapshot Warning: Could not find simple.el or simple.elc Cannot open load file: No such file or directory, warnings ``` I have also tried running it as sudo, and the same thing happens. I do not have an .emacs.d/ folder, so it should just run as vanilla. Do anyone have any idea how i can make it work? # Answer > 3 votes I have the same issue. It looks all el-files were placed into incorrect directory. I'm not sure but I found 2 directories in /usr/share/emacs for 25.0.50 and 25.1.50. The version of my emacs is 25.0.50 and I think it's the latest version but all required files in directory 25.1.50. I just renamed original 25.0.50 directory and created symlink with name 25.0.50 to point to 25.1.50. It works for me. # Answer > 2 votes I have encountered the same phenomenon today and Googled the message and I reached here. The workaround that Vitaly has worked, but I wonder why I could install Emacs just by `$ sudo apt install emacs` before but I could not then. I asked the same question in the Japanese Stack Overflow and a person told me that simple.elc is included in the dependent library `emacs25-common`. So I ran `$ sudo apt install emacs25-common` and then I could fix the problem. Maybe it was because I installed the older Emacs before. I thought I have purged the old Emacs but maybe the old libraries have remained somehow. ANd when I re-installed emacs25-common, I could overwrite the old library with the correct one so I could fix it. Pseudo code: 1) install Emacs with `$ sudo apt install emacs` 2) if succeed =\> congrats! your work has done 3) else if you got the massage `simple.elc missing` then `$ sudo apt install emacsXX-core` (where XX is version number) Hope this helps. --- Tags: emacs-snapshot ---
thread-54554
https://emacs.stackexchange.com/questions/54554
How can I use the function debian-run-directories in Ubuntu 18?
2019-12-27T22:23:03.120
# Question Title: How can I use the function debian-run-directories in Ubuntu 18? I had this code in my emacs config to load/include any additional config in the site-start.d folder. It worked well on two debian machines, but currently I need to use Ubuntu 18 with emacs 26.3 and it fails. ``` (setq dotfiles-dir (file-name-directory (or load-file-name (buffer-file-name)))) (let ((user-site-start-dir (concat dotfiles-dir "/site-start.d"))) (debian-run-directories user-site-start-dir)) ``` From a related answer at https://stackoverflow.com/a/27676611 I understood it is both available in debian and Ubuntu. The error I get on start is: ``` Warning (initialization): An error occurred while loading ‘/home/foo/.emacs.d/init.el’: Symbol's function definition is void: debian-run-directories ``` What is the easiest way to use it in Ubuntu? # Answer > 1 votes Ubuntu 18.04 does not have emacs 26 in its repositories, so it has been installed from source or from a ppa that doesn't include the debian patches. The function `debian-run-directories` is defined in `debian-startup.el` that is part of the `emacsen-common` package, you can install it with ``` sudo apt install emacsen-common ``` After the package installation you may need to add `/usr/share/emacs/site-lisp/` to `load-path` before loading `debian-startup.el`. ``` (add-to-list 'load-path "/usr/share/emacs/site-lisp") (load "debian-startup") ``` --- Tags: ubuntu ---
thread-15209
https://emacs.stackexchange.com/questions/15209
Redefine evil-ex-command
2015-08-31T14:16:32.743
# Question Title: Redefine evil-ex-command I use evil and evil-tabs with Emacs and am quite comfortable with my setup except a few times when I have multiple splits open in a tab, using `:q` ends up closing all the splits in the window. In Vim it will close only the split I am currently in. I think this part of `evil-tabs.el` is responsible: ``` (evil-define-command evil-tab-sensitive-quit (&optional bang) :repeat nil (interactive "<!>") (if (> (length (elscreen-get-screen-list)) 1) (elscreen-kill) (evil-quit bang))) (evil-ex-define-cmd "q[uit]" 'evil-tab-sensitive-quit) ``` I tried doing the following in my `.emacs`: ``` ;;; `:quit` ends up quitting more than I intended. So rebind that. (evil-ex-define-cmd "q[uit]" 'kill-buffer-and-window) ``` Also: ``` (eval-after-load 'evil-tabs ;; `:quit` ends up quitting more than I intended. So rebind that. '(evil-ex-define-cmd "q[uit]" 'kill-buffer-and-window)) ``` But `:q` again closes the whole tab. Any clues on how to change or debug this? # Answer > 1 votes I've submitted a pull request to fix this in the evil-tabs repo just now, so hopefully it will be applied soon. But in case it isn't or you don't want to wait (anyone coming here just now as I did) you can change evil-tab-sensitive-quit to be: `(evil-define-command evil-tab-sensitive-quit (&optional bang) :repeat nil (interactive "<!>") (if (> (length (elscreen-get-screen-list)) 1) (if (> (length (window-list)) 1) (evil-quit bang) (elscreen-kill) (evil-quit bang)) (evil-quit bang)))` The behavior is then: if tab contains \> 1 window, then :q will just close current window else close tab and also if last window in last remaining tab then :q will kill Emacs --- Tags: evil ---
thread-54566
https://emacs.stackexchange.com/questions/54566
forward-word and non-letter "words"
2019-12-28T20:11:19.570
# Question Title: forward-word and non-letter "words" Using `forward-word` with this line: ``` foo *** *** bar, ``` I want to have the folowing behavior: ``` foo| ***| ***| bar|, ``` Not: ``` foo| *** *** bar|, ``` So, if between spaces there are only non-letter symbols, let's consider this a word too. `forward-whitespace` is not good enough, cause it loses distinction between letters and non-letters at all. How this can be done? # Answer Just use `forward-sexp` instead (bound to `C-M-f`). Likewise, `backward-sexp` (`C-M-b`). See (elisp) List Motion. --- If you don't want to do that then you'll need to change the syntax for character `*` in your buffer to be word syntax: ``` (modify-syntax-entry ?* "w") ``` Or for a given syntax table, `my-table`: ``` (modify-syntax-entry ?* "w" my-table) ``` > 1 votes --- Tags: navigation, syntax-table, syntax, characters, words ---
thread-54558
https://emacs.stackexchange.com/questions/54558
What is this permanently highlighted region?
2019-12-28T03:50:30.953
# Question Title: What is this permanently highlighted region? I accidentally pressed some keys in a buffer and created the permanently highlighted region shown below. What is this region called, and how can I get rid of it? # Answer > 5 votes That permanently highlighted region is the secondary selection. We deduced this in the comments to your question by putting point in the middle of the highlighted region and by calling `M-x` `describe-char` `RET`. You get something like the following in the opening `*Help*` buffer: > ``` > There is an overlay here: > From 316781 to 316796 > face secondary-selection > > ``` You also mentioned in one of your comments that your window manager hides `mouse-1` events from Emacs. One possible solution to that problem could be to define the following key bindings: ``` (global-set-key [?\e mouse-1] 'mouse-start-secondary) (global-set-key [?\e drag-mouse-1] 'mouse-set-secondary) (global-set-key [?\e down-mouse-1] 'mouse-drag-secondary) (global-set-key [?\e mouse-3] 'mouse-secondary-save-then-kill) (global-set-key [?\e mouse-2] 'mouse-yank-secondary) ``` These are the secondary selection bindings of `mouse.el` with `M-` replaced by `?\e`, the escape key. So whenever you are asked to use the Meta modifier for a secondary selection command you can press the `ESC` key before the unmodified key sequence instead. For an example, press `ESC` `<mouse-1>` instead of `M-<mouse-1>` to **get rid of the "strange" highlighting** by deleting the secondary selection overlay. Note, that the secondary selection can become handy when you want to temporarily *remember* stuff in a selection while using the primary selection as usual. For an example you can mark some stretch of text by the secondary selection, mark and delete some other stretch of text with the primary selection and insert the stuff from the secondary selection with `ESC` `<mouse-2>`. --- Tags: secondary-selection ---
thread-54571
https://emacs.stackexchange.com/questions/54571
How to show the beginning and end of a long function name in `which-key`?
2019-12-29T04:34:36.840
# Question Title: How to show the beginning and end of a long function name in `which-key`? By default, in `which-key`, descriptions that are longer than 27 characters are truncated, and `..` is added. How can I prevent this eliding and show the beginning and end of a long function name? # Answer There's a customizable variable you can set: `which-key-max-description-length` Setting it to `nil` will prevent it from truncating. From the `describe-variable` output: > Documentation: > > Truncate the description of keys to this length. Also adds "..". If nil, disable any truncation. ``` (setq which-key-max-description-length nil) ``` > 1 votes --- Tags: spacemacs, which-key ---
thread-54578
https://emacs.stackexchange.com/questions/54578
Rebind 'q' key in Emacs Dired to the command 'kill-this-buffer'
2019-12-29T18:08:27.557
# Question Title: Rebind 'q' key in Emacs Dired to the command 'kill-this-buffer' If I press 'q' in Dired this buries the current buffer. I would prefer to have 'q' kill the buffer. Hence, I would like to bind the command "kill-this-buffer" to 'q' in Dired. Is this possible and advisable? # Answer > 2 votes Is this possible?: Yes. Is this advisable?: Emacs is meant to be configurable and custom tailored to the needs of each particular user. There is no disadvantage that I am aware of to rebinding the "q" key to something that the O.P. finds more useful. ``` (require 'dired) (define-key dired-mode-map "q" 'kill-this-buffer) ``` --- Tags: key-bindings ---
thread-43944
https://emacs.stackexchange.com/questions/43944
Minibuffer for each window
2018-08-05T16:50:08.303
# Question Title: Minibuffer for each window Is there a way to have a minibuffer window for each window? I don't want recursive minibuffers, just one per window so that I don't have to look to the bottom of the screen when editing a window placed near the top. # Answer For Emacs 26 and later you can use emacs-maple-minibuffer or ivy-posframe if your are using ivy. Those packages let you configure to popup a minibuffer frame at any position, including the current window top/bottom. The docs of those packages describe how to set them up. > 4 votes # Answer If you don't mind using command-line emacs rather than the gui version you could consider using tmux panes rather than emacs windows. If you run emacs as a server you can then have an emacsclient running in as many tmux panes as you like. Each will have its own minibuffer display at the bottom. > 1 votes --- Tags: window, minibuffer, posframe ---
thread-54588
https://emacs.stackexchange.com/questions/54588
Regex search contains font-lock strings
2019-12-30T15:44:03.477
# Question Title: Regex search contains font-lock strings I am searching in a buffer for a regular expression by this snippet: ``` (setq jb-revision-version "\\([[:digit:]]+\\.?\\)") (setq jb-revision-string "\\(\\(Revision\\|Id\\): +\\)") (progn (save-excursion (goto-char (point-min)) (setq start (re-search-forward jb-revision-string) end (re-search-forward (concat jb-revision-version "+"))) (setq version (buffer-substring start end)))) ``` The result in variable version is this: ``` version #("0.1.2" 0 5 (face font-lock-comment-face fontified nil)) ``` What I want, is the pure string `"0.1.2"` in this case. Even if I insert `(font-lock-mode -1) ... (font-lock-mode 1)` in my above code, the result still contains some font-lock-info: ``` #("0.1.2" 0 5 (fontified nil)) ``` I haven't found any `font-lock-to-string` function, to get rid of that stuff. Neither did I find a command, to temporarily defontify the buffer before searching. I haven't found any hints in the Emacs, Emacs-Lisp or the Lisp-Introduction Info manuals. # Answer You'll want to use the function `buffer-substring-no-properties`. In the documentation for `M-x describe-function buffer-substring` it says this: > This function copies the text properties of that part of the buffer into the result string; if you don’t want the text properties, use `buffer-substring-no-properties` instead. > 2 votes --- Tags: regular-expressions, font-lock ---
thread-54556
https://emacs.stackexchange.com/questions/54556
Company-mode complete custom matches not necessarily prefix
2019-12-28T00:45:12.583
# Question Title: Company-mode complete custom matches not necessarily prefix If I type character `a`, can `completion-at-point` be used to show possible matches from this list `a ɑ æ ɐ ɑ̃`, even without matching a prefix? # Answer > 1 votes ``` (defconst sample-completions '(("a" "a" "ɑ" "æ" "ɐ" "ɑ̃") ("f" "o" "r"))) (defun company-sample-backend (command &optional arg &rest ignored) (interactive (list 'interactive)) (case command (interactive (company-begin-backend 'company-sample-backend)) (prefix (and (eq major-mode 'fundamental-mode) (company-grab-symbol))) (candidates (dolist (element sample-completions) (let ((head (car element))) (message "%s -%s" head arg) (if (string= head arg) (return element)))) ))) (add-to-list 'company-backends 'company-sample-backend) ``` Tweaked from here Enable `M-x company-mode` and `M-x fundamental-mode`, type `a` or `f` (the first element of list) and execute `company-complete` to get completion menu. How would I enable it only inside quotations? --- Tags: completion, company-mode ---
thread-54580
https://emacs.stackexchange.com/questions/54580
org-refile under a given heading
2019-12-29T22:35:58.170
# Question Title: org-refile under a given heading From org-refile to a known fixed location I have learned that the argument `RFLOC` looks like this: `'(heading file regular-expression position-of-target-heading)` I am trying to programmatically refile a subtree to become the child of a given heading. This is easy, manually, as long as I have `(file :maxlevel . 1)` as part of the `org-refile-targets`. With point on the heading of the subtree, I call `(org-refile nil nil ("Projects" "/tmp/projects.org" nil nil))`. This does refile to the `/tmp/projects.org` file but the refiled subtree becomes a sibling of `Projects`, not a child. How can I change my code so that the subtree properly moves under `Projects` ? # Answer Turns out org-mode provides a function to retrieve existing refile targets, which means if it's OK to set `org-refile-targets`, we can just let org-mode do the hard work of creating the `RFLOC` variable. This means the code I need is just the following. I go through the generated refile targets and I find the one heading that matches what I am looking for - in this case, a string that ends with `Projects` : ``` (find-if (lambda (refloc) (string-match ".*Projects" (car refloc))) (org-refile-get-targets)) ``` > 1 votes --- Tags: org-mode, org-refile ---
thread-54427
https://emacs.stackexchange.com/questions/54427
Failed to update packages getting error "gnutls-error #<process elpa.gnu.org> -50" on Windows 10
2019-12-17T16:57:13.823
# Question Title: Failed to update packages getting error "gnutls-error #<process elpa.gnu.org> -50" on Windows 10 When I run `package-refresh-contents` after running `toggle-debug-on-error` I get the following backtrace: ``` Debugger entered--Lisp error: (gnutls-error #<process elpa.gnu.org> -50) signal(gnutls-error (#<process elpa.gnu.org> -50)) package--download-one-archive(("gnu" . "https://elpa.gnu.org/packages/") "archive-contents" nil) package--download-and-read-archives(nil) package-refresh-contents() funcall-interactively(package-refresh-contents) call-interactively(package-refresh-contents record nil) command-execute(package-refresh-contents record) execute-extended-command(nil "package-refresh-contents" "package-ref") funcall-interactively(execute-extended-command nil "package-refresh-contents" "package-ref") call-interactively(execute-extended-command nil nil) command-execute(execute-extended-command) ``` Taking reference from the discussion found here I tried the following steps: Running `M-: (gnutls-available-p)` produces: ``` (ClientHello\ Padding Session\ Ticket Extended\ Master\ Secret Encrypt-then-MAC ClientHello\ Padding ALPN Heartbeat SRTP Signature\ Algorithms SRP Supported\ ECC\ Point\ Formats Negotiated\ Groups ...) ``` Running shell command `gnutls-cli -p 443 elpa.gnu.org` from Emacs produces: ``` 'gnutls-cli' is not recognized as an internal or external command, operable program or batch file. ``` Value of the variable `gnutls-trustfiles` is: ``` ("/etc/ssl/certs/ca-certificates.crt" "/etc/pki/tls/certs/ca-bundle.crt" "/etc/ssl/ca-bundle.pem" "/usr/ssl/certs/ca-bundle.crt" "/usr/local/share/certs/ca-root-nss.crt" "/etc/ssl/cert.pem") ``` Added paths of `ssl/cert.pem` and `ssl/certs/ca-bundle.crt` in Emacs' installation directory to the `gnutls-trustfiles` variable. In my case they're `c:/Program Files/emacs/ssl/cert.pem` and `c:/Program Files/emacs/ssl/certs/ca-bundle.crt`. Running `package-refresh-contents` after saving from the variable customization menu and running `eval-buffer` still produces the same error. Restarting Emacs also produces the same error. > On MS-Windows Emacs is supposed to use the system certificate store through MS-Windows native interfaces. No additional certificates in a separate bundle should be needed. So either your GnuTLS version has a bug of some kind, or your Windows system lacks some updates, or there's a genuine problem with ELPA's certificates. Emacs version is "GNU Emacs 26.3 (build 1, x86\_64-w64-mingw32) of 2019-08-29" # Answer > 1 votes I solved this by setting the variable `gnutls-algorithm-priority` to TLS-1.2. ``` (setq gnutls-algorithm-priority "NORMAL:-VERS-TLS1.2"). ``` It's because on Windows or Windows Subsystem Linux (WSL) the local gnutls-utils may not support TLS1.3. --- Tags: microsoft-windows, package-repositories, gnutls ---
thread-54602
https://emacs.stackexchange.com/questions/54602
How do I define a function to execute as a command with M-x?
2019-12-31T18:34:11.393
# Question Title: How do I define a function to execute as a command with M-x? I wish to `M-x my-func` and let my code run. This seems basic but where can I get more documentation about this, if possible inside emacs itself? # Answer > 0 votes A simple example: ``` (defun hello-world () "Insert \"Hello World!\"." (interactive) (insert "Hello World!\n")) ``` # Answer > 2 votes You need to distinguish between a common function and an interactive command. The latter is also a function, but with the addition of `(interactive)` to its body. You can run the latter, but not the former, by binding commands to keys or calling them by name via `M-x`. See the elisp manual links above more more details. --- Tags: functions, commands, interactive, m-x ---