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-53420
https://emacs.stackexchange.com/questions/53420
Workaround for "Invalid search bound (wrong side of point)" in CC Mode
2019-10-28T15:26:19.090
# Question Title: Workaround for "Invalid search bound (wrong side of point)" in CC Mode Emacs 24.x and 25.x have a bug in CC Mode which can result in some operations failing with the error > Invalid search bound (wrong side of point) For example, I can reproduce it with the following file `a.c`: ``` #if defined(FOO) || \ defined(BAR) ``` and running ``` emacs -Q -nw a.c --eval '(occur "FOO")' ``` (Running `M-x occur RET FOO RET` after that works. I have a bigger file where this doesn't work.) This is a known bug: #28850. The fix is in two commits 46540a1c7adb1b89b6c2f6c9150fe8680c3a5fba and ad68bbd0da4ed90117f09dc2344c0c3d9d728851 which were first released in Emacs 26.1. I can confirm that Emacs 26.3 works with both the minimal example above and my real file. The machines I use most often run Emacs 24.5.1 or Emacs 25.2.2, so I need a workaround for Emacs 24.x and 25.x. My init file has several hot fixes for Emacs bug and I'm fine with adding one more. I normally hot-fix in an `eval-after-load` form, either by advising a function or by replacing its definition. But here there's a bug in the function `c-make-font-lock-search-form` which, if I understand correctly, is used **at compile time**. This is the relevant part of `cc-fonts.el`: ``` (eval-and-compile … (defun c-make-font-lock-search-form (regexp highlights) ;; this code needs to be patched …) (defun c-make-font-lock-context-search-function (normal &rest state-stanzas) (c-make-font-lock-search-form …)) ;; this call needs to be patched ) (c-lang-defconst c-cpp-matchers t `( … ,(c-make-font-lock-context-search-function …))) ``` So `cc-fonts.elc` contains buggy byte-compiled code. Merely fixing the buggy function after `cc-fonts.elc` is loaded won't help. Even fixing the function before `cc-fonts.elc` wouldn't help. **How can I work around this bug? The workaround needs to work on Emacs 24.x and 25.x.** The workaround needs to fix the "Invalid search bound" error, without disabling fontification. I don't mind if there's a slight loss of performance or accuracy compared to the official fix. # Answer > 1 votes A big-hammer approach is to add `cc-mode` to your config, as it is maintained externally and tends to be very backwards-compatible. The latest version says "CC Mode 5.34 should work out of the box with Emacs \>= 24.5 ... It may well work on earlier versions." The 5.33 release notes say "The minimum versions supported ... Emacs 23.2". --- Tags: search, byte-compilation, cc-mode, monkey-patching ---
thread-53428
https://emacs.stackexchange.com/questions/53428
How to convert an org string to html in an elisp program (with macros)?
2019-10-28T19:27:23.880
# Question Title: How to convert an org string to html in an elisp program (with macros)? In an elisp program, I am trying to convert strings from org syntax to (say) html. For that, I use `org-html-convert-region-to-html` with a temporary buffer, and everything is fine: ``` (defun tv/org-string-to-html (string &optional macros) (if (or (not string) (string-empty-p string)) "" (with-temp-buffer (insert string) (set-mark (point-min)) (goto-char (point-max)) (when macros (setq org-macro-templates macros)) ;; not working (org-html-convert-region-to-html) (substring (buffer-substring-no-properties (point-min) (point-max)) 4 -5)))) ;; ELISP> (tv/org-string-to-html "This is [[file:test][a link]], this is *bold*, and this is /italic/") ;; "This is <a href=\"test\">a link</a>, this is <b>bold</b>, and this is <i>italic</i>" ``` However, it does not work if the string I am trying to convert has a macro, because my temporary buffer does not know about this macro. I have tried to pass the content of the `org-macro-templates` variable to my converter function in the function above, but it doesn't appear to work, the macro is still not recognized. Examining `org-macro-expand` with edebug, it appears that the macro templates are overwritten by org -- which makes sense. And the `org-macro-templates` variable does warn not to set it directly, but to use `#+MACRO:` lines instead. Now, the obvious solution would be to collect all the macros in the org buffer and insert them in the temporary buffer, or to simply use the current org buffer instead of a temporary buffer. Neither option is really nice... Is there a proper way to achieve what I want? # Answer I don't know if this is proper, but here is a version that seems close. The idea is to use a copy of the buffer to insert it, and convert it to html. There result seems to get wrapped in `<p></p>`, but maybe you can use a substring to get rid of these. ``` (defun tv/org-string-to-html (string &optional macros) (if (or (not string) (string-empty-p string)) "" (org-export-with-buffer-copy (let ((start (goto-char (point-max)))) (insert string) (narrow-to-region start (point-max)) (with-current-buffer (org-html-export-as-html nil nil t t) (buffer-string)))))) ``` > 1 votes --- Tags: org-mode, org-export ---
thread-53437
https://emacs.stackexchange.com/questions/53437
What is the data-type for :symbol?
2019-10-29T07:54:35.490
# Question Title: What is the data-type for :symbol? When looking at 'Face attributes' in emacs you have keywords like `:family`, `:height`, `:weight` etc. When using `use-package` you have keywords like `:ensure`, `:init`, `:config` etc. 1. What are the terms for describing these symbols where you have a colon prepended to a name? 2. Where in info can I find out more? Please use the format: `(info "(manual)DOCUMENT NODE")` which can be searched for by using `M-:` e.g. `(info "(elisp)Lisp Data Types")` # Answer > 3 votes From the manual Section 9.2. "Symbol Components": > Most symbols can have any Lisp object as a value, but certain special symbols have values that cannot be changed; these include nil and t, and **any symbol whose name starts with ‘:’ (those are called keywords)**. See Constant Variables. This page can be reached with `M-:` `(info "(elisp)Symbol Components")` `<RET>` --- Tags: info, symbols ---
thread-53441
https://emacs.stackexchange.com/questions/53441
move focus between sub-windows (or buffers?) with ctrl-tab?
2019-10-29T08:51:37.237
# Question Title: move focus between sub-windows (or buffers?) with ctrl-tab? Currently using GNU Emacs 23.1.1. I've used xemacs since the late 90s and am only now switching to proper emacs. If I had my xemacs window split into a top buffer and bottom buffer, I could move the keyboard focus between them with ctrl-tab. *(I cannot remember if that's something I wrote myself 20+ years ago, or was a standard mapping, but checking my config files I don't think I wrote it myself.)* There are similar questions about rotating *between* buffers, but, I think, keeping the focus in the same sub-window. That's not my question, but just to be clear, the following is something I find very useful but isn't what this current question is asking. I probably have the wrong terminology, but the following code changes the buffer within the current sub-window. Instead I want to leave all the sub-windows looking at their current buffers, and instead move focus to the next sub-wind. > (defun switch-to-next-buffer () (interactive) (switch-to-buffer (other-buffer))) # Answer Gnu Emacs has the function `other-window` which is bound to `C-x o`. The relevant section from the doc string of `other-window`: > `(other-window COUNT &optional ALL-FRAMES)` > ... > Select another window in cyclic ordering of windows. COUNT specifies the number of windows to skip, starting with the selected window, before making the selection. If COUNT is positive, skip COUNT windows forwards. If COUNT is negative, skip -COUNT windows backwards. COUNT zero means do not skip any window, so select the selected window. In an interactive call, COUNT is the numeric prefix argument. So the keysequence `C-<minus>` `C-x o` gives you the inverse of `C-x o`. Note that `C-<minus>` stands for the numeric prefix arg `-1`. > 2 votes --- Tags: buffers, focus ---
thread-53448
https://emacs.stackexchange.com/questions/53448
How do you do runtime code swapping?
2019-10-29T12:44:43.157
# Question Title: How do you do runtime code swapping? Does elisp have the "runtime code swapping" feature? mentioned in slide at 27:14 https://www.youtube.com/watch?v=3TlEqzptWr0&t=27m14s > > Hot code loading is the art of replacing an engine from a running car without having to stop it. Definition of *code hot swapping* from the PhD of Don Stewart: > **Definition** Hot swapping is the replacement of existing code fragments at runtime without loss of the environment (state) associated with that code. Further below he explains: > The goal of code hot swapping is to allow for upgrades to components without observable loss in availability. # Answer > 3 votes Yes, at any point you can redefine a function by evaluating a `defun` with the name of an existing function. By extension, when you reload a file with `M-x load-file`, all function definitions in that file will be reevaluated, and the corresponding old function definitions replaced. If you want to change the behaviour of an existing function, it might be cleaner to "advise" that function using `advice-add` instead of redefining it. See this answer for a description of how to do this. # Answer > 3 votes There is no real definition in Dave Thomas' video presentation. Therefore I stick to the definition Don Stewart gives in his PhD cited in your question. Dave Thomas mentiones in his video that a functional language "potentially allows runtime code swapping" because "it is pure". The notion of a pure function means that the function does not have an internal state. The arguments of the function completely determine its output. That would fit nicely to Don's definition. It also gives a hint how your question must be answered: The answer is: "**Yes and No** depending on the code." # Yes ## Function definitions Nowadays one is encouraged to use lexical binding. Let us define a function `f` on lexical top-level. In the following Elisp code fragments the evaluation results are given in the comments following the Elisp forms. ``` (defun f (x) "Pure function" (1+ x)) ;; f (symbol-function 'f) ;; (closure (t) (x) "Pure function" (1+ x)) ``` The lexical environment does just hold a `t` which is the symbol standing for "true" and evaluating to itself. The closure holds no state at all and we have a pure function which can be replaced by binding `f`'s function cell to another (pure) closure. If we consider the contents of the value cells of all symbols as the current state of the Elisp runtime then swapping the pure function does not change the state of the Elisp runtime. Note: Here we completely ignore that the function cells of the symbols actually also contribute to the state of the runtime. But that is also covered by Don's definition because the values of the function cells more or less represent the code fragments whose Don is speaking of. ## Library reloading Symbols for variables of a library should be declared as special by `defvar` on top-level of the library. A default value can be passed as argument to `defvar`. The value cell of the dynamic variable is is only bound to the given default value if it is not yet bound, i.e., it is not set yet. If only `devar` and `defun` are used on top-level of the library and no `setq` or function evaluation then the state of the library is even preserved when one reloads the library with `(load-file "someLibName.el")` or `(load-library "someLibName.el")`. Thereby, the newly loaded library can also be a modified version of the first-loaded one. Naturally, it should use its dynamic variables in a compatible way. # No ## Function definitions Closures get a lexical environment with lexically bound symbols if they are defined in the context of a (nontrivial) `let`-binding. If one redefines the closure in a separate evaluation of the (same) `let` form the newly defined closure has a fresh lexical environment. It can no longer access the lexical bindings from the first evaluation of the `let` binding. That means that closures with nontrivial lexical environment have an internal state and that state is lost if one redefines the closure through reevaluation of the `let` form. The following code demonstrates the effect: ``` ;; -*- lexical-binding: t -*- (defun my-definitions () (let ((state 1)) (defun my-set-state (x) (setq state x)) (defun my-get-state () state))) ;; my-definitions (my-definitions) ;; my-get-state (defalias 'my-save-fun (symbol-function 'my-set-state)) ;; my-save-fun (my-definitions) ;; my-get-state (symbol-function 'my-save-fun) ;; (closure ((state . 1) t) (x) (setq state x)) (symbol-function 'my-set-state) ;; (closure ((state . 1) t) (x) (setq state x)) (symbol-function 'my-get-state) ;; (closure ((state . 1) t) nil state) (eq (cadr (symbol-function 'my-set-state)) (cadr (symbol-function 'my-get-state))) ;; t ;; `my-set-state' and `my-get-state' have the same lexical environment (eq (cadr (symbol-function 'my-set-state)) (cadr (symbol-function 'my-save-fun))) ;; nil ;; `my-save-fun' and `my-get-state' look very alike but they have differing lexical environments (my-save-fun 2) ;; 2 ;; setting state of `my-save-fun' to 2 (my-get-state) ;; 1 ;; state of `my-get-state' remains 1 (my-set-state 3) ;; 3 ;; set state of `my-set-state' and `my-get-state' to 3 (my-get-state) ;; 3 ;; Voila... ``` ## Library reloading If one sets the value of dynamically bound variables in a library with `setq` its previously set value is lost. Thus reloading such a library destroys the state of the runtime. Needless to say that function evaluation on top-level of a library can also modify the values of the dynamic variables of the library. --- Tags: load, monkey-patching ---
thread-53445
https://emacs.stackexchange.com/questions/53445
How remove asterisks in org mode?
2019-10-29T11:10:53.950
# Question Title: How remove asterisks in org mode? Windows 10 Emacs 26.1 Here example of my org file with many inner items In my opinion it does not look very comfortable. I think asterisks make "noise". Is it possible to remove asterisks? # Answer > 6 votes Several possibilities are exposed in the manual. The first is to use `org-indent-mode`. > Org provides an alternate stars and indentation scheme, as shown on the right in the following table. It uses only one star and indents text to line with the heading: > ``` > * Top level headline | * Top level headline > > ``` ``` ** Second level | * Second level *** 3rd level | * 3rd level some text | some text *** 3rd level | * 3rd level more text | more text * Another top level headline | * Another top level headline ``` > To turn this mode on, use the minor mode, ‘org-indent-mode’. Text lines that are not headlines are prefixed with spaces to vertically align with the headline text(1) If you don't want the text to be indented you can just configure the variable `org-hide-leading-stars` > Org can make leading stars invisible. For global preference, configure the variable ‘org-hide-leading-stars’. For per-file preference, use these file ‘#+STARTUP’ options: > ``` > #+STARTUP: hidestars > > ``` ``` #+STARTUP: showstars ``` > ``` > With stars hidden, the tree is shown as: > > ``` > ``` > * Top level headline > > ``` ``` * Second level * 3rd level ... ``` If you had previously set `#+STARTUP: indent` you may need to reset with `C-c C-c` with the cursor on the`#+STARTUP` line (or any other keyword line). # Answer > 5 votes You can change the asterisks for any UTF-8 character using org-bullets-mode. Just download `org-bullets` from MELPA repository and add the following into your init file: ``` (require 'org-bullets) (add-hook 'org-mode-hook (lambda () (org-bullets-mode 1))) ``` If you don't like default org-bullet symbols, you can set yours as follows: ``` (setq org-bullets-bullet-list '("✙" "♱" "♰" "☥" "✞" "✟" "✝" "†" "✠" "✚" "✜" "✛" "✢" "✣" "✤" "✥")) ``` **Since you want to remove the "noise", the cleanest option is to set bullet symbols to zero width space.** ``` (setq org-bullets-bullet-list '("\u200b")) ``` You can find other bullet symbols sets here. **Note:** some Windows users have reported rendering issues of unicode, the solution seems to be here. --- Tags: org-mode ---
thread-53452
https://emacs.stackexchange.com/questions/53452
How to open a folder as project in emacs?
2019-10-29T17:30:51.123
# Question Title: How to open a folder as project in emacs? VSCode (and other graphical editors) allow you to open any folder, and all source files in that folder are already tagged such that you can jump to definitions of functions/objects as long as the definitions exist in that same folder (as well as other features like finding all references in the entire project folder) I'm trying to explore emacs for my day-to-day tasks and would like to understand the best way to achieve the above. The official GNU Emacs documentation talks about EDE mode, but that required each subfolder to be manually assigned as a project (i.e. the .ede files will exist in all folders in the directory). Is there a better way to do this? The reason I need this is that all of our official code is maintained as Visual Studio solutions and if I'm using any other editor/IDE, then I can open the project folder as a project and still be able to read/understand the code outside of Visual Studio. Thanks! # Answer > 4 votes Emacs packages will automatically find the project root, IMO, workspace is an outdated idea. Everything should just work out of box without setup. BTW, unlike VSCode, in Emacs you can easily code in multiple projects at the same time. So the answer to your question is simple, "do nothing". Just use the most popular packages other guys are using. --- Tags: directory, project ---
thread-53436
https://emacs.stackexchange.com/questions/53436
Looking for a shortcut to select the function/method at point
2019-10-29T07:32:42.193
# Question Title: Looking for a shortcut to select the function/method at point I have this problem in JavaScript, but I understand the solution to it could be more general. My cursor (point) is on the name -or on the body- of a function, like this : ``` function test() { // My cursor is here or anywhere between "function" and "}" console.log("test"); } ``` I would like to quickly select function test, in order to move it somewhere else in the code, or remove it completely. Is there a function, in js2-mode or anywhere else, which would allow me to do that? # Answer > 3 votes See this part of the manual. Marking with `C-M-h` should work just fine. This runs `mark-defun` and marks the complete current function definition around point. Some nifty details: * If your mark was already active, it extends the region until the end of the next defun. * A negative argument reverses the direction of traver for all subsequent calls. So by default without previous calls to `mark-defun` this selects the previous defun. # Answer > 6 votes Emacs calls a function definition a “defun”, because `defun` is the keyword¹ that starts a function definition starts in Lisp. Commands to move by defuns use the modifiers `Ctrl`+`Alt`: * `C-M-a` and `C-M-e` to move to the beginning/end of the current function definition; * `C-M-h` to select the current function definition. This is somewhat similar, but not strictly parallel, to `M-a` and `M-e` to move to the beginning/end of the current sentence, and `M-h` to select the current paragraph. The exact behavior of these commands depend on the programming language. The default rule is that a defun starts with a line with 0 indentation, but many programming language modes change this, either by tuning the way the default function works or by binding the usual keyboard shortcuts to a different function. On a related note, Emacs calls a subexpression a “sexp”. Generally a sexp is delimited by balanced parentheses, brackets or braces, or is a single identifer. Again the exact rules depend on the programming language. The main commands for sexps are: * `C-M-b` and `C-M-f` to move back/forward to the previous/next sexp. * `C-M-p` and `C-M-n` to move back/forward to the previous/next expression delimited by parentheses (the exact rules depend on the language, but typically this stops in fewer places than `C-M-b` and `C-M-f`). * `C-M-u` (`M-x backward-up-list`) and `M-x up-list` (no default binding) to move out of the surrounding parentheses/brackets/braces. * `C-M-SPC` or `C-M-@` to select the following sexp. ¹ <sub> Not a keyword, strictly speaking, but close enough. </sub> # Answer > 1 votes I think I found it. Use `C-M h`, which is bound to `mark-defun`. The beauty of it is that it works not only on JavaScript, but also on Python, Elisp, or seemingly any other language. I found the solution on this post which is specific to C. # Answer > 1 votes Install `evil`, `evil-matchit`, then press `%`. It supports many programming language, not just javascript. It can be extended easily by user to support new syntax and new languages. --- Tags: programming ---
thread-53464
https://emacs.stackexchange.com/questions/53464
How can I turn on support package automatically
2019-10-30T01:23:23.463
# Question Title: How can I turn on support package automatically As I said in title, when you load a major mode like matlab-mode, I need company-mode as well. It's so easy to turn on the package, but is there any way to load automatically? through .emacs or .init ? When I try to load 'matlab-shell', 'company-mode' is loaded without extra action for example. I have no idea about LISP. # Answer The instructions for `company-mode` at https://company-mode.github.io/ say: "*To use company-mode in all buffers, add the following line to your init file*": ``` (add-hook 'after-init-hook 'global-company-mode) ``` To use `company-mode` in only certain major-modes, use something like this (where the first argument to `add-hook` is the name of the applicable major-mode hook): ``` (add-hook 'matlab-mode-hook 'company-mode) ``` > 1 votes --- Tags: package ---
thread-53467
https://emacs.stackexchange.com/questions/53467
Replace lines with ( with :( by regex-replace
2019-10-30T05:14:39.397
# Question Title: Replace lines with ( with :( by regex-replace I have such a snippets: ``` Exercise 2.32. We can represent a set as a list of distinct elements, and we can represent the set of all subsets of the set as a list of lists. For example, if the set is (1 2 3), then the set of all subsets is (() (3) (2) (2 3) (1) (1 3) (1 2) (1 2 3)). Complete the following definition of a procedure that generates the set of subsets of a set and give a clear explanation of why it works: (define (subsets s) (if (null? s) (list nil) (let ((rest (subsets (cdr s)))) (append rest (map <??> rest))))) ``` Select them all and run `regex-replace` `^\(.*(\) → : \1` The result I expected is Nevertheless, it proved to be: Whats' the problem with my usage? # Answer > 2 votes `.` matches any single character except a newline, so `^.*(` matches from line beginning till `(`, thus all lines besides the empty line matches. Don't forget the first line contains `(`: ``` Exercise 2.32. ... For example, if the set is (1 2 3), ... ``` You should change `.` into `\s-` (it matches any whitespace character, you can also just use space character). However, I always use `C-x r t` (`M-x string-rectangle`) to prepend a common prefix to multiple lines. --- Tags: regular-expressions ---
thread-53461
https://emacs.stackexchange.com/questions/53461
Specifying a binding for control shift tab?
2019-10-30T00:27:54.573
# Question Title: Specifying a binding for control shift tab? I defined a function like this: ``` (defun switch-to-prev-window () (interactive) (other-window -1)) ``` and it appears to work if I call it with M-x. But I've added the binding ``` (global-set-key [(control shift tab)] 'switch-to-prev-window) ``` and that does NOT seem to work. In fact when I use M-x to run it, it reports `you can run the command 'switch-to-prev-window' with <C-S-tab>`. But when I type ctrl-shit-tab I see `<C-S-iso-lefttab> is undefined`. And yet ``` (global-set-key [(control tab)] 'other-window) ``` seems to work fine. Based on the error message I tried ``` (global-set-key [(control shift iso-lefttab)] 'switch-to-prev-window) ``` and *that* works fine too. So I'm left wondering: is `control tab` aliased to `control iso-lefttab`, but there's no corresponding `control shift tab` alias? And yet if that were the case, why the reminder that `<C-S-tab>` is available? # Answer Key naming is messier than it ought to be. When you press the `Tab` key while the `Shift` modifier is held down, your operating system tells Emacs that you've pressed the `ISO_Left_Tab` key. I guess that you're using an X11-based system (I think that's the only platform with this particular key name) and you're using a standard XKB layout which specifies (e.g. through `/usr/share/X11/xkb/symbols/pc`): ``` key <TAB> { [ Tab, ISO_Left_Tab ] }; ``` This means: when the user presses the physical key `TAB`, it's the logical key `Tab` if unshifted but `ISO_Left_Tab` if shifted. The reason to have a separate key is that there (used to) exist terminals with a both a “left tab” and a “right tab” key. Most terminals only have a single tab key which is a right tab key, and the convention to indent or move to the left is to use this key with the Shift modifier. That's why `Shift`+`Tab` is translated to a “left tab” keyboard event. Emacs has its own name for the logical key “tab towards the left”, which is `backtab`. In `local-function-key-map` on an X11 frame, there's a translation from `iso-lefttab` and `S-iso-lefttab` to `backtab`. There's no corresponding translation for `C-iso-lefttab` or `C-S-iso-lefttab`. Add these translations to `function-key-map`. (That's not the absolute cleanest place to put them, because `function-key-map` applies to all terminals and not just X11 frames. But since this translation doesn't hurt elsewhere, you might as well apply it systematically.) Add any other similar translation if you want to use other modifiers. ``` (define-key function-key-map [(control shift iso-lefttab)] [(control shift tab)]) (define-key function-key-map [(meta shift iso-lefttab)] [(meta shift tab)]) (define-key function-key-map [(meta control shift iso-lefttab)] [(meta control shift tab)]) ``` Alternatively, make your key binding for `C-S-iso-lefttab` rather than `C-S-tab`. Some modes do set up bindings for `S-iso-lefttab` rather than rely on the translation. If you use the `function-key-map` approach and a mode defines a binding for `C-S-iso-lefttab`, the mode's binding takes precedence over the translation in `function-key-map`. For completeness, the canonical place for a key translation that should only take place in an X11 frame is in `x-alternatives-map`, which is used as the `local-function-key-map` on X11 frame (each terminal has its own value of `local-function-key-map`). > 10 votes --- Tags: key-bindings ---
thread-31160
https://emacs.stackexchange.com/questions/31160
How to install GNU Emacs on Windows 10 Pro?
2017-03-01T18:09:00.137
# Question Title: How to install GNU Emacs on Windows 10 Pro? I can't find a clear tutorial for how to install GNU Emacs on Windows 10. Normally there are a few tricks required to get it running properly, so I thought I would ask here before trying one of the Windows 8 tutorials. The specific “flavour” of Emacs is not particularly important. # Answer Some third-party Windows package managers offer a straightforward installation of GNU Emacs on Windows 7+. Notes: * Chocolatey requires an administrative shell access, whereas Scoop does not and makes installation portable. * Both Chocolatey and Scoop install 64-bit Emacs on 64-bit host system. * Both Chocolatey and Scoop automatically create corresponding shims so that Emacs can be called from the console via `emacs` (GUI version) or `emacs -nw` (terminal session). # Chocolatey ### Installation Open *elevated* PowerShell and install the `choco` package manager, then install `emacs` package: ``` choco install emacs ``` ### Launching By default an icon is added to the start menu and the launcher can be found at `C:\ProgramData\chocolatey\bin\runemacs.exe`. ### Updating ``` choco update emacs ``` ### Removing ``` choco uninstall emacs ``` # Scoop ### Installation Open PowerShell and install the `scoop` package manager, then add `extras` repo (you will need to install `git` and `7zip` as well): ``` scoop bucket add extras ``` Install `emacs` package: ``` scoop install emacs ``` ### Launching By default an icon is added to the start menu into the Scoop Apps folder and the launcher can be found at `~\scoop\apps\emacs\current\bin\runemacs.exe`. ### Updating ``` scoop update emacs ``` ### Removing ``` scoop uninstall emacs ``` > 9 votes # Answer After reading many tutorials and readmes I was unable to install Emacs and `spacemacs` on my machine until now. It is super easy. 1. create a folder in a directory you wish to install (eg I'd like to install on drive `c:/` 2. add a new user variable named `HOME` and valued `to the created folder` (eg `c:/emacs/` 3. download the latest version of Emacs 4. extract the content of the downloaded file into the folder you have created a couple of steps ago. (eg `c:/emacs/`) 5. open `runemacs.exe` located in `c:/emacs/bin/` directory; this would generate a folder named `.emacs.d` in `c:/emacs/` **installing `spacemacs`** 6. quit Emacs 7. download spacemacs 8. extract the content in the `c:/emacs/.emacs.d` directory 9. finally re-execute `runemacs.exe`. > I've learned about the instruction in this video > 2 votes --- Tags: microsoft-windows, emacsclient, install ---
thread-53474
https://emacs.stackexchange.com/questions/53474
Prevent magit-status from closing hunk preview window when magit-status buffer close
2019-10-30T09:39:59.300
# Question Title: Prevent magit-status from closing hunk preview window when magit-status buffer close I configured magit-status to open selected buffer change hunk in other window rather then in the same window with: ``` (setq magit-display-file-buffer-function (lambda (buffer) (setq current-prefix-arg t) (magit-display-file-buffer-traditional buffer))) ``` Now when I close status buffer the other window is closed as well and I assume window state is bring back to the one before magit-status was opened. How can I keep this window and buffer open after closing magit-status window. The solution would be to prevent magit from restoring windows status before magit-status was opened. # Answer > 3 votes Use this: ``` (setq magit-bury-buffer-function 'magit-mode-quit-window) ``` Also see the Modes and Buffers node. --- Tags: magit ---
thread-53443
https://emacs.stackexchange.com/questions/53443
using cyphejor with projectile
2019-10-29T10:18:39.350
# Question Title: using cyphejor with projectile Make names of major modes shorter in the mode-line describes a way to shorten the modeline with cypejor. However, it seems like projectile-mode is not shortened by cyphejor. Is there anything that needs to be added to the config? Example: ``` (setq cyphejor-rules '(:upcase ("projectile" "P") ("menu" "▤" :postfix) ("mode" "") ("package" "↓") ("python" "π") ("shell" "sh" :postfix) )) (cyphejor-mode 1) ``` # Answer While the question still remains, projectile can itself shorten its mode line part: > * `projectile-mode-line-prefix` (by default " Projectile") controls the static part of the mode-line > * `projectile-dynamic-mode-line` (by default t) controls whether to display the project name & type part of the mode-line > 1 votes --- Tags: projectile, cyphejor ---
thread-36547
https://emacs.stackexchange.com/questions/36547
How do I do a `git add` with vc-git?
2017-11-01T18:17:29.553
# Question Title: How do I do a `git add` with vc-git? I want to stage a file or a hunk using vc-git (the vc system that comes with Emacs). How do I do this? (To clarify, I made modifications on a file that is already (registered) in git. I would like to stage the new modifications made. How do I do this with vc-git?) # Answer > 4 votes `C-x v v` will run `vc-next-action` command. > Do the next logical version control operation on the current fileset. This requires that all files in the current VC fileset be in the same state. If not, signal an error. > > For merging-based version control systems: > > * If every file in the VC fileset is not registered for version control, register the fileset (but don’t commit). > * If every work file in the VC fileset is added or changed, pop up a `*vc-log*` buffer to commit the fileset. --- Tags: git, vc ---
thread-53478
https://emacs.stackexchange.com/questions/53478
How to format shell commands run from Dired?
2019-10-30T13:43:01.077
# Question Title: How to format shell commands run from Dired? I want to execute a formatted shell command on a file from within Dired. I am aware that I can use `dired-do-shell-command` to run a shell command on a selected file file by entering ``` ! <command> ``` to run ``` <command> file ``` Ideally I want to run ``` ! <command> file <additional-arguments> ``` In other words I want to be able to specify where in the command file appears. I tried running ``` ! <command> {} <additional-arguments> ``` and reading the doc for `dired-do-shell-command`, but neither of those gave me the solution to achieve this. # Answer > 4 votes Simply add your parameters to the command prompt, separated by space, without any placeholder for filenames. To construct commands like `ls -l <file>`, just enter `ls -l`. --- **OR**: the interface supports the placeholders `*` and `?`. Where `?` means call command with one marked file only, in a loop; and `*` means call with all marked files. Read more at masteringemacs.org Example: (`ls` would be your `<command>` **and** `-l` would be your `<additional-arguments>`). You could enter `ls * -l` as command for example to run `ls <files> -l` once (with all marked files at once). Or you could enter `ls ? -l` to run `ls <file> -l` for every single file. --- *Edit:* dired-do-shell-command help string: > Signature > (dired-do-shell-command COMMAND &optional ARG FILE-LIST) > > Documentation > ... > If there is a * in COMMAND, surrounded by whitespace, this runs COMMAND just once with the entire file list substituted there. > > If there is no \*, but there is a ? in COMMAND, surrounded by whitespace, this runs COMMAND on each file individually with the file name substituted for ?. --- Tags: dired, shell ---
thread-53482
https://emacs.stackexchange.com/questions/53482
Difference between (quote string) and "string"
2019-10-30T16:16:02.497
# Question Title: Difference between (quote string) and "string" Experiment on interative ielm ``` ELISP> (print 'list) list list ELISP> (print "list") "list" "list" ``` Any differences with the two results? by the way, one extra times printed. # Answer `'list` and `"list"` are different datatypes: ``` ELISP> (type-of 'list) symbol ELISP> (type-of "list") string ``` Note that they even show up differently in your example -- it's the difference between `list` and `"list"`. But why do they show up twice? Well, because the REPL displays anything printed out, but *also* prints out the return value of the s-expression. For example: ``` ELISP> 3 3 (#o3, #x3, ?\C-c) ELISP> "I'm being returned!" "I'm being returned!" ``` So if we use progn, which runs all of its arguments and returns the last one, we can see the difference between a *printed* value and a returned one: ``` ELISP> (progn (print "I'm being printed") 'not-printed) "I'm being printed" not-printed ELISP> (progn 'not-printed (print "I'm being printed")) "I'm being printed" "I'm being printed" ``` See how in the first example, the printed value shows up, followed by the not printed one? `'not-printed` only ever shows up because it's *returned*; in the second example, we don't see `'not-printed` ever show up! We see `"I'm being printed"` twice -- first printed, then returned. > 7 votes --- Tags: string, symbols, print ---
thread-53484
https://emacs.stackexchange.com/questions/53484
Is there a clean way to splice some args to an existing Lisp macro?
2019-10-30T17:25:57.857
# Question Title: Is there a clean way to splice some args to an existing Lisp macro? I have the following non-working elisp code: ``` (use-package eglot ;; For debug/testing, load local copy of eglot if it exists ,@(if (file-directory-p (concat user-emacs-directory "/eglot")) '(:load-path "eglot/") '(:quelpa ((eglot :fetcher github :repo "joaotavora/eglot")))) :commands eglot :hook ((vue-mode . eglot-ensure) (typescript-mode . eglot-ensure) (javascript-mode . eglot-ensure)) :config (add-to-list 'company-backends 'company-capf)) ``` You can see what I'm after -- if `~/.emacs.d/eglot` exists, use the package from my local dir. Otherwise use quelpa to fetch it from its repo. I'm doing this because I'm working on some fixes. The idea is to use `,@` to interpolate items into the arg list. But of course you can't use `,@` outside of a backquoted list. So I know I could pull all the args out and use `(apply 'use-package eglot-args)` but I'm wondering if there's a clever Elisp syntax to interpolate a list into an arg list dynamically like this. # Answer Since you have already a solution for your special use-case (switching from package.el to straight.el) that has nothing to do with macro-expansion I will answer your general question *Is there a clean way to splice some args to an existing Lisp macro?*. Evaluation of a non-compiled macro form involves both macro expansion and evaluation of the resulting code. So you should just use `eval` on the backquoted macro form where you splice in the args you like as usual. Since the arg of `eval` is evaluated before the `eval` the parameters are spliced in before macro expansion of `m`. I demonstrate that in the following with a simple macro `m`. For each top-level Elisp form the evaluation result is given in the comment following it. ``` (defmacro m (&rest arglist) `(quote (arglist: ,@arglist))) ;; m (setq splice-in nil) ;; nil (eval `(m ,@(when splice-in (list :myarg 1)))) ;; (arglist:) (setq splice-in t) ;; t (eval `(m ,@(when splice-in (list :myarg 1)))) ;; (arglist: :myarg 1) ``` If you use that construct in your init files it is no problem that the macro call is not byte-compiled since init files should not be byte-compiled anyway. Citation of the Emacs Manual: > Byte-compiling your init file is not recommended (see Byte Compilation). It generally does not speed up startup very much, and often leads to problems when you forget to recompile the file. Otherwise you can use the solution proposed by Drew in one of his comments. Maybe, he transforms it into an alternative answer. > 3 votes --- Tags: use-package, elisp-macros ---
thread-53489
https://emacs.stackexchange.com/questions/53489
shift selection not working for rebound M-{ backward-paragraph
2019-10-31T00:29:14.213
# Question Title: shift selection not working for rebound M-{ backward-paragraph I slightly simplified the keys for `backward-paragraph` and `forward-paragraph`: ``` (global-unset-key (kbd "M-{")) ;; originally backward-paragraph (global-unset-key (kbd "M-}")) ;; originally forward-paragraph (global-set-key (kbd "M-[") 'backward-paragraph) (global-set-key (kbd "M-]") 'forward-paragraph) ``` These work, but I was hoping to get Shift Selection for free. In particular, the official manual says: > If you hold down the shift key while typing a cursor motion command, this sets the mark before moving point, so that the region extends from the original position of point to its new position. This feature is referred to as shift-selection. It is similar to the way text is selected in other editors. > > ... > > Shift-selection only works if the shifted cursor motion key is not already bound to a separate command (see Customization). For example, if you bind S-C-f to another command, typing S-C-f runs that command instead of performing a shift-selected version of C-f (forward-char). I have `shift-select-mode` as its default value, which is `t`. However, if I now press `M-{`, I just get `M-{ is undefined` in the echo area, instead of shift-selected `backward-paragraph` as I was hoping. This seems to contradict the passage from the manual above. Is this a bug or am I doing something wrong? **edit**: I also tried the following, taken from a similar question: ``` (global-set-key (kbd "M-[") (lambda () (interactive "^") (backward-paragraph))) ``` And this had the exact same result as my initial method; e.g. `M-[` effectively acts as `backward-paragraph`, but `M-{` just says `undefined` # Answer > 1 votes This appears to be a bug in emacs; `M-{` should just automatically work, if we take the manual at face value. As a workaround, I took an answer to a similar question and modified it: ``` (global-set-key (kbd "M-[") 'backward-paragraph) (global-set-key (kbd "M-{") 'backward-paragraph-with-shift-select) (global-set-key (kbd "M-]") 'forward-paragraph) (global-set-key (kbd "M-}") 'forward-paragraph-with-shift-select) (defun backward-paragraph-with-shift-select () (interactive) (setq this-command-keys-shift-translated t) (call-interactively 'backward-paragraph)) (defun forward-paragraph-with-shift-select () (interactive) (setq this-command-keys-shift-translated t) (call-interactively 'forward-paragraph)) ``` This works perfectly. --- Tags: key-bindings, paragraphs, shift-selection ---
thread-53493
https://emacs.stackexchange.com/questions/53493
How to allow a sexp within a quoted list to be evaluated?
2019-10-31T01:54:19.113
# Question Title: How to allow a sexp within a quoted list to be evaluated? ``` (setq a 2) (setq l '(a b c)) (car l) ``` Got `a` when evaluating this, and why its value not `2` ? # Answer The single quote inhibits evaluation of elements in the list. An alternative form would be to use the function `list` instead of single quote, or use a backtick and comma combination. See: https://www.gnu.org/software/emacs/manual/html\_node/elisp/Backquote.html ``` (progn (setq a 2) (setq l `(,a b c)) (car l)) ``` or ``` (let (a b c l) (setq a 2) (setq l (list a b c)) (car l)) ``` > 3 votes --- Tags: quote ---
thread-53435
https://emacs.stackexchange.com/questions/53435
What does z originate in C-x z (z no relation with repeat literally
2019-10-29T05:04:58.587
# Question Title: What does z originate in C-x z (z no relation with repeat literally In contract to vim's arbitrary behaviors in choosing keys, emacs's key binding performs semantically, C-x (C for commands, x for execute) M-x (M for meta commands or named command, invoke a command by its original name) C-c (c for create) C-p (previous) C-n (next) Even the arcane bindings: C-v (vertical) M-v (m for meta(above beyond) so M-v is move vertically above and thus illustrate why C-v moving down. When it comes to C-x z which evaluate `repeat`, What's z here and it relation with repeat? P.S. Why dig it > We now come to the decisive step of mathematical abstraction: we forget about what the symbols stand for. ...\[The mathematician\] need not be idle; there are many operations which he may carry out with these symbols, without ever having to look at the things they stand for. > > * Hermann Weyl, The Mathematical Way of Thinking # Answer > 3 votes Following from the excellent comment by @daveloyall, here's the key quote from the Commentary of `vi-dot.el` by Will Mengarini (circa March 1998, before `vi-dot` was renamed to `repeat`). This is from `lisp/repeat.el.~0a8cbe6881^~`. > Since the whole point of vi-dot is to let you repeat commands that are bound to multiple keystrokes by leaning on a *single* key, it seems not to make sense to bind vi-dot itself to a multiple-character key sequence, but there aren't any appropriate single characters left in the orthodox global map. (Meta characters don't count because they require two keystrokes if you don't have a real meta key, and things like function keys can't be relied on to be available to all users. We considered rebinding `C-z`, since `C-x C-z` is also bound to the same command, but RMS decided too many users were accustomed to the orthodox meaning of `C-z`.) So the vi-dot command checks what key sequence it was invoked by, and allows you to repeat the final key in that sequence to keep repeating the command. For example, `C-x ] C-x z z z` will move forward 4 pages. --- Tags: key-bindings ---
thread-18883
https://emacs.stackexchange.com/questions/18883
persistent org-mode clock-in history
2015-12-16T08:12:37.813
# Question Title: persistent org-mode clock-in history Is there a way to make the list of recently clocked-in tasks in org-mode persistent across Emacs restarts and (more importantly) closed buffers? It's annoying having to find the previous task just because I happened to exit a file. # Answer > 5 votes I made a little package org-mru-clock to solve this. When I run `org-mru-clock-select-recent-task` or `org-mru-clock-in` it finds all recently-clocked-in tasks from org files and stores the top `org-mru-clock-how-many` in `org-history`; that takes about 5 seconds, so it doesn't do anything if `org-history` already has that many entries. This is nicer than saving to disk, since I have the org files version controlled, and the initial 5 second wait is acceptable. It's compatible with ivy, ido, selectrum or the built-in completion; my init.el has this: ``` (use-package org-mru-clock :ensure t :bind* (("<f8>" . org-mru-clock-in)) :commands (org-mru-clock-in org-mru-clock-select-recent-task) :config ;; I use embark, this gives me some actions on tasks: (add-hook 'minibuffer-setup-hook #'org-mru-clock-embark-minibuffer-hook) (setq org-mru-clock-how-many 100)) ``` The ivy interface also happens to make it really easy to switch quickly between recent tasks: # Answer > 3 votes Org-Mode also includes this feature by default. You can set `org-clock-persist` to `'history` to save the clock entry history when closing emacs. Or set it to `t` to also save the running clock when Emacs is closed. See the manual or the emacs help on `org-clock-persist`. For this to work you also have to run `(org-clock-persistence-insinuate)` in your init file. --- Tags: org-mode, org-clock, persistence ---
thread-53487
https://emacs.stackexchange.com/questions/53487
Are `emacs-devel` mailing list archives from prior to the year 2000 available somewhere?
2019-10-30T23:33:04.910
# Question Title: Are `emacs-devel` mailing list archives from prior to the year 2000 available somewhere? The archives of the `emacs-devel` mailing list go back to the year 2000 and are publicly available on the web. Are there older archives somewhere? Was `emacs-devel` the first mailing list that was used to discuss GNU emacs development, or were there others? # Answer > 4 votes The archives go back to the very beginning of the `emacs-devel` mailing-list, AFAIK. Before that, development discussions were split between the `help-gnu-emacs` list and a non-public `emacs-core` mailing-list (which stopped being used when `emacs-devel` was created). I don't think there are any archives of the `emacs-core` mailing-list. --- Tags: emacs-history ---
thread-53498
https://emacs.stackexchange.com/questions/53498
How do I change the font color of mode-line?
2019-10-31T15:41:28.850
# Question Title: How do I change the font color of mode-line? How do I change the font color of the mode-line to make it more visible? # Answer > 6 votes What you call the bottom bar is the "mode line". I recommend reading the first fews sections of the manual, especially this one to know the names of the various screen elements (this is not difficult at all, but not straightforward for newcomers.) The graphical attributes of text in emacs are grouped in "faces". As mentionned in the manual: > By default, the mode line of nonselected windows is displayed in a different face, called mode-line-inactive. Only the selected window is displayed in the mode-line face. This helps show which window is selected. So the answer is to customize the face `mode-line`. To do so, you can look at the face definition by typing `M-x describe-face RET mode-line RET` and from that select the "customize this font" link (or you can directly use `M-x customize-face`). Customization is rather straightforward, but if you want to know more, see the manual section on customizing faces. --- Tags: faces, mode-line, colors ---
thread-53501
https://emacs.stackexchange.com/questions/53501
How do you type a space character in Spacemacs?
2019-11-01T02:54:20.143
# Question Title: How do you type a space character in Spacemacs? I was researching editors and I ended up stumbling upon Spacemacs and the fact that it uses the spacebar instead of traditional modifier keys. The documentation claims that this lowers the user's risk of RSI. Okay that seems reasonably plausible I guess, but it raises the question of how do you type the space character, " " if the key has a different meaning? I don't see how you could avoid needing to do that. Surprisingly, I am unable to find the answer in the documentation. This FAQ doesn't have the answer either. I'm guessing that it's somehow obvious if you use the program, since it's apparently not a commonly asked question, but I don't want to install the program just to find out. Hence I'm asking the question here. # Answer > 6 votes Spacemacs uses evil-mode which is a VI emulation layer. Evil-mode adds VI modal editing to spacemacs. In a nutshell modal editing has different modes where keybindings do different things. This is partly so that keybindings can remain short and easy to remember. In essence, the answer to your question is that you enter the space character by switching to *insert state* (Note that in emacs they actually use the term *state* instead of mode so as to not conflict with emacs modes). In insert state pressing a key inserts that key as text. This is the exact behavior "normal" modeless editors that you're used to where space just inserts space. In *normal-state*, a state typically used for navigating text space is where spacemacs uses space as a modifier key as you mention. This is only possible because spacemacs is modal. If it were not, you'd be right and there'd be no way to insert space. If you wish to learn more details about the specifics about evil, I highly recommend noctuid's evil guide. Also, this might be easier to understand once you try it. Try installing spacemacs (or for that matter you could use VI or VIM) and type **i**. **i** is the character that switches from normal state (the state you'll likely most often be in) to insert state. --- Tags: spacemacs, evil, whitespace, characters ---
thread-53500
https://emacs.stackexchange.com/questions/53500
Use projectile-find-file after switching to a notes file that's not in the project directory
2019-11-01T00:56:31.497
# Question Title: Use projectile-find-file after switching to a notes file that's not in the project directory I have a "home file" with a keyboard shortcut of C-c h (used for writing quick notes, org style) How can I still use projectile-find-file, after switching to my notes file? The issue is the notes reside in a non project git repo at ~/notes/, and on any given day I might be working on ~/project1/ ~/project2 or ~/project3 So when I invoke projectile-find-file, I am shown files in my notes folders, when what I really want to see is the app/models, app/controllers, Gemfile, etc in the ~/projectN folder of the "project of the day" The "project of the day" is the "primary project I'm focussing on for that day". It's a constant for any given day. # Answer > 2 votes You can use `projectile-switch-project`. Once you've selected your project, it invokes another action, which by default is `projectile-find-file` (but you can set it to any function with no arguments). Another option is to use `projectile-find-file-in-known-projects`, which will let you find files across all of your projects. (By the way, I hope you're using `helm-projectile`, it's great!) --- Tags: projectile ---
thread-53505
https://emacs.stackexchange.com/questions/53505
Converting a Scheme function to Emacs Lisp
2019-11-01T15:13:24.177
# Question Title: Converting a Scheme function to Emacs Lisp I am taking efforts to rephrase an example from SICP ``` #+BEGIN_SRC scheme (define (average-damp f) (lambda (x) (average x (f x)))) (define (average x y) (/ (+ x y) 2)) (define (square x) (* x x)) ((average-damp square) 10) #+END_SRC #+RESULTS: : 55 ``` After spent hours on it and got ``` (defun average-damp (f) (lambda (x) (average x (funcall f x)))) (defun average (x y) ;; Keep the float (/ (+ x y) 2.0)) (defun square (x) (* x x)) (funcall #'(average-damp 'square) 10) ``` Still report error `invalid function`, yet I am lost Could you please provide any hints? # Answer > 6 votes You are almost there. There are only two little details you need to take care of: 1. Remove the quoting `#'` in `(funcall #'(average-damp 'square) 10)`. You **do want to eval** `average-damp` and give you the actual function for the `funcall`. That is what Aquaactress correctly statet as **problem 1**. 2. For the form ``` (defun average-damp (f) (lambda (x) (average x (funcall f x)))) ``` to work you need lexical binding. The argument list of `average-damp` goes into its lexical environment. You can refer to that variable in the `lambda` that is within the lexical environment of `average-damp`. So your source block defining `average-damp` should have the `:lexical t` header argument. It should look like follows: ``` #+begin_src emacs-lisp :lexical t (defun average-damp (f) (lambda (x) (average x (funcall f x)))) #+end_src ``` # Answer > 4 votes There are two problems I found with the code you wrote. ### problem 1 ``` (funcall #'(average-damp 'square) 10) ``` `funcall` requires a function as it's first argument. However, here you're trying to pass in the unevaluated list `(average-damp 'square)` as if it were a function. But it's not, it's data. Remember that `#'` is a shorthand for `function` and `function` does not evaluate it's arguments (see anonymous functions). So it does not evaluate `(average-damp 'square)`. ### problem 2 The other problem is your definition of `average-damp`. ``` (defun average-damp (f x) (lambda (x) (average x (funcall f x)))) ``` `lambda` does not evaluate it's body. Therefore the `f` that you're passing into `average-damp` won't end up replacing the `f` in `(funcall f x)` which it seems like is what you want. As an illustration, this is what your version of `average-damp` returns when passed in with `square`. ``` (average-damp 'square) ;=> (lambda (x) (average x (funcall f x))) ``` Note that the `f` still hasn't been replaced with `square`. Consequently, when the lambda this function is called, it won't know what `f` is (unless you defined a global variable `f`) and you're bound to get a `Symbol's value as variable is void: f` error. ### solution To address problem 2 you can use backquote to ensure that the value of `average-damp`'s parameter, `f`, is replaced with `square`. And to address problem 1, you should remove the `#'`. You don't need it because you want `(average-damp 'square)` to be evaluated so that it returns a function, which is what `funcall` requires as it's first argument. ``` (defun average-damp (f) `(lambda (x) (average x (funcall #',f x)))) (funcall (average-damp 'square) 10) ;=> 55.0 ``` # Answer > 1 votes You can not enter `x` value to `(average-damp )` in your code. You should declare `x` as a function argument or define `(average-damp )` as a macro. ``` (defun average-damp (f x) (average x (funcall f x))) (defmacro average-damp2 (f) `(lambda (x) (average x (funcall ,f x)))) (defun average (x y) ;; Keep the float (/ (+ x y) 2.0)) (defun square (x) (* x x)) ;; using function (funcall #'average-damp #'square 10);; => 55.0 (average-damp #'square 10);; => 55.0 ;; using macro ((lambda (x) (average x (square x))) 10);; => 55.0 (funcall (average-damp2 #'square) 10);; => 55.0 ``` --- Tags: scheme ---
thread-53510
https://emacs.stackexchange.com/questions/53510
Org-mode: How to LaTeX export "$n$-" correctly?
2019-11-01T20:12:30.410
# Question Title: Org-mode: How to LaTeX export "$n$-" correctly? I have notes containing many of the following type of LaTeX fragments ``` $p$-adic ... $n$-th ... ``` But org-mode exports them as literal dollar sign instead of math. The problem seems to be the `-` directly following the second dollar sign. How can I change this behavior? # Answer Change the syntax of character `-` from symbol to punctuation in org-mode. You can do that by: ``` (defun my-org-change-minus-syntax-fun () (modify-syntax-entry ?- ".")) (add-hook 'org-mode-hook #'my-org-change-minus-syntax-fun) ``` You can add these lines to your init file. Note that I have running that setup for ages now with no relevant negative effects. > 3 votes # Answer Org-mode translates `$n$` to `\(n\)` in latex. You can also directly write `\(n\)-doc` in the org file and it should export just fine. > 3 votes --- Tags: org-mode, org-export, latex ---
thread-53519
https://emacs.stackexchange.com/questions/53519
Can you configure python-mode, elpy-mode to apply font-locking to imported library functions?
2019-11-02T22:37:10.627
# Question Title: Can you configure python-mode, elpy-mode to apply font-locking to imported library functions? This question is likely an expansion / duplicate of this question: how to highlight imported functions in python code? My .py file looks like this: ``` from math import floor (max(1, 8)) (floor(3.7)) ``` Screenshot for reference: **max** has font-lock applied to it. While **floor** has no font-lock applied. Questions: 1. How can I configure my setup (python-mode, elpy-mode) so that emacs recognises 'floor' as a function that font-lock should apply to. 2. If there are no answers for #1, can you recommend a package which can help? # Answer I think this might be close to what you want: The `next-import` function leverages font lock to dynamically add these keywords. Then, we add a hook function that runs that. ``` (defun next-import (limit) (when (re-search-forward "from \\(\\w+\\) import \\(\\w+\\)" limit t) (font-lock-add-keywords nil `((,(regexp-quote (match-string 2)) 0 font-lock-keyword-face))))) (defun my-import-keywords () (font-lock-add-keywords nil '((next-import (nil nil t))) t)) (add-hook 'python-mode-hook 'my-import-keywords) ``` One limitation of this is that it only font-locks from imports that have a single imported function. With some work you could probably match a comma separated list, and add each one. > 0 votes --- Tags: python, font-lock ---
thread-53524
https://emacs.stackexchange.com/questions/53524
How to enable Backtrace?
2019-11-03T05:44:46.960
# Question Title: How to enable Backtrace? I'm following the tutorial's "Making error": reproduced in the screenshot below. The manufactured error does not open the **Backtrace** window as it should. The same page says "It is possible to prevent Emacs entering the debugger in cases like this. \[...\] in the echo area and look like this: ``` Symbol's function definition is void: this ``` ". And that is indeed what I get. Thus my question: how to switch on the backtrace feature? # Answer > 4 votes In your mode line, `[...]` suggests you have an existing backtrace is running, you need to quit this one in order to trigger a new backtrace, you can do this by `C-x b *Backtrace*` and `q`. If there is something in the mode line you don't understand, you can use mouse hover to see the tooltip. For example, if you hover `[` or `]`, it will say something like "Recursive edit, type C-M-c to get out". (emacs) Recursive Edit is a feature that allow users continue to use Emacs without quit the current command, in this debugging case, you can use continue to use Emacs as usual while you're debugging Emacs itself. To quit one Recursive edit, you can use `C-M-c` (`exit-recursive-edit`, one level) or `C-]` (`abort-recursive-edit`, all levels) or `M-x top-level` (actually `q` in the end of the first paragraph runs `top-level`). --- Tags: debugging, recursive-edit ---
thread-53528
https://emacs.stackexchange.com/questions/53528
Are the graphical depictions in docs drawed in manual labour?
2019-11-03T08:52:13.513
# Question Title: Are the graphical depictions in docs drawed in manual labour? There are tons of pretty graphical depictions in the emacs(or elisp) docs such as ``` x1: -------------- -------------- -------------- | car | cdr | | car | cdr | | car | cdr | | a | o------->| b | o------->| c | nil | | | | -->| | | | | | -------------- | -------------- -------------- | x2: | -------------- | | car | cdr | | | z | o---- | | | -------------- ``` Are they portrayed in labor manner, dash by dash or with some helpful tools? I want one. # Answer Included with emacs is a basic tool called `picture-mode`: > To edit a picture made out of text characters (for example, a picture of the division of a register into fields, as a comment in a program), use the command ‘M-x picture-mode’ to enter Picture mode. > > In Picture mode, editing is based on the “quarter-plane” model of text, according to which the text characters lie studded on an area that stretches infinitely far to the right and downward. The concept of the end of a line does not exist in this model; the most you can say is where the last nonblank character on the line is found. See the manual for more information. The manual also mentions the existence of file `artist.el` that provides more sophisticated operations through `artist-mode`. Here's an extract of the docstring: > Artist lets you draw lines, squares, rectangles and poly-lines, ellipses and circles with your mouse and/or keyboard. > > \[...\] > > Drawing with the mouse: > > mouse-2 shift mouse-2 > Pops up a menu where you can select what to draw with mouse-1, and where you can do some settings (described below). > > mouse-1 shift mouse-1 > Draws lines, rectangles or poly-lines, erases, cuts, copies or pastes: > > \[...\] > 9 votes --- Tags: help, list, documentation ---
thread-53522
https://emacs.stackexchange.com/questions/53522
Why do I get free variable warnings with use-package?
2019-11-03T00:48:49.583
# Question Title: Why do I get free variable warnings with use-package? I have, for instance, this in my `.emacs`: ``` (use-package company :bind (("M-RET" . company-complete)) :demand ; load it now (better for eglot) :config (global-company-mode) (setq company-backends '(company-capf company-semantic company-dabbrev-code company-dabbrev company-etags company-keywords)) (setq company-dabbrev-downcase nil ; make case-sensitive company-dabbrev-ignore-case nil) ; make case-sensitive ) ``` The last setq gives flycheck free-variable warnings for `company-dabbrev-downcase` and `company-dabbrev-ignore-case` even though they are both defined with `defcustom` in `company-mode`. Should I just ignore these warnings, or should I do something differently to fix them? # Answer > 3 votes You could try the :defines keyword in `use-package`. According to `use-package`'s README it's for "introduce\[ing\] dummy variable and function declarations solely for the sake of the byte-compiler". ``` (use-package company :defines company-dabbrev-downcase company-dabbrev-ignore-case ...) ``` --- Tags: use-package ---
thread-53515
https://emacs.stackexchange.com/questions/53515
MU4E: Force myself to check mail once and only once?
2019-11-02T14:02:47.763
# Question Title: MU4E: Force myself to check mail once and only once? Emacs workflow is smooth. Usually we want it smoother. But I would like to make it less smooth.. This might be a strange question. I use emacs and mu4e to deal with my mails. However, the workflow is so smooth that sometimes I found myself checking it impulsively without thinking.. I wonder if there's a way to tweak this workflow (by adding some elips code?) to restrict myself from checking it too often! I'm pretty new to emacs, and would like to learn some practical elisp-codes. This could be my first one to start with. Any pointers to relevant tutorial / documentations are appreciated. # Answer > 1 votes Following @John's advice, I wrote a primitive shell script that checks the difference between current time and the last check time. If the difference is not larger than `$mercy`, then it won't proceed. Otherwise, mail will be checked and time will be recorded in the same file (unit: linux epoch time). ``` #!/bin/bash ### Content ### # This shell script restricts myself from # impulsively checking my email too frequently. # # After running mail check command, the current time will # be recorded in the end of this script. ### Config ### checkMailCommand="mbsync -c ~/.emacs.d/.mbsyncrc gmail" mercy=28800 # in second ### Main Script ### scriptDir=$HOME/.scripts/checkmail currentTime=$(date '+%s' -d $(date -Is)) lastCheckTime=$(cat $scriptDir | tail -1 | sed '/^\# */!d; s///;q') timeDiff=$(($currentTime - $lastCheckTime)) if [[ $timeDiff -gt $mercy ]]; then $checkMailCommand echo "# $currentTime" >> $scriptDir else echo "You check your mail too frequently --" echo "check it again $(($mercy - $timeDiff)) seconds later!" echo " or change config in $scriptDir." echo "Exiting in 5 seconds.." sleep 5 fi exit ### checkmail history (unit: linux epoch time) ### # 1572789737 ``` --- Tags: org-mode, email ---
thread-39434
https://emacs.stackexchange.com/questions/39434
Evil - don't yank with only whitespace to register
2018-03-15T13:22:11.147
# Question Title: Evil - don't yank with only whitespace to register How can I configure Emacs in Evil mode to delete an empty line (`d d`) without copying it but still copy it when deleting a non-empty line? # Answer You can try this. ``` (evil-define-operator evil-delete-without-register-if-whitespace (beg end type reg yank-handler) (interactive "<R><y>") (let ((text (replace-regexp-in-string "\n" "" (filter-buffer-substring beg end)))) (if (string-match-p "^\\s-*$" text) (evil-delete beg end type ?_) (evil-delete beg end type reg yank-handler)))) ``` Followed by rebinding `d` with it: ``` (define-key evil-normal-state-map "d" #'evil-delete-without-register-if-whitespace) ``` I found this looking at this emacs configuration. What you're asking for does not require knowledge of spacemacs. It involves evil, a package that is included in spacemacs. Deleting in `evil` is an operator. This defines a new operator to replace the default one; the main difference being that it checks to see if what's being added to the register is whitespace. If it is it adds nothing, otherwise it adds it to the register. To learn more about evil check out noctuid's evil guide. Note: that this is not *strictly* what you asked for because you spoke of not adding *empty lines* to the register while this doesn't add whitespace in general to the register (even if not a full empty line). But I suspect you'd actually find this more useful. > 3 votes # Answer Here is what I use: ``` (define-key evil-normal-state-map "x" 'delete-forward-char) (define-key evil-normal-state-map "X" 'delete-backward-char) ``` Explanation: * `delete-forward/backward-char` is the function to delete something **without** yanking it to any register. * **`Vx`**: this would select a line (**`V`**) then delete it (**`x`**) without yanking it, so it might be what you want when you delete a blank line. * **`vexP`**: select a word (**`ve`**) and change it (**`xP`**) with content in the register **without** changing the content of the register, ie. paste the register over a word **without** changing the content of the register. This is quite usefull, for example, when you have a text `foo bar barr barr barrr` and you want to change all `bar` `barr` `barrr` to `foo`, then just yank `foo` then paste that `foo` to other words. Logic: * While a region is selected, then **`d`** would do the same job as original **`x`**: “delete and yank”. So, change **`x`** to “delete **without** yank” is fine, without limiting capability at all. For example, when you want to delete a line and yank it, press **`Vd`** or **`dd`**. * If there is no region selected, then **`vd`** would delete one character and yank. Or, you can just press **`delete`** to do the same job. So, again, change **`x`** to delete **without** yank is also fine. Generally you do not need to delete and yank only one character anyway. (sorry for my broken English) > 0 votes --- Tags: evil, copy-paste, deletion ---
thread-35758
https://emacs.stackexchange.com/questions/35758
VC status behavior in ibuffer-vc
2017-09-26T13:13:18.683
# Question Title: VC status behavior in ibuffer-vc I use ibuffer-vc, a replacement for `list-buffer` that displays the VC status of the listed files. I noted that the VC status stays as "edited" even after I push my changes. That is, the VC status does not differentiate between the following two situations: (1) I modified a file and I still have to push my changes; and (2) I pushed my changes and the local and remote versions are the same. The VC status for both situations is "edited". However, I would like to differentiate between these two types of situations. **My question is**: Assuming that this is the typical behavior of VC status, is there a way of changing my Emacs config so that the VC status could differentiate between the two situations cited above? *Note*: I use git and magit for my version control. My understanding is that ibuffer-vc uses `vc-state` to get the status of a file. # Answer > 2 votes Use `vc-refresh-state` like this to get rid of the `edited` vc-state: ``` (defun vc-state-refresh-post-command-hook () "Check if command in `this-command' was executed, then run `vc-refresh-state'" (when (memq this-command '(other-window kill-buffer ido-kill-buffer ido-switch-buffer)) (vc-refresh-state))) (add-hook 'after-save-hook 'vc-refresh-state) (add-hook 'after-revert-hook 'vc-refresh-state) (add-hook 'post-command-hook #'vc-state-refresh-post-command-hook) ``` You can change the sentence `'(other-window kill-buffer ido-kill-buffer ido-switch-buffer)` to use a variable you can redefine in your configuration with the true commands you use (say, `ace-window` instead of `other-window` because you use it, etc). # Answer > 0 votes I have a better way of doing this because I don't like putting unnecessary things in the `post-command-hook`. Then, they are run every time you run a command. I defined the following function that only takes buffers controlled by a vc backend and refreshes all of them. Then I just set this to a keybinding in ibuffer-mode-map. I use a prefix key for all my commands in ibuffer, which is set to `h` but just change the keybinding for `jj/ibuffer-vc-refresh-state`. Also, I set it to run in an ibuffer-mode-hook, but if you have a ton of buffers open this might cause a bit of a lag. ``` (eval-after-load "ibuffer-vc" '(progn (defun jj/vc-refresh-state-all-buffers () "Refresh all vc buffer statuses by calling `vc-refresh-state` on each one if it has an associated vc backend." (interactive) (dolist (buf (buffer-list)) (let ((file-name (with-current-buffer buf (file-truename (or buffer-file-name default-directory))))) (when (ibuffer-vc--include-file-p file-name) (let ((backend (ibuffer-vc--deduce-backend file-name))) (when backend (with-current-buffer buf (vc-refresh-state)) )))))) (defun jj/ibuffer-vc-refresh-state () (interactive) (jj/vc-refresh-state-all-buffers) (ibuffer-redisplay)) )) (add-hook 'ibuffer-mode-hook 'jj/ibuffer-vc-refresh-state) (define-prefix-command 'ibuffer-h-prefix-map) (define-key ibuffer-mode-map (kbd "h") 'ibuffer-h-prefix-map) (define-key ibuffer-h-prefix-map (kbd "h") 'describe-mode) (define-key ibuffer-h-prefix-map (kbd "r") 'jj/ibuffer-vc-refresh-state) )) ``` Also, if you use use-package then the below is my setup: ``` (use-package ibuffer :bind ( :map ibuffer-mode-map :prefix-map ibuffer-h-prefix-map :prefix "h" ("h" . describe-mode) ("g" . ibuffer-clear-filter-groups) ("r" . ibuffer-clear-filter-groups))) (use-package ibuffer-vc :bind (:map ibuffer-h-prefix-map ("v" . ibuffer-vc-set-filter-groups-by-vc-root) ("V" . jj/ibuffer-vc-refresh-state)) :config (defun jj/vc-refresh-state-all-buffers () "Refresh all vc buffer statuses by calling `vc-refresh-state` on each one if it has an associated vc backend. Uses functions from `ibuffer-vc`, so decouple these functions if you need to use this without loading ibuffer-vc." (interactive) (dolist (buf (buffer-list)) (let ((file-name (with-current-buffer buf (file-truename (or buffer-file-name default-directory))))) (when (ibuffer-vc--include-file-p file-name) (let ((backend (ibuffer-vc--deduce-backend file-name))) (when backend (with-current-buffer buf (vc-refresh-state)) )))))) (defun jj/ibuffer-vc-refresh-state () "Refresh all vc buffer statuses and redisplay to update the current status in ibuffer." (interactive) (jj/vc-refresh-state-all-buffers) (ibuffer-redisplay)) (add-hook 'ibuffer-mode-hook 'jj/ibuffer-vc-refresh-state) ) ``` --- Tags: version-control, ibuffer, vc ---
thread-53462
https://emacs.stackexchange.com/questions/53462
font-lock keywords and syntax-table mutually interfering
2019-10-30T00:30:43.853
# Question Title: font-lock keywords and syntax-table mutually interfering I would like to define something that font-locks a bit like a new sort of string-literal/comment. I might write: ``` (font-lock-add-keywords 'emacs-lisp-mode (list '("<<.*>>" 0 'my-custom-face prepend))) ``` I'm using `'emacs-lisp-mode` as my example just because it's an existing mode with syntax-table driven string literal and comment highlighting. As per How to highlight specific keywords inside strings/quotes? the `prepend` above ensures that my new delimiters take precedence, so that ``` <<"foo" bar>> ``` font locks entirely with the new face. I'm happy enough with that. But I would like ``` ; some comment text <<foo>> ``` to highlight with the comment colors, and for ``` "some string stuff <<foo>>" ``` to highlight entirely with string-literal colors. Unfortunately, I get the custom face appearing within the literals and comments, which is distracting and arguably wrong (certainly, string literals and comments are mutually compatible). How do I get the outermost delimiters to take precedence? (Annoyingly, if I don't have the `prepend`, the syntax-table stuff takes precedence particularly dramatically: something like `<<foo bar>>` is fine, but `<<"foo" bar>>` has the `"foo"` in string literal colors, and doesn't color the delimiters or the `bar` at all.) # Answer > 1 votes I don't particularly like the solution, but I used a function matcher that called `re-search-forward` to find the start delimiter, and then checked the return code of `syntax-ppss` to see if the position was in a comment or string literal. This looped forward until it ran out of room (*i.e.,* respecting the provided `limit` parameter), or found a left-delimiter not inside comment or string syntax. Having done that, it could then search forward for the right delimiter and then return the appropriate match-data if it found one. --- Tags: font-lock, syntax-highlighting, syntax-table ---
thread-28135
https://emacs.stackexchange.com/questions/28135
In Evil mode, how can I prevent adding to the kill ring when I yank text, visual mode over other text, then paste over?
2016-10-26T03:33:48.420
# Question Title: In Evil mode, how can I prevent adding to the kill ring when I yank text, visual mode over other text, then paste over? If I have `text1 text2`, I yank `text1` with `yw` then I highlight `text2` with `vw` and paste overwrite that text with `p`, my kill ring now has `text2`. I'd prefer if `text2` wasn't added to my kill ring because next time I paste text, Emacs will paste `text2` which I inadvertently copied. Same question for `x` (which deletes 1 character), the deleted character goes into my kill ring. `p` then `C-p` to cycle through the kill ring isn't ideal. I paste the text again, the over written text is continually added onto the kill ring leading to more `C-p` presses to get the original text. Ideally I'm hoping to disable or redefine p when over writing text to not add to the kill ring # Answer > 5 votes After yank `text1`, the text is saved in both register `"` and `0`: ``` "" text1 "0 text1 "1 ... ``` When paste with `p`, you actually got `text1` from register `"`, at the same time, the killed text is saved in `"`: ``` "" text2 "0 text1 "1 ... ``` So, if you want paste `text1` next time, you should press `"0p` instead of `p`, or replace the default key binding: ``` (defun evil-paste-after-from-0 () (interactive) (let ((evil-this-register ?0)) (call-interactively 'evil-paste-after))) (define-key evil-visual-state-map "p" 'evil-paste-after-from-0) ``` # Answer > 11 votes The suggestion in @gongqj's answer changes the behavior of paste so that cut text (via `d`) no longer gets pasted. This does not seem like what you want given your comment: > Ideally pasted over text is not added to the kill ring but we get killed text (not from pasting over, i.e. `D`) then it'd be nice to paste that on visual state paste. If your real goal is to avoid adding the replaced text to the kill ring upon pressing `p`, you could add the following: ``` (setq-default evil-kill-on-visual-paste nil) ``` The relevant lines are in the `evil-visual-paste` definition in `evil-commands`: ``` (when evil-kill-on-visual-paste (kill-new new-kill)) ``` # Answer > 1 votes Here is my solution: Press **`xP`** to paste over the region without changing the kill ring. ``` (define-key evil-normal-state-map "x" 'delete-forward-char) ; delete to the black hole (define-key evil-normal-state-map "X" 'delete-backward-char) ``` Explanation in details: https://emacs.stackexchange.com/a/53536/18298 # Answer > 0 votes I'm pretty new to emacs, so I'm not sure about the terminology, but using vim-speak (and this works in evil-mode), yanking populates the `0` register, while deleting text will populate the `1`-`9` registers, pushing them along as you delete text. So in your case, you should be able to access your yanked text using `"0p`, even after deleting something else. --- Tags: evil, yank, kill-ring ---
thread-53539
https://emacs.stackexchange.com/questions/53539
eshell grep thinks options are patterns on windows
2019-11-03T18:12:48.660
# Question Title: eshell grep thinks options are patterns on windows I'm using Emacs on windows, and was trying to run grep from within eshell (M-x eshell). The default shell through M-x is cmd.exe, but eshell has linux utilities so I'm trying to use eshell. Now, when i try grep with typical arguments, say -i to a case insensitive search, I get a message saying 'pattern "-i" not found'. So, the grep tool seems to think the option is the pattern. But if I give the exact patter without any options, and the exact filename to search in, it works. For example, this works: ``` > grep "Hello" main.c ``` It opens up a new buffer with the results which I can click on, or browse through This is quite inconvenient. Any help to fix this would be appreciated. Side note, I've tried using the WSL ubuntu bash and that works fine, except the PROMPT looks all messed up, and the results of grep are not clickable. # Answer Looks like Emacs cannot find the external `grep` tool and uses its internal `eshell-poor-mans-grep`. It interprets the first argument as expression and all other arguments as files. Here is the doc string of `poor-mans-grep` which pityingly does not clarify the arguments: > `eshell-poor-mans-grep` is a compiled Lisp function in `‘em-unix.el’`. > > `(eshell-poor-mans-grep ARGS)` > > A poor version of grep that opens every file and uses `‘occur’`. This eats up memory, since it leaves the buffers open (to speed future searches), and it’s very slow. But, if your system has no grep available... If you want to use an external grep you need to install it and make it known to Emacs (e.g., by correcting the PATH environment variable). One possible choice is mingw-w64. Note that Emacs has its own powerful grep tools which do not depend on external tools like `xah-find` and `elgrep` on melpa. > 2 votes --- Tags: eshell, grep ---
thread-53521
https://emacs.stackexchange.com/questions/53521
Avoid installing package to ".emacs.d/elpa/" directory
2019-11-03T00:41:20.617
# Question Title: Avoid installing package to ".emacs.d/elpa/" directory I install yasnippet from the repository using the package manager and I add the corresponding directory to the load path before (use-package yasnippet): ``` ;; Add all subdirs in site-lisp to the load-path (let ((default-directory "/usr/share/emacs/site-lisp/")) (normal-top-level-add-subdirs-to-load-path)) ``` but when I start emacs it installs the package (despite of the load path) in the ".emacs.d/elpa/" directory. Is there a way to avoid it? # Answer > 0 votes When I execute the following lisp code: ``` (print load-path) ``` I get the list of all directories in the load path including /usr/share/emacs/site-lisp/ with all subdirectories. I've tried the following: ``` ;; Undo Tree ;; using C-x u to choose and q to quit/undo/ to the step (use-package undo-tree :ensure t :init (global-undo-tree-mode) ) ``` and the package was automatically installed in "~/.emacs.d/elpa/". but when I've commented the ":ensure t" and delete the package from ".../elpa" but installed wit the package manager to "/usr/share/emacs/site-lisp/" I still had the undo-tree package but from the common directory. ``` (use-package undo-tree :init (progn (require 'undo-tree) (global-undo-tree-mode) )) ``` Problem solved! --- Tags: use-package, load-path ---
thread-53531
https://emacs.stackexchange.com/questions/53531
Emacs and EXWM window manager. Switch between applications and emacs buffer
2019-11-03T09:34:54.877
# Question Title: Emacs and EXWM window manager. Switch between applications and emacs buffer I'm trying to use Emacs as my main window manager, by using EXWM: > https://github.com/ch11ng/exwm . Installation works fine. However, my default Emacs key binding to move between splits is: Shift + Arrow keys. This doesnt seem to work if you have say Firefox on the left split, and say an Emac buffers like scratch buffer on the right (a vertical split). I can do Shift+ Left and it focuses the cursor on the Firefox instance. However, I cant seem to move from Firefox back to scratch buffer, i.e. doing Shift + Right doesnt work. Please let me know how to get this to work. I can just use the mouse to click the buffer but I'd rather use the keyboard. # Answer The reason your emacs bindings don't work in firefox is because they are not bound through EXWM. EXWM is the medium emacs uses to communicate to x-windows so you need to set the bindings through it. EXWM by default enables only a subset of your emacs bindings are available in x windows (and only in line-mode). Like in Emacs, there are two kinds of bindings in EXWM, global and local. Based on your question it seems like you'd like these bindings to always work in x windows so I would recommend global binding. To remedy this you need to set `exwm-input-global-keys` to the bindings you want. ``` (setq exwm-input-global-keys `((,(kbd "S-<up>") . windmove-up) (,(kbd "S-<down>") . windmove-down) (,(kbd "S-<left>") . windmove-left) (,(kbd "S-<right>") . windmove-right))) ``` This will set the bindings in Emacs and in all x windows. Sidenote: some modes like `org-mode` have these keys bound to something. So in that case you'd have to override those keys. > 2 votes --- Tags: exwm ---
thread-28810
https://emacs.stackexchange.com/questions/28810
Associate Emacs with 7zip for .odt export?
2016-11-21T18:48:28.207
# Question Title: Associate Emacs with 7zip for .odt export? After asking this question, I have downloaded 7zip for Windows. When I try to export to .odt, I am still getting this: "OpenDocument export failed: Executable "zip" needed for creating OpenDocument files." What is my next step? # Answer > 1 votes After you have associated 7zip with files that have a give extension (e.g. `.zip`), in the usual way for MS Windows (I don't think that's your question), you can have Emacs open such files using that associated program. To do that, start with the Emacs Wiki Category W32. There you will find, among other things: * MS Shell Execute \- tell Emacs to use Windows programs associated with given file types * Dired+ \- open files from Dired using the associated Windows programs * Bookmark+ \- use Windows file associations as bookmark actions # Answer > 1 votes Might be a little late for an answer but here it goes anyway. If you search `ox-odt.el` you can see that the error message you're getting comes from `org-odt--export-wrap` which is the macro called by `org-odt-export-to-odf` and `org-odt-export-to-odt` to create the actual `ODT` file. Inside `ox-odt--export-wrap` there is this little piece of code: ``` (unless (executable-find "zip") ;; Not at all OSes ship with zip by default (error "Executable \"zip\" needed for creating OpenDocument files")) ``` that will prevent the process to continue unless the `zip` excecutable exists in your `PATH`. Also a few lines below there's this: ``` (cmds `(("zip" "-mX0" ,target-name "mimetype") ("zip" "-rmTq" ,target-name "."))) ``` which defines how to call the `zip` command in order to create an `ODT` file. Considering all of the above you have at least three options here: 1. Modify the `ox-odt.el` file so it uses the `7z` command instead of `zip`. 2. Wrap your calls to `7z` into some kind of `zip.cmd` command. 3. Download `zip` for Windows, in fact you should get GNU on Windows or Cygwin, any of them will save you a lot of troubles while working with Emacs. # Answer > 0 votes If you just need export `org` to `odt`, see org-mode zip needed, how to over come?. If you need 7-Zip as your zip program, you need download 7-Zip Extra: standalone console version and put 7-zip extra in Windows `%PATH%`. Call `(make-zip-bat (executable-find "7za"))` to generate `zip.bat` and put it in your `%PATH%` and `exec-path`. `zip.bat` for `7za` looks like: ``` @echo off REM zip.bat for 7za on Windows REM generated by More Reasonable Emacs https://github.com/junjiemars/.emacs.d REM local variable declaration setlocal EnableDelayedExpansion set _OPT=%* set _ZIP= set _ARGV= REM parsing command line arguments :getopt if "%1"=="-mX0" set _OPT=%_OPT:-mX0=-mx0% & shift & goto :getopt if "%1"=="-0" set _OPT=%_OPT:-0=-mx0% & shift & goto :getopt if "%1"=="-9" set _OPT=%_OPT:-9=-mx9% & shift & goto :getopt REM ignore options if "%1"=="-r" set _OPT=%_OPT:-r=% & shift & goto :getopt if "%1"=="--filesync" set _OPT=%_OPT:--filesync=% & shift & goto :getopt if "%1"=="-rmTq" set _OPT=%_OPT:-rmTq=% & shift & goto :getopt REM extract zip and argv if not "%1"=="" ( if "%_ZIP%"=="" ( if "%_ARGV%"=="" ( set _ZIP=%1 ) ) else ( set _ARGV=%_ARGV% %1 ) set _OPT=!_OPT:%1=! shift goto :getopt ) REM 7za call 7za a %_OPT% -tzip -- %_ZIP% %_ARGV% if exist %_ZIP% ( 7za d %_OPT% -tzip -- %_ZIP% %_ZIP% ) ``` Now, export `org` to `odt` should works, see more More Reasonable Emacs: zip program # Answer > 0 votes > When I try to export to .odt, I am still getting this: "OpenDocument export failed: Executable "zip" needed for creating OpenDocument files." Based on https://lists.gnu.org/archive/html/emacs-orgmode/2013-04/msg00489.html, you can use the zip package from following links ``` http://gnuwin32.sourceforge.net/packages.html http://gnuwin32.sourceforge.net/packages/zip.htm ``` --- Based on https://lists.gnu.org/archive/html/emacs-orgmode/2013-04/msg00538.html, you may also use the `zip` executable from https://fossies.org/windows/misc/zip300xn.zip/ --- Tags: odt ---
thread-45710
https://emacs.stackexchange.com/questions/45710
Run custom bash functions with M-!
2018-11-02T17:22:43.570
# Question Title: Run custom bash functions with M-! I have a few custom bash functions that are defined is some file and are made available to me in regular terminals via the line ``` . "/path/Custom Bash Functions.sh" ``` in my `~/.bashrc`. However, Emacs does not recognize them. I don't really care whether they are available in any terminal emulator inside Emacs. I only care about them working when I hit `M-!`. This answer suggests setting `shell-command-switch` to `"-ic"` (adding switch `i` to the default). However, all this seemingly results in is that the output of all commands I execute via `M-!` are preceded by: ``` bash: cannot set terminal process group (-1): Inappropriate ioctl for device bash: no job control in this shell ``` I still can't execute custom bash functions. Auto-complete for them doesn't work either. Maybe this is because I use a newer version. I use the latest version on the master branch of Emacs' git repo (pulled the latest changes and installed them less than 2 hours ago). # Answer I just put my desired alias(es) in `.zshenv` instead of `.zshrc`, so that Emacs would pick up on the alias for sure, regardless of whether the shell was interactive. My main reason for doing this was because when I set `shell-command-switch` to `"-ic"`, I ran into trouble with the output of `M-&` because it spawns asyncrhonous subprocesses. For example, running `du -sh` on a directory via `dired-do-async-shell-command` (or `&`) yields the following output: ``` [1] 12345 100M directory_name [1] + done du -sh directory_name ``` As you can see, there is extraneous output surrounding the actual output of `du -sh`. This is apparently due to it running as an interactive shell. So I instead just gave up on making it interactive and placed my desired alias into `.zshenv` instead. > 2 votes --- Tags: shell, shell-command ---
thread-53555
https://emacs.stackexchange.com/questions/53555
Convert a formmated region to org table
2019-11-05T07:52:08.550
# Question Title: Convert a formmated region to org table I tried convert the following region to table ``` Attribute Description form A dictionary with all the form fields submitted with the request. args A dictionary with all the arguments passed in the query string of the URL. values A dictionary that combines the values in form and args. cookies A dictionary with all the cookies included in the request. headers A dictionary with all the HTTP headers included in the request. files A dictionary with all the file uploads included with the request. get_data() Returns the buffered data from the request body. get_json() Returns a Python dictionary with the parsed JSON included in the body of the request. blueprint The name of the Flask blueprint that is handling the request. Blueprints are introduced in Chapter 7. endpoint The name of the Flask endpoint that is handling the request. Flask uses the name of the view function as the endpoint name for a route. method The HTTP request method, such as GET or POST. scheme The URL scheme (http or https). is_secure() Returns True if the request came through a secure (HTTPS) connection. host The host defined in the request, including the port number if given by the client. path The path portion of the URL. query_string The query string portion of the URL, as a raw binary value. full_path The path and query string portions of the URL. url The complete URL requested by the client. base_url Same as url, but without the query string component. remote_addr The IP address of the client. environ The raw WSGI environment dictionary for the request. ``` Tried multiple times to convert the region to table but failed. Could please provide any hints? # Answer From the documentation: > ‘C-c | (org-table-create-or-convert-from-region)’ > > ``` > Convert the active region to a table. If every line contains at > least one TAB character, the function assumes that the material is > tab separated. If every line contains a comma, comma-separated > values (CSV) are assumed. If not, lines are split at whitespace > into fields. You can use a prefix argument to force a specific > separator: ‘C-u’ forces CSV, ‘C-u C-u’ forces TAB, ‘C-u C-u C-u’ > will prompt for a regular expression to match the separator, and a > numeric argument N indicates that at least N consecutive spaces, or > alternatively a TAB will be the separator. > > ``` So you first need to set the region to contain the block of test (`C-SPACE` at begin of first line, then move point at end of last line) and then you can do the following: `C-u 2 C-c |` That is, specify that the columns are separated by at least two consecutive spaces (or a TAB). For more complex separators, one can use a regular expression to specify column separators (here the regexp specifies a sequence of at least two spaces): `C-u C-u C-u C-c| [[:blank:]][[:blank:]]+ RET` This command itself calls command `org-table-convert-region` which is available from the `Tbl` menu in the menu bar (\*1). --- (\*1) However, to provide arguments, you have to proceed as for the two examples above, replacing`C-c |` by a click on this menu entry, so the menu entry is usefull only for the case where the command is able to discover the column separators (TAB, comma, or whitespace). > 6 votes --- Tags: org-mode ---
thread-53453
https://emacs.stackexchange.com/questions/53453
Swap Shift/non-shift key behavior for particular mode
2019-10-29T17:37:38.743
# Question Title: Swap Shift/non-shift key behavior for particular mode I want to press `-` on my keyboard and have `_` be inserted and vice-versa *only for a particular mode*. The following does this globally using the `post-self-insert-hook`, It checks the character just inserted and makes a replacement accordingly: ``` (defun my-swap-dash () "Make dash insert and underscore and vice-versa." (interactive) (let ((just-inserted (char-before (point)))) (cond ((equal just-inserted 45) ;; '-' (progn (delete-backward-char 1) (insert "_"))) ((equal just-inserted 95) ;; '_' (progn (delete-backward-char 1) (insert "-")))))) (add-hook 'post-self-insert-hook #'my-swap-dash) ``` How could I get this same behavior for *only* `python-mode`? My first thought is to define a minor mode and then enable it through the `python-mode-hook`. However, using the `post-self-insert-hook` means the replacement must happen globally. As a work-around, I created a method of toggling the behavior manually: ``` (defvar swap-dash-state-p nil "Is swap-undash enabled?") (defun toggle-swap-dash () "Toggle `my-swap-dash'." (interactive) (if swap-dash-state-p (progn (remove-hook 'post-self-insert-hook #'my-swap-dash) (setq swap-dash-state-p nil)) (progn (add-hook 'post-self-insert-hook #'my-swap-dash) (setq swap-dash-state-p t)))) ``` Thoughts and coding style comments welcome! # Answer > 4 votes You can simply map the keys `-` and `_` to do what you want in python mode: ``` (defun insert-underscore () "Guess what!" (interactive) (insert "_")) (defun insert-hyphen () "You know it!" (interactive) (insert "-")) (defun python-remap-hyphen-and-underscore () (define-key python-mode-map "-" 'insert-underscore) (define-key python-mode-map "_" 'insert-hyphen)) (if (boundp 'python-mode-map) (python-remap-hyphen-and-underscore) (add-hook 'python-mode-hook 'python-remap-hyphen-and-underscore)) ``` What we do here is to define two commands to insert an underscore and an hyphen, then a function to associate these commands to the `-` and `_` keys in `python-mode-map` (the variable that holds the key bindings in `python-mode`). If you insert this snippet in your init file, before python-mode is loaded, you can replace the last three lines simply by ``` (add-hook 'python-mode-hook 'python-remap-hyphen-and-underscore) ``` # Answer > 1 votes What I actually implemented is a modification of @JeanPierre's solution: ``` (defun my-remap-dash-and-underscore () (interactive) (define-key python-mode-map "-" #'(lambda () (interactive) (insert "_"))) (define-key python-mode-map "_" #'(lambda () (interactive) (insert "-")))) (defun my-undo-remap-dash-and-underscore () (interactive) (define-key python-mode-map "-" 'self-insert-command) (define-key python-mode-map "_" 'self-insert-command)) (add-hook 'python-mode-hook 'my-remap-dash-and-underscore) ``` This sets the swap up by default in `python-mode`. It can be toggled manually via the appropriate function with `M-x`. # Answer > 1 votes you can achieve this with evil-swap-keys.el (which is not tied to `evil`): ``` (global-evil-swap-keys-mode) (add-hook 'python-mode-hook #'evil-swap-keys-swap-underscore-dash) ``` --- Tags: key-bindings, keymap, minor-mode ---
thread-53558
https://emacs.stackexchange.com/questions/53558
Active Timestamps with org-add-note
2019-11-05T08:57:12.370
# Question Title: Active Timestamps with org-add-note If you add a Note to a TODO task with ***C-c C-z*** it adds an inactive timestamp to the note. This way it does not show up in the agenda view. ``` - Note taken on [2019-11-05 Di 09:32] \\ ``` I want ***org-add-note*** to create active Timestamps ``` - Note taken on <2019-11-05 Di 09:32> \\ ``` Is there a way to enable this? # Answer You can customize `org-log-note-headings`to change this. Using `"Note taken on %T"` instead of `"Note taken on %t"` should make the timestamps active. > 2 votes --- Tags: org-mode ---
thread-19983
https://emacs.stackexchange.com/questions/19983
Set author per repository
2016-01-31T20:09:20.320
# Question Title: Set author per repository I work on both work and personal projects on my machine, and for my work projects, I prefer to use my work email, and vice versa. In shell, I use direnv to set `GIT_COMMITTER_EMAIL` and `GIT_AUTHOR_EMAIL`. How do I achieve something like this in magit? # Answer > 7 votes One way to do this is to set the author configuration in `.git/config` in each repository, in the same format as in `~/.gitconfig`, i.e.: ``` [user] name = My Name email = me@example.com ``` # Answer > 7 votes you can do this with one-time git configuration. you can use it for `email` and so on, but also for using a different `ssh` key: in `~/.gitconfig`: ``` [includeIf "gitdir:~/work/"] path = .gitconfig_work ``` in `~/.gitconfig_work`: ``` [user] email = … [core] sshCommand = ssh -i ~/.ssh/id_…_work -o 'IdentitiesOnly yes' ``` explanation: this makes git use another configuration, which specifies `email` and a ssh key (which you should create with a different filename and then add to your github account) when running git anywhere below the `~/work` directory. in practice, this one time configuration makes it work for all current and future clones. # Answer > 4 votes Anoter useful option is the git-identity package. From its README: > This Emacs package lets you manage local Git identities, i.e. user.name and user.email options in .git/config, inside Emacs. It can be useful if you satisfy all of the following conditions: > > ``` > - You have multiple Git identities on the same machine(s). > - You use Emacs. > - You (almost always) use magit for Git operations on your machine(s). > > ``` # Answer > 2 votes Same effective answer as @legoscia, but instead of modifying the file, I find that if you do ``` git config user.email me@example.com git config user.name "My Name" ``` It sets the local config, i.e `.git/config` If you add the flag `--global` then it modifies your global config. Thus you can have different name/email setup per repository, and can even check them by running `git config user.email`. When called without any arguements, it works as a `GET` command. --- Tags: magit, git, project ---
thread-53562
https://emacs.stackexchange.com/questions/53562
Do not show created timestamps in agenda
2019-11-05T10:58:02.717
# Question Title: Do not show created timestamps in agenda I'm using a package that automatically adds a `CREATED` property with a current time stamp to every item I create. I would like these timestamps not to appear in my agenda. To demonstrate, here is a minimal example. The whole `init.el` reads: ``` (global-set-key "\C-ca" 'org-agenda) (setq org-agenda-files (list "~/org.org")) ``` File `~\org.org` contains: ``` * TODO Created Today :PROPERTIES: :CREATED: <2019-11-05 Tue 11:00> :END: * TODO Scheduled Today SCHEDULED: <2019-11-05 Tue> * TODO Deadline Tomorrow DEADLINE: <2019-11-06 Wed> ``` With that, pressing `C-c a a` (i.e., conjuring up the default agenda) gives me this: I like the fact that it tells me what's scheduled when and when which deadlines are, but having this huge time table to show me when I created which items is just unnecessary. Is there a way of getting rid of that? The documentation of the agenda says that it shows "the entries for each day". It is very unspecific what it considers to be "an entry for a day". Is there a way of controlling this? Also note that I did not switch the agenda into "logbook mode". In fact, in my example, it shows the exact same thing in "logbook mode". However, since the `CREATED` timestamp is not in the `LOGBOOK` drawer, it should not be affected by logbook mode anyways, right? # Answer > 1 votes Okay, I figured it out (by chance, by reading a different question about time stamps that just came up): Apparently, the agenda just includes everything that contains an "active time stamp". An active time stamp is any time stamp in angular brackets. Thus, if I replace in my timestamp-inserting code ``` (setq timestr (format-time-string (cdr org-time-stamp-formats))) ``` with ``` (setq timestr (format-time-string "[%Y-%m-%d %a %H:%M]")) ``` then inactive time stamps (in square brackets) are inserted, which do not show up in my agenda anymore. --- Tags: org-mode, org-agenda ---
thread-53566
https://emacs.stackexchange.com/questions/53566
Magit doesn't prompt for SSH key after OS upgrade?
2019-11-05T14:26:23.447
# Question Title: Magit doesn't prompt for SSH key after OS upgrade? **Q:** magit no longer prompts me for my ssh key when pushing/pulling; how do I fix it? After an OS upgrade (Lubuntu 19.04 to 19.10), I can no longer push to origin from magit. Pushing to origin results in a process that hangs when invoked from magit; I have to kill that process manually. The problem seems to be that Emacs no longer prompts me for my public ssh key, and just sits there humming quietly to myself while git waits for it. Pushing from a terminal using the same command that magit uses works as expected, since I can enter my ssh key unimpeded. How do I figure out what could be causing this to happen? # Answer > 1 votes This is due to an update to OpenSSH 8.1. that changes the confirmation prompt when connecting to a new remote. The issue has been fixed a couple weeks ago. Updating magit should be enough. --- Tags: magit ---
thread-31086
https://emacs.stackexchange.com/questions/31086
How to load personal prolog.el only if system's one is outdated?
2017-02-27T14:03:09.020
# Question Title: How to load personal prolog.el only if system's one is outdated? I need to use a version of `prolog.el` not older than 1.25, so I defined the function `maybe-reload-prolog-el`: ``` (defun maybe-reload-prolog-el () (when (version< prolog-mode-version "1.25") (add-to-list 'load-path (file-name-as-directory (concat my-lib-path "prolog-el"))) (load-library "prolog")))) ``` ...which adds the path to my personal copy of `prolog.el` to `load-path` (and then reloads `prolog`) if it detects that `prolog-mode-version` is too old <sup>1</sup>. Then I put a call to `maybe-reload-prolog-el` in a hook I already had for `prolog-mode`: ``` (add-hook 'prolog-mode-hook (lambda () ;; ;; some keyboard settings, like ;; (local-set-key [f10] ...) ;; (local-set-key [f9] ...) ;; ;; etc (**maybe-reload-prolog-el**))) ``` The main problem with this approach is that `prolog.el` is responsible for more than `prolog-mode`. For example, it has the code for the autoloaded function `run-prolog`, which I use to run a Prolog sub-process in an Emacs buffer. AFAICT, `prolog-mode-hook` does not get triggered when I run `run-prolog`, so I end up running an outdated version of it. **Is there some way to trigger `maybe-reload-prolog-el` *right after* `prolog.el` is loaded, before any of its code gets executed?** --- BTW, as currently written, `maybe-reload-prolog-el` can run only after `prolog.el` is loaded, because it relies on the variable `prolog-mode-version`, which is defined in `prolog.el`, to decide whether to load my local copy of `prolog.el`. IOW, if I simply put the following code in my init file ``` (if (version< prolog-mode-version "1.25") (add-to-list 'load-path (file-name-as-directory (concat my-lib-path "prolog-el")))) ``` ...it fails with: ``` Symbol’s value as variable is void: prolog-mode-version ``` If there were some way to test the version of the default `prolog.el`'s version before loading it (let's call this method `PROLOG-OLDER-THAN-1.25-p`, then I would just put this in my init file: ``` (if (PROLOG-OLDER-THAN-1.25-p) (add-to-list 'load-path (file-name-as-directory (concat my-lib-path "prolog-el")))) ``` Please let me know if there's a way to implement a `PROLOG-OLDER-THAN-1.25-p` that does not require `prolog.el` to be loaded. --- Of course, I know that I can always use my copy of `prolog.el`, unconditionally. IOW, I can just put this in my init file: ``` (add-to-list 'load-path (file-name-as-directory (concat my-lib-path "prolog-el")))) ``` This approach works in the short-term, of course, but it requires more maintenance long-term. --- <sup><sup>1</sup> Please let me know if what my `maybe-reload-prolog-el` function does is the best way to conditionally reload `prolog.el`. I'm not too confident that `(load-library "prolog")` is the right thing to do here.</sup> # Answer Did you try using `eval-after-load` or `with-eval-after-load`? E.g. something like this? ``` (eval-after-load "prolog" '(maybe-reload-prolog-el)) ``` > 1 votes # Answer I'd check `emacs-major-version` instead of the version of prolog.el. > 0 votes --- Tags: hooks, autoload ---
thread-35797
https://emacs.stackexchange.com/questions/35797
Getting Rid of Constant "Recentf Changed On Disk" Error
2017-09-27T19:42:09.217
# Question Title: Getting Rid of Constant "Recentf Changed On Disk" Error I use spacemacs. It seems like every time I switch windows from spacemacs and come back to it I get the annoying error ``` recentf changed on disk; really edit the buffer? ``` I have tried disabling recentf mode, but other modes turn it back on automatically (i.e., helm or ido). I need those modes for my workflow. # Answer Force-updating spacemacs (at least on the master branch) seems to have solved this problem. > 0 votes # Answer Removing the whole emacs cache fixed the issue: ``` rm -rf ~/.emacs.d/.cache/ ``` > 2 votes # Answer Maybe try turning on `global-auto-revert-mode`? ``` global-auto-revert-mode is an interactive autoloaded compiled Lisp function in ‘autorevert.el’. (global-auto-revert-mode &optional ARG) Toggle Global Auto-Revert Mode. With a prefix argument ARG, enable Global Auto-Revert Mode if ARG is positive, and disable it otherwise. If called from Lisp, enable the mode if ARG is omitted or nil. Global Auto-Revert Mode is a global minor mode that reverts any buffer associated with a file when the file changes on disk. Use ‘auto-revert-mode’ to revert a particular buffer. ``` My invocation of it looks like this: ``` (use-package autorevert :config ;; Also auto refresh dired, but be quiet about it (setq global-auto-revert-non-file-buffers t) (setq auto-revert-verbose nil) :init (global-auto-revert-mode t)) ``` > 0 votes --- Tags: spacemacs, recentf ---
thread-53573
https://emacs.stackexchange.com/questions/53573
Number value echoed from evaluation
2019-11-05T22:42:05.250
# Question Title: Number value echoed from evaluation What does the (#o3, #x3, ?\C-c) output in the echo area (next to the 3) represent? Here I've simply evaluated ``` (+ 1 2) ``` # Answer Different views of 3 as octal, hex and a char. > 2 votes --- Tags: help, characters ---
thread-53571
https://emacs.stackexchange.com/questions/53571
Clock in automatically when org file is opened
2019-11-05T17:18:06.080
# Question Title: Clock in automatically when org file is opened Is it possible to create a hook so that It clocks in automatically whenever org file is opened for editing Kindly help # Answer > 1 votes You could use a file local variable setting like this in your org file: ``` # Local Variables: # eval: (org-clock-in) # End: ``` This has the benefit of only affecting the files you put it in. If you want it in every file, even new ones, you can make a hook function like this. ``` (defun my-clock-in () (when (org-before-first-heading-p) (org-insert-heading) (insert " " (read-string "Heading: "))) (org-clock-in)) (add-hook 'org-mode-hook 'my-clock-in) ``` Note this assumes there is a heading at the beginning of the file, and will add one if not. If that isn't what you want you will have to use a better logic, e.g. to search for an appropriate headline to clock into. This might not do exactly what you want though, e.g. if you have a set of org buffers open and switch between them, it will not switch the clock between them. There are `focus-in-hook` and `focus-out-hook` that might be suitable for that. --- Tags: org-mode ---
thread-53576
https://emacs.stackexchange.com/questions/53576
Unbalanced parentheses error when installing flycheck
2019-11-06T00:31:15.743
# Question Title: Unbalanced parentheses error when installing flycheck I'm having trouble installing flycheck. I'm on a Mac (see below for details), and I have placed the 3-line code snippet recommneded on the flycheck installation page in my emacs init file. When I start up emacs (note, I don't use GUI, I always use emacs -nw), and then I attempt to install flycheck with M-x package-install RET flycheck I get the following error: Scan error: "Unbalanced parentheses", 888, 3796 I tried both the MELPA-Stable and MELPA versions, but they both yield the same error. Any ideas as to what's causing this error? Many thanks. Mac and emacs details: MacOS 10.15 (19A602) Emacs from https://emacsformacosx.com/ GNU Emacs 26.3 (build 1, x86\_64-apple-darwin18.2.0, NS appkit-1671.20 Version 10.14.3 (Build 18D109)) of 2019-09-02 # Answer As indicated in the comments underneath the question by the original poster, the problem turned out to be a missing square bracket in the user-configuration file. The built-in function `M-x check-parens` is often times very helpful to locate mismatched parentheses in an open buffer; e.g., open up the user-configuration file and use the function `check-parens` .... > 2 votes --- Tags: flycheck, install ---
thread-53547
https://emacs.stackexchange.com/questions/53547
In Dired, how can I color the names of files younger than 1 hour?
2019-11-04T14:48:08.423
# Question Title: In Dired, how can I color the names of files younger than 1 hour? windows 10, Emacs 26.1 , Dired+ I install dired+ from here https://www.emacswiki.org/emacs/DiredPlus Here example of some dir in the dired+ mode Is it possible to change color of file names that not older than one hour? In this example this is a two files: ``` get_room_by_id_response.json create_dummy_room_response.json ``` # Answer > 1 votes You can use https://github.com/syohex/emacs-dired-k . By default, dates are fade with age. As @Drew said (Thanks), you can use dired-k.el together with Dired+. --- Tags: dired ---
thread-42252
https://emacs.stackexchange.com/questions/42252
Run local command on remote file with TRAMP?
2018-06-26T01:50:00.910
# Question Title: Run local command on remote file with TRAMP? Having a remote directory open in Emacs (... via TRAMP), I can run remote commands on remote files (using `!`). I can also view them locally (... even if they're image files) with builtin Emacs viewers (just "Enter"), resulting in the file being copied over to the local disk transparently. Is there a way to run a non-Emacs command that's only available on the local machine (... on which Emacs is running; e.g. an X11 pdf viewer), with the input being the *remote* file, in a way that's simpler than copying over the remote file manually first? # Answer > 5 votes I've written the following snippet which (as far as I can tell) does what you're looking for from the point of view of the ! command. It does the following: * Takes the files that would have operated on by dired-do-shell-command (i.e. the `!` key). This will be either the marked files, the file under point if nothing is marked or the files specified by a prefix arg. As far as I can tell this is the same as the behavior you get from `!` * Downloads a local (temporary) copy of each of the files in directory specified by `temporary-file-directory` on your system. * Runs `dired-do-shell-command` in that directory on that file or files ``` (defun dired-do-local-command () (interactive) (let* ((marked-files (dired-get-marked-files nil current-prefix-arg)) (local-tmp-files (mapcar #'file-local-copy marked-files)) (num-files (length local-tmp-files)) (default-directory temporary-file-directory) (command (dired-read-shell-command "! on %s: " num-files marked-files))) (dired-do-shell-command command num-files local-tmp-files))) ``` You can bind this to a key in dired mode (I've chosen ") with ``` (define-key dired-mode-map (kbd "\"") 'dired-do-local-command) ``` and it should behave similarly to the ! key. --- Tags: tramp ---
thread-52569
https://emacs.stackexchange.com/questions/52569
How to set schedule and deadline for entires being inserted via org-capture template file?
2019-09-08T14:54:54.723
# Question Title: How to set schedule and deadline for entires being inserted via org-capture template file? I'm trying to leverage the power of org capture templates. There are a few tasks I know I will be scheduling on particular dates of the month. Setting their schedule and deadline in the capture template automatically would be quiet cool, however I'm unable to get to a decent solution. Consider this example: year and month-name are variables I have initialized via setq (is it an acceptable way to do this?) ``` ** TODO pay salaries %(org-schedule 0 (format "%s %s 1 9am" year month-name)) ``` However when this is evaluated, what I get in the file looks like this: ``` ** TODO pay salaries Scheduled to <2019-09-01 Sun 09:00> ``` Besides constructing the scheduled and deadline strings manually, is there any other way to achieve this? # Answer > 1 votes This seems to do the required trick. Found the `jk-org-insert-time-stamp` function here: https://emacs.stackexchange.com/a/27323/20123 . ``` * PROJ %(progn (defun jk-org-insert-time-stamp (time-string) (interactive "sTime: ") (let ((default-time (apply 'encode-time (decode-time)))) (org-insert-time-stamp (apply 'encode-time (org-read-date-analyze time-string default-time default-time)) t nil))) (setq my-date (org-read-date nil t nil "Day 1 of month under purview?")) (setq month-str (format-time-string "%m" my-date)) (setq month (string-to-number month-str)) (setq month-name (format-time-string "%b" my-date)) (setq year (format-time-string "%Y" my-date)) (setq lastday (calendar-last-day-of-month month year)) (setq day7 (parse-time-string (format "%s-%s-07" year month))) (setq-local my-day1 (format-time-string "%Y-%m-01" my-date)) (format-time-string "%Y %b" my-date) (concat " " month-name year)) %? :LOGBOOK: - Added: %U :END: ** TODO pay salaries SCHEDULED: %(jk-org-insert-time-stamp (format "%s %s 31 9am" year month-name)) DEADLINE: %(jk-org-insert-time-stamp (format "%s %s 31 11pm" year month-name)) ``` If there is a better way to do this I would like to know. Needless to say, I was just able to stitch something up that works with my limited understanding of lisp. # Answer > 1 votes I usually add `%^{SCHEDULED}p` to my org-capture template. But first it prompts for a SCHEDULED value which is useless and I leave it empty, and finally it prompts for a date and adds a SCHEDULED property to the task: `SCHEDULED: <2019-11-06 Ср>`. --- Tags: org-mode, org-capture, time-date, template ---
thread-50367
https://emacs.stackexchange.com/questions/50367
org-mode table/matrix in latex export
2019-05-06T22:18:43.057
# Question Title: org-mode table/matrix in latex export I have an issue when exporting a table using \*matrix environments. The align string appears in the cell content, whatever it is specified or not ``` #+CAPTION: my matrix #+ATTR_LATEX: :mode displaymath :environment pmatrix | 1 | 2 | 3 | | 4 | 5 | 6 | #+CAPTION: my matrix #+ATTR_LATEX: :mode displaymath :environment pmatrix :align ccc | 1 | 2 | 3 | | 4 | 5 | 6 | ``` Any idea about how to solve that? # Answer Replace `displaymath` by `math`. So the header of your table should look like this: ``` #+ATTR_latex: :mode math :environment pmatrix :align ccc ``` > 0 votes --- Tags: org-mode, org-export, latex ---
thread-53590
https://emacs.stackexchange.com/questions/53590
Why in diredp-dired-recent-files show folder in title?
2019-11-06T16:39:50.447
# Question Title: Why in diredp-dired-recent-files show folder in title? Emacs 26.1 Dired+ I'm in folder `d:/temp/test` and use command "`diredp-dired-recent-files`" here steps: And here result: As you can see the frame's title is correct: ``` Recently visited files ``` Nice. But why it show folder `D/temp/test` ? I think it must be hide. # Answer > 1 votes It does so because that's how Dired works with an arbitrary file listing (files from anywhere). And because having that directory line makes various parts of Dired work (marking etc.). A Dired listing of arbitrary files (which is what this is), as opposed to a Dired listing that corresponds to `ls` output, has, unfortunately, a certain number of limitations with respect to Dired functionality. Still, it offers much of the functionality you would expect. And perhaps over time it will be improved to offer more. Such a listing (arbitrary files) has always been Dired's poor cousin. It's hardly mentioned anywhere, in fact. Dired+, at least, tries to make use of it in various ways, to give you more possibilities. *Summary:* Ignore that "directory" line, but know that it needs to be there. --- Tags: dired ---
thread-53549
https://emacs.stackexchange.com/questions/53549
Swap M-x and M-q
2019-11-04T17:19:28.487
# Question Title: Swap M-x and M-q How can I swap `M-x` and `M-q`? I can swap `C-x` and `C-q` with ``` ;; swap C-q and C-x (keyboard-translate ?\C-q ?\C-x) (keyboard-translate ?\C-x ?\C-q) ``` The following errors out ``` (keyboard-translate ?\M-q ?\M-x) (keyboard-translate ?\M-x ?\M-q) ``` as well as ``` (keyboard-translate (kbd "M-q") (kbd "M-x")) ``` I would expect the key references (`?\C-x` and `?\M-x`) to be symmetric, but clearly something in my understanding is off. EDIT: Reading @phils response and the referenced documentation, I can see that the above fails, at least in part, because there isn't a character in range to translate. Thinking more about the problem, translation is probably not what I need but rather good old rebinding: ``` (global-set-key (kbd "M-q") 'execute-extended-command) (global-set-key (kbd "M-x") 'fill-paragraph) ``` That is, make `M-q` call the command which is typically associated with `M-x` (`execute-extended-command`) and remap the displaced command (`fill-paragraph`). # Answer > 1 votes You can use `key-translation-map`: ``` (define-key key-translation-map (kbd "M-q") (kbd "M-x")) (define-key key-translation-map (kbd "M-x") (kbd "M-q")) ``` # Answer > 8 votes A control-modified letter character still results in a character, and hence character translation works for those; but most other modified keys do not result in a *character*. ``` (characterp ?\C-q) t (characterp ?\M-q) nil ``` Both *are* represented as integers, but there's a limit to the ints which are valid for `characterp`. See the following for details: * `C-h``i``g` `(elisp)Character Codes` * `C-h``i``g` `(elisp)Keyboard Events` For translating key sequences generally, see: `C-h``i``g` `(elisp)Translation Keymaps` --- Tags: key-bindings ---
thread-53594
https://emacs.stackexchange.com/questions/53594
org-mode capture template prompt directly to agenda without opening file
2019-11-06T20:07:30.880
# Question Title: org-mode capture template prompt directly to agenda without opening file I defined a template like so ``` ("g" "Godo" entry (file+headline "~/mega/org/gcal.org" "Tasks") "* TODO %^{description}%?\n %T %i\n %a"))) ``` and when pressing C-c c g I am prompted for a descpription. But after putting it in and hitting return, I am still taken to the file gcal. how can I achieve that the text I enter in the minibuffer is just combined with the current date and put into the gcal file without putting me in the capture template buffer? # Answer > 1 votes Adding the property `:immediate-finish` will have the desired effect: https://orgmode.org/manual/Template-elements.html `:immediate-finish`: "*When set, do not offer to edit the information, just file it away immediately. This makes sense if the template only needs information that can be added automatically.*" --- Tags: org-capture ---
thread-53601
https://emacs.stackexchange.com/questions/53601
C-M-\ fails to indent Lisp code
2019-11-07T02:14:06.567
# Question Title: C-M-\ fails to indent Lisp code I follow this tutorial. The code after selecting the region and `<Tab>` or equivalently `C-M-\` in an org file: ``` (setq trees '(pine fir oak maple) herbivores '(gazelle antelope zebra)) ``` I would have expected an indent before "herbivores". # Answer `indent-region` indents the region according to the current mode. In a Lisp mode (e.g. `emacs-lisp-mode`), selecting that as the region and using `TAB` indents it as you say you expect, not as you show. Why would expect it to behave similarly in Org mode? (The section of the tutorial that you cite doesn't say anything about indentation, BTW.) `C-h f indent-region` tells us: > **`indent-region`** is an interactive compiled Lisp function in `indent.el`. > > It is bound to `C-M-\`, menu-bar edit region indent-region\`. > > `(indent-region START END &optional COLUMN)` > > Indent each nonblank line in the region. > > A numeric prefix argument specifies a column: indent each line to that column. > > With no prefix argument, the command chooses one of these methods and indents all the lines with it: > > 1. If `fill-prefix` is non-`nil`, insert `fill-prefix` at the beginning of each line in the region that does not already begin with it. > 2. If `indent-region-function` is non-`nil`, call that function to indent the region. > 3. Indent each line via `indent-according-to-mode`. > > Called from a program, `START` and `END` specify the region to indent. If the third argument `COLUMN` is an integer, it specifies the column to indent to; if it is `nil`, use one of the three methods above. Next, read what `C-h f` tells you about `indent-region-function` in a Lisp mode, and what it tells you about `indent-according-to-mode`. > 0 votes --- Tags: indentation ---
thread-53600
https://emacs.stackexchange.com/questions/53600
What's the idiomatic way of overriding a key binding for a given major-mode (but no other)?
2019-11-07T01:23:48.260
# Question Title: What's the idiomatic way of overriding a key binding for a given major-mode (but no other)? I'd like to bind `C-x C-e` to `python-shell-send-region` when I am in python major-mode. In my config file, I have an add-hook for python mode, but I'd like this keybinding override to be removed/restored when I *exit* python major-mode. The use-case for this is that I want to be able to switch my \*scratch\* buffer between modes and for things to continue making sense. Is there an idiomatic way to achieve this? # Answer Not too sure what you're asking. But it sounds like the answer is to bind your key in the major mode's keymap, not in the `global-map`. For example, if the keymap for your Python mode is `python-mode-map` then do this: ``` (define-key python-mode-map (kbd "C-x C-e") 'python-shell-send-region) ``` > 2 votes --- Tags: key-bindings, python, major-mode ---
thread-53605
https://emacs.stackexchange.com/questions/53605
org-archive-subtree: Invalid ‘org-archive-location’ Mark set
2019-11-07T07:18:34.457
# Question Title: org-archive-subtree: Invalid ‘org-archive-location’ Mark set I get this when I try to archive a subtree. My config reads ``` (setq org-archive-location "~/mega/org/archive.org") ``` which does exist. So what am I doing wrong here? # Answer > 1 votes If you use **C-h v** and type in *org-archive-location* you will see the documentation. There you can see the original value ("%s\_archive::") and a few examples ``` "~/org/archive.org::" , "::* Archived Tasks" or "~/org/archive.org::* From %s" ``` Now you will probably already realize that you need the double colon in your string. Syntax seems to be the following: ``` "/path/::Heading" ``` So your solution should be: ``` (setq org-archive-location "~/mega/org/archive.org::") ``` --- Tags: org-mode, archive-mode ---
thread-53606
https://emacs.stackexchange.com/questions/53606
How do I search the auto-complete options?
2019-11-07T10:23:32.297
# Question Title: How do I search the auto-complete options? Spacemacs by default comes with company for autocomplete. When typing, it shows all kinds of symbols matching what I have typed so far. This list can be **very** long. Is there any way to search in the currently available completions? **Example:** Say I want to add a key to an evil-mode keymap. `(define-key evil-` will show a bunch of options but now I would like to filter those for the ones that also contain `map`. # Answer Use `C-s` (`company-search-candidates`), use `C-h f company-search-candidates` to learn more: > company-search-candidates is an interactive compiled Lisp function in `company.el`. > > (company-search-candidates) > > Start searching the completion candidates incrementally. > > Search can be controlled with the commands: > > * `company-search-repeat-forward` (C-s) > * `company-search-repeat-backward` (C-r) > * `company-search-abort` (C-g) > * `company-search-delete-char` (DEL) > > Regular characters are appended to the search string. > > Customize `company-search-regexp-function` to change how the input is interpreted when searching. > > The command `company-search-toggle-filtering` (C-o) uses the search string to filter the completion candidates. > 2 votes --- Tags: spacemacs, company-mode ---
thread-51128
https://emacs.stackexchange.com/questions/51128
Grep pipe support and how to filter grep results
2019-06-20T03:55:31.323
# Question Title: Grep pipe support and how to filter grep results I try to filter the output of `M-x grep` with `grep --color=always -nH -e "text_to_find" ~/path/to/files/*.org | grep -v "text_to_ignore"` but it doesn't seem to be working. The 'to be ignored' part is still not filtered away. Is it true that `grep` in Emacs do not support piping? If so, how do we filter `grep` results? # Answer Note that the first grep `grep --color=always -nH -e "text_to_find" ~/path/to/files/*.org` puts escape sequences around matches for `text_to_find` to colorize those matches. If the second search string `text_to_ignore` contains `text_to_find`. Matches of `text_to_ignore` in the original files are not found in the output of the first `grep` call because of those escape sequences. Leave the `--color=always` option out to avoid that effect. The matches of `text_to_find` are no longer highlighted with yellow color but the second grep works if `text_to_find` is part of `text_to_ignore`. If you really need to colorize the matches for `text_to_find` you can colorize them as a last step: ``` grep -nH -e "text_to_find" ~/path/to/files/*.org | grep -v "text_to_ignore | grep --color=always -e "text_to_find"" ``` > 5 votes # Answer What you were attempting with a pipe works fine for me (tested in 26.1 and 25.3). * Which version are you using? * Does your command work *outside* of Emacs? *Edit*: `C-h``v` `grep-use-null-device` might mess up your command, by preventing the second grep from reading stdin. This would be apparent in the command line displayed in the grep buffer. If this is the issue, then hopefully you can simply disable that option via the customize interface. --- Failing that, you can always filter the results after the fact with the `flush-lines` and `keep-lines` commands, after toggling the read-only state with `C-x``C-q`. Personally I like/use the winnow library for streamlining that: Use `x` to remove lines matching a pattern, or `m` to keep only the lines matching a pattern. > 4 votes # Answer Another alternative: The elgrep library allows searching files without external programs and with user-defined search function. The command `M-x` `elgrep-menu` -- also available as menu item `Tools` -\> `Search Files (elgrep)...` -- provides an input field `Search Function`. The following search function searches for the given regular expression `text` but ignores lines that match `text_to_ignore`. ``` (lambda (re &rest _) (and (re-search-forward re nil t) (null (string-match-p "text_to_ignore" (thing-at-point 'line))))) ``` Remarks: * `elgrep` only checks whether the return value of the search function is non-nil * it evaluates the match data after a successful return of the search function * `string-match-p` preserves the match data * `(thing-at-point 'line)` uses `forward-line` and therefore does also not change the match data The following image shows the full dialog of `elgrep-menu`. > 2 votes # Answer The elgrep library has evolved. So there is now a better alternative way to search for lines matching `text_to_find` but not matching `text_to_ignore`. One does no longer need to explicitly input Elisp functions. One can define records of a file, and specify a regular expression that must not match in a record to be considered in the search for another regular expression. Full lines are an example for records. Settings for your usecase in the `elgrep-menu` (`Tools``Search Files (Elgrep)...`): * Set `Expression` to `List of regexps` * Input `text_to_find` as first regexp * Input `!text_to_ignore` as second regexp Note, that the leading `!` negates the expression. The negated expression must not match within the record. * Input the directory and the file name regexp. Note that you can use completion for the input of the directory. Furthermore resetting the elgrep menu sets the directory to the directory of the last visited file. * Set `Beginning of Record` to `Regexp` and use `^` as regexp standing for `beginning-of-line`. * Set `End of Record` to `Regexp` and use `$` as regexp standing for `end-of-line`. Note that this method can be inefficient for very large files with many lines (order of 100MB with 100 Mio lines) with only few matches for `text_to_find` because each line is searched for the regexps. > 1 votes --- Tags: grep ---
thread-53611
https://emacs.stackexchange.com/questions/53611
How to trace the evaluation of all forms in the body of an Elisp function
2019-11-07T13:48:56.543
# Question Title: How to trace the evaluation of all forms in the body of an Elisp function When working with bash scripts, when something is not behaving the way you want it to, you can add a ``` set -x ``` and the next time you run the script you can see the methods and the sub methods being called in real time. Is there an equivalent switch in "elisp"? # Answer > 5 votes The *Elisp debugger* doesn't provide a trace, but it does let you investigate (and even affect) the evaluation of Lisp code on the fly. * You can enter the debugger, to walk or skip through any function, using `M-x debug-on-entry`. * You can put breakpoints, which enter the debugger, at any place in Lisp source code, just by adding `(debug)`. (See `C-h f debug` for info about optional args.) * You can automatically open the debugger when an error is raised, by setting variable `debug-on-error` to non-`nil`. See the Elisp manual, starting with node Invoking the Debugger. In Emacs you can get to that by `C-h i`, choosing Elisp, then `i debug RET`. There is also Edebug, whose use is a bit different. For that, you "instrument" particular functions whose evaluation in calls you want to investigate. You can read about it here: `C-h i` then choose Elisp, then `g edebug RET`. That takes you to node Edebug of the Elisp manual. # Answer > 3 votes The function `edebug-instrument-for-tracing` as defined in the following Elisp snippet works similar to `edebug-defun`. But, instead of instrumenting stuff for `edebug` it prepares it for tracing into the buffer `*edebug-trace*`. ``` (defun edebug-untrace (form) "Remove tracing instructions from FORM." (if (consp form) (if (eq (car form) 'edebug-tracing) (edebug-untrace (caddr form)) (cons (edebug-untrace (car form)) (edebug-untrace (cdr form)))) form)) (defcustom edebug-trace-print-level 3 "`print-level' for `edebug-make-trace-form'." :type 'integer :group 'edebug) (defcustom edebug-trace-print-length 5 "`print-length' for `edebug-make-trace-form'." :type 'integer :group 'edebug) (defun edebug-make-trace-form (form) "Prepare FORM for tracing." `(edebug-tracing ,(let ((print-level edebug-trace-print-level) (print-length edebug-trace-print-length)) (prin1-to-string (edebug-untrace form))) ,form)) (defun edebug-make-trace-enter-wrapper (forms) "Prepare function with FORMS for tracing." (if edebug-def-name `(edebug-tracing ,(format "%S%S" edebug-def-name (nreverse edebug-def-args)) ,@forms) `(progn ,@forms))) (defun edebug-instrument-for-tracing () "Like `edebug-defun' but instruments for tracing." (interactive) (cl-letf (((symbol-function 'edebug-make-enter-wrapper) (lambda (forms) (edebug-make-trace-enter-wrapper forms))) ((symbol-function 'edebug-make-before-and-after-form) (lambda (before-index form after-index) (edebug-make-trace-form form))) ((symbol-function 'edebug-make-after-form) (lambda (form after-index) (edebug-make-trace-form form)))) (edebug-defun))) ``` For testing, put point into the following form and run `M-x` `edebug-instrument-for-tracing`. ``` (let ((i 0)) (while (< i 2) (message "i=%d" i) (setq i (1+ i)))) ``` You get an `*edebug-trace*` buffer with the following output. Each form is printed before and after its evaluation. The result of the evaluation of the form is also printed. ``` { (let ((i 0)) (while (< i 2) (message "i=%d" i) (setq i ...))) :{ (while (< i 2) (message "i=%d" i) (setq i (1+ i))) ::{ (< i 2) :::{ i :::} i result: 0 ::} (< i 2) result: t ::{ (message "i=%d" i) :::{ i :::} i result: 0 ::} (message "i=%d" i) result: i=0 ::{ (setq i (1+ i)) :::{ (1+ i) ::::{ i ::::} i result: 0 :::} (1+ i) result: 1 ::} (setq i (1+ i)) result: 1 ::{ (< i 2) :::{ i :::} i result: 1 ::} (< i 2) result: t ::{ (message "i=%d" i) :::{ i :::} i result: 1 ::} (message "i=%d" i) result: i=1 ::{ (setq i (1+ i)) :::{ (1+ i) ::::{ i ::::} i result: 1 :::} (1+ i) result: 2 ::} (setq i (1+ i)) result: 2 ::{ (< i 2) :::{ i :::} i result: 2 ::} (< i 2) result: nil :} (while (< i 2) (message "i=%d" i) (setq i (1+ i))) result: nil } (let ((i 0)) (while (< i 2) (message "i=%d" i) (setq i ...))) result: nil ``` Note that this is a kind of simple prototype-implementation. It is not very efficient. It may be that tracing becomes a bit slow on deeply nested functions. # Answer > 2 votes I don't know anything like that, but if you want to see the calls (including parameters and return value) for a few specific functions you can use the `trace-function` command. Here's its docstring: > (trace-function FUNCTION &optional BUFFER CONTEXT) > > Trace calls to function FUNCTION. > > With a prefix argument, also prompt for the trace buffer (default ‘trace-buffer’), and a Lisp expression CONTEXT. > > Tracing a function causes every call to that function to insert into BUFFER Lisp-style trace messages that display the function’s arguments and return values. It also evaluates CONTEXT, if that is non-nil, and inserts its value too. For example, you can use this to track the current buffer, or position of point. > > ... > > To stop tracing a function, use ‘untrace-function’ or ‘untrace-all’. --- Tags: debugging ---
thread-53618
https://emacs.stackexchange.com/questions/53618
Left margin grows while typing
2019-11-07T18:39:15.350
# Question Title: Left margin grows while typing My buffer slips to the right while editing a file. Whenever I press a button, left margin area grows one character. This isn't happening for all files. My buffer normally looks like this: ``` line with text another line with text ``` After I push a buttons, the screen slips to the right, left margin area grows and the buffer looks like this: ``` <this area got wider> line with text <this area got wider> another line with text ``` This problem did not occur for all files; but it isn't resolved with restarting the Emacs. # Answer > 3 votes I've found the problem is the `git-gutter`. I've searched and found it is a known compatibility issue with `linum-mode` in Emacs 26.1. Everything has fixed when I use `display-line-numbers-mode` as suggested. --- Tags: buffers, margins ---
thread-53620
https://emacs.stackexchange.com/questions/53620
Chronos cannot speak French
2019-11-07T20:05:51.663
# Question Title: Chronos cannot speak French I changed `chronos-text-to-speech-notify` acording to https://github.com/dxknight/chronos/issues/2. My Chronos config includes this: > (setq chronos-text-to-speech-program-parameters "-s 50 -k 1 -a 50 -v mb/mb-fr1" ). The command > (chronos-add-timer "0:0:1" "Coucou, je parle français" nil) is supposed to speak the message with a French voice, but it doesn't (default English voice only) Chronos sent this shell command: > espeak \\"-s 50 -k 1 -a 50 -v mb/mb-fr1\\" \\"20:44 Coucou, je parle français\\" which returned > Failed to read voice 'mb/mb-fr1"' This shell command works fine, however: > ``` > espeak -s 50 -k 1 -a 50 -v mb/mb-fr1 "20:44 Coucou, je parle français" > > ``` This sounds like a bug, but I haven't succeeded in fixing it. # Answer > 2 votes Following a look at chronos.el > ``` > (setq chronos-text-to-speech-program-parameters > "-s 50 -k 1 -a 50 -v mb/mb-fr1") > > ``` should probably be: ``` (setq chronos-text-to-speech-program-parameters '("-s" "50" "-k" "1" "-a" "50" "-v" "mb/mb-fr1")) ``` It looks buggy in that it's not passing the arguments through `shell-quote-argument`, although it's unclear if there's actually any reason to be using `start-process-shell-command` (as opposed to `start-process`). Either way I suspect there are improvements which could be made upstream. --- Tags: shell ---
thread-53624
https://emacs.stackexchange.com/questions/53624
How to run a mini-buffer command from interpreter
2019-11-08T03:23:36.123
# Question Title: How to run a mini-buffer command from interpreter I think this might be a duplicate but I can't figure out how to run this: ``` (man emacs)[cursor] [C-x][C-e] ``` Error I get back: ``` Debugger entered--Lisp error: (void-variable gpg) (man gpg) eval((man gpg) nil) elisp--eval-last-sexp(nil) eval-last-sexp(nil) funcall-interactively(eval-last-sexp nil) call-interactively(eval-last-sexp nil nil) command-execute(eval-last-sexp) ``` I'm trying to put a lisp expression in a file to open the man page in Emacs. So I can save an expression like this in my notes, and then open the man page in Emacs by running eval on the line. I thonght it might be `(man 'emacs)`, but It didn't work. # Answer Try using any of the following examples, with double quotes around the MAN-ARGS: ``` (man "emacs") ``` or ``` (man "gpg") ``` or ``` (man "chmod(2)") ``` I don't have the `gpg` manual installed, but the other two examples do generate a manual buffer ... > 0 votes --- Tags: help ---
thread-53628
https://emacs.stackexchange.com/questions/53628
Use write-region in read-only buffer
2019-11-08T06:24:22.573
# Question Title: Use write-region in read-only buffer I am writing a custom function which is supposed to write selected text to some arbitrary file on the system. It does something like ``` (defun write-region-to-file (&optional arg) (interactive "*p") (write-region (point) (mark-marker) "/path/to/file/other/then/visited")) ``` If I then run it in a read-only buffer I get ``` command-execute: Buffer is read-only: #<buffer ...> ``` Why is this happening? I don't do any modification to the visited one, I am writing to a completely different file. Any ideas? # Answer The interactive code `*` is used to: "*Signal an error if the current buffer is read-only. Special.*" https://www.gnu.org/software/emacs/manual/html\_node/elisp/Interactive-Codes.html Thus, the line that reads `(interactive "*p")` can be changed to eliminate the asterisk. NOTE: In the example, the optional argument `ARG` is not used. Thus, consider changing `(&optional arg)` to just `()`; and, consider changing the interactive statement to just `(interactive)`. > 3 votes --- Tags: interactive, read-only-mode ---
thread-53195
https://emacs.stackexchange.com/questions/53195
Org mode + table.el: Use Org formatting inside cells
2019-10-16T23:50:41.200
# Question Title: Org mode + table.el: Use Org formatting inside cells Say I have a table in an Org document looking like this: (Source) ``` +----------+-----------+----------+-------------------------------------------------------+ | Date | Day | Pages | Content | +----------+-----------+----------+-------------------------------------------------------+ | 28 Aug | Wednesday | 114-128 | - Freehold Society | | | | | - Quakers | | | | | - Early Immigrants | | | | | - Religious Beliefs | | | | | - Enlightenment in America | +----------+-----------+----------+-------------------------------------------------------+ | 29 Aug | Thursday | 129-135 | - Great Awakening | | | | | - Whitefield | | | | | - Edwards | | | | | - Old Lights | | | | | - New Lights | +----------+-----------+----------+-------------------------------------------------------+ | 30 Aug | Friday | 135-140 | - French & Indian War | | | | | - Pontiac's Uprising | | | | | - Albany Plan of the Union | | | | | - Treaty of Paris (1763) | +----------+-----------+----------+-------------------------------------------------------+ | 2 Sep | Monday | 140-143 | - Paxton Boys | | | | | - Regulators | | | | | - results of the French and Indian War | +----------+-----------+----------+-------------------------------------------------------+ | 3 Sep | Tuesday | 152-160 | - Proclamation of 1763 | | | | | - Sugar Act | | | | | - Stamp Act | | | | | - Stamp Act Congress | | | | | - Quartering Act | | | | | - Sons of Liberty | | | | | - Ideological Differences (3 total) | | | | | - John Dickinson | +----------+-----------+----------+-------------------------------------------------------+ | 4 Sep | Wednesday | 160-167 | - Declatory Act | | | | | - Townshend Acts | | | | | - Sons of Liberty | | | | | - Daughters of Liberty | | | | | - Boston Massacre | +----------+-----------+----------+-------------------------------------------------------+ | 5 Sep | Thursday | 168-179 | - Committees of correspondence | | | | | - Tea Act | | | | | - Boston Tea Party | | | | | - Intolerable or Coercive Acts | | | | | - Quebec Act | | | | | - First Contintental Congress | | | | | - Loyalists | | | | | - Olive Branch Petition | | | | | - Proclamation for Suppressing Rebellion and Sedition | | | | | - Prohibitory Act | | | | | - /Common Sense/ | | | | | - Declaration of Independence | +----------+-----------+----------+-------------------------------------------------------+ ``` I'd expect the right most cells to become lists when exported, and in the case of `Common Sense` to format as italics. However, the table content gets exported as plaintext with a ton of no-break-spaces. (HTML Output) How do I fix this so that these tables are properly exported with formatting? # Answer > 3 votes The following Elisp code modifies the html export backend so that it accepts an additional option `HTML_TABLEEL_ORG`. If you set this option to `t` or `yes` table cells in table.el-tables are rendered as org-mode strings. You can copy the code into your init file if the first line of your init file contains the file-local setting `lexical-binding: t` as demonstrated in the code snippet. If you do not want to evaluate your init file with lexical binding you can copy-paste the code inclusively the first comment line into some new Elisp file in your `load-path` and `require` that file in your init file. ``` ;; -*- lexical-binding: t -*- (defcustom org-html-tableel-org "no" "Export table.el cells as org code if set to \"t\" or \"yes\". This is the default and can be changed per section with export option: #+OPTIONS: HTML_TABLEEL_ORG: t" :type '(choice (const "no") (const "yes")) :group 'org-html) (eval-after-load 'ox-html '(eval ;;< Avoid eager macro expansion before ox-html is loaded. '(cl-pushnew (list :html-tableel-org "HTML_TABLEEL_ORG" ;; keyword "html-tableel-org";; option for #+OPTIONS: line org-html-tableel-org ;; default value for the property t ;; handling of multiple keywords for the same property. (Replace old value with new one.) ) (org-export-backend-options (org-export-get-backend 'html))))) (defvar org-element-all-elements) ;; defined in "org-element" (defun table-generate-orghtml-cell-contents (dest-buffer language cell info) "Generate and insert source cell contents of a CELL into DEST-BUFFER. LANGUAGE must be 'orghtml." (cl-assert (eq language 'html) nil "Table cells with org content only working with html export") (let* ((cell-contents (extract-rectangle (car cell) (cdr cell))) (string (with-temp-buffer (table--insert-rectangle cell-contents) (table--remove-cell-properties (point-min) (point-max)) (goto-char (point-min)) (buffer-substring (point-min) (point-max))))) (with-current-buffer dest-buffer (let ((beg (point))) (insert (org-export-string-as string 'html t info)) (indent-rigidly beg (point) 6))))) (defun org-orghtml-table--table.el-table (fun table info) "Format table.el TABLE into HTML. This is an advice for `org-html-table--table.el-table' as FUN. INFO is a plist used as a communication channel." (if (assoc-string (plist-get info :html-tableel-org) '("t" "yes")) (cl-letf (((symbol-function 'table--generate-source-cell-contents) (lambda (dest-buffer language cell) (table-generate-orghtml-cell-contents dest-buffer language cell info)))) (funcall fun table info)) (funcall fun table info))) (advice-add #'org-html-table--table.el-table :around #'org-orghtml-table--table.el-table) ``` The following reduced example demonstrates the usage: ``` #+HTML_HEAD_EXTRA: <style type="text/css"> td { padding: 0px 10px 0px 10px } </style> #+OPTIONS: html-tableel-org:t +----------+-----------+----------+-------------------------------------------------------+ | Date | Day | Pages | Content | +----------+-----------+----------+-------------------------------------------------------+ | 28 Aug | Wednesday | 114-128 | - Freehold Society | | | | | - Quakers | | | | | - Early Immigrants | | | | | - Religious Beliefs | | | | | - Enlightenment in *America* | +----------+-----------+----------+-------------------------------------------------------+ | 29 Aug | Thursday | 129-135 | - Great Awakening | | | | | - /Whitefield/ | | | | | - Edwards | +----------+-----------+----------+-------------------------------------------------------+ ``` The exported html rendered by firefox: Tested with: `emacs-version`: `GNU Emacs 26.3 (build 2, x86_64-pc-linux-gnu, GTK+ Version 3.22.30) of 2019-09-16` `table.el` version: built-in `org-version`: `Org mode version 9.2.6` --- Tags: org-mode, org-export, org-table ---
thread-53635
https://emacs.stackexchange.com/questions/53635
How to prevent deactivating the region after a command?
2019-11-08T16:16:20.577
# Question Title: How to prevent deactivating the region after a command? When a function is called on a region, I want a visual indication of affected area (a blink for ex.). Say, I've written a function upcasing previous word, and after evaluation I immediately get the result (and that's good) but I also want region highlighted for a sec. How could it be implemented? Also I even can't get the region remain highlighted after the evaluation. `(setq mark-active t)` doesn't seem to work at all. Mark is forced to deactivate after interactive function or what? ``` (defun upcase-previous-WORD () (interactive) (set-mark (point)) (forward-whitespace -1) (call-interactively 'upcase-region) (exchange-point-and-mark) (setq mark-active t))) ``` # Answer > 1 votes \[ I'll answer the second question. \] Yes, Emacs resets `mark-active` to nil automatically after executing a command which modified the buffer (or more specifically, after executing a command which set `deactivate-mark` to a non-nil value). To prevent that you can use `(setq deactivate-mark nil)` in your function (after performing the buffer modification). --- Tags: region ---
thread-53627
https://emacs.stackexchange.com/questions/53627
Representing leading zeroes in a list
2019-11-08T05:36:39.083
# Question Title: Representing leading zeroes in a list I would like to have this table ``` #+NAME: addition-table | | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | |---+----+----+----+----+----+----+----+----+----+----| | 0 | 00 | 01 | 02 | 03 | 04 | 05 | 06 | 07 | 08 | 09 | | 1 | 01 | 02 | 03 | 04 | 05 | 06 | 07 | 08 | 09 | 10 | | 2 | 02 | 03 | 04 | 05 | 06 | 07 | 08 | 09 | 10 | 11 | | 3 | 03 | 04 | 05 | 06 | 07 | 08 | 09 | 10 | 11 | 12 | | 4 | 04 | 05 | 06 | 07 | 08 | 09 | 10 | 11 | 12 | 13 | | 5 | 05 | 06 | 07 | 08 | 09 | 10 | 11 | 12 | 13 | 14 | | 6 | 06 | 07 | 08 | 09 | 10 | 11 | 12 | 13 | 14 | 15 | | 7 | 07 | 08 | 09 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | | 8 | 08 | 09 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | | 9 | 09 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | |---+----+----+----+----+----+----+----+----+----+----| ``` represented as a list. This is what I did: ``` #+BEGIN_SRC emacs-lisp '((0 00 01 02 03 04 05 06 07 08 09) (1 01 02 03 04 05 06 07 08 09 10) (2 02 03 04 05 06 07 08 09 10 11) (3 03 04 05 06 07 08 09 10 11 12) (4 04 05 06 07 08 09 10 11 12 13) (5 05 06 07 08 09 10 11 12 13 14) (6 06 07 08 09 10 11 12 13 14 15) (7 07 08 09 10 11 12 13 14 15 16) (8 08 09 10 11 12 13 14 15 16 17) (9 09 10 11 12 13 14 15 16 17 18)) #+END_SRC ``` Unfortunately, upon evaluation, elisp wants to remove any leading zero, hence, I get this return: ``` #+RESULTS: | 0 | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | | 1 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | | 2 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | | 3 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | | 4 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | | 5 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | | 6 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | | 7 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | | 8 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | | 9 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | ``` It's no different in the scratch buffer, by the way. ``` ((0 0 1 2 3 4 5 6 7 8 9) (1 1 2 3 4 5 6 7 8 9 10) (2 2 3 4 5 6 7 8 9 10 11) (3 3 4 5 6 7 8 9 10 11 12) (4 4 5 6 7 8 9 10 11 12 13) (5 5 6 7 8 9 10 11 12 13 14) (6 6 7 8 9 10 11 12 13 14 15) (7 7 8 9 10 11 12 13 14 15 16) (8 8 9 10 11 12 13 14 15 16 17) (9 9 10 11 12 13 14 15 16 17 18)) ``` How can I tell elisp to keep my leading zeroes as in the original table? # Answer > 2 votes You can use this org table formula, `format` is used to ensure the number's width is 2 and padded with zero, as @sds's answer suggested: ``` #+NAME: addition-table | | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | |---+----+----+----+----+----+----+----+----+----+----| | 0 | 00 | 01 | 02 | 03 | 04 | 05 | 06 | 07 | 08 | 09 | | 1 | 01 | 02 | 03 | 04 | 05 | 06 | 07 | 08 | 09 | 10 | | 2 | 02 | 03 | 04 | 05 | 06 | 07 | 08 | 09 | 10 | 11 | | 3 | 03 | 04 | 05 | 06 | 07 | 08 | 09 | 10 | 11 | 12 | | 4 | 04 | 05 | 06 | 07 | 08 | 09 | 10 | 11 | 12 | 13 | | 5 | 05 | 06 | 07 | 08 | 09 | 10 | 11 | 12 | 13 | 14 | | 6 | 06 | 07 | 08 | 09 | 10 | 11 | 12 | 13 | 14 | 15 | | 7 | 07 | 08 | 09 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | | 8 | 08 | 09 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | | 9 | 09 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | |---+----+----+----+----+----+----+----+----+----+----| #+TBLFM: @2$2..@>$>='(format "%02d" (+ @1 $1));N ``` You can also quote these numbers to convert them into strings, for example, with `query-replace-regexp`: ``` C-M-% [0-9]+ → \,(format "\"%02d\"" \#&) ``` then ``` #+BEGIN_SRC emacs-lisp '(("00" "00" "01" "02" "03" "04" "05" "06" "07" "08" "09") ("01" "01" "02" "03" "04" "05" "06" "07" "08" "09" "10") ("02" "02" "03" "04" "05" "06" "07" "08" "09" "10" "11") ("03" "03" "04" "05" "06" "07" "08" "09" "10" "11" "12") ("04" "04" "05" "06" "07" "08" "09" "10" "11" "12" "13") ("05" "05" "06" "07" "08" "09" "10" "11" "12" "13" "14") ("06" "06" "07" "08" "09" "10" "11" "12" "13" "14" "15") ("07" "07" "08" "09" "10" "11" "12" "13" "14" "15" "16") ("08" "08" "09" "10" "11" "12" "13" "14" "15" "16" "17") ("09" "09" "10" "11" "12" "13" "14" "15" "16" "17" "18")) #+END_SRC #+RESULTS: | 00 | 00 | 01 | 02 | 03 | 04 | 05 | 06 | 07 | 08 | 09 | | 01 | 01 | 02 | 03 | 04 | 05 | 06 | 07 | 08 | 09 | 10 | | 02 | 02 | 03 | 04 | 05 | 06 | 07 | 08 | 09 | 10 | 11 | | 03 | 03 | 04 | 05 | 06 | 07 | 08 | 09 | 10 | 11 | 12 | | 04 | 04 | 05 | 06 | 07 | 08 | 09 | 10 | 11 | 12 | 13 | | 05 | 05 | 06 | 07 | 08 | 09 | 10 | 11 | 12 | 13 | 14 | | 06 | 06 | 07 | 08 | 09 | 10 | 11 | 12 | 13 | 14 | 15 | | 07 | 07 | 08 | 09 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | | 08 | 08 | 09 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | | 09 | 09 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | ``` # Answer > 1 votes # TL;DR You need to format your numbers with the leading zeros if you want them: ``` (format "%03d" 3) ==> "003" ``` # Details When you type ``` (defvar foo '(00 01 02)) ``` and evaluate it, Emacs reads the string `"01"` and recognizes it as a number (`integer`) and stores it in the list. Then it promptly forgets how the number was represented - as `"1"` or `"01"` or `"000001"`. When the list is printed, Emacs cannot know how you want your numbers to be represented, so it prints them with the usual decimal form. If you want leading zeros (or, say, octal representation), you need to specify that explicitly by calling `format` in a loop. --- Tags: org-mode, list, numbers, format ---
thread-53598
https://emacs.stackexchange.com/questions/53598
How to downscale linum font size (and avoid left margin gap)?
2019-11-07T00:26:13.663
# Question Title: How to downscale linum font size (and avoid left margin gap)? I need your help cause I couldn't figure it out. My ideal linum format has 5 digits at least. I'd really like to scale the linum font size down with respect to the text, say by 1/3. This is great cause it avoids an excessively wide linum column (especially in a split view of 2 frames). However, if I fix the linum height to be 80 for instance, emacs adds a gap between the left margin and the fringe, which defeats the whole idea of scaling it down. In linum-mode the left margin is fixed, so manually setting left-margin-width doesn't help. After many tries I came to the conclusion that it cannot be done with my poor level of understanding of lisp and how emacs handles the display. Below is an example. Is it possible to have different linum and text font size, but avoiding that gap? @Stefan: Thanks! emacs 24.5 / Debian Stretch. I am not incline to update emacs for now if possible, but I will try nlinum-mode (although I read linum should be more efficient). @Stefan: sorry my bad: "\[nlinum\] should usually be about **as fast or faster** than linum.el". That sounds great, thanks! I am slightly concerned about a problem found with the deamon “ERROR: Invalid face: linum”. But I'll definitely give it a try - I wasn't aware you were directly involved in dev this, well thanks twice then. # Answer > 0 votes Turns out, nlinum-mode doesn't suffer the same gap issue as described in the question. Emacsclient won't work, workaround at the link. --- Tags: linum-mode, fringe ---
thread-53552
https://emacs.stackexchange.com/questions/53552
Org-mode: Using sparse tree to search through timestamps (non-scheduled, non-deadlines)
2019-11-05T02:53:29.717
# Question Title: Org-mode: Using sparse tree to search through timestamps (non-scheduled, non-deadlines) I am aware that I able to use sparse tree to search "\[b\]efore-date" with `C-c``/``b` or search "\[a\]fter-date" with `C-c``/``a`. However, I recognise that seems to only be with dates that are **schedules** or **deadlines**. Is it possible to use sparse tree or something similar to filter my org-mode bullets by time-stamps? Say in the context of using org-mode to do a logbook/diary of sorts. Or is the best solution input the time-stamps as schedules? # Answer > 2 votes When you bring up `org-sparse-tree`, pressing `c` should cycle you through date types. The first date type after the default of **scheduled/deadline** is **all timestamps**. That includes normal timestamps. So: `C-c``/``c``a` should do what you need. --- Tags: org-mode, search ---
thread-53643
https://emacs.stackexchange.com/questions/53643
org-mode: <N> to set column width isn't working
2019-11-08T20:06:54.073
# Question Title: org-mode: <N> to set column width isn't working I'm trying to set a column width in an org-mode table, but using the syntax isn't working. Here's my table: ``` | col 1 | col 2 with quite a long header | col 3 here | |-------+--------------------------------+------------| | | <5> | | | abc | 123 | x | | def | 456 | y | ``` I'd expect that after a re-align, the second column would be displayed with a width of 5 -- but it stays the way seen above. I'm not exporting this file, I just want to narrow the usually-displayed column so my table is easier to read. Any ideas why org isn't displaying the width correctly? # Answer > 3 votes Normal realign with `C-c C-c` does not consider column widths (anymore?, idk). Use `C-c TAB` (`org-table-toggle-column-width`) instead to shrink or expand the current column. To narrow all columns with a specified width call it with a prefix argument `C-u C-c TAB`. To automatically shrink columns with a width cookie you can either set `#+STARTUP: shrink` on a per-file basis or `org-startup-shrink-all-tables` to `t` to do it globally. --- Tags: org-mode ---
thread-19903
https://emacs.stackexchange.com/questions/19903
How can I customize the LaTeX export of org babel #+RESULTS?
2016-01-28T16:20:45.857
# Question Title: How can I customize the LaTeX export of org babel #+RESULTS? I regularly use org-mode and org-babel to create e.g. exercises or proof-of-principle documents which I export to PDF via the LaTeX exporter. I noticed that the `#RESULTS` generated by a `#+begin_src`-`#+end_src` block are put in a `#+begin_example`-`#+end_example` block, which is exported to LaTeX's `verbatim` environment. I would like to customize this LaTeX export. I could try and add some `#+LATEX_HEADER` lines customizing the `verbatim` environment (e.g. using the `fancyvrb` package), however, ideally I would like to use the `listings` environment for the output. Is this possible? EDIT: I currently use the `listings` package to format the `src` blocks, so ideally I would like to use the same formatting for both. # Answer There may be a "smarter" way but if you don't use `EXAMPLE` blocks for other purpose you could instruct the latex exporter to export them as `lstlisting` environment, using export filters. ``` (defun my-latex-export-example-blocks (text backend info) "Export example blocks as listings env." (when (org-export-derived-backend-p backend 'latex) (with-temp-buffer (insert text) ;; replace verbatim env by listings (goto-char (point-min)) (replace-string "\\begin{verbatim}" "\\begin{lstlisting}") (replace-string "\\end{verbatim}" "\\end{lstlisting}") (buffer-substring-no-properties (point-min) (point-max))))) (add-to-list 'org-export-filter-example-block-functions 'my-latex-export-example-blocks) ``` > 9 votes # Answer For reference I found this message on the org-mode mailing list which mentions a way to do this by means of file local `#+LATEX_HEADER` lines which use the `fancyvrb` package and redefine the verbatim environment that org-mode `#+RESULTS` blocks get exported to via: ``` #+LATEX_HEADER: \RequirePackage{fancyvrb} #+LATEX_HEADER: \DefineVerbatimEnvironment{verbatim}{Verbatim}{fontsize=\small,formatcom = {\color[rgb]{0.5,0,0}}} ``` > 6 votes --- Tags: org-mode, org-export, latex, org-babel ---
thread-53648
https://emacs.stackexchange.com/questions/53648
Eliminate org capture message
2019-11-09T15:15:26.020
# Question Title: Eliminate org capture message How can I disable the persistent message on an org capture buffer that says? ``` Capture buffer. Finish `C-c', Refile `C-w', abort `C-k'. ``` A similar message is displayed when entering a source block. That message can be disabled with `org-edit-src-persistent-message`. However I don't see such an option for capturing. I've searched this online and used `M-x apropos-documentation` as well as `apropos-variable` with the terms `capture` and `message`to no avail. # Answer There is no variable to control that, but you can accomplish what you want with a hook. Some background: when you start a capture, a capture buffer is created and although its major mode is `org-mode`, a minor mode is added: `org-capture-mode`. Like all modes, it has a hook (a list of functions that are called when the mode is entered) called `org-capture-mode-hook`. By default, it is nil, but we can add a function to it using the standard `add-hook` mechanism. One convention that all modes share is the (buffer-local) variable `header-line-format`. If that is defined, then every buffer that has that mode enabled gets that header line. If you look in org-capture.el, you will see that the `org-capture-mode` definition defines `header-line-format` to be the string that you want to eliminate, so all we need to do is make it nil. Putting the above together, you can accomplish what you want with the following code: ``` (defun org-capture-turn-off-header-line () (setq-local header-line-format nil)) (add-hook 'org-capture-mode-hook #'org-capture-turn-off-header-line) ``` The only problem is to add it to the proper place. You need to add it to your initialization file somewhere, but it needs to be done *after* `org-capture-mode-hook` is defined. The standard method to do that is with `eval-after-load`: ``` (eval-after-load 'org-capture (progn (defun org-capture-turn-off-header-line () (setq-local header-line-format nil)) (add-hook 'org-capture-mode-hook #'org-capture-turn-off-header-line))) ``` > 3 votes --- Tags: org-capture ---
thread-53597
https://emacs.stackexchange.com/questions/53597
Specifying a refiling target at the file level
2019-11-06T23:21:30.830
# Question Title: Specifying a refiling target at the file level I have a question about refiling under orgmode. For a certain file, I want a different set of refiling targets that what I have in general (specifically, only refiling within this document itself). I'm hoping there is a header setting I can use to override the refile target for a given file, but I haven't been able to track it down despite much search. Any help much appreciated. # Answer > 0 votes Continued research has revealed a partial answer, setting variables at the level of the *directory*, which is sufficient for my use case and perhaps for other. The documentation entry is https://www.gnu.org/software/emacs/manual/html\_node/emacs/Directory-Variables.html and useful descriptions are at http://endlessparentheses.com/a-quick-guide-to-directory-local-variables.html and http://joelmccracken.github.io/entries/project-local-variables-in-projectile-with-dirlocals/ --- Tags: org-mode ---
thread-53656
https://emacs.stackexchange.com/questions/53656
How to prevent Emacs from moving my mouse pointer out of the way?
2019-11-10T06:49:33.953
# Question Title: How to prevent Emacs from moving my mouse pointer out of the way? I'm using Spacemacs on MS Windows (msys2 build) and when a tooltip pops up Emacs seems to move my mouse pointer out of the way. How can I prevent this automatic movement? # Answer I do not use Spacemacs, but this could be caused by `mouse-avoidance-mode`. It normally moves the mouse when the cursor is nearby. So it may also apply to tooltips, I am not sure. You can check if it is enabled with `C-h v mouse-avoidance-mode`. If it is not `nil`, you can disable it with `(mouse-avoidance-mode -1)`. There are also several other options how the mouse is moved, see the manual. I used to set it to `'exile`, which makes the cursor automatically return. > 3 votes --- Tags: spacemacs, mouse, tooltip ---
thread-53655
https://emacs.stackexchange.com/questions/53655
Assign buffer-name to variable
2019-11-10T06:08:41.640
# Question Title: Assign buffer-name to variable I'd like to write `Elisp` code that compares text character by character between two buffers. To do that, I need to first assign buffer names to the variables `source-buffer` and `target-buffer` respectively. ``` (defun set-source-buffer (&optional buffer) "Sets source-buffer to current-buffer. " (interactive "bSelect Source Buffer: \nr" buffer) (cond ((boundp 'buffer) buffer) (setq source-buffer (current-buffer)))) ``` I would like to call this function by either activating the buffer to be selected as source and do `(setq source-buffer (current-buffer))` or use `(set-source-buffer buffer)` in code, whereby `buffer` is the name of the buffer to be selected. The above code returns `nil` when run on an active buffer. How do I fix this? --- # Update: I refer to the `if` statement provided by @Hubisan below. ``` (defun my-set-source-buffer (&optional buffer-or-name) "Sets `my-source-buffer' to `current-buffer' unless BUFFER-OR-NAME is given. BUFFER-OR-NAME can be a string of an existing buffer or a buffer object." (interactive "bSelect Source Buffer:") (setq my-source-buffer (if (buffer-live-p (get-buffer buffer)) (get-buffer buffer) (current-buffer)))) ``` When should we use `buffer-or-name` for a variable and when to use just `buffer` alone? # Answer > 3 votes * Use `cond` to bind either the buffer provided or the current buffer to my-source-buffer. No need for the extra line below. As there is actually only one condition an if statement would probably serve you better. * For the interactive line: Don't include the buffer variable. See Using-Interactive. * `(boundp 'buffer)` also returns `t` if `buffer` is nil as the symbol itself exists because it is an argument of the function. To check if buffer was provided a simple `(when buffer ...)` is enough. * It's advisable to prefix custom variables and functions with for instance `my-`. See Elisp \> Coding-Conventions. Adapted the names in the following code accordingly. ``` (defun my-set-source-buffer (&optional buffer-or-name) "Sets `my-source-buffer' to `current-buffer' unless BUFFER-OR-NAME is given. BUFFER-OR-NAME can be a string of an existing buffer or a buffer object." (interactive "bSelect Source Buffer:") (setq my-source-buffer (cond ;; Check if buffer is a buffer and if it still exists. ;; `get-buffer' is used to get the buffer by name if needed. ((buffer-live-p (get-buffer buffer-or-name)) (get-buffer buffer-or-name)) ;; Otherwise return the current buffer. (t (current-buffer)))) ;; Same with using if statement. ;; (setq my-source-buffer ;; (if (buffer-live-p (get-buffer buffer-or-name)) ;; (get-buffer buffer-or-name) ;; (current-buffer))) ) ``` The function can be called as follows: * with string of an existing buffer: `(my-set-source-buffer "*scratch*")` * with a buffer object: `(my-set-source-buffer (get-buffer "*scratch*"))` * interactively: `M-x my-set-source-buffer` and select the buffer interactively. --- Tags: buffers, interactive ---
thread-53661
https://emacs.stackexchange.com/questions/53661
C-c C-x f (org-footnote-action) cannot create a new footnote
2019-11-10T16:25:23.643
# Question Title: C-c C-x f (org-footnote-action) cannot create a new footnote I am used to create new footnotes in Emacs Org Mode with the key binding C-c C-x f. But now there are shown several options in the echo area, when I use this key binding, although the cursor is not on a footnote reference or definition. and I did not use a prefix argument. And I didn't change any variables or configurations (intentional). # Answer Let's look at the docstring of `org-footnote-action` (emphasis mine): > (org-footnote-action &optional SPECIAL) > > Do the right thing for footnotes. > > When at a footnote reference, jump to the definition. > > When at a definition, jump to the references if they exist, offer to create them otherwise. > > When neither at definition or reference, create a new footnote, interactively if possible. > > With prefix arg SPECIAL, or **when no footnote can be created**, offer additional commands in a menu. So it seems that when point is at beginning of line it is considered no footnote can be created. Arguably, this could be made more explicit. I actually wonder if it's a bug: the test is performed by function `org-footnote--allow-reference-p`, where one can read on the source (for org-version 9.1.14): ``` (defun org-footnote--allow-reference-p () "Non-nil when a footnote reference can be inserted at point." ;; XXX: This is similar to `org-footnote-in-valid-context-p' but ;; more accurate and usually faster, except in some corner cases. ;; It may replace it after doing proper benchmarks as it would be ;; used in fontification. (unless (bolp) ... ``` As we can see, the beginning of line test is the very first one. Also, it turns out that the mentionned `org-footnode-in-valid-context-p` function does return `t` when point is at beginning of line. > 2 votes # Answer By chance I found my mistake: The cursor was at the beginning of a line. But I don't understand exactly what's the problem. Perhaps it is in conjunction with the variable org-footnote-define-inline, which defines where the footnote appears. > 0 votes --- Tags: org-mode ---
thread-53667
https://emacs.stackexchange.com/questions/53667
How to disable stack with flycheck for Haskell?
2019-11-10T20:47:41.843
# Question Title: How to disable stack with flycheck for Haskell? I'm on nixos and due to stack's integration with Nix/Nixos the following command is very slow: ``` time stack ghc ghc: no input files Usage: For basic information, try the `--help' option. stack ghc 1.14s user 0.13s system 95% cpu 1.324 total ``` This means after a few keystrokes the emacs editor hangs... So I usually uninstall stack to remove it from the `$PATH`. How can I disable this, to avoid this really frustrating delay? In the messages: ``` haskell-stack-ghc: Flycheck checker haskell-stack-ghc returned non-zero exit code 1, ``` I have tried adding: ``` (add-to-list '(flycheck-disabled-checkers '(haskell-stack-ghc))) ``` to my init file, but there was no change in behavior. # Answer ``` (add-to-list 'flycheck-disabled-checkers 'haskell-stack-ghc) ``` The first argument to `add-to-list` is the name (more precisely the symbol) of the variable to modify. The second argument is the element (here again a symbol) to add. Both symbols need to be quoted since you need to pass the symbol itself to the function and not the value that the variable is bound to. > 1 votes # Answer ``` (setq-default flycheck-disabled-checkers '(haskell-stack-ghc)) ``` I had to set the above... > 0 votes --- Tags: flycheck, haskell-mode ---
thread-53673
https://emacs.stackexchange.com/questions/53673
How to include lines in a regular expression search which might not be present?
2019-11-11T00:42:20.767
# Question Title: How to include lines in a regular expression search which might not be present? I'm using a regular expression search which is working as expected. This searches for unified diff file entries and works as expected. ``` (re-search-forward (concat ;; Prefix '+++ '. "^" "\\-\\-\\-[[:blank:]]+.*\n" "\\+\\+\\+[[:blank:]]+.*\n" ;; May have trailing text which can be safely ignored. "@@[[:blank:]]+.*[[:blank:]]@@") nil t 1) ``` However some diffs have leading lines, eg: ``` // some context text. diff --git a/my_source.c b/my_source.c index 43484a57f1c..5985d498606 100644 --- a/my_source.c +++ b/my_source.c // some other context text. ``` My question is: How can I include lines in the search which may or may not exist? In this case: `diff` and `index`. I tried this but it doesn't work, the `\n` literals prevent the following `^` from being detected. ``` (re-search-forward (concat ;; This fails :( "\\(\\|^diff[[:blank:]]+.*\n\\)" "\\(\\|^index[[:blank:]]+.*\n\\)" ;; Prefix '+++ '. "^" "\\-\\-\\-[[:blank:]]+.*\n" "\\+\\+\\+[[:blank:]]+.*\n" ;; May have trailing text which can be safely ignored. "@@[[:blank:]]+.*[[:blank:]]@@") nil t 1) ``` How can these lines be included in the search if they exist, otherwise left as empty groups if they aren't present? # Answer `?` is the zero-or-one quantifier: `\\(...\\)?` says the group may or may not match anything. Make it non-capturing if you don't care about backreferences to that group: `\\(?:...\\)?` > I tried this but it doesn't work, the `\n` literals prevent the following `^` from being detected. `^` only has its special meaning in certain positions; You can't put it anywhere and have it mean "the beginning of a line". `C-h``i``g` `(elisp)Regexp Special` explains: ``` For historical compatibility reasons, ‘^’ can be used only at the beginning of the regular expression, or after ‘\(’, ‘\(?:’ or ‘\|’. ``` More specifically, if you *do* use it in other positions then it matches a literal `^` character (but if you want to match a `^` then it's preferable -- for the sake of readability -- to escape it, even in these cases where you can get away without escaping it). But note that you don't need a `^` to match the beginning of a line if the previous matched character was *guaranteed* to be a newline. > 2 votes --- Tags: regular-expressions, search ---
thread-53675
https://emacs.stackexchange.com/questions/53675
which-function-mode and modified mode line
2019-11-11T04:04:07.197
# Question Title: which-function-mode and modified mode line I modified my mode-line, but now `which-function-mode` stopped working: nothing is displayed. Code: ``` (setq mode-line-position (list '(:eval (propertize "L%l " 'face nil 'help-echo "Line number")) '(:eval (propertize "C%C " 'face nil 'help-echo "Column number")) (list -3 (propertize "%P" 'face nil 'help-echo "Position in buffer")) '(:eval (when (buffer-file-name) (propertize " %I" 'face 'font-lock-variable-name-face 'help-echo "Buffer size"))))) (setq mode-line-modified (list '(:eval (propertize "%*" 'face nil 'help-echo "Buffer read-only and modification indicator")) '(:eval (propertize "%+" 'face nil 'help-echo "Buffer read-only and modification indicator")))) (setq mode-line-buffer-identification (list '(:eval (propertize "%12b" 'face 'mode-line-buffer-id 'help-echo default-directory)))) (setq-default mode-line-format (list "%e" mode-line-position " " mode-line-modified " " mode-line-buffer-identification " " mode-line-modes " " mode-line-misc-info )) (which-function-mode) ``` `which-function-mode` uses `mode-line-misc-info`, which I did not modify. Its value is ``` ((which-function-mode (which-func-mode (#1="" which-func-format " "))) (global-mode-string (#1# global-mode-string " "))) ``` Why isn't it showing anything then? (Nothing is displayed if Emacs is started with this code as `~/.emacs`.) # Answer > 0 votes Don't evaluate list when you set `mode-line-format`. Use `'` instead of `list`: ``` (setq-default mode-line-format '("%e" mode-line-position " " mode-line-modified " " mode-line-buffer-identification " " mode-line-modes " " mode-line-misc-info )) ``` At the moment you set `mode-line-format` there are no `which-function-mode` related code in the `mode-line-misc-info`. See Quoting. --- Tags: mode-line, quote, which-function-mode ---
thread-53678
https://emacs.stackexchange.com/questions/53678
Get verbatim output of 'curl wttr.in' in org src code
2019-11-11T13:02:30.130
# Question Title: Get verbatim output of 'curl wttr.in' in org src code I want to record the weather info within org with commands ``` #+BEGIN_SRC shell :results output curl wttr.in/place #+END_SRC #+RESULTS: #+begin_example Weather report: place [38;5;226m \ / [0m Clear [38;5;226m .-. [0m [38;5;047m7[0m °C[0m [38;5;226m ― ( ) ― [0m [1m↑[0m [38;5;046m0[0m km/h[0m [38;5;226m `-’ [0m 10 km[0m [38;5;226m / \ [0m 0.0 mm[0m ``` The gibberish get outputted however, How could get it display as 'curl wttr.in' work on terminal ? # Answer > 6 votes Use the `T` option to turn off the color (you can learn all possible options on http://wttr.in/:help, I learnt this from https://github.com/chubin/wttr.in): > T # switch terminal sequences off (no colors) For example, ``` #+BEGIN_SRC sh :results output curl 'wttr.in/?0T' #+END_SRC #+RESULTS: : Weather report: Yancheng, China : : \ / Partly cloudy : _ /"".-. 15..16 °C : \_( ). ← 12 km/h : /(___(__) 10 km : 0.0 mm ``` The `0` option means only current weather. --- There is also a hard way suggested by @legoscia's answer, you can remove the ansi escape sequences with `ansi-color-apply` (it translates the ascii escape color codes into text props which can be easily ignored or stripped). ``` #+NAME: strip #+BEGIN_SRC elisp :var text="\e[31mHello world\e[0m" (ansi-color-apply text) #+END_SRC #+RESULTS: strip : Hello world #+BEGIN_SRC sh :results output :post strip(*this*) curl 'wttr.in/?0' #+END_SRC #+RESULTS: : Weather report: Yancheng, China : : \ / Partly cloudy : _ /"".-. 15..16 °C : \_( ). ← 12 km/h : /(___(__) 10 km : 0.0 mm ``` The `:post` header is documented in the org manual, see (org) post. # Answer > 4 votes You can use `ansi-color` to format the text. It doesn't have an interactive function, so you need to evaluate something like: ``` (require 'ansi-color) (ansi-color-apply-on-region (point) (point-max)) ``` That would treat the output in the current buffer from point to the end of buffer. Note that some of the formatting gets lost if you save the file, close it, and open it again. --- Tags: org-mode ---
thread-53658
https://emacs.stackexchange.com/questions/53658
Forcing Speedbar's Sorting Order of Org File Headers to Mirror File's
2019-11-10T09:28:44.817
# Question Title: Forcing Speedbar's Sorting Order of Org File Headers to Mirror File's I use both org-sidebar (https://github.com/alphapapa/org-sidebar/) and Speedbar to navigate Org files. Both have minor issues. However, I find Speedbar works best, but it has a terrible habit of sorting headers in an order different to that of the file. In particular, headings with no sub-headings (such as when drafting an outline) are always displayed after headings with sub-headings. Does anybody know how to force the headeings' sort order in Speedbar to match that of the file's? # Answer The variable `speedbar-tag-hierarchy-method` has a doc-string that states in relevant part: "*List of hooks which speedbar will use to organize tags into groups.*" The list can contain values such as: `speedbar-prefix-group-tag-hierarchy`; `speedbar-trim-words-tag-hierarchy`; `speedbar-simple-group-tag-hierarchy`; `speedbar-sort-tag-hierarchy`. The original poster has stated a preference that the tags *not* be sorted; i.e., that the order in which they appear be the same as the order in the file from which they were gathered. In a comment underneath the question, the O.P. has indicated that he is happy with setting the above-mentioned variable to `nil`. It may be preferable, however, to nevertheless keep a non-offending value such as trimming the words; e.g. ``` (setq speedbar-tag-hierarchy-method '(speedbar-trim-words-tag-hierarchy)) ``` > 1 votes --- Tags: org-mode, speedbar ---
thread-53676
https://emacs.stackexchange.com/questions/53676
Display all the months from M-x calendar
2019-11-11T07:18:18.570
# Question Title: Display all the months from M-x calendar M-x calendar would display a three-month calendar and C-u M-x calendar could select the center of the three month. How could display an arbitrary numbers of months, for instance view all the month in 2019 as bash command: ``` ncal -M 2019 ``` # Answer The original poster has indicated in a comment underneath the question that the suggestion of looking at the `calfw` library https://github.com/kiwanami/emacs-calfw is sufficient to suit his/her needs. However, that library does not do exactly what the question seeks to answer. Instead, it has built-in views for 1-month, 2-weeks, 1-week, 1-day. There is no 12-month view, despite the fact that I erroneously stated it did in my comment. \[Ooops ... sorry.\] Nevertheless, the `calfw` library is very popular and I use it myself. The closest thing that I am aware of that actually answers the call of the question is a thread from several years ago on stackoverflow ("*Emacs calendar: show more than 3 months?*"): https://stackoverflow.com/questions/9547912/emacs-calendar-show-more-than-3-months > 2 votes --- Tags: calendar ---
thread-53683
https://emacs.stackexchange.com/questions/53683
Melpa - 'Failed to download melpa'
2019-11-11T17:45:15.090
# Question Title: Melpa - 'Failed to download melpa' I am on a fresh install of emacs 26.3, and I have the following in my `init.el`: ``` (require 'package) (add-to-list 'package-archives '("melpa", "http://melpa.org/packages/") t) (package-initialize) ``` When I go to refresh the package list (`M-x package-refresh-contents`) I encounter the following error: ``` string-match("\\`https?:" ((\, "http://melpa.org/packages/")) nil) package--download-one-archive(("melpa" (\, "http://melpa.org/packages/")) "archive-contents" t) package--download-and-read-archives(t) package-refresh-contents(t) package-menu-refresh() package-list-packages(nil) funcall-interactively(package-list-packages nil) call-interactively(package-list-packages record nil) command-execute(package-list-packages record) execute-extended-command(nil "package-list-packages" "package-lis") funcall-interactively(execute-extended-command nil "package-list-packages" "package-lis") call-interactively(execute-extended-command nil nil) command-execute(execute-extended-command) ``` What is happening and why doesn't this work? I have seen some chatter on related issues that ``` (setq gnutls-algorithm-priority "NORMAL:-VERS-TLS1.3") ``` before `(package-initialize)` should resolve this issue, but it doesn't. # Answer The error seems to be saying that `((\, "http://melpa.org/packages/"))` doesn't match the regex ``` "\`https?:" ``` Let's look at that value, the one being added to `package-archives`: ``` '("melpa", "http://melpa.org/packages/") ``` If we put this into `IELM`, let's see what we get: ``` ELISP> '("melpa", "http://melpa.org/packages/") ("melpa" (\, "http://melpa.org/packages/")) ``` Oh! This is not what we expect! The `cdr` of this list is a proper list (we want a string), and *that* has a comma as the first character. What happened here? What is each element of `package-archives` supposed to be? > package-archives is a variable defined in ‘package.el’. > > Each element has the form (ID . LOCATION). A period instead of a comma makes this a single cons cell, and not a proper list. The proper code is: ``` (add-to-list 'package-archives '("melpa" . "https://melpa.org/packages/") t) ``` > 11 votes --- Tags: debugging, list ---
thread-53610
https://emacs.stackexchange.com/questions/53610
How to disable the release notes in spacemacs?
2019-11-07T11:43:34.953
# Question Title: How to disable the release notes in spacemacs? Is there a simple setting to disable the release notes in the startup screen, rather than modifying the core.el here? https://github.com/syl20bnr/spacemacs/blob/master/core/core-spacemacs-buffer.el#L360 # Answer You can toggle the \[Release Notes\] link in the spacemacs buffer to hide the release notes - they should stay hidden after restarting from now on. > 6 votes --- Tags: spacemacs ---
thread-53666
https://emacs.stackexchange.com/questions/53666
How to run "ert" tests?
2019-11-10T20:33:16.437
# Question Title: How to run "ert" tests? What I tried: ``` Cloned a package with ert tests (https://github.com/dgutov/robe ) # sidenote this package was previously installed using use-package emacs ~/robe/core-tests.el M-x ert ``` > Selector: t Passed: 0 Failed: 0 Skipped: 0 Total: 0/0 Started at: 2019-11-10 12:31:14-0800 Finished. Finished at: 2019-11-10 12:31:14-0800 This feels wrong because obviously the package has more than 0 tests. Also btw: how do I run tests in "emacs -batch" mode. # Answer When you ran `emacs ~/robe/core-tests.el`, that opened up the file in your Emacs, right? Then the tests themselves have to be loaded into Emacs. The `ert` tests are written in ELisp, so you need to evaluate that file. That can be done with `M-x eval-buffer`, or if the file is not open, you can run `M-x load-file`. Then `M-x ert` will run those tests. Simply opening the file is not enough. > 8 votes --- Tags: ert ---
thread-46673
https://emacs.stackexchange.com/questions/46673
Babel + Python function definition with for loop causes IndentationError
2018-12-18T20:10:56.793
# Question Title: Babel + Python function definition with for loop causes IndentationError I am using orgmode and Babel to run Python source code blocks. I noticed that if I define a function that returns a value, and if this function has a for loop inside it, then evaluating it with Babel leads to an `IdentationError: unexpected indent`. For example, in org-mode write the following: ``` #+BEGIN_SRC python :results silent :session pysession def foo(): for _ in range(1): pass return 1 print(foo()) #+END_SRC ``` Then calling `C-c C-c` sends the code to the `pysession` buffer running the Python session, and it results in the error `IdentationError: unexpected indent`. However, if we remove the for loop from the function definition, then things just work (prints 1): ``` #+BEGIN_SRC python :results silent :session pysession def foo(): return 1 print(foo()) #+END_SRC ``` **Question**: How to fix this behavior so that I can define functions with loops and have them work with babel? **Edit 1:** The `print` can be removed from the code and the error still arises. The `:results silent` option is necessary since I do not want results in my org-file. **Edit 2:** I noticed that when `:results silent` is selected and `C-c C-c`, it appears that Babel is sending the code line by line to the session, but when the line that contains the `pass` is send, Babel for some reason sends another `RET`, which makes the python REPL finish defining the function `foo` without any return statement. Then, when the line containing `return 1` is sent, it is evaluated out of the scope of the function and causes the indentation error!!! At this doc page it says: > Session mode in python is slightly different from non-session mode ... blank lines are special: they indicate the end of an indented block But in this case it is not working at all: there is no line between `pass` and `return 1`, but Babel is treating as if there was, since it is thinking the indented block is ended after `pass`. It seems there is some bug with the backend. When we use `:results output`, Babel actually saves the contents of the code block as is in a temporary file. It then reads the file and evaluates it in Python with `exec`. Since Python gets the entire code at once it works. Thanks for helping! # Answer For best results and features edit code blocks by running in a dedicated buffer using `org-edit-special`. With pointer in the code block type `ctrl-c``'` `org-edit-src-code` that will open in your case a python buffer with your hooks, the configured indentations and all. Use `ctrl-c``'` to return to the org file. from gnu.org: > C-c ' for editing the current code block. It opens a new major-mode edit buffer containing the body of the ‘src’ code block, ready for any edits. C-c ' again to close the buffer and return to the Org buffer. > > C-x C-s saves the buffer and updates the contents of the Org buffer. > > Set org-edit-src-auto-save-idle-delay to save the base buffer after a certain idle delay time. > > Set org-edit-src-turn-on-auto-save to auto-save this buffer into a separate file using auto-save-mode. > > C-c ' to close the major-mode buffer and return back to the Org buffer. > > While editing the source code in the major-mode, the org-src-mode minor mode remains active. It provides these customization variables as described below. For even more variables, look in the customization group org-edit-structure. For more details and how to configure specifically editing-source-code > 0 votes # Answer I cannot reproduce your error. On my system, the answer is `nil`. But if you change the header to `:results output :session pyssesion` the result of evaluating is OK. See this for further explanations. Of coarse, some other configurations/settings may be needed if the error will be the same. > 0 votes # Answer I'm not 100% that the issue you have is the same one I did, but I solved it with: `(setq org-src-preserve-indentation t)` > 0 votes --- Tags: org-mode, org-babel, indentation, python ---
thread-53688
https://emacs.stackexchange.com/questions/53688
Retrieve the lunar phases to diary.org as a record
2019-11-12T00:37:48.587
# Question Title: Retrieve the lunar phases to diary.org as a record I tried to record the sunrise and sunset info to the diary ``` #+begin_src emacs-lisp :tangle yes (sunrise-sunset) ;;(lunar-phases) #+end_src #+RESULTS: : Sunrise 6:57am (CST), sunset 5:00pm (CST) at 40.0N, 116.3E (10:03 hrs daylight) ``` `sunrise-sunset` worked as expected, But to lunar-phases ``` #+begin_src emacs-lisp :tangle yes ;;(sunrise-sunset) (lunar-phases) #+end_src #+RESULTS: : Computing phases of the moon...done ``` How could get the lunar phases as it print to the echo area? # Answer > 1 votes In the following example, the month has been hard-coded to be the 11th month of the year (i.e., November), and the year has been hard-coded to be the year 2019. \[How did I come up with this example? I typed `M-x find-function RET lunar-phases RET`; and, then I placed my cursor on `calendar-lunar-phases` and repeated the `find-function`; and, then I extracted the guts of that latter function and came up with the examples below based upon the extracted code.\] ``` (let ((month 11) (year 2019)) (require 'lunar) (mapcar (lambda (x) (format "%s: %s %s" (calendar-date-string (car x)) (lunar-phase-name (nth 2 x)) (cadr x))) (lunar-phase-list month year))) ``` For a pretty formatted *return value*, use .... ``` (let ((month 11) (year 2019)) (require 'lunar) (mapconcat (lambda (x) (format "%s: %s %s" (calendar-date-string (car x)) (lunar-phase-name (nth 2 x)) (cadr x))) (lunar-phase-list month year) "\n")) ``` Which gives us a *return value* as follows: ``` Monday, November 4, 2019: First Quarter Moon 2:24am (PST) Tuesday, November 12, 2019: Full Moon 5:34am (PST) Tuesday, November 19, 2019: Last Quarter Moon 1:17pm (PST) Tuesday, November 26, 2019: New Moon 7:08am (PST) Tuesday, December 3, 2019: First Quarter Moon 10:59pm (PST) Wednesday, December 11, 2019: Full Moon 9:11pm (PST) Wednesday, December 18, 2019: Last Quarter Moon 9:03pm (PST) Wednesday, December 25, 2019: New Moon 9:16pm (PST) Thursday, January 2, 2020: First Quarter Moon 8:47pm (PST) Friday, January 10, 2020: Full Moon 11:20am (PST) Friday, January 17, 2020: Last Quarter Moon 5:04am (PST) Friday, January 24, 2020: New Moon 1:44pm (PST) ``` --- Tags: org-babel ---
thread-20954
https://emacs.stackexchange.com/questions/20954
Compile from parent directory in Emacs
2016-03-13T22:49:04.070
# Question Title: Compile from parent directory in Emacs I'm trying to map `F5` to compile from a parent directory of the current buffer. Emacs compile-command find makefile in superior directory provides an excellent answer to achieve this: ``` (defun compile-project () (interactive) (let* ((make-directory (locate-dominating-file (buffer-file-name) "Makefile")) (command (concat "make -k -C " (shell-quote-argument make-directory)))) (compile command))) (global-set-key (kbd "<f5>") 'compile-project) ``` Besides, C/C++ Development Environment for Emacs describes a way such that `F5` does not prompt for the compile command every time, but if a prefix argument `C-u` is provided, then `compile` prompts for a compile command: ``` (global-set-key (kbd "<f5>") (lambda () (interactive) (setq-local compilation-read-command nil) (call-interactively 'compile))) ``` **Question:** How can I modify the `compile-project` function, so that when a prefix command `C-u` is provided, it shows the compilation command in the mini-buffer, including a default command of `make -k -C ...` generated by the body of `let*`? # Answer > 2 votes I think that you almost had it. I modified your original `compile-project` as follows: ``` (defun compile-project () (interactive) (let* ((mk-dir (locate-dominating-file (buffer-file-name) "Makefile")) (compile-command (concat "make -k -C " (shell-quote-argument mk-dir))) (compilation-read-command nil)) (call-interactively 'compile))) ``` The only real difference is that the `compile` function reads from `compilation-read-command` to figure out how to read the compilation command *and* `compile-command`. If you set `compilation-read-command` to nil, `compile` will use the value of `compile-command` instead of prompting. (Also, all of this is available in `M-x` `describe-function` `compile` if you need to look up something more.) # Answer > 0 votes This is an expanded version of @Xaldew's answer that... * Checks for multiple kinds of makefile. * Reports when the makefile isn't found. ``` (defun locate-dominating-file-multi (dir compilation-filenames) "Search for the compilation file traversing up the directory tree. DIR the base directory to search. COMPILATION-FILENAMES a list pairs (id, list-of-names). Note that the id can be any object, this is intended to identify the kind of group. Returns a triplet (dir, filename, id) or nil if nothing is found. " ;; Ensure 'test-dir' has a trailing slash. (let ( (test-dir (file-name-as-directory dir)) (parent-dir (file-name-directory (directory-file-name dir))) ) (catch 'mk-result (while (not (string= test-dir parent-dir)) (dolist (test-id-and-filenames compilation-filenames) (cl-destructuring-bind (test-id test-filenames) test-id-and-filenames (dolist (test-filename test-filenames) (when (file-readable-p (concat test-dir test-filename)) (throw 'mk-result (list test-dir test-filename test-id)) ) ) ) ) (setq test-dir parent-dir parent-dir (file-name-directory (directory-file-name parent-dir)) ) ) ) ) ) (defun compile-from-any-makefile () (interactive) (let* ( (mk-reference-dir (expand-file-name ".")) (mk-dir-file-id (locate-dominating-file-multi mk-reference-dir (list '("make" ("Makefile" "makefile" "GNUmakefile")) '("ninja" ("build.ninja")) '("scons" ("SConstruct")) ) ) ) ) (if mk-dir-file-id (cl-destructuring-bind (dir file id) mk-dir-file-id (let ( ;; ensure 'compile-command' is used. (compilation-read-command nil) (compile-command (cond ((string= id "make") (concat "make -C " (shell-quote-argument dir))) ((string= id "ninja") (concat "ninja -C " (shell-quote-argument dir))) ((string= id "scons") (concat "scons -C " (shell-quote-argument dir))) (t (error "Unhandled type (internal error)")) ) ) ) (call-interactively 'compile) ) ) (message "No makefile found in %S" mk-reference-dir) ) ) ) ``` --- Tags: compilation, interactive, prefix-argument ---
thread-46501
https://emacs.stackexchange.com/questions/46501
Fontify headline with todo keyword color
2018-12-09T22:39:00.593
# Question Title: Fontify headline with todo keyword color I would like to fontify headlines with the same color/weight as their TODO keywords. So for example, the default is like this: **TODO** Headline And I want it to look like this: **TODO Headline** Any ideas? # Answer You can find out what face is applied to the text under point (the cursor) with the command `M-x describe-face`. By doing this, I learned that the face applied to `TODO` keywords is called `org-todo`. The Face for top-level headings is `org-level-1`. You can customize faces using via `M-x customize-face`. You can set attributes individually, or you can apply the attributes from one face directly to another using the **Inherit** attribute. In your case, set the **Inherit** attribute for `org-level-1` to `org-todo`. When you're done, `C-c C-c` in the customize buffer will set your changes temporarily, and `C-c C-s` will save them permanently. > 1 votes # Answer For DONE-keywords, there is a variable `org-fontify-done-headline` that activates fontification of the whole headline. To do this also for "not-done" keywords, we have to add a similar extra font-lock rule for org. The easiest way to do this is by modifying `org-font-lock-extra-keywords` using `org-font-lock-set-keywords-hook` (this then runs when initializing each buffer, as TODO-keywords etc. can vary). The following works for the case of fontifying “not-done” headlines: ``` (defface aj/org-headline-todo '((t :inherit org-todo :weight normal)) "Face for TODO headlines." :group 'org-faces) (defun aj/org-fontify-todo-headlines () "Add rule for fontifying not-done headlines in org-mode." (push (list (format org-heading-keyword-regexp-format org-not-done-regexp) '(2 'aj/org-headline-todo t)) org-font-lock-extra-keywords)) (add-hook 'org-font-lock-set-keywords-hook #'aj/org-fontify-todo-headlines) ``` The custom face that inherits from `org-todo` can of course be customized to suit your needs. > 1 votes --- Tags: org-mode, font-lock, todo ---
thread-32396
https://emacs.stackexchange.com/questions/32396
Complete path numbering of org-mode headlines and plain lists
2017-04-26T17:25:54.910
# Question Title: Complete path numbering of org-mode headlines and plain lists I would like to get the complete hierarchy numbers in the plain lists of org-mode Instead of this: ``` 1. something 1. something 2. something 1. something 2. something 1. something 2. something 3. something ``` I'm looking for something like this: ``` 1. something 1.1. something 1.2. something 1.2.1. something 2. something 2.1. something 2.2. something 2.3. something ``` And the same thing in headlines. Instead of this: ``` * chapter ** section A ** section B *** subsection * chapter ** section A ** section B ``` this: ``` * 1. chapter ** 1.1. section A ** 1.2. section B *** 1.2.1. subsection * 2. chapter ** 2.1. section A ** 2.2. section B ``` This helps me to see how many children a headline has and where I am. EDIT: Is it at least possible to get the table of contents with the complete numbering of the headlines (for easier navigating in the org document)? New EDIT: I mean a new buffer with just these lines (the items are empty): ``` * 1. chapter ** 1.1. section A ** 1.2. section B *** 1.2.1. subsection * 2. chapter ** 2.1. section A ** 2.2. section B ``` Of course every line of the "new buffer" should be linked with the corresponding headline of the org document: So by clicking or typing "RETURN" I can go to the headline directly. I know that by exporting to txt I can get the TOC but there aren't the links to the headlines. What I'm looking for (meanwhile) is a function that construct the toc with numbers and with links. # Answer > 4 votes Here is a lightly tested approach to use overlays on the headings. This will work up to 9th level headings (one less zero than is in the counters). ``` (require 'cl) (require 'dash) (defun overlay-numbered-headings () "Put numbered overlays on the headings." (interactive) (loop for (p lv) in (let ((counters (copy-list '(0 0 0 0 0 0 0 0 0 0))) (current-level 1) last-level) (mapcar (lambda (x) (list (car x) ;; trim trailing zeros (let ((v (nth 1 x))) (while (= 0 (car (last v))) (setq v (butlast v))) v))) (org-map-entries (lambda () (let* ((hl (org-element-context)) (level (org-element-property :level hl))) (setq last-level current-level current-level level) (cond ;; no level change or increase, increment level counter ((or (= last-level current-level) (> current-level last-level)) (incf (nth current-level counters))) ;; decrease in level (t (loop for i from (+ 1 current-level) below (length counters) do (setf (nth i counters) 0)) (incf (nth current-level counters)))) (list (point) (-slice counters 1))))))) do (let ((ov (make-overlay p (+ 1 p)))) (overlay-put ov 'display (concat (mapconcat 'number-to-string lv ".") ". ")) (overlay-put ov 'numbered-heading t)))) (define-minor-mode numbered-org-mode "Minor mode to number org headings." :init-value nil (if numbered-org-mode (overlay-numbered-headings) (ov-clear 'numbered-heading))) ``` # Answer > 5 votes Org mode from version 9.3 includes the library `org-num`. Activating `org-num-mode` displays the outline numbers for headlines as overlays that updates automatically when editing. There are also customization options for excluding trees that are commented, have special tags, or have the `UNNUMBERED` property. # Answer > 1 votes An alternative implementation of the overlay solution provided in John Kitchin’s answer is to just use the standard functions from `org-export`. I have wrapped this up in a small library here: https://gitlab.com/andersjohansson/org-outline-numbering The core is this function (which serves as a direct replacement for Kitchin’s `overlay-numbered-headings`): ``` (require 'ox) (require 'cl-lib) (require 'ov) (defun org-outline-numbering-overlay () "Put numbered overlays on the headings." (interactive) (cl-loop for (p lv) in (let* ((info (org-combine-plists (org-export--get-export-attributes) (org-export--get-buffer-attributes) (org-export-get-environment) '(:section-numbers t))) (tree (org-element-parse-buffer)) numberlist) (org-export--prune-tree tree info) (setq numberlist (org-export--collect-headline-numbering tree info)) (cl-loop for hl in numberlist collect (cons (org-element-property :begin (car hl)) (list (cdr hl))))) do (let ((ov (make-overlay p (+ (length lv) p)))) (overlay-put ov 'display (concat (mapconcat 'number-to-string lv ".") ". ")) (overlay-put ov 'numbered-heading t) (overlay-put ov 'face 'default)))) ``` --- Tags: org-mode ---
thread-53693
https://emacs.stackexchange.com/questions/53693
Unable to bind keys `M-[` and `M-]`
2019-11-12T10:04:25.173
# Question Title: Unable to bind keys `M-[` and `M-]` I'm trying to bind `M-[` and `M-]` to the following functions (courtesy of Xah Lee): ``` (defun xah-forward-block (&optional n) "Move cursor beginning of next text block. A text block is separated by blank lines. This command similar to `forward-paragraph', but this command's behavior is the same regardless of syntax table. URL `http://ergoemacs.org/emacs/emacs_move_by_paragraph.html' Version 2016-06-15" (interactive "p") (let ((n (if (null n) 1 n))) (re-search-forward "\n[\t\n ]*\n+" nil "NOERROR" n))) (defun xah-backward-block (&optional n) "Move cursor to previous text block. See: `xah-forward-block' URL `http://ergoemacs.org/emacs/emacs_move_by_paragraph.html' Version 2016-06-15" (interactive "p") (let ((n (if (null n) 1 n)) ($i 1)) (while (<= $i n) (if (re-search-backward "\n[\t\n ]*\n+" nil "NOERROR") (progn (skip-chars-backward "\n\t ")) (progn (goto-char (point-min)) (setq $i n))) (setq $i (1+ $i))))) (global-set-key (kbd "<M-[>") 'xah-backward-block) (global-set-key (kbd "<M-]>") 'xah-forward-block) ``` After I add the above code to the init file and save, and then do `M-x eval-buffer` or restart, it doesn't take effect. When I try to move or look them up via `C-h k` it says `M-[` or `M-]` is undefined. But I can see them listed in the describe-bindings buffer via `C-h b`. I also tried to escape the brackets as `\[` and `\]` because I thought maybe they're special characters, but still I've got the same result. But when I change the brackets to arrow keys it works. The version of Emacs I use is 26.2 and OS is Fedora 30. I've checked a lot of places and still haven't found the solution. # Answer Substrings in the `kbd` argument that are delimited by `<` and `>` are labels for non-character input events such as `<mouse-2>`. But, with `[` you mean the character `[` and with `M-` you mean the meta modifier. So `<` and `>` are inappropriate in your use-case. Use `(kbd "M-[")` instead of `(kbd "<M-[>")`. > 7 votes --- Tags: key-bindings ---
thread-53698
https://emacs.stackexchange.com/questions/53698
Replace full-width numerals with half-width numerals
2019-11-12T14:03:16.853
# Question Title: Replace full-width numerals with half-width numerals I'd like to convert numerals from half-width to full-width characters with a simple regex search and replace as follows: > replace-regexp-in-string *regexp rep string &optional fixedcase literal subexp start* ``` (replace-regexp-in-string '(0 1 2 3 4 5 6 7 8 9) '(0 1 2 3 4 5 6 7 8 9)) ``` Evaluating the above code in a buffer gave me this error: `(wrong-number-of-arguments (3 . 7) 2)` I suppose the missing argument is the *string*, which I assumed would take care of itself when I evaluate the code using `M-:` on a buffer. How do I do this correctly? --- # Follow-up Question: I would like to abstract the commands given in @Tobias' answer into a single function, so that I can call them with a single key-binding. Here's my attempt: ``` (defun num-half2full (query-replace-regexp [0-9] /,(string (+ (string-to-char \&) (- ?0 ?0))))) ``` ## Error: ``` (error "Malformed arglist: (query-replace-regexp [0-9] / (, (string (+ (string-to-char &) (- 65296 48)))))") ``` --- # My last attempt at writing the function: (defun num-full2half () "Convert numbers from full-width to half-width" (interactive) (goto-char (point-min)) (replace-regexp "\[0-9\]" (quote (replace-eval-replacement replace-quote (string (+ (string-to-char (match-string 0)) 48 (- 65296))))))) The expected replacement did not take place in the buffer at which M-x\<\kbd\>(num-full2half) was called. # Answer No, `regplace-regexp-in-string` does not magically substitute the buffer string into the `STRING` argument. It is a function but not a command (does not have an interactive specification). The command you are actually looking for is `query-replace-regexp` which can be used interactively and is bound to `C-M-%`. Use: `C-M-%` `[0-9]` `RET` `\,(string (+ (string-to-char \&) (- ?0 ?0)))` `RET` to replace normal digit chars with wide digit chars. The escape sequence `\,(...)` allows you to call Elisp from the replacement string. In our case the regexp is the character group `[0-9]` of normal digits. Used Elisp forms: * ?0 and `?0` give the character codes for the wide zero char and the normal zero char (e.g., ASCII code 48 for `?0`) * `(- ?0 ?0)` computes the offset between the wide digit zero char and the normal digit zero char * `\&` is replaced with the match string, (e.g., `"1"`) * `(string-to-char \&)` delivers the char code of the first char in the match string, (in our case the match string only contains one digit char) * `(+ (string-to-char \&) (- ?0 ?0)))` adds the offset between wide digits and normal digits to the found digit char. * `(string (+ (string-to-char \&) (- ?0 ?0))))` Generates a string containing only the wide digit char that we just have calculated. --- The inverse is also possible: Use: `C-M-%` `[0-9]` `RET` `\,(string (+ (string-to-char \&) (- ?0 ?0)))` `RET` to replace wide digit chars with normal digit chars. The essential differences to the `query-replace` above are: * we search for wide digit chars instead of normal digit chars * we have changed the sign of the offset `(- ?0 ?0)` instead of `(- ?0 ?0)` --- The command `M-x` `list-command-history` `RET` reveals the actually called command: ``` (query-replace-regexp "[0-9]" (quote (replace-eval-replacement replace-quote (string (+ (string-to-char (match-string 0)) 48 (- 65296))))) nil nil nil nil nil) ``` As Elisp beginner you can just use that code in your Elisp function. (Even if the doc-string of `query-replace-regexp` says that this function is for interactive use only.) If you want to avoid the query you can remove the prefix `query-` and all the nils at the tail of the argument list: ``` (replace-regexp "[0-9]" (quote (replace-eval-replacement replace-quote (string (+ (string-to-char (match-string 0)) 48 (- 65296)))))) ``` --- Now a word about what the doc string of `query-replace-regexp` actually suggests. It wants you to write a loop: ``` (goto-char (point-min)) ;; maybe first go to the beginning of the accessible buffer (while (re-search-forward "[0-9]" nil t) (replace-match (string (+ (string-to-char (match-string 0)) (- ?0 ?0)))) ``` > 3 votes --- Tags: regular-expressions, replace ---
thread-53697
https://emacs.stackexchange.com/questions/53697
Disable indenting on org-babel restclient edits
2019-11-12T13:10:35.687
# Question Title: Disable indenting on org-babel restclient edits Despite I am not a new Emacs user, my elisp is nearly not existent. I want to present some REST API stuff with epresent and org babel restclient. This is working fine until I want to edit a source block (request) inline during the presentation. You can reproduce this by using the following org structure ``` * Testitem #+begin_src restclient #Get URL: GET https://www.bing.com #+end_src ``` I tried to disable electric indent mode in my init.el to check if this is the reason, but no luck. ``` (electric-indent-local-mode -1) ``` If I call the edit function (I need to change an URL param, due to preceding requests within the presentation) and confirm the edit with **C-c '**, the code is indented by 2 spaces and the source snippet is not shown/working anymore in epresent hereafter. It changed to: ``` * Testitem #+begin_src restclient #Get URL: GET https://www.bing.com #+end_src ``` Which is then not shown anymore and thus also not executable within epresent. Can anyone point me to the reason for the indentation of the restclient source block and how to disably this? # Answer > 3 votes Org mode indents code in src blocks by 2 spaces by default. To change this you can set `org-edit-src-content-indentation` to `0` for no indentation. Alternatively changing `org-src-preserve-indentation` to `t` may also achieve what you want to do. Some description of indentation behaviour is in this part of the manual. --- Tags: org-mode, org-babel, restclient ---
thread-40644
https://emacs.stackexchange.com/questions/40644
Attach files using org-mu4e
2018-03-24T13:51:29.310
# Question Title: Attach files using org-mu4e I am currently using org-mu4e with ``` (setq org-mu4e-convert-to-html t) ``` and `(org-mu4e-compose-org-mode)`. When I attach files to a email I get the classical ``` <#part type="application/type" filename="/somepath/somefile" disposition=attachment description=somedescription> <#/part> ``` inserted into the body, but when org-mode converts the body to html it somehow does nothing and the actual email displays the code `<#part.... #/part>` without including any file. Is there any workaround? I need the option `org-mu4e-convert-to-html` since I use LaTeX in my emails. # Answer You have to put the html code in ``` #+begin_export html #+end_export ``` block so that it is exported to html format via babel. Edit: I wrote "src" instead of export by mistake . > 0 votes # Answer The actual solution is to enclose the `<#part ...>` tag like this: ``` #+BEGIN_EXPORT html <#part ...> <#/part> #+END_EXPORT ``` > -1 votes --- Tags: org-mode, mu4e ---