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-29239
https://emacs.stackexchange.com/questions/29239
Reflection on function argument signatures
2016-12-12T03:53:33.337
# Question Title: Reflection on function argument signatures Is there anything built into elisp for reflection on function argument signatures? I have used `(length (cadr (symbol-function #'my/function)))`, but this notably fails on built-in C functions. I'm sure there are probably limitations because of function representation and there being argument keywords and destructuring in different contexts, but the goal here is strictly exploratory. Possibilities: * signature length (arity) * has optional args * min signature length * ... # Answer Here's the code I have in my dot files. This code evolved over the years while maintaining backward compatibility; it should work with any Emacs or XEmacs version since the late 19.x series. If you only care about recent versions, the code can undoubtedly be simplified. ``` (cond ;; XEmacs ((fboundp 'compiled-function-arglist) (defalias 'emacsen-compiled-function-arglist 'compiled-function-arglist)) ;; GNU Emacs (t (defun emacsen-make-up-number-arglist (start end tail) (while (< start end) (setq end (1- end)) (setq tail (cons (intern (format "a%d" end)) tail))) tail) (defun emacsen-compiled-function-arglist (func) (let ((a (aref func 0))) (if (integerp a) ;; An integer encoding the arity. Encountered in Emacs 24.3. ;; http://emacs.stackexchange.com/questions/971/argspec-or-arity-of-a-bytecode-function-in-emacs-24/973#973 (let ((arglist (if (zerop (logand a 128)) nil '(&rest rest))) (mandatory (logand a 127)) (nonrest (lsh a -8))) (if (> nonrest mandatory) (setq arglist (cons '&optional (emacsen-make-up-number-arglist mandatory nonrest arglist)))) (emacsen-make-up-number-arglist 0 mandatory arglist)) ;; Otherwise: this is the arglist. The only format I've seen up to GNU 23. a))))) (defun interactive-spec (function &optional safe) "Return the interactive calling specs of FUNCTION. Signal an error if FUNCTION does not have interactive calling specs. However, in this case, if optional second argument SAFE is non-nil, return nil." (want-type 'functionp function) (while (symbolp function) (setq function (symbol-function function))) (condition-case e (progn (if (eq (car-safe function) 'autoload) (progn (if (null (fifth function)) (signal 'wrong-type-argument `(interactivep ,function))) (load (third function)))) (cond ((byte-code-function-p function) (or (if (fboundp 'compiled-function-interactive) (compiled-function-interactive function) (aref function 5)) (signal 'wrong-type-argument `(interactivep ,function)))) ((and (consp function) (eq 'lambda (car function))) (or (cdr (assq 'interactive (cdr (cdr function)))) (signal 'wrong-type-argument `(interactivep ,function)))) (t (signal 'failure `(interactive-spec ,function ,@(and safe (list safe))))))) (wrong-type-argument (if (and (eq (car-safe (cdr e)) 'interactivep) safe) nil (signal 'wrong-type-argument (cdr e)))))) (defun function-argspec (func) "Return a function's argument list. For byte-compiled functions in Emacs >=24, some information may be lost as the byte compiler sometimes erases argument names. In this case, fake argument names are reconstructed." (if (symbolp func) (setq func (indirect-function func))) (cond ((or (subrp func) (and (consp func) (eq (car func) 'autoload) (consp (cdr func)) (consp (cdr (cdr func))) (stringp (car (cdr (cdr func)))))) (let ((docstring (documentation func))) (save-match-data (if (string-match "\n.*\\'" docstring) (let ((form (read (match-string 0 docstring)))) (cdr form)) nil)))) ((byte-code-function-p func) (emacsen-compiled-function-arglist func)) ((and (consp func) (eq (car func) 'lambda) (consp (cdr func))) (car (cdr func))) ((and (consp func) (eq (car func) 'closure) (consp (cdr func)) (consp (cdr (cdr func)))) (car (cdr (cdr func)))) (t (signal 'wrong-type-argument (list 'functionp func))))) (defun function-arity (func) "Return a function's arity as (MIN . MAX). Return minimum and maximum number of args allowed for SUBR. The returned value is a pair (MIN . MAX). MIN is the minimum number of args. MAX is the maximum number or the symbol `many', for a function with `&rest' args, or `unevalled' for a special form. This function is like `subr-arity', but also works with user-defined and byte-code functions. Symbols are dereferenced through `indirect-function'." ;; TODO: keyword support (if (symbolp func) (setq func (indirect-function func))) (cond ((and (subrp func) (fboundp 'subr-arity)) (subr-arity func)) (t (let ((mandatory 0) (optional 0) (rest nil) (where 'mandatory)) (when (and (consp func) (eq 'macro (car func))) (setq func (cdr func)) (setq rest 'unevalled)) (let ((argspec (function-argspec func))) (dolist (arg argspec) (cond ((eq arg '&optional) (setq where 'optional)) ((eq arg '&rest) (unless rest (setq rest 'many))) (t (set where (+ (symbol-value where) 1))))) (cons mandatory (or rest (+ mandatory optional)))))))) ``` For built-in functions, there was no way to obtain parameter information directly before Emacs 25, but the information can be parsed from the docstring. > 2 votes # Answer Stable Emacs releases offer `subr-arity` which returns a cons describing the argument length. This function has been extended to work in a more general fashion on the master branch, check out `func-arity` and the thread leading to it. I'd generally advise against using this for more than tools helping you with elisp development (such as better error messages indicating minimum/maximum args). If you can, find a way to not reach into that bag of tricks. > 2 votes # Answer Do people still answer old questions? Anyway, I think the built-in `help-function-arglist` could be useful here. It skips any advice in effect, but other than that it provides just what you'd see in the help buffer. > 1 votes --- Tags: elisp, arguments ---
thread-4037
https://emacs.stackexchange.com/questions/4037
Simulate vim splash screen
2014-12-02T14:02:57.097
# Question Title: Simulate vim splash screen I've been trying evil mode in emacs. Unfortunately, it does not remind me to "Help poor children in Uganda!" when I start emacs. Is there a simple way to simulate this? Hopefully there's just a setting for evil-mode. **Update** Thanks MrBones I find it very soothing... # Answer > 6 votes Add this to your init.el ``` (setq inhibit-startup-screen t) (setq initial-scratch-message ";; Message goes here") ``` The first bit hides the startup screen, so the default buffer when you open emacs will `*scratch*`. The second lines sets the default contents in the scratch buffer. # Answer > 1 votes this seems to be a package that fits the description: emacs-splash it is pretty self-explanatory -- it is a single elisp that puts on a simple startup screen and only after either a key is pressed or some time passes then it switches to the default about buffer or the scratch buffer. No mode-line, no toolbar etc. Very minimalistic --- Tags: evil, vim-emulation ---
thread-64589
https://emacs.stackexchange.com/questions/64589
Not able to filter Global list of TODO items
2021-04-26T14:02:09.437
# Question Title: Not able to filter Global list of TODO items I have been using: ``` (defun org-todo-list-current-file (&optional arg) ;; "Like `org-todo-list', but using only the current buffer's file." (interactive "P") (let ((org-agenda-files (list (buffer-file-name (current-buffer))))) (if (null (car org-agenda-files)) (error "%s is not visiting a file" (buffer-name (current-buffer))) (org-todo-list arg)))) (global-set-key (kbd "<f7>") 'org-todo-list-current-file) ``` to create a Global list of TODO items, as a shortcut key to `C-c a < t` . I then used to be able to do > Press ‘N r’ (e.g. ‘0 r’) To filter by a particular TODO type. However, for some reason, this stopped working recently. Maybe due to an upgrade of emacs. Also pressing `r` to refresh a list has stopped working. However, if I use `C-c a < t` to create the same Global list of TODO items, then `N - r` and `r` do work. I have been trying to figure out a solution to this and have not come up with anything. Any help much appreciated. # Answer > 2 votes Try the following: ``` (defun ndk/org-todo-list-current-file () (interactive) (when (derived-mode-p 'org-mode)) (org-agenda nil "t" 'buffer)) (define-key org-mode-map (kbd "<f7>zt") #'ndk/org-todo-list-current-file) ``` Since we assume that the current file is an Org mode file (it does not make any sense to ask for the TODO list of arbitrary files), the function checks that the mode of the current buffer is `org-mode` before calling `org-agenda` in a special way: it calls it with a `keys` argument of the string `"t"` (IOW asking for `org-agenda` to dispatch to the function `org-todo-list`) and with a `restriction` argument of `buffer`, restricting the agenda command to just the current buffer. This is the lisp equivalent of `C-c a < t`. We also define the key to bind this command to in `org-mode-map` only, not globally, since it is not useful to define it globally: we cannot invoke the command unless the buffer is an Org mode buffer. Given this, we could dispense with the checking of the mode in the function, but a little paranoia never hurt (and actually, it is necessary, just in case you decide to call the function directly with `M-x ndk/org-todo-list-current-file` and not through the keybinding). You can use any key combo that is not used. In my particular case, both `<f7>` and `<f7>z` are prefix keys, and `<f7>zt` was unused, so that's the keybinding I used, but YMMV: choose something appropriate to your setup. If I visit an Org mode file (whether it's an agenda file or not) and call the command either with the keybinding I created, `<f7>zt`, or with `M-x ndk/org-todo-list-current-file` I get the TODO list for that file only and any subsequent `N r` invocations remain restricted to that file only. --- Tags: org-mode ---
thread-64599
https://emacs.stackexchange.com/questions/64599
Key map and vector key sequence
2021-04-27T18:25:55.327
# Question Title: Key map and vector key sequence **paredit.el** has the following example code for setting a keybinding: https://github.com/emacsmirror/paredit/blob/8330a41e8188fe18d3fa805bb9aa529f015318e8/paredit.el#L54 ``` (eval-after-load 'paredit '(progn (define-key paredit-mode-map (kbd "ESC M-A-C-s-)") 'paredit-dwim))) ``` Evaluating `(kbd "ESC M-A-C-s-)")` outputs `[27 213909545]`. How to interpret this vector key sequence. What keys does this represent? # Answer If you look at the doc string of `kbd` (`C-h f kbd)`), it mentions that there is an approximate inverse function called `key-description`. If you apply this function to the vector, you get ``` (key-description [27 213909545]) "ESC A-C-M-s-)" ``` Note the different order! The explanation is that these represent modifier keys: that's ESC followed by the key combination `ALT-CONTROL-META_SUPER-)` i.e. you have to hold all of those modifier keys down while you press the closing paren key. That also explains why the order of the modifiers does not matter, so `kbd` and `key-description` can list them in different orders. Since, AFAICT, `paredit-dwim` does not exist as a function, and since most keyboards define some but not all of these modifier keys (making it impossible to press that combination unless you use something like `xmodmap` to define all the modifiers), I can only assume that the example is meant as tongue-in-cheek. > 3 votes --- Tags: key-bindings, keymap, paredit ---
thread-64597
https://emacs.stackexchange.com/questions/64597
org-datetree: is it possible to insert a datetree at point without using org-capture?
2021-04-27T07:38:08.057
# Question Title: org-datetree: is it possible to insert a datetree at point without using org-capture? I would like to manually create a orgmode file with date entries. Is it possible to do it without the org-capture template? Just at point? Thanks! # Answer > 2 votes If you don't mind what Org mode defines as `inactive time stamps` of the form `[2021-04-28 Wed]` (do `C-h i g (org)Timestamps` for more info), then Org mode has all the facilities you need: ``` (defun ndk/org-insert-heading-and-inactive-time-stamp () (interactive) (org-insert-heading) (org-time-stamp-inactive) (insert "\n")) (define-key org-mode-map (kbd "C-c H") #'ndk/org-insert-heading-and-inactive-time-stamp) ``` If you want `active`time stamps (of the form `<2021-04-28 Wed>` \- see the same section above for info), just replace the call to `org-time-stamp-inactive` with `org-time-stamp`. Both of these use the standard Org mode mechanism of popping up a calendar and letting you select a date by typing it in, or clicking on the calendar, or specifying the date using all sorts of shortcuts (e.g. `+7` or `+1w` for the date one week ahead - the docs contain much more info). OTOH, if you want a bare date as you indicated above, you'll have to use lower-level functions to produce the output you want. I recommend you go either with inactive or active dates and forego bare dates. --- Tags: org-mode ---
thread-64610
https://emacs.stackexchange.com/questions/64610
Incremental search for visible org headings that begin with STRING
2021-04-28T12:43:31.317
# Question Title: Incremental search for visible org headings that begin with STRING I have a document with hundreds of org headings, sorted alphabetically. I would like to find a way of jumping to the first visible heading whose initial letter(s) match the string typed so far. (Intuitively, the functionality I am trying to replicate resembles that of some file managers such as OSX Finder, where one can quickly jump to any file or directory just by typing the first few letters of it, with the difference being that the candidates here are instead visible org headings.) For example, suppose that the first few lines of my document look like this: ``` * AlphaGo AlphaGo is a computer program that plays the game Go. It should not be confused with AlphaZero. ** Gamma * AlphaZero * Beta * Gamma ``` Then (assuming point is at the beginning of the document) typing `a` would move point to the first line, typing `alphaz` would move point to the fourth line, and typing `g` would move point to the final line if the first heading is folded, and to the third line otherwise. # Answer > 0 votes NickD's solution is a good enough approximation. Here's a custom function based on it: ``` (defun ps/isearch-forward-visible-org-heading () (interactive) (let ((search-invisible nil)) (isearch-forward nil 1) (isearch-yank-string "* "))) ``` # Answer > 1 votes Ordinary interactive search (`C-s`) is almost exactly what you are describing: `C-s * a` does what you want, `C-s alphaz` ditto. Ordinarily, `isearch` searches through invisible, as well as visible text, so `C-s * g` would find the second level `Gamma` even if folded, but you can toggle that behavior: `C-s M-s i * g` would skip invisible text, so it would end up at the top level `Gamma` if the `AlphaGo` heading is folded. So as long as you start your isearch with `C-s M-s i` and remember to search for `* something`, not just `something`, it will work - most of the time. Where this fails to meet your expectations is that you need to specify `*` as part of the search string and if you had `* Gamma` as part of the text and not a heading, it would find it and get a false positive. In that case, another `C-s` will find the next instance and you can continue from there. So not a perfect solution but, IMO, a 99% one: hope it works for you. --- Tags: org-mode ---
thread-64604
https://emacs.stackexchange.com/questions/64604
full screen hook?
2021-04-27T22:47:45.037
# Question Title: full screen hook? Is there a way to add a hook for when emacs goes full screen? I'd like to set slightly different transparency for the frame when in fullscreen but there seems to be no easy way for that. What I would want is for emacs to detect it is now in fullscreen and subsequently change its transparency. # Answer > 4 votes The only hook I know of that might help is `window-size-change-functions`. Code such as this, for example (replace the `message` call by whatever you want done: ``` (defun foo (frame) (let ((fullscreen (frame-parameter frame 'fullscreen))) (when (memq fullscreen '(fullscreen fullboth)) (message "Do what you want here.")))) (add-hook 'window-size-change-functions 'foo) ``` This hook runs each time there is a change in any window size the hook functions are invoked. `C-h v` says: > Functions called during redisplay, if window sizes have changed. The value should be a list of functions that take one argument. During the first part of redisplay, for each frame, if any of its windows have changed size since the last redisplay, or have been split or deleted, all the functions in the list are called, with the frame as argument. If redisplay decides to resize the minibuffer window, it calls these functions on behalf of that as well. You can instead advise a function, such as `toggle-frame-fullscreen` (bound to `<f11>`), that makes the frame fullscreen. --- Emacs hooks and such advice will *not*, however, be called when you use window-manager artifacts, such as a maximize/restore icon/button. It's possible to invoke Elisp code when *some* window-manager events, such as clicking the iconify/minimize icon/button. You do that using keymap `special-event-map`. For example, to do something different from iconifying when you click the iconify/minimize button, you can do this: ``` (define-key special-event-map [iconify-frame] 'my-frame-action) ``` I take advantage of that, optionally, in my library `thumb-frm.el`, for example -- Fisheye With Thumbs. (Be aware of this fact/feature, which is true of any binding on keymap `special-event-map`: The event interrupts any key sequence in progress, to invoke its command, and then the key sequence as a whole is processed, ignoring the special event.) However, as far as I can tell, the maximize/restore icon/button is *not* associated by Emacs with a special event. (Iconify/minimize is, but maximize is not.) So I don't see a way to make the window-manager maximize/restore button invoke Elisp code. Maybe someone else has some suggestion about this. --- Tags: hooks, fullscreen ---
thread-21459
https://emacs.stackexchange.com/questions/21459
Programmatically read and set buffer-wide org-mode property
2016-04-06T09:45:50.527
# Question Title: Programmatically read and set buffer-wide org-mode property How one can programmatically read and set a buffer-wide org-mode property? I am aware of this, which points to ``` (org-entry-put POM "PWE-1" "47") ``` but it does not seem useful in case of buffer global properties. ### Details: If a file has buffer global properties, like, ``` #+PROPERTY: PWE-1 42 #+PROPERTY: Cite "Silmarillon 1984" #+PROPERTY: my/common-list (1 "two" (1 2 3 5 7)) ``` How could one fetch, for example, the buffer-wide property PWE-1, or any other? How would one set it, ie, write a different value, say ``` #+PROPERTY: PWE-1 2197 ``` so that the buffer will *keep the updated value as stored in the file, available at next load*? Where could I look up similar information in detail? Is there a detailed list of org-mode's API? # Answer > 10 votes You could just do a text search for `#+PROPERTY: ...`. Alternatively, you can use the following functions. These functions take into account that values can be accumulated via `+` and it is an error if the first `PROPERTY` key has a `+`. (Is that true?) ``` (require 'cl-lib) (defun org-global-props-key-re (key) "Construct a regular expression matching key and an optional plus and eating the spaces behind. Test for existence of the plus: (match-beginning 1)" (concat "^" (regexp-quote key) "\\(\\+\\)?[[:space:]]+")) (defun org-global-props (&optional buffer) "Get the plists of global org properties of current buffer." (with-current-buffer (or buffer (current-buffer)) (org-element-map (org-element-parse-buffer) 'keyword (lambda (el) (when (string-equal (org-element-property :key el) "PROPERTY") (nth 1 el)))))) (defun org-global-prop-value (key) "Get global org property KEY of current buffer. Adding up values for one key is supported." (let ((key-re (org-global-props-key-re key)) (props (org-global-props)) ret) (cl-loop with val for prop in props when (string-match key-re (setq val (plist-get prop :value))) do (setq val (substring val (match-end 0)) ret (if (match-beginning 1) (concat ret " " val) val))) ret)) (defun org-global-prop-set (key value) "Set the value of the first occurence of #+PROPERTY: KEY add it at the beginning of file if there is none." (save-excursion (let* ((key-re (org-global-props-key-re key)) (prop (cl-find-if (lambda (prop) (string-match key-re (plist-get prop :value))) (org-global-props)))) (if prop (progn (assert (null (match-beginning 1)) "First occurence of key %s is followed by +." key) (goto-char (plist-get prop :begin)) (kill-region (point) (plist-get prop :end))) (goto-char 1)) (insert "#+PROPERTY: " key " " value "\n")))) ``` # Answer > 3 votes `(org-collect-keywords '("PROPERTY"))` could also be helpful, as mentioned in https://emacs.stackexchange.com/a/63102/31740. The `org-collect-keywords` doc string states: > Return values for KEYWORDS in current buffer, as an alist. > > KEYWORDS is a list of strings. Return value is a list of elements with the pattern: > > (NAME . LIST-OF-VALUES) > > where NAME is the upcase name of the keyword, and LIST-OF-VALUES is a list of non-empty values, as strings, in order of appearance in the buffer. This allows one to *get* the property values, but it does not allow *setting* them. In fact, Org mode does not provide *any* way of setting them, so @Tobias's answer still stands for the setting part: you basically have to edit the file, either by hand or programatically. --- Tags: org-mode, org-babel ---
thread-64614
https://emacs.stackexchange.com/questions/64614
emacs-custom file get overwritten
2021-04-28T16:21:26.297
# Question Title: emacs-custom file get overwritten In my `init.el`, I have the following line ``` (setq custom-file (expand-file-name "custom.el" user-emacs-directory)) ``` which is supposed to set the file `custom.el` into `.emacs.d` config folder for getting all customization tidy. Over the years, emacs populated this file with various things. I ran customization with `M-x customize-variable` and made some change and saved them. Afterwards, I discovered that emacs added the new custom into `custom.el`, overwriting the previous version of the file. What's the mistake? Should I put `(load custom-file)` after the line above? Can this be the problem? # Answer You used `M-x customize-variable`, edited the option value, and then ***saved*** it. When you save your changes they're written to your `custom-file` (or your init file, if you have no `custom-file` defined). So yes, it's normal that `custom-file` was overwritten. Yes, in your init file, somewhere *after you define* the value of option `custom-file`, you need to *load* that file, if you want Emacs to recognize its customizations. And it's generally better to use `customize-save-variable` or `customize-set-variable` than just `setq`, to change the value of a user option. It's not critical here, but it's a good habit to have. For example, in your init file: ``` ;; Possibly some stuff... (customize-save-variable 'custom-file (expand-file-name "custom.el" user-emacs-directory)) ;; Possibly some other stuff... (load-file custom-file) ;; Possibly some other stuff... ``` > 4 votes --- Tags: init-file, customize, load, custom-file ---
thread-64621
https://emacs.stackexchange.com/questions/64621
Ivy: How can I execute an action on a selection without opening the action menu?
2021-04-28T22:21:14.547
# Question Title: Ivy: How can I execute an action on a selection without opening the action menu? Apologies if the question is poorly formulated, I am a beginner at understanding internals of Emacs/packages. I am using using Doom Emacs, which provides Ivy as an interface for, for example, finding files. I understand that custom actions can be created for acting on candidates. In my case (with Doom's Evil bindings), I select a candidate and hit `C-o` to open the actions menus I wrote a function that opens the selected file in a vertical split rather than in the current window, and added it as an action. However, I would like to call this function directly by hitting a keyboard shortcut when I'm in Ivy (as I'm filtering files/buffers and selecting a candidate), instead of having the additional step of opening the actions menu. So, for example, when I open ivy in my personal config folder and select the file I want, I would like to: * Press `RET` to perform the default Ivy action (open the file in the current window) * Press `C-v` to open the file in a vertical split using my custom function * Possibly add more key mappings for other custom functions as well. How might I be able to accomplish this? # Answer > However, I would like to call this function directly when I'm in Ivy (as I'm filtering files/buffers and selecting a candidate), instead of having the additional step of opening the actions menu. How might I be able to accomplish this? If I understood correctly, you're trying to set this function as the default action. If you're calling `ivy-read` yourself, you can pass this function as the value of the `:action` keyword. For example: ``` (defun my-echo (&rest args) "Echo ARGS." (message ">>> %s" args)) (ivy-read "Echo: " '("a" "b" "c") :action #'my-echo) ``` You can also modify the action list of an existing command, for example: ``` (ivy-add-actions #'ivy-switch-buffer '(("o" my-echo "echo"))) ``` Here `"o"` is the default action key, so this will actually replace the previous default with `my-echo`. For more on Ivy actions, see `(info "(ivy) Actions")`. ### Edit > Possibly add more key mappings for other custom functions as well. If you're calling `ivy-read` directly, you can specify a custom keymap to be composed with `ivy-minibuffer-map`, for example: ``` (defun my-echo-candidate () "Exit Ivy completion, echoing selected candidate." (interactive) (ivy-exit-with-action (lambda (cand) (message ">>> %s" cand)))) (ivy-read "Echo: " '("a" "b" "c") :keymap (easy-mmode-define-keymap '(("\C-v" . my-echo-candidate)))) ``` Of course, to reuse your custom bindings, you can either create your own named keymap: ``` (defvar my-ivy-map (let ((map (make-sparse-keymap))) (define-key map "\C-v" #'my-echo-candidate) map) "Keymap to compose with `ivy-minibuffer-map'.") ``` or modify `ivy-minibuffer-map` directly (see `(info "(ivy) Minibuffer key bindings")`). This is probably your only option if you want to modify the minibuffer keymap of an Ivy command not under your direct control. > 3 votes --- Tags: ivy, counsel ---
thread-64620
https://emacs.stackexchange.com/questions/64620
Preview stored register locations in a dedicated buffer
2021-04-28T20:44:26.613
# Question Title: Preview stored register locations in a dedicated buffer Is it possible save a bunch of point locations into registers and then navigate through them with a preview buffer? I have tried getting along with `helm-all-mark-rings` and `evil-jumper`, but neither really provide what I am looking for. Currently I just set a bunch of registers to points of interest and fumble my way through jumping back through all of them after I forget which register holds what. # Answer > 0 votes Emacs provides a preview by default, ever since Emacs 24.4. Just wait a moment after typing `C-x``r``j` and the preview will be displayed. NEWS.24 details the change: > \*** All interactive commands that read a register (`copy-to-register`, etc.) now display a temporary window after `register-preview-delay` seconds that summarizes existing registers. To disable this, set that option to nil. Interactive commands that read registers and want to make use of this should use `register-read-with-preview` to read register names. --- Tags: registers ---
thread-64628
https://emacs.stackexchange.com/questions/64628
How to disable auto indentation in asm-mode
2021-04-29T14:03:42.403
# Question Title: How to disable auto indentation in asm-mode When programming in extended assembler (using `asm-mode`), auto indentation insists on indenting compiler directives, such as `#define`, `#if` and `#endif`, how can I disable this? Emacs version: `0.300.0@26.3 (spacemacs)` # Answer > 1 votes setting `electric-indent-mode` to `nil` on `asm-mode-hook` resolved the issue. --- Tags: indentation ---
thread-14638
https://emacs.stackexchange.com/questions/14638
Change highlight color when window isn't in focus?
2015-08-11T03:27:35.680
# Question Title: Change highlight color when window isn't in focus? I'm using hl-mode as a minor mode for deft. How do I make the highlighted line change color (e.g. to gray) when the deft window isn't the current window, and then back to the default highlight color when the deft window becomes the current window again? # Answer I've implemented this for `hl-line-mode` using the `buffer-list-update-hook`. Here's the code: ``` (defface hl-line-inactive '((t nil)) "Inactive variant of `hl-line'." :group 'hl-line) (defun hl-line-update-face (window) "Update the `hl-line' face in WINDOW to indicate whether the window is selected." (with-current-buffer (window-buffer window) (when hl-line-mode (if (eq (current-buffer) (window-buffer (selected-window))) (face-remap-reset-base 'hl-line) (face-remap-set-base 'hl-line (face-all-attributes 'hl-line-inactive)))))) (add-hook 'buffer-list-update-hook (lambda () (walk-windows #'hl-line-update-face nil t))) ``` What this code is doing: * Define a new face `hl-line-inactive` to be used in inactive windows. You can use `M-x customize-face` to modify the attributes of this face to your taste. * Define a function to temporarily remap the highlighting face in inactive windows. A window is considered inactive if it is not displaying the same buffer as the currently selected window. * Add a hook to `buffer-list-update-hook` that calls `hl-line-update-face` for all the visible windows. **Old answer** The code above (which I'm using in my own `init` file) is much simpler than what I originally posted. Thanks @Drew for the suggestion to use `walk-windows`. I also read more about face remapping (see Face Remapping in the Emacs Lisp Manual) and realized I could remove a lot of the code. For posterity, here's what I originally posted: ``` ;; Define a face for the inactive highlight line. (defface hl-line-inactive '((t nil)) "Inactive variant of `hl-line'." :group 'local) (defun toggle-active-window-highlighting () "Update the `hl-line' face in any visible buffers to indicate which window is active." (let ((dups)) (mapc (lambda (frame) (mapc (lambda (window) (with-current-buffer (window-buffer window) (when hl-line-mode (make-local-variable 'face-remapping-alist) (let ((inactive (rassoc '(hl-line-inactive) face-remapping-alist))) (if (eq window (selected-window)) (progn (setq dups (get-buffer-window-list nil nil 'visible)) (setq face-remapping-alist (delq inactive face-remapping-alist))) (unless (or inactive (memq window dups)) (add-to-list 'face-remapping-alist '(hl-line hl-line-inactive)))))))) (window-list frame))) (visible-frame-list)))) (add-hook 'buffer-list-update-hook #'toggle-active-window-highlighting) ``` > 5 votes # Answer You can use `window-selection-change-functions`. By adding a function locally the function is called each time when the window showing that buffer has been selected/deselected (see the docstring for more info). This can be used to toggle `hl-line-face` face for the deft buffer: ``` (defvar-local deft-hl-line-toggle-cookie+ nil) (defun deft-toggle-hl-line-face+ (w) (cond ((eq (current-buffer) (get-buffer deft-buffer)) (when deft-hl-line-toggle-cookie+ (face-remap-remove-relative deft-hl-line-toggle-cookie+))) (t (with-current-buffer (get-buffer deft-buffer) (setq deft-hl-line-toggle-cookie+ (face-remap-add-relative hl-line-face `(:inherit ,hl-line-face :background "gray"))))))) (defun deft-hl-line-toggle-setup+ () (add-hook 'window-selection-change-functions 'deft-toggle-hl-line-face+ nil t)) (add-hook 'deft-mode-hook 'deft-hl-line-toggle-setup+) ``` > 2 votes --- Tags: window, highlighting, focus ---
thread-64636
https://emacs.stackexchange.com/questions/64636
Specify a block of text that should not be filled (leave it "verbatim")?
2021-04-30T13:46:15.367
# Question Title: Specify a block of text that should not be filled (leave it "verbatim")? Consider the following piece of text (in whatever general major mode it may be): <pre><code>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. ``` function foo() println("Hello World") println("Don't fill me please!") end ``` Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. </code></pre> The idea is that I want triple backticks to serve as delimiters for regions of the text that I would like to not fill. I am using the filladapt mode and right now executing `fill-paragraph` with the cursor in the "code block" region causes a fill: <pre><code>``` function foo() println("Hello World") println("Don't fill me please!") end ``` </code></pre> I would like to specify that all blocks of text inside triple backticks should be left verbatim - not filled, not touched in any way at all by the fill algorithm. Is this possible? Preferrably in `filladapt` since I am using it already. # Answer # Polymode Polymode might serve your purpose here. It supports editing documents that combine code in different languages. It does a lot more than just let you tweak autofilling, so it might be worth spending a bit of time to investigate. Basically, it allows you to edit your document in one major mode, and seamlessly switch to a different major mode when editing code blocks. You can then turn auto-fill on in your 'host mode', and turn it off for the 'inner mode'. At the same time, you get the syntax highlighting and keyboard shortcuts you normally use for editing your code, without requiring you to use the same shortcuts and highlighting for the surrounding text. Your example looks like a markdown document with a code block in programming language. There may already be a polymode for this combination - Poly-markdown already exists, and can be combined with Poly-R to get support for R code in markdown code blocks, for example. If the appropriate combination doesn't exist, it's relatively easy to make your own. The polymode manual is the best place to get started. # Orgmode As NickD points out, you can also use orgmode in this way. This has a few additional limitations, but also gives you access to a whole ecosystem of tools built into the orgmode system. The primary 'limitation' with orgmode, compared to polymode, is that the main document has to be in org format. This is similar to markdown, and easily exported to html, latex/pdf, odt etc. It also has a lot more features for task management, scheduling (and a *lot* more). You don't need to use all those features. The one you'll be interested in will be code blocks. You won't be able to use arbitrary delimiters, (i.e., triple backticks), you'll have to use the slightly more verbose orgmode style: ``` #+begin_src LANG function foo() println("Hello World") println("Don't fill me please!") end #+end_src ``` The advantage here is that you can include code blocks of most (all?) languages in the same document, so long as there's an Emacs mode for editing them. You get the same syntax highlighting support as in `polymode`. You don't get the seamless editing, but it's almost as good. There's a shortcut key for creating a temporary buffer for editing your code in its 'normal' mode, and then returning to your org document. Both approaches are rather involved for your simple question. But if you do a lot of mixed-language editing I think it's worthwhile to learn one or the other, or both. If you mostly use the same two languages, and especially if you have collaborators who don't use Emacs but want to edit your documents, I would recommend polymode. That's what I use for RMarkdown (markdown with R code blocks). Orgmode is much more powerful and flexible, but it requires that you adopt the org format, and it won't be as easy to share with non-Emacs users. I use this for files that only I will edit, especially when I'm mixing more than two languages into a document. > 2 votes --- Tags: fill-paragraph ---
thread-64634
https://emacs.stackexchange.com/questions/64634
Color settings with helm
2021-04-30T08:45:22.883
# Question Title: Color settings with helm I use helm a lot. I have a problem setting colors. In my `init.el` I have ``` (require 'helm) (require 'helm-config) ;; change active line color (set-face-attribute 'helm-selection nil :background "red" :foreground "white") ``` Supose I have the situation in the picture below where I search for `XXX`. In `C` the helm-occur buffer uses red/white colors for the selected line. But in the parent buffer in point `B` I still have green and purple for the pattern match. I'd like to change the colors in `B` so that they match what happens in `C`. I suppose I should do something like the code above, but I don't understand what controls the colors in `B` # Answer > 2 votes First, instead of the code you're using to customize face `helm-selection`, just use `M-x customize-face`, and save your changes. Using Customize is nearly always a better idea. --- To your question: Put your cursor on the text whose face you want to know, e.g. the face you say is "green and purple", and use `C-u C-x =`. The `*Help*` buffer will tell you (near the bottom) what faces are present at that position. Then use `M-x customize-face` to customize that face (likewise, any others). When customizing you can even define a face to just inherit from some other face. Easy-peasy. --- Tags: helm, faces, highlighting, customize-face ---
thread-64625
https://emacs.stackexchange.com/questions/64625
How can I display only current png and hide others in org-mode?
2021-04-29T07:51:14.820
# Question Title: How can I display only current png and hide others in org-mode? I have a lot of inline images and I want to disply only 1 in buffer and hide others while viewing. With `M-x org-toggle-inline-images` I can do this for the entire buffer, but it's too much for me. So, how can I do this? Update: With `M-x org-open-at-point` I can preview the image, but I would like to be able to compare multiple images. # Answer I don't think that there is anything ready-made, but it does not take too much work to create something like that. The main question is what interface you find convenient. `org-toggle-inline-images` (bound to `C-c C-x C-v`) calls the function `org-display-inline-images` underneath the covers (that is mentioned in the doc string BTW - do `C-h f org-toggle-inline-images` to see it). If you do `C-h f org-display-inline-images`, you will see that it is capable of displaying images *in a region*: > (org-display-inline-images &optional INCLUDE-LINKED REFRESH BEG END) > > ... > > BEG and END define the considered part. They default to the buffer boundaries with possible narrowing. So one way to go is to narrow the buffer to a region that contains just the image you want with `C-x n n`, toggle inline images with `C-c C-x C-v` and widen the buffer with `C-x n w`. That's probably too much work so we can write a more targeted function: ``` (defun ndk/org-display-inline-images (beg end) (interactive "r") (org-display-inline-images nil nil beg end)) (define-key org-mode-map (kbd "C-c v") #'ndk/org-display-inline-images) ``` The function passes the region to `org-display-inline-images`, so you avoid the narrowing/widening of the buffer. We also define a keybinding to it, so it can be called easily. Now all you have to do is select a region that contains one or more images, press `C-c v` and the image(s) within the region will be inlined. You can get rid of the inlining with `C-c C-x v`, i.e. calling our old friend `org-toggle-inline-images`. If that's still too much work, you can write a more specialized function that determines the region around the link at point on its own and passes that region to `org-display-inline-images`. It's more limited in the sense that it will only look for one image around point, never more than one, but you might prefer that: ``` (defun ndk/org-display-inline-image-at-point () (interactive) (let* ((context (org-element-context (org-element-at-point))) (type (org-element-type context)) (beg (plist-get (cadr context) :begin)) (end (plist-get (cadr context) :end))) (when (eq type 'link) (org-display-inline-images nil nil beg end)))) (define-key org-mode-map (kbd "C-c v") #'ndk/org-display-inline-image-at-point) ``` This version uses the `org-element` parser to figure out the "thing" around point and it finds a link, it gets the beginning and the end of the region that the link occupies and passes that region to `org-display-inline-images` as before. Putting your cursor on a link and saying `C-c v` then inlines the link. Moving to another link and doing `C-c v` there undoes the previous inlining and inlines the new link. If any inlining is showing, then using the toggle function with `C-c C-x C-v` gets rid of all inlining. > 2 votes --- Tags: org-mode, images, display ---
thread-64642
https://emacs.stackexchange.com/questions/64642
Custom paragraph-start and paragraph-separate for editing *.srt files
2021-04-30T21:49:10.647
# Question Title: Custom paragraph-start and paragraph-separate for editing *.srt files I'm having some trouble coming up with regular expressions for variables `paragraph-start` and `paragraph-separate` to do what I want (to be defined shortly). I'm editing `*.srt` files (subtitles for school lectures) and trying to set my variables so that `M - }` and `M - {` take me up and back one block of text for editing. The file has the following format: ``` 1 00:00:16,040 --> 00:00:23,130 Some text here that marks the beginning <-- of a block. 2 00:00:23,390 --> 00:00:28,230 (Speaker): And some more <-- 3 00:00:28,230 --> 00:00:32,350 text here that also marks the <-- beginning of another block. There could be multiple sentences in here. ``` I want to set variables `paragraph-start` and `paragraph-separate` in such a way that `M-{` and `M-}` (paragraph back and forward) take me between the beginning of the lines marked with `<--`. I tried to set `paragraph-separate` to `".*-->.*"` (since the arrow never appears in the subtitles text) and `paragraph-start` to match any after this line, but `M-}` always seems to place me **on** the timestamps line (the one including the `-->`), although I want to go to the line **after** it. Any ideas what I'm doing wrong and how I can set the variables `paragraph-start` and `paragraph-separate` appropriately? # Answer > 0 votes The following code will probably do what you want. Note that it will change globally `M-{` and `M-}`. I would use an hydra for this (assuming that I would use also other functions during file editing). ``` (defun adl/srt-backward-paragraph () (interactive) (backward-paragraph 2) (if (= (point) (point-min)) (next-line 2) (next-line 3))) (defun adl/srt-forward-paragraph () (interactive) (forward-paragraph) (while (= (char-after) 10) (next-line)) (next-line 2)) (global-set-key (kbd "M-{") 'adl/srt-backward-paragraph) (global-set-key (kbd "M-}") 'adl/srt-forward-paragraph) ``` --- Tags: paragraphs ---
thread-57608
https://emacs.stackexchange.com/questions/57608
Split code across multiple SRC blocks?
2020-04-05T22:28:58.020
# Question Title: Split code across multiple SRC blocks? For my current config, I'm tangling an org-mode buffer into my `init.el`, and I have a few sections where I'd like to insert rich text between segments of Emacs lisp code, like the following: ``` ... #+BEGIN_SRC elisp (use-package exwm :config (exwm-enable) #+END_SRC I find that four workspaces is enough to start out with, and I like being able to use my X windows across workspaces. #+BEGIN_SRC elisp :init (setq exwm-workspace-number 4 exwm-workspace-show-all-buffers t exwm-layout-show-all-buffers t) #+END_SRC ... ``` The issue is, if I `C-c '` to edit the second SRC block, it reindents to the beginning of the line. Smartparens is also unhappy about any unmatched closing parentheses I have in subsequent blocks. Is there anything in org-mode that would support something like this? Perhaps some marker I can tag each block with as a hint that they should all be pulled into the same Org Src buffer when I `C-c '` on one of them? # Answer > 1 votes You have two issues here and probably should have 2 questions. First issue is the indenting; second is the bracket matching for smartparens. You can indent the whole tangled source file after saving it. This idea is taken from Grant Rettke's page. The relevant code is ``` (defun help/org-babel-post-tangle-hook-fn () (interactive) (indent-region (point-min) (point-max) nil) (save-buffer)) (add-hook 'org-babel-post-tangle-hook #'help/org-babel-post-tangle-hook-fn) ``` To deal with the bracket issue, I would look at weaving and literate programming and Grant Rettke's link above, so that each code block is balanced, e.g.: ``` #+BEGIN_SRC elisp (use-package exwm :config (exwm-enable) :init <<exwm>> ) ; close use-package #+END_SRC ``` and ``` #+BEGIN_SRC elisp :tangle no :noweb-ref exwm (setq exwm-workspace-number 4 exwm-workspace-show-all-buffers t exwm-layout-show-all-buffers t) ; parens balanced in code block #+END_SRC ``` By placing the `:init` in the top level block, the code in the other block is valid elisp and so, when editing the block in a buffer, you can execute it easily. # Answer > 0 votes You can use `(use-package exwm ... )` multiple times. That might help. --- Tags: org-mode, literate-programming ---
thread-53641
https://emacs.stackexchange.com/questions/53641
How to run zone-matrix?
2019-11-08T19:20:24.830
# Question Title: How to run zone-matrix? I found something that looks like fun: https://github.com/ober/zone-matrix A matrix-inspired EMACS screen saver. I need this in my life, but I can't (for the life of me) figure out how to get it to run. I've placed the files in my `~/.emacs.d/lisp` directory, and appended my init.el to include the load-path and settings per example\_user\_config.el, but I cannot get it to start by executing 'M-x zone' I'm running Emacs on MSYS2 (which I believe is the bleeding edge for Windows builds nowadays). EDIT: Solved. I needed tabbar-mode, which I found here: https://github.com/dholm/tabbar/blob/master/tabbar.el Now I see the characters scrolling, it makes me happy! # Answer ``` (defun tabbar-mode () (lambda (x) (message "%s"))) (add-to-list 'load-path (concat dotfiles-dir "zone")) (require 'zone-matrix) (require 'zone-matrix-settings) (require 'zone-settings) (setq zone-programs [zone-matrix]) (zone-when-idle 60) ``` This is all you need. This assumes that you have zone-matrix in ~/.emacs.d/zone as I do. It also removes the need for the real tabbar-mode. I cribbed this from somewhere a long while back, and have not found updates to it. > 1 votes --- Tags: package ---
thread-64651
https://emacs.stackexchange.com/questions/64651
Emacs client doesn't recognize non-ascii input
2021-05-01T14:46:17.510
# Question Title: Emacs client doesn't recognize non-ascii input **The problem:** When I type a non-ascii character, the character is not wrote and instead a weird key combination is performed, depending on which character I have typed, as if it didn't support utf-8. This strange behavior is true whether I: * input non-ascii characters directly from my keyboard (such as the french letter `ç`) * create them with XCompose (such as ) * input them using a different keyboard layout (I tried a chinese keyboard) However, this only occurs when I use emacsclient in a terminal. If I start a fresh new emacs program, no problem. If I use emacsclient with GUI, no problem. Restarting the emacs server doesn't change anything. Besides that, emacsclient has no problem in reading or showing non-ascii characters (eg. I can open files that contain utf-8 characters and edit them). --- **What I tried:** I tried setting `keyboard-coding-system` to `utf-8` from within an emacsclient session, and it works until I leave it. If I close the session, and open it again, it quits working, even though the server hasn't stopped. I tried saving it into emacs' configuration via `customize`, but it doesn't work: each time I close and re-open emacsclient, it comes back to `utf-8-unix`, saying that it has been changed outside `customize` (even though in `init.el` the value is set to `utf-8`). I tried the same thing with emacs, and the same thing happens: I can change temporally the value, but when I restart it comes back to the original value. However, I am positively sure I don't overwrite `keyboard-coding-system` in my configuration. To rule that out, I started emacs with `-q` (which tells emacs not to read any configuration file, just start as-is), but it still had the value `utf-8-unix` saying `CHANGED outside Customize`. --- **To recap**: changing `keyboard-coding-system` temporarily solves the issue for emacsclient, but I can't make it definitive. And, I have no problem neither in emacs nor in emacsclient GUI with the default value for `keyboard-coding-system`. This is especially problematic since my keyboard is full of non-ascii keys and each time I press them by mistake emacs runs commands (depending on which key I have pressed) which is very annoying. -- Technical details: I have the same problem on several Linux distros, including a Debian which has emacs 26.1 and NixOS which has the latest stable emacs. -- **EDIT 1**: A comment asked what `locale` returned in the terminal in which I start emacsclient. ``` $ locale LANG=en_US.UTF-8 LANGUAGE= LC_CTYPE="en_US.UTF-8" LC_NUMERIC="en_US.UTF-8" LC_TIME=fr_FR.UTF-8 LC_COLLATE="en_US.UTF-8" LC_MONETARY="en_US.UTF-8" LC_MESSAGES="en_US.UTF-8" LC_PAPER=fr_FR.UTF-8 LC_NAME="en_US.UTF-8" LC_ADDRESS="en_US.UTF-8" LC_TELEPHONE="en_US.UTF-8" LC_MEASUREMENT=fr_FR.UTF-8 LC_IDENTIFICATION="en_US.UTF-8" LC_ALL= ``` # Answer Does this fix the problem? ``` (defun my-terminal-keyboard-coding-system (&optional frame) "Force the terminal `keyboard-coding-system' to be `utf-8'. Prevents terminal frames using a coding system based on the locale. See info node `(emacs) Terminal Coding'." (with-selected-frame (or frame (selected-frame)) (unless window-system (set-keyboard-coding-system 'utf-8)))) ;; Run now, for non-daemon Emacs... (my-terminal-keyboard-coding-system) ;; ...and later, for new frames / emacsclient (add-hook 'after-make-frame-functions 'my-terminal-keyboard-coding-system) ``` Any time you need to customize terminal-local settings you need to check/set them for every frame that is created, because each given frame can *potentially* be different to any other (e.g. you can ssh to the server host from multiple different machines each with different terminals and locales, and run an emacsclient to the same single server from each terminal). > 1 votes --- Tags: emacsclient, input-method, server, utf-8 ---
thread-3821
https://emacs.stackexchange.com/questions/3821
A faster method to obtain `line-number-at-pos` in large buffers
2014-11-23T07:48:54.483
# Question Title: A faster method to obtain `line-number-at-pos` in large buffers The function `line-number-at-pos` (when repeated about 50 times) is causing a noticeable slow-down in semi-large buffers -- e.g., 50,000 lines -- when point is near the end of the buffer. By slow-down, I mean a combined total of about 1.35 seconds. Instead of using a 100% `elisp` funciton to count-lines and goto the top of the buffer, I'd be interested in a hybrid method that taps into the built-in C abilities responsible for the line number appearing on the mode-line. The line-number that appears on the mode-line occurs at light speed, regardless of the size of the buffer. --- Here is a test function: ``` (defmacro measure-time (&rest body) "Measure the time it takes to evaluate BODY. http://lists.gnu.org/archive/html/help-gnu-emacs/2008-06/msg00087.html" `(let ((time (current-time))) ,@body (message "%.06f" (float-time (time-since time))))) (measure-time (let* ( line-numbers (window-start (window-start)) (window-end (window-end))) (save-excursion (goto-char window-end) (while (re-search-backward "\n" window-start t) (push (line-number-at-pos) line-numbers))) line-numbers)) ``` # Answer > 20 votes Try ``` (string-to-number (format-mode-line "%l")) ``` You can extract other information using %-Constructs described in the Emacs Lisp Manual. **Caveat:** *In addition* to limitations pointed out by **wasamasa** and **Stefan** (see comments below) this does not work for buffers that are not displayed. Try this: ``` (with-temp-buffer (dotimes (i 10000) (insert (format "%d\n" i))) (string-to-number (format-mode-line "%l"))) ``` and compare to ``` (with-temp-buffer (dotimes (i 10000) (insert (format "%d\n" i))) (line-number-at-pos)) ``` # Answer > 5 votes nlinum.el uses the following: ``` (defvar nlinum--line-number-cache nil) (make-variable-buffer-local 'nlinum--line-number-cache) ;; We could try and avoid flushing the cache at every change, e.g. with: ;; (defun nlinum--before-change (start _end) ;; (if (and nlinum--line-number-cache ;; (< start (car nlinum--line-number-cache))) ;; (save-excursion (goto-char start) (nlinum--line-number-at-pos)))) ;; But it's far from clear that it's worth the trouble. The current simplistic ;; approach seems to be good enough in practice. (defun nlinum--after-change (&rest _args) (setq nlinum--line-number-cache nil)) (defun nlinum--line-number-at-pos () "Like `line-number-at-pos' but sped up with a cache." ;; (assert (bolp)) (let ((pos (if (and nlinum--line-number-cache (> (- (point) (point-min)) (abs (- (point) (car nlinum--line-number-cache))))) (funcall (if (> (point) (car nlinum--line-number-cache)) #'+ #'-) (cdr nlinum--line-number-cache) (count-lines (point) (car nlinum--line-number-cache))) (line-number-at-pos)))) ;;(assert (= pos (line-number-at-pos))) (setq nlinum--line-number-cache (cons (point) pos)) pos)) ``` with the following extra config in the mode function: ``` (add-hook 'after-change-functions #'nlinum--after-change nil t) ``` # Answer > 1 votes Revisiting this old topic, `(string-to-number (format-mode-line "%l")` still holds up quite well against `(line-number-at-position)`. I found it is also highly cached for "nearby" line positions. For example, operating on `/usr/dict/words` (236k lines here): ``` (let* ((buf (get-buffer "words")) (win (get-buffer-window buf)) (len (buffer-size buf)) (off 0) (cnt 20000) (step (floor (/ (float len) cnt))) line) (set-window-point win 0) (redisplay) ; we must start at the top; see note [1] (measure-time (dotimes (i cnt) (set-window-point win (cl-incf off (+ step (random 5))));(random len)) (setq line (string-to-number (format-mode-line "%l" 0 win))))) (message "Final line: %d (step %d cnt %d)" line step cnt)) ``` This takes about 20s to run through, visiting 20,000 positions spanning the entire file in order. If instead you just look in the vicinity of a position (here ±5000 characters): ``` (let* ((buf (get-buffer "words")) (win (get-buffer-window buf)) (len (buffer-size buf)) (off (/ len 2)) (cnt 20000) (step (floor (/ (float len) cnt))) line) (set-window-point win off) (redisplay) ; we must start at the top (measure-time (dotimes (i cnt) (let ((pos (+ off (- (random 10000) 5000)))) (set-window-point win pos);(random len)) (setq line (string-to-number (format-mode-line "%l" 0 win)))))) (message "Final line: %d (step %d cnt %d)" line step cnt)) ``` This only takes ~1/5s or so! So (as you'd expect) it's highly optimized for scrolling to nearby locations (vs jumping across the entire file randomly). In contrast: ``` (let* ((buf (get-buffer "words")) (win (get-buffer-window buf)) (len (buffer-size buf)) (off 0) (cnt 1000) (step (floor (/ (float len) cnt))) line) (measure-time (dotimes (i cnt) (with-current-buffer buf (setq line (line-number-at-pos (cl-incf off step)))))) (message "Final line: %d" line)) ``` takes over 10s (for 20x fewer positions) each and every time. So to summarize, `format-mode-line` is ~10x faster than `line-number-at-pos`, on a full and fast run through a long file. And for nearby positions, it gives near instantaneous results through local caching. \[1\] Before I brought the point back to the top and redisplayed, subsequent full-file runs were taking \<\< 1 second. At first I thought this was some miraculous internal caching of `format-mode-line`, but then I noticed that this only happened if you left point at the end of the buffer. In that case `set-window-point` doesn't actually move point over such long distances, and `format-mode-line` just quickly returns the same line, over and over. --- Tags: elisp, mode-line, line-numbers ---
thread-64630
https://emacs.stackexchange.com/questions/64630
Insert url link with org-ref-insert-cite-link
2021-04-29T20:07:19.683
# Question Title: Insert url link with org-ref-insert-cite-link I am using org-ref to insert citations in org files from a BibTeX file. In this BibTeX file, all entries have a "url" field. As I am sharing these files on Gitlab with people not using emacs, I would like to define a function that mimics `org-ref-insert-cite-link`, but that would include the url from the corresponding BibTeX entry in the final link, resulting in something like ``` [[http://url-from-key.com][cite:key]] ``` so that "cite:key" appears as a link that points out to the online version of the paper linked from the BibTeX entry. Is there a built-in function in org-ref that would allow doing such a thing, and if not how should I go about defining a function that have the behavior I just described? # Answer > 1 votes There is no function `org-ref-insert-cite-link` in org-ref. You must mean `org-ref-insert-link`. Org-ref contains several implementations that add completion to allow interactively select values. You could write your own replacement for one of these functions depending on the framework you use. For example, write your own `org-ref-ivy-insert-cite-link` and use code from `or-ivy-bibtex-open-url` to copy the URL in to the link. --- Tags: org-mode, org-ref ---
thread-64659
https://emacs.stackexchange.com/questions/64659
Remove color overlay from active line with `display-line-numbers-mode`
2021-05-02T08:44:53.710
# Question Title: Remove color overlay from active line with `display-line-numbers-mode` Since `linum-mode` is replaced with `display-line-numbers-mode` I'm having an color overlay on the active line, seen in this screenshot as white on the line 77: Tried to change the theme and few other modifications but this remains. I'm not doing anything to emphasize line on which my cursor is at, so I'm guessing that shouldn't be the source also. I tried setting it with both `(global-display-line-numbers-mode t)` and `(display-line-numbers-mode t)` but it's the same. How could this be removed, or what variable could be set to customize that color? Additional question: Could I instead of that overlay have slightly different font color? # Answer It's controlled by face `line-number-current-line` You can M-x `customize-face` to change it. and you can learn more from https://www.gnu.org/software/emacs/manual/html\_node/emacs/Display-Custom.html > 1 votes --- Tags: linum-mode ---
thread-64660
https://emacs.stackexchange.com/questions/64660
How do I build only the Emacs C source files and not the Elisp source files in the Emacs repository?
2021-05-02T09:16:55.247
# Question Title: How do I build only the Emacs C source files and not the Elisp source files in the Emacs repository? Running the default procedure: ``` ~/emacs $ mkdir build ~/emacs $ cd build ~/emacs/build $ ../configure ~/emacs/build $ make ``` Results in building both the C source files and the Elisp source files. What command (or target) do I have to pass to `make` in order for me to build JUST the C source files? # Answer > 4 votes > Running the default procedure: If you're in a checkout of the Emacs repository, as the OP title suggests, then there's a missing step there: the `configure` script is generated by the `autogen.sh` script, so you need to run the latter first. If instead you're in a release tarball, then the generated `configure` script is already included. > Results in building both the C source files and the Elisp source files. Note that release tarballs already include the byte-compiled `.elc` files, so they will not be recompiled by running `make`. > What command (or target) do I have to pass to `make` in order for me to build JUST the C source files? The Emacs sources are organised such that many subdirectories have their own makefile, and most of the C sources are under the `src` subdirectory. So I think the easiest way to build (mostly) just the C sources is via `make -C src temacs`. This builds a bare Emacs executable called `temacs` that lacks any of the usually preloaded Elisp libraries like `lisp/subr.el` or `lisp/simple.el`. Actually, this target will also generate some charset files, but at least it won't byte-compile Elisp. Alternatively, `make -C src` will additionally byte-compile the necessary preloaded Elisp libraries, and dump a functional `emacs` executable. This avoids byte-compiling most auxiliary Elisp packages, such as Gnus or Org. Note that there are also some auxiliary C sources under `lib-src`, such as those for `emacsclient`. Run `make -C lib-src` or similar to build those. See `(info "(elisp) Building Emacs")` for more details on how Emacs is bootstrapped. --- Tags: build ---
thread-58697
https://emacs.stackexchange.com/questions/58697
Saving Python matplotlib figures with source-code blocks
2020-05-24T14:45:30.707
# Question Title: Saving Python matplotlib figures with source-code blocks So I am trying to create a Data Science workflow using org-mode source-blocks. Basically, I need to emulate the jupyter notebook functionality where you create a plot and it shows the figure. Now, following this link, you can do this: ``` #+begin_src python :results file import matplotlib, numpy matplotlib.use('Agg') import matplotlib.pyplot as plt fig=plt.figure(figsize=(4,2)) x=numpy.linspace(-15,15) plt.plot(numpy.sin(x)/x) fig.tight_layout() plt.savefig('images/python-matplot-fig.png') return 'images/python-matplot-fig.png' # return filename to org-mode #+end_src ``` The problem with this is that, you have to save the figure manually and then you have to return the path to the figure (Because org is wrapping that code in a function). That is super awkward to me, because I don't want to be saving the figure manually nor have that return statement at the end, because I want to export these org files to my blog using orig-publish, and that return statement is not valid code outside of the org source blocks code context. I then tried to do this: ``` #+begin_src python :file example.png :dir images/ :results file import numpy as np import matplotlib.pyplot as plt import seaborn as sns sns.set() # Enable Seaborn theme random_points = np.random.randint(0, 10, (100, 2)) plt.scatter(random_points[:, 0], random_points[:, 1]) plt.show() #+end_src #+RESULTS: [[file:images/example.png]] ``` But the problem is that, it does not save any figure at the images/example.png path. What I would want to do would be that org-mode would save that figure on the path I specified in the header, and then allow me to visualize it in the results. How could I achieve this? Thank you! # Answer > 7 votes I'm a little late but I just figured out a pretty neat way to do this using `:file` and without using `:var`. As the other anwser already pointed out `plt.show()` doesn't produce output. However you can use `:results output file` instead of `:results file` (which is the same as `:results value file`). This means that the data to create the image is taken from stdout instead of the value returned directly by python. Because of this we can use `plt.savefig(sys.stdout.buffer)` to output the image: ``` #+BEGIN_SRC python :results output file :file example.png :output-dir images/ import sys import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 2 * np.pi, 100) y = np.sin(x) plt.plot(x, y) plt.savefig(sys.stdout.buffer) #+END_SRC #+RESULTS: [[file:images/example.png]] ``` # Answer > 4 votes The basic problem is that `plt.show()` does not produce anything (other than showing the image as a side-effect and blocking), so there is nothing to save (it actually produces the None object, so that's what you get in the result): ``` #+begin_src python :results file import numpy as np import matplotlib.pyplot as plt random_points = np.random.randint(0, 10, (100, 2)) plt.scatter(random_points[:, 0], random_points[:, 1]) plt.show() #+end_src #+RESULTS: [[file:None]] ``` The None that you see in the link is the return value of `plt.show()`. So you have to save the image: ``` #+begin_src python :results file :var f="images/example.png" import numpy as np import matplotlib.pyplot as plt random_points = np.random.randint(0, 10, (100, 2)) plt.scatter(random_points[:, 0], random_points[:, 1]) plt.savefig(f) #+end_src #+RESULTS: [[file:None]] ``` That still does not work, because `savefig()` saves the image but still returns None. So we need to change things to return the file name: ``` #+begin_src python :results file :var f="images/example.png" import numpy as np import matplotlib.pyplot as plt random_points = np.random.randint(0, 10, (100, 2)) plt.scatter(random_points[:, 0], random_points[:, 1]) plt.savefig(f) return f #+end_src #+RESULTS: [[file:images/example.png]] ``` Usign a `:var f="..."` header allows us to define it in one place and use it in the block. But I don't know how to avoid that and use `:file/:dir` headers instead. --- Tags: org-mode, python, literate-programming ---
thread-64083
https://emacs.stackexchange.com/questions/64083
Tramp with Dired produces unwanted //DIRED// line
2021-03-24T06:09:41.470
# Question Title: Tramp with Dired produces unwanted //DIRED// line Connected via Tramp to an old remote system, when I list a directory using Dired, I get: ``` /plink:user@example.com:/tmp: total used in directory 549 available 114.7 MiB drwxrwxrwt 3 root root 2048 Mar 24 06:59 . drwxr-xr-x 19 root root 1024 Sep 12 2011 .. drwxr-xr-x 2 root root 12288 Oct 30 1998 lost+found -rw------- 1 root root 446528 Mar 24 06:59 quota.user -rw-r--r-- 1 root root 46909 Mar 14 01:07 zman06938aaa -rw-r--r-- 1 root root 46909 Mar 21 01:07 zman28862aaa //DIRED// 69 70 128 130 188 198 256 266 324 336 394 406 ``` According to Tramp’s debug buffer, the command that is executed by Dired is: ``` /bin/ls --color=never --dired -al /tmp/ 2>/dev/null ``` It outputs: ``` total 549 drwxrwxrwt 3 root root 2048 Mar 24 06:59 . drwxr-xr-x 19 root root 1024 Sep 12 2011 .. drwxr-xr-x 2 root root 12288 Oct 30 1998 lost+found -rw------- 1 root root 446528 Mar 24 06:59 quota.user -rw-r--r-- 1 root root 46909 Mar 14 01:07 zman06938aaa -rw-r--r-- 1 root root 46909 Mar 21 01:07 zman28862aaa //DIRED// 69 70 128 130 188 198 256 266 324 336 394 406 ``` I assume there is some incompatibility between the output from an old `ls` and the current Dired. *Is there any way to get rid of the `//DIRED//` line at the end?* The problem is that the presence of this line makes navigation in Dired super slow if there are many files in the directory. Moving from line to line can then take more than a second. # Answer The issue has been fixed by Michael Albinus in Tramp 2.5.0.4. Thank you! > 0 votes --- Tags: dired, tramp, shell, files, remote ---
thread-64673
https://emacs.stackexchange.com/questions/64673
Can lisp code executed via (load ...) access it's own file path?
2021-05-03T05:48:15.987
# Question Title: Can lisp code executed via (load ...) access it's own file path? If a script runs using `(load /path/to/file.el)`, is there a way for the script that runs to access it's own path? (similar to Python's `__file__`) --- Asking this because I'd like to construct a relative path from a `.dir-locals.el` file. # Answer Yes The variable `load-file-name` https://www.gnu.org/software/emacs/manual/html\_node/elisp/How-Programs-Do-Loading.html contains the name of the file that is being loaded. or `buffer-file-name` https://www.gnu.org/software/emacs/manual/html\_node/elisp/Buffer-File-Name.html as a local variable in the buffer saying where it is visiting or as a function that returns the file path from the buffers name. > 2 votes --- Tags: path ---
thread-64682
https://emacs.stackexchange.com/questions/64682
Inline Images not displaying under org-mode
2021-05-03T17:00:36.337
# Question Title: Inline Images not displaying under org-mode I was trying to use org-mode to organize my notes as usual and produce some reports, but can't get images to display inline. This used to work in the past, but doesn't seem to work anymore, any tips what I'm doing wrong? I have a png in the current \*.org document folder called audit.png which I linked by adding a link `[[file:audit.png][audit image]]` but it simply doesn't show up. When I do `C-c C-x C-v` to display the image inline it says there aren't any. This is my emacs version: And these are my variables controlling the image search (with values below): ``` image-file-name-extensions ; => ("png" "jpeg" "jpg" "gif" "tiff" "tif" "xbm" "xpm" "pbm" "pgm" "ppm" "pnm" ...) image-file-name-regexps ; => nil ``` If I open the link with `C-c C-o` I can see the image within emacs though which confuses me even more. This would help me a lot in work. Thank you for you attention. # Answer > 0 votes **\[SOLVED\]** Oh boy, this post had the answer: Org-mode: No images to display inline Apparently if you add a description to the image the inline display won't work. --- Tags: org-mode, inline-image ---
thread-64686
https://emacs.stackexchange.com/questions/64686
How to subtract time values formatted as "HH:mm"?
2021-05-03T19:24:10.027
# Question Title: How to subtract time values formatted as "HH:mm"? I want to subtract time values like `12:04` from `11:30` and get *34 minutes* or *0:34*. I tried to achieve this using calculations like ``` (time-subtract (parse-time-string "12:04") (parse-time-string "11:30")) ``` This way I get the error `Invalid time specification`. OK. Maybe I need to encode times first: ``` (time-subtract (apply #'encode-time (parse-time-string "12:04")) (apply #'encode-time (parse-time-string "11:30"))) ``` Now I get the error `Wrong type argument: fixnump, nil`. Is there a way to subtract times without having to calculate total minutes of both times first like `12 * 60 + 4`? # Answer > 7 votes > This way I get the error `Invalid time specification`. > > OK. Maybe I need to encode times first: Indeed. > Now I get the error `Wrong type argument: fixnump, nil`. This is because `parse-time-string` is documented as returning `nil` for unknown entries, such as those for the date (emphasis mine): ``` parse-time-string is a compiled Lisp function in `parse-time.el'. (parse-time-string STRING) Probably introduced at or before Emacs version 27.1. Parse the time in STRING into (SEC MIN HOUR DAY MON YEAR DOW DST TZ). STRING should be an ISO 8601 time string, e.g., "2020-01-15T16:12:21-08:00", or something resembling an RFC 822 (or later) date-time, e.g., "Wed, 15 Jan 2020 16:12:21 -0800". This function is somewhat liberal in what format it accepts, and will attempt to return a "likely" value even for somewhat malformed strings. The values returned are identical to those of `decode-time', but any unknown values other than DST are returned as nil, and an ^^^^^^^^^^^^^^^ unknown DST value is returned as -1. ``` For example: ``` (parse-time-string "12:04") ;; => (0 4 12 nil nil nil nil -1 nil) ``` This result cannot be handled directly by other time functions, so those `nil`s need filling in. Emacs 27 introduced the handy utility function `decoded-time-set-defaults` for this purpose: ``` decoded-time-set-defaults is a compiled Lisp function in `time-date.el'. (decoded-time-set-defaults TIME &optional DEFAULT-ZONE) Set any nil values in `decoded-time' TIME to default values. The default value is based on January 1st, 1970 at midnight. TIME is modified and returned. ``` Behold: ``` (decoded-time-set-defaults (parse-time-string "12:04")) ;; => (0 4 12 1 1 0 nil -1 nil) ``` Putting it all together (note that the new calling convention of `encode-time` accepts a decoded time as a single list argument): ``` (require 'time-date) (defun my-mins-between (time1 time2) "Return the minutes between HH:mm strings TIME1 and TIME2." (let ((diff (apply #'time-subtract (mapcar (lambda (time) (encode-time (decoded-time-set-defaults (parse-time-string time)))) (list time1 time2))))) (/ (float-time diff) 60))) (my-mins-between "12:04" "11:30") ;; => 34.0 ``` Or you can declare technical bankruptcy and rely on Org parsing functions instead. Since Org 9.1: ``` (- (org-duration-to-minutes "12:04") (org-duration-to-minutes "11:30")) ;; => 34.0 ``` In older Org versions: ``` (- (org-hh:mm-string-to-minutes "12:04") (org-hh:mm-string-to-minutes "11:30")) ;; => 34 (- (org-duration-string-to-minutes "12:04") (org-duration-string-to-minutes "11:30")) ;; => 34 ``` --- **References** --- Tags: time-date ---
thread-64691
https://emacs.stackexchange.com/questions/64691
How to create humanly readable delta between two times?
2021-05-04T02:36:26.933
# Question Title: How to create humanly readable delta between two times? Given two times (in the format returned by `(current-time)`), does Emacs have a way to convert this to a humanly readable delta? Examples could include: * 3 days. * 2 weeks, 3 days. * 3 hours, 2 minutes. * tomorrow *(possible alternative to `1 day`)* * yesterday *(possible alternative to `-1 day`)* ... etc. # Answer Here's one way: ``` (defun my-format-time-delta (time1 time2) "Return difference between TIME1 & TIME2 as a readable string." (format-seconds "%Y %D %H %M %z%S" (float-time (time-subtract time1 time2)))) ``` This relies on the function `format-seconds`: ``` format-seconds is a compiled Lisp function in `time-date.el'. (format-seconds STRING SECONDS) Probably introduced at or before Emacs version 23.1. Use format control STRING to format the number SECONDS. The valid format specifiers are: %y is the number of (365-day) years. %d is the number of days. %h is the number of hours. %m is the number of minutes. %s is the number of seconds. %z is a non-printing control flag (see below). %% is a literal "%". Upper-case specifiers are followed by the unit-name (e.g. "years"). Lower-case specifiers return only the unit. "%" may be followed by a number specifying a width, with an optional leading "." for zero-padding. For example, "%.3Y" will return something of the form "001 year". The "%s" spec takes an additional optional parameter, introduced by the "," character, to say how many decimals to use. "%,1s" means "use one decimal". The "%z" specifier does not print anything. When it is used, specifiers must be given in order of decreasing size. To the left of "%z", nothing is output until the first non-zero unit is encountered. ``` Sample usage: ``` (mapconcat (lambda (delta) (let* ((now (current-time)) (then (time-subtract now delta))) (format "%9d => %s" delta (my-format-time-delta now then)))) '(10 100 10000 100000 100000000) "\n") ;; 10 => 10 seconds ;; 100 => 1 minute 40 seconds ;; 10000 => 2 hours 46 minutes 40 seconds ;; 100000 => 1 day 3 hours 46 minutes 40 seconds ;; 100000000 => 3 years 62 days 9 hours 46 minutes 40 seconds ``` For more details, see: > 4 votes --- Tags: time-date ---
thread-64680
https://emacs.stackexchange.com/questions/64680
isearch buffer greyed out/blurred after update to macOS 11.3
2021-05-03T16:09:04.097
# Question Title: isearch buffer greyed out/blurred after update to macOS 11.3 I'm running Mac Port version of emacs 27.2 on macOS big sur. I recently updated to macos 11.3, and I'm having some strange behavior when I do a `C-s` search. In around 75% of instances, the entire buffer turns blurred-out/grey except for the search matches (see screenshot). It looks like the semi-transparent background macOS puts behind many objects (e.g., dock, spotlight search) Even after I've exited isearch, the greyed background persists until I switch buffers and switch back, so it's quite annoying. I experience the issue on both integrated MacBook screen and external displays. Things I've tried: * Reducing transparency in macOS preferences * Disabling spotlight search in macOS preferences * updating from emacs 27.1 --\> 27.2 * stripping down .emacs file How can I fix this? # Answer Managed to solve the issue with these steps: 1. uninstall of emacs, 2. upgrade to Xcode command line tools 3. re-install Mac ports emacs with `brew install emacs-mac` > 0 votes --- Tags: osx, isearch ---
thread-64645
https://emacs.stackexchange.com/questions/64645
Rebinding M-q in `define-minor-mode`
2021-05-01T05:47:34.347
# Question Title: Rebinding M-q in `define-minor-mode` I'm trying to define a minor mode that rebinds `M-q` to a modified version of `fill-paragraph`. What I've written so far: ``` (defun myfun () (message "myfun called")) (define-minor-mode mymode "Test for minor mode keymap." :lighter " MM" :keymap '(([M-q] . myfun))) ``` doesn't work, as `M-q` is still bound to `fill-paragraph` when `mymode` is active. Can anyone spot the issue with my code and tell me how to rebind that key properly? # Answer > 2 votes Contrast `M-f1` for a function key with `?\M-f` for a character. You've bound `myfun` to `[M-q]` which means the one-key sequence where the key is the function key called `q` (which does not exist) with the modifier whose prefix is `M` (which is meta). Instead of referencing a function key `q`, you need to reference the character `q`. You can write this `[?\M-q]`, or in string notation `"?\M-q"`. You can also use the ESC prefix (written `\e` as a character) instead of the meta modifier: `"\eq"` or `[?\e \q]`. (Do not use `[escape q]`, because that would override the default redirection of the `escape` function key to the escape character `?\e`, and so pressing `Escape` `*key*` would no longer be equivalent to `Meta`+`*key*`.) # Answer > 1 votes I'd consider calling `(define-key mymode-map [remap fill-paragraph] #'myfun)` from `mymode-hook` rather than defining it in the minor mode. ``` (defun remap-fill-paragraph () (define-key mymode-map [remap fill-paragraph] #'myfun)) (add-hook 'mymode-hook #'remap-fill-paragraph) ``` This means you don't have to remember to change the minor-mode mapping if you ever change the default mapping for `fill-paragraph`. Unfortunately (based on a single quick test) it seems that the expansion of the `define-minor-mode` Lisp macro is not smart enough to handle a `[remap ...]` within the `:keymap` form, hence the need to use the more verbose approach. # Answer > 0 votes There are two problems in the code above: 1. The code was bound to the non-existing `q` function key (see Gilles' answer). 2. In order to be added to a keymap, functions must be commands (i.e. interactive). The following code works and solves both problems: ``` (defun myfun () (interactive) (message "myfun called")) (define-minor-mode mymode "Test for minor mode keymap." :lighter " MM" :keymap '([?\M-q] . myfun)) ``` --- Tags: key-bindings, minor-mode ---
thread-10391
https://emacs.stackexchange.com/questions/10391
How can I specify the filename for org-mode export in Emacs?
2015-03-30T00:12:12.587
# Question Title: How can I specify the filename for org-mode export in Emacs? My org file is named `README.org` and I want to export to Markdown into a file named `README`. Every time I run the export it writes to `README.md`. Here is my org file: ``` #+PROPERTY: EXPORT_FILE_NAME thing * Test export ``` I'm using the `EXPORT_FILE_NAME` property based on this link: http://orgmode.org/manual/Export-settings.html#index-property\_002c-EXPORT\_005fFILE\_005fNAME-1617 but it doesn't seem to do anything. # Answer > 15 votes According to the cited manual page, `EXPORT_FILE_NAME` applies only for subtree export. Whole file export will take its name from the buffer file name. If you only have 1 level-1 headline, you may add this property to a drawer inside the first heading, and always export as subtree from inside this top-level heading to get your desired file name. # Answer > 10 votes An easy workaround is to add this at the bottom of the source Org file: ``` # Local Variables: # after-save-hook: (lambda nil (when (org-html-export-to-html) (rename-file "README.html" "index.html" t))) # End: ``` In this example, assuming the source file is named `README.org`, it will automatically export the file to HTML and then rename it to `index.html`. # Answer > 10 votes For more recent versions of org-mode a new export setting was added, `#+EXPORT_FILE_NAME:`, which will set the file name when file is exported. * For example: ``` #+EXPORT_FILE_NAME: README.txt ``` The setting can be overwritten inside the properties drawer under a heading. * For example: ``` * Chapter 2 :PROPERTIES: :EXPORT_FILE_NAME: chapter2 :END: ``` --- > **This code was tested using:** > emacs version: GNU Emacs 25.2.1 (x86\_64-unknown-cygwin, GTK+ Version 3.22.10) > Org mode version: 9.1.2 # Answer > 2 votes You can use the function `org-export-to-file` This will let you specify the file you want to save to and the back-end for the export. ``` (org-export-to-file 'html "README.html" ) ``` # Answer > 0 votes I was inspired by user3871's amazing idea to go a bit further, including configuring a safety exception so you don't get prompted to allow the code to run when opening the file. I append this to the file to generate an HTML version of the same file on every save: ``` # Local Variables: # after-save-hook: (lambda nil (org-export-to-file 'html (format "dest_dir/%s.html" (file-name-nondirectory (file-name-sans-extension (buffer-file-name)))))) # End: ``` To make it stop prompting me, I did this rudimentary safe-variable exception: ``` ;; not perfectly secure, just checks for lambdas that call org-export-to-file as the first form. (defun my-validate-after-save-hook (form) (and (eq (nth 0 form) 'lambda) (eq (car (nth 2 form)) 'org-export-to-file))) (put 'after-save-hook 'safe-local-variable 'my-validate-after-save-hook) ``` --- Tags: org-mode, org-export ---
thread-64710
https://emacs.stackexchange.com/questions/64710
How to change CSS files to indent to 2 spaces?
2021-05-05T04:23:54.637
# Question Title: How to change CSS files to indent to 2 spaces? I have only installed emacs straight out of the box. I have not installed anything else: ``` GNU Emacs 26.3 Copyright (C) 2019 Free Software Foundation, Inc. GNU Emacs comes with ABSOLUTELY NO WARRANTY. You may redistribute copies of GNU Emacs under the terms of the GNU General Public License. For more information about these matters, see the file named COPYING. ``` my `.emacs` file: ``` ;; Added by Package.el. This must come before configurations of ;; installed packages. Don't delete this line. If you don't want it, ;; just comment it out by adding a semicolon to the start of the line. ;; You may delete these explanatory comments. (package-initialize) (custom-set-variables ;; custom-set-variables was added by Custom. ;; If you edit it by hand, you could mess it up, so be careful. ;; Your init file should contain only one such instance. ;; If there is more than one, they won't work right. '(custom-enabled-themes (quote (wombat)))) (custom-set-faces ;; custom-set-faces was added by Custom. ;; If you edit it by hand, you could mess it up, so be careful. ;; Your init file should contain only one such instance. ;; If there is more than one, they won't work right. ) (when (version<= "26.0.50" emacs-version ) (global-display-line-numbers-mode)) (setq-default indent-tabs-mode nil) (setq-default tab-width 2) (setq js-indent-level 2) ``` # Answer Suppose your `major-mode` is `css-mode`. You can place `(setq-default css-indent-offset 2)` into `.emacs`. Or you can set up per buffer, ``` (defun my-setup-indent () (setq-local css-indent-offset 2)) (add-hook 'prog-mode-hook 'my-setup-indent) ``` > 4 votes --- Tags: init-file, indentation, css ---
thread-64695
https://emacs.stackexchange.com/questions/64695
org-mode export with ox-pandoc: setting CSS for HTML5 output
2021-05-04T10:52:54.593
# Question Title: org-mode export with ox-pandoc: setting CSS for HTML5 output The latest versions of emacs and ox-pandoc already provide a great output but I need to customize the HTML5 output by setting a CSS stylesheet that matches my company's templates. How can I do that? I tried adding: ``` #+PANDOC_OPTIONS: css: ./style.css ``` and even ``` #+PANDOC_OPTIONS: css: <style>h1, h2 {color: #00abff;}; </style> ``` but I get this: ``` org-babel-exp process bash at position 3277... Wrong type argument: stringp, nil ``` This would make producing reports so much easier than using word documents and slides and such manually. Thank you! # Answer > 1 votes You could place the style in an HTML block: ``` #+BEGIN_HTML <style> h1, h2 { color: #00abff; } </style> #+END_HTML ``` --- Tags: org-mode, pandoc ---
thread-64712
https://emacs.stackexchange.com/questions/64712
org-capture with reference to file in which it was invoked
2021-05-05T06:52:37.843
# Question Title: org-capture with reference to file in which it was invoked Is there a way to configure org-capture so that, if I create a note from within a certain file, it will include a link to that file? # Answer If I do `M-x describe-variable <RET> org-capture-templates`, I learn that `%f` expands to the filename you desire and `%F` the full path of the file. From there, you should be able to cook a link. > 2 votes --- Tags: org-mode, org-capture ---
thread-64702
https://emacs.stackexchange.com/questions/64702
Org HTML Export With No Additional Divs
2021-05-04T17:44:40.447
# Question Title: Org HTML Export With No Additional Divs As you're all probably aware, when you export a document from Org mode to HTML, the resulting file contains extra `<div>` and `</div>` items around each heading. In some cases these are very helpful, but is there a way to optionally exclude these additional HTML elements for a cleaner output? # Answer > 1 votes You can use ox-slimhtml, an alternative HTML exporter. It produces minimalistic HTML output and in particular does not wrap each heading in a div. # Answer > 1 votes advice is the magic to solve many Emacs problems, ``` (defun my-org-export-as-hack (orig-func &rest args) (let* ((result (apply orig-func args)) (backend (nth 0 args))) (when (eq backend 'html) ;; use `replace-regexp-in-string' to process exported result (message "result=%s" result)) result)) (advice-add 'org-export-as :around #'my-org-export-as-hack) ``` --- Tags: org-mode, org-export ---
thread-64716
https://emacs.stackexchange.com/questions/64716
how to turn off all the formatting and all?
2021-05-05T08:12:25.520
# Question Title: how to turn off all the formatting and all? When I load some log files (50mb) When it has long json contents, emacs becomes unbearably slow. Note the log file is simply text file which happened to have json content. So json mode is not on. Is there a way to turn off every formatting or other computing in emacs? Just open a text file without any processing - mode? # Answer Emacs is often slow on any file with long lines. Improving its performance is not too hard though. I think that the easiest way to improve performance is to enable `global-so-long-mode`. Add this to your init file: ``` (if (version<= "27.1" emacs-version) (global-so-long-mode 1)) ``` Edit: If you’re using an old version of Emacs, then the easiest thing to do is to install and configure the `so-long` package from ELPA. You should also upgrade to the most current version of Emacs, but that’s a separate matter. > 4 votes # Answer You can open your file with `M-x find-file-literally`. Moreover you can use the vlf package https://github.com/m00natic/vlfi > 2 votes --- Tags: format ---
thread-64578
https://emacs.stackexchange.com/questions/64578
emacs-pinentry not working on emacs 28.0.50 and Ubuntu 20.04?
2021-04-25T08:18:15.673
# Question Title: emacs-pinentry not working on emacs 28.0.50 and Ubuntu 20.04? `Emacs-pinentry` is not working for me on `emacs 28.0.50` and Ubuntu 20.04, and I wonder why. I follow these steps: 1. In `/home/user`, do `git clone https://github.com/ecraven/pinentry-emacs.git` 2. Following the answer here, I put this in `~/.gnupg/gpg-agent.conf`: ``` allow-emacs-pinentry allow-loopback-pinentry ``` 3. Tell `gpg-agent` to load this configuration with `gpgconf` in a shell: `gpgconf --reload gpg-agent` 4. In Emacs' `init.el` I write: ``` (use-package pinentry :config (setq epa-pinentry-mode 'loopback) (pinentry-start)) ``` 5. Following advice here, I also include in my emacs dotfiles: ``` (defun pinentry-emacs (desc prompt ok error) (let ((str (read-passwd (concat (replace-regexp-in-string "%22" "\"" (replace-regexp-in-string "%0A" "\n" desc)) prompt ": ")))) str)) ``` The author of `emacs-pinentry` also says to set `GPG_AGENT_INFO` correctly inside Emacs, but I don't know what that means. Maybe that's the missing bit for my setup to work. Thought I think to remember that on one or two occassions I did enter successfully the password for decrypting some entry in `.password-store` with `pass`. But on those occassions I entered the password blindly, without any prompt or feedback on the minibuffer. I kinda tried my luck and it worked. However, my expectation was to have a prompt on the minibuffer and some indication that I am typing, such as a string of stars. # Answer In the channel `#emacs` of the Discord channel `System Crafters`, a very nice indeed participant called `Ashraz` told me that: * `pinentry-emacs` isn't necessary anymore. + which explains why `pinentry-emacs` didn't get an update for ~4 years. + Reason: `gpg-agent` has `allow-emacs-pinentry` nowadays, which tells the default `pinentry` program to use Emacs as `pinentry` (if it is running and the `pinentry` service has been started via `pinentry-start`). + Also `GPG_AGENT_INFO` shouldn't be necessary in `GPG 2.1` or higher. So all you need to do is: First, add the following lines in your `gpg-agent.conf`: ``` allow-emacs-pinentry allow-loopback-pinentry ``` The second line allows Emacs to be used as pinentry even if Emacs originally asked the decryption. Second, you need to adjust epa to use the loopback interface instead and start the server: ``` (setq epa-pinentry-mode 'loopback) (pinentry-start) ``` For more information, see info pinentry and Enabling minibuffer pinentry with Emacs 25 and GnuPG 2.1 on Ubuntu Xenial Another interesting read is: https://www.masteringemacs.org/article/keeping-secrets-in-emacs-gnupg-auth-sources (Note that the process may be different for emacs version 26 and later; see https://emacs.stackexchange.com/a/68304) > 1 votes --- Tags: gpg ---
thread-3774
https://emacs.stackexchange.com/questions/3774
A comprehensive list of shortcuts provided by AUCTeX
2014-11-21T11:28:38.520
# Question Title: A comprehensive list of shortcuts provided by AUCTeX Is there a document (pdf if any) that contains a comprehensive list of all shortcuts provided by AUCTeX? I mean a kind of **AUCTEX Reference Card** but for all shortcuts. This question is related to my previous question: Is there a shortcut for \mathrm in AUCTeX? # Answer Yes, there is an index of keybindings: it's in the index of the AUCTeX manual. Note: I got to this index by googling "auctex manual", opening up the first hit, which is the manual, selecting the HTML option (although any of them would work), selecting "Indices," and finally selecting "Key Index." Likewise, a google search for "AUCTEX reference card", the phrase you asked about, turns up quite a lot of them. Please consider doing a little background research in the relevant manual. Although manuals vary in their comprehensiveness, and sometimes it's hard to know what to look for when the software does something astonishing, keybindings are generally pretty well documented. > 10 votes # Answer You can run `C-h``b` to see the current bindings. > 7 votes # Answer The (currently) latest documentation for AUCTEX can be found here: https://ftp.gnu.org/gnu/auctex/12.3-extra/ The directory contains the manual (`auctex.pdf`) and reference card (`tex-ref.pdf`). When a newer version is out by the time you read this, it can probably be found by clicking on `Parent Directory` and selecting the latest directory called something like `XX.Y-extra/`. > 2 votes --- Tags: key-bindings, auctex ---
thread-64706
https://emacs.stackexchange.com/questions/64706
local variable set to nil after switch-to-buffer call
2021-05-05T01:02:14.153
# Question Title: local variable set to nil after switch-to-buffer call Emacs 26.1 user here. I know some common-lisp but new to elisp, so I wonder if I'm missing something obvious. I'm trying a rather simple frame setup with a function I wrote, and there's this strange behaviour. My local variable is getting set to nil after switch-to-buffer call. Here's the simplified version that has the same issue. ``` (defun my-frame-test1 () (let ((frame (make-frame '((name . "test-frame") (width . 300) (visibility . nil) (height . 100)))) left-window edit-window-left edit-window-right) (set-frame-position frame 100 100) (make-frame-visible frame) (select-frame frame) (setq-local left-window (selected-window)) (setq-local edit-window-left (split-window-right 30)) (select-window edit-window-left) (setq-local edit-window-right (split-window-right)) ;; ---- edit-window-right has the expected value at this point ---- (dolist (f '("/tmp/file1.lisp" "/tmp/file2.lisp")) (find-file-noselect f t)) (switch-to-buffer (get-file-buffer "/tmp/file1.lisp")) ;; after this line, edit-window-right has changed to nil (select-window edit-window-right) ;; <-- thus, this call doesn't work. (switch-to-buffer (get-file-buffer "/tmp/file2.lisp")) )) ``` I tried using setq instead of a let block, using different variable name, for example 'amp-edit-window-right, calling (switch-to-buffer (get-file-buffer "/tmp/file1.lisp") nil t), and all behave the same. When I do a line by line execution by using the new frame and M-: it is the same. And the window that edit-window-right is set to (#\<window 18 on some-file.el\>) still has the same print value after edit-window-right is set to nil (i.e. the same window still exists). Why would this happen? # Answer Annotating parts of your code: ``` (let (left-window edit-window-left edit-window-right) ;; ^ these variables go out of scope at the end of the `let' form, ;; ;; If you were using `setq' below instead of `setq-local' then you would ;; be manipulating these values; but because you're setting buffer-local ;; values instead, these let-bound variables never change from their `nil' ;; default values. ;; ;; We are currently in some arbitrary buffer X. (setq-local left-window (selected-window)) (setq-local edit-window-left (split-window-right 30)) ;; ^ These values are local to buffer X. (select-window edit-window-left) (setq-local edit-window-right (split-window-right)) ;; ^ This value is also local to buffer X (because `edit-window-left' is ;; still showing buffer X). (dolist (f '("/tmp/file1.lisp" "/tmp/file2.lisp")) (find-file-noselect f t)) ;; ^ These are quite likely to be different buffers to X. (switch-to-buffer (get-file-buffer "/tmp/file1.lisp")) ;; ^ We can no longer see the values which were local to X ;; (unless this buffer was X), so we will see the `nil' values ;; from your `let' bindings. (select-window edit-window-right) (switch-to-buffer (get-file-buffer "/tmp/file2.lisp")) ;; ^ As before -- we probably see the `let' bound values in here. ) ;; The `let' ends here, and so now *only* buffer X sees values for ;; `left-window', `edit-window-left', and `edit-window-right'. ``` > 3 votes # Answer 1. I'm guessing that you really want to use `setq`, not `setq-local` in that code. Did you intend to set buffer-local values of those `let`-bound variables? As @phils points out, `setq-local` sets a buffer-local variable. And the Elisp manual tells us, in node Creating Buffer Local: > Making a variable buffer-local within a `let`-binding for that variable does not work reliably, unless the buffer in which you do this is not current either on entry to or exit from the `let`. This is because `let` does not distinguish between different kinds of bindings; it knows only which variable the binding was made for. 2. What's more, when you change the current buffer in that code by visiting a file, the buffer you switch to turns on a major mode, and that invokes `kill-all-local-variables`, which does this: > `kill-all-local-variables` is a built-in function in ‘C source code’. > > `(kill-all-local-variables)` > > Switch to Fundamental mode by **killing current buffer's local variables**. > > Most local variable bindings are eliminated so that the default values become effective once more. Also, the syntax table is set from `standard-syntax-table`, the local keymap is set to `nil`, and the abbrev table from `fundamental-mode-abbrev-table`. This function also forces redisplay of the mode line. > > **Every function to select a new major mode starts by calling this function.** > > As a special exception, local variables whose names have a non-`nil` `permanent-local` property are not eliminated by this function. > > The first thing this function does is run the normal hook `change-major-mode-hook`. 3. `setq-local` is really `set` applied to a buffer-local variable. `(setq-local foo bar)` macroexpands to `(set (make-local-variable 'foo) bar)`. So `setq-local` always applies to a *dynamic* binding. Node Setting Variables of the Elisp manual tells us: > When dynamic variable binding is in effect (the default), `set` has the same effect as `setq`, apart from the fact that `set` evaluates its SYMBOL argument whereas `setq` does not. But when a variable is lexically bound, `set` affects its *dynamic* value, whereas `setq` affects its current (lexical) value. See Variable Scoping. > 4 votes # Answer You've been mislead by the unusual terminology in Emacs Lisp. A *buffer-local variable* is not a local variable! It's a global variable which has (potentially) different values in every buffer. “Buffer-local variable” is a shortcut for “variable with buffer-local bindings”. A buffer-local variable doesn't have to be global, but it usually is. The macro `setq-local` sets the *buffer-local value* of the specified *global* variable. To set the value of a local variable, call `setq`. > 3 votes --- Tags: frames, local-variables ---
thread-64730
https://emacs.stackexchange.com/questions/64730
org-mode not showing entries with timestamp
2021-05-06T12:51:15.693
# Question Title: org-mode not showing entries with timestamp I have the following entry in an org-mode file running emacs 26.3 freshly installed: ``` ** lorem ipsum <2021-05-09 Sun> ``` When opening the agenda or clicking the date there will be no entry in the calendar. Why is this? # Answer The answer was to be found here: https://orgmode.org/worg/org-configs/org-customization-guide.html "Just open a .org file, press `C-c [` to tell org that this is a file you want to use in your agenda, and start putting your life into plain text. " > 0 votes --- Tags: org-mode, time-date ---
thread-64733
https://emacs.stackexchange.com/questions/64733
How to stop Emacs from highlighting Linux Tab characters?
2021-05-06T16:39:52.367
# Question Title: How to stop Emacs from highlighting Linux Tab characters? So I opened a c++ script made in Xubuntu and every tab character was highlighted with grey. That doesn't happen when I open scripts made on Windows. How do I stop Emacs from highlighting them, it's very distracting? Here is a picture of what it looks like: # Answer You have `whitespace-mode` turned on. Turn it off. > 0 votes --- Tags: highlighting, tabs, whitespace-mode ---
thread-64735
https://emacs.stackexchange.com/questions/64735
Unable to bind a key in ledger-mode-map
2021-05-06T19:54:43.883
# Question Title: Unable to bind a key in ledger-mode-map Having written a function (say, `my-func`), I wanted to map it in `ledger-mode-map` to the keypress that I will call "Control dollar," that is, the dollar sign $, typed while the Ctrl key is held down. The expression: ``` (define-key ledger-mode-map (kbd "C-$") 'my-func) ``` when executed does not indicate a failure, but a subsequent `C-h my-func` indicates no key binding. Executing `C-h k C-$` produces the output "C-$ is undefined". I need a way to express "Control dollar" so that Emacs can recognize it as a keypress, if that is even possible. Here are a few of the alternatives I have tried to `(kbd "C-$")`: | Expression | Result when evaluated | | --- | --- | | \[?\C-4\] | 67108916 | | \[?\C-\\$\] | 67108900 | | (kbd "C-\\$") | 67108900 | | \[C-S-4\] | \[C-S-4\] | | (kbd "\[67108900\]") | "\[67108916\]" | | \[$\] | \[$\] | | \[\\$\] | \[$\] | | (kbd "C-\[$\]") | C- must prefix a single character, not \[$\] | | (kbd "C-$") | 67108900 | | \[(control $)\] | \[(control $)\] | | \[(control \\$)\] | \[(control $)\] | @amitp: It does work if I use `global-map` instead of `ledger-mode-map`. It does not work if I use, say, `C-!` instead of `C-$` with `ledger-mode-map`. # Answer > 0 votes Here's a MWE: ``` (require 'package) (setq package-archives nil) (add-to-list 'package-archives '("org" . "https://orgmode.org/elpa/" ) t) (add-to-list 'package-archives '("melpa" . "http://melpa.org/packages/" ) t) (add-to-list 'package-archives '("gnu" . "http://elpa.gnu.org/packages/") t) (package-initialize) (package-refresh-contents) (defun my-func () "Say `HEY'." (interactive) (message "HEY")) (use-package ledger-mode :ensure t :bind (:map ledger-mode-map ("<C-f13>" . my-func))) (define-key ledger-mode-map (kbd "C-$") 'my-func) ``` If we evaluate the above expression, then edit a buffer in ledger-mode, and then press either `C-$`or `C-f13`, "HEY" shows up in the minibuffer. But if instead of using `define-key` to do the mapping for `C-$`, we add it to the `:bind` section of `use-package` thus: ``` (use-package ledger-mode :ensure t :bind (:map ledger-mode-map ("<C-f13>" . my-func) ((kbd "C-$") . my-func))) ``` and then evaluate the expression, the `*Warnings*` buffer displays this: `Error (use-package): Failed to parse package ledger-mode: use-package: ledger-mode wants arguments acceptable to the 'bind-keys' macro, or a list of such values` The trick is to change that last line from ``` ((kbd "C-$") . my-func))) ``` to ``` ("C-$" . my-func))) ``` Then once again either `C-$` or `C-f13` display "HEY" in the minibuffer. --- Tags: keymap, ledger ---
thread-54070
https://emacs.stackexchange.com/questions/54070
Error during installation of Magit: "el-get: make el-get could not build transient [make EMACSBIN=c:/Users/.../emacs-26.1-x86_64/bin/emacs info]
2019-11-29T19:41:49.357
# Question Title: Error during installation of Magit: "el-get: make el-get could not build transient [make EMACSBIN=c:/Users/.../emacs-26.1-x86_64/bin/emacs info] **In this folder** `~/.emacs.d/el-get/transient (master)` **there are** following files for `transient` ``` ./ ../ .git/ .github/ .gitignore default.mk docs/ LICENSE lisp/ Makefile README.md ``` **then run** `runemacs --debug-init` from `MINGW64(git-bash)` command line and the following error message shows up: ``` Debugger entered--Lisp error: (error "el-get: make el-get could not build transient [make EMACSBIN=c:/Users/.../AppData/Local/emacs-26.1-x86_64/bin/emacs info]") signal(error ("el-get: make el-get could not build transient [make EMACSBIN=c:/Users/.../AppData/Local/emacs-26.1-x86_64/bin/emacs info]")) error("el-get: %s %s" "make" "el-get could not build transient [make EMACSBIN=c:/Users/.../AppData/Local/emacs-26.1-x86_64/bin/emacs info]") el-get-start-process-list(transient ((:command-name "make" :buffer-name "*el- `el-get-build(transient (("make" "EMACSBIN=c:/Users/.../AppData/Local/emacs-26.1-x86_64/bin/emacs" "info")) nil sync el-get-post-install-build)` el-get-post-install(transient) el-get-start-process-list(transient (nil (:command-name "*git submodule update*" :buffer-name "*git clone transient*" :default-directory "c:/Users/.../.emacs.d/el-get/transient/" :program "c:/Program Files/Git/bin/git.exe" :args ("--no-pager" "submodule" "update" "--init" "--recursive") :message "git submodule update ok" :error "Could not update git submodules")) el-get-post-install) el-get-start-process-list(transient ((:command-name "*git clone transient*" :buffer-name "*git clone transient*" :default-directory "c:/Users/.../.emacs.d/el-get" :program "c:/Program Files/Git/bin/git.exe" :args ("--no-pager" "clone" "--depth" "1" "-b" "master" "https://github.com/magit/transient.git" "transient") :message "Package transient installed." :error "Could not install package transient.") nil (:command-name "*git submodule update*" :buffer-name "*git clone transient*" :default-directory "c:/Users/.../.emacs.d/el-get/transient/" :program "c:/Program Files/Git/bin/git.exe" :args ("--no-pager" "submodule" "update" "--init" "--recursive") :message "git submodule update ok" :error "Could not update git submodules")) el-get-post-install) el-get-git-clone(transient "https://github.com/magit/transient.git" el-get-post-install) el-get-github-clone(transient nil el-get-post-install) ... ... ``` # Answer When el-get is installing the `transient` package required by Magit, it downloads it, enters its directory, and runs `make all`: ``` $ make all make[1]: Entering directory '/home/~/.emacs.d/el-get/transient/lisp' Compiling transient.el Generating transient-autoloads.el INFO Scraping files for transient-autoloads.el... INFO Scraping files for transient-autoloads.el...done make[1]: Leaving directory '/home/~/.emacs.d/el-get/transient/lisp' make[1]: Entering directory '/home/~/.emacs.d/el-get/transient/docs' Generating transient.info make[1]: makeinfo: No such file or directory make[1]: *** [Makefile:31: transient.info] Error 127 make[1]: Leaving directory '/home/~/.emacs.d/el-get/transient/docs' make: *** [Makefile:26: docs] Error 2 ``` However, it doesn't find the `makeinfo` command. On Ubuntu, try running the command to get more info about it: ``` $ makeinfo Command 'makeinfo' not found, but can be installed with: sudo apt install texinfo ``` Now you know what to do. Install `texinfo` and the installation of Magit will work. > 1 votes --- Tags: el-get ---
thread-64728
https://emacs.stackexchange.com/questions/64728
Exclude parts of the org-mode content based on export filetype
2021-05-06T10:52:33.437
# Question Title: Exclude parts of the org-mode content based on export filetype I work with org-reveal for presentations and export to LaTeX based PDF for handouts. I use SVG for the graphs in the reveal-presentation for better scaling and I want those to be ignored when exporting to LaTeX-PDF. Instead a PDF should be used. There are also some slides I want to have in the presentation but are not necessary for the handout. Is there a way to exclude parts of the tree from export, e.g., `:noexport:`, based on the export filetype? # Answer > 0 votes Since the graphs are pre-made, you can use export blocks to include the appropriate version for the appropriate export (IIRC, `ox-reveal` defines an exporter that's derived from HTML, hence the `html` tag in the block below): ``` #+BEGIN_EXPORT html [[file:/path/to/img.svg][An SVG image]] #+END_EXPORT #+BEGIN_EXPORT latex [[file:/path/to/img.pdf][A PDF image]] #+END_EXPORT ``` A bit ugly and repetitive, but it can be automated in the longer run. --- Tags: org-mode, org-export, org-reveal ---
thread-64745
https://emacs.stackexchange.com/questions/64745
Close only code folds using evil
2021-05-07T17:57:59.967
# Question Title: Close only code folds using evil How do I close all code folds (but not comments) with `evil`'s code folding? For now I'm using `evil-close-folds` and `evil-open-folds`, but it closes all folds, including comments. I'm using `spacemacs 0.300.0@26.3` with the `emacs` edit style. # Answer > 1 votes ``` (setq hs-hide-comments-when-hiding-all nil) ``` evil relies on `hs-minor-mode` for folding comments. and `hs-minor-mode` provides `hs-hide-comments-when-hiding-all` option to control whether hide comments. --- Tags: spacemacs, evil, code-folding ---
thread-64747
https://emacs.stackexchange.com/questions/64747
Occur: optional arg REGION usage
2021-05-07T20:25:16.230
# Question Title: Occur: optional arg REGION usage I have 2 markers (created with `copy-marker`): `b` and `e` and I want to run `occur` for the string "foo" on the region between `b` and `e`. What's the correct syntax? I tried: ``` (occur "foo" 1 '((b . e))) ``` because the help says: > Optional arg REGION, if non-nil, mean restrict search to the specified region. Otherwise search the entire buffer. REGION must be a list of (START . END) positions as returned by ‘region-bounds’. but it doesn't work. I also tried: ``` (occur "foo" 1 '(((point-min) . (point-max)))) ``` to try to understand the syntax, but it doesn't work. # Answer > 3 votes You are quoting too much and e.g. not giving a chance to `point-min` and `point-max` to evaluate anything - ditto for `b` and `e` in your first attempt. Try `(occur "foo" 1 (list (cons (point-min) (point-max))))` or `(occur "foo" 1 (list (cons b e)))` or use backticks and commas to allow the selective evaluation of subexpressions: `(occur "foo" `((,(point-min) . ,(point-max))))` or `(occur "foo" `((,b . ,e)))` --- Tags: occur ---
thread-64729
https://emacs.stackexchange.com/questions/64729
How to fold nested list items in markdown-mode
2021-05-06T12:16:36.887
# Question Title: How to fold nested list items in markdown-mode I would like to be able to fold nested list items in markdown-mode in the same way that it is possible to do in org-mode, so that, for example, the first sub-item in the following list can be easily hidden. * List item 1 + List item 1.1 * List item 2 The result would look something like the following. * List item 1 ... * List item 2 And ideally I would like to be able to use the mouse to fold and unfold the relevant blocks of text, and to have a marker displayed in the left margin to indicate that a block can be, or has been, folded. From what I've read, it looks like the most promising option may be to use hs-minor-mode, which allows the use of the mouse to fold and unfold blocks, along with hideshowvis, which displays indicators in the margin for the blocks that can be folded, or have been folded, by hs-minor-mode. I've tried out a few other ways of doing the folding that work ok---in particular, selective display, origami, and yafolding---but, as far as I could see, none of them allowed for the use of the mouse to fold and unfold blocks. I tried to set this up using hs-minor-mode but couldn't get it to work. I think I needed to define a 'forward-sexp' function, or something, but this is beyond my current capabilities. Has anyone set up markdown-mode to fold nested list items like this? Does anyone have any advice on how I could get it working? # Answer > 4 votes `markdown-mode` uses parts of `outline-mode` for folding. So, IMHO it is most natural to implement the folding of items also with the help of `outline-mode`. The most obvious way would be: 1. to include beside `markdown-regex-header` also `markdown-regex-list` in `outline-regexp` 2. to replace the function `markdown-outline-level` as value of variable `outline-level` by some other function which also assigns levels to matched lists. Pityingly, step 2 of this strategy does not work since `markdown-mode` uses `outline-level` in other contexts. So, an advice is needed for `markdown-outline-level`. Setting the `mouse-face` and `keymap` text properties on heading markers and list items is quite standard. `md-outline-list.el` is an example implementation of a package that can fold items in Markdown files. You can toggle the folding by mouse-clicks on the bullets or the heading markers. Marking the foldable regions on the fringe is not (yet) implemented. --- Tags: code-folding, markdown-mode, hideshow ---
thread-64752
https://emacs.stackexchange.com/questions/64752
How do I order overlays?
2021-05-08T09:32:10.377
# Question Title: How do I order overlays? I have two overlays that are initially in the same position. ``` (defvar-local minibuffer-overlay nil) (defvar-local minibuffer-overlay2 nil) (defun minibuffer-advice (fn &rest args) (minibuffer-with-setup-hook #'minibuffer-setup (apply fn args))) (defun minibuffer-setup () (setq minibuffer-overlay (make-overlay (point-min) (point-min) nil t nil)) (setq minibuffer-overlay2 (make-overlay (point-min) (point-min) nil t t)) (add-hook 'post-command-hook #'minibuffer-exhibit nil 'local)) (defun minibuffer-exhibit () (move-overlay minibuffer-overlay (minibuffer-prompt-end) (minibuffer-prompt-end)) (overlay-put minibuffer-overlay 'before-string "!") (move-overlay minibuffer-overlay2 (point-max) (point-max)) (overlay-put minibuffer-overlay2 'after-string "?")) (advice-add #'completing-read-default :around #'minibuffer-advice) ``` M-x looks like `M-x ?!|` where `|` is the cursor. If I type `foo` then it becomes `M-x !foo?|`. How do I make M-x initially look like `M-x !?|` instead? EDIT: Example for a \*scratch\* buffer since it may be confusing having it in the minibuffer: ``` (let ((overlay1 (make-overlay (point-min) (point-min))) (overlay2 (make-overlay (point-min) (point-min)))) (move-overlay overlay1 (point-min) (point-min)) (overlay-put overlay1 'before-string "!") (move-overlay overlay2 (point-min) (point-min)) (overlay-put overlay2 'after-string "?")) ``` The beginning of the buffer will look like `?!`. Why does the second overlay come first and how can I change that? # Answer Your two overlays have coincident beginning and end; that is, the beginning and end position are the same. So regardless of the order of what is displayed by properties `before-string' and` after-string', the definitions of those properties hold. The Elisp manual, node Overlay Properties tells us: > **‘before-string’** This property’s value is a string to add to the display at the beginning of the overlay. The string does not appear in the buffer in any sense—only on the screen. > **‘after-string’** This property’s value is a string to add to the display at the end of the overlay. The string does not appear in the buffer in any sense—only on the screen. Both of those hold, because the beginning and end positions are the same. Your `?` is after that position and your `!` is before it. Nothing about the definitions is violated. Those descriptions hint that you shouldn't (can't) depend on the apparent order of those displayed strings when beginning and end coincide. --- You can remove the `overlay-move` sexps from your minimal example, as they do nothing. --- I suspect this may be an X-Y question. What's the question behind your question - what is it that you are really trying to do? (Ask that in a separate question - don't edit this one to change this one.) Why are you trying to use `before-string` and `after-string` on empty overlays? > 1 votes --- Tags: overlays ---
thread-20993
https://emacs.stackexchange.com/questions/20993
How to toggle company-mode with $ prefix?
2016-03-16T14:40:37.343
# Question Title: How to toggle company-mode with $ prefix? When I write JavaScript code, company does not toggle when prefix is `$`, how to fix it? ``` (setq company-idle-delay 0) (setq company-minimum-prefix-length 0) (setq company-auto-complete t) (setq company-require-match nil) ``` # Answer > 0 votes You need `company-dabbrev-code` ; my config : ``` (use-package company :init (setq company-minimum-prefix-length 1 company-selection-wrap-around t company-dabbrev-code-ignore-case t company-dabbrev-downcase nil company-dabbrev-ignore-case t company-backends '((company-dabbrev-code) (company-yasnippet company-capf ; completion-at-point-functions company-files ; files & directory company-keywords))) ;; (setq company-dabbrev-downcase nil) (eval-after-load 'company '(add-to-list 'company-backends '(company-dabbrev-code company-yasnippet company-abbrev company-dabbrev company-capf)))) ``` --- Tags: company-mode ---
thread-62658
https://emacs.stackexchange.com/questions/62658
Font Size (Face Attributes, Height) in Org Mode's Column View
2021-01-08T03:46:33.427
# Question Title: Font Size (Face Attributes, Height) in Org Mode's Column View Happy New Year! I use Org Mode and columnview extensively. The issue I am having is that zooming (`Command +` on MacOs or `C- +` on PC) doesn't work in column view. Here is an example before zooming in Now, here is the view after zooming in (using `C- +` on PC and `CMD +` on Mac. You can clearly see text from the property drawer enlarged and the text from the columns unchanged. I have looked at the face attributes in column view using `C-u C-x =` to get The right-hand buffer with the face information is I cannot quite figure out where to go from here. I thought about clicking on the line `((:foreground unspecified) (:height 120 :family "Menlo") org-column org-level-2)` which brings up Clicking on `(customize this face)` at the top brings up Clicking on brings up this menu Checking `Height` and using `2.0` instead of `1.0` and hitting `Apply` blows up the font of the headers. I need to increase the font size of the text in the column cells. Anybody knows how to do this? # Answer > 1 votes The culprit is Material theme. I like it, but it interferes with font size in Org's column view. --- Tags: org-mode, customize-face ---
thread-64765
https://emacs.stackexchange.com/questions/64765
xref-find-defnition not finding any definition
2021-05-09T11:52:42.407
# Question Title: xref-find-defnition not finding any definition I am a newbie and in this part of the tutorial: " More generally, if you want to see a function in its original source file, you can use the xref-find-definitions function to jump to it. xref-find-definitions works with a wide variety of languages, not just Lisp, and C, and it works with non-programming text as well. For example, xref-find-definition will jump to the various nodes in the Texinfo source file of this document (provided that you've run the \`etags' utility to record all the nodes in the manuals that come with Emacs; " M-. doesn't find any definition of functions even though the autocompletion in the call works. I have no idea how to create a tag table, because the manual just states "etags *inputfile*" but again I have no idea which file i would need to create my tags on. Also find-function doesn't work either, it just states simple.el can't be found which is no surprise because only a simple.elc exists. so it searches for the wrong file by default but i don't know how to change that either. Can somebody help? # Answer You need create tags file in project root first. Run `etags` in project root to create tags file whose name is `TAGS`. etags is a command line program bundled with Emacs. See https://www.gnu.org/software/emacs/manual/html\_node/emacs/Create-Tags-Table.html for details These days most people use `ctags` instead of `etags`. Run `ctags -e .` in project root to create tags files. There are two ctags implementation, Exuberant Ctags and Universal Ctags. Universal Ctags is more actively maintained. See https://en.wikipedia.org/wiki/Ctags for details. > 2 votes --- Tags: xref ---
thread-64763
https://emacs.stackexchange.com/questions/64763
How to delete a link in org mode in spacemacs
2021-05-09T09:34:23.360
# Question Title: How to delete a link in org mode in spacemacs I was trying to delete a link and replace it with the description in org mode. And I thought there would be a command to do it. But I could not find one. There is a solution here. But the question is dated. So, I thought I would ask again. Is not there a built-in solution to remove the link but retain the description? # Answer > 2 votes Just `C-c C-l` on the link and `C-a C-k` in the minibuffer to delete the link part will do it.. This used to produce an error before Org mode version 9.4, but it no longer does (see commit https://code.orgmode.org/bzg/org-mode/commit/6d62c76d2). --- Tags: org-mode, org-link, hyperlinks ---
thread-60329
https://emacs.stackexchange.com/questions/60329
Byte compilation error with use-package
2020-08-27T00:50:21.197
# Question Title: Byte compilation error with use-package The beginning of my `~/.emacs.d/init.el` file looks like this: ``` ;; MELPA (require 'package) (setq package-enable-at-startup nil) (setq package-check-signature nil) (add-to-list 'package-archives '("melpa" . "https://melpa.org/packages/")) (add-to-list 'package-archives '("elpy" . "https://jorgenschaefer.github.io/packages/")) ;; boostrap 'use-package' (unless (package-installed-p 'use-package) (package-refresh-contents) (package-install 'use-package)) (use-package windmove ;; move cursor between windows :demand :bind (("C-<left>" . windmove-left) ("C-<right>" . windmove-right) ("C-<up>" . windmove-up) ("C-<down>" . windmove-down))) ... more stuff ... ``` I am trying to byte compile my `init.el` file. I execute the following in the terminal, sinde the `~/.emacs.d/` directory: ``` $ emacs --batch --eval '(byte-compile-file "init.el")' ``` The output is: ``` In toplevel form: init.el:59:1:Warning: ‘("C-<left>" . windmove-left)’ is a malformed function init.el:59:14:Warning: reference to free variable ‘windmove’ init.el:62:3:Error: Wrong type argument: sequencep, windmove-right ``` Basically, the very first key binding definition fails... and there is also some sort of warning about a free variable. How do I properly byte-compile the `init.el` file - even for the above very simple example (imagine there's nothing else to the `init.el` file)? # Answer Your code is missing a `(require 'use-package)`; without that, Emacs gets confused about use-package and treats it as a function instead of a macro. > 1 votes # Answer A guess is that you need to quote the list after `:bind`: ``` '(("C-<left>" . windmove-left) ("C-<right>" . windmove-right) ("C-<up>" . windmove-up) ("C-<down>" . windmove-down)) ``` The error message tells you that the compiler is trying to *evaluate* this as a functional application: ``` (("C-<left>" . windmove-left) ("C-<right>" . windmove-right) ("C-<up>" . windmove-up) ("C-<down>" . windmove-down)) ``` That is, it's looking at that as an application of the "function" `("C-<left>" . windmove-left)` to the arguments that are the other elements of that list. It looks as the list as `(FUNCTION ARG1 ARG2 ARG3)`. Because it's trying to *evaluate* the list instead of taking it as data (i.e., as a list), I assume you need to quote it (`'`). Quoting it prevents evaluation of the list itself; evaluating a quoted list just returns the list. **UPDATE** Well, I don't use `use-package`, and know nothing about it. I just know that the error message means the list you have is being interpreted as a functional application. But looking at other questions about `use-package` with `:bind` I see that the list after `:bind` is not supposed to be quoted. So another guess is that you're missing something after `:demand`, so that `:demand` is acting on `:bind`, and so the list after `:bind` is evaluated. (Just another guess...) And finding other examples, it seems that what you're missing after `:demand` is `t`: ``` (use-package windmove ;; move cursor between windows :demand t :bind (("C-<left>" . windmove-left) ("C-<right>" . windmove-right) ("C-<up>" . windmove-up) ("C-<down>" . windmove-down))) ``` In sum, each of the keywords (`:demand` and `:bind`) needs to be followed by a value. Because `:demand` was missing its value (`t`) the compiler took the `:bind` after it as the value of `:demand`. And after that there was no keyword but just a list. And that got evaluated as a functional application. > -1 votes --- Tags: init-file, debugging, use-package, byte-compilation ---
thread-64775
https://emacs.stackexchange.com/questions/64775
Is there any way to get the memory size (usage) of a Lisp variable/value?
2021-05-09T22:41:57.017
# Question Title: Is there any way to get the memory size (usage) of a Lisp variable/value? Basically `sizeof` for lists, hashmaps, etc., with nested structures. I could of course disable garbage collection and then compare numbers from memory usage functions before and after allocation, getting vaguely informative but imprecise numbers—due to probably also having created intermediate vars. But maybe there's a method that involves less approximate guesswork and more straightforward calculation? # Answer > Is there any way to get the memory size/usage of a variable? Emacs 28 adds a more fine-grained memory usage reporting command than was previously available: ``` ** New command 'memory-report'. This command opens a new buffer called "*Memory Report*" and gives a summary of where Emacs is using memory currently. ``` One of its subroutines is `memory-report-object-size`: ``` (defun memory-report-object-size (object) "Return the size of OBJECT in bytes." (unless memory-report--type-size (memory-report--garbage-collect)) (memory-report--object-size (make-hash-table :test #'eq) object)) ``` For example: ``` (let ((table (make-hash-table))) (mapcar #'memory-report-object-size (list (cons nil nil) (list nil nil) table (cons table table) (list table table)))) ;; => (16 32 1056 1072 1088) ``` > 8 votes --- Tags: debugging, performance ---
thread-5389
https://emacs.stackexchange.com/questions/5389
Correcting and maintaining org-mode hyperlinks
2014-12-14T23:08:20.333
# Question Title: Correcting and maintaining org-mode hyperlinks This is a two part question having to do with link rot. 1. Does org-mode provide any functionality for validating hyperlinks, especially local ones? This could be used to combat link rot after the fact. 2. Even better, does org provide functionality so that if I rename a file in dired, it will update affected files? This could prevent some kinds of link rot before it happens, at least for local files. # Answer > 7 votes For part 1, I didn't find anything built-in. The following function will provide a list of broken links in the minibuffer. I've tested it on some simple examples, but far from exhaustively. ``` (defun check-bit-rot () "Searches current buffer for file: links, and reports the broken ones." (interactive) (save-excursion (beginning-of-buffer) (let (file-links) (while (re-search-forward org-link-bracket-re nil t) (if (string= "file:" (match-string-no-properties 1)) (if (not (file-exists-p (match-string-no-properties 3))) (setq file-links (cons (match-string-no-properties 0) file-links))))) (message (concat "Warning: broken links in this file:\n" (mapconcat #'identity file-links "\n")))))) ``` # Answer > 19 votes Since Org 9.0 you can run the `org-lint` function which, among other things, checks for broken local links. # Answer > 4 votes I wrote a Python script https://github.com/cashTangoTangoCash/orgFixLinks that attempts to repair broken links to local files, within one or more org files on a local drive in the Ubuntu OS. It is certainly an amateur command line script, but might be worth playing with. There is a GitHub wiki that provides a degree of documentation: https://github.com/cashTangoTangoCash/orgFixLinks/wiki. Please check the warnings in the README. I'm sorry that this Python script is not a part of Org, but completely separate/stand-alone. I hope no-one is bothered that I am not answering the question of the OP directly; I just thought someone might like playing with the Python script. # Answer > 0 votes ``` (setq org-id-link-to-org-use-id 'create-if-interactive-and-no-custom-id) ``` * use `org-store-link` to store a link (works on non-org files, too) * use `org-insert-link` to insert the stored link If you want more features: * org-super-links * org-roam Update: `org` needs some kind of config to actually find the IDs after renames. One way to do this is to: * Install `org-roam` * Set `org-roam-directory` to the root of all your files * Run `(org-roam-db-build-cache)`, `(org-roam-db-update)` Another solution is to set `org-id-extra-files` to all the org files you have. --- Tags: org-mode ---
thread-64777
https://emacs.stackexchange.com/questions/64777
solve error: variable is void: projectile-mode-map
2021-05-10T01:38:20.120
# Question Title: solve error: variable is void: projectile-mode-map I'm trying to bind projectile-find-file to a keyboard shorcut and running in to this error. Apparently projectile is installed, because M-x listing shows at least a dozen projectile prefixed commands. # Answer > 2 votes Projectile might not be loaded. (require 'projectile) should work fine. Some projectile functions, listed by M-x, are just prepared to be autoloaded. EDIT: Thanks, @Basil The answer above is not wrong. But in your init.el, writing `(require 'projectile)` is not recommended, because projectile can be loaded on your first time to use one of the projectile functions prepared to be autoloaded. Writing `require` in init.el lead longer startup time of Emacs. So replace the `BODY...` with provided `define-key`s on below code: ``` (with-eval-after-load 'projectile BODY...) ``` `BODY` in `with-eval-after-load` is evaluated after loading of projectile. So this code makes sure that `BODY` is evaluated after defining `projectile-mode-map`. On the other hand, if you just want to try the key binds only on the current sesstion, requiring projectile and evaluating them are easy, i think. Technical Words: "Require" has almost same meanings as "load." It means reading el(c) file and making the feature available. --- Tags: projectile ---
thread-64780
https://emacs.stackexchange.com/questions/64780
Export all org-tables from batch mode
2021-05-10T03:40:14.810
# Question Title: Export all org-tables from batch mode How can I export all the tables in org-mode file similar to that. ``` * May :PROPERTIES: :TABLE_EXPORT_FILE: ~/Desktop/may.csv :TABLE_EXPORT_FORMAT: orgtbl-to-csv :END: |One|Two| |---+---| * June :PROPERTIES: :TABLE_EXPORT_FILE: ~/Desktop/june.csv :TABLE_EXPORT_FORMAT: orgtbl-to-csv :END: |One|Two| |---+---| ``` I want to run something like this to export all tables to the defined file. ``` emacs --batch table.org --eval 'org-table-export' ``` The problem is that I have to be in the table. # Answer > 4 votes You can use `org-table-map-tables` for iterating over the tables of an Org file. Example for the Shell command: ``` emacs --batch table.org --eval '(org-table-map-tables (quote org-table-export))' ``` You should give the file names for the exported tables and the export format in the org file like that: ``` * First Section :PROPERTIES: :TABLE_EXPORT_FILE: first.csv :TABLE_EXPORT_FORMAT: orgtbl-to-csv :END: | header 1 | header 2 | |----------+----------| | 1.1 | 1.2 | | 2.1 | 2.2 | * Second Section :PROPERTIES: :TABLE_EXPORT_FILE: second.csv :TABLE_EXPORT_FORMAT: orgtbl-to-csv :END: | 2nd header 1 | 2nd header 2 | |--------------+--------------| | 21.1 | 21.2 | | 22.1 | 22.2 | ``` --- Tags: org-mode, org-table, batch-mode ---
thread-44771
https://emacs.stackexchange.com/questions/44771
Term double prompting (duplicate prompts) in Emacs
2018-09-15T18:08:20.180
# Question Title: Term double prompting (duplicate prompts) in Emacs My **term** in emacs appear: ``` 0;me@debian: ~me@debian:~$ ``` instead of `me@debian:~$` ``` ~$ echo $PS1 \[\e]0;\u@\h: \w\a\]\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;33m\]\w\[\033[00m\]\[\033[0;35m\]$\[\033[0m\] ``` Versions: **debian-9.5.0** and **GNU Emacs 25.1.1** I tried various solutions given in stackexchange by adding additional lines to `.bashrc` and `init.el` But nothing worked out. This issue is there in **shell** also; but not in **eshell**. # Answer Based on the S.O. duplicates linked to in the question, the initial `\[\e]0;\u@\h: \w\a\]` is intended to set the title text of an xterm window. If the terminal does not recognise those (non-standard) escape codes (as is the case in `term` and `shell`), you end up with the situation shown in the question. If you want to retain the xterm behaviour in compatible terminals, you should perform the appropriate tests in your shell config when setting `PS1`, such that you only set that prefix in situations where it is supported. If you don't care about xterm window titles, then just remove the prefix from the prompt entirely. If you want to keep those, then add those codes conditionally. ``` # Generic colour prompt (works in Emacs) PS1="\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;33m\]\w\[\033[00m\]\[\033[0;35m\]$\[\033[0m\] " # In an xterm, also set the window title case $TERM in xterm*) PS1="\[\e]0;\u@\h: \w\a\]$PS1";; esac ``` > 0 votes # Answer I ran into this and found it was caused (in fish at least), by `fish_title` being set. This resolved the issue: ``` if status is-interactive if [ "$TERM" = "eterm-color" ] # pass else function fish_title if [ $_ = 'fish' ] echo "["(prompt_pwd)"]" else echo "("$_")" end end end end ``` > 0 votes --- Tags: shell, ansi-term, term, prompt ---
thread-64787
https://emacs.stackexchange.com/questions/64787
Automatically update a date in tangled files of an .org file?
2021-05-10T14:27:39.807
# Question Title: Automatically update a date in tangled files of an .org file? I'm in the process of writing a LaTeX class using `org-babel` for the literate programming. In several places of the file `.org` file, I have to insert the release date of this class, at least in the tangled `README.md` file like this: ``` Release ------- 2021-05-10 v1.0.0-alpha ``` and in the tangled `.cls` source file of the class, like this: ``` \ProvidesExplPackage{my-nice-class} {2021-05-10} {v1.0.0-alpha} { Lorem ipsum dolor sit amet, consectetuer adipiscing elit. } ``` Because I'm likely to forget to update this date before the actual release, I'd like it to be automatically updated each time the `.org` file is saved (in the same spirit as Inserting and Updating Copyrights). Is it possible? ## Edit In order to make clearer my question, here is a minimal example of my `org-mode` file: ``` #+TITLE: My Nice Class #+LANGUAGE: en #+OPTIONS: num:t toc:nil #+LaTeX_CLASS: article #+LaTeX_CLASS_OPTIONS: [11pt,english] #+LaTeX_HEADER: \usepackage{babel} #+PROPERTY: header-args :padline no :tangle my-nice-class.cls :exports both :noweb yes :eval always #+begin_src markdown :tangle README.md :exports none my-nice-class ============================================================= About ------- This class is mine and nice! Release ------- 2021-05-10 v1.0.0-alpha #+end_src #+begin_src latex \ProvidesExplClass{my-nice-class} {2021-05-10} {v1.0.0-alpha} { A nice class } #+end_src ``` # Answer # Update: noweb references I misunderstood your question. My original solution works for text *outside of code blocks*, when you asked for updating values *inside code blocks*. To accomplish this, we can use (org) Noweb Reference Syntax. This allows us to insert the value of one code block in another. Using your example, this looks like: ``` #+TITLE: My Nice Class #+LaTeX_CLASS: article #+LaTeX_CLASS_OPTIONS: [11pt,english] #+LaTeX_HEADER: \usepackage{babel} #+PROPERTY: header-args :padline no :exports both :noweb yes :eval always #+name: release-date #+begin_src elisp :exports none 2021-05-10 #+end_src #+name: release-version #+begin_src elisp :exports none v1.0.0-alpha #+end_src #+begin_src markdown :tangle README.md :exports none :noweb yes my-nice-class ============================================================= About ------- This class is mine and nice! Release ------- <<release-date>> <<release-version>> #+end_src #+begin_src latex :noweb yes :tangle my-nice-class.cls \ProvidesExplClass{my-nice-class} {<<release-date>>} {<<release-version>>} { A nice class } #+end_src ``` You don't need to use `elisp` source blocks, any language will do. The key thing is the block needs to return the value you want inserted elsewhere. The blocks need to have names, which you can then reference with the `<<<block-name>>>` syntax. Tangling this file with `org-babel-tangle` produces two code files. my-nice-class.cls: ``` \ProvidesExplClass{my-nice-class} {2021-05-10} {v1.0.0-alpha} { A nice class } ``` And README.md: ``` my-nice-class ============================================================= About ------- This class is mine and nice! Release ------- 2021-05-10 v1.0.0-alpha ``` I don't think there's a way to capture macro values, like `date`, in noweb references. You could use `before-save-hook` to call a custom function that searches for the `reference-date` block and updates the contents to accomplish this. # Original answer: org macros I think this is one of the main use-cases for (org) Macro Replacement. In your case, you could do something like this: ``` #+MACRO: RELEASE 2021-05-10 v1.0.0-alpha * Release {{{RELEASE}}} ``` The macro is replaced every time you export your file. Use the {{{RELEASE}}} string anywhere you need it in your document. There are also ways to automatically generate dates, either the date the file was exported, or the `DATE` keyword from the org file header. See the manual page for more details. # Auto-updating on save I use the following code to automatically update the `DATE` of my org-mode file: ``` (defun tws-org-set-time-file-property (property &optional anywhere pos) "Set the time file PROPERTY in the preamble. When ANYWHERE is non-nil, search beyond the preamble. If the position of the file PROPERTY has already been computed, it can be passed in POS. https://github.com/zaeph/.emacs.d/blob/615ac37be6bd78c37e967fdb43d28897a4116583/lisp/zp-org.el#L194" (when-let ((pos (or pos (tws-org-find-time-file-property property)))) (save-excursion (goto-char pos) (if (looking-at-p " ") (forward-char) (insert " ")) (delete-region (point) (line-end-position)) (let* ((now (format-time-string "[%Y-%m-%d %a %H:%M]"))) (insert now))))) (defun tws-org-set-date () "Update the LAST_MODIFIED file property in the preamble. https://github.com/zaeph/.emacs.d/blob/615ac37be6bd78c37e967fdb43d28897a4116583/lisp/zp-org.el#L212" (when (and (derived-mode-p 'org-mode) (buffer-modified-p)) (tws-org-set-time-file-property "DATE"))) (add-hook 'before-save-hook 'tws-org-set-date nil t) ``` This will automatically update the `#+DATE:` header in your file after each save. That means you can use the `{{{date}}}` macro in your document anywhere you need to to update to the last-saved date. > 3 votes --- Tags: org-mode, org-babel, time-date ---
thread-64766
https://emacs.stackexchange.com/questions/64766
Add custom agenda options instead of replacing the whole set
2021-05-09T11:58:00.923
# Question Title: Add custom agenda options instead of replacing the whole set I use some custom agendas for work and some for personal stuff. At the moment I load a huge set of custom agendas in `org-agenda-custom-commands` containing all agendas for work and for personal stuff. This clutters up the dispatcher. When I define two different sets of custom agendas, one for work and one for personal, I can only load and access agendas of one set. But with home office, sometimes I need "work agendas" on my personal computer. How can I write the configuration, that I can "add" sets of agendas to `org-agenda-custom-commands` if necessary, without completely replacing it with one set or the other? # Answer > 0 votes Only way I can think of is to use a function which sets the variable and then calls the dispatcher. Something like: ``` (defun my/org-agenda-dispatcher-PERSONAL () (interactive) (setq org-agenda-custom-commands '(("1" "Week Agenda + All Tasks" ((agenda "w" ((org-agenda-span 'week))) (todo "TODO|LATER" ((org-agenda-sorting-strategy '(todo-state-up)) (org-agenda-skip-function '(org-agenda-skip-entry-if 'scheduled))) ))))) (org-agenda)) (defun my/org-agenda-dispatcher-WORK () (interactive) (setq org-agenda-custom-commands '(("1" "Today's Agenda + Priority Tasks" ((agenda "d" ((org-agenda-span 'day))) (todo "TODO" ((org-agenda-sorting-strategy '(todo-state-up)) (org-agenda-skip-function '(org-agenda-skip-entry-if 'scheduled)))))))) (org-agenda)) ``` Then you just call your custom functions rather than the generic `org-agenda` command. But you'd have to watch out for other commands which might rely on the `org-agenda-custom-commands` variable. --- Tags: org-mode, org-agenda, config ---
thread-17430
https://emacs.stackexchange.com/questions/17430
How to implement remove-key to completely undo the effect of define-key
2015-10-16T20:55:46.807
# Question Title: How to implement remove-key to completely undo the effect of define-key A long time ago I implemented `remove-key` to completely undo the effect of `define-key`, but when I just tried that implementation, it did not work reliably. How would you implement `remove-key` so that for any given key this is true: ``` (let ((map (make-sparse-keymap))) (define-key map KEY 'bound) (remove-key map KEY) map) => (keymap) ``` It should also work for non-sparse keymaps. And when a sub-keymap is involved which becomes empty when the key is removed, then the sub-keymap should also be removed. Here's the documentation - now I only need an implementation :-) ``` (defun remove-key (keymap key) "In KEYMAP, remove key sequence KEY. Make the event KEY truely undefined in KEYMAP by removing the respective element of KEYMAP (or a sub-keymap) as opposed to merely setting it's binding to nil. There are several ways in which a key can be \"undefined\": (keymap (65 . undefined) ; A (66)) ; B As far as key lookup is concerned A isn't undefined at all, it is bound to the command `undefined' (which doesn't do anything but make some noise). This can be used to override lower-precedence keymaps. B's binding is nil which doesn't constitute a definition but does take precedence over a default binding or a binding in the parent keymap. On the other hand, a binding of nil does _not_ override lower-precedence keymaps; thus, if the local map gives a binding of nil, Emacs uses the binding from the global map. All other events are truly undefined in KEYMAP. Note that in a full keymap all characters without modifiers are always bound to something, the closest these events can get to being undefined is being bound to nil like B above." ...) ``` Why do I want that? It has already been mentioned in the above doc-string, but here it is again, quoting (elisp)Format of Keymaps (emphasis mine). > **When the binding is `nil`**, it doesn't constitute a definition but **it does take precedence over a default binding or a binding in the parent keymap**. On the other hand, a binding of `nil` does *not* override lower-precedence keymaps; thus, if the local map gives a binding of `nil`, Emacs uses the binding from the global map. `(define-key map KEY nil)` does not remove the entry for `KEY`, it just sets the binding to `nil`, which "doesn't constitute a definition", but which never-the-less can have an effect. # Answer > 3 votes Eventually I came up with a solution that satisfies me and added it to my `keymap-utils` package. ``` (defun kmu-remove-key (keymap key) "In KEYMAP, remove key sequence KEY. Make the event KEY truely undefined in KEYMAP by removing the respective element of KEYMAP (or a sub-keymap) as opposed to merely setting its binding to nil. There are several ways in which a key can be \"undefined\": (keymap (65 . undefined) ; A (66)) ; B As far as key lookup is concerned A isn't undefined at all, it is bound to the command `undefined' (which doesn't do anything but make some noise). This can be used to override lower-precedence keymaps. B's binding is nil which doesn't constitute a definition but does take precedence over a default binding or a binding in the parent keymap. On the other hand, a binding of nil does _not_ override lower-precedence keymaps; thus, if the local map gives a binding of nil, Emacs uses the binding from the global map. All other events are truly undefined in KEYMAP. Note that in a full keymap all characters without modifiers are always bound to something, the closest these events can get to being undefined is being bound to nil like B above." (when (stringp key) (setq key (kmu-parse-key-description key t))) (define-key keymap key nil) (setq key (cl-mapcan (lambda (k) (if (and (integerp k) (/= (logand k ?\M-\0) 0)) (list ?\e (- k ?\M-\0)) (list k))) key)) (if (= (length key) 1) (delete key keymap) (let* ((prefix (vconcat (butlast key))) (submap (lookup-key keymap prefix))) (when (and (not (eq submap 'ESC-prefix)) (= (length submap) 1)) (delete (last key) submap) (kmu-remove-key keymap prefix))))) ``` --- *The old answer because it discusses some details:* After looking at it again I realized that my existing implementation actually works quite well, but is very picky about the format of the KEY. It has to be a vector in the "internal format", so `[?\C-i]` would work but `[(control ?i)]` would not. All elements have to be either integers or symbols. ``` (defun remove-key (keymap key) (define-key keymap key nil) (setq key (cl-mapcan (lambda (k) (if (and (integerp k) (/= (logand k ?\M-\^@) 0)) (list ?\e (- k ?\M-\^@)) (list k))) key)) (if (= (length key) 1) (delete key keymap) (let* ((prefix (vconcat (butlast key))) (submap (lookup-key keymap prefix))) (delete (last key) submap) (when (= (length submap) 1) (remove-key keymap prefix))))) ``` `?\M-\^@` is Emacs' value for the meta key. To make this function less picky about the format of the KEY, this might work: ``` (setq key (if (stringp key) (edmacro-parse-keys key t) (edmacro-parse-keys (key-description key) t))) ``` The first line `(define-key keymap key nil)` should take care of the case where KEY is part of the full keymap's char-table, assuming this is correct: > Note that in a full keymap all characters without modifiers are always bound to something, the closest these events can get to being undefined is being bound to nil like B above. That first line should also prevent the parent keymap from being modified, in the non-char-table case. I do not avoid doing that for a full keymap, because there is no `full-keymap-p` predicate. Usually the first element of a full keymap is the char-table, but last I checked that was not actually enforced, a keymap also functions as a full keymap if a later element is a char-table. It just seemed wiser to do some potentially unnecessary work instead of risking getting it wrong. # Answer > 2 votes You could start with ``` (defun remove-key (keymap key) (let ((binding (assq key keymap)) (parentbinding (assq key (keymap-parent keymap)))) (and binding (not (eq binding parentbinding)) ;Don't change the parent! (delq binding keymap)))) ``` This will only work for a sparse `keymap` and expects `key` to be a single key, rather than a key sequence. \[ And it's guaranteed 100% untested, so even for that limited case it might not work. \] # Answer > 2 votes This is a simplified version of information extracted from the accepted answer posted by tarsius which contains more advanced information and requires a package for `kmu-parse-key-description`. This small stand alone function undoes the effect of `define-key` by removing the declaration from the keymap. Removing the declaration is more effective than setting its value to nil. ``` (defun remove-key (keymap key) (define-key keymap key nil) (setq key (cl-mapcan (lambda (k) (if (and (integerp k) (/= (logand k ?\M-\^@) 0)) (list ?\e (- k ?\M-\^@)) (list k))) key)) (if (= (length key) 1) (delete key keymap) (let* ((prefix (vconcat (butlast key))) (submap (lookup-key keymap prefix))) (delete (last key) submap) (when (= (length submap) 1) (remove-key keymap prefix))))) ``` Thanks to tarsius, the above code works. I used `remove-key` to remove troublesome cua keys which, when set to `nil` using `define-key` caused `C-x` to behave unpredictably, if any reaction at all. ``` (remove-key cua--prefix-repeat-keymap (kbd "C-x")) (remove-key cua-global-keymap (kbd "<C-return>")) ``` The `C-x` declaration is successfully removed. Unfortunately, cua is somehow still affecting `C-return` is still a problem, but remove-key did remove the declaration as promised. Some interlinks can get complex. Using `remove-key` get rid of the declaration actually simplifies the situation. --- Tags: key-bindings ---
thread-64786
https://emacs.stackexchange.com/questions/64786
How to remove gray color in Dired mode?
2021-05-10T13:41:27.993
# Question Title: How to remove gray color in Dired mode? Linux Mint , Emacs 27.2 Dired, Dired+, Dired-k As a result here is the dired mode view As you can see, the names of files: * to.do.org * to.do.org\_archive\_2017 * to.do.org\_archive\_2019 are gray. Can I remove this gray color? # Answer Put your cursor on a char with that gray foreground, and use `C-u C-x =`. The `*Help*` tells you (near the bottom) what face(s) are used there. Then use `M-x customize-face` to customize the face(s) to be as you like. > 1 votes # Answer After set this: `(dired-k-human-readable t)` the gray color is gone ``` Use human readable size format option. ``` Nice. P.S. Here another settings: color depends on file size Here another settings: color depends on file date. > 0 votes --- Tags: dired, faces, customize-face ---
thread-64798
https://emacs.stackexchange.com/questions/64798
The Emacs eshell alias of CMake doesn't recognize path correctly?
2021-05-11T04:31:35.060
# Question Title: The Emacs eshell alias of CMake doesn't recognize path correctly? I'm using the Emacs eshell's alias feature to make an alias to the `cmake` command like below: ``` $ alias cmake 'cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=1' ``` The alias is created correctly, here is the output of running `which cmake` inside eshell: ``` $ which cmake cmake is an alias, defined as "cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=1" ``` However, when running this alias `cmake` inside my project, it doesn't recognize the input path correctly. For example, when running `cmake ..`, it seems unable to interpret the `..` path. Here are the detailed steps to produce this error: ``` $ cd my-project # the CMakeLists.txt is stored at the root folder of this project $ mkdir build $ cd build $ cmake .. # running the cmake alias CMake Warning: No source or binary directory provided. Both will be assumed to be the same as the current working directory, but note that this warning will become a fatal error in future CMake releases. CMake Error: The source directory "/home/trungtq/workspace/ocaml/discover/llvm-normalizer/build" does not appear to contain CMakeLists.txt. Specify --help for usage, or press the help button on the CMake GUI. ``` Does anyone know how to fix this problem? Thank you very much! # Answer You need to include the arguments in the Eshell alias as `$1`, `$2`, ... or as full list of provided arguments `$*`. See the documentation of Eshell `aliases`. In your special case you could use: ``` alias cmake 'cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=1 $*' ``` > 1 votes --- Tags: eshell, aliases ---
thread-38543
https://emacs.stackexchange.com/questions/38543
Cherry-pick columns to display in Dired or Dired+
2018-02-02T10:41:23.003
# Question Title: Cherry-pick columns to display in Dired or Dired+ I would like to customize the amount of detail displayed in Dired. Basically I would like to cherry-pick the "columns" to display. More precisely, I would like to hide the "owner group" information. So instead of this: ``` drwxrwxrwx 1 fgeorges Utilisa. du domaine 40960 01-28 20:16 bar -rw-rw-rw- 1 fgeorges Utilisa. du domaine 10574 01-29 08:31 file.txt -rw-rw-rw- 1 fgeorges Utilisa. du domaine 198331 01-29 08:31 file.xml drwxrwxrwx 1 fgeorges Utilisa. du domaine 40960 01-29 08:31 foo -rw-rw-rw- 1 fgeorges Utilisa. du domaine 10499 01-28 20:17 file.json ``` I would rather see this: ``` drwxrwxrwx 1 fgeorges 40960 01-28 20:16 bar -rw-rw-rw- 1 fgeorges 10574 01-29 08:31 file.txt -rw-rw-rw- 1 fgeorges 198331 01-29 08:31 file.xml drwxrwxrwx 1 fgeorges 40960 01-29 08:31 foo -rw-rw-rw- 1 fgeorges 10499 01-28 20:17 file.json ``` It would be OK to never generate it in the first place, or to be able to hide it, by configuration or using a command. I am aware of `dired-hide-details-mode`, but this is different. It presents everything or nothing. I would still like to have details, but just not some of them. I searched quite a lot, and found nothing, but I cannot believe it is not possible to configure which columns to display in Dired. BTW - I take solutions using Dired+ as well (I can consider any other extension, but would like to keep it to Dired or Dired+) # Answer You can configure the columns with `dired-listing-switches`. For GNU `ls`, the relevant switch is: ``` -G, --no-group in a long listing, don't print group names ``` Here is a snippet from my `.emacs` (macOS, with GNU `coreutils` installed): ``` ;; Show human-readable sizes, and group directories first. (when (eq system-type 'darwin) (setq dired-use-ls-dired t insert-directory-program "/usr/local/bin/gls" dired-listing-switches "-l --all --group-directories-first --human-readable --no-group")) ``` The result: > 0 votes # Answer (Got to this question, because it was a suggestion by stackexchange when I asked my own question related to this.) Weeeeell, just today I hacked something together to achieve that. It needs refactoring, it's barely tested, it's not complete (for instance, I plan to update the regex at the core whenever I run into something that breaks it, like Dired marks.) But if you're daring or willing to hack Elisp, this might be a starting point: ``` ;; In file: egoge-dired.el (defconst egoge-dired-regex (rx line-start ;; Dired mark (? (or ?C ?*)) ;; leading whitespace (* blank) ;; 1. directory, file, or link. (group (or ?d ?- ?l)) ;; 2. user permissions (group (or ?r ?-) (or ?w ?-) (or ?x ?- ?s)) ;; 3. group permission (group (or ?r ?-) (or ?w ?-) (or ?x ?- ?s)) ;; 4. other permissions (group (or ?r ?-) (or ?w ?-) (or ?x ?- ?s)) ;; whitespace ;; (+ blank) (+ blank) ;; 5. links (group (+ digit)) ;; whitespace blank ;; 6. owner (group (+ graphic)) ;; whitespace (+ blank) ;; 7. group (group (+ graphic)) ;; whitespace (+ blank) ;; 8. size (group (+ digit) (? (and (or ?\, ?\.) (+ digit))) (? (or ?K ?M ?G)) ) ;; whitespace (+ blank) ;; 9. date (default or long-iso (group (or (and (+ alpha) blank (+ digit)) (and (repeat 4 digit) ?- (repeat 2 digit) ?- (repeat 2 digit)))) ;; whitespace (+ blank) ;; 10. time (group (repeat 2 digit) ?: (repeat 2 digit)) )) (defface egoge-dired-face '((((class color) (background dark)) (:foreground "grey40" :height .8)) (((class color) (background light)) (:foreground "grey50"))) "Dim dired information") (defsubst egoge-dired-hide+dim-dir () (goto-char (point-min)) (let ((max-group-length 0) (max-size-length 0) group-pos-lst size-pos-lst) (while (not (eobp)) (when (looking-at egoge-dired-regex) (let ((s (match-beginning 1)) (e (match-end 10))) (put-text-property s e 'font-lock-face 'egoge-dired-face) (put-text-property s e 'help-echo (buffer-substring-no-properties s e))) ;; type + permissions (put-text-property (match-beginning 1) (1+ (match-end 4)) 'invisible 'egoge-dired-hide-permissions) ;; links (let ((type (match-string-no-properties 1)) (s (match-beginning 5)) (e (match-end 5))) (unless (string= type "d") (put-text-property s e 'display " ")) (put-text-property s (1+ e) 'invisible 'egoge-dired-hide-links)) ;; owner + group (put-text-property (match-beginning 6) (match-end 6) 'invisible 'egoge-dired-hide-owner+group) (push (match-beginning 7) group-pos-lst) (let ((len (- (match-end 7) (match-beginning 7)))) (and (> len max-group-length) (setq max-group-length len))) ;; (message "str: %s, len: %S" (match-string-no-properties 7) max-group-length) ;; size (let ((type (match-string-no-properties 1))) (unless (string= type "-") (let* ((s (match-beginning 8)) (e (match-end 8)) (len (- e s))) (push e size-pos-lst) (and (> len max-size-length) (setq max-size-length len)) ;; (put-text-property s e 'display (make-string (- e s) ?-)) ))) ;; time (put-text-property (match-beginning 10) (1+ (match-end 10)) 'invisible 'egoge-dired-hide-time)) (forward-line 1)) (dolist (p group-pos-lst) (put-text-property (1- p) (+ p max-group-length 1) 'invisible 'egoge-dired-hide-owner+group)) (dolist (p size-pos-lst) (put-text-property (- p max-size-length) p 'display (make-string max-size-length ?-))))) (defun egoge-dired-hide+dim () (let ((inhibit-read-only t) (inhibit-point-motion-hooks t)) (save-excursion (remove-text-properties (point-min) (point-max) '(display)) (goto-char (point-min)) (while (not (eobp)) (let ((s (point))) (or (search-forward "\n\n" nil t) (goto-char (point-max))) (save-restriction (narrow-to-region s (point)) (egoge-dired-hide+dim-dir) (goto-char (point-max)))))))) (defun egoge-dired-toggle-property (prop) (if (not (eq major-mode 'dired-mode)) (message "Not in Dired buffer") (if (memq prop buffer-invisibility-spec) (remove-from-invisibility-spec prop) (add-to-invisibility-spec prop)))) (defun egoge-dired-toggle-permissions () (interactive) (egoge-dired-toggle-property 'egoge-dired-hide-permissions)) (defun egoge-dired-toggle-owner+group () (interactive) (egoge-dired-toggle-property 'egoge-dired-hide-owner+group)) (defun egoge-dired-toggle-time () (interactive) (egoge-dired-toggle-property 'egoge-dired-hide-time)) (defun egoge-dired-toggle-links () (interactive) (egoge-dired-toggle-property 'egoge-dired-hide-links)) (defvar egoge-dired-visibility-properties '(egoge-dired-hide-permissions egoge-dired-hide-owner+group egoge-dired-hide-time egoge-dired-hide-links )) (defun egoge-dired-show-all () (interactive) (let ((inhibit-read-only t)) (remove-text-properties (point-min) (point-max) '(display))) (if (not (eq major-mode 'dired-mode)) (message "Not in Dired buffer") (dolist (p egoge-dired-visibility-properties) (remove-from-invisibility-spec p)))) (defun egoge-dired-hide-all () (interactive) (if (not (eq major-mode 'dired-mode)) (message "Not in Dired buffer") (dolist (p egoge-dired-visibility-properties) (add-to-invisibility-spec p)))) (provide 'egoge-dired) ;; In .emacs: (when (require 'egoge-dired nil t) (add-hook 'dired-after-readin-hook #'egoge-dired-hide+dim) (add-hook 'dired-mode-hook #'egoge-dired-hide-all)) ``` Or, if there's interest in this, I would be willing to update it whenever I fix something. Btw., is there still something like `gnu.emacs.sources` of the old days? > 2 votes --- Tags: dired, customization ---
thread-64800
https://emacs.stackexchange.com/questions/64800
Emacs not loading function on start-up
2021-05-11T07:39:14.093
# Question Title: Emacs not loading function on start-up I put the following in my .init file: ``` (defun ndk/org-refile-candidates () (directory-files "/home/rob/Dokumente/todo/" t ".*\\.org$")) (add-to-list 'org-refile-targets '(ndk/org-refile-candidates :maxlevel . 3)) ``` It does work when evaluating manually with `C-x` `C-e`, but not when I restart Emacs. I get the error: > Symbol's value as variable is void: org-refile-targets 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. Why isn't it setting the value of the variable like when I do it manually? Does it get overwritten by some default somehow? Can somebody point me into the right direction? # Answer This is because no variable `org-refile-targets` has yet been defined when that code in your init file is being evaluated. (Obviously you've loaded the relevant library by the time you attempt this manually.) It looks like `org-refile` is the library which defines this, so you can either forcibly load that before using the variable: ``` (require 'org-refile) (add-to-list 'org-refile-targets '(ndk/org-refile-candidates :maxlevel . 3)) ``` But I can see that's going to load much of `org` in turn, which is a bit of a performance hit at start-up, so I suggest this instead: ``` (with-eval-after-load 'org-refile (add-to-list 'org-refile-targets '(ndk/org-refile-candidates :maxlevel . 3))) ``` > 5 votes --- Tags: org-mode, init-file ---
thread-64806
https://emacs.stackexchange.com/questions/64806
Tasks with indefinite intervals in org-habit
2021-05-11T14:10:49.000
# Question Title: Tasks with indefinite intervals in org-habit I'm trying to figure out a way to keep track of habits that do not have a definite interval for repetitions. I created the following habit without a deadline and time interval because I don't know how often I'd like to repeat it, but I do want to keep track of how often I repeat it. ``` ** DONE do something CLOSED: [2021-05-11 Tue 16:01] :PROPERTIES: :STYLE: habit :LAST_REPEAT: [2021-05-11 Tue] :END: ``` The problem is that, as you can see, it's in the done state, and repetitions aren't logged. If there is a deadline, each repeat will be logged: ``` ** TODO do something DEADLINE: <2021-05-12 Wed .+1d> :PROPERTIES: :STYLE: habit :LAST_REPEAT: [2021-05-11 Tue 16:07] :END: - State "DONE" from "FEEDBACK" [2021-05-11 Tue 16:07] ``` Is there a way to log each time it enters into "DONE" without setting an interval? # Answer > 1 votes AFAIK, you cannot use org-habit without a repeater intervals in date. for logging DONE state (or other todo keywords) ``` (setq org-todo-keywords '((sequence "TODO" "|" "DONE(!)"))) ;mind the ! ``` for more: https://www.gnu.org/software/emacs/manual/html\_node/org/Tracking-TODO-state-changes.html --- Tags: org-mode, org-agenda, org-habit ---
thread-64795
https://emacs.stackexchange.com/questions/64795
Emacs -q error "Failed to initialize color list unarchiver"
2021-05-10T20:49:53.133
# Question Title: Emacs -q error "Failed to initialize color list unarchiver" When I run emacs -q I got the following error (on Mac OS) although emacs window still pops up. Any idea? ``` % /Applications/Emacs.app/Contents/MacOS/Emacs -q 2021-05-10 22:44:57.297 Emacs-x86_64-10_14[43625:9228583] Failed to initialize color list unarchiver: Error Domain=NSCocoaErrorDomain Code=4864 "*** -[NSKeyedUnarchiver _initForReadingFromData:error:throwLegacyExceptions:]: non-keyed archive cannot be decoded by NSKeyedUnarchiver" UserInfo={NSDebugDescription=*** -[NSKeyedUnarchiver _initForReadingFromData:error:throwLegacyExceptions:]: non-keyed archive cannot be decoded by NSKeyedUnarchiver} ``` # Answer **tl;dr** delete `~/Library/Colors/Emacs.clr`, your Emacs will recreate it at the next startup. This seems to have become a recurring issue for Emacs on macOS. See if the answers here help you: https://stackoverflow.com/questions/52521587/emacs-error-failed-to-initialize-color-list-unarchiver-when-i-call-it-in-the-t > 0 votes --- Tags: error ---
thread-64265
https://emacs.stackexchange.com/questions/64265
How do I make Evil's C-o work with Org's C-c C-o?
2021-04-02T13:59:18.817
# Question Title: How do I make Evil's C-o work with Org's C-c C-o? Org mode's `org-open-at-point` (`C-c C-o`) works great for internal links, e.g. ``` Stuff to buy: - <<food>> food: - tomato - potato - banana - <<drinks>> drinks: - juice - tea - coffee Maybe look for some more variation for [[food]]? ``` However, when I use `org-open-at-point` in `[[food]]`, Evil mode's `evil-jump-backward` (`C-o`) does not bring me back to my original position. Org mode itself tells me in the echo area to use `C-c &` (`org-mark-ring-goto`) instead, but I would like to use `evil-jump-backward` to remember only a single keybinding. Is it possible to use Evil's `C-o` also movements via `org-open-at-point`? # Answer Besides @Zeta‘s answer. a less intrusive way could be: ``` (evil-set-command-property 'org-open-at-point :jump t) ``` for how it works, just inspect `evil--jump-hook` which is in `pre-command-hook`. > 0 votes # Answer Sure. `evil-jump-backward` knows where to jump to via `evil-set-jump`. All we need to do is to call `evil-set-jump` before we jump in `org-open-at-point`. We need to advice the function for that: ``` (advice-add 'org-open-at-point :before 'evil-set-jump) ``` This makes sure that before `org-open-at-point` gets called, `evil-set-jump` gets called first, therefore saving the location. `C-o` will then work as intended. > 0 votes --- Tags: org-mode, evil ---
thread-61441
https://emacs.stackexchange.com/questions/61441
yas-new-snippet always duplicates the selected input. What might be causing it?
2020-10-27T08:08:57.280
# Question Title: yas-new-snippet always duplicates the selected input. What might be causing it? I've experienced this issue for some time. It's not a blocker but it is a bit annoying. **Steps to reproduce:** Select a region that you want to extract into YASnippet snippet("foo bar"). Eval `yas-new-snippet`. You are redirected to a new buffer +new-snippet+ with the following content: ``` # -*- mode: snippet -*- # name: # key: # -- // foo bar // foo bar ``` **Expected behavior:** ``` # -*- mode: snippet -*- # name: # key: # -- // foo bar ``` > pkg-info-package-version yasnippet 20200604.246 # Answer > 2 votes You have probably set `yas-wrap-around-region` to `t`, this will insert your region at the snippet placeholder `$0`. Calling `yas-new-snippet` will expand a snippet to create your new snippet: `yas-new-snippet-default`. If you look at the default value, it contains `$0` and `yas-selected-text`, and now both will be filled with your region. I suggested a fix in this PR: https://github.com/joaotavora/yasnippet/pull/1102 As a workaround, you could advice the function like this: ``` (defun yas-new-snippet-fix-region (func &rest args) (let ((yas-wrap-around-region nil)) (apply func args))) (advice-add 'yas-new-snippet :around #'yas-new-snippet-fix-region) ``` --- Tags: yasnippet ---
thread-64549
https://emacs.stackexchange.com/questions/64549
Suppress "Ignoring <ruby gem>" messages on emacs startup
2021-04-23T05:13:11.340
# Question Title: Suppress "Ignoring <ruby gem>" messages on emacs startup When I start emacs, I get a bunch of messages ``` Ignoring charlock_holmes-0.7.7 because its extensions are not built. Try: gem pristine charlock_holmes --version 0.7.7 Ignoring escape_utils-1.2.1 because its extensions are not built. Try: gem pristine escape_utils --version 1.2.1 Ignoring eventmachine-1.2.7 because its extensions are not built. Try: gem pristine eventmachine --version 1.2.7 Ignoring executable-hooks-1.6.1 because its extensions are not built. Try: gem pristine executable-hooks --version 1.6.1 Ignoring ffi-1.15.0 because its extensions are not built. Try: gem pristine ffi --version 1.15.0 Ignoring ffi-1.14.2 because its extensions are not built. Try: gem pristine ffi --version 1.14.2 Ignoring ffi-1.9.18 because its extensions are not built. Try: gem pristine ffi --version 1.9.18 Ignoring gem-wrappers-1.4.0 because its extensions are not built. Try: gem pristine gem-wrappers --version 1.4.0 Ignoring github-linguist-7.13.0 because its extensions are not built. Try: gem pristine github-linguist --version 7.13.0 Ignoring http_parser.rb-0.6.0 because its extensions are not built. Try: gem pristine http_parser.rb --version 0.6.0 Ignoring nokogiri-1.8.0 because its extensions are not built. Try: gem pristine nokogiri --version 1.8.0 Ignoring nokogumbo-2.0.5 because its extensions are not built. Try: gem pristine nokogumbo --version 2.0.5 Ignoring nokogumbo-2.0.4 because its extensions are not built. Try: gem pristine nokogumbo --version 2.0.4 Ignoring racc-1.5.2 because its extensions are not built. Try: gem pristine racc --version 1.5.2 Ignoring rugged-1.1.0 because its extensions are not built. Try: gem pristine rugged --version 1.1.0 Ignoring sassc-2.4.0 because its extensions are not built. Try: gem pristine sassc --version 2.4.0 2021-04-21 00:29:41.421 Emacs-x86_64-10_14[68954:1066860] Failed to initialize color list unarchiver: Error Domain=NSCocoaErrorDomain Code=4864 "*** -[NSKeyedUnarchiver _initForReadingFromData:error:throwLegacyExceptions:]: non-keyed archive cannot be decoded by NSKeyedUnarchiver" UserInfo={NSDebugDescription=*** -[NSKeyedUnarchiver _initForReadingFromData:error:throwLegacyExceptions:]: non-keyed archive cannot be decoded by NSKeyedUnarchiver} ``` How do I suppress these messages? I have tried doing what they ask (i.e., running `gem pristine charlock_holmes --version 0.7.7`), but nothing changes. Of course, fixing them instead of suppressing them would be good, but I'm not sure that's an Emacs issue. # Answer > 1 votes Sounds like you're using the https://emacsformacosx.com/ build of Emacs (installable directly or via `brew install homebrew/cask/emacs`.) Because of its nature as a macOS App bundle, it uses a wrapper to setup the pre-launch environment of Emacs. In this case, the wrapper is written in Ruby, and if you have any issues in your Ruby environment they'll show up. I'm not a Ruby person, but an easy test would be to comment out the `exec` call in the Ruby wrapper. Then run "emacs" again, and since we're not actually starting Emacs, if you get the same errors you'll know it's not Emacs's fault, and most likely an issue with your Ruby setup. Something like: ``` ❯ v /usr/local/bin/emacs lrwxr-xr-x 1 44 nega 11 May 13:44 /usr/local/bin/emacs -> /Applications/Emacs.app/Contents/MacOS/Emacs* ❯ file /Applications/Emacs.app/Contents/MacOS/Emacs /Applications/Emacs.app/Contents/MacOS/Emacs: Ruby script text, UTF-8 Unicode text ❯ vi /Applications/Emacs.app/Contents/MacOS/Emacs ## comment out the exec call and save and quit ## ❯ /usr/local/bin/emacs ## ruby errors here ## ``` If you're **not** using Emacs for OSX, but either the "regular" Emacs (`brew install emacs`, and symlinks directly to a Mach-O executable) or Aquamacs (an app bundle too, but with a Perl wrapper) and seeing Ruby errors, then something strange indeed is happening. --- Tags: init-file, message, warning, ruby ---
thread-58760
https://emacs.stackexchange.com/questions/58760
Using straight.el to develop your own package which is also on github
2020-05-27T19:07:17.200
# Question Title: Using straight.el to develop your own package which is also on github I am considering using `straight.el`, but reading the docs, I have difficulties to understand whether the particular use cases I am interested in are handled as I hope to. Here are the cases: 1. I have some packages of my own which are hosted on github. Currently, I have a local git repository, and I `git fetch` it to a directory within the `load-path`. So I basically hope that by using `straight.el`, I could reduce it to one directory, the local git repository. But what happens when I edit a file in this repository? As far as I understand, `straight.el` will detect the modified file and rebuild the package. But that would mean that I cannot properly develop the package because it will always affect my current setup. So how do we get around that? Would I need, say, spin off a `develop` branch and tell `straight.el` to use the `master` branch? I do not understand how `straight.el` would handle the case that the current branch is not the branch which should be used for compiling and packaging. 2. The second use case is actually very similar: I clone a github repo and want to edit it, possible to create a PR. Again, my question is: How do I prevent that my edit destroys my current setup, or that it is destroyed when the repo is fetched again from upstream? Maybe someone could help me to clarify this. If these use cases are not handled properly, I won't change to `straight.el`, I guess. # Answer > 1 votes I understand your concerns, but I'm not sure they're founded. Although I'm not a straight expert, I have been using it since at least November 2020. You're welcome to look at my init. My understanding is that packages are built automatically only on first install. Straight uses (mainly) git to clone a package into the `straight/repos` directory. There are functions `straight-pull-all`, `straight-pull-package`, and a few others which are used to do this. Builds can be manually triggered with `straight-rebuild-all` or `straight-rebuild-package`. If straight automatically pulled and built, why would these commands exist interactively? I maintain a few packages for personal use (here and here). Occasionally, I update and push them. I've always had to manually pull them when using another machine. This sounds precisely like your use case. I always try to fork whatever package I want to use. This has two consequences. First, it only matches upstream whenever I tell it to; I have to manually update the fork. That locks the system independently of straight. Second, it helps with PRs on Github since you need a fork to do that. This also sounds like one of your use cases. Finally, just try it out. It sounds like you only have concerns (which are valid). However, those concerns can be confirmed or diffused by trying the system out. Switching to straight was, well, straight forward for me. I just did one package at a time until I got the hang of it. It looks scary and the docs are intimidatingly thorough. Consider, though: there are docs and you control all the source code for all your packages. There is lots of useful information in the Github issues. The main point, however, is it's really as simple as backing up your current .emacs.d and trying straight out. If you don't like it, delete everything and return to your previous packaging system. That was my attitude and I never looked back. # Answer > 0 votes You could try using Chemacs to run emacs with different set-up profiles. You can have a profile that runs from a development branch if it's under version control or from a different emacs-user-directiory. --- Tags: package, package-development, github, straight.el ---
thread-64819
https://emacs.stackexchange.com/questions/64819
Why is slime working in emacs but not in the minimal set-up?
2021-05-12T15:09:46.543
# Question Title: Why is slime working in emacs but not in the minimal set-up? I am quite new to Emacs. Hence, I have been using the minimal set-up version. However, slime seems to work only on the full version. If I do on my Ubuntu 20.04 terminal the following: ``` emacs ``` And then, inside emacs: ``` M-x slime ``` I have slime working perfectly. However, if I use the minimal setup version with: ``` emacs -nw -Q ``` After typing M-x slime I get the following error version: ``` M-x slime (no match) ``` Is there something I could to run the Smile REPL inside emacs minimal set-up? # Answer > 2 votes Slime isn't part of the base Emacs install. You need to add it to your config. Usually this is done via `package-install-packages`, but you may have downloaded the code yourself. Regardless of how you installed slime, using it requires you load the appropriate configuration code. When you start emacs with `emacs -Q`, you are explicitly telling Emacs to ignore all your configuration, including the code that tells it to use slime. --- Tags: slime ---
thread-64823
https://emacs.stackexchange.com/questions/64823
How to launch 'term' with my default shell without a prompt to select the shell?
2021-05-13T00:42:33.787
# Question Title: How to launch 'term' with my default shell without a prompt to select the shell? I would like to launch `term` with my default shell, without being prompted every time for the path of the shell. How can I bind a key to `term` without being prompted for the shell to run? # Answer > 2 votes ``` (global-set-key (kbd "C-x t") (lambda () (interactive) (term shell-file-name))) ``` --- Tags: term ---
thread-64753
https://emacs.stackexchange.com/questions/64753
Is there a way to have in a org-mode file a placeholder for the current date automatically updated when saved?
2021-05-08T15:44:11.257
# Question Title: Is there a way to have in a org-mode file a placeholder for the current date automatically updated when saved? (I'm aware of "Creating timestamps", but my point is to automatically update such timestamps distributed in several places in the file.) I'd like to have in a `org-mode` file a kind of placeholder for the current date (at the `YYYY-MM-DD` format), which is automatically updated when the file is saved. Is it possible? ## Edit Here is the context of my question: I'm in the process of writing a LaTeX class using `org-babel` for the literate programming. In several places of the file `.org` file, I have to insert the release date of this class, at least in the exported `README.md` file like this: ``` Release ------- 2021-05-10 v1.0.0-alpha ``` and in the exported `.cls` source file of the class, like this: ``` \ProvidesExplPackage{my-nice-class} {2021-05-10} {v1.0.0-alpha} { Lorem ipsum dolor sit amet, consectetuer adipiscing elit. } ``` Because I'm likely to forget to update this date before the actual release, I'd like it to be automatically updated each time the `.org` file is saved. # Answer `time-stamp`, which comes with Emacs by default, will allow you to do exactly what you want with the appropriate settings. E.g. I have: ``` # Local Variables: # time-stamp-line-limit: 1000 # time-stamp-format: "[%Y-%m-%d %H:%M]" # time-stamp-active: t # time-stamp-start: "version = \"" # time-stamp-end: "\"" # End: ``` in some of my org files. After adding `time-stamp` to the `before-save-hook`: ``` (add-hook 'before-save-hook #'time-stamp) ``` and with the above settings, a template like this: ``` # version = "" ``` will be filled out like this: ``` # version = "[2021-05-15 11:34]" ``` > 2 votes # Answer I think there are better methods to keep track of the modification time of the file: e.g. `ls -l` on the directory will tell you exactly what you are asking: the time that the file was last modified. Even better, keep it under source control and then you'll know *every change*, as well as when that change was made. THe point is that the modification time is *metadata* and should be treated as such. If you put the timestamp in the file, then it's part of the data that the file stores. IMO, that's the wrong place for it. Be that as it may, if you still insist of keeping a time stamp in the file, you can use `before-save-hook` to run an arbitrary function just before the file is saved. The function can e.g. check that this is an Org mode file and replace every occurrence of some placeholder with the current time and date. What I'm implementing here is sort-of what the old RCS system did: it looked for lines of the form ``` $foo: bar$ ``` where `foo` is an RCS `keyword` and it would replace the RHS (the part after the colon with some calculated value. Initially, you could just say `$foo$` and RCS would expand the keyword with a value as above. Then the value would change, depending on what RCS calculated for it. So the idea here is to have a keyword `TS` in your Org mode file: ``` * foo $TS$ ``` and when the file gets saved, the keyword is expanded to: ``` * foo $TS: Sat May 8 19:26:46 2021$ ``` Here's the implementation: ``` (defvar ndk/ts-placeholder-re "$TS:?[^$]*\\$") (defun ndk/ts-placeholder-replace () (when (eq major-mode 'org-mode) (let ((ts (current-time-string))) (replace-regexp ndk/ts-placeholder-re (format "$TS: %s$" ts) nil (point-min) (point-max))))) (add-hook 'before-save-hook #'ndk/ts-placeholder-replace) ``` The regexp matches `$TS$` as well as the expanded form `$TS: Sat May 8 19:26:46 2021$`, so the keyword is expanded in either case. The function checks that this is an Org mode file (you can check for other modes or delete the check altogether, depending on your needs). It then looks for the regexp and replaces every occurrence with the result of calling the function `current-time-string`. You can replace that with a different function that returns a string of the timestamp in your preferred format. For example ``` (format-time-string "%Y-%m-%dT%H:%M:%S" (current-time)) => "2021-05-08T19:41:22" ``` See the doc string of `format-time-string` for the gory details: `C-h f format-time-string`. --- EDIT: A better answer to this question is given by @Tyler at https://emacs.stackexchange.com/a/64789/14825 > 1 votes --- Tags: org-mode, time-date ---
thread-57919
https://emacs.stackexchange.com/questions/57919
Preview images, and PDFs inside a SSH terminal session or inside emacsclient session via SSH?
2020-04-20T06:56:37.047
# Question Title: Preview images, and PDFs inside a SSH terminal session or inside emacsclient session via SSH? I work remotely to Linux servers, writing R scripts with `ESS`. Rstudio works well if I have a fast and stable GUI-based remote desktop connection to the server. Rstudio server also works OK if I have the server running and now problems with managing logins. However, these two choices are not available on the server. So, Emacs+ESS is a great choice for code editing experience. The catch is, I will have to download generated images and PDF to my local computer to see them. That is not a workflow I want to do every couple of minutes. Doing a SSHFS mount to local computer is a better, but is still not the workflow I want. The ideal workflow: 1. Write code in an `emacsclient` inside a `tmux` session 2. Run code to generate plots, or PDFs from Rmarkdown 3. Preview the files right afterward inside the emacsclient window, or in another tmux split, or Window. This threads discusses various options to view images in the terminal. There is pdf-tools package for emacs to preview PDF documents. So, I believe it is technically possible at the moment. But I don't use emacs so frequent these days so my reflex is a bit rusty. Some guidance/demo setup code will be really appreciated. # Answer If you run Emacs on your local machine, and open files on the remote machine via Tramp, you can view remote files as if they were on your local machine, you don't need to do anything special. ESS also uses Tramp to run an R process on your remote machine: My workflow is: 1. open emacs locally 2. edit file on remote machine, via `C-x C-f /ssh:remotehost:myRScript.R` 3. start a new R process (either directly via `M-x R`, or by running a line from my script via `C-c C-n` etc After this, you are editing in your local environment (with full graphical support), R is running on your remote machine, and Tramp manages the connection for you. If you generate a plot, e.g., ``` jpeg(file = "myplot.jpeg") plot(1:25) dev.off() ``` You can open it for viewing via `C-x C-f myplot.jpeg` from your script file. If you use org mode, this is even easier: you specify the output file for each code block, and org will insert a link to that file after you run the code. Click the link, and the file (on your remote machine) opens in your local Emacs. > 2 votes --- Tags: ess, images, remote, previewing ---
thread-64755
https://emacs.stackexchange.com/questions/64755
Does zetteldeft miss some org-roam functionality?
2021-05-08T18:58:20.363
# Question Title: Does zetteldeft miss some org-roam functionality? Has somebody used both packages and could tell me whether zetteldeft misses some functionality of org-roam? Thanks! # Answer First off: I’m the author of Zetteldeft. And second: I don’t think this is a question of the ‘factual’ type that can be adequately answered in the StackExchange format. That said: Zetteldeft and Org-roam are two completely different packages, with different aims and philosophies. Zetteldeft is rather minimalist and relies on Deft. It supports and facilitates linking between notes but doesn’t do much to automate such tasks But to answer your y-or-n question: yes, Zetteldeft lacks a lot of Org-roam functionality > 5 votes --- Tags: org-roam ---
thread-64792
https://emacs.stackexchange.com/questions/64792
Where should I find init.el, if it is not in .emacs.d?
2021-05-10T17:14:14.670
# Question Title: Where should I find init.el, if it is not in .emacs.d? I do not find init.el in .emacs.d. Where should I put my configuration? ``` % ls -a .emacs.d . .session auto-save-list recentf .. .uptimes.el org-clock-save.el var ``` # Answer > 4 votes From the manual (emacs) Find Init: > Emacs looks for your init file using the filenames ‘~/.emacs.el’, ‘~/.emacs’, or ‘~/.emacs.d/init.el’ in that order; you can choose to use any one of these names. (Note that only the locations directly in your home directory have a leading dot in the location’s basename.) There are a few other, less common, possibilities. See the manual for more details. If you don't have an init file in any of these locations, you need to create one. Since you already have an `.emacs.d` directory, it's probably most convenient to create a new file `.emacs.d/init.el`. `init.el` is just a plain text file with elisp code in it. There's nothing special needed to create it, just start saving your config code in a file with that name and you're ready to go. # Answer > 1 votes If you want to find where the init file for an existing Emacs is located, from within Emacs itself, you can look at the value of the `user-init-file` variable with `C-h v user-init-file RET`. This will open a buffer showing the value of the variable. If it is `nil` then no init file is used. Otherwise it will show the path to the currently used init file. --- Tags: init-file ---
thread-64836
https://emacs.stackexchange.com/questions/64836
Running elpy-test on a file opened over ssh via tramp
2021-05-13T20:13:06.033
# Question Title: Running elpy-test on a file opened over ssh via tramp I'm trying to run elpy's `C-c C-t` to do `elpy-test` on a python `test_x.py` file I have opened on a remote machine with TRAMP. Some parameters: * There is a python virtual env in the (remote machine's) directory, `~/myproject/env/default/` * I want to run the tests relative to the (remote machine's) project root `~/myproject/` * The PYTHONPATH is set to the root directory, which is `~/myproject/` Locally, I run `C-c C-t` and this works like so: ``` -*- mode: compilation; default-directory: "~/myproject/test/integration/data/mymod/" -*- Compilation started at Thu May 13 13:56:38 py.test --log-level\=DEBUG /home/user/myproject/test/integration/data/mymod/mod2/test_x.py\:\:test_y ================================================================================ test session starts ================================================================================= platform linux -- Python 3.7.3, pytest-5.4.3, py-1.10.0, pluggy-0.13.1 -- /env/default/bin/python cachedir: .pytest_cache rootdir: /home/user/myproject, inifile: pytest.ini plugins: asyncio-0.14.0, flask-1.1.0, forked-1.2.0, xdist-1.33.0, requests-mock-1.8.0, typeguard-2.7.0 collected 1 item mod2/test_x.py::test_y SKIPPED [100%] ============================================================================= slowest 10 test durations ============================================================================== 0.00s setup test/integration/data/mymod/mod2/test_x.py::test_y 0.00s teardown test/integration/data/mymod/mod2/test_x.py::test_y ================================================================================= 1 skipped in 2.05s ================================================================================= Compilation finished at Thu May 13 13:56:41 ``` This looks good. This is exactly what I want to see. However, when I remotely open the same file, and expect it to run on the remote machine via TRAMP, picking up the remote environment: ``` -*- mode: compilation; default-directory: #("/ssh:remote:/home/user/myproject/test/integration/data/mymod/" 1 4 (helm-ff-file t) 5 13 (helm-ff-file t)) -*- Compilation started at Thu May 13 14:00:37 py.test --log-level\=DEBUG /ssh\:remote\:/home/user/myproject/test/integration/data/mymod/mod2/test_x.py\:\:test_y /bin/sh: 2: py.test: not found Compilation exited abnormally with code 127 at Thu May 13 14:00:37 ``` Some things I notice: * The default directory looks mostly correct AFAICT, but I'm not sure what the `#()` is doing. * It's not clear to me why py.test is not found. * I don't see elpy listing any of that other stuff, like cachedir or platform---is it not configured at all? * Is there a variable I need to set either within emacs, orperhaps an environment variable, etc., so that when executed remotely, I can pick up the local environments? Additionally, I have a `.dir-locals.el` in the root where I can set these as needed, if they are location-specific. What can I change so I can run my tests with elpy over a tramp ssh session successfully? # Answer > 1 votes I have no knowledge about elpy and the like. However, some observations: * py.test is not found because its location is not mentioned in the remote $PATH * The call of py.test comes with a remote file name `/ssh\:remote\:/home/...`. This looks wrong. I recommend to contact the author(s) of elpy whether it is prepared for remote activation. --- Tags: python, tramp, elpy, virtualenv ---
thread-64805
https://emacs.stackexchange.com/questions/64805
How to disable org-mode 9.4.4 from indenting
2021-05-11T12:16:18.783
# Question Title: How to disable org-mode 9.4.4 from indenting After upgrading to org-mode 9.4.4 when I create a simple org file with a list (though it could be a heading) like below: ``` - test ``` And hit return, then it automatically indents. This doesn't make any sense because there is no hierarchy. How can I disable this? # Answer > 1 votes Set the variable `org-adapt-indentation` to `nil` by running the command `M-x set-variable`. # Answer > 0 votes ### Why it does make sense: plain list entry doesn't limit to single line. Below is legit list. ``` - In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document or a typeface without relying on meaningful content. ``` ### How can I disable this? Usually `C-j` and `RET`(or `C-m`) behave differently, one does indentation and the other doesn't. You may check it up and consider exchanging its bindings. (In my emacs RET bind to `org-return` and it doesn't indent by default) --- Tags: org-mode ---
thread-64623
https://emacs.stackexchange.com/questions/64623
How to change #+begin_comment .... #+end_comment background and text color?
2021-04-29T05:36:58.127
# Question Title: How to change #+begin_comment .... #+end_comment background and text color? When I have this code: ``` #+begin_comment So this is my comment's body text. I want it to have these features: 1. text color will be yellow 2. background color will be blue 3. text will be cursive #+end_comment ``` How to do that? What code should I put in my .spacemacs config file? # Answer > 1 votes This is from my `.emacs`: `'(org-meta-line ((t (:background "#0f0f0f" :foreground "azure4" :box (:line-width 1 :color "#0f0f0f")))))` To do the same for you, set the face: `org-meta-line`. --- Tags: spacemacs, font-lock, syntax-highlighting ---
thread-64851
https://emacs.stackexchange.com/questions/64851
Why is company mode not working with company-tng?
2021-05-14T22:16:27.933
# Question Title: Why is company mode not working with company-tng? I've got a setup like the following in my `init.el` ``` (use-package company :ensure t :after lsp-mode :hook (after-init . global-company) :bind (:map company-active-map ("<tab>" . company-complete-selection)) (:map lsp-mode-map ("<tab>" . company-indent-or-complete-common)) :custom (company-minimum-prefix-length 1) (company-idle-delay 0.0)) (use-package company-box :after company-mode :hook (company-mode . company-box-mode)) ``` However, I keep seeing the error `failed to define Autoloading file /Users/nland/.emacs.d/straight/build/company/company-tng.el failed to define function company-tng-mode` I have no idea why this is happening. I've looked in `company-tng.el` and there is no function `company-tng-mode` and I'm kind of lost now. # Answer > 0 votes Ok, so I clearly jumped the gun on asking this question, I've figured out the issue. The issue was that I was using an out-of-date version of `company`, I think the issue was more with `straight.el` than `company`, but after an update, I'm back in business. --- Tags: company-mode ---
thread-64853
https://emacs.stackexchange.com/questions/64853
Auto-load Ivy.elc failed to define swiper
2021-05-15T00:52:59.527
# Question Title: Auto-load Ivy.elc failed to define swiper I get the followingerror message: > command-execute: Autoloading file /home/user/.emacs.d/elpa/ivy-20210506.2157/ivy.elc failed to define function swiper after just having installed emacs 27.2 and having this init.el: ``` ;General Configuration (setq inhibit-startup-message t) (scroll-bar-mode -1) (tool-bar-mode -1) (tooltip-mode -1) (set-fringe-mode 10) ;was macht das? (menu-bar-mode -1) ;;Set up the visible bell (setq visible-bell t) (load-theme 'wombat) ;; Make ESC quit prompts (global-set-key (kbd "<escape>") 'keyboard-escape-quit) ;; Initialize package sources (require 'package) (setq package-archives '(("melpa". "https://melpa.org/packages/") ("org" . "https://orgmode.org/elpa/") ("elpa" . "https://elpa.gnu.org/packages/"))) (package-initialize) (unless package-archive-contents (package-refresh-contents)) ;; Initialize use-package on non-Linux platforms (unless (package-installed-p 'use-package) (package-install 'use-package)) (require 'use-package) (setq use-package-always-ensure t) (use-package command-log-mode) (use-package ivy :diminish :bind (("C-s" . swiper) :map ivy-minibuffer-map ("TAB" . ivy-alt-done) ("C-l" . ivy-alt-done) ("C-j" . ivy-next-line) ("C-k" . ivy-previous-line) :map ivy-switch-buffer-map ("C-k" . ivy-previous-line) ("C-l" . ivy-done) ("C-d" . ivy-switch-buffer-kill) :map ivy-reverse-i-search-map ("C-k" . ivy-previous-line) ("C-d" . ivy-reverse-i-search-kill)) :config (ivy-mode 1)) ``` I have only one ivy folder in my load path. Does anybody have an idea? # Answer > 1 votes I found my answer here: https://www.reddit.com/r/emacs/comments/90hiew/swiper\_disappeared/ Depending on whether ivy got installed from ELPA or MELPA it might be included or not. https://www.reddit.com/r/emacs/comments/90hiew/swiper\_disappeared/ adding: > (use-package swiper :ensure t) solved the issue. --- Tags: ivy ---
thread-64825
https://emacs.stackexchange.com/questions/64825
How to make 'term' close the buffer when the process exits?
2021-05-13T01:25:06.610
# Question Title: How to make 'term' close the buffer when the process exits? When I press Ctrl-D in a 'term', the buffer stays open with the text "Process terminal finished". How can I make this buffer close instead of staying open with this text displayed? --- Note, this is similar to this question: How to automatically kill a shell buffer when the shell process exits however the solution there didn't work for 'term'. # Answer > 2 votes Add your `(kill-buffer (current-buffer))` to the tail end of `term-handle-exit`, either with an advice or just create a new function by the same name (ensuring that the library containing said function gets loaded before redefining it). To see what triggers it, have a look at `term-sentinel`. To verify it's the right place, just put in a few messages and see what happens when you type `C-d` in the term buffer. ``` (defun my-term-handle-exit (&optional process-name msg) (message "%s | %s" process-name msg) (kill-buffer (current-buffer))) (advice-add 'term-handle-exit :after 'my-term-handle-exit) ``` --- Tags: term ---
thread-64858
https://emacs.stackexchange.com/questions/64858
Why does vdiff not show differences between these two files?
2021-05-15T09:38:28.840
# Question Title: Why does vdiff not show differences between these two files? Linux Mint 20, Emacs 27.2, vdiff -20210426.155 I create two files and want to find the difference between them. ``` M-x vdiff-files ``` Select file1.txt and file2.txt Here is the result: As you can see both files have different content (last character in every row). Why does **vdiff** not show this difference? # Answer Mine works just fine, though I've recently installed it from melpa and it's marked as version "0.2.4" maybe try upgrading your package, remove your modifications, or make sure that `M-x vdiff-send-changes` works as expected. Here's my screen capture. > 3 votes --- Tags: diff ---
thread-64807
https://emacs.stackexchange.com/questions/64807
Address autocompletion doesn't work after compiling `elc` files for `mu4e`
2021-05-11T14:38:44.880
# Question Title: Address autocompletion doesn't work after compiling `elc` files for `mu4e` After compiling `elc` files for `mu4e` in `/usr/local/share/emacs/site-lisp/mu4e` (Ubuntu 20.04) with ``` sudo emacs -Q -batch -L . -f batch-native-compile *.el ``` I get this error when writing an address of the `To:` field ``` Company: backend company-capf error "Symbol’s function definition is void: start" with args (prefix) ``` Prior to `elc` compiling `mu4e` everything worked alright. So I guess some bits of the config are out of sync now. Grateful for any tips. (Note that in `mu4e` address auto-completion is enabled by default, i.e., `mu4e-compose-complete-addresses` is set to true) I'm using mu4e 1.5.11 on Emacs 28.0.50 with native compilation. # Answer > 0 votes Issue solved when I build Emacs from the branch mentioned here: https://github.com/ch11ng/exwm/issues/835#issuecomment-841524743 --- Tags: mu4e, auto-complete-mode, compilation ---
thread-64863
https://emacs.stackexchange.com/questions/64863
Trying to edit/save file with root privilege fails with "Copying directly failed, see buffer '*tramp/sudo root @HOST*'
2021-05-15T14:53:44.157
# Question Title: Trying to edit/save file with root privilege fails with "Copying directly failed, see buffer '*tramp/sudo root @HOST*' I have done this a ton of times in the past 10 months or so that I have been using Emacs (which I have quickly come to love, by the way) and never had a problem. No clue what I changed or how, but now this does not work at all. As far as I know, I didn't change anything. Haven't edited my init.el or similar, haven't changed any configurations on my host machine. No clue what's going on here. I have the below in my init.el to open dired and then opening files from there to edit when I need to edit with privileges. (require 'tramp) (defun sudired () (interactive) (dired "/sudo::/")) That has served me well for months. Now, I open dired and open a file (say /boot/config.txt), do my edits, C-x C-s, and I get the message "Copying directly failed, see buffer '*tramp/sudo root@HOST*' for details." There buffer it mentions is empty. My messages buffer has this: Saving file /sudo:root@HOST:/boot/config.txt... Renaming /sudo:root@HOST:/boot/config.txt to /sudo:root@HOST:/boot/config.txt~...done Copying /tmp/tramp.eqRQkH.txt to /sudo:root@HOST:/boot/config.txt... Copying directly failed, see buffer ‘*tramp/sudo root@HOST*’ for details. I've searched around and found similar problems involving Tramp... Nothing that helps my issue though. At least not that I can work out. Same thing happens when I try to use C-x C-f and type out /sudo:root@HOST:/boot/config.txt, do my edits, and then C-x C-s. I get those same error messages, etc. Probably making a noob mistake here. Someone school me please. # Answer Hard to say what's up. Please contact the Tramp tower via email to `tramp-devel@gnu.org`. Prepare traces with level 6 and send them with, the Tramp manual teaches you how to do this. > -1 votes --- Tags: tramp, sudo, root ---
thread-12212
https://emacs.stackexchange.com/questions/12212
How to type the password of a .gpg file only when opening it
2015-05-07T10:01:44.787
# Question Title: How to type the password of a .gpg file only when opening it <sub>*(I understand the security implications of the following, and I'm fine with them.)*</sub> I have a single encrypted file in my org directory, `diary.org.gpg`. I never did any special configuration for it to work, still 1. Whenever I visit the file, I'm prompted for the encryption password. Which is great. 2. Whenever I save the buffer, I'm prompted for the password again twice. *Which is my problem*. *Note that I haven't configured anything for this to work, so any answers regarding agents or keyrings will have to come with configuration instructions.* I thought of keeping the password written somewhere inside the file (at the header or end-of-file comments). Then, whenever I save, Emacs could read the password in the buffer and use that instead of prompting me. But when I started looking into this, I got completely lost somewhere inside `epa.el`. **Q:** How can I send a password directly from Emacs to the encryption system/process when saving the buffer, instead of being prompted for it? All the rest (finding the password in the buffer) I can figure out myself. I just got lost when trying to understand how Emacs interfaced with gpg. *Note that I'm on Ubuntu, Arch Linux, and Windows. Which is why my first idea was an emacs-centric solution.<br>I can live with a solution that doesn't work on Windows, as long as I can still access the file on it in the manual way.* # Answer > 19 votes ## Encryption using password + key This does not save the password directly in the file but does something similar without any security risk and helps you achieve what you want. * You need to use asymmetric encryption so that your password is associated with an email ID in a *keyring*. * Save the below at the top of your .gpg file ``` -*- epa-file-encrypt-to: ("your@email.address") -*- ``` The password is prompted the very first time the file is saved/created. But after that the password is prompted only once each time you open the saved file ***The only catch is that you must not lose the keyring file which is saved in `~/.gnupg/` by default.*** ## GPG Setup ### Emacs Setup No setup is needed to be done for this in emacs. ### System Setup But you do need to have your system environment ready with few libraries for the GPG feature to work. At the time of setting this up, I had to install the following: * gpgme-1.5.3 * libgpg-error-1.17 * libksba-1.3.2 * libassuan-2.2.0 * libgcrypt-1.6.2 * gnupg-2.0.26 * pinentry-0.9.0 I needed one or two of the above libraries and I ended up installing the others because they were either mandatory or optional dependencies. Once everything is installed, do ``` > gpg --gen-key ``` And generate a *never-expiring* key for yourself and associate it with your real name and email. The generated key will be saved in your `~/.gnupg/` directory. **Changing the keyring location** You can change the location of keyring by either changing `$GNUPGHOME`, using `--homedir` or `--keyring` options for `gpg`. From `man gpg`: > `--keyring file` > > Add file to the current list of keyrings. If file begins with a tilde and a slash, these are replaced by the $HOME directory. If the filename does not contain a slash, it is assumed to be in the GnuPG home directory ("~/.gnupg" if --homedir or $GNUPGHOME is not used). > > Note that this adds a keyring to the current list. If the intent is to use the specified keyring alone, use --keyring along with --no-default-keyring. ### Using GPG with emacs In emacs, you simply create a file with a `.gpg` extension. For example, if the file was originally `auth.el`, you would rename it to `auth.el.gpg`. Place this line at the top of the file: ``` ;; -*- epa-file-encrypt-to: ("your@email.address") -*- ``` *Note that I have used the elisp comment chars `;;` as the example file here is `auth.el.gpg`.* Use the exact email address you used at the time of key generation. When you try to save it, emacs will show this prompt in a buffer: ``` Select recipients for encryption. If no one is selected, symmetric encryption will be performed. - `m' to mark a key on the line - `u' to unmark a key on the line [Cancel][OK] u <GPG KEY> <YOUR NAME> (<YOUR GPG KEY NAME>) <<YOUR GPG KEY EMAIL>> ``` Navigate the point to the line containing the key, hit `m`. Navigate the point to the `[OK]` button and hit `<return>`. You can now save the file and kill that file buffer. Next time when you open that .gpg file, you will be prompted for the password only once and then consecutive saves will be password-prompt-free. ## More info # Answer > 16 votes Turns out all I had to do was ``` (setq epa-file-cache-passphrase-for-symmetric-encryption t) ``` This solution works on both Linux and Windows, and is a courtesy of Ted and Michael over at help-gnu-emacs. # Answer > 0 votes A more convenient way to encrypt files with key is to store encryption target in emacs directory local variable, so it applies to all org files in the directory cat .dir-locals.el ``` ((org-mode . ((epa-file-encrypt-to . <your-email>)))) ``` --- Tags: encryption, epa, gpg ---
thread-64845
https://emacs.stackexchange.com/questions/64845
How to hide the *Org Links* buffer when insert org links
2021-05-14T11:59:57.777
# Question Title: How to hide the *Org Links* buffer when insert org links When insert org links with org-insert-link, an *Org Links* buffer is created. How can I hide it? --- # Answer After investigating the definition of the command (pressing `M-. org-insert-link`), I modified the body by commenting these lines out ``` ;; (org-switch-to-buffer-other-window "*Org Links*") ;; (with-current-buffer "*Org Links*" ;; (erase-buffer) ;; (insert "Insert a link. ;; Use TAB to complete link prefixes, then RET for type-specific completion support\n") ;; (when org-stored-links ;; (insert "\nStored links are available with <up>/<down> or M-p/n \ ;; \(most recent with RET):\n\n") ;; (insert (mapconcat #'org-link--prettify ;; (reverse org-stored-links) ;; "\n"))) ;; (goto-char (point-min))) ;; (let ((cw (selected-window))) ;; (select-window (get-buffer-window "*Org Links*" 'visible)) ;; (with-current-buffer "*Org Links*" (setq truncate-lines t)) ;; (unless (pos-visible-in-window-p (point-max)) ;; (org-fit-window-to-buffer)) ;; (and (window-live-p cw) (select-window cw))) ``` and it seems to be working fine without displaying *Org Links* buffer, though you may have to test this for a while. It's tedious to do this every time org receives an update. Try redefining the function without the mentioned lines if it works for you. > 0 votes --- Tags: org-mode ---
thread-64860
https://emacs.stackexchange.com/questions/64860
How to delete a single column cell in an org-mode table?
2021-05-15T11:09:58.233
# Question Title: How to delete a single column cell in an org-mode table? In Excel etc it is possible to delete a cell in a column and have the cells below it "shift up" without affecting the content of the other columns. I haven't found a command for this in `org-mode`, is there one? Example: In the following table I want to delete the cell `Banana`. ``` | Cars | Fruits | |-------+--------| | Volvo | Apple | | Saab | Banana | | Ford | Pear | ``` This should be the result: ``` | Cars | Fruits | |-------+--------| | Volvo | Apple | | Saab | Pear | | Ford | | ``` Now ideally if I were to additionally delete `Volvo` the table would look like this: ``` | Cars | Fruits | |------+--------| | Saab | Apple | | Ford | Pear | ``` # Answer Here's a function I wrote, ``` (defun org-table-collapse-cell () (interactive) (save-excursion ;; Save point (org-table-blank-field) ;; Blank the cell (while (progn ;; Swap blank cell with a cell under it until the blank is at the bottom. (org-table--move-cell 'down) (org-table-align) (org-table-check-inside-data-field)))) (org-table-next-field)) ``` It's very rough and calling it on `Volvo` and `Banana` yields ``` | Cars | Fruits | |------+--------| | Saab | Apple | | Ford | Pear | | | | ``` Which, I think should be enough you can delete the empty row yourself. > 2 votes --- Tags: org-mode, org-table ---
thread-55408
https://emacs.stackexchange.com/questions/55408
Emacs crash because of special utf-8 character
2020-02-10T16:09:00.190
# Question Title: Emacs crash because of special utf-8 character I am trying to open a file that contains the following utf-8 character: ⛺ Unfortunately, my emacs does really not appreciate, and immediately crashes. I have tried to comment out all my `init.el` (and actually I've even renamed my `.emacs_d` folder to be sure that my local packages/functions have nothing to do with it). The crash still occurs (it just closes the editor when attempting to open the file). Any idea of what the problem might be/how to fix this ? Using emacs 25.2.2 on Ubuntu 18.04. Edit: here is the terminal output when running `emacs -Q --debug-init`. No message on startup. When trying to paste ⛺ in the scratch buffer: ``` X protocol error: BadLength (poly request too large or internal Xlib length error) on protocol request 139 When compiled with GTK, Emacs cannot recover from X disconnects. This is a GTK bug: https://bugzilla.gnome.org/show_bug.cgi?id=85715 For details, see etc/PROBLEMS. Fatal error 6: Aborted ... // long backtrace ending with a core dump ``` # Answer > 3 votes I see the same crash. Quoting the likely-looking answer from @rpluim: > This is the infamous Xft + emoji bug. Either upgrade to emacs-27, or to an emacs-26 build compiled with Cairo support. – rpluim As discussed at #30045 - Emoji causing Emacs (GTK+3 backend) to crash - GNU bug report logs and Modifying Frontsets, a quick workaround is to disable the problematic font for colored emoji via M-: > (add-to-list 'face-ignored-fonts "Noto Color Emoji") --- Tags: utf-8, crash ---
thread-64861
https://emacs.stackexchange.com/questions/64861
Can't use helm `find-file` action with key binding
2021-05-15T14:25:35.433
# Question Title: Can't use helm `find-file` action with key binding I have the following code that I found here (note that the buffer version works fine): ``` (use-package helm) (use-package ace-window) (defun helm-find-ace-window (file) "Use ‘ace-window' to select a window to display FILE." (ace-select-window) (find-file file)) (add-to-list 'helm-find-files-actions '("Find File in Ace window" . helm-find-ace-window) :append) (defun helm-file-run-ace-window () (interactive) (with-helm-alive-p (helm-exit-and-execute-action 'helm-file-ace-window))) (define-key helm-find-files-map (kbd "M-o") #'helm-file-run-ace-window) ``` If I run `helm-find-files` and then hit TAB on a file (to open the action menu), I am able to scroll down to an entry called `Find File in Ace window` and hit enter. This works perfect. Strangely though if instead of hitting TAB I use my `M-o` key binding, emacs spits back to me: `[No such action 'helm-file-ace-window' for this source]`. I find it contradictory that I can select the action from the action menu, yet when I use a key binding emacs says the action does not exist. I am using Emacs 27.2 and Helm 3.6.2 # Answer > 1 votes Change `helm-file-ace-window` to `helm-find-ace-window`. --- Tags: key-bindings, helm ---
thread-26122
https://emacs.stackexchange.com/questions/26122
How do I make emacs find `ac-source-pycomplete`?
2016-08-07T11:04:45.203
# Question Title: How do I make emacs find `ac-source-pycomplete`? I followed Jessica Hamrick's emacs setup before adding `evil`. This means that there is a lot of specific configuration issues in my `~/.emacs.d/` which I don't necessarily understand, shame on me, but specifically I have checked that both `python-mode` and `auto-complete` were installed using `el-get`, and yet the `python-mode-hook` complains that it does not know about `ac-source-pycomplete`: ``` auto-complete error: (void-variable ac-source-pycomplete) ``` The symbol is explicitly added (with other symbols) to `ac-sources` as part of `'python-mode-hook`, because `pycomplete` thinks it's clever enough for all auto-completion tasks and removes all other sources from the `ac-sources`. ``` (add-hook 'python-mode-hook (lambda () (setq ac-sources '(ac-source-pycomplete ac-source-yasnippet ac-source-abbrev ac-source-dictionary ac-source-words-in-same-mode-buffers)))) ``` How do I get Emacs to know `pycomplete` in a clean-ish way? # Answer When `python-mode-hook` is run (when `python-mode` is enabled) `ac-source-pycomplete` has not yet been defined, which indicates that the library where `ac-source-pycomplete` is defined has not yet been loaded. Find out what that library is and ensure that you load it (e.g. using `require`) before you enable `python-mode`. > 0 votes # Answer It works for me just by commenting out variable `ac-source-pycomplete` in `auto-complete-setting.el` while leaving everything intact. Then, Jedi mode takes care of AC in ``` ; hack to fix ac-sources after pycomplete.el breaks it (add-hook 'python-mode-hook '(lambda () (setq ac-sources '(;; ac-source-pycomplete ac-source-yasnippet ac-source-abbrev ac-source-dictionary ac-source-words-in-same-mode-buffers)))) ``` > 0 votes --- Tags: python, auto-complete-mode ---
thread-64879
https://emacs.stackexchange.com/questions/64879
How to check if point moved or is on a different line in a buffer since the last user command?
2021-05-17T09:17:30.677
# Question Title: How to check if point moved or is on a different line in a buffer since the last user command? I would like to make a snippet of code that only executes if the point is on a different line in a particular buffer since the last user command. The only way I could think to do it was using the post-command-hook: ``` (setq my-prev-line 0) (defun my-install-move-hook (buf) (with-current-buffer buf (add-hook 'post-command-hook 'my-move-hook nil t))) (defun my-move-hook () (when (and my-prev-line (= my-prev-line (line-number-at-pos))) (message "The point moved from line number %d to %d" my-prev-line (line-number-at-pos)) (setq my-prev-line (line-number-at-pos)))) ``` That seems like overkill, since `post-command-hook` triggers after **every** command, not just user-invoked commands. Would it be better if the line number was stored during `pre-command-hook`? # Answer > 2 votes You say: *"post-command-hook triggers after every command, not just user-invoked commands."* And in comments you say that by "user-invoked" you really mean invoked *interactively*. It's not true that `post-command-hook` triggers each time a function that is a command is invoked. It's triggered for such a function only when it is invoked interactively: ``` (defun foo () (interactive) (message "THIS: %s, FOO" this-command) (bar)) (defun bar () (interactive) (message "THIS: %s, BAR" this-command)) (defun toto () (message "TOTO, THIS: %s" this-command) (when (equal this-command 'foo) (message "TOTO, FOO was invoked"))) (add-hook 'post-command-hook 'toto) ``` This is what `*Messages*` shows, when you evaluate `(foo)`, that is, you do *not* invoke `foo` interactively (i.e., as a command): ``` THIS: eval-last-sexp, FOO THIS: eval-last-sexp, BAR "THIS: eval-last-sexp, BAR" TOTO, THIS: eval-last-sexp ``` And this is what `*Messages*` shows when you do `M-x foo`, that is, you invoke `foo` interactively (i.e., as a command): ``` TOTO, THIS: execute-extended-command TOTO, THIS: self-insert-command [3 times] THIS: foo, FOO THIS: foo, BAR TOTO, THIS: foo TOTO, FOO was invoked ``` You can put conditional code in your hook function, to do whatever you want when `foo` is invoked *as a command*. That's what the test `(equal this-command 'foo)` does above. You can see that `toto` prints `TOTO, FOO was invoked` only when `foo` is invoked as a command (e.g. `M-x`). --- Alternatively, depending on what you really want, use function `called-interactively`, to test whether `foo` has been invoked *as a command*. --- Tags: hooks, commands, point, line-numbers ---
thread-58960
https://emacs.stackexchange.com/questions/58960
Re-fill compilation-mode buffer from shell script
2020-06-07T19:06:10.710
# Question Title: Re-fill compilation-mode buffer from shell script This might require more tricks than just Emacs-fu, but since Emacs is at the heart of it I hope to get some ideas on how to approach my need here. I use Emacs/Make/gcc as my development environment. I have a script that watches my source files so that whenever a change is saved it rebuilds, run all tests and updates coverage (thanks cov-mode). I'm normally running this in a separate terminal window so any compilation errors will show up there, when what I really want is for those errors to end up in a compilation-mode-type buffer in Emacs so I can go to `next-error` with one key-stroke. Here are my attempts so far: * run script in a `term-window` \- failed to get `next-error` to work * run script in a `shell-window`\- same problem * run script and collect output in a file which is visited in a buffer - couldn't get that window to auto-update (can I?) I also want to ensure that `next-error` is from the last "round", but since the buffer is not cleared on a ^L/`clear`-command you would have to step through all the errors unknowing when you are actually on a current one. Update: I have been exploring writing the output from the script into a file and then forcing my running Emacs to re-read it using `auto-revert-mode` while still keeping the `*compilation*`-like behaviour in that buffer. This works, but the problem is that `next-error` can't be reset to start from the new errors after reverting. Using `C-u C-x `` just errors with "Moved past last error". Not even using the `after-revert-hook` to do `(next-error 4 t)` seems to do the trick. How can I reset the `next-error` "pointer" in this scenario? Or are there any other approaches I should try? # Answer > 1 votes I have a similar script, and I just run it directly from `M-x compile`. In my case, the script runs continuously once started and triggers a recompilation on file change. Sounds like that should work for you? You'd run `utman make debug unit test` from `compile`, don't invoke emacsclient or anything. Then, to get `next-error` working correctly on recompile, I do this. 1. Add a function to `compilation-filter-hook` to watch the script output for a special string the script emits on recompilation (for example purposes let's say that string is "Change detected, recompiling ...") 2. Call `compilation-forget-errors` when the string is found. (Note that the manual doesn't advertise this function, I found it by hunting around in the compile.el source code.) 3. Not technically necessary, but for quality of life I after-advise `compilation-forget-errors` to reset the mode-line counts of errors / warnings / info lines. For some reason it doesn't do that by default (in Emacs 27.1) All in, my code snippet looks like this: ``` ;;; this runs with the *compilation* buffer current. see the documentation ;;; for `compilation-filter-hook' (defun my/forget-compilation-errors () (let ((inserted-string (buffer-substring-no-properties compilation-filter-start (point)))) (when (string-match-p "Change detected, recompiling" inserted-string) (compilation-forget-errors)))) (add-hook 'compilation-filter-hook #'my/forget-compilation-errors) (defadvice compilation-forget-errors (after reset-num-errors-found activate) (progn (setq-local compilation-num-errors-found 0) (setq-local compilation-num-warnings-found 0) (setq-local compilation-num-infos-found 0))) ``` --- *Actually* that snippet up there is a bit of a lie. It's what I had at first. These days I *actually* always give a prefix argument to `compile` so that I get `comint-mode` \+ `compilation-shell-minor-mode`. That way I can interact with my script if it prompts for input, which it does sometimes, and I can cleanly shut it down with C-c C-c. The same principles apply, it's just I have to use a different hook. So my *actual* code snippet now looks like: ``` (defun my/forget-compilation-errors (inserted-string) (prog1 inserted-string (when (string-match-p "Change detected, recompiling" inserted-string) (compilation-forget-errors)))) (add-hook 'comint-preoutput-filter-functions #'my/forget-compilation-errors) (defadvice compilation-forget-errors (after reset-num-errors-found activate) (progn (setq-local compilation-num-errors-found 0) (setq-local compilation-num-warnings-found 0) (setq-local compilation-num-infos-found 0))) ``` --- Tags: buffers, emacsclient, compilation-mode ---
thread-57923
https://emacs.stackexchange.com/questions/57923
Alternate citation with Org-Ref
2020-04-20T10:19:29.250
# Question Title: Alternate citation with Org-Ref I am used to manage my bibliography with org-ref and I am very satisfy with it. Nevertheless, in the context of a grant proposal writing, space is limited. So I would to save the space allowed to bibliography refs by replacing the classical citation approach by direct links on DOI (through https:\\doi.org...) of the cited paper. i.e. something like: ``` [[https://www.doi.org/10.1002/jbio.200900094][Sim2017]] ``` instead of : ``` cite:sim2017 ``` Do you know if is there a way to do what I expect with org-ref ? Thx # Answer You can just add `(org-ref-define-citation-link "citea")` to your init file, and it should create that link type. > 0 votes # Answer The solution first rests in Latex instead of the org-ref configuration. Indeed a solution using biblatex and the definition of a new command is described here by Yegor256 and perfectly do the job (but directly in Latex). Now the next step is to make org-ref able to recognize this alternate `\citea{}` command. Any idea ? > 0 votes --- Tags: org-mode, org-link, org-ref ---
thread-64848
https://emacs.stackexchange.com/questions/64848
Why is electric-indent-mode adding extra indentation after pressing return twice in org source blocks?
2021-05-14T15:58:32.043
# Question Title: Why is electric-indent-mode adding extra indentation after pressing return twice in org source blocks? When I try to write code in source block in Org mode, pressing return once acts as expected while hitting it a second time increases the indentation to two levels if it's currently less than that. Here's an example of how the cursor moves when I press return at various initial indentation levels: ``` #+begin_src python def my_function(): # Each "." shows where the cursor goes after pressing RET. . . . . def internal_function(): # Same thing from here. . . . . def double_internal_function(): # Same thing from here. . . . . # Same thing from here. . . . . #+end_src ``` It is `(org-return electric-indent-mode)` that is being called when I press return, and I'm able to reproduce this behavior by calling this myself. Some other function calls that don't exhibit the same behavior are `(org-return-and-maybe-indent)`, `(org-return)`, `(org-newline-and-indent)`, and `(newline-and-indent)`. If I disable `electric-indent-mode`, then the second return eliminates all indentation entirely. Ideally, I would want repeatedly pressing return to maintain the same indentation level. # Answer > 0 votes You need to set the variable: `org-adapt-indentation` to off. --- Tags: org-mode, org-babel, indentation, electric-indent ---
thread-8129
https://emacs.stackexchange.com/questions/8129
Pure elisp spell checking in Emacs
2015-02-10T17:10:25.037
# Question Title: Pure elisp spell checking in Emacs The question What options are there for doing spell-checking in emacs discuss various spell checking solutions for Emacs. Emacs ispell interface uses external tools such as `Aspell` or `Hunspell` for spell checking. Considering the fact that many free dictionary files are available (for example by Openoffice see for example the dictionary file en\_US.zip) I am wondering if it would be possible to write a native spell checking function in Emacs using such free dictionary files. **Added**: More precisely I am wondering if there are existing packages which can be used for spell-checking (without using external tools such as `Aspell` or `Hunspell`) within Emacs. A tool which checks if a word is correct and if not suggests some corrections. In case the answer is negative, any hint to do this would be helpful. # Answer > 2 votes From the comments, Jordon Biondo has some proof-of-concept code at https://gist.github.com/jordonbiondo see in particular `se-spell.el` and `elisp-checker.el`. # Answer > 0 votes See: spell-fu this highlights misspelled words, without calling external processes. Although currently the aspell is used for the initial dictionary dump. --- Tags: ispell, spell-checking ---
thread-64888
https://emacs.stackexchange.com/questions/64888
How can I convert a string form of a list to an actual list?
2021-05-18T09:42:21.650
# Question Title: How can I convert a string form of a list to an actual list? I would like to convert these two strings `"(a b c)"` `"(9 . 3)"` to these `(a b c)` `(9 . 3)` I'd had some luck with the first one evaluating this, `(mapcar 'intern (split-string (string-trim "(a b c)" "(" ")")))` basically, removes parentheses from string, splits it to ("a" "b" "c"), then calls `intern` to turn all the elements to symbols and yields `(a b c)`. When evaluating this with `"(9 . 3)"` though, It escaped all elements and yields `(\9 \. \3)`, this however, is not the same as `(9 . 3)` that I wanted. # Answer > 6 votes ``` ELISP> (read "(a b c)") (a b c) ELISP> (read "(9 . 3)") (9 . 3) ``` If by `(9 . 3)` you mean you'd like a cons, then my answer would work. Note however if you actually would like a dot, my answer not so much. --- Tags: list, string, read ---