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-54605
https://emacs.stackexchange.com/questions/54605
Is there a command to delete items from an org list?
2019-12-31T21:04:45.880
# Question Title: Is there a command to delete items from an org list? I have an `org-mode` list. ``` 1) John 2) Paul 3) Jimmy 4) George 5) Ringo ``` I've decided that item number three doesn't belong on this list. I can purge this item by removing it and then issuing `C-c C-c` and the list updates. ``` 1) John 2) Paul 3) George 4) Ringo ``` Is there a command to do this automatically? # Answer There is no command that I am aware of. But one can adapt the code of `org-move-item-down` to that task: ``` (defun org+-kill-list-item (&optional delete) "Kill list item at POINT. Delete if DELETE is non-nil. In interactive calls DELETE is the prefix arg." (interactive "P") (unless (org-at-item-p) (error "Not at an item")) (let* ((col (current-column)) (item (point-at-bol)) (struct (org-list-struct))) (org-list-send-item item (if delete 'delete 'kill) struct) (org-list-write-struct struct (org-list-parents-alist struct)) (org-list-repair) (org-move-to-column col))) ``` Tested with Emacs 26.3 and Org 9.2.3. > 4 votes --- Tags: org-mode ---
thread-54587
https://emacs.stackexchange.com/questions/54587
Cutting only after I paste
2019-12-30T11:47:01.947
# Question Title: Cutting only after I paste Is there a way to cut text in such a way that it is only removed from the buffer when I paste it somewhere else? I find myself often losing the text I had cut because, after I cut, I find out I need to do something else before I can paste the text where I want it. # Answer > 1 votes While it's certainly possible to program something to do that, there's no reason not to be able to yank back previously killed text even if you do some other edits after the kill. Note that emacs does not define *cut* and *paste* operations, but similar *killing* and *yanking*, as the "Killing and Moving Text" section of the manual states: > In Emacs, “killing” means erasing text and copying it into the “kill ring”. “Yanking” means bringing text from the kill ring back into the buffer. (Some applications use the terms “cutting” and “pasting” for similar operations.) The kill ring is so-named because it can be visualized as a set of blocks of text arranged in a ring, which you can access in cyclic order. Subsection "Yanking" defines: > “Yanking” means reinserting text previously killed. The usual way to move or copy text is to kill it and then yank it elsewhere. > > ‘C-y’ Yank the last kill into the buffer, at point (‘yank’). > > ‘M-y’ Replace the text just yanked with an earlier batch of killed text (‘yank-pop’). So what you can do is simply kill your text and yank it back (`C-y`) when you need it. If you have performed other kills in between, you can use `M-y` to replace the just yanked text with the previous in the kill ring. Repeating `M-y` will cycle through the kill ring, letting you find the wanted block of previously killed text. Of course the kill ring cannot grow indefinitely, but it defaults to storing a maximum of 60 kills, wich is most probably much more than you need, and can be changed: > The maximum number of entries in the kill ring is controlled by the variable ‘kill-ring-max’. The default is 60. If you make a new kill when this limit has been reached, Emacs makes room by deleting the oldest entry in the kill ring. # Answer > 0 votes As I said in my other answer, I don't think you should have to do that. But as I also said, this can be done, so here's a way to do it. It's rather straightforward and basically works for cut/pastes *inside the same buffer*. I haven't thought much about it, so there could be unexpected pitfalls. 1. Select the region you want to "cut late": set *mark* to one end and *point* to the other one and run `M-x jp/cut-late-select-region`, 2. Later, actually perform the cut/paste with `M-x jp/cut-late-do-cut-paste`. Of course, you can bind those two commands to whatever keys you like. ``` (defvar-local jp/cut-late1 nil "Cut late region beginning") (defvar-local jp/cut-late2 nil "Cut late region end") (defun jp/cut-late-select-region (beg end) "Select region to be cut/pasted by jp/cut-late-do-cut-paste." (interactive "r") (pop-mark) (setq jp/cut-late1 beg jp/cut-late2 end)) (defun jp/cut-late-do-cut-paste () "Cut and paste the region previously selected by jp/cut-late-select-region." (interactive) (if (and jp/cut-late1 jp/cut-late2) (progn (kill-region jp/cut-late1 jp/cut-late2) (yank) (setq jp/cut-late1 nil jp/cut-late2 nil)) (error "No cut late region defined in this buffer!"))) ``` --- Tags: kill-ring ---
thread-54615
https://emacs.stackexchange.com/questions/54615
wrong-type-argument listp eval
2020-01-01T19:29:29.553
# Question Title: wrong-type-argument listp eval I have a project which is centralized in a directory. The directory contains the `.dir-locals.el` file with the following content, just a defun: ``` (defun pr--narrow-buffer () "Narrow the current buffer from the start of the BODY section to the end of it." (interactive) (goto-char (point-min)) (setq v-beg (search-forward-regexp "^@BODY$")) (setq v-end (search-forward-regexp "^@/BODY$")) (narrow-to-region v-beg v-end)) ``` When I open a file in that directory I get the error: `Error reading dir-locals: (wrong-type-argument listp defun)` and the `pr-narrow-buffer` function cannot be used. Where am I wrong? # Answer A `.dir.locals.el` file is not supposed to contain arbitrary Lisp code, but a data structure resembling an alist where each key describes where to apply the settings to and the value which settings to apply. The above function definition doesn't fit that pattern and therefore throws an error. If there's no reason for that `.dir.locals.el` file to exist, just delete it and `M-x revert-buffer`. > 1 votes --- Tags: directory-local-variables ---
thread-36460
https://emacs.stackexchange.com/questions/36460
How to copy into mintty xterm clipboard from terminal emacs
2017-10-28T15:34:29.780
# Question Title: How to copy into mintty xterm clipboard from terminal emacs My host machine is Windows, but I'm working in Linux virtualbox machine over ssh from mintty in MSYS2 environment. As you may know, in mintty you copy via `C-insert` and paste via `C-S-insert`. When I `ssh` from mintty to my linux guest and open in it Emacs (`emacs-nox`) I can paste with default shortcut for mintty, it triggers Emacs function `xterm-paste`. My problem is that I can not find way to copy, there's no `xterm-copy` function at all. Also there's no X so I can not use xsel as I used before. So my question is how to copy to mintty clipboard from terminal emacs, is there any way? I always had problems with all those clipboard possibilities and can not figure it out. # Answer I have pretty similar settings as you do running emacs-nox on linux over SSH from a windows host with mintty. With the default settings, you can try holding shift and dragging the mouse over the region you want to copy and it will automatically copy to system clipboard. Some settings to verify that this will work as I described is to check mintty options: * Options-\>Mouse-\>Copy on select is checked. * Options-\>Mouse-\>Default click target: Application * Options-\>Mouse-\>Modifier for overriding default: Shift You can make this even easier by changing the default click target to Window meaning you can just drag the text you want to copy. This has some annoyances such as requiring me to toggle off line numbers and close other windows but it's the best solution I have found. > 1 votes --- Tags: terminal-emacs, copy-paste, clipboard ---
thread-14423
https://emacs.stackexchange.com/questions/14423
Include vendor's tags for ruby-mode and ggtags
2015-08-03T08:27:05.680
# Question Title: Include vendor's tags for ruby-mode and ggtags I'm trying to install and configure the `ggtags` package. Primarily, I use it for a ruby on rails projects (`enh-ruby-mode`). I can generate ctags including all vendor's files for my project with the following command: ``` ctags -R --languages=ruby --exclude=.git --exclude=log . $(bundle list --paths) ``` How can I configure `ggtags` package to achieve the same thing? I use OS X, with installed `exuberant-ctags` and `pygments` plugins. I think, I need to add some settings to `~/.globalrc` or to the project root's `gtags.conf`, but I don't know the settings. # Answer > 1 votes Here's how to use `global` installed from a Ubuntu repository. The version I've had in 6.6.3-2. First, copy the example config to your home directory. A commentary at its top makes it seem like this is unnecessary, but that's not true. The default config it has is much different, and doesn't recognize `.rb` files at all, AFAICT. ``` cat /usr/share/doc/global/examples/gtags.conf.gz | gzip -d >~/.globalrc ``` Second, you need to choose the underlying mechanism. Pygments sounds great, but it generates "other symbol" entries, not definitions, which is what we normally need. `universal-ctags` might be the best choice, but the version of Global seems to need recompiling to use it (either the apt or the snap version). `exuberant-ctags` works out of the box, though. The ancient version `5.9~svn20110310-1`. Now, as explained in the documentation and in this issue, you would normally need to run `gtags --gtagslabel=` in every gem directory: ``` for d in $(bundle list --paths); do if [ -d $d ]; then echo "$d"; (cd $d && find . -type f -name "*.rb" | gtags --gtagslabel=ctags -f -) fi done ``` The use of `find` here is to avoid including JS files, etc, mostly because of the minified assets. But you can create a smarter enumeration. To use the indexes from all these directories you need to set the env var `GTAGSLIBPATH` to the appropriate value during an Emacs session. Given that it's different for every project, and even changes over time, maybe the best approach is to manually call a command in the project directory that will do that for you. Here's one you can use: ``` (defun set-gtagslibpath-to-bundle-paths () (interactive) (let ((paths (split-string (with-output-to-string (process-file-shell-command "bundle list --paths" nil standard-output)) "\n"))) (while (and paths (string-match-p "\\`The dependency'" (car paths))) (setq paths (cdr paths))) (setenv "GTAGSLIBPATH" (mapconcat #'identity paths ":")))) ``` # Answer > 0 votes You can also generate the tags with the following command to command to be read by ggtags ``` gtags --gtagslabel=ctags ``` The above command should be helpful of any language not supported by gtags but supported by ctags. --- Tags: ruby-mode, ctags, gtags, enh-ruby-mode ---
thread-54612
https://emacs.stackexchange.com/questions/54612
Non-greedy regex not working
2020-01-01T16:03:25.053
# Question Title: Non-greedy regex not working I can't seem to get the non-greedy regex to work. # Sample String: ``` ABCD,E《F》、《GH》、《XYIJ》、《KL》、《MN》。 ``` # Regex Code: ``` 《.+?IJ》 ``` # Search Result: Because `.+?` is a non-greedy input, I was expecting the search to confine to the nearest `《》` pair, as shown below. The present output is no different from searching this: ``` 《.+IJ》 ``` Which essentially makes the non-greedy code redundant. # Expected Result: How should we get the non-greedy function to work as expected? # Answer > 5 votes The problem is not about using non-greedy matching. It is about which chars you're matching. Specifically, you want to match followed by any number of **non-** chars, followed by `IJ》`. This is a regexp that finds that: **`《[^《]+IJ》`**. This is a typical operation, for searching text that has paired delimiters. For example, you do the same thing when searching for a string: `"[^"]*"`. --- Or if you also want to deal with char escaping, `"\([^"]\|\\\(.\|\n\)\)*"`. That matches either any char other than `"` (**`[^"]`**), or (**`\|`**) a backslash (**`\\`**) followed by any character. The "any character" part is (**`\(.\|\n\)`**, that is, either any char except newline (**`.`**) or a newline char (**`\n`**). The final **`*`** says match zero or more such things. (And don't forget that if you use a regexp in a Lisp string you need to double the backslashes - not shown here. See Syntax for Strings.) # Answer > 2 votes I will give the same answer as @Drew, but phrased a little differently. Your expression 《.+IJ》will match the first 《, then will match the minimum number of characters (because of the ?) until the IJ》 sequence. You cannot use the "non-greediness" of the ? to un-match the first matching 《 in order to find a later one. An expression you can use to do what you want is what Drew said: 《\[^《\]+IJ》 This will match a 《, then at least one non-《 character, then IJ, then the closing 》. For this problem, you don't need a non-greedy modifier. --- Tags: regular-expressions, isearch, characters ---
thread-54624
https://emacs.stackexchange.com/questions/54624
Why funcall doesn't work from a closure
2020-01-02T05:11:59.387
# Question Title: Why funcall doesn't work from a closure I'm having difficulty to call a function passed as an argument. Why the following snippet doesn't work, and how can I make it work? `lexical-binding` is set to `t` ``` (defun on-success (data) (print "This works!") (print data)) (defun send-req (url callback) (request url :success (function* (lambda (&key data &allow-other-keys) (print (type-of callback) ; <- this prints 'symbol', without lexical binding it would be nil (funcall 'callback data))))) (defun foo () (send-req "https://google.com" 'on-success)) (foo) ``` # Answer Don't quote `callback` here: ``` (funcall 'callback data) ``` Quoted, you've said to call the function *named* "callback" (i.e. using the function slot of the `callback` symbol). What you want to do is call the function in the *value* of the `callback` argument: ``` (funcall callback data) ``` > 1 votes --- Tags: closures, funcall ---
thread-35548
https://emacs.stackexchange.com/questions/35548
Company mode does not complete automatically
2017-09-15T05:10:56.960
# Question Title: Company mode does not complete automatically So I have installed company mode with the backend company-gtags. This is what my init file looks like for company. ``` ;; == company-mode == (use-package company :diminish company-mode :ensure t :init (add-hook 'after-init-hook 'global-company-mode) :config (setq company-idle-delay 0.1 company-minimum-prefix-length 2 company-show-numbers t company-tooltip-limit 20 company-dabbrev-downcase nil company-backends '((company-gtags)) ) :bind ("s-;" . company-complete-common) ) ``` When I type part of a variable/function, and wait for company to autocomplete, nothing happens. Then when I press s-; I see the popup with completions. However, I would like for company to start the completion automatically and I am not sure what I am missing. Thanks! # Answer The configuration looks all right. There could be something wrong with your gtags setting. For what it's worth, I think you should use `company-complete` instead. `company-complete`: > Insert the common part of all candidates or the current selection. The first time this is called, the common part is inserted, the **second time**, or when the selection has been changed, the selected candidate is inserted. > 1 votes # Answer I had the same problem and found out that `company-begin-commands` was screwed by some configuration I copied from sombody else. The value defines when company completion should be triggered. The default for the value is: ``` '(self-insert-command org-self-insert-command orgtbl-self-insert-command c-scope-operator c-electric-colon c-electric-lt-gt c-electric-slash) ``` Make sure this variable contains at least `self-insert-command` so that a popup can be triggered by normal typing. > 1 votes # Answer `company` should work out of box if you: * build tags using GNU Global * set up environment variable `GTAGSLIBPATH` See https://www.gnu.org/software/global/manual/global.html > 0 votes --- Tags: company-mode ---
thread-54600
https://emacs.stackexchange.com/questions/54600
Creating ctag DB gives "permission denied" error on git-bash (MS Windows)
2019-12-31T09:43:39.913
# Question Title: Creating ctag DB gives "permission denied" error on git-bash (MS Windows) I am a Linux user (world was pretty neat; less to no headache)-- I've been using vim with cscope to wade through huge code-base....... And for some reason, now I have to use windows machine, here are the things I do have on my PC `git-bash`; downloaded Emacs (I start to love it); and within the Emacs package has `ctags.exe`. So, I am trying to create the tag file from git-bash ``` ~/Downloads/emacs-26.3-x86_64/bin/ctags.exe -R * ``` The tag file gets created, but it skips the source code present in the directories, after running the above command I get ``` bin: Permission denied contrib: Permission denied crypto: Permission denied doc: Permission denied etc: Permission denied games: Permission denied gnu: Permission denied include: Permission denied initrd: Permission denied lib: Permission denied libexec: Permission denied nrelease: Permission denied sbin: Permission denied ``` Really not sure what I am doing wrong here-- even ran `git-bash` as an administrator, tried creating tag file from `cmd` by running it as an admin, yet no luck-- same issue. What can I do to fix this? # Answer > 0 votes I got the answer. Thanks to `Eli Zaretskii<eliz@gnu.org>`, Gist: ctags on windows won't work on directories. > You are invoking 'ctags' incorrectly: it needs a list of file names to open and scan. You used the wildcard "\*" which matches all the files, including the directories, and 'ctags' on Windows cannot open and scan directories, only files. > > What you probably want is this instead: > > $ find . -name '*.\[chm\]' -o -name '*.el' | ~/Downloads/emacs-26.3-x86\_64/bin/ctags - > > (This assumes you have a GNU 'find' command reachable from the git-bash where you run this.) Also found this https://www.emacswiki.org/emacs/BuildTags manual, which I ignored initially, because I though when used the switch `-R` * ctags can recur on directories and build DB out of files, but it wasn't the case and the error it reported `Permission denied` also added more confusions to the puzzle. --- Tags: microsoft-windows, bash, ctags ---
thread-45086
https://emacs.stackexchange.com/questions/45086
Automatically `expand-abbrev` with `org-meta-return` and `org-insert-heading-respect-content`
2018-10-01T15:18:12.510
# Question Title: Automatically `expand-abbrev` with `org-meta-return` and `org-insert-heading-respect-content` I take notes with `org-mode` and `abbrev-mode`. Normally pressing `SPC` or `RET` leads to any abbreviations at point expanding before the edit is made. This doesn't happen when I use `C-RET` (`org-insert-heading-respect-content`) or `M-RET` (`org-meta-return`). Is there a way to make this happen simpler than advising those functions? # Answer A solution with advice is: ``` (defun expand-abbrev-eat-args (&rest args) "Call `expand-abbrev', ignoring ARGS." (expand-abbrev)) (advice-add 'org-insert-heading :before #'expand-abbrev-eat-args) (advice-add 'org-table-wrap-region :before #'expand-abbrev-eat-args) (advice-add 'org-insert-item :before #'expand-abbrev-eat-args) ``` > 0 votes # Answer Adding this in your `init.el` should do the trick: ``` (advice-add 'org-meta-return :before #'expand-abbrev) (advice-add 'org-meta-return :before #'org-insert-heading-respect-content) ``` > 0 votes --- Tags: org-mode, abbrev ---
thread-38453
https://emacs.stackexchange.com/questions/38453
json-readtable-error during org-capture
2018-01-30T01:25:44.437
# Question Title: json-readtable-error during org-capture This problem only arose today and I haven't really changed anything substantial in my init.el so I am sure what the source of the error is. Essentially, when running `org-capture` (and also during startup) I get `(json-readtable-error)`. When I set `debug-on-error` to be true, but could not find anything useful (debugger output is below). ``` Debugger entered--Lisp error: (error "Capture abort: (json-readtable-error)") signal(error ("Capture abort: (json-readtable-error)")) error("Capture abort: %s" (json-readtable-error)) #[512 "\203� \306=\203�\307\310\232!\311\232\203�\312 \207\313\232\203\"�\314 \207p\315\303!\2034�\2034�\316\f\317\"\202A�\3201?�\321\322!0\202A�\210\322 \206H�\323!\322@\206W�\324 \205W�`\325 {\262\211;\203f�\326\327G\330$\210;\203t�\326\327G\331$\210\332\232\203\200�\333\334!\202\222\335\232\203\214�\336\337!\202\222\340!\210\341 \210\342\343\344\345!\206\253�\346\347!\205\253�\350A\"@\351\345\n!\205\271�\352\345!!\317\n\353\n\354\355 \356\n\206\311�\357 &\210\360 \210\3611\334�\342\362\363 \"0\202\354�\364\365!\203\346�\366\365!\210\367\370\"\262\210\371\372!B\327\232\203\375�\373 \202\222\3741 \375\371\376!@\377=!0\202>\201E�p!\203'\201F�\201G�\201H� \"\203'\366p!\210\201I�\371\354!!\210\367\201J�\371\201K�!A@#\262\210\201L�\201M�!\203\206\371\201N�!\203\206\201O�1\201\201P� \203j\342\201Q�\201R�C!\"\210\201S� \210\201T�\201D�!\210\201U�\211D0\202\205\210\202\206\210\371\201V�!\205\222\201W� \207" [org-capture-use-agenda-date major-mode org-overriding-default-time org-capture-link-is-already-stored org-store-link-plist org-capture-entry org-agenda-mode org-get-cursor-date 1 (4) org-capture-goto-target (16) org-capture-goto-last-stored boundp plist-get :annotation (error) org-store-link nil org-capture-select-template org-region-active-p mark remove-text-properties 0 (read-only t) (read-only t) "C" customize-variable org-capture-templates "q" user-error "Abort" org-capture-set-plist org-capture-get-template org-capture-put :original-buffer :original-file buffer-file-name featurep dired rassq :original-file-nondirectory file-name-nondirectory :initial :return-to-wconf current-window-configuration :default-time org-current-time org-capture-set-target-location (error quit) ...] 21 ("/Users/bibekpokharel/.emacs.d/elpa/org-20180129/org-capture.elc" . 23542) "P"](nil nil) ad-Advice-org-capture(#[512 "\203� \306=\203�\307\310\232!\311\232\203�\312 \207\313\232\203\"�\314 \207p\315\303!\2034�\2034�\316\f\317\"\202A�\3201?�\321\322!0\202A�\210\322 \206H�\323!\322@\206W�\324 \205W�`\325 {\262\211;\203f�\326\327G\330$\210;\203t�\326\327G\331$\210\332\232\203\200�\333\334!\202\222\335\232\203\214�\336\337!\202\222\340!\210\341 \210\342\343\344\345!\206\253�\346\347!\205\253�\350A\"@\351\345\n!\205\271�\352\345!!\317\n\353\n\354\355 \356\n\206\311�\357 &\210\360 \210\3611\334�\342\362\363 \"0\202\354�\364\365!\203\346�\366\365!\210\367\370\"\262\210\371\372!B\327\232\203\375�\373 \202\222\3741 \375\371\376!@\377=!0\202>\201E�p!\203'\201F�\201G�\201H� \"\203'\366p!\210\201I�\371\354!!\210\367\201J�\371\201K�!A@#\262\210\201L�\201M�!\203\206\371\201N�!\203\206\201O�1\201\201P� \203j\342\201Q�\201R�C!\"\210\201S� \210\201T�\201D�!\210\201U�\211D0\202\205\210\202\206\210\371\201V�!\205\222\201W� \207" [org-capture-use-agenda-date major-mode org-overriding-default-time org-capture-link-is-already-stored org-store-link-plist org-capture-entry org-agenda-mode org-get-cursor-date 1 (4) org-capture-goto-target (16) org-capture-goto-last-stored boundp plist-get :annotation (error) org-store-link nil org-capture-select-template org-region-active-p mark remove-text-properties 0 (read-only t) (read-only t) "C" customize-variable org-capture-templates "q" user-error "Abort" org-capture-set-plist org-capture-get-template org-capture-put :original-buffer :original-file buffer-file-name featurep dired rassq :original-file-nondirectory file-name-nondirectory :initial :return-to-wconf current-window-configuration :default-time org-current-time org-capture-set-target-location (error quit) ...] 21 ("/Users/bibekpokharel/.emacs.d/elpa/org-20180129/org-capture.elc" . 23542) "P"] nil) apply(ad-Advice-org-capture #[512 "\203� \306=\203�\307\310\232!\311\232\203�\312 \207\313\232\203\"�\314 \207p\315\303!\2034�\2034�\316\f\317\"\202A�\3201?�\321\322!0\202A�\210\322 \206H�\323!\322@\206W�\324 \205W�`\325 {\262\211;\203f�\326\327G\330$\210;\203t�\326\327G\331$\210\332\232\203\200�\333\334!\202\222\335\232\203\214�\336\337!\202\222\340!\210\341 \210\342\343\344\345!\206\253�\346\347!\205\253�\350A\"@\351\345\n!\205\271�\352\345!!\317\n\353\n\354\355 \356\n\206\311�\357 &\210\360 \210\3611\334�\342\362\363 \"0\202\354�\364\365!\203\346�\366\365!\210\367\370\"\262\210\371\372!B\327\232\203\375�\373 \202\222\3741 \375\371\376!@\377=!0\202>\201E�p!\203'\201F�\201G�\201H� \"\203'\366p!\210\201I�\371\354!!\210\367\201J�\371\201K�!A@#\262\210\201L�\201M�!\203\206\371\201N�!\203\206\201O�1\201\201P� \203j\342\201Q�\201R�C!\"\210\201S� \210\201T�\201D�!\210\201U�\211D0\202\205\210\202\206\210\371\201V�!\205\222\201W� \207" [org-capture-use-agenda-date major-mode org-overriding-default-time org-capture-link-is-already-stored org-store-link-plist org-capture-entry org-agenda-mode org-get-cursor-date 1 (4) org-capture-goto-target (16) org-capture-goto-last-stored boundp plist-get :annotation (error) org-store-link nil org-capture-select-template org-region-active-p mark remove-text-properties 0 (read-only t) (read-only t) "C" customize-variable org-capture-templates "q" user-error "Abort" org-capture-set-plist org-capture-get-template org-capture-put :original-buffer :original-file buffer-file-name featurep dired rassq :original-file-nondirectory file-name-nondirectory :initial :return-to-wconf current-window-configuration :default-time org-current-time org-capture-set-target-location (error quit) ...] 21 ("/Users/bibekpokharel/.emacs.d/elpa/org-20180129/org-capture.elc" . 23542) "P"] nil) org-capture(nil) funcall-interactively(org-capture nil) call-interactively(org-capture nil nil) command-execute(org-capture) ``` # Answer I received the exact same error on a fresh Ubuntu install using Emacs 26.3. In my case it was related to the `ob-ipython` packet, which requires `ipython` and `jupyter` to be installed, which I hadn't come around to doing yet. After a `sudo apt install ipython jupyter` the error was gone. > 2 votes # Answer For anyone who is curious, adding the following code in the `init.el` solved the issue. Turns out Rmacs was not being able to load JSON setup because it was looking in the wrong folder. I also had to install the package `exec-path-from-shell`. ``` (when (memq window-system '(mac ns x)) (exec-path-from-shell-initialize)) ``` > 1 votes --- Tags: debugging, org-capture, json ---
thread-54596
https://emacs.stackexchange.com/questions/54596
mu4e-xxxx-folder evaluates to nil
2019-12-31T06:50:26.237
# Question Title: mu4e-xxxx-folder evaluates to nil I'm trying to abstract elisp code for my dynamic folders on mu4e but for some reason executing a command fails with `mu4e-error: [mu4e] mu4e-xxxx-folder evaluates to nil`, here is the current code: ``` (setf shackra/mu4e-maildir-dirs '("yahoo" "kue" "gmail")) (defun shackra/mu4e-find-maildir (msg place &optional alternative) (if msg (let ((msg-maildir (mu4e-message-field msg :maildir))) (dolist (maildir shackra/mu4e-maildir-dirs) (when (string-match-p (concat "^/" maildir) msg-maildir) (concat "/" maildir "/" place)))) (if alternative alternative (dolist (maildir shackra/mu4e-maildir-dirs) (when (string-match-p maildir user-mail-address) (concat "/" maildir "/" place)))))) (setf mu4e-sent-folder ;; carpeta de enviados (lambda (msg) (shackra/mu4e-find-maildir msg "Sent"))) (setf mu4e-drafts-folder ;; carpeta de borradores (lambda (msg) (shackra/mu4e-find-maildir msg "Drafts"))) (setf mu4e-trash-folder ;; carpeta de correo borrado (lambda (msg) (shackra/mu4e-find-maildir msg "Trash" "/gmail/Trash"))) (setf mu4e-refile-folder ;; carpeta de correo salvado (lambda (msg) (shackra/mu4e-find-maildir msg "Archive" "/gmail/Archive"))) ``` # Answer > 0 votes Turns out I was getting my own code wrong. My assumption was that the execution flow would stop inside the `when` clause, in reality code stops at the end of the function definition, thus returning `nil` I changed my function to this: ``` (setf shackra/mu4e-maildir-dirs '("yahoo" "kue" "gmail")) (defun shackra-mu4e-get-maildir (maildir place) "Retorna ubicación para mover el mensaje por MAILDIR a otro lugar PLACE." (let ((maildir-path)) (dolist (dir shackra/mu4e-maildir-dirs) (when (string-match-p (concat "^/" dir) maildir) (setf maildir-path (concat "/" dir "/" place)))) (unless maildir-path (setf maildir-path (mu4e-ask-maildir-check-exists "Mover el mensaje al maildir: "))) maildir-path)) ``` and used it like this: ``` (setf mu4e-sent-folder ;; carpeta de enviados (lambda (msg) (shackra-mu4e-get-maildir (or (mu4e-message-field msg :maildir) "") "Sent"))) (setf mu4e-drafts-folder ;; carpeta de borradores (lambda (msg) (shackra-mu4e-get-maildir (or (mu4e-message-field msg :maildir) "") "Drafts"))) (setf mu4e-trash-folder ;; carpeta de correo borrado (lambda (msg) (shackra-mu4e-get-maildir (or (mu4e-message-field msg :maildir) "") "Trash"))) (setf mu4e-refile-folder ;; carpeta de correo salvado (lambda (msg) (shackra-mu4e-get-maildir (or (mu4e-message-field msg :maildir) "") "Archive"))) ``` --- Tags: mu4e ---
thread-54623
https://emacs.stackexchange.com/questions/54623
How to know if the buffer returned by a function is newly opened?
2020-01-02T04:34:18.763
# Question Title: How to know if the buffer returned by a function is newly opened? I'm using a command that reverts a diff chunk in a buffer (linked question), however I don't know if the buffer is newly opened - or if an existing buffer is used. While I could make a list of all buffers, then check if that buffer is in the original list, is there a better way to know if the buffer from a function is newly created or not? # Answer > 3 votes *"Newly opened"* can only mean relative to a state when the buffer didn't exist. Every time prior to when it came into being it didn't exist. So yes, you need to take a snapshot of the list of existing buffers at some point prior to creating the new buffer, in order to later check whether the buffer is "new" - compared to that prior snapshot moment. Save the value of `buffer-list` in a variable (e.g. `let`-bound), and then, later, check whether the buffer in question is in that previous snapshot. If it is, then it's not new; if it isn't, then it's new. --- If you're only interested in certain kinds of buffers then you can filter `buffer-list`, to make your lookup quicker. --- Tags: buffers ---
thread-40924
https://emacs.stackexchange.com/questions/40924
Org mode subtitle not being exported to pdf
2018-04-09T14:07:51.130
# Question Title: Org mode subtitle not being exported to pdf ``` #+TITLE: My title #+SUBTITLE: My subtitle * Blah blah blah ``` My subtitle isn't being exported, anyone know why? LaTeX export: https://pastebin.com/Wg2gVS12 # Answer > 3 votes <sup>\[Collecting the comment interactions into an answer; thanks to @dangorn for discovering this solution\]</sup> You are using an outdated version of Org that did not yet support `#+SUBTITLE` (if you check the value of `org-latex-subtitle-format` with `C-h v org-latex-subtitle-format RET` it will be undefined). To fix, update your Org Mode (see MELPA and `use-package`). --- Tags: org-mode, latex ---
thread-30188
https://emacs.stackexchange.com/questions/30188
Show only today's tasks in org-agenda
2017-01-24T22:49:17.407
# Question Title: Show only today's tasks in org-agenda I am using org-mode to organize my life. I got used to planning with **DEADLINE**. Additionally, I am using **Effort** property to predict how much effort that I have to show to finish all tasks. **org-agenda-columns C-c C-x C-c** provide good interface to estimate effort in agenda. *org-agenda* shows today tasks, but it also shows future and overdue tasks at the same view like below in the picture. So, it makes really hard to understand how many hours that I have to spend today because it sums automatically all efforts. I prepared small customized view to show just today tasks as I wanted, but these tasks are filtered with kind of regexp, so that reason, it's not possible to see next or previous days by using **org-agenda-earlier** and **org-agenda-later** **TLDR;** Is there any option to show only today's(not overdue and future) tasks in org-agenda? **Things that can help** Example input: ``` * Main ** Today 1st task DEADLINE: <2017-01-25 Wed> :PROPERTIES: :EFFORT: 01:00 :END: ** Today 2nd task DEADLINE: <2017-01-25 Wed> :PROPERTIES: :EFFORT: 00:30 :END: ** Yesterday Overdue DEADLINE: <2017-01-24 Tue> :PROPERTIES: :EFFORT: 02:00 :END: ** Future task DEADLINE: <2017-01-30 Mon> :PROPERTIES: :EFFORT: 00:30 :END: ``` **My non-interactive filter** that shows todays tasks ``` (setq org-agenda-custom-commands '(("d" "daily" tags "DEADLINE>=\"<today>\"&DEADLINE<=\"<now>\"" ((org-agenda-sorting-strategy '(todo-state-down))) (org-agenda-overriding-header "TODAY tasks")))) ``` Example **Interactive agenda-view** that shows just A priority ``` (add-to-list 'org-agenda-custom-commands '("f" agenda "" ((org-agenda-skip-function (lambda nil (org-agenda-skip-entry-if (quote notregexp) "\\=.*\\[#A\\]"))) (org-agenda-ndays 0) (org-agenda-overriding-header "Today's Priority #A tasks: ")))) ``` # Answer > 8 votes **COMPATIBLE WITH ORG-MODE 9.0.3** The function `org-agenda-skip-deadline-if-not-today` is designed to be used in conjunction with the `org-agenda-skip-function` and an `agenda` entry in the `org-agenda-custom-commands` that contains *proposed* entries such as: ``` (add-to-list 'org-agenda-custom-commands '("b" agenda "Today's Deadlines" ((org-agenda-span 'day) (org-agenda-skip-function '(org-agenda-skip-deadline-if-not-today)) (org-agenda-entry-types '(:deadline)) (org-agenda-overriding-header "Today's Deadlines ")))) ``` ``` (defun org-agenda-skip-deadline-if-not-today () "If this function returns nil, the current match should not be skipped. Otherwise, the function must return a position from where the search should be continued." (ignore-errors (let ((subtree-end (save-excursion (org-end-of-subtree t))) (deadline-day (time-to-days (org-time-string-to-time (org-entry-get nil "DEADLINE")))) (now (time-to-days (current-time)))) (and deadline-day (not (= deadline-day now)) subtree-end)))) ``` --- **COMPATIBLE WITH ORG-MODE 8.2.10** Emacs version 25.1 ships with `org-mode` version 8.2.10. Within said release, there is an undocumented dynamically scoped variable called `org-agenda-only-exact-dates`, which can be used to accomplish the goal of the original poster. Within the `org-agenda-custom-commands`, set `(org-agenda-only-exact-dates t)`. `org-agenda-only-exact-dates` is used by `org-agenda-get-deadlines`, which is one of the functions responsible for the behavior the original poster wishes to customize. It is also used by `org-agenda-get-scheduled`. The function `org-timeline` is what sets this dynamically scoped variable to `t`. This answer (above) takes advantage of said variable. **CAVEAT**: Many people are using the latest release of `org-mode` which does not ship with Emacs -- e.g., `org-mode` version 9.0.4. I grepped 9.0.3 and did not see `org-agenda-only-exact-dates` used within either `org-agenda-get-deadlines` or `org-agenda-get-scheduled`. I'm not sure why the `org-mode` team removed that variable or whether something else replaced its functionality in the latest release. To the extent that another forum participant would like to research the code of 9.0.4 and post an alternative answer that works with the latest release, please feel free to do so. # Answer > 4 votes I am answering my question that I asked long time ago. A new package which name orq-ql is also lead us to desired situation. Additionally provides many like filtering, ordering etc on-the-fly. You can use code block at below, also interactive `M-x org-ql-view` allow us some default filtering methods. ``` (org-ql-view "Today") ``` --- Tags: org-mode, org-agenda, org-ql ---
thread-54634
https://emacs.stackexchange.com/questions/54634
How to save and execute a python file?
2020-01-02T17:04:01.193
# Question Title: How to save and execute a python file? I do not prefer `python-mode`. I would like a generic way so that I can understand emacs. I wish the file be saved and `python file` command then be run as if in a shell. # Answer > 1 votes Use `M-!` (`M-x shell-command`) if you want to run a shell command, e.g. `python file.py` and print the output in a new buffer (`*Shell Command Output*`). That does not open a shell in a new buffer. Use `M-x shell` to run a shell in a new buffer as pointed by @NickD. # Answer > 1 votes You could use `M-x` `compile` with an appropriate `compile-command` value. e.g. as a file-local variable: ``` # -*- compile-command: "python file.py"; -*- ``` Emacs will prompt you to save (or not) the file before running the command. --- Tags: python, shell, commands ---
thread-54635
https://emacs.stackexchange.com/questions/54635
How to hook a TAG file with Emacs (Git-bash / windows)
2020-01-02T18:45:20.273
# Question Title: How to hook a TAG file with Emacs (Git-bash / windows) I've successfully created a Tag file and could wade through the code using keys like `M-,`, but every time I need to choose the tag file for searching, so, I am looking for a way to hook the tag file I created with Emacs , found one reference, but not sure how to execute it on git-bash or how execute it on Emacs command-line, Helps appreciated....... https://www.gnu.org/software/emacs/manual/html\_node/emacs/Select-Tags-Table.html # Answer > 0 votes `M-,` executes `xref-pop-marker-stacker` it just go back the position before you start code navigation. `M-.` executes `xref-find-definitions` which does the code navigation thing. So your question is not clear what exactly you want to achieve. `M-,` will always be successful since you already finished code navigation and the original start position is "marked". You need only set global variable `tag-file-name` or `tags-table-list` once. And you will never be asked to set either of them again unless: * for some reason, you set the above flags as buffer local variable directly or indirectly. Besides, only one of the above two variables should be set. It's better to run `C-h v tag-file-name` or check `tags-table-list` before you running `xref-find-definitions`, make sure it's not empty. * The current file is binding a different `xref-backend`. Eval expression `(xref-find-backend)` and make sure it's `etags` before running `xref-find-definition` I suggest you using `counsel-etags` for code navigation. It works out of box and has many improvements. For example, it can use ctags to update tags file automatically, and ctags is running as background process which does block the Emacs UI interaction. Here is function to update tags file, ``` (defun counsel-etags-async-shell-command (command tags-file) "Execute string COMMAND and create TAGS-FILE asynchronously." (let* ((proc (start-process "Shell" nil shell-file-name shell-command-switch command))) (set-process-sentinel proc `(lambda (process signal) (let* ((status (process-status process))) (when (memq status '(exit signal)) (cond ((string= (substring signal 0 -1) "finished") (let* ((cmd (car (cdr (cdr (process-command process)))))) (if counsel-etags-debug (message "`%s` executed." cmd)) ;; reload tags-file (when (and ,tags-file (file-exists-p ,tags-file)) (run-hook-with-args 'counsel-etags-after-update-tags-hook ,tags-file) (message "Tags file %s was created." ,tags-file)))) (t (message "Failed to create tags file.\nerror=%s\ncommand=%s" signal ,command))))))))) ``` As you can see, the code is not simple. There are lots of technical know how. Since I've already provided a robust solution (Yes, I'm the developer), don't waste time to re-invent the wheel. --- Tags: tags, etags ---
thread-47018
https://emacs.stackexchange.com/questions/47018
emacs-w3m has quit working for me, but not other users
2019-01-09T21:12:58.560
# Question Title: emacs-w3m has quit working for me, but not other users GNU Emacs Version 26.1 and emacs-w3m version 1.4.631, running on Fedora 29. emacs-w3m seems to have quit working for me. More precisely: 1. I issue the command "emacs -q" 2. I do (set debug-on-error t) in the *scratch* buffer. 3. I do (w3m) in the scratch buffer. The result is the backtrace at the end of this posting. Oddly enough, other users do not encounter this problem: w3m works as expected. Suggestions? Here's the backtrace: Debugger entered--Lisp error: (wrong-type-argument stringp nil) string-match("/" nil 0) split-string(nil "/") mailcap-mime-info("desc=\\"adobe") byte-code("\306\307\010!\310\211\211\211\211\211\211\031\032\033\034\035\036\031\036\032\036\033\036\034\016\033\211A\026\033\242\211\026\032\203\206\0\016\032@\026\031\016\032A\025\016\031G\311U\204\030\0\016\031C\024\312\015\016\033\\"\211\023\203b\0\013@G\311U\204X\0\013@\f\235\204X\0\013@\fB\024\313\013\016\033\\"\026\033\202:\0\314\015!\022\015\fA\203r\0\315\f!\202v\0\316\016\031!\317P\n;\205~\0\n\310F\011B\021\202\030\0\016\035\310\036\036\211\036\037\203\353\0\016\037@\211\026\036A\310\036 \211\036\037\203\341\0\016\037@\026 \320\321\016 @\\"\204\330\0\305\016 A\236A\025\302\016 A\236A\022\320\322\015\\"\204\330\0\323\015\011\\"\204\330\0\015\310\n;\205\323\0\n\310F\011B\021\016\037A\211\026\037\204\241\0\*\016\037A\211\026\037\204\221\0\*\011\310\036\032\211\036\037\203L\001\016\037@\211\026\032AA@\211\022\203C\001\324\n!\310\211\022\036!\211\036\037\203:\001\016\037@\211\026!\325\230\203!\001\326\202.\001\016!\327\230\203,\001\330\202.\001\016!\nB\022\016\037A\211\026\037\204\022\001\*\016\032AA\n\237\240\210\016\037A\211\026\037\204\366\0\*\016\034\310\036\032\211\036\037\203\177\001\016\037@\026\032\323\016\032@\011\\"\211\023\203q\001\013\016\032A\241\210\202v\001\016\032\011B\021\016\037A\211\026\037\204X\001\*\011\237.\011\207" \[mailcap-mime-extensions rest viewer tem exts type (("text/sgml" "\\.sgml?\\'" nil "text/plain") ("text/xml" "\\.xml\\'" nil "text/plain") ("text/x-markdown" "\\.md\\'" nil w3m-prepare-markdown-content) ("application/xml" "\\.xml\\'" nil w3m-detect-xml-type) ("application/rdf+xml" "\\.rdf\\'" nil "text/plain") ("application/rss+xml" "\\.rss\\'" nil "text/plain") ("application/xhtml+xml" nil nil "text/html") ("application/x-bzip2" "\\.bz2\\'" nil nil nil) ("application/x-gzip" "\\.gz\\'" nil nil nil)) copy-sequence nil 0 rassoc delq mailcap-mime-info regexp-opt regexp-quote "\\'" string-match "\\\`\\.\\\*\\'" "/\\\*\\'" assoc split-string "%s" file "%u" url ext elem extensions additions mailcap-mime-data major --dolist-tail-- minor v\] 10) (defvar w3m-content-type-alist (byte-code "\306\307\010!\310\211\211\211\211\211\211\031\032\033\034\035\036\031\036\032\036\033\036\034\016\033\211A\026\033\242\211\026\032\203\206\0\016\032@\026\031\016\032A\025\016\031G\311U\204\030\0\016\031C\024\312\015\016\033\\"\211\023\203b\0\013@G\311U\204X\0\013@\f\235\204X\0\013@\fB\024\313\013\016\033\\"\026\033\202:\0\314\015!\022\015\fA\203r\0\315\f!\202v\0\316\016\031!\317P\n;\205~\0\n\310F\011B\021\202\030\0\016\035\310\036\036\211\036\037\203\353\0\016\037@\211\026\036A\310\036 \211\036\037\203\341\0\016\037@\026 \320\321\016 @\\"\204\330\0\305\016 A\236A\025\302\016 A\236A\022\320\322\015\\"\204\330\0\323\015\011\\"\204\330\0\015\310\n;\205\323\0\n\310F\011B\021\016\037A\211\026\037\204\241\0\*\016\037A\211\026\037\204\221\0\*\011\310\036\032\211\036\037\203L\001\016\037@\211\026\032AA@\211\022\203C\001\324\n!\310\211\022\036!\211\036\037\203:\001\016\037@\211\026!\325\230\203!\001\326\202.\001\016!\327\230\203,\001\330\202.\001\016!\nB\022\016\037A\211\026\037\204\022\001\*\016\032AA\n\237\240\210\016\037A\211\026\037\204\366\0\*\016\034\310\036\032\211\036\037\203\177\001\016\037@\026\032\323\016\032@\011\\"\211\023\203q\001\013\016\032A\241\210\202v\001\016\032\011B\021\016\037A\211\026\037\204X\001\*\011\237.\011\207" \[mailcap-mime-extensions rest viewer tem exts type (("text/sgml" "\\.sgml?\\'" nil "text/plain") ("text/xml" "\\.xml\\'" nil "text/plain") ("text/x-markdown" "\\.md\\'" nil w3m-prepare-markdown-content) ("application/xml" "\\.xml\\'" nil w3m-detect-xml-type) ("application/rdf+xml" "\\.rdf\\'" nil "text/plain") ("application/rss+xml" "\\.rss\\'" nil "text/plain") ("application/xhtml+xml" nil nil "text/html") ("application/x-bzip2" "\\.bz2\\'" nil nil nil) ("application/x-gzip" "\\.gz\\'" nil nil nil)) copy-sequence nil 0 rassoc delq mailcap-mime-info regexp-opt regexp-quote "\\'" string-match "\\\`\\.\\\*\\'" "/\\\*\\'" assoc split-string "%s" file "%u" url ext elem extensions additions mailcap-mime-data major --dolist-tail-- minor v\] 10) ("/usr/share/emacs/site-lisp/w3m/w3m.elc" . -37893)) autoload-do-load((autoload "w3m" ("/usr/share/emacs/site-lisp/w3m/w3m-load.elc" . 16159) t nil) w3m) command-execute(w3m record) execute-extended-command(nil "w3m" "w3m") funcall-interactively(execute-extended-command nil "w3m" "w3m") call-interactively(execute-extended-command nil nil) command-execute(execute-extended-command) # Answer Check the `.mime.types` file in your home directory. You've probably got a line that looks like: ``` desc="adobe ..." \ ``` and it seems w3m calls something that reads that file (among others) and adds data to `mailcap-mime-extensions`. In the case of lines like the above, it seems like it puts something into the variable that causes the crash you see. In my case I had a bunch of similar lines from software I don't use anymore and removing them fixed my (similar) crash. > 1 votes --- Tags: w3m ---
thread-477
https://emacs.stackexchange.com/questions/477
How do I automatically save org-mode buffers?
2014-09-29T23:27:40.267
# Question Title: How do I automatically save org-mode buffers? I regularly use `org-mode` and the agenda to keep track of my to-do list. Since I use Dropbox to sync my list, I need the same tasks to be available on all computers. Sometimes during the course of my cleanup I will forget to save my changes, leaving emacs open at home when I go into the office (thus I am not prompted to save on closing emacs). How can I automatically save changes to `*.org` agenda buffers that are modified through the agenda? EDIT: To clarify, I use the agenda view of my tasks to show me an overview. From that view, I can change the status of tasks. Additionally, I use remember-mode to add new tasks, which can then be recategorized in the agenda view. These changes in the agenda result in modified org-mode agenda buffers, which must then be saved. When these changes are made, I would like the buffers to be saved automatically. # Answer > 16 votes A quick hack, which I'm not sure will satisfy your use-case would be ``` (add-hook 'org-agenda-mode-hook (lambda () (add-hook 'auto-save-hook 'org-save-all-org-buffers nil t) (auto-save-mode))) ``` As long as the Org agenda buffer is open, all org buffers will be saved periodically (it equivalent to what would happen if `s` was pressed regularly from the agenda view). This is somewhat abusing `auto-save-mode` in that the agenda buffer itself doesn't make much sense as far as `auto-save` is concerned. If you happen to use that hack, you'd better make sure that backup files are kept for all your .org files, to be on the safe side. # Answer > 13 votes I see many answers that are more complicated, this worked for me: ``` `(add-hook 'auto-save-hook 'org-save-all-org-buffers)` ``` Auto Save defaults to running after 30 seconds of inactivity (and in other non-related scenarios documented in the manual) # Answer > 8 votes You can save all org buffers whenever a particular agenda function is called. For instance, to save all org buffers after you quit the agenda: ``` (advice-add 'org-agenda-quit :before 'org-save-all-org-buffers) ``` Alternatively, you could save all org-buffers after each edit, say after a deadline is added: ``` (advice-add 'org-deadline :after 'org-save-all-org-buffers) ``` This will work both in org-agenda and org buffers. Use `org-agenda-deadline` instead if you want to restrict auto-saves to the agenda. You can do the same for any org function, so this method allows you to choose exactly when to save org buffers. This approach covers some corner cases that the method by @Sigma misses: you can have your agenda changes saved even if you leave the agenda before `auto-save` has a chance to trigger, or make changes outside the agenda and forget to save them. I personally use both methods to cover all my bases. \[Edit: See comment on @Sigma solution for why I no longer use his solution.\] # Answer > 5 votes I use the following snippet to automatically save all the agenda mode buffers after a new capture, but you could hook it anywhere you'd like: ``` (defun my/save-all-agenda-buffers () "Function used to save all agenda buffers that are currently open, based on `org-agenda-files'." (interactive) (save-current-buffer (dolist (buffer (buffer-list t)) (set-buffer buffer) (when (member (buffer-file-name) (mapcar 'expand-file-name (org-agenda-files t))) (save-buffer))))) ;; save all the agenda files after each capture (add-hook 'org-capture-after-finalize-hook 'my/save-all-agenda-buffers) ``` Change the `'org-capture-after-finalize-hook` to `'org-agenda-finalize-hook`, which I believe is called just before displaying the agenda buffer. # Answer > 0 votes This will work whether you are currently in the Agenda buffer or not: ``` (defun my-org-mode-autosave-settings () (add-hook 'auto-save-hook 'org-save-all-org-buffers nil nil)) (add-hook 'org-mode-hook 'my-org-mode-autosave-settings) ``` This is based on Karim's and Sigma's answers. --- Tags: org-mode, saving ---
thread-3779
https://emacs.stackexchange.com/questions/3779
How do I turn-off smartparens when using prelude?
2014-11-21T13:21:55.837
# Question Title: How do I turn-off smartparens when using prelude? I find smartparens awkward. It's easier for me to type the matching paren/quote than to arrow over or `C-f` over. I want to turn off smartparens everywhere. I'm using prelude though and I can see that prelude turns on smartparens for a variety of the language specific packages that it uses. **Is there a way to globally turn off smartparens?** I'm assuming that it goes somewhere in my `personal/` directory in one of my custom init files. # Answer I don't see an option in prelude to disable `smartparens` globally -- looks like it is enabled in a `prog-mode-hook` and a few other places. You could advise `smartparens-mode` (and perhaps `smartparens-strict-mode`as well) to prevent them from enabling the mode. Assuming you are on Emacs 24.4, try this: ``` (advice-add #'smartparens-mode :before-until (lambda (&rest args) t)) ``` This effectively makes `smartparens-mode` return `t` and do nothing. > 4 votes # Answer This worked for me: ``` M-x customize-group RET smartparens RET ``` Then use the Easy Customization interface to toggle `Smartparens Global Mode` to "off" (nil), then choose to apply and save your changes. (The setting started in the "off" state for me, but smartparens was active anyway. I had to toggle it "on" and back "off" to disable it successfully.) *EDIT*: I take it back; it worked *temporarily*. Smartparens is activated again upon starting a new session. Maybe this is an issue with Prelude? > 1 votes # Answer What worked for me: ``` (defun disable-smartparens () (smartparens-mode -1)) (add-hook 'smartparens-enabled-hook 'disable-smartparens t) ``` It appears that the `smartparens-enabled-hook` is called when smartparens is enabled. So, essentially, whenever smartparens turns on, we immediately turn it off. If you just want to rebind some of the keys within there, you can change the function to: ``` (defun rebind-keys () (global-set-key example 'command)) ``` And customize as appropriate from https://www.gnu.org/software/emacs/manual/html\_node/emacs/Rebinding.html > 0 votes --- Tags: smartparens, prelude ---
thread-44631
https://emacs.stackexchange.com/questions/44631
Implmentation of org-id-goto but for arbitrary properties?
2018-09-09T12:42:26.420
# Question Title: Implmentation of org-id-goto but for arbitrary properties? Does there exist a function similar to `org-id-goto`, but instead one that can allow you to jump to tasks that have arbitrary property names (other than just "ID")? So for example `(org-goto "ID1" "VALUE")` would jump to the (perhaps first found) task with property `ID1` and value `VALUE`. # Answer This jumps to the first heading with property `ID1` set to `VALUE` in the current buffer: ``` (goto-char (org-with-wide-buffer (org-find-property "ID1" "VALUE"))) ``` Found that function from looking at the source of `org-find-entry-with-id`. > 1 votes # Answer I think you want C-c a m (org-tags-view) After you type C-c am, enter this at the prompt in the minibuffer: ``` ID1="VALUE" ``` you should get an agenda list of tasks matching that. You can open which ever one you want. > 0 votes --- Tags: org-mode ---
thread-54657
https://emacs.stackexchange.com/questions/54657
How to find the matching bracket at a point in elisp?
2020-01-03T22:43:23.033
# Question Title: How to find the matching bracket at a point in elisp? What is a reliable way to find the matching balanced bracket (eg: `{}`, `[]`, `()` in C or Python), which doesn't get confused by brackets in strings, or escaped brackets for e.g. Example: ``` ["Foo]" ?\] 0 [1 2]] ^ ^ Input point. Return point. ``` Something like how `show-paren-mode` works, except as an elisp-function where you can pass in a point and get a matching point or `nil` when not found. # Answer Generally `forward-sexp` should know what to do in any given mode, so you could perhaps base it on this: ``` (save-excursion (ignore-errors (forward-sexp) (1- (point)))) ``` Alternatively... > Something like how `show-paren-mode` works You could use that exact same code. Look at `M-x` `find-function` `RET` `show-paren-function` and how it uses the results of `(funcall show-paren-data-function)`, and adapt to your purposes. ``` show-paren-data-function is a variable defined in `paren.el'. Its value is `show-paren--default' This variable may be risky if used as a file-local variable. Documentation: Function to find the opener/closer "near" point and its match. The function is called with no argument and should return either nil if there's no opener/closer near point, or a list of the form (HERE-BEG HERE-END THERE-BEG THERE-END MISMATCH) Where HERE-BEG..HERE-END is expected to be near point. ``` > 1 votes --- Tags: syntax, balanced-parentheses, delimiters ---
thread-54483
https://emacs.stackexchange.com/questions/54483
What is the `'inf-template` file in the ob-template.el file (template for creating new babel language)
2019-12-21T14:30:01.307
# Question Title: What is the `'inf-template` file in the ob-template.el file (template for creating new babel language) Because the options provided by the mathematica.el file in org-contrib are quite limited, I am trying to create a new, extended, mathematica.el file. As explained on the org language development page, I start out with the ob-template.el file. However, the template file expects an `inf-template` file (all occurences of template should be substituted by the target language, but I keep things general here) on linenumber 71 in the `org-babel-expand-body` function but I have no idea what kind of file that should be. Also I can not find any other `inf-...` file on my system. As I don't know much about inf files my general question is: Someone here can share some useful information about `inf-...` files? # Answer > 1 votes In the mean time I discovered some `inf-...` file on my system. (i.e. `inf-lisp.el`). From the contents of the file I found that the file defines an **inferior lisp mode** so that I understand that an `inf-...` file defines an optional inferior mode that can be used by the extension. --- Tags: org-mode, org-babel, babel ---
thread-54675
https://emacs.stackexchange.com/questions/54675
How to count the number of lines between two points? (ignoring word wrap)
2020-01-05T01:40:25.230
# Question Title: How to count the number of lines between two points? (ignoring word wrap) Is there a convenient way to count the number of lines between two points? While I could search for `\n` in a loop and limit it to one of the points, this seems like an overly verbose way of doing it. # Answer > 4 votes There is a function to count lines. `(count-lines beg end)` *Found this soon after posting.* --- Tags: newlines ---
thread-10400
https://emacs.stackexchange.com/questions/10400
How can I find surrounding parenthesis (from emacs lisp)?
2015-03-30T12:11:32.247
# Question Title: How can I find surrounding parenthesis (from emacs lisp)? Is there a way to find out the type of the surrounding parenthesis (i.e. '(', '\[' or '{') around point? For example (using `|` to represent point) ``` { abc, | df } ``` should return '{', and ``` { abc[ | ], 123 } ``` should return '\['. Ideally I would like it to handle quotation marks as well. --- In case anyone is curious or needs more details: my aim is to set up smart automatic spacing around `:` in python using electric-spacing (also known as smart-operator). The problem is that normally (in python) `:` is either the slice operator or the start of a for/if/... statement, which shouldn't be surrounded by spaces. However, within a dictionary it is something like an assignment operator, and so it should be surrounded by spaces. So I a way need to check if point is inside a dict (i.e. inside `{}`), but not inside a slice operation or string within that dict (i.e. not inside `[]` or `""`). --- # Edit: Here's the helper function I wrote, based on abo-abo's answer: ``` (defun enclosing-paren () "Return the closing parenthesis of the enclosing parens, or nil if not inside any parens." (ignore-errors (save-excursion (up-list) (char-before)))) ``` Then then the final predicate is: ``` (and (not (in-string-p)) (eq (enclosing-paren) ?\})) ``` # Edit 2: The above function turned out to be too slow (it often caused a noticeable lag when a `:` was typed). I'm using Stefan's answer instead now, which seems to be much faster. # Answer > 11 votes Rather than `up-list` I'd recommend you use `(syntax-ppss)` which will return to you some parsing state. This will include info about whether you're inside a string or a comment, the position of the last open "paren" etc... E.g. you can find the kind of paren with ``` (let ((ppss (syntax-ppss))) (when (nth 1 ppss) (char-after (nth 1 ppss)))) ``` and it should hopefully let you handle quotation marks as well (by checking `(nth 3 ppss)` and `(char-after (nth 8 ppss))`). # Answer > 5 votes Try this: ``` (save-excursion (up-list) (char-before)) ``` Note that `up-list` can throw, so you need to handle errors as well. # Answer > 1 votes While the preferable answer IMO was given by Stefan, here an example which includes a solution not relying on syntax-table WRT delimiters: It uses something like ``` (skip-chars-backward "^{\(\[\]\)}") ``` and a stack. See source here https://github.com/emacs-berlin/general-close # Answer > 0 votes Here is a function which returns surrounding parenthesis, including the case when the point is directly on the first or last parenthesis (which was important in my case). This works with the language, so `({[]})` all work in C for example. ``` (defun find-surrounding-brackets (pos) "Return a pair of buffer positions for the opening & closing bracket positions. Or nil when nothing is found." (save-excursion (goto-char pos) (when (or ;; Check if we're on the opening brace. (when ;; Note that the following check for opening brace ;; can be skipped, however it can cause the entire buffer ;; to be scanned for an opening brace causing noticeable lag. (and ;; Opening brace. (eq (syntax-class (syntax-after pos)) 4) ;; Not escaped. (= (logand (skip-syntax-backward "/\\") 1) 0)) (forward-char 1) (if (and (ignore-errors (backward-up-list arg) t) (eq (point) pos)) t ;; Restore location and fall through to the next check. (goto-char pos) nil)) ;; Check if we're on the closing or final brace. (ignore-errors (backward-up-list arg) t)) ;; Upon success, return the pair as a list. (list (point) (progn (forward-list) (1- (point))))))) ``` --- Tags: balanced-parentheses, parsing, sexp ---
thread-54659
https://emacs.stackexchange.com/questions/54659
How to delete surrounding brackets?
2020-01-04T04:57:00.517
# Question Title: How to delete surrounding brackets? I'd like to be able delete the innermost brackets around the current point. What's a good way to do this? While the evil-surround package can do this, it needs to take a bracket type as input, so can't remove the inner-most brackets (without some extra code). # Answer > 3 votes Use `up-list` or `backward-up-list` to move forward or backward to the first enclosing bracket, then `forward-list` or `backward-list` to locate the matching bracket. Delete the closing bracket then the opening bracket (in this order, because deleting the opening bracket moves the position of the closing bracket. ``` (defun delete-enclosing-parentheses (&optional arg) "Delete the innermost enclosing parentheses around point. With a prefix argument N, delete the Nth level of enclosing parentheses, where 1 is the innermost level." (interactive "*p") (save-excursion (backward-up-list arg) (let ((beg (point))) (forward-list) (delete-backward-char 1) (goto-char beg) (delete-char 1)))) ``` # Answer > 1 votes Adding an answer based on @gilles-so-stop-being-evil 's current answer which works when the point is on the opening bracket as well as the last bracket, it also error checks and prints useful status upon completion. ``` (defun my-delete-surround-at-point--find-brackets (pos) "Return a pair of buffer positions for the opening & closing bracket positions. Or nil when nothing is found." (save-excursion (goto-char pos) (when (or ;; Check if we're on the opening brace. (when ;; Note that the following check for opening brace ;; can be skipped, however it can cause the entire buffer ;; to be scanned for an opening brace causing noticeable lag. (and ;; Opening brace. (eq (syntax-class (syntax-after pos)) 4) ;; Not escaped. (= (logand (skip-syntax-backward "/\\") 1) 0)) (forward-char 1) (if (and (ignore-errors (backward-up-list 1) t) (eq (point) pos)) t ;; Restore location and fall through to the next check. (goto-char pos) nil)) ;; Check if we're on the closing or final brace. (ignore-errors (backward-up-list 1) t)) ;; Upon success, return the pair as a list. (list (point) (progn (forward-list) (1- (point))))))) (defun my-delete-surround-at-point () (interactive) (let ((range (my-delete-surround-at-point--find-brackets (point)))) (unless range (user-error "No surrounding brackets")) (pcase-let ((`(,beg ,end) range)) ;; For user message. (let ((lines (count-lines beg end)) (beg-char (char-after beg)) (end-char (char-after end))) (save-excursion (goto-char end) (delete-char 1) (goto-char beg) (delete-char 1)) (message "Delete surrounding \"%c%c\"%s" beg-char end-char (if (> lines 1) (format " across %d lines" lines) "")))))) ``` # Answer > 0 votes This is an answer I came up with, adding for completeness, however I'd rather not depend on evil-surround because it gives less control and is more likely to break. ``` (defun delete-surround-at-point (arg) (interactive "p") (let ( (best-range most-positive-fixnum) (best-inner nil) (best-outer nil) (chars (list ?\( ?\[ ?\{ ?\" ?\')) (char-found nil)) (dolist (c chars) (let* ( (overlay-inner (ignore-errors (evil-surround-inner-overlay c))) (overlay-outer (and overlay-inner (<= (overlay-start overlay-inner) (point)) (>= (overlay-end overlay-inner) (point)) (ignore-errors (evil-surround-outer-overlay c))))) (if (and overlay-inner overlay-outer) (let ((test-range (- (overlay-end overlay-inner) (overlay-start overlay-inner)))) (when (< test-range best-range) (setq best-range test-range) (when best-inner (delete-overlay best-inner) (delete-overlay best-outer)) (setq best-inner overlay-inner) (setq best-outer overlay-outer) (setq char-found c))) ;; Else delete either overlay if it exists. (when overlay-inner (delete-overlay overlay-inner)) (when overlay-outer (delete-overlay overlay-outer))))) (unless (null char-found) (evil-surround-delete char-found best-outer best-inner)) (when best-inner (delete-overlay best-inner) (delete-overlay best-outer)))) ``` # Answer > 0 votes Brackets can be detected using `forward-sexp` and `backward-sexp`, this examples uses these functions to implement context sensitive bracket removal. ``` (defun find-surrounding-brackets (pt &optional strict) "Find surrounding braces. Argument PT is the point which is checked for brackets. When argument STRICT is non-nil, only use braces at PT, otherwise surrounding brackets are searched for." (catch 'match (let ( (re-begin "\\((\\|{\\|\\[\\)") (re-end "\\()\\|}\\|\\]\\)") (pt-begin nil) (pt-end nil)) ;; First check if we're already on an ending bracket with a match, ;; handle this as a special case because there is no ambiguity in this instance. ;; Otherwise search for the previous bracket. (save-excursion (goto-char pt) (save-match-data (cond ((looking-at re-begin) (when (setq pt-end (ignore-errors (forward-sexp) (1- (point)))) (setq pt-begin pt) (throw 'match (list pt-begin pt-end)))) ((looking-at re-end) (forward-char 1) (when (setq pt-begin (ignore-errors (backward-sexp) (point))) (setq pt-end pt) (throw 'match (list pt-begin pt-end))))))) ;; Now loop over preview brackets ;; until we find a match which includes `pt'. (unless strict (let ((pt-iter (1+ pt))) (while (setq pt-begin (save-excursion (goto-char pt-iter) (save-match-data (when (search-backward-regexp re-begin (point-min) t 1) (match-beginning 0))))) (setq pt-end (save-excursion (goto-char pt-begin) (ignore-errors (forward-sexp) (1- (point))))) (when (and pt-end (< pt pt-end)) (throw 'match (list pt-begin pt-end))) (setq pt-iter pt-begin))))) (throw 'match nil))) (defun delete-surround-at-point (arg) (interactive "p") (let ((range (find-surrounding-brackets (point)))) (unless range (user-error "No surrounding brackets")) (pcase-let ((`(,start ,end) range)) (save-excursion (goto-char end) (delete-char 1) (goto-char start) (delete-char 1))))) ``` --- Tags: balanced-parentheses, parentheses ---
thread-54674
https://emacs.stackexchange.com/questions/54674
How can I do a regex search recursively from a directory?
2020-01-05T01:14:28.603
# Question Title: How can I do a regex search recursively from a directory? Basically I want a command that can do the following: `find /path/dir -type f -print0 | xargs -0 grep -l "foo"` Is there an emacs command to do this? If not, then is there a convenient keybinding that I can make? I tried to do the following: ``` (global-set-key (kbd "C-f") 'find) (defun find (dir string) (interactive) (shell) (insert "find") (insert dir) (insert "-type f -print0 | xargs -0 grep -l") (insert string) ) ``` But it doesn't seem to work. It gives me "wrong type argument: commandp, find". # Answer The following does that and presents the results as a `dired` buffer: `M-x` `find-grep-dired` You'll also want to know about: `M-x` `rgrep` (which doesn't support the `-l` option to grep, but is usually what I want from a recursive regexp search.) > 1 votes # Answer @phils answered the question. This is just to say that the version of `find-grep-dired` in library `find-dired+.el` provides a bit more than the vanilla version: * It has two optional args, `DEPTH-LIMITS` and `EXCLUDED-PATHS`. * The `interactive` spec uses `read-from-minibuffer`, `read-file-name`, `dired-regexp-history` and `find-diredp-default-fn`. > **`find-grep-dired`** is an interactive compiled Lisp function in `find-dired+.el`. > > `(find-grep-dired DIR REGEXP &optional DEPTH-LIMITS EXCLUDED-PATHS)` > > Use Dired on the list of files in `DIR` whose contents match `REGEXP`. > > The `find’` command run (after changing into `DIR`) is essentially this, where `LS-SWITCHES` is `(car find-ls-option)`: ``` find . \( -type f -exec grep grep-program find-grep-options -e REGEXP {} \; \) LS-SWITCHES ``` > Thus `REGEXP` can also contain additional `grep` options. > > Optional arg **`DEPTH-LIMITS`** is a list `(MIN-DEPTH MAX-DEPTH)` of the minimum and maximum depths. If `nil`, search directory tree under `DIR`. > > Optional arg **`EXCLUDED-PATHS`** is a list of strings that match paths to exclude from the search. If `nil`, search all directories. > > When both optional args are non-`nil`, the `find` command run is this: ``` find . -mindepth MIN-DEPTH -maxdepth MAX-DEPTH \( -path EXCLUDE1 -o -path EXCLUDE2 ... \) -prune -o -exec grep-program find-grep-options -e REGEXP {} \; LS-SWITCHES ``` > where `EXCLUDE1`, `EXCLUDE2`... are the `EXCLUDED-PATHS`, but shell-quoted. > 1 votes --- Tags: shell-command, grep, find-dired, find ---
thread-54683
https://emacs.stackexchange.com/questions/54683
How to disable a minor/major mode so that mwheel-scroll don’t take effect?
2020-01-05T06:52:50.747
# Question Title: How to disable a minor/major mode so that mwheel-scroll don’t take effect? I am trying to have a simple solution to center the cursor at all times. I found that `centered-cursor-mode` was too slow and found this simpler solution. The only problem is mouse scrolling no longer works unless I disable the minor/major mode I implemented to center the cursor. I tried to advise `mwheel-scroll` to disable the mode but that was unsuccessful. I am not sure what I am doing wrong. ``` (define-minor-mode centered-point-mode "Always center the cursor on the screen." :lighter "..." (cond (centered-point-mode (add-hook 'post-command-hook 'line-change)) (t (remove-hook 'post-command-hook 'line-change)))) (defun line-change () (recenter)) (define-globalized-minor-mode my-global-centered-point-mode centered-point-mode (lambda () (centered-point-mode 1))) (my-global-centered-point-mode 1) (defun disable-centered (interactive) (centered-point-mode -1)) (advice-add 'mwheel-scroll :before (lambda () (interactive) (call-interactively 'disable-centered))) ``` # Answer The O.P. has indicated in a comment underneath the original question that a previous suggestion by this author resolved the issue, and this answer is a write-up of that solution.... There is no need to use any `advice-...`. Instead, the O.P. could use one of two potential conditions: 1. For just one exception, modify the function `line-change` as follows: ``` (unless (eq this-command 'mwheel-scroll) (recenter)) ``` 2. For multiple exceptions, modify the function `line-change` as follows: ``` (unless (memq this-command '(mwheel-scroll foo-command bar-command baz-command)) (recenter)) ``` In most cases, `this-command` is the command of the current command loop -- however, certain hooks run after `this-command` becomes the `last-command` even though the command loop is still the same ... but, the `post-command-hook` is early enough in time so that `this-command` is still current. > 1 votes --- Tags: major-mode, minor-mode, scrolling ---
thread-54648
https://emacs.stackexchange.com/questions/54648
Yearly calendar view of agenda (with colored background)
2020-01-03T16:01:38.920
# Question Title: Yearly calendar view of agenda (with colored background) I would like to have a yearly calendar view of my agenda. The code from https://stackoverflow.com/questions/9547912/emacs-calendar-show-more-than-3-months shows how to display a calendar for the whole year. Ideally, I would like to connect it to my agenda such as to color the background of each day according to the number of events for this day. This would allow me to quickly visually check what are the busy days (I imagine I can probably query the information but I would prefer such a visual). Is there any package that could do that? # Answer > 5 votes I ended up doing it in Python and I display it in the terminal. Code at https://gist.github.com/rougier/d559fbd766da14540e8eb47435a5782d --- Tags: org-mode, org-agenda, calendar ---
thread-54666
https://emacs.stackexchange.com/questions/54666
How to show diffs of merge commits in magit?
2020-01-04T11:08:13.620
# Question Title: How to show diffs of merge commits in magit? When viewing a merge commit it only shows the number of lines changed but no diff. I know that it is possible with `git show --first-parent`. Is there a way to add an argument to `magit-show-commit`? I'm aware that I can just diff from the commit view but I thought there may be a way to do it directly when viewing the commit. # Answer Use the diff dwim command instead (`d d`); it does what you want it to do in this case too. > 10 votes --- Tags: magit ---
thread-54681
https://emacs.stackexchange.com/questions/54681
Org Mode link to structure blocks
2020-01-05T03:24:54.223
# Question Title: Org Mode link to structure blocks Is there a way of linking to a specific structure block in org mode? I have a block of text as follows: ``` * Heading Some text ** Subheading some text #+BEGIN_PROSE Lorem Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. #+END_PROSE some text ``` `C-c``C-l` would only store a link to the top of `subheading`. I would like to be able the use `[[Lorem]]` to jump to the bock of text. Would that be possible? ----- # Update: Because the text would be printed, I would like any dedicated target to stay within the template code or comment. I've tried `#+BEGIN_PROSE <<Lorem>>` and `# <<Lorem>>` but neither works. # Answer > 2 votes I think you need to put a name on the block like this: ``` * Heading Some text ** Subheading some text #+name: Lorem #+BEGIN_PROSE Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. #+END_PROSE some text * Heading with link to Lorem Here is the link: [[Lorem]]. ``` # Answer > 1 votes Just insert a dedicated target `<<lorem>>` at the place where you would like to jump to with `[[lorem]]`. It's clear that John Kitchin's solution works with blocks. What I meant is: ``` * Heading Some text [[lorem]] ** Subheading some text #+BEGIN_PROSE Lorem <<lorem>> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. #+END_PROSE some text ``` --- Tags: org-mode, org-link ---
thread-53700
https://emacs.stackexchange.com/questions/53700
How to disable org-metaleft in org capture?
2019-11-12T14:54:39.240
# Question Title: How to disable org-metaleft in org capture? The combination of org capture, `org-metaleft` (bound to `S-LEFT`), and refiling can mess up an org file. Here is an example: * Start a new heading with quick capture, say `*** new`. This heading is refiled depending on your quick capture template, say `** Miscellaneous`. * Press `S-LEFT` twice, which is bound to `org-metaleft` and which I often use to go back a word instead of `M-b`. The heading `*** new` becomes `* new` and all the next level 2 headings will become children of this new heading. * Refile with `C-c C-w`, say to `* Today`. The heading becomes `** new` and carries all the children with it to the new location. The problem with this behavior is that it is completely hidden, unlike in the main buffer where I would see it happening. So I think `org-metaleft` should be disabled in org capture. Why is it enabled, and how to turn it off? # Answer > 0 votes Following @lawlist's comments, `C-h k <M-LEFT>` on an org-capture buffer shows that the key is bound through `org-mode-map`. I overrode the keybinding of `M-LEFT` to a function that checks if the current buffer is an Org-capture buffer: ``` (defun my-org-is-buffer-org-capture() "Checks if the current buffer is an org-capture buffer." (string-match-p (regexp-quote "CAPTURE-") (buffer-name))) (defun my-org-metaleft (&optional arg) "Wrapper function for org-metaleft, except in org-capture buffers where it calls backward-word." (interactive) (if (my-org-is-buffer-org-capture) (backward-word) (org-metaleft arg))) (defun my-org-metaright (&optional arg) "Wrapper function for org-metaright, except in org-capture buffers where it calls forward-word." (interactive) (if (is-buffer-org-capture) (forward-word) (org-metaright arg))) ;; Disable org-metaleft and org-metaright in org-capture buffers (define-key org-mode-map (kbd "<M-left>") 'my-org-metaleft) (define-key org-mode-map (kbd "<M-right>") 'my-org-metaright) ``` --- Tags: org-mode ---
thread-54695
https://emacs.stackexchange.com/questions/54695
No graphic output for MATLAB src block in org-mode
2020-01-05T15:49:55.057
# Question Title: No graphic output for MATLAB src block in org-mode In an org file, if I include a MATLAB src block that has a graphic output (a figure is plotted there), for example, the following src block: ``` #+begin_src matlab :session :file tst.png :results graphics imagesc(rand(100)) #+END_SRC ``` it won't be shown in the result of the src block (although the file gets saved as it should). Emacs returns, `Code block produces no output` (this is "not" the case for a python src block). # Answer > 3 votes This issue is related to recent changes in org-mode (i.e. org 9.3). In the latest change log they mentioned that: > `:file` header argument no longer assume "file" `:results` The "file" `:results` value is now mandatory for a code block returning a link to a file. The `:file` or `:file-ext` header arguments no longer imply a "file" result is expected. So, one needs to use the following block to have the graphic output: ``` #+begin_src matlab :session :file tst.png :results file graphics imagesc(rand(100)) #+END_SRC ``` for `:results` only `graphics` is not sufficient any more, it needs to be `file graphics` --- Tags: org-mode, org-babel, matlab ---
thread-54689
https://emacs.stackexchange.com/questions/54689
AUCTeX does not compile if the local variable is already set
2020-01-05T12:20:42.600
# Question Title: AUCTeX does not compile if the local variable is already set I'm basically want to ask the question that was asked in Tex Stackexchange but was considered off-topic there (this is the link to the question). When I am trying to compile (using the command `C-c C-c` or `C-c C-a`) a latex document **which already has the needed local variables** to point to the `master-file` like lines below at the end: ``` %%% Local Variables: %%% mode: latex %%% TeX-master: t %%% End: ``` or if the `master-file` is another file: ``` %%% Local Variables: %%% mode: latex %%% TeX-master: "fileNameOfMasterFile" %%% End: ``` it does not compile and instead, just shows the following message`Master file already set` in the mini buffer. If I simply delete the local variable `%%% TeX-master: "fileNameOfMasterFile"` or `%%% TeX-master: t` and try to compile again (using the command `C-c C-c` or `C-c C-a`) it asks for the `master-file` and compiles as usual. Further on, it works normally when I compile again. But if I simply close the buffer and (re-)open the file again I face the same issue. Is it a natural behavior? If not, any idea why this happens and how I can solve it? If needed, I have the following in my `init` file: ``` (setq-default TeX-master nil) ``` **Add-on:** I'm suspicious that this might be related to AUCTeX version. What I just explained in the question was tested on AUCTeXversion 12.2.0 and I tried with a similar setting (same init file but an older emacs) with an older version AUCTeX (12.1.2)(on a different machine) and it works as it is expected. # Answer > 0 votes Change to `(setq-default TeX-master t)` and don't forget to omit the "tex" extension. --- Tags: latex, auctex ---
thread-54696
https://emacs.stackexchange.com/questions/54696
How to sort comma separated (or otherwise) text?
2020-01-05T16:09:26.223
# Question Title: How to sort comma separated (or otherwise) text? Suppose I have the following text: ``` int z; int a; int c; int g; ``` or the following text: `z, a, c, g` How can I sort them to: ``` int a; int c; int g; int z; ``` and ``` a, c, g, z ``` respectively? # Answer > 4 votes Use `M-x sort-lines` for the first example. For the second example, change it into ``` z, a, c, g, ``` then use `M-x sort-regexp-fields <RET> ., <RET> \& <RET>`. --- Tags: text-editing, sorting ---
thread-54701
https://emacs.stackexchange.com/questions/54701
Programmed completion in minibuffer
2020-01-05T17:33:03.600
# Question Title: Programmed completion in minibuffer I can read a string in the minibuffer, with completion, using `completing-read`: ``` (completing-read "Chose one: " '("Han Solo" "Chewbacca" "Lando Calrissian")) ``` I would like to use my own completion function, which searches some of my files, instead of a list. The Programmed Completion page of the manual details just how to do that, but does not give any example. The best I could achieve is this : ``` (defun completion-function (input-string predicate flag) (if flag '("Chewbacca" "C3-PO" "Calrissian") "C3-PO")) (completing-read "Chose one: " 'completion-function) ``` However, this does not behave at all like I would : * it suggests only one choice on the first `TAB` press (I would like all of them to be shown, as what shows a second `TAB` push) * it does not filter the results on the input string (do I need to implement that as well?) Can someone give a better, more complete example? # Answer > 4 votes Your `completion-function` is a function, but not a proper completion table (it does not obey all the expected behavior). I recommend you use `completion-table-dynamic` to build a proper completion table function from a function that simply lists all the possible completions. E.g. ``` (defun my-completion-function (prefix) ;; You can just ignore the prefix '("Chewbacca" "C3-PO" "Calrissian")) (completing-read "Chose one: " (completion-table-dynamic #'my-completion-function)) ``` --- Tags: completion ---
thread-54610
https://emacs.stackexchange.com/questions/54610
completion of a sentence rather than word
2020-01-01T12:45:12.577
# Question Title: completion of a sentence rather than word I use emacs-org for my "non-programming" work. I need a completion framework. Present completion framework like completion.el, dabbreav, pabbrev and company provide single word completion. I need something to complete a sentence like -- Generalised painless progressive distention of abdomen -- Generalised painless progressively increasing jaundice. On typing Generalised , I should get these options. Is it possible Regards # Answer > 2 votes abbrev can abbreviate text. Use a numeric argument to say how many words before point should be taken as the expansion. For example, to abbreviate the sentence "The cat and the mooon." as x, put the point at the end and do ``` C-u 5 C-x a g x <RET> ``` The emacs manual (info) for Abbrevs gives the details. # Answer > 0 votes You can use `hippie-expand`: ``` (setq hippie-expand-try-functions-list '(try-expand-line)) (global-set-key (kbd "C-;") 'hippie-expand) ``` Now `C-;` should expand to the closest matching line. Repeating the command will get you all the matches. Finally, if you want a popup menu with the choices listed there are some hacky ways of plugging `hippie-expand` into `company-mode`, but I'm not sure they work well. You can check the github page for `company-mode`. --- Tags: completion ---
thread-54097
https://emacs.stackexchange.com/questions/54097
How to auto-format an Elisp file on save?
2019-12-02T04:24:54.183
# Question Title: How to auto-format an Elisp file on save? Having used `clang-format` to format the buffer when saving, I find this functionality useful. Are there tools to reformat an Elisp buffer when saving? # Answer > 2 votes Since asking this question I've written an auto-formatter that runs on save. Other elisp formatting tools I found caused a \*lot\* of right-shift and didn't seem well maintained. See: elisp-autofmt. This can be configured to run for some projects and not others. While this runs on save, it first checks for `.elisp-autofmt` before re-formatting the buffer. --- See other auto-formatting tools for reference. --- Tags: formatting, saving ---
thread-31675
https://emacs.stackexchange.com/questions/31675
How do you use the eieio-persistent class to serialize a set of objects?
2017-03-24T13:27:09.713
# Question Title: How do you use the eieio-persistent class to serialize a set of objects? I am trying to use the eieio-persistent class to make persistent objects. My goal is to store many objects in a file. I am not sure how to achieve this though. If I use this code, I do get a persistent object saved in test.db, but (perhaps predictably) the second save overwrites the first one. ``` (defclass animal (eieio-persistent) ((type :initarg :type) (file :initform "/Users/jkitchin/Dropbox/org-mode/test.db"))) (let ((a1 (animal :type 'mammal))) (eieio-persistent-save a1)) (let ((a1 (animal :type 'rodent))) (eieio-persistent-save a1)) ``` Is there a way to save a list of these "animals" using the eieio framework? I would prefer not to create individual files for each object (I am anticipating thousands of objects later that need to be read in). Ideally, there would be another class that had a list of these animal objects in a records field. Something like this is close ``` (defclass animal-db (eieio-named eieio-persistent) ((id :initarg :id) (file :initform "/Users/jkitchin/Dropbox/org-mode/test.db") (records :initarg :records :type listp)) "Base db for animal class") ``` but the list in the records doesn't appear to be actual objects, when I read the code back in, but code that needs to be eval'd to get the object. Any ideas? # Answer If you want to store objects by the group rather than per instance, a more natural pattern (with a more out-of-the-box implementation) may be a collector or composite object. Based only on the examples provided in your question, you may be able to apply eieio-persistent only on *some* levels of your hierarchy, perhaps adding classes just for grouping purposes. Obviously, this may unacceptably complicate ones modeling. This uses oset and oref to work with the list but I might take the time to create custom accessors methods if I planned to work with these objects from various points in code. ``` (defclass animal () ((type :initarg :type))) (defclass zoo (eieio-persistent) ((animals :initarg :menagerie :initform nil) (file :initform "~/where-ever-you/test.db"))) (let ((z1 (zoo))) (let ((a1 (animal :type 'mammal))) (oset z1 animals (append (oref z1 animals) (list a1))) (eieio-persistent-save z1)) (let ((a1 (animal :type 'rodent))) ;; sorry pal ;;(oset z1 animals (append (oref z1 animals) a1)) (eieio-persistent-save z1)) (let ((a1 (animal :type 'unicorn))) (oset z1 animals (append (oref z1 animals) (list a1))) (eieio-persistent-save z1))) ``` For me (GNU Emacs 26.3 for Windows 10) this creates a file containing: ``` ;; Object zoo ;; EIEIO PERSISTENT OBJECT (zoo "zoo" :file "test.db" :menagerie (list (animal "animal" :type mammal) (animal "animal" :type unicorn))) ``` > 0 votes --- Tags: eieio ---
thread-51088
https://emacs.stackexchange.com/questions/51088
Simple way to add parent node
2019-06-18T09:08:09.013
# Question Title: Simple way to add parent node Is there a simple way to add parent node in `org-mode`? ``` * heading ... # 100 or more first-level headings over here * heading # interspersed with ones with subtrees ** heading ** heading *** heading ... ``` I would like to add a `NEW HEADING` to the above so that everything else shifts down and right. ``` * NEW HEADING ** heading *** heading *** heading **** heading ... ``` Currently, selecting everything and hitting `M-→` works just some of the time. It gets cumbersome when many sub and/or sub-sub headings are involved. --- # Note: I presently use mark set to select region to be demoted. It works only in a specific way and not all the time. Namely, I need to: 1. `C-@ ↓` somewhere above the first `* heading` 2. Move the cursor to the left-most `*` just below the region the be selected 3. Hit `M-→` Any other method would fail incessantly. # Answer > 1 votes This function inserts a new parent/root node above the current subtree and demotes the original subtree respectively: ``` (defun org-insert-parent-node () (interactive) (catch 'exit (while (or (org-up-heading-safe) (= (org-outline-level) 1)) (when (= (org-outline-level) 1) (org-insert-heading) (save-excursion (outline-next-heading) (org-demote) (throw 'exit t)))))) ``` Edit: I reread your question and I think you also want to include first-level headings above the current subtree. With this command you can select the current subtree and any number of first-level headings above it: ``` (defun org-insert-parent-node (beg end) (interactive (list (region-beginning) (region-end))) (save-restriction (narrow-to-region beg end) (let ((beg (save-excursion (goto-char beg) (skip-chars-forward "* ") (point))) (end (save-excursion (goto-char end) (line-beginning-position)))) (goto-char beg) (org-insert-heading) (goto-char beg) (save-excursion (while (outline-next-heading) (unless (= end (point)) (org-demote))))))) ``` # Answer > 1 votes `org-demote-subtree` does that. It is bound to `C-c C->`. # Answer > 0 votes As you might know, org-mode files are plaintext-based and heading depth is determined by the number of `*` characters in front of it This means you can simply insert a `*` in front of all headings you want to be demoted in plaintext instead of relying on org-mode functions. You don't even need to exit org-mode for that. The easiest way to do this I know of is to enter `rectangle-mark-mode` (`C-x SPC`) at the beginning of the first line, navigate to the beginning of the last line and use `string-insert-rectangle` (`C-t`) to enter as many `*` as levels you want to demote the headings by. (Evil-mode users can use `C-v` and `I` instead.) **EDIT: This only works if there is no text under headings** The slightly more complicated way that also works with text under heading is to mark the lines you want to demote and use `replace-regexp` to replace `^*` with `**` and `^SPC` with `SPCSPC`. (Evil-mode user can use `C-V` to mark and `:'<,'>s/^*/**/g` to replace) --- Tags: org-mode ---
thread-54673
https://emacs.stackexchange.com/questions/54673
Em dash before italic in org export
2020-01-04T22:46:51.897
# Question Title: Em dash before italic in org export In my document, I have an em dash that needs to be followed by italics. Here's a minimal example: ``` He was surprised—/excuse me/? ``` The LATEX/PDF output includes the slashes and the text is not italicized. How can I resolve this without adding spaces? This is a quote, so I can't change the text. # Answer > 2 votes As you have found out, adding a space between the em-dash and the slash renders the italics properly (both in the buffer, if you use a font that has a slanted version; and in the exported file, be that PDF or HTML or ...). The reason that works is the setting of `org-emphasis-regexp-components`. This is a complex variable: it is a list of various parts which are used to construct *at initialization time* some rather formidable regexps that are used during runtime to determine whether emphasis is to be applied. The hope (which is partly but not completely realized IMHO) was that it would be easier to understand each part and be able to modify it more easily than to understand the whole monstrous regexp that Org mode constructs. The description of the variable (at the default setting) is as follows (you can see it by doing `C-h v org-emphasis-regexp-components RET` in your emacs): > org-emphasis-regexp-components is a variable defined in ‘org.el’. Its value is `("-[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)` > > Documentation: Components used to build the regular expression for emphasis. This is a list with five entries. Terminology: In an emphasis string like `" *strong word* "`, we call the initial space PREMATCH, the final space POSTMATCH, the stars MARKERS, "s" and "d" are BORDER characters and "trong wor" is the body. The different components in this variable specify what is allowed/forbidden in each part: > > pre Chars allowed as prematch. Beginning of line will be allowed too. > > post Chars allowed as postmatch. End of line will be allowed too. > > border The chars *forbidden* as border characters. > > body-regexp A regexp like "." to match a body character. Don’t use non-shy groups here, and don’t allow newline here. > > newline The maximum number of newlines allowed in an emphasis exp. > > You need to reload Org or to restart Emacs after setting this. Note that the `pre` set consists of `-`, `(`, `'`, `"`, `{` and any member of the character class `[:space:]` which includes the ordinary space character , but can also include other characters (see Char Classes in regexps for details). In your case, you want em-dash to be a legal `pre` character. That's relatively easy - assuming that Org mode is loaded already, you can modify the `pre` part of the variable (the car of the list) with: ``` (setcar org-emphasis-regexp-components "-—[:space:]('\"{") ``` We just add the em-dash to the existing `pre` set of characters and set the `car` of the variable to the new value. The trouble is that modifying this variable does *nothing* to the (already constructed at initialization time) regexps that are based on this. That's why the doc says: `You need to reload Org or to restart Emacs after setting this.` \- either of these actions will run the initialization code again to (re-)calculate the derivative regexps. If you are only going to need this modification for this session of emacs only, you can do the `setcar` and then reload Org mode: `M-x org-reload RET`. However, if you want to make the change permanent, you will need to add the `setcar` above to your initialization file (e.g. `~/.emacs.d/init.el` or similar); but that can only be done if the variable is already defined, which is only done when `org.el[c]` is loaded. So the invocation in your initialization file has to be something like this: ``` (eval-after-load 'org '(progn (setcar org-emphasis-regexp-components "-—[:space:]('\"{") (org-reload))) ``` This evaluates the form when the file that provides the `org` feature is loaded (or if it is already loaded). That ensures that the variable is defined before we try to modify it. Then we reload Org mode in order to have the recalculation of the derivative regexps take place. EDIT: Actually, this last method causes a recursive file mode error. I think adding a complete definition of `org-emphasis-regexp-components` somewhere near the beginning of your initialization file, *before* Org mode is loaded, will work better: ``` (setq org-emphasis-regexp-components '("-—[:space:]('\"{" "-[:space:].,:!?;'\")}\\[" "[:space:]" "." 1)) ... (require 'org) ``` This *defines* a new variable (IOW, it does not try to modify an existing one), so it can (and *should*) be done before org is loaded. When org *is* loaded, it uses *this* variable definition instead of the default one. Restarting emacs after this will make the em-dash a permanent member of the `pre` set. --- Tags: org-mode, latex ---
thread-54632
https://emacs.stackexchange.com/questions/54632
Org mode monospaces more than it should
2020-01-02T15:39:43.267
# Question Title: Org mode monospaces more than it should Org mode lets you `monospace` text by enclosing it within `=` signs. However, I don't think the regex actually considers if it is a "starting" `=` or a "closing" `=`. Example: `=s[=$i$=]=` renders not only the `s[` and `]` as monospace, but also the enclosed `$i$`, which is not what I want. Another example: ``` In =bar=s case, blabla, =something monospaced= ``` This monospaces not only `bar` and `something monospaced`, but also the text within, i.e. `s case, blablabla,`. I have to insert a space between `=bar=` and the following s, but this is not something I want to do. Any help? # Answer > 0 votes Please refer to this answer for all the gory details. The default `post` set of characters in `org-emphasis-regexp-components` is `-[:space:].,:!?;'\")}\\[` i.e. dash, the `:space:` character class, period, comma, colon, exclamation mark, question mark, semicolon, single quote, double quote, closing paren, closing brace, backslash or opening square bracket. Any of those after a closing emphasis character (`=` in your examples above) will mark the end of the emphasis region. In your case, you want to add the dollar sign `$` to the `post` set, but you also want to add it to the `pre` set: that way, the example `=s[=$i$=]=` will work as you want it to work. For the other example, you want `s` (or perhaps any alpha char) to be in the `post` set. So in your init file, define `org-emphasis-regexp-components` as follows (and make sure that it is defined *before* you load Org mode): ``` (setq org-emphasis-regexp-components '("-$[:space:]('\"{" "-$[:alpha:][:space:].,:!?;'\")}\\[" "[:space:]" "." 1)) ... (require 'org) ... ``` This makes your examples work, but depending on your needs, it might not be enough or it might be too much: you might need to add additional characters or classes to the `pre` and/or `post` sets, but you might also find that different examples require conflicting definitions, in which case you might be stuck: this variable might be too blunt an instrument to resolve some situations. --- Tags: org-mode ---
thread-54717
https://emacs.stackexchange.com/questions/54717
How can I save a personal bookmark file?
2020-01-06T09:47:44.383
# Question Title: How can I save a personal bookmark file? I work on doom-emacs and keep personal configuration in `.doom.d`, thus leave the gene config `.emacs.d`. Today, I re-installed doom.emacs to `.emacs.d`, but find all my bookmarks disappeared when launch in. How can I save a personal bookmarks file? # Answer > 3 votes Did you clobber your original `~/.emacs.d/` directory? You may have lost all manner of things if you've done that. Assuming you backed it up first, just grab the `~/.emacs.d/bookmarks` file from your backup. If there's no such file, check `C-h``v` `bookmark-default-file` to see what it was actually called. --- Tags: bookmarks, config ---
thread-54698
https://emacs.stackexchange.com/questions/54698
Can I use mmm-mode two levels deep?
2020-01-05T16:47:31.517
# Question Title: Can I use mmm-mode two levels deep? I have the following elixir code that looks like this: ``` defmodule Drawing do use Surface.Component def render(assigns) do ~H""" <svg viewBox={{ "0 0 #{@width} #{@height}" }}> {{ SomeElixirCall.here() }} </svg> """ end end ``` It's elixir outside, with HTML in between `~H"""` and `"""`, and elixir inside the html, between `{{` and `}}`. I have made some `mmm` config that managed to highlight the html parts and the outer elixir part, but not the elixir inside the html. Is that possible with mmm, two levels deep mmm'ing? Or maybe I am just doing it wrong? Thanks! ``` (mmm-add-classes '((sf-elixir :submode mhtml-mode :front "^[ ]*~H\"\"\"$" ;; regex to find the opening tag :back "^[ ]*\"\"\"$"))) ;; regex to find the closing tag (mmm-add-mode-ext-class 'elixir-mode nil 'sf-elixir) (mmm-add-classes '((elixir-sf :submode elixir-mode :front "{{" ;; regex to find the opening tag :back "}}"))) ;; regex to find the closing tag (mmm-add-mode-ext-class 'mhtml-mode nil 'elixir-sf) ``` # Answer > 1 votes I've asked in the github repo, and it seems to not be supported at the moment, but could be implemented soon: https://github.com/purcell/mmm-mode/issues/102 --- Tags: mmm-mode ---
thread-54722
https://emacs.stackexchange.com/questions/54722
Select to the sentence of line in a shortcut
2020-01-06T15:45:49.103
# Question Title: Select to the sentence of line in a shortcut `C-k` and `M-k` could delete forward to the end of line and sentence respectively. How could only select to the end in a shortcut? Usually select a sentence and append it to a file for further reference with the following code: ``` ;; Captrue words (require 'thingatpt) (defun my-append-word () (interactive) (let ((word (if (not (region-active-p)) (word-at-point) (buffer-substring (region-beginning) (region-end))))) (with-current-buffer (find-file-noselect "~/Documents/OrgMode/ORG/src/build-vocabulary.org") (goto-char (point-max)) (insert word "\n") (save-buffer)))) ``` # Answer > 2 votes Command `mark-end-of-sentence` does what you request. It's not bound to a key by default, but you can bind it to one. `C-h f mark-end-of-sentence` tells you: > **`mark-end-of-sentence`** is an interactive compiled Lisp function in `paragraphs.el`. > > `(mark-end-of-sentence ARG)` > > Put mark at end of sentence. Arg works as in `forward-sentence`. > > If this command is repeated, it marks the next `ARG` sentences after the ones already marked. --- You can find this command by asking `apropos-command` (`C-h a`) for commands related to "mark" and "sentence": `C-h a mark sentence`. Commands that select text often have the word `mark` in their names, as selecting is about setting the mark at one end of the thing you're selecting (the end opposite point). --- Library Thing-At-Point Commands (`thing-cmds.el`) has generic command **`select-things`** (aliased to the name `mark-things`), to select successive THINGs of any kind that has an associated `forward-THING` command. If the region isn't active then you're prompted for the type of THING to use. If the region is active, you aren't prompted, and the last-used type of THING is used again. On consecutive uses of `mark-thing`, the region is active, so you aren't prompted, and the region is extended to successive things of the same type. This is true even if the region is empty, so you can just hit `C-SPC` to set mark and activate an empty region, then use `mark-thing` to select successive things of the last type used. Command `thgcmd-bind-keys` (interactively or in your init file) binds `C-M-SPC` to `select-things`. (Vanilla Emacs binds `C-M-SPC` to `mark-sexp`.) # Answer > 1 votes Use `S-C-e` and `S-M-e`, that is holding Shift while typing `C-e` and `M-e`, see (emacs) Shift Selection. --- Tags: region, mark, point, sentences ---
thread-54720
https://emacs.stackexchange.com/questions/54720
org -captue template display a fake board
2020-01-06T15:14:02.170
# Question Title: org -captue template display a fake board After I updated doom-emacs, the todo captuer template board displayed as It's actually a fake board because I custom them as ``` (setq org-capture-templates '(("n" "Personal Note" entry (file+function "~/Documents/OrgMode/ORG/src/todo.today.org" my-org-goto-last-personal-notes-headline) "* %T %?") ("t" "Personal Todo" entry (file+function "~/Documents/OrgMode/ORG/src/todo.today.org" my-org-goto-last-personal-tasks-headline) "* TODO %i%?") ("pn" "Project Note" entry (file+function "~/Documents/OrgMode/ORG/src/todo.today.org" my-org-goto-last-project-notes-headline) "* %T %?") ("pt" "Project Todo" entry (file+function "~/Documents/OrgMode/ORG/src/todo.today.org" my-org-goto-last-project-tasks-headline) "* TODO %i%?") ("T" "Tickler" entry (file+headline "~/Documents/OrgMode/ORG/src/tickler.org" "Tickler") "* %i%? \n %U"))) ``` So when I dispatch `pt`, it invoke 'project doto`rather than 'personal todo` Where could configure the board? # Answer > 2 votes Your setting is incorrect, `C-h v org-capture-templates`: > When using several keys, keys using the same prefix key must be together in the list and preceded by a 2-element entry explaining the prefix key, for example > > ``` > ("b" "Templates for marking stuff to buy") > > ``` so you need to put something like `("p" "Project Tasks")` right before your "pn" template, for example, ``` (setq org-capture-templates '(("p" "Project Tasks") ("pn" "Project Note") ("pt" "Project Todo"))) ``` --- Tags: org-mode, org-capture ---
thread-54684
https://emacs.stackexchange.com/questions/54684
ignore dependencies when setting CANCELED todo-state
2020-01-05T07:38:22.287
# Question Title: ignore dependencies when setting CANCELED todo-state **CONTEXT** I have `org-todo-keywords` set to `"TODO(t) | DONE(d) CANCELED(c)"`. Also, I have configured `org-todo-state-triggers` to ``` (cons 'quote (list (cons 'todo (list (cons org-archive-tag nil))) (cons "CANCELED" (list (cons org-archive-tag t))))) ``` This sets the `:ARCHIVE:` tag on the entire subtree, once the todo-state is set to `CANCELED`. It also automatically removes the tag if the todo-state is changed back to `TODO`. **PROBLEM** Finally, I have `org-enforce-todo-dependencies` set to `t`. This would prevent setting the todo-state to `DONE`, when any subtask is not yet `DONE`. Unfortunately, it has the undesirable side-effect, that until all subtasks are in done state (i.e. `DONE` or `CANCELED`), I would not be able to set the parent task to the **CANCELED** state, as it is blocked by the enforcement rule. Is there a way to make the **CANCELED** todo-state ignore the subtask dependencies, or even better, to set the entire subtree to **CANCELED** state atomically? # Answer > 2 votes It is actually explained in the docs that it is possible to simply override the enforcement of todo dependencies by using the `C-c C-t` command with triple prefix argument: `C-u C-u C-u`. Also, there is no need to set all the subtasks individually to `CANCELED` state, as the archive-tag archives the entire subtree, which removes all the subtasks from the agenda. # Answer > 2 votes I have not found a builtin way to accomplish this "easily", so I wrote the following two functions which can manually be invoked to change the status of all `todo states` in a subtree to `CANCELLED` and back. You can use `undo` right after cancelling to reset it but this won't work some days later, therefore the uncancel-function. **IMPORTANT:** This includes **ALL** `todo` keywords. If you created some other keywords like `HOLD` or `WAITING`, they will also be changed to `CANCELLED` and on "uncancelling" they will be set to `TODO`. `Done` keywords will remain as they are. (check the example) One Logbook entry will automatically be created for the main headline if desired. *You can change the `CANCELLED` to `CANCELED` in the first line (I didn't know both spellings are okay).* ``` ;; Since there are different spellings for that word we rather have a variable for it (setq org-cancel-keyword "CANCELLED") ;; Taken from http://doc.norang.ca/org-mode.html#Projects (defun bh/is-project-p () "Any task with a todo keyword subtask" (save-restriction (widen) (let ((has-subtask) (subtree-end (save-excursion (org-end-of-subtree t))) (is-a-task (member (nth 2 (org-heading-components)) org-todo-keywords-1))) (save-excursion (forward-line 1) (while (and (not has-subtask) (< (point) subtree-end) (re-search-forward "^\*+ " subtree-end t)) (when (member (org-get-todo-state) org-todo-keywords-1) (setq has-subtask t)))) (and is-a-task has-subtask)))) (defun my/org-cancel-subtree () (interactive) (save-mark-and-excursion (let ((projects (list))) (org-map-entries (lambda () (if (org-entry-is-todo-p) (if (bh/is-project-p) (push (point) projects) (org-todo org-cancel-keyword)))) nil 'tree) (dolist (project projects) (goto-char project) (org-todo org-cancel-keyword)))) ;; We need to mark the main project as cancelled, too (if (org-entry-is-todo-p) (org-todo org-cancel-keyword))) (defun my/org-uncancel-subtree () (interactive) (save-mark-and-excursion ;; Ignore the first line, so that the note will be inserted on the first line (let ((first-header (save-excursion (org-back-to-heading)(point)))) (org-map-entries (lambda () (if (not (= (point) first-header)) (org-todo "TODO"))) (concat "/" org-cancel-keyword) 'tree))) (org-todo "TODO")) ``` Here an example. Before cancellation: ``` * TODO My Tree ** TODO Some todo ** TODO A Project with TODOs in it *** TODO Some todo *** DONE A DONE todo *** TODO another project within a project **** TODO some todo **** HOLD This todo is on HOLD :LOGBOOK: - State "HOLD" from [2020-01-05 Sun 14:08] \\ reason :END: **** TODO some more todo **** Just an information - not a todo ** TODO more TODOs ** more Informations ** TODO Another TODO ``` After Cancellation: ``` * CANCELLED My Tree :CANCELLED: CLOSED: [2020-01-05 Sun 15:57] :LOGBOOK: - State "CANCELLED" from "TODO" [2020-01-05 Sun 15:57] \\ This is my cancellation Note. :END: ** CANCELLED Some todo :CANCELLED: CLOSED: [2020-01-05 Sun 15:57] ** CANCELLED A Project with TODOs in it :CANCELLED: CLOSED: [2020-01-05 Sun 15:57] *** CANCELLED Some todo :CANCELLED: CLOSED: [2020-01-05 Sun 15:57] *** DONE A DONE todo *** CANCELLED another project within a project :CANCELLED: CLOSED: [2020-01-05 Sun 15:57] **** CANCELLED some todo :CANCELLED: CLOSED: [2020-01-05 Sun 15:57] **** CANCELLED This todo is on HOLD :CANCELLED: CLOSED: [2020-01-05 Sun 15:57] :LOGBOOK: - State "HOLD" from [2020-01-05 Sun 14:08] \\ reason :END: **** CANCELLED some more todo :CANCELLED: CLOSED: [2020-01-05 Sun 15:57] **** Just an information - not a todo ** CANCELLED more TODOs :CANCELLED: CLOSED: [2020-01-05 Sun 15:57] ** more Informations ** CANCELLED Another TODO :CANCELLED: CLOSED: [2020-01-05 Sun 15:57] ``` After "uncancellation": ``` * TODO My Tree :LOGBOOK: - State "TODO" from "CANCELLED" [2020-01-05 Sun 17:30] - State "CANCELLED" from "TODO" [2020-01-05 Sun 15:57] \\ This is my cancellation Note. :END: ** TODO Some todo ** TODO A Project with TODOs in it *** TODO Some todo *** DONE A DONE todo *** TODO another project within a project **** TODO some todo **** TODO This todo is on HOLD :LOGBOOK: - State "HOLD" from [2020-01-05 Sun 14:08] \\ reason :END: **** TODO some more todo **** Just an information - not a todo ** TODO more TODOs ** more Informations ** TODO Another TODO ``` > Funfact: It took me about 3 hours and some useless debugging to find out that `/` prefix matches TODOs --- Tags: org-mode, todo, dependency ---
thread-54710
https://emacs.stackexchange.com/questions/54710
How to scroll using mouse while keeping cursor on same line/position?
2020-01-06T00:43:24.657
# Question Title: How to scroll using mouse while keeping cursor on same line/position? I am using this minor mode to scroll and keep cursor on same line, `mwheel-scroll` however screws up the smooth scroll since it moves the cursor to a different line, scrolling return the cursor back to original line but the visual is not smooth. I tried: ``` scroll-preserve-screen-position 'always ``` But that didn't help. This is the minor mode I am using: ``` (define-minor-mode centered-point-mode "Always center the cursor in the 1/3rd of the screen." :lighter "..." (cond (centered-point-mode (add-hook 'post-command-hook 'line-change)) (t (remove-hook 'post-command-hook 'line-change)))) (setq recenter-positions '(0.35)) (defun line-change () (interactive) (unless (memq this-command '(mwheel-scroll mac-mwheel-scroll)) (recenter-top-bottom))) (define-globalized-minor-mode my-global-centered-point-mode centered-point-mode (lambda () (centered-point-mode 1))) (my-global-centered-point-mode 1) ``` # Answer > 3 votes If you add the built-in `scroll-lock-mode` to your code, you should get behavior like what you want. Here's a slightly more-expansive update to your mode that fixes two other issues I found (the buffer-local version works normally and it doesn't change `recenter-positions` globally). Following your comments, I've also updated it not to rely directly on `scroll-lock-mode`, so it doesn't add any key bindings. ``` (defcustom centered-point-position 0.35 "Percentage of screen where `centered-point-mode' keeps point." :type 'float) (setq centered-point--preserve-pos nil) (define-minor-mode centered-point-mode "Keep the cursor at `centered-point-position' in the window" :lighter " centerpoint" (cond (centered-point-mode (add-hook 'post-command-hook 'center-point nil t) (setq centered-point--preserve-pos scroll-preserve-screen-position) (setq-local scroll-preserve-screen-position 'all)) (t (remove-hook 'post-command-hook 'center-point t) (setq-local scroll-preserve-screen-position centered-point--preserve-pos)))) (defun center-point () "Move point to the line at `centered-point-position'." (interactive) (when (eq (current-buffer) (window-buffer)) (let ((recenter-positions (list centered-point-position))) (recenter-top-bottom)))) (defun centered-point-mode-on () (centered-point-mode 1)) (define-globalized-minor-mode global-centered-point-mode centered-point-mode centered-point-mode-on) ``` Then use `(global-centered-point-mode 1)` to enable the mode globally. `centered-mouse-mode` seems to provide this functionality, so you might want to take a look at that as well. --- Tags: mouse, scrolling, cursor ---
thread-54728
https://emacs.stackexchange.com/questions/54728
What's the Emacs package that enables a "mini-mini-map" in the status bar?
2020-01-06T18:33:43.090
# Question Title: What's the Emacs package that enables a "mini-mini-map" in the status bar? I'm specifically talking about the package Spacemacs enables. It creates a tiny square with a horizontal bar, that goes up and down in accordance with your position in the file you have opened. E.g., if you're halfway down the file, the bar would be in the middle of the square. Also, there's a number beside the square, with a percentage, giving you what percent down the file you are. So, in the above scenario, it'd say 50%. Does anyone know what this package is, or how to enable this feature? # Answer The package is called spaceline. It can be installed via melpa. https://github.com/TheBB/spaceline > 1 votes --- Tags: spacemacs, minimap ---
thread-54729
https://emacs.stackexchange.com/questions/54729
how can I change the inferior Python process
2020-01-06T19:54:40.247
# Question Title: how can I change the inferior Python process I would like to be able to start Python 3 and ipython from Emacs in an inferior mode buffer. Currently `start interpreter C-c C-p` starts 2.7. I know there must be a way to change to start another python environment. # Answer > 1 votes Customize `python-shell-interpreter` to something else than `python`. --- Tags: python, process ---
thread-54734
https://emacs.stackexchange.com/questions/54734
mail attachment filename coding
2020-01-07T05:33:51.803
# Question Title: mail attachment filename coding I try to use mu4e with smtpmail to send mail, and use `mml-attach-file` to add attachment. If the attachment filename contains non-english name, such as Chinese, the header of message will become `Content-Disposition: attachment; =?us-ascii?Q?filename=3D=22=3D=3Futf-8=3FB=3F5aSN5Lmg5o+Q57qyLTE5LmRvY3g?=`, which can show correct filename in mu4e. And there is a `utf-8` coding in this header. But, it cannot be shown in some web mail client such as zoho and gmail and some local client. They display the name by themselves rules such as the mail's subject. And I check the one's header which attachment filename can be shown correctly, it is `Content-Disposition: attachment; filename*0*=utf-8''...` or `filename="=?UTF-8...` The first term of my emacs's coding-system in priority list is `utf-8`. `sendmail-coding-system` and `mm-coding-system` are `nil` or `utf-8`, which `nil` means use the same as emacs configuration. My language environment is `English`, and I also tried to set it to `UTF-8`, but it is no effect. By the way, my shell variable of `LANG` is `en_US.UTF-8`. Is there a way to make it work correctly? # Answer Setting `rfc2047-encode-encoded-words` to nil can make it work. > 0 votes --- Tags: email, unicode, smtpmail, attachment ---
thread-54690
https://emacs.stackexchange.com/questions/54690
Compile and run single file c++ programs in Emacs[SOLVED]
2020-01-05T12:38:15.777
# Question Title: Compile and run single file c++ programs in Emacs[SOLVED] I want to bind to a key a compile-and-run function to be able to compile my C++ single file programs and run them into a term/shell so I could give my variables values whenever I use `cin` in my programs. For example, in my Neovim config, I had this line: ``` autocmd FileType cpp nnoremap <F8> :w <CR> :vsp <CR> <C-w>l :term g++ % -o %< && ./%< <CR> i ``` I want to have something similar in Emacs. In Emacs, this line will be looking like so: ``` (define-key c++-mode-map (kbd "<f8>") #'compileandrun) ``` But I have no clue how the `compileandrun` function will look. edit 1: Here is a function I have tried ``` (defun compileandrun() (interactive) (compile (concat "g++ " (file-name-nondirectory (buffer-file-name)) " -o " (file-name-sans-extension (file-name-nondirectory (buffer-file-name))))) (term (concat "./" (file-name-sans-extension (file-name-nondirectory (buffer-file-name)))))) ``` it only compiles the program but it dosen't run it . # Answer > 2 votes `compile` uses the shell. You can chain program execution with `&&` like `g++ test.cc -o test && ./test`. With the last command `./test` is executed if compilation with `g++` succeeds. I'll modify your command accordingly: ``` (defun compileandrun() (interactive) (let* ((src (file-name-nondirectory (buffer-file-name))) (exe (file-name-sans-extension src))) (compile (concat "g++ " src " -o " exe " && ./" exe)))) ``` # Answer > 1 votes Here is the final elisp function that works. It automatically switches to the window and move the cursor to the bottom . ``` (defun compileandrun() (interactive) (save-buffer) (compile (concat "g++ " (file-name-nondirectory (buffer-file-name)) " -o " (file-name-sans-extension (file-name-nondirectory (buffer-file-name))) " && ./" (file-name-sans-extension (file-name-nondirectory (buffer-file-name)))) t ) (other-window 1) (end-of-buffer) ) (add-hook 'c++-mode-hook (lambda () (local-set-key (kbd "<f8>") #'compileandrun))) ``` If you have any improvments let me know . --- Tags: shell-command ---
thread-54741
https://emacs.stackexchange.com/questions/54741
Using company-ispell with large text dictionary?
2020-01-07T12:58:47.750
# Question Title: Using company-ispell with large text dictionary? I've managed to setup `company-ispell` which seems to work for small files, but fails for a dump of the aspell dictionary. This works when pressing `C-SPC` without any existing text before the cursor. But when there is some text e.g. `wheel`, there is no completion found. However when there is no prefix, there are multiple words starting with `wheel` in the list. ``` (use-package company :commands (company-complete-common)) (global-set-key (kbd "C-SPC") 'company-complete-common) (add-hook 'after-change-major-mode-hook (lambda () (when (derived-mode-p 'text-mode) (company-mode) (make-local-variable 'company-backends) ;; company-ispell is the plugin to complete words (setq company-backends (list 'company-ispell)) (setq ispell-complete-word-dict (expand-file-name (concat user-emacs-directory "aspell_words.txt"))) (when (and ispell-complete-word-dict (not (file-exists-p ispell-complete-word-dict))) (shell-command (concat "aspell -d en_US dump master > " ispell-complete-word-dict)))))) ``` In the `*Message*` buffer, there is output. ``` Starting "look" process... No completion found ``` Checking the process monitor, there aren't any hanging background processes. How can company-mode's `company-complete-common` be used to complete dictionary words? # Answer It turns out the word list needs to be sorted (case insensitive), at least sorting it makes it work for me. Assuming you use company mode and have a shortcut to activate it. ``` (use-package company :commands (company-complete-common)) (global-set-key (kbd "C-SPC") 'company-complete-common) ``` ``` ;; Dictionary for completion. (setq ispell-complete-word-dict (expand-file-name (concat user-emacs-directory "aspell_words.txt"))) (defun my-generic-ispell-company-complete-setup () ;; Only apply this locally. (make-local-variable 'company-backends) (setq company-backends (list 'company-ispell)) (when ispell-complete-word-dict (let* ( (has-dict-complete (and ispell-complete-word-dict (file-exists-p ispell-complete-word-dict))) (has-dict-personal (and ispell-personal-dictionary (file-exists-p ispell-personal-dictionary))) (is-dict-outdated (and has-dict-complete has-dict-personal (time-less-p (nth 5 (file-attributes ispell-complete-word-dict)) (nth 5 (file-attributes ispell-personal-dictionary)))))) (when (or (not has-dict-complete) is-dict-outdated) (with-temp-buffer ;; Optional: insert personal dictionary, stripping header and inserting a newline. (when has-dict-personal (insert-file-contents ispell-personal-dictionary) (goto-char (point-min)) (when (looking-at "personal_ws\-") (delete-region (line-beginning-position) (1+ (line-end-position)))) (goto-char (point-max)) (unless (eq ?\n (char-after)) (insert "\n"))) (call-process "aspell" nil t nil "-d" "en_US" "dump" "master") ;; Case insensitive sort is important for the lookup. (let ((sort-fold-case t)) (sort-lines nil (point-min) (point-max))) (write-region nil nil ispell-complete-word-dict)))))) ;; Enable this in appropriate modes. (add-hook 'org-mode-hook (lambda () (my-generic-ispell-company-complete-setup))) (add-hook 'rst-mode-hook (lambda () (my-generic-ispell-company-complete-setup))) (add-hook 'markdown-mode-hook (lambda () (my-generic-ispell-company-complete-setup))) ``` > 4 votes --- Tags: company-mode, ispell ---
thread-38350
https://emacs.stackexchange.com/questions/38350
Clearing the Contents of an Org-Mode Header Programmatically?
2018-01-25T19:14:13.063
# Question Title: Clearing the Contents of an Org-Mode Header Programmatically? If we have ``` * Header 1 Some contents. ``` Is there a way to programmatically kill the contents of `Header 1` so that it remains like: ``` * Header 1 ``` ? # Answer > 8 votes There isn't a command for deleting the subtree (i.e., the head line and all its contents), but there is a command to `mark` it. We can use that to get what you want: ``` (defun clear-subtree () (interactive) (org-mark-subtree) ;; mark the current subtree (forward-line) ;; move point forward, so the headline isn't in the region (delete-region (region-beginning) (region-end)) ;; delete the rest ) ``` # Answer > 7 votes There are many ways of removing the contents of a headline. Taylor gave you already a straight-forward text editing method which is good and which you should perhaps accept as an answer. But there is more. Orgmode has a well defined syntax and also routines for parsing and printing. So one way to change the contents of your org buffer is: * parsing the org buffer via `org-element-parse-buffer` * search the parse tree for the element you want to change via `org-element-map` * modify the element in the parse data * print out the parse data via `org-element-interpret-data` I give you an example for your special case of removing the content of `Header 1`. The following code returns a string with the text of buffer `test.org` modified with the contents of `Header 1` removed. ``` (with-current-buffer "test.org" (let* ((data (org-element-parse-buffer))) (org-element-map data 'headline (lambda (el) (when (equal (car-safe (org-element-property :title el)) "Header 1") (setf (nthcdr 2 el) nil) ;; Here we remove the contents from this headline. ))) (org-element-interpret-data data))) ``` Which method you should use strongly depends on the actual use-case. # Answer > 1 votes It seems you can use `org-map-entries` to do this as well: ``` #+BEGIN_SRC emacs-lisp :results none (let ((MATCH t) (SCOPE nil) (SKIP nil) (spacing nil)) (org-map-entries (lambda () (let ((name (nth 4 (org-heading-components)))) (if (string= name "Header 1") (save-restriction (org-mark-subtree) (forward-line) (delete-region (region-beginning) (region-end)) )) )) MATCH SCOPE SKIP)) #+END_SRC * Header 1 Content of header 1 * Header 2 Content of header 2 ``` If you run the source code block with `C-c C-c`, it will remove `Content of header 1` under `Header 1`. # Answer > 0 votes Another trick is to find the bounds of what you want to clear, and then move to the `END` and keep deleting the previous character until the value of point is smaller than the value of `START`. You may also want to preserve metadata information by setting the optional argument to a non-nil value. ``` (defun clear-subtree (&optional metadata) (let (start) (save-excursion (org-back-to-heading t) (if metadata (org-end-of-meta-data nil) (forward-line 1)) (setq start (point)) (org-end-of-subtree t) (while (>= (point) start) (delete-char -1))))) ``` --- Tags: org-mode ---
thread-54745
https://emacs.stackexchange.com/questions/54745
How to stop (aquamacs) emacs opening all new buffers in new (gui) window/emacs frame?
2020-01-07T16:20:54.730
# Question Title: How to stop (aquamacs) emacs opening all new buffers in new (gui) window/emacs frame? I've just upgraded my aquamacs installation and a bunch of packages, and now emacs is opening every new buffer in a new (gui) window (aka emacs frame). I don't like this. I want to have every buffer open in a new tab within the same frame. I already have this tabbar and window config, but it's not doing the trick: ``` (custom-set-variables '(pop-up-frames nil) '(pop-up-windows nil)) (use-package tabbar :ensure t :config (tabbar-mode 't)) ``` How do I keep my buffers all in one frame? I'm using version: Aquamacs 3.5 GNU Emacs 25.3.50.1 (x86\_64-apple-darwin16.7.0, NS appkit-1504.83 Version 10.12.6) # Answer > 1 votes The customization I want is: ``` (custom-set-variables '(one-buffer-one-frame-mode nil nil (aquamacs-frame-setup))) ``` Instead of: `(one-buffer-one-frame-mode t nil (aquamacs-frame-setup)))` --- Tags: buffers, window, frames, aquamacs ---
thread-46960
https://emacs.stackexchange.com/questions/46960
Unable to use emacsclient with emacs server when running mac port of emacs
2019-01-07T19:59:07.563
# Question Title: Unable to use emacsclient with emacs server when running mac port of emacs I am running the mac port version of emacs that I installed via homebrew (see here). I'm also trying to run the Emacs server to avoid long startup times. To do this, I first run the server: `/Applications/Emacs.app/Contents/MacOS/Emacs --daemon` This process appears to complete successfully. The next step is to start an emacs client like so: `/Applications/Emacs.app/Contents/MacOS/bin/emacsclient -n -c` However, when I run this command, nothing happens at all. If I run the command, without the `-c` option, a client opens in the terminal, but I want to run Eamcs in Cocoa. Has anyone run into this problem? # Answer > 2 votes I've been trying to figure out how to get a single emacs server running and having the ability to spin up emacsclients in GUI and TTY. Apparently, this is not possible in the Mac port due to (in the developer's words): ``` The developer has no idea how to detach Emacs as a GUI application from Window Server or Dock without separating a GUI process (not thread) from the main Emacs (Lisp evaluator) process. ``` See https://github.com/railwaycat/homebrew-emacsmacport/issues/52 for more info --- Tags: emacsclient, emacs-daemon, emacs-mac-port ---
thread-54744
https://emacs.stackexchange.com/questions/54744
Write text between inline exported code and the result of this execution code?
2020-01-07T14:54:41.320
# Question Title: Write text between inline exported code and the result of this execution code? After some search, i don't found example corresponding to my use case. Writing a research text, i'm interested to mix source blocks code and text with results using inline mode, for example this simple example : > Open a terminal and write `git --version` returning `git version 2.20.1` `git version 2.20.1` is the simple result of `src_sh[:results value :exports code]{git --version}`. But using this command it's impossible to inject text (here the word `returning`) between the exported code `git --version` and the result of `git -- version` evaluation. Is it possible to reproduce this behaviour using org-mode and org-babel ? **UPDATE 1 :** A short example of behaviour i want to achieve : Open your terminal and run the command `src_sh[exports:code]{git --version}` which return `$1`, go to `src_sh[exports: code]{cd /home/xxx/myproject}` and count the number of commit using `src_sh[exports:code]{git rev-list --all --count && git branch | wc -l }` returning `$1` commit(s) on `$2` branche(s). # Answer > 2 votes When I evaluate the inline src block: ``` src_sh[:results value :exports code]{git --version} ``` I get the following in my org mode buffer: ``` src_sh[:results value :exports code]{git --version} {{{results(=git version 2.24.1=)}}} ``` If you get the same thing, then the only thing you have to do is define a macro that will do what you want: ``` #+MACRO: results returning $1 ``` When you export, you should get exactly what you want. **UPDATE**: For your updated question, I would use src code blocks, not inline ones, but then call them inline. This is not quite what you want, but it is close: ``` #+MACRO: results $1 * Instructions Open your terminal and run the command =git --version= which returns call_gitversion[:exports results](), =cd /home/nick/emacs/emacs= and count the number of commits using =git rev-list --all --count && git branch | wc -l= returning call_ncommits[:exports results]() commit(s) on call_nbranches[:exports results]() branch(es). * Code :noexport: #+name: gitversion #+begin_src shell :exports none git --version #+end_src #+RESULTS: gitversion : git version 2.24.1 #+name: ncommits #+begin_src shell :exports none cd /home/nick/src/emacs/emacs git rev-list --all --count #+end_src #+RESULTS: ncommits : 145317 #+name: nbranches #+begin_src shell :exports none cd /home/nick/src/emacs/emacs git branch | wc -l #+end_src #+RESULTS: nbranches : 2 ``` And this was done in a hurry: caveat emptor. --- Tags: org-mode, org-export, org-babel ---
thread-42127
https://emacs.stackexchange.com/questions/42127
Org capture template not working (when trying to set local notes file)
2018-06-20T08:53:38.687
# Question Title: Org capture template not working (when trying to set local notes file) My goal is to get org-capture to store captured notes in a local "notes.org" file located in the same directory as the current working buffer. I set the template like so: ``` (setq org-capture-templates '(("x" "local notes" entry (file+headline (concat ,(file-name-directory buffer-file-name) "notes.org") "Copied regions") "* %^{Title} %U \n %i") ) ) ``` Alas, when invoking the template i get `Invalid file location: nil`. How should this be done? # Answer > 6 votes As the docs say, you can supply a function (with no arguments) to set the file here. Thus: ``` (setq org-capture-templates '(("x" "local notes" entry (file+headline (lambda () (concat (file-name-directory buffer-file-name) "notes.org")) "Copied regions") "* %^{Title} %U \n %i") )) ``` does the job. # Answer > 0 votes Change the leading apostrophe to a backquote on the template list. It will work then, no lambda needed! --- Tags: org-mode, org-capture ---
thread-54766
https://emacs.stackexchange.com/questions/54766
Piping contents of buffer into eshell command
2020-01-08T09:50:05.910
# Question Title: Piping contents of buffer into eshell command I know `eshell` supports output redirection to buffers ``` cmd > #<buffername> ``` Is there a way to do piping buffer contents into command? I would like to have something like ``` cat #<buffername> | cmd ``` The problem is that `cat` is not a builtin so it doesn't know `emacs` buffers. I could always save the buffer `buffername` to a file and then `cat` it but that is not always desired (e.g r-o filesystem) # In more detail I am passing from using a terminal emulator with zsh towards using eshell. Often I write scripts that run a command, pipe the output into `grep`,`gawk`, `sed` or whatnot and then pipe the result into another program. I would like to separate this into steps. I know `eshell` supports output redirection to buffer via ``` cmb > #<buffername> ``` I would then process the contents of `buffername` using powerful `emacs` tools. I know then that `eshell` **does not** support input redirection. I read in some manual to use pipes instead. If I saved the output to a file with `cmb > filename` I could then do ``` cat filename | cmd2 ``` but sometimes saving a `buffername` to a file `filename` is impossible or inconvenient. Any tips? # Answer > 3 votes You can use `M-|` (`shell-command-on-region`). Within eshell, you can use ``` ~ $ (with-current-buffer "*scratch*" (buffer-string)) | nl 1 ;; This buffer is for text that is not saved, and for Lisp evaluation. 2 ;; To create a file, visit it with <open> and enter text in its buffer. ~ $ ``` Eshell commands are Emacs functions, e.g,. ``` (defun kitty (buffer) (with-current-buffer buffer (buffer-string))) ``` ``` ~ $ kitty #<*scratch*> | nl 1 ;; This buffer is for text that is not saved, and for Lisp evaluation. 2 ;; To create a file, visit it with <open> and enter text in its buffer. 3 (defun kitty (buffer) 4 (with-current-buffer buffer 5 (buffer-string))) ~ $ ``` here is another way to write an eshell command, then you can invoke it via `your-cat` in eshell: ``` (defun eshell/your-cat (&rest args) (if (bufferp (car args)) (with-current-buffer (car args) (buffer-string)) (apply #'eshell/cat args))) ``` --- Tags: eshell, pipe ---
thread-54703
https://emacs.stackexchange.com/questions/54703
Exporting LaTeX commands to HTML/MathJax
2020-01-05T18:10:55.980
# Question Title: Exporting LaTeX commands to HTML/MathJax I am writing a document that is specifying a language with associated grammar and semantics. For this I have written the specification in Latex, using a method very similar to the one presented here. That is: it heavily uses Latex's `\newcommand` macros. However, the contents of the commands themselves are **nothing fancy** and falls *within* the subset of Latex that MathJax supports. I am slowly rewriting my documentation to Org mode, partially because of the HTML backend, allowing me to not only generate the original-ish PDF, but also a HTML page containing the same. Now my question is: how can I export my (big list of) Latex `\newcommand` macros to `Org` such that they get compiled back to their originals on the Latex backend, but to their MathJax equivalent when exporting with the HTML backend? **Bonus question**: Is it possible to *redefine* macros in MathJax? My original version contains several iterations of the same things, and overloads the macros by simply calling `\renewcommand`. Ideally, I would replicate this in MathJax, but it is not a dealbreaker: I can "simply" append some version id to each new iteration of the command, i.e. `\somecommandA`, `\somecommandB` etc. # Answer > 3 votes I ended up finding the following solution. I found a base solution on reddit that adds a "fake" language to babel as follows: ``` (add-to-list 'org-src-lang-modes '("latex-macros" . latex)) (defvar org-babel-default-header-args:latex-macros '((:results . "raw") (:exports . "results"))) (defun prefix-all-lines (pre body) (with-temp-buffer (insert body) (string-insert-rectangle (point-min) (point-max) pre) (buffer-string))) (defun org-babel-execute:latex-macros (body _params) (concat (prefix-all-lines "#+LATEX_HEADER: " body) "\n#+HTML_HEAD_EXTRA: <div style=\"display: none\"> \\(\n" (prefix-all-lines "#+HTML_HEAD_EXTRA: " body) "\n#+HTML_HEAD_EXTRA: \\)</div>\n")) ``` This lets you define a `latex-macros` block as follows: ``` #+BEGIN_SRC latex-macros \newcommand{\Z}{\mathbb{Z}} \newcommand{\Hom}{\mathrm{Hom}} #+END_SRC ``` For the Latex output, because it uses `#+LATEX_HEADER`, the commands are put in the preamble. For the HTML output, because of the `HTML_HEAD_EXTRA`, it is also put somewhere in the top of the document. This got near what I wanted, but not quite, as I wanted to be able to redefine commands. What I ended up doing was modifying the code to add a 2nd "fake" language `latex-macros-inline` that uses `#+BEGIN_EXPORT latex` and `BEGIN_EXPORT html` blocks like so: ``` (defvar org-babel-default-header-args:latex-macros-inline '((:results . "raw") (:exports . "results"))) (defun org-babel-execute:latex-macros-inline (body _params) (concat "\n#+BEGIN_EXPORT latex\n" body "\n#+END_EXPORT" "\n#+BEGIN_EXPORT html\n" "<div style=\"display: none\"> \n\\(\n" body "\n\\)\n</div>\n" "#+END_EXPORT")) ``` Because of these blocks, both the Latex and HMTL is outputted at the actual place the block is defined. --- Tags: org-mode, latex, html, mathjax ---
thread-54760
https://emacs.stackexchange.com/questions/54760
Is there a way to add git alias of customized log to magit?
2020-01-08T06:52:35.417
# Question Title: Is there a way to add git alias of customized log to magit? In `~./gitconfig`, I have ``` [alias] lg1 = log --graph --abbrev-commit --decorate --format=format:'%C(bold blue)%h%C(reset) - %C(bold green)(%ar)%C(reset) %C(white)%s%C(reset) %C(dim white)- %an%C(reset)%C(bold yellow)%d%C(reset)' --all ``` In magit, when type `ll`, it will log differently. Is there a way to add another keystroke combination (such as `lL`) in magit to do customization log as `lg1` above? # Answer > 1 votes It is possible to add additional commands to the log popup (or any other of its popup), but it would be far from trivial to implement your alias as a Magit command. It is not enough to pass the desired arguments to `git`, something then also has to parse the output. This is done in one of the darker corners of Magit, see `magit-log-wash-rev`. You would have to edit that function and add a new `magit-log-*-re` variable. So no, in practice you cannot do what you want to do. However you might not have to. Are you aware that you can show additional information in the *margin*, including the author and commit date? That seems to cover the additional information you want to display. See the documentation about the log margin. --- Tags: magit ---
thread-54063
https://emacs.stackexchange.com/questions/54063
Browse line range of file in GitHub with Magit
2019-11-29T00:37:42.537
# Question Title: Browse line range of file in GitHub with Magit Is it possible to select a range of code and open it in GitHub using Magit? I use the browse-at-remote package for this, but I wonder if this could be done from Magit. I'd like to navigate both from code selection and from a commit diff. Also, I'd like to be able to browse the master branch, even if I'm in a feature branch. Right now with browse-at-remote I have to manually replace the branch name with master in the GitHub URL. Thanks! # Answer > 1 votes The magit extension `forge` supports visiting certain things in a browser, but currently that is limited to issues, pull-requests, commits and the repository itself. Files and even locations within files might be supported in the future, or not. While I think this would be nice to have I don't plan to work on it any time soon. --- Tags: magit, github ---
thread-54750
https://emacs.stackexchange.com/questions/54750
Insert White-space to Right to Even Out Region
2020-01-07T19:34:10.487
# Question Title: Insert White-space to Right to Even Out Region Lets say I have the following block of text: ``` ---- ## ---- ## ---- ``` There is no white space after the # character. Is there some command to insert white space to the right of lines to even them with the longest line in the region? So it would become a rectangle of text, including spaces. # Answer > 0 votes I ended up writing a function for this. First it reads the region into a list, splitting it by newline character. It then loops over the list, getting the length of the longest line. It loops over the list of lines again, for each line adding enough spaces to reach the max line length, and then adding that padded line to a new list. This new list is then joined, with new line characters as separators. The region is replaced with this string. I'm sure its not very efficient, but lisp is still a mystery to me so I don't know how to edit in place. It's fast enough for my needs, though. ``` (defun fill-ws (beginning end) (interactive "r") ; Grab active region as string (setq region (buffer-substring-no-properties beginning end)) ; Split region string by new-line character (setq lines (split-string region " ")) ; Get the length of the longest line in the region (setq max_len 0) (dolist (element lines) (setq max_len (max max_len (length element))) ) ; For each line, pad it with enough spaces to reach length max_len ; Then, add it to a new list. (setq padded '() ) (dolist (element lines padded) (if (= (length element) max_len) (setq padded_line element) ; If the string is of length max_len, no need to pad ; If its shorter than max, concatenate with (max-len - len(element)) spaces (setq padded_line (concat element (make-string (- max_len (length element)) ? ))) ) ; Append the padded value to the list (setq padded (append padded (make-list 1 padded_line))) ) ; Join the new list to create replacement for region (setq replace (string-join padded " ")) ; Replace the region (save-excursion (delete-region beginning end) (insert replace) ) ) ``` --- Tags: text-editing ---
thread-54738
https://emacs.stackexchange.com/questions/54738
Using larger font with Powerline
2020-01-07T10:56:17.230
# Question Title: Using larger font with Powerline I've just switched to using spacemacs with powerline. I'm trying to make the font larger (my eyes are not as good as they used to be). But when I do, the powerline separator gets screwed up. Is there anyway to scale that up as well? I've update size to 16 (from 13) and changed powerline-scale to 0.8 (from 1.1) to try and counteract the size problem. ``` dotspacemacs-default-font '("Source Code Pro" :size 16 :weight normal :width normal :powerline-scale 0.8) ``` This is what I get # Answer > 1 votes Okay, I misunderstood how the `:powerline-scale` parameter works. To use with a larger font, I need to make it **larger** rather then smaller. For my situation, I scale factor of 1.5 seems to fix the issue. ``` dotspacemacs-default-font '("Source Code Pro" :size 16 :weight normal :width normal :powerline-scale 1.5) ``` --- Tags: spacemacs, powerline ---
thread-54754
https://emacs.stackexchange.com/questions/54754
How to change the company complete backend based on the current syntax?
2020-01-08T02:21:55.513
# Question Title: How to change the company complete backend based on the current syntax? I would like to have natural language completion (`company-ispell` for e.g.) but only when editing comments. How should the company back-end be swapped out when editing commensts? # Answer > 1 votes Insert below code into `~/.emacs` to enable `company-ispell` in comment, ``` (defun my-in-comment-p (pos) "Check whether the code at POS is comment by comparing font face." (let* ((fontfaces (get-text-property pos 'face))) (if (not (listp fontfaces)) (setq fontfaces (list fontfaces))) (delq nil (mapcar #'(lambda (f) ;; learn this trick from flyspell (or (eq f 'font-lock-comment-face) (eq f 'font-lock-comment-delimiter-face))) fontfaces)))) (eval-after-load 'company-ispell '(progn ;; use company-ispell in comment when coding (defadvice company-ispell-available (around company-ispell-available-hack activate) (cond ((and (derived-mode-p 'prog-mode) (or (not (company-in-string-or-comment)) ; respect advice in `company-in-string-or-comment' (not (my-in-comment-p (point))))) ; auto-complete in comment only (setq ad-return-value nil)) (t ad-do-it))))) ``` # Answer > 1 votes This is a modified version of @chen-bin's answer which uses a wrapper function instead of using advice (avoids interfering with other uses). It also generalizes the syntax checking to allow checking for other kinds of syntax. ``` (defun company-complete-common-use-context () (interactive) (let ((faces-found (face-at-point nil t)) (faces-comment-list '(font-lock-comment-face font-lock-comment-delimiter-face font-lock-doc-face))) (cond ((seq-intersection faces-found faces-comment-list) (let ((company-backends (list 'company-ispell))) (company-complete-common))) (t (company-complete-common))))) ``` Then bind the key to `company-complete-common-use-context`. --- Tags: completion, company-mode, comment ---
thread-51359
https://emacs.stackexchange.com/questions/51359
Spacemacs org-mode python session plotting problem
2019-07-02T20:02:57.307
# Question Title: Spacemacs org-mode python session plotting problem I have been using `org-mode` with R in Spacemacs for a while now with no issue. I'm moving my workflow from R to Python. Jupyter notebooks (EIN) works great, but I prefer `org-mode`: Normal (non-plot) blocks work well enough, but Emacs hangs when I try to plot using sessions (I can get it to plot if I don't use sessions). I get a message that says, `executing Python code block...` that remains until I escape with `C-g`. Here is an example of a function that won't print: ``` #+BEGIN_SRC python :session *Python* import glob from pandas import DataFrame, Series import pandas as pd import numpy as np import matplotlib.pyplot as plt from pandas.plotting import register_matplotlib_converters register_matplotlib_converters() import seaborn as sns plt.rcParams["figure.figsize"] = (15, 10) sns.set() #+END_SRC #+BEGIN_SRC python :session *Python* :results output drawer units.pivot_table('A', 'B', 'C', aggfunc=len).fillna(0).plot() fig=plt.figure(figsize=(6,4)) plt.savefig('test.png') 'test.png' #+END_SRC ``` I really want to use `org-mode` instead of notebooks. Any idea what I need to correct to make it work? # Answer > 0 votes Try usimng ipython blocks instead of python (`#+BEGIN_SRC ipython`) and add the following line to your first source block: ``` %matplotlib inline ``` Note - I'm not sure if this will work with Spacemacs, but it is what scimax is all about. I used Spacemacs for about 6 months for python and jupyter notebooks before I switched to scimax for org-mode and never looked back. --- Tags: org-mode, spacemacs, python ---
thread-54749
https://emacs.stackexchange.com/questions/54749
Linked, Split screen scrolling for a single buffer?
2020-01-07T19:16:55.553
# Question Title: Linked, Split screen scrolling for a single buffer? I would like to be able to have * a `C-x 3` split to have two windows in a frame * both windows view a single buffer * window on left ends at line n * window on right starts at line n +/- configurable offset * vertical scrolling action scrolls BOTH windows Does something like this already exist? # Answer > 2 votes The closest existing tool to what I have asked for is `follow-mode`: Cliffs: * `M-x follow-mode` to trigger manually * `(setq follow-auto t)` to trigger automatically * `C-c . 1` or `M-x follow-delete-other-windows-and-split` to maximise the current buffer in a two column format --- Tags: window-splitting, scrolling ---
thread-54705
https://emacs.stackexchange.com/questions/54705
How do I add text to every new buffer that I create?
2020-01-05T19:06:04.840
# Question Title: How do I add text to every new buffer that I create? Suppose I want to put my name and the date at the top of every new buffer that I create. How would I do that? Furthermore, suppose I want to use the name of the new buffer in the text that I want to place automatically, where what text is placed depends on a parameter that I specify. Let's say if the parameter is "java" then the text placed will be ``` public class [Filename without file extension] { static void main (String[] args) { } } ``` or if it's "cpp" then, ``` public class [Filename without file extension] { int main(int argc, char** argv) { } } ``` # Answer 1. Define a function that inserts the boilerplate code you want, at the buffer position you want. 2. Put that function on a relevant hook. For #2, one of these might be a relevant hook: * `window-configuration-change-hook` \- used when you change buffers * `write-file-hooks` \- used when you write a file to disk * `find-file-hook` \- used when you visit a file * A major mode hook But there are lots of other hooks, some of which might be relevant for your use case. --- This question is closely related, I think. It's about automatically inserting a file header. See also the questions under tag `[yasnippet]` (put that in the Search field). > 2 votes # Answer Have a look at the autoinsert package which will do much of what you want although maybe not all. > -1 votes --- Tags: hooks, insert, file-header ---
thread-54793
https://emacs.stackexchange.com/questions/54793
Adjusting indenting for lisp if statements
2020-01-09T07:41:57.043
# Question Title: Adjusting indenting for lisp if statements I am learning common lisp and am trying to follow the style guide suggested by lisp-lang.org. In this style guide is an `if` statement style that I think makes the code more readable: ``` (if (cond) (true-branch) (false-branch)) ``` That is, the branches line up. I find this to be syntactically easier to read. Using `lisp-mode` with no extra goodies the default seems to be: ``` (if (cond) (true-branch) (false-branch)) ``` For some strange reason. The false block is pushed back to line up with the `f` of the if statement. I find this a little jarring. Is there a way to clean this up so I can have the default formatting conform the linked styleguide? # Answer > 3 votes # Why is Emacs so weird? Emacs indents lisp code as if it were Emacs Lisp, where `if` accepts unlimited `else` forms; unlike in Common Lisp, where `if` accepts at most 3 arguments. # What to do? Tell Emacs to indent Lisp as if it were Common Lisp: ``` (custom-set-variables '(lisp-indent-function 'common-lisp-indent-function)) (autoload 'common-lisp-indent-function "cl-indent" "Common Lisp indent.") ``` --- Tags: indentation, common-lisp, emacs-lisp-mode, lisp ---
thread-54799
https://emacs.stackexchange.com/questions/54799
How to jump multiple lines in emacs?
2020-01-09T12:00:29.503
# Question Title: How to jump multiple lines in emacs? Suppose I want to jump x amount of lines up or down. Is there a convenient command for it? # Answer > 2 votes To discover an existing command that moves up or down lines, use command `apropos-command`, bound to `C-h a` by default. Commands involving lines often have `line` in their name. So try that: `C-h a line RET`. Among the displayed command names and their descriptions, you'll find `next-line` and `previous-line`. --- Tags: help, motion ---
thread-54811
https://emacs.stackexchange.com/questions/54811
Open link of file in org mode with its defalut application rather than within spacemacs
2020-01-09T18:38:35.193
# Question Title: Open link of file in org mode with its defalut application rather than within spacemacs really new to `spacemacs`, I want to open a link (which is a file stored somewhere on my computer and the full path is used) inserted into `org-mode` file of `spacemacs` with the default application of such file, say excel, rather than within `spacemacs`. I searched up online, it seems like below is the solution: `(setq org-file-apps '("\\.xlsx\\'" . "excel %s"))`,but this throw out the error : `wrong type argument: listp "excel $s"`. See these links for your reference and any helpful suggestion is deeply appreciated. I'm on the latest develop branch of `spacsmacs`, if this is of any use. link\_1, link\_2, link\_3 # Answer > 2 votes The documentation says that `org-file-apps` should be a list of cons cells but you have supplied a single cell instead. Solution: one more set of parens: ``` (setq org-file-apps '(("\\.xlsx\\'" . "excel %s"))) ``` You now have a list containing a single cons cell and `org-file-apps` should be happy. --- Tags: org-mode, spacemacs ---
thread-54789
https://emacs.stackexchange.com/questions/54789
How to quickly jump to a directory in emacs?
2020-01-09T00:56:06.637
# Question Title: How to quickly jump to a directory in emacs? Say I have a project directory called "project". In the directory there are two directories "mini1" and "mini2". Suppose my active buffer is deep within a subdirectory in "mini1". Is there a way to make a C-f like binding where the pre-existing directory text is /project/mini2/ and not the deeply nested directory under mini1 that I'm in? # Answer > 1 votes Use `find-directory-in-project-by-selected` from https://github.com/technomancy/find-file-in-project I also wrote a prototype in pure Lisp. It does not use any third party command line program or package, ``` (require 'find-lisp) (require 'dired) (require 'ido) (defun my-open-dir-in-project () "Open directory in project." (interactive) (let* ((root (locate-dominating-file default-directory ".git")) (input-regex (read-string "Input regex (or press ENTER): ")) (ignored-regex ".*/\\.git\\|.*/\\.svn\\|.*/\\.bzr") (find-lisp-regexp (if (string= input-regex "") ".*" input-regex)) (cands (find-lisp-find-files-internal root 'find-lisp-file-predicate-is-directory 'find-lisp-default-directory-predicate)) selected) (when cands (setq cands (delq nil (mapcar `(lambda (c) (unless (string-match-p ,ignored-regex c) c)) cands))) (setq selected (and cands ;; `ido-completing-read' could be replaced with `ivy-read' (ido-completing-read (format "directories %s: " root) cands)))) (when selected (switch-to-buffer (dired selected))))) ``` --- Tags: commands, directories ---
thread-54823
https://emacs.stackexchange.com/questions/54823
How to run commands from other packages if they exist, without depending on them?
2020-01-10T00:52:39.800
# Question Title: How to run commands from other packages if they exist, without depending on them? I have package that has no relation to evil-mode, but doesn't work well when the command is repeated. While the repeat command can be disabled, I don't want to add a dependency on evil mode just to do this. I also want to avoid the load-order of my package and evil causing my package not to detect evil mode. While this works, it's not elegant, is there a better way to handle this? ``` (if (fboundp 'evil-declare-not-repeat) (progn (evil-declare-not-repeat 'my-foo-cmd) (evil-declare-not-repeat 'my-bar-cmd) (evil-declare-not-repeat 'my-baz-cmd)) (with-eval-after-load 'evil (evil-declare-not-repeat 'my-foo-cmd) (evil-declare-not-repeat 'my-bar-cmd) (evil-declare-not-repeat 'my-baz-cmd))) ``` # Answer This can be done using `with-eval-after-load` which runs after the package has been loaded, or immediately if it's already loaded. --- Submitting own answer, although there may be better alternatives. ``` (declare-function evil-declare-not-repeat "ext:evil-common") (with-eval-after-load 'evil (evil-declare-not-repeat 'my-foo-cmd) (evil-declare-not-repeat 'my-bar-cmd) (evil-declare-not-repeat 'my-baz-cmd)) ``` > 1 votes --- Tags: package-development ---
thread-54816
https://emacs.stackexchange.com/questions/54816
python interpreter within emacs fails on simple test on __main__ (syntax error)
2020-01-09T22:22:43.800
# Question Title: python interpreter within emacs fails on simple test on __main__ (syntax error) This small program runs well in Terminal : ``` mac2011% cat bug.py print(__name__ == "__main__") #if True: if __name__ == "__main__": print("main") else: print("not main") mac2011% python bug.py True main mac2011% python --version Python 3.6.9 :: Anaconda, Inc. ``` In Emacs: ``` mac2011% Emacs --version GNU Emacs 26.3 mac2011% Emacs -q bug.py ``` the file opens in (Python ElDoc) mode. Python menu Start interpreter (C-c C-p) Eval buffer (C-c C-c) ``` Python 3.6.9 |Anaconda, Inc.| (default, Jul 30 2019, 13:42:17) [GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> python.el: native completion setup loaded >>> Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Users/alba/Documents/projets/plot time series/bug.py", line 5 else: ^ SyntaxError: invalid syntax >>> ``` Replacing `if __name__ == "__main__":` by `if True:`, there is no more error. Replacing `"__main__"` by `"__main_"`, there is no error. Can you reproduce the facts? Do you have any explanation? How to repair? Same with Python 3.7.6. My emacs comes from Emacs for Mac OS X. Same with emacs 28.0.50 that I have just built. # Answer > 6 votes Use `C-u C-c C-c`. See `python-shell-buffer-substring` function docstring: > When optional argument `NOMAIN` is non-nil everything under an `if __name__ == '__main__'` block will be removed. And `python-shell-send-buffer`: > When optional argument `SEND-MAIN` is non-nil, allow execution of code inside blocks delimited by `if __name__== '__main__':`. When called interactively `SEND-MAIN` defaults to nil, unless it’s called with prefix argument. So the code actually sent by `C-c C-c` is: ``` print(__name__ == "__main__") #if True: else: print("not main") ``` --- Tags: python, syntax ---
thread-54791
https://emacs.stackexchange.com/questions/54791
How to check if two lists share any elements?
2020-01-09T03:50:03.067
# Question Title: How to check if two lists share any elements? Besides looping over list items and comparing, what is a good way in elisp to check if there are any shared items between two lists? For example, in Python this can be done with sets or list comprehension. ``` a = [1, 2, 3] b = [3, 5, 0] ``` ``` items_shared = bool(set(a) & set(b)) ``` Or by checking in a loop. ``` items_shared = any(True for v in a if v in b) ``` --- Edit: for the purpose of this question, the same comparison rules for `memq` seem reasonable. # Answer > 7 votes You can use `seq-intersection`, it is documented in its docstring and (elisp) Sequence Functions: > seq-intersection is a compiled Lisp function in \`seq.el'. > > ``` > (seq-intersection SEQUENCE1 SEQUENCE2 &optional TESTFN) > > ``` > > Return a list of the elements that appear in both SEQUENCE1 and SEQUENCE2. Equality is defined by TESTFN if non-nil or by \`equal' if nil. for example, ``` (seq-intersection '(2 3 4 5) '(1 3 5 6 7)) ;; => (3 5) ``` Another choice is `cl-intersection` from cl-lib.el, unlike `seq-intersection`, it works for just lists, and it uses `eql`/`eq` for testing by default. # Answer > 3 votes I think xuchunyang's is the correct answer, as `seq-intersection` is a generic function that can work on any built-in or user-defined sequence type, accepts a custom equality predicate, and perfectly conveys the intention, which is to determine whether two sequences intersect. All these benefits come with some performance overhead, of course, but the performance of `seq-intersection` should be fine for many applications. However, OP voiced some performance concerns in a comment. If one really wants to juice this for all the speed they can get, my first suggestion would be to step back and think about whether the application can be designed so that list intersection, an `O(MN)` operation at worst, isn't necessary. For example, can the lists be sorted, or are their lengths known ahead of time, or can a hash table be used instead, etc. Failing all of that, a custom intersection function can be written. For generalisation to all sequence types, one should continue to use the `seq.el` library: ``` (defun my-seq-intersect-p (seq1 seq2 &optional testfn) "Return non-nil if any elements of SEQ1 appear in SEQ2. Comparison is done with TESTFN if non-nil, otherwise `equal'." (seq-some (lambda (elem) (seq-contains-p seq2 elem testfn)) seq1)) ``` In my benchmarks, this runs slightly faster than `seq-intersection` because of reduced consing and garbage collection, but the difference isn't great. If the function need only accept lists and the required equality predicate is known ahead of time, then the function can be made far faster as follows: ``` (defun my-list-intersect-p (list1 list2) "Return non-nil if any elements of LIST1 appear in LIST2. Comparison is done with `equal'." (while (and list1 (not (member (car list1) list2))) (pop list1)) list1) ``` Other lookup functions like `memq`, `cl-member`, etc. can be used in place of `member` if needed. There is also room for future optimisations in `seq.el` itself. --- Tags: list ---
thread-54827
https://emacs.stackexchange.com/questions/54827
How to loop zoom-frm-in?
2020-01-10T13:27:46.683
# Question Title: How to loop zoom-frm-in? Every time I dock/undock I must hit 10 times `M-x` `zoom-frm-in`. Since I don't understand the `dotimes` example in the lisp tutorial I need to know how you would automate this task. # Answer > 1 votes `(dotimes (number 10) (zoom-frm-in))` Found here: https://emacs.stackexchange.com/a/2507/21118 --- Tags: zooming ---
thread-54765
https://emacs.stackexchange.com/questions/54765
Can a mode setup function fail?
2020-01-08T09:37:39.940
# Question Title: Can a mode setup function fail? If I define a new mode using `define-derived-mode` or `define-minor-mode`, can the mode setup somehow signal failure so that the mode is not activated? All of the following modes are activated despite the error. ``` (define-derived-mode foo-major-mode fundamental-mode "Foo" "Docstring" (error "Unable to set up Foo major mode")) (define-minor-mode foo-local-minor-mode "Docstring" (when foo-local-minor-mode (error "Unable to set up Foo local minor mode"))) (define-minor-mode foo-global-minor-mode "Docstring" :global t (when foo-global-minor-mode (error "Unable to set up Foo global minor mode"))) ``` # Answer No, the mode has *already* done a whole bunch of stuff before your error happens. Use `M-x` `pp-macroexpand-last-sexp` to see what your definitions expand to, and where your mode body code *actually* runs. If you want to prevent a mode from being enabled, the logic needs to be in the place which tries to enable the mode. Alternatively, you can add some `before` advice to your mode function -- that *will* run before anything else happens. (I wouldn't particularly recommend this approach without knowing that there was a good reason for doing it, though.) > 2 votes # Answer For a minor mode, you can do: ``` ... (setq foo-local-minor-mode nil) (error "Unable to set up Foo local minor mode") ``` For a major mode it's a bit different: there's basically no such thing as "removing" a major mode, the only thing you can hope to do is to go back to the previous major mode (but that requires saving it beforehand) or switch to some "bare" major mode. To "go back", the only standard option is `major-mode-restore`, which requires you've done a `major-mode-suspend` bedforehand. This is used for example in `image-mode` to switch between the "view image" and the "view underlying data" mode (where the underlying data is often binary junk but can be text in cases like Postscript, SVG, XPM, ...). To set a "bare" major mode you could do: ``` (fundamental-mode) ``` which will revert to (surprise, surprise) `fundamental-mode`. > 1 votes --- Tags: major-mode, minor-mode, error-handling ---
thread-53867
https://emacs.stackexchange.com/questions/53867
how to set a fill suffix?
2019-11-19T19:38:53.227
# Question Title: how to set a fill suffix? I want to fill (wrap) long lines at *n* characters, ensuring that each new line ends with "///". (That is the "continuation character" for long lines in Stata code. So that something like this ``` This is a long line. This is a long line. This is a long line. This is a long line. This is a long line. This is a long line. ``` would be broken up into something like this ``` This is a long line. This is a long line. This is a long line. This /// is a long line. This is a long line. This is a long line. ``` (where the first line, along with the /// is no more than *n* characters. I see info about *prefixes* in the fill section of the manual, but nothing about suffixes. Thanks! # Answer > 0 votes There's very little support for it in Emacs's standard infrastructure, sadly. You can try using something like: ``` (add-function :around (local 'comment-line-break-function) #'my-insert-triple-slash-at-eol) (defun my-insert-triple-slash-at-eol (orig-fun &rest args) (insert "///") (apply orig-fun args)) ``` --- Tags: fill-paragraph ---
thread-54830
https://emacs.stackexchange.com/questions/54830
Change buffer background color on LaTeX compile error, or highlight errors more prominently?
2020-01-10T13:53:22.657
# Question Title: Change buffer background color on LaTeX compile error, or highlight errors more prominently? I am using Emacs+Auctex to write LaTeX code. When compiling a document that contains an error, Emacs writes ``` LaTeX errors in ‘*~/doc output*’. Use C-c ` to display. ``` to the Messages buffer (and displays it below the mode line). I often overlook this and continue to work on an erroneous document. Is it possible to configure Emacs such that the background color of a LaTeX buffer is changed (e. g., to light red), if a document is compiled that raises an error? And the color changes back when the error is fixed and the document is re-compiled? Alternatively, are there any other, possibly simpler, ways to highlight LaTeX compile errors more prominently? # Answer I had the same problem as you. My solution was to add the status of the last Latex compilation (in bright colors) to the mode line. An error is displayed in red so it is hard to overlook. Here is the code (you can add it to your init file): ``` (setq last-latex-compilation-status "No Compilation") (setq-default mode-line-format (append mode-line-format '((:eval (last-latex-compilation-status-update nil))))) (defun last-latex-compilation-status-update (arg) "Update the string that holds the status of the last latex compilation" (setq last-latex-compilation-status (save-excursion (set-buffer "*Messages*") (goto-char (point-max)) (if (search-backward-regexp "^LaTeX\\(.*\\)$" nil t nil) (let ((compilationstatus (match-string 1))) (cond ((string-match "successfully" compilationstatus) (propertize "Success" 'font-lock-face '(:background "green"))) ((string-match "errors" compilationstatus) (propertize "Error" 'font-lock-face '(:foreground "red"))) ((string-match "unresolved" compilationstatus) (propertize "Unresolved" 'font-lock-face '(:foreground "blue"))) (t "No Compilation"))))))) ``` > 1 votes --- Tags: latex, auctex ---
thread-54810
https://emacs.stackexchange.com/questions/54810
Clojure nrepl: 'cider-jack-in returns error: "Spawning child process: Invalid argument"
2020-01-09T17:58:27.897
# Question Title: Clojure nrepl: 'cider-jack-in returns error: "Spawning child process: Invalid argument" Running GNUEmacs 26.3 on Windows 10, trying to set up environment per instructions for 'Clojure for the Brave and True' from here: https://github.com/flyingmachine/emacs-for-clojure/ I was able to get the packages built and such, looks like it behaves ok. However, when I start a `lein repl` in the directory and call `M-x cider-jack-in`, I get: ``` Spawning child process: Invalid argument ``` Not sure where to go from here. # Answer Try `M-x cider-connect` if you've already started a REPL via leiningen yourself. `cider-jack-in` tries to start a repl-server and connect to it. For some reason, this fails, maybe because of the already running REPL, so you might try `cider-jack-in` without starting a REPL manually first. > 1 votes --- Tags: process, clojure, cider ---
thread-54835
https://emacs.stackexchange.com/questions/54835
Creating Shell-Based Filter in .emacs.d/init.el
2020-01-10T17:51:42.727
# Question Title: Creating Shell-Based Filter in .emacs.d/init.el This could be a useful FAQ for non-emacs-programmers. > What should I put into `.emacs.d/init.el` in order to hard-code a specific shell filter that will replace the contents of the region? For example, say I wanted to create an emacs command named `uniqc` that replaces the region with the output of `uniq -c`. This should presumably be based on `shell-command-on-region`... If I figure it out myself, I will post it tomorrow. # Answer > 2 votes If I understand you properly, you're asking how to automate calling a command with a specific set of arguments. To do this, first take a look at the command in question: `C-h f shell-command-on-region`: > shell-command-on-region is an interactive compiled Lisp function in ‘simple.el’. > > It is bound to M-|, . > > (shell-command-on-region START END COMMAND &optional OUTPUT-BUFFER REPLACE ERROR-BUFFER DISPLAY-ERROR-BUFFER REGION-NONCONTIGUOUS-P) > > ... This gives us the outline of the command we want to call. The part I've trimmed at the end explains the arguments in detail. The command you actually want to call is: ``` (shell-command-on-region <beginning-of-region> <end-of-region> "uniq -c" nil t) ``` We need to replace the bits in `<...>` with actual elisp. The `apropos` command can help here: `M-x apropos region beginning`: > ... > region-beginning Function: Return the integer value of point or mark, whichever is smaller. > > ... That's handy. The same thing works for `region end`, although there are a few more things to work through. That gets us the following: ``` (shell-command-on-region (region-beginning) (region-end) "uniq -c" nil t) ``` Now all we need to do is wrap that in an interactive function, aka a `command`, that we can call: ``` (defun uniqc () (interactive) (shell-command-on-region (region-beginning) (region-end) "uniq -c" nil t)) ``` Now we can test that out. Paste it in your *scratch* buffer, but the cursor after the end of the defun, and type `C-j`. Then set a region, and call `M-x uniqc`. Voila! It does what we want. You can save that code directly in your .emacs, and then you'll have `uniqc` available everytime you start emacs. You can also bind it to a key if you want a shortcut; there are lots of questions here about keybindings. Finally, there's a convenience for getting the region beginning and end that can make our function a little neater: ``` (defun uniqc (BEG END) (interactive "r") (shell-command-on-region BEG END "uniq -c" nil t)) ``` See the elisp manual for a full explanation of how to use the `interactive` form. # Answer > 1 votes ``` (defun my-filter (start end) (interactive "r") (shell-command-on-region start end "uniq -c" 1 ;; use current buffer 1 ;; replace the text region selected nil t nil)) ``` --- Tags: shell-command ---
thread-54840
https://emacs.stackexchange.com/questions/54840
Can icomplete mode be enabled selectively, only for certain commands?
2020-01-10T21:28:24.390
# Question Title: Can icomplete mode be enabled selectively, only for certain commands? I'd like to use icomplete-mode for certain commands, but not for everything. Is there a way to enable it for just a list of commands I specify? # Answer IIRC, Currently, the only way icomplete offers to control it is via `icomplete-with-completion-tables` which is rather inflexible. Of course, you could enable/disable it for specific commands by advising those commands and temporarily rebinding `icomplete-with-completion-tables` accordingly. > 0 votes --- Tags: completion, minibuffer, icomplete ---
thread-54844
https://emacs.stackexchange.com/questions/54844
How to get the point position relative to thing-at-point?
2020-01-11T03:51:59.723
# Question Title: How to get the point position relative to thing-at-point? When using `thing-at-point` to get a word or filename - for example, how can I get the cursor position relative to the text? Either by getting the absolute starting location of the thing, or a relative character index. # Answer You find the following answer within the code of `thing-at-point`: ``` (defun start-of-thing-at-point (thing) "Get start of THING at point." (let ((bounds (bounds-of-thing-at-point thing))) (and bounds (car bounds)))) ``` For your examples `thing` should be either `'word` or `'filename`. Tested with 26.3. > 2 votes --- Tags: thing-at-point ---
thread-54843
https://emacs.stackexchange.com/questions/54843
Place time displayed in the beginning of modeline
2020-01-11T03:00:37.303
# Question Title: Place time displayed in the beginning of modeline I installed doom-emacs and modeline displayed as How could I place the time `10:55 AM` in the beginning, since if more windows are opened and arranged horizontally, the directory names are long enough to push "displayed time" out of view? # Answer > 6 votes You can re-define the main mode line with `doom-modeline-def-modeline`. The first argument is the mode line type, the second argument is the left-hand segment list, and the third argument is the right-hand segment list. Shift the `misc-info` entry from the right-hand segment list to the beginning of the left-hand segment list. With the current version of the main mode line you get after this modification: ``` (with-eval-after-load "doom-modeline" (doom-modeline-def-modeline 'main '(misc-info bar workspace-name window-number modals matches buffer-info remote-host buffer-position word-count parrot selection-info) '(objed-state persp-name battery grip irc mu4e gnus github debug lsp minor-modes input-method indent-info buffer-encoding major-mode process vcs checker))) ``` Tested with emacs 26.3 and `doom-modeline-20200110.440`. Disclaimer: I do not use `doom-modeline`. That is just what I got in a couple of minutes. Maybe, there is another way to re-configure `doom-modeline`. --- Tags: mode-line ---
thread-34901
https://emacs.stackexchange.com/questions/34901
ORGMODE Exporting to text without wrapping
2017-08-15T13:19:05.013
# Question Title: ORGMODE Exporting to text without wrapping As simple as that. Everytime I export from orgmode to text the lines are wrapped. How to disable this? Thank you, E. # Answer John Kitchin initially wrote a simple program to do this. He then improved it and made it into ox-clip a org-mode based Emacs package, which is easy to get through Melpa's repository. Not only does it avoid wrapping text, it also preserves the format on the clipboard so that it is a breeze to paste. ox-clip may need you to install a clipboard manager depending on your system. Specific installation instructions can be found here. > 2 votes # Answer Org-mode provides the customization variable `org-ascii-text-width`. If you set this to a large enough value, it has the effect of not wrapping text blocks during export to plain text. However, doing this also does weird things to text that the exporter tries to present as centered titles and subtitles. That applies to the contents of `#+TITLE:` and `#+AUTHOR:` lines, and probably other similar options. You can turn these off via the customization variables `org-export-with-title` and `org-export-with-author`. I don't see any obvious way of modifying the title formatting in a way that wouldn't get mangled by long lines. > 3 votes # Answer Once in a while, I'm drafting e-mails in an orgmode buffer. I'd like to export the plain text, but without wrapped lines. Usually I forget to disable auto-fill-mode while writing. So after finishing the text, I copy it into scratch, mark it and then: `M-x replace-string Ctrl-q Ctrl-j Ctrl-q Ctrl-j RET XXXX RET`. Result: Every new paragraph is replaced by XXXX. Next step: `M-x replace-string Ctrl-q Ctrl-j RET <space> RET` : I'm replacing the single newlines with a singel space. Next step: `M-x replace-string XXX RET Ctrl-q Ctrl-j RET` : I'm replacing the XXXX against the former new paragraphs. Ready for copy and paste. --- # Edit: After OP made a comment about the `#+OPTIONS:`, I found that you can write `#+OPTIONS: \n:nil` into the preamble of the org file, which is supposed to toggle whether to preserve line breaks (\`org-export-preserve-breaks'). Then -- thanks to Tyler -- I customized org-ascii-text-width. Set it to 10000 and you don't get a line break. But unfortunately the exporter assumes the pagewidth were that large and pushes the sections and the title \_far\_far\_ away. > 0 votes --- Tags: org-export ---
thread-54329
https://emacs.stackexchange.com/questions/54329
Prepend to block of text, but ignore blank lines
2019-12-12T02:39:09.183
# Question Title: Prepend to block of text, but ignore blank lines How to add the string 'export ' to the beginning of each line of this text, with emacs: ``` RBENV_VERSION="2.n.0" AUTHORIZE_NET_API_LOGIN_ID=example AUTHORIZE_NET_TRANSACTION_KEY=example # Google Calendar Integration # Google Calendar GOOGLE_CLIENT_ID=example GOOGLE_CLIENT_SECRET=example # Live Mailchimp keys MAILCHIMP_API_KEY=example ``` # Answer An answer to a different question would be to add ``` _oldflags=$- ; set -a ``` as the first line of the file and ``` [[ "$_oldflags" =~ a ]] || set +a ; unset _oldflags ``` which tells bash to export all the variables (the set -a) and restore the state of the "set -a" flag at the end. If you never use "set -a" then this can be simplified to adding "set -a" at the start and "set +a" at the end. > 1 votes # Answer Here's one way: ``` (defun doit () (interactive) (while (not (eobp)) (beginning-of-line) (when (looking-at "[A-Z]") (insert "export ")) (next-line))) ``` This will walk through the lines starting at the cursor until the end of the buffer, and if the line starts with a capital letter (per the given regular expression range), then it will prepend with the string. To use, paste this into \*scratch\*, position your cursor after the last close paren, and hit C-x C-e to load the definition. Then go to the buffer with your text, position your cursor on the first line you want to change, and invoke with `M-x doit`. Of course this could be enhanced to only work in a region, parameterize in various ways, etc. Another option, if you don't want to define a function, is to adapt the approach into a macro like this: 1. Go to the first line you want to change in your buffer 2. Type C-x ( to start recording macro 3. Type C-a to go to beginning of line (don't skip this step even if you're already at the beginning of the line) 4. Type M-: to bring up the "Eval:" prompt and enter `(when (looking-at "[A-Z]") (insert "export "))` 5. Type C-n to go to the next line 6. End the macro with C-x ) 7. Repeat the macro a bunch of times: C-u 10 C-x e > 1 votes --- Tags: text-editing, rectangle ---
thread-54801
https://emacs.stackexchange.com/questions/54801
What's the rules to bind keys
2020-01-09T12:36:26.447
# Question Title: What's the rules to bind keys I learn the `mark-end-of-sentence` is handy to select to end of the sentence as handy as C-M-Space which select a word. from Select to the sentence of line in a shortcut The function is not bound by default, so I tried kinds of keys permutations. * one option is C-M-s (s for sentence) and C-M corresponding to C-M-Space to select a word, then faild. `(global-set-key (kbd "C-M-s") #'mark-end-of-sentence)` global-set-key (kbd “C-M-s”) 'mark-end-of-sentence * It remind me that M-e move-forward to end of a sentence, then set 'C-M-e`which cover the original`(sp-end-of-sexp &optional ARG)\`, still failed. `(global-set-key (kbd "C-M-s") #'mark-end-of-sentence)` * Final solution, I set a key sequence randomly. Take it seriously, what's the rules to bind keys? Two items I could get: 1. Not conflict with the current important and frequent keys 2. as semantic as possible to assistance memory. I am determined passing my emacs.config to the grandsons, how could I play a intelligent role from now? # Answer Per the conventions referenced in a comment on the question, > Sequences consisting of `C-c` and a letter (either upper or lower case) are reserved for users; they are the **only** sequences reserved for users, so do not block them. So as a user, you redefine arbitrary keys outside of that range at your own risk, though of course people do it all the time. Recently as I work on my config I've been trying to go back to original conventions as much as possible. For example, one of the first things in my first .emacs in 1995 was to bind `query-replace-regexp` to M-s (instead of M-%), but I've just turned it back to M-%. It's still customized because I want regexp by default instead of regular, but it follows the convention so is more portable, easier to talk to others about, less likely to conflict with functionality added in the future, etc. For what bindings I do add, I have been trying to use custom prefix maps as a way to get unconstrained namespaces. Relevant to your example about commands to mark things, I have a "mark-map" to support different functions to mark text objects. Of course you still need to bind the map to some prefix key, and maybe C-M-SPC would be a good choice, so `mark-word` would become C-M-SPC w. Or if you wanted to be more standards compliant you could use C-c m. Or I think meta-capital-letter combinations are overlooked; how about M-M (shift-meta-m)? ``` (defvar mark-text-object-map (make-sparse-keymap) "Keymap for selecting text objects") (global-set-key (kbd "C-M-SPC") mark-text-object-map) (global-set-key (kbd "C-M-@") mark-text-object-map) ;; How C-M-SPC shows up in some terminals (define-key mark-text-object-map (kbd "b") #'mark-whole-buffer) (define-key mark-text-object-map (kbd "w") #'mark-word) (define-key mark-text-object-map (kbd "s") #'mark-end-of-sentence) ... ;; get a listing of the available commands (define-key mark-text-object-map (kbd "?") #'(lambda () (interactive) (with-help-window (help-buffer) (with-current-buffer (help-buffer) (insert (substitute-command-keys "\\{mark-text-object-map}")))))) ``` All that said, binding new keys isn't everything. Decomposition can be a good strategy. Sometimes it's easier to do C-SPC M-f, or C-SPC M-e, than it is to bind and use a dedicated command :) > 1 votes --- Tags: key-bindings ---
thread-54831
https://emacs.stackexchange.com/questions/54831
Change font or point colour based on absolute path of the source file
2020-01-10T15:10:23.070
# Question Title: Change font or point colour based on absolute path of the source file This is a rare occasion when I need it, but I am trying to figure out a way to change colour of font/point based on the path of source file to easily distinguish which file I am editing when I am working on two similar repositories. (E.g. based on files from */some/path/local\_master* and */some/path/remote\_master*). Any advice? # Answer > 1 votes You could use a directory-local variable. Relevant documentation node. To use this, you create a file `.dir-locals.el` in the root of each project dir with contents like: ``` ((nil . ((my/is-local . t)))) ``` Then in your config you need to do two things, you need to set the variable as safe so Emacs doesn't prompt you about it whenever it loads a file in that directory, and you need to modify your display however you want based on it. Below is an example: ``` ;; Mark any boolean value as safe. ;; See https://stackoverflow.com/q/19806176/4851078 (put 'my/is-local 'safe-local-variable #'booleanp) ;; Set unfontified text in buffers from the local repo to dark blue ;; See https://www.emacswiki.org/emacs/FacesPerBuffer (add-hook 'find-file-hook #'(lambda () (when (bound-and-true-p my/is-local) (buffer-face-set '(:foreground "#003"))))) ``` --- Tags: hooks, faces, point ---
thread-54861
https://emacs.stackexchange.com/questions/54861
How to check if a list ends with another list?
2020-01-12T10:24:20.660
# Question Title: How to check if a list ends with another list? Currently I'm using a fairly inefficient way to check if one list uses another list at it's end. Is there a more efficient way to do this? ``` (defun is-in-list (ls-haystack ls-ends-with) (catch 'found (while (not (or (eq ls-haystack t) (null ls-haystack))) (when (eq ls-haystack ls-ends-with) (throw 'found t)) (setq ls-haystack (cdr ls-haystack))))) ``` # Answer What you are looking for is known in Common Lisp as `tailp` and is present in Emacs Lisp as `cl-tailp`: ``` (defun cl-tailp (sublist list) "Return true if SUBLIST is a tail of LIST." (while (and (consp list) (not (eq sublist list))) (setq list (cdr list))) (if (numberp sublist) (equal sublist list) (eq sublist list))) ``` > 5 votes # Answer Use `nthcdr`: ``` (let* ((x '(4 5)) (y `(1 2 3 . ,x))) (eq (nthcdr (- (length y) (length x)) y) x)) ;; => t ``` ``` (defun foo (list list2) "Return t if LIST ends with LIST2." (eq (nthcdr (- (length list) (length list2)) list) list2)) (let ((x (list 4 5))) (foo (cons 1 (cons 2 x)) x)) ;; => t ;; it is ok if LIST is shorter than LIST2 (foo '(1 2) '(1 2 3 4)) ;; => nil ``` > 0 votes --- Tags: list ---
thread-54866
https://emacs.stackexchange.com/questions/54866
Make pdf-tools highlight persist after searching
2020-01-12T14:38:38.133
# Question Title: Make pdf-tools highlight persist after searching Is it possible to make the highlight of searched terms persist after pressing `RET`? I had liked very much the behavior of `zathura` in this aspect. My question is : Can `pdf-tools` be tweaked to have the same behavior of `isearch` with `isearch-lazy-highlight-cleanup` set to `nil`? (i.e. make highlighting persist after stop searching) # Answer I know nothing about `pdf-tools`. But it sounds like you're just asking how to make Isearch's lazy highlighting persist after you stop searching. If so, the answer to that is to set user option `lazy-highlight-cleanup` to `nil`. `C-h v` tells you: > **`lazy-highlight-cleanup`** is a variable defined in `isearch.el`. > > Its value is `t` > > Documentation: > > Controls whether to remove extra highlighting after a search. > > If this is `nil`, extra highlighting can be "manually" removed with `M-x lazy-highlight-cleanup`. > > You can customize this variable. > 1 votes --- Tags: isearch, highlighting, pdf-tools ---
thread-54796
https://emacs.stackexchange.com/questions/54796
Instruct Emacs never to open files of a certain type or size
2020-01-09T09:38:25.953
# Question Title: Instruct Emacs never to open files of a certain type or size In Emacs by default there is a large file warning threshold. I would prefer to instruct Emacs *never* to open files of a certain type or size. These are files I would prefer always to open in an external application. I now have it set up that I can use the shortcut key C-RET to open a file in an external application. Sometimes however I accidentally press RET and Emacs prompts me as to whether I would like to open the file. My preferred response would be for Emacs to do nothing, not even to prompt me. Otherwise, I would prefer to always open the type in the default external app. # Answer It sounds like you want this only for interactive use, i.e., a command. Define your own substitute for command `find-file` (or `find-file-other-window` etc.). Have you command check the file size, using functions `file-attributes` and `file-attribute-size`, and refuse to open the file if it is bigger than some threshold you set. For example (untested): ``` (defvar my-find-file-max-size 100000 "Max size for `my-find-file'.") (defun my-find-file (file &optional wildcards) "`find-file`, unless FILE is > `my-find-file-max-size' bytes." (interactive (find-file-read-args "Find file: " (confirm-nonexistent-file-or-buffer))) (when (> (file-attribute-size (file-attributes file))) (error "File %s is too big" file)) (find-file file wildcards)) ``` > 2 votes # Answer I am grateful to @Drew for also providing me with similar code for Emacs Dired. With it, clicking on a large file in Dired will result in a message about the file being too big to open. ``` (defun my-dired-find-file () "Like `dired-find-file', but raise error file is too big." (interactive) (let ((find-file-run-dired t) (switch-to-buffer-preserve-window-point (if dired-auto-revert-buffer nil switch-to-buffer-preserve-window-point)) (file (dired-get-file-for-visit))) ;; Check file size, and raise error if too big. (when (> (file-attribute-size (file-attributes file)) large-file-warning-threshold) (error "File %s is too big" file)) (find-file file))) (define-key dired-mode-map [remap dired-find-file] 'my-dired-find-file) ``` The size of the file will depend here on the value of the variable `large-file-warning-threshold`. > 1 votes --- Tags: files, find-file, large-files ---
thread-38381
https://emacs.stackexchange.com/questions/38381
Shell coding system
2018-01-26T18:38:52.823
# Question Title: Shell coding system If, before `M-x shell`, I run `C-x RET c` (`universal-coding-system-argument`) I can change the coding system used by the shell. Therefore, given ``` echo Straße > foo ``` `foo` will be encoded in the related CS. How can I change the coding system after issuing `M-x shell`? More generally, how can I set comint input/output encoding? # Answer As regards Linux, the behaviour can be controlled by with: ``` (setenv "LANG" ENCODING) ``` before calling `M-x shell` and after from the shell buffer with: ``` (set-buffer-process-coding-system INPUT-ENCODING OUTPUT-ENCODING) ``` Both should be set to a value compatible with the string to be represented. UTF-8 encoding family should work in most of the cases. To learn about current encoding, we can use: ``` (getenv "LANG") (process-coding-system (get-buffer-process (current-buffer))) ``` Note that `(setenv "LANG" ENCODING)` affects all subsequently created processes, which will inherit the `LANG` value; `(set-buffer-process ...` and `(process-coding-system...` are buffer specific, so they require that the related (shell) buffer is current when called. For the most cases this should work ``` M-S-: (setenv "LANG" "en_US.UTF-8") M-x shell M-S-: (set-buffer-process-coding-system 'utf-8-unix 'utf-8-unix) echo Straße > foo ``` On the contrary, using `(setenv "LANG" "en_US")` (without UTF-8), would print in the console or the file weird characters. Chances there are that the proper values (UTF-8 based) are already the default ones. As regards Windows, the function `set-buffer-process-coding-system` still applies, but there is no `LANG` variable in Windows. Windows represents the encodings in terms of *code page* numbers. Code pages are often associated to several languages, for example most of the Western languages (though not US English) are encoded through code page 850. To learn about the system code page consult the registry key: ``` HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Nls\CodePage\OEMCP ``` When in the language setting you change Windows default input language, you might end up changing this value, e.g. switching from US to UK English changes `OEMCP` value from 437 to 859. You can manually change this value and there is a code page equivalent to UTF-8, that is 65001. While 65001 (UTF-8) could be the standard in the future (like already is for Linux), given the relevant changes, you might break some non-unicode apps with CP 65001. Luckly, it is possible to easily set the code page in the Windows command prompt, rather than system wide, with the `chcp` command (change code page). Under the Emacs perspective this boils down to: ``` M-x shell chcp 65001 dir type foo.txt ``` In practice, assuming you have an English Windows, the command `dir` and `type` should be able to correctly show respectively filenames and file content in Russian or Chinese. > 1 votes --- Tags: shell, character-encoding, process, comint ---
thread-54869
https://emacs.stackexchange.com/questions/54869
Enable auto-save based on filename
2020-01-12T16:51:08.587
# Question Title: Enable auto-save based on filename How can I enable auto-save based on filename? I use a naming convention (a prefix to the filename) for my notes and I'd like to enable auto-save for those files. # Answer I don't know if there is a "correct" way to make this happen. What comes to my mind is: ``` (defvar my-auto-save-regexp "/jdigit") (defun my-auto-save-mode-fn () (when (string-match my-auto-save-regexp buffer-file-name) (auto-save-mode 1))) (add-hook 'find-file-hook 'my-auto-save-mode-fn) ``` > 1 votes --- Tags: auto-save ---
thread-3593
https://emacs.stackexchange.com/questions/3593
Move cursor with respect to indentation
2014-11-15T22:50:04.200
# Question Title: Move cursor with respect to indentation Is there any way to enable the following behavior. Let's say i have some code: ``` def main(args: List[String]): Unit = { } ``` Of cause the blank line between braces is indented, but when i move cursor to that position i need to hit tab to place it on the proper column according to my indentation settings, can i enable such behavior by default? E.g in the given example, if i move cursor up or down, the cursor would be in this position: ``` def main(args: List[String]): Unit = { | } ``` But i want it to be in this: ``` def main(args: List[String]): Unit = { | } ``` # Answer The command `back-to-indentation` (bound to `M-m` by default) moves point to the first non-whitespace character on the current line. Arranging for it to be called whenever you move the cursor is a matter of advising the correct function. For example, the following will cause `back-to-indentation` to be called whenever you move up: ``` (advice-add 'previous-line :after #'back-to-indentation) ``` However, I strongly advise against such a customization: you most probably want to go to the indentation only in a limited set of occasions (maybe for whitespace-only lines?). Most of the time, you probably expect your cursor to stay on the same column when moving up or down. > 2 votes # Answer Old question, but: You can make it so that all the common ways of moving around do an auto-indent, like this: ``` (advice-add 'previous-line :after #'indent-according-to-mode) (advice-add 'next-line :after #'indent-according-to-mode) (advice-add 'scroll-up-command :after #'indent-according-to-mode) (advice-add 'scroll-down-command :after #'indent-according-to-mode) (add-hook 'isearch-mode-end-hook #'indent-according-to-mode) ``` This has side effects; as you move around, (a) indentation on non-blank lines will be fixed up, and (b) if you move to a non-blank line within the indentation, the cursor will be automatically pushed to the beginning of the text as with `back-to-indentation`. Maybe these are good side effects. However, there is a shortcoming that you can arrive on lines in other ways, like for example if the blank line happens to be at the end of the buffer and you do `Alt`-`>`, or when you pop the mark ring. But the above might cover enough of the movement scenarios to meet the requirement. I couldn't find a hook that is called after cursor movement of any kind, so if you wanted to be more thorough you might have to use `post-command-hook` which starts to seem like a pretty invasive change. A bigger issue is that this approach leaves trailing whitespace everywhere in your document. (To see it, do `Ctrl`-`Alt`-`s` `[[:space:]]+$` or turn on `global-whitespace-mode`). So you could also patch the navigation commands to remove the trailing whitespace before moving away, but even if you do there are ways in which the cleanup will fail to be invoked, like if you save while positioned on an indented blank line. Probably a better approach is not to bother with incremental clean-up, and just sweep the whole document on save, with something like `(add-hook 'before-save-hook 'delete-trailing-whitespace)` in your config \[ref\].) In all, this is probably not a good thing to do to Emacs because it coarsens your control over the content of the document. > 2 votes --- Tags: indentation ---
thread-29303
https://emacs.stackexchange.com/questions/29303
Remap redo to C-S-/
2016-12-15T08:41:59.143
# Question Title: Remap redo to C-S-/ I do not like the standard keybinding to redo so I would like to customise it. How can I remap redo to C-S-/? I am not able to find any solution in internet. # Answer > 2 votes If you haven't already try undo-tree.el. It gives Emacs a conventional undo, otherwise you need to undo the undos in order to redo--there is no redo function... With it you can add: ``` (global-set-key (kbd "C-s-/") 'undo-tree-redo) ``` to your emacs init file, or where ever you keep custom keybindings, and walk back and forward through any change. # Answer > 1 votes By default, Emacs doesn't support redo with a single key-stroke. You can do one of the following. --- Tags: undo, mapping ---
thread-54845
https://emacs.stackexchange.com/questions/54845
Projectile command for debug and release
2020-01-11T04:02:39.493
# Question Title: Projectile command for debug and release My google searches aren't turning up anything useful, but I am trying to figure out how I" can use projectile-project-compilation-cmd to be able to dynamically switch between release and debug with cmake, ie I would like to be able to somehow do a theoretical projectile-project-compilation-cmd-debug, projectile-project-compilation-cmd-release, but I have no idea how to go about doing this. Thanks for suggestions! # Answer You could use `projectile-test-project` (bound to `C-p p P`) as your debug command and `projectile-compile-project` (bound to `C-p p c`) as your release command. `projectile-toggle-between-implementation-and-test` (bound to `C-p p t`) also seems promising but I haven't used this yet, so I can't help you set this up. > 1 votes --- Tags: projectile, compile ---
thread-54881
https://emacs.stackexchange.com/questions/54881
How to remove subdirectories inserted into the dired buffer with i?
2020-01-13T09:09:49.223
# Question Title: How to remove subdirectories inserted into the dired buffer with i? Pressing `i` on a subdirectory in the dired mode inserts that directory in the buffer. How can I remove it from the buffer? # Answer > 13 votes **TL;DR**: Type `C-u``k` on the subdirectory header line. Quoth `(emacs) Subdirectories in Dired`: ``` Use the ‘l’ command (‘dired-do-redisplay’) to update the subdirectory’s contents, and use ‘C-u k’ on the subdirectory header line to remove the subdirectory listing (see Dired Updating). You can also hide and show inserted subdirectories (see Hiding Subdirectories). ``` and `(emacs) Dired Updating`: ``` If you use ‘k’ to kill the line for a directory file which you had inserted in the Dired buffer as a subdirectory (see Subdirectories in Dired), it removes the subdirectory listing as well. Typing ‘C-u k’ on the header line for a subdirectory also removes the subdirectory line from the Dired buffer. ``` and `(emacs) Hiding Subdirectories`: ``` “Hiding” a subdirectory means to make it invisible, except for its header line. ‘$’ Hide or show the subdirectory that point is in, and move point to the next subdirectory (‘dired-hide-subdir’). This is a toggle. A numeric argument serves as a repeat count. ``` How I navigated the manual: 1. `C-h``r` (`info-emacs-manual`) 2. `i` (`Info-index`) 3. `subdir``TAB``RET` (autocompletes to `subdirectories in Dired`) --- Tags: dired ---
thread-44081
https://emacs.stackexchange.com/questions/44081
How to tweak `org-emphasis-alist' to put, e.g., neon-yellow over bold (or italic, underscole...) text?
2018-08-12T15:05:33.610
# Question Title: How to tweak `org-emphasis-alist' to put, e.g., neon-yellow over bold (or italic, underscole...) text? I read here that I could colorize the markup in my `org-mode` configuration, so I searched, and here I found an example. The problem is when I append this code, as the answer suggests, to my `.emacs`: ``` (add-to-list 'org-emphasis-alist '("*" (:foreground "red"))) ``` When I restart Emacs, I get this error: > Warning (initialization): An error occurred while loading ‘c:/Users/username/.emacs’: > > Symbol's value as variable is void: org-emphasis-alist > > To ensure normal operation, you should investigate and remove the cause of the error in your initialization file. Start Emacs with the ‘--debug-init’ option to view a complete error backtrace. # Answer > 9 votes EUREKA! To everyone struggling like me to obtain an "easy to make highlight style", Make something like this: ``` (setq org-emphasis-alist '(("*" (bold :foreground "Orange" )) ("/" italic) ("_" underline) ("=" (:background "maroon" :foreground "white")) ("~" (:background "deep sky blue" :foreground "MidnightBlue")) ("+" (:strike-through t)))) ``` # Answer > 3 votes In general, you can only `add-to-list` to an already defined variable. The variable `org-emphasis-alist` is not defined until org-mode is loaded. So you need to delay the `add-to-list` until after it is loaded: just move it to (say) the end of your init file (assuming that somewhere in your init file, org-mode is loaded). *HOWEVER* that is not going to work in this particular case, because `org-emphasis-alist` is a special variable: (re)setting it has no effect until the new value has been used to recalculate a bunch of stuff that depends on it. So you either need to figure out how to do these recalculations, so you can do them by hand after modifying the variable in your init file (*not* recommended) or you have to find an easier way. The easiest way to deal with this case is to use the customization mechanism: customize the value of `org-emphasis-alist`, save it (for this and future sessions) and you should be all set. The customization mechanism takes care of recalculating the extra stuff. # Answer > 1 votes As a comment to the answer by wing (but not enough reputation points to comment), `org-emphasis-alist` is a customizable variable so that it can be customized via the customization menu. It is found in the `Org group` under the subgroup `Org Appearance`. Modifications applied via the customization menu should be persistent over sessions. --- Tags: org-mode, init-file, org-emphasis ---
thread-54889
https://emacs.stackexchange.com/questions/54889
org-mode capture click event within org-babel code block
2020-01-13T18:50:00.193
# Question Title: org-mode capture click event within org-babel code block I wish to run C-c C-c, then click any code line to trigger my code (print "clicked" in this demo) ``` #+BEGIN_SRC elisp :results output (defun myclick(n) (interactive "p") (print "clicked") ) (add-hook 'org-mode-hook '(lambda () (local-set-key (kbd "<mouse-1>") #'myclick))) #+END_SRC ``` But it doesn't print out anything now. # Answer > 1 votes `C-c C-c` evaluates the code which adds the function to the hook, but the hook is not run: you need to close the file and reopen it in order for the hook to run. Or you can add this to the code block: ``` (run-hooks 'org-mode-hook) ``` That will run the hook, which will do the `local-set-key` to set the mouse click to your function. --- Tags: org-mode, org-babel ---
thread-54877
https://emacs.stackexchange.com/questions/54877
Override org-insert-link for those that match a pattern
2020-01-13T06:15:38.767
# Question Title: Override org-insert-link for those that match a pattern I often need to keep track of conversations that happen in Slack, so I wrote a small elisp package that retrieves all message info (channel, timestamps, message(s)) for a given Slack permalink. Then I convert the data to org-element using `org-element-interpret-data`. Now, I need to find a way to either override `org-insert-link` so whenever I want to insert a link and it happens to match a pattern, it would not insert link as is, but extracts Slack data using my method and inserts that instead. What's the best way of doing something like this? # Answer Usually advising functions can be used to change the behavior of a function. But for this interactive function it would get complicated when looking at the source. Fortunately `org-mode` (version 9.1+) has a built-in method to add custom link types which is the preferred way in this case: ``` (org-link-set-parameters TYPE &rest PARAMETERS) ``` An example that should come close to what you have in mind: ``` (defun my-org-link-insert-slack-data (&optional arg) "Get the slack link and insert the data." (let ((slack-link (read-string "slack link: "))) ;; Use your function here to insert the slack data. (insert slack-link))) (org-link-set-parameters "slack" :complete #'my-org-link-insert-slack-data) ``` Evaluate the example code and then run `M-x org-insert-link`. The custom link type `slack` can be selected: Then it prompts you for the slack link and inserts the text entered at point. Usually the completing function has to return a string. But as long as I have understood your question correctly you don't really want to insert a link. Therefore the function just inserts the text itself. Org will show an user error in the minibuffer (`wrong type argument: stringp, nil`) but it still works. It would probably be better to just use a function for this and not rely on `org-insert-link` at all. > 0 votes --- Tags: org-link ---