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-55690
https://emacs.stackexchange.com/questions/55690
Org-Babel Javascript error
2020-02-21T22:44:44.400
# Question Title: Org-Babel Javascript error I am having trouble getting the simplest Javascript source block in org-mode to run. ``` #+begin_src js console.log("Hello"); #+end_src ``` I always get this error: ``` /tmp/babel-8kqQwQ/js-script-shBzKH:1 require('sys').print(require('sys').inspect(function(){ ^ TypeError: require(...).print is not a function at Object.<anonymous> (/tmp/babel-8kqQwQ/js-script-shBzKH:1:16) at Module._compile (internal/modules/cjs/loader.js:1151:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1171:10) at Module.load (internal/modules/cjs/loader.js:1000:32) at Function.Module._load (internal/modules/cjs/loader.js:899:14) at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12) at internal/main/run_main_module.js:17:47 ``` I am running on Spacemacs and did the configuration as described in the Org Wiki https://orgmode.org/worg/org-contrib/babel/languages/ob-doc-js.html OS is the latest Manjaro. Emacs 26.3 The funny thing is, I am running my Emacs on my other machine with the exact same config. Same OS, same Emacs, same `.spacemacs` file. No issues. I even did a fresh install of Spacemacs with the current config template on both systems. Same result. The desktop works, the notebook doesn't. I can only imagine that an external JS runner is missing or broken? I really don't know how to debug this. # Answer > 5 votes Looks like a bug as wasamasa said, but until that gets fixed this works for me: ``` (setq org-babel-js-function-wrapper "console.log(require('util').inspect(function(){\n%s\n}(), { depth: 100 }))") ``` If you want to print deeper or otherwise modify output, change the options for `require('util').inspect(...)` in that string, as documented here. If you want to print a value into org without explicitly calling `console.log` in your own source block, put a `return` statement in your source block: ``` #+BEGIN_SRC js return 1 + 1; #+END_SRC #+RESULTS: : 2 ``` # Answer > 2 votes Org supports evaluating JavaScript either via Node.js or mozrepl. Your error message suggests you're using Node, but your current version of it doesn't support the sys module. Which is kind of bad, consider reporting an Org bug about that. --- Tags: org-mode, org-babel ---
thread-56352
https://emacs.stackexchange.com/questions/56352
Can syntax parsing recognize the SQL '' (escape apostrophe/single quote) construct within SQL strings?
2020-03-25T13:46:55.747
# Question Title: Can syntax parsing recognize the SQL '' (escape apostrophe/single quote) construct within SQL strings? I am trying to enhance SQL mode such that editing of files of SQL code becomes more convenient, especially as far as jumping around is concerned (e.g. things like sql-goto-end-of-string etc.). I have found syntax parsing to be very useful in that, but have stumbled across one curious thing: SQL has the apostrophe as the string delimiter and the (as would seem to me) quirky idea of using, of all possibilities, a double apostrophe to denote a literal apostrophe within a string, i.e. the `'` doubles as its own escape character when it occurs two times in a row, such that `'McDonald''s'` in SQL means what would be written as e.g. `"McDonald's"` or `'McDonald\'s'` in some other languages. It would seem to mean to me that any SQL parser, when encountering an apostrophe inside a string, must always read the next character before it can decide whether this is the end of the string or rather a literal apostrophe inside it. As to Emacs in `sql-mode`, `(nth 3 (parse-partial-sexp (point-min) pos))` in sql-mode returns the following when parsing over such a construct (`^` denotes point): ``` 'McDonald''s' ^ --> 39 'McDonald''s' ^ --> nil 'McDonald''s' ^ --> 39 ``` In other words, it treats the sequence as two separate, abutting strings, `'McDonald'` and `'s'` (which of course do not exist in valid SQL syntax), presumably because `'` is simply the string terminator in `sql-mode-syntax-table` (`(char-to-string (char-syntax ?'))` returns `"\""` and is simply described as `" which means: string` by `describe-syntax`). My **question** is whether Emacs is in principle capable of parsing this construct correctly, if, e.g., given a more complex syntax table entry for `'`. I see it **is** capable of parsing two-character comment delimiters, such that `/` has a specific meaning when followed by `*`, and `*` is specific when inside a comment and followed by `/`. The provisions in syntax tables for such sequences, which AFAIU seem to be the syntax flags, seem to be specific to comments, however, and the exact problem also seems to be different (I cannot think of an example of a single "end comment" character that is escaped with itself in the languages that I am familiar with, at least), as far as I can tell (I have not looked into prefix characters, admittedly). I would readily accept if this is simply a limitation of Emacs' syntax parsing (and would not think it too hard to come up with workarounds for my purposes), but my impression is that syntax parsing is the most efficient method, so it would be really cool to do it this way if it *can* be done. (I do wonder whether using syntax-table properties would work, e.g. by assigning the punctuation syntax class to `''` within strings, and if so, how substantial the overhead would be.) I would greatly appreciate any pointers through the jungle! Thanks! # Answer > 2 votes The syntax tables themselves can't handle this right, but Emacs offers `syntax-propertize` to circumvent this kind of limitation by giving special syntax to specific occurrences of characters in buffers. E.g. `pascal-mode` (where the same escaping is used in strings as the one you describe) has: ``` (defconst pascal--syntax-propertize (syntax-propertize-rules ;; The syntax-table settings are too coarse and end up treating /* and (/ ;; as comment starters. Fix it here by removing the "2" from the syntax ;; of the second char of such sequences. ("/\\(\\*\\)" (1 ". 3b")) ("(\\(/\\)" (1 (prog1 ". 1c" (forward-char -1) nil))) ;; Pascal uses '' and "" rather than \' and \" to escape quotes. ("''\\|\"\"" (0 (if (save-excursion (nth 3 (syntax-ppss (match-beginning 0)))) (string-to-syntax ".") ;; In case of 3 or more quotes in a row, only advance ;; one quote at a time. (forward-char -1) nil))))) [...] (define-derived-mode pascal-mode ... ... (setq-local syntax-propertize-function pascal--syntax-propertize) ...) ``` # Answer > 1 votes Thanks, Stefan, it seems to work like a charm! I.e. the parser state is exactly as expected, and e.g. `forward-sexp` now jumps over `'McDonald''s'`, which it did not do without the syntax propertizing. I am unsure where `parse-sexp-lookup-properties`, which must obviously be t for syntax table properties to be actually used, is set. `pascal.el` does not set it, and works fine (i.e. jumps over the above string -- of course I can't type any other Pascal). Is it t by default? As I found the docstring of `syntax-propertize-rules` somewhat arcane, and the appropriate actions somewhat tricky to understand (pascal.el has a very crisp explanation) I have exhaustively commented the minimal rule I extracted from `pascal.el`, just in case somebody as amateurish as me needs a transparent example. A short version for the experts comes first: ``` (defconst sql--syntax-propertize-escaped-apostrophe (syntax-propertize-rules ("''" (0 (if (save-excursion (nth 3 (syntax-ppss (match-beginning 0)))) (string-to-syntax ".") ; AFAIU, just "." should also work (forward-char -1) nil))))) (add-hook 'sql-mode-hook #'(lambda () (setq-local syntax-propertize-function sql--syntax-propertize-escaped-apostrophe))) ``` I'm dubious as to whether the mode hook is the right place for a patch, as I've never submitted one before. The long version: ``` (defconst sql--syntax-propertize-escaped-apostrophe (syntax-propertize-rules ;; Out of many possible RULES, we need just one, which propertizes ;; escaped apostrophes within strings (such as the '' in ;; 'McDonald''s') with the appropriate syntax class (punctuation): ("''" ;; A rule's car is a REGEXP; here: when you find two ' in a row ... (0 ;; ... apply to "HIGHLIGHT", i.e. subexp ;; (here NUMBER 0, i.e., to the whole "''" match), ... ;; ... the following SYNTAX property, i.e. what the following ;; expression returns (should be the appropriate syntax-table ;; property when appropriate, or nil, when not appropriate): (if (save-excursion ; (Restore point after you have peeked to the left.) (nth 3 (syntax-ppss ; Are we inside a string ... (match-beginning 0)))) ; ... at the pos directly before the ''? ;; then return the punctuation syntax-table property: (string-to-syntax ".") ; AFAIU, just "." should also work ;; Else, the two '' found are not an escaped ' within a string, ;; so we need to return nil, whatever else may need to be done. ;; What the strings *can be* is one of the following: ;; ;; a) just '' on its own, i.e. an empty string, in which case ;; we can just search on (apart from returning nil) ;; ;; b) part of any number of '''' ... within a comment, in which ;; case we can also just search on (apart from returning nil) ;; ;; c) the first two of four '''' (the whole sequence being a ;; lonely escaped apostrophe in a string), in which case we ;; must not propertize the first two, but the 2nd and 3rd ;; apostrophes. Thus, we'll return nil for now, but need to ;; go back one char, so the next search continues before the ;; 2nd ' and will then match the 2nd + 3rd '. (Otherwise, the ;; 1st + 2nd and then the 3rd + 4th will be examined ;; together, missing exactly the sequence of the 2nd + ;; 3rd.) ;; ;; We can actually go back one character in *all* of these cases, ;; however, because this causes no harm in the first two cases: ;; in case a), point is then followed by just one ', so won't ;; lead to any match on the next search, while in the esoteric ;; case b), point will go through a ''''... sequence of any ;; length at half the speed (i.e. twice the searches), but our ;; propertizing expression will return nil on each and every of ;; the overlapping '' sequences it then matches, as (nth 3 ;; (syntax-ppss POS)) invariably returns nil when POS is within ;; a comment, unimpressed by any char that is normally a string ;; terminator. Distinguishing between case c) and the other two ;; would very likely cause more overhead than the simple ;; backtracking used here (especially as case b) is certainly ;; extremely rare, although one should never say it never ;; occurs). ;; ;; Because of the backtracking we do, the '' *cannot* be: ;; ;; - the 3rd and 4th ' of a '''' sequence, because because of ;; our backtracking, a search can only start before the 1st, ;; before the 2nd, and before the 4th '. ;; ;; So, as explained, now go back one char and return nil: (forward-char -1) nil))))) ``` --- Tags: string, syntax, sql, parsing ---
thread-56366
https://emacs.stackexchange.com/questions/56366
Org table date arithmetic with Lisp expressions
2020-03-25T19:07:21.083
# Question Title: Org table date arithmetic with Lisp expressions It's easy to do date arithmetic using org-mode table formulas. For example, if I enter this table: ``` | [2020-01-01] | | | [2020-02-01] | | | [2020-03-01] | | #+TBLFM: $2=$1+1 ``` ...and then do `C-c C-c` on the formula, the table updates column 2, adding one day to the dates in column 1. Can this be done using a Lisp formula instead of a calc formula? If so, how? I see in the org-mode manual that Lisp formulas support various trailing flags to interpret the table cells in different formats, but not datestamps. I experimented with `calc-eval`, but calc datestamps differ in format from org datestamps. It appears there's some invisible plumbing that connects the two. # Answer You can use `org-table-eval-formula` to do the calculation in-place of the field and then retrieve the field value which the lisp form must return with `org-table-get-field`. In that way you can evaluate the calc formula within your lisp form. In lisp formulae $1 delivers a string `"[2020-01-01]"` for the date `[2020-01-01]`. Therefore the somewhat awkward construction of the calc formula `(concat $1 "+1")`. See the following example: ``` | [2020-01-01] | | | [2020-02-01] | | | [2020-03-01] | | #+TBLFM: $2='(progn (org-table-eval-formula nil (concat $1 "+1") t t t t) (org-table-get-field)) ``` --- In this special case where you really only want date calculation you can also use the following Elisp formula instead: ``` | [2020-01-01] | [2020-01-02] | | [2020-02-01] | [2020-02-02] | | [2020-03-01] | [2020-03-02] | #+TBLFM: $2='(org-format-time-string "[%F]" (org-time-from-absolute (1+ (org-time-string-to-absolute $1)))) ``` > 1 votes --- Tags: org-mode, org-table ---
thread-12130
https://emacs.stackexchange.com/questions/12130
How to insert inactive [timestamp] via function?
2015-05-04T21:26:55.133
# Question Title: How to insert inactive [timestamp] via function? `C-u C-c !` generates a time stamp like \[2015-05-04 Mon 17:13\] I would like to assign a shortcut (e.g F1) to this action. So far I have: ``` (defun my/timenow (&optional arg) (interactive) (let ((current-prefix-arg 4)) ;; emulate C-u (org-time-stamp arg 'inactive) ) ) ``` But this prompts me for the time and I have to press `RET` to insert it. How can I insert the inactive timestamp without any prompts at all? # Answer > 11 votes From the documentation of `org-time-stamp`: > With two universal prefix arguments, insert an active timestamp with the current time without prompting the user. So eval the below: ``` (org-time-stamp '(16) t) ``` * `'(4)` \- one prefix arg (4) * `'(16)` \- two prefix args (4 * 4) * `'(64)` \- three prefix args (4 * 4 * 4) To read more about the universal arguments and arguments in general: # Answer > 1 votes Now there is a dedicated function for this (see `org-time-stamp-inactive`). For example: ``` (defun my/timenow () (interactive) (let ((current-prefix-arg '(16))) (call-interactively 'org-time-stamp-inactive))) (define-key org-mode-map (kbd "<f1>") 'my/timenow) ``` You can also skip the prompt with two universal prefix arguments: `C-u C-u C-c !`. --- Tags: org-mode, time-date, prefix-argument ---
thread-56375
https://emacs.stackexchange.com/questions/56375
user-init-file Variable Value Doesn't Change
2020-03-26T11:31:48.347
# Question Title: user-init-file Variable Value Doesn't Change **The Goal** Place everything related to `emacs` in `~/.config/.emacs.d` **What I Have Done** * Created `/usr/share/emacs/site-lisp/site-start.el` which contain the following code: ``` (setq user-init-file "~/.config/.emacs.d/init.el") (setq user-emacs-directory "~/.config/.emacs.d") (load user-init-file) ``` Source **The Outcome** * `emacs` still creates `~/.emacs.d` which contains the `auto-save-list` directory. * Changing the value of variables through `M-x customize` creates the `~/.emacs` file. * Examining the value of variables modified within `site-start.el` I get the following result: ``` user-init-file is a variable defined in ‘C source code’. Its value is "~/.emacs" user-emacs-directory is a variable defined in ‘subr.el’. Its value is "~/.config/.emacs.d" ``` Is it possible to achieve what I want? This is part of my effort to organize my `HOME` directory. I have read the following documentation. # Answer You can't do that. Emacs doesn't care if you've (unexpectedly) set `user-init-file` -- it looks for your init file in the places it's hard-coded to look for it, and it then *sets* `user-init-file` to the path of the init file it located. *However* if you wait for Emacs 27 (or try a pretest release; currently 27.0.90 at time of writing), it essentially provides what you're looking for. See the NEWS for details: > Emacs can now use the XDG convention for init files. The 'XDG\_CONFIG\_HOME' environment variable (which defaults to "~/.config") specifies the XDG configuration parent directory. Emacs checks for "init.el" and other configuration files inside the "emacs" subdirectory of 'XDG\_CONFIG\_HOME', i.e. "$XDG\_CONFIG\_HOME/emacs/init.el" > > However, Emacs will still initially look for init files in their traditional locations if "~/.emacs.d" or "~/.emacs" exist, even if "$XDG\_CONFIG\_HOME/emacs" also exists. This means that you must delete or rename any existing "~/.emacs.d" and "~/.emacs" to enable use of the XDG directory. > > If "~/.emacs.d" does not exist, and Emacs has decided to use it (i.e. "$XDG\_CONFIG\_HOME/emacs" does not exist), Emacs will create it. Emacs will never create "$XDG\_CONFIG\_HOME/emacs". > > Whichever directory Emacs decides to use, it will set 'user-emacs-directory' to point to it. > 3 votes --- Tags: init-file ---
thread-56374
https://emacs.stackexchange.com/questions/56374
How could I abort and apply space when company suggests completion?
2020-03-26T10:28:58.240
# Question Title: How could I abort and apply space when company suggests completion? While I am typing `company` shows suggestons. When I press space I want to abort suggestions and apply space, but instead it only does abort. Hence I need to press two times space to apply space. **\[Q\]** How could I abort and apply space when company suggests completion? ``` (add-hook 'after-init-hook 'global-company-mode) (setq company-auto-complete t) (with-eval-after-load "company" (define-key company-active-map (kbd "C-p") #'company-select-previous-or-abort) (define-key company-active-map (kbd "C-n") #'company-select-next-or-abort) (define-key company-active-map (kbd "C-h") #'backward-delete-char) (define-key company-active-map (kbd ".") #'company-abort) (define-key company-active-map (kbd "SPC") #'company-abort) (define-key company-active-map (kbd "C-f") #'company-abort) ) (eval-after-load 'company '(progn (define-key company-active-map (kbd "TAB") 'company-complete-common-or-cycle) (define-key company-active-map (kbd "<tab>") 'company-complete-common-or-cycle))) (setq company-frontends '(company-pseudo-tooltip-unless-just-one-frontend company-preview-frontend company-echo-metadata-frontend)) (setq company-auto-complete t) (global-set-key (kbd "C-c C-k") 'company-complete) ``` # Answer > 1 votes Quite an ugly (and untested) suggestion: 1. Define an ad-hoc function: ``` (defun company-abort-and-insert-space () (interactive) (company-abort) (insert " ")) ``` 2. Replace ``` (define-key company-active-map (kbd "SPC") #'company-abort) ``` by ``` (define-key company-active-map (kbd "SPC") #'company-abort-and-insert-space) ``` in your `init.el` file. --- Tags: company ---
thread-56377
https://emacs.stackexchange.com/questions/56377
Is there a way to change order of the key in a hashtable?
2020-03-26T14:33:30.793
# Question Title: Is there a way to change order of the key in a hashtable? Say i have following keys in hashtable: ``` "first1" "second2" "third3" "forth4" ``` Is there a way to put key `"third3"` at the top. So that when i run func `hash-table-keys` i get following list: ``` ("third3" "first1" "second2" "forth4") ``` I tried running `remhash` followed by `puthash`. But the order stays the same. # Answer > 3 votes *No*, you cannot change the order of the keys in a hash table. As @xuchunyang's comment points out, hash tables do not have an order in the way you're thinking about them. From the elisp manual node on hash tables: ``` The correspondences in a hash table are in no particular order. ``` You may wish to order the keys in some form (say, for the purposes of accessing the values in some particular order), but that ordering will live outside the hash table itself. `hash-table-keys` returns a *list* of the table's keys, and you can manipulate that list just as any other list: `sort`ing it, `setf`ing it, and so on. --- Tags: sorting, hash-tables ---
thread-28915
https://emacs.stackexchange.com/questions/28915
Coedit mode on Emacs
2016-11-26T00:32:46.780
# Question Title: Coedit mode on Emacs I often use the web service Kobra.io, in which we can edit a specific file with some people together at the same time. Is there such a package on Emacs? I'd like to edit a specific lisp code at the same time with some people. If I change some parts in the code, the other people can see the change at the same time. Could you tell me how to implement this function? I'd appreciate your help. # Answer > 1 votes There's `rudel`, available on GNU ELPA, which intends to do that (it supports various protocols of communication between the various Emacs sessions). # Answer > 1 votes There is floobits. It works OK. # Answer > 0 votes A pure Lisp alternative called shared-buffer was developed during the Lisp in Summer projects 7 years ago. It requires a Common Lisp server (also distributed as part of the repo). In principle it may be possible to port the Common Lisp portion to Emacs Lisp, for a 100% Emacs based solution, but at the time of writing that has not been done. --- Tags: package, package-development ---
thread-56363
https://emacs.stackexchange.com/questions/56363
Is it possible for multiple modes to combine their fontifications?
2020-03-25T17:42:27.137
# Question Title: Is it possible for multiple modes to combine their fontifications? For example, a buffer has some major mode and it does its own fontification. If I turn on a minor mode A then it adds its own fontification which changes the existing fontification by changing the apperance of some characters which are already fontified by the major mode. Then if I turn off the minor mode it removes its own fontification and for those characters which the major mode fontified originally the original fontification is restored. Is it possible for a minor mode to change fontification in such a layer-like way, so that it overshadows the existing fontification, but this layer of fontification can be removed cleanly if the mode is turned off? # Answer Yes it is possible to add the fontification of a minor mode to the existing fontification of the major mode. You add font lock keywords with `font-lock-add-keywords` and remove them with `font-lock-remove-keywords`. There are many possible structures for the keywords. See the doc for the variable `font-lock-keywords` for the full list. One such structure is: `(MATCHER SUBEXP FACENAME [OVERRIDE])` * `MATCHER` can be a regexp or a function matching the keyword; The function is called with point at the beginning of the region to be fontified and it receives the end of that region as argument. The function should set the match-data like `re-search-forward` * `SUBEXP` is the number of the sub-expression of `MATCHER` that should be fontified * `FACENAME` can be an expression returning the face name to use or a list `(face FACE PROP1 VAL1 PROP2 VAL2 ...)`; The second form is handy to set text properties on the keyword. * `OVERRIDE` Overrides all previous fontification if set to t. Other allowed values are `prepend` and `append` with the obvious meaning. Normally, you would use the `OVERRIDE` flag with value t, `prepend`, or `append` to overwrite or combine the fontification of the major and the minor mode. If the rule for the fontification of the match is more complicated you can also set the face and the text properties directly in `MATCHER`. In this case add `MATCHER` as follows to `font-lock-keywords`: `(font-lock-add-keywords nil '((MATCHER)))` That technique is often used by org-mode. See, e.g., `org-fontify-entities`. The following Elisp code gives an example for a minor mode that adds `display` text properties to org tables for a fancier presentation: ``` (defun org+-fancy-table-lines (limit) "Draw org tables with fancy lines. This is a face-lock matcher with arg LIMIT." (let ((p (point)) hline-p found) (forward-line 0) (while (re-search-forward "^[[:space:]]*|" limit t) (backward-char) (let* ((hline-p (looking-at org-table-hline-regexp)) (re (if hline-p "[|+-]" "|")) (line-limit (min limit (line-end-position)))) (when (< (point) p) (goto-char p)) (while (re-search-forward re line-limit 'noError) (let ((b (1- (point))) (e (point))) (setq found t) (cl-case (char-before) (?- (skip-chars-forward "-") (setq e (point)) (put-text-property b e 'display (make-string (- e b) ?─))) (?+ (put-text-property b e 'display "┼")) (?| (if hline-p (if (eq (char-before b) ?-) (put-text-property b e 'display "┤") (put-text-property b e 'display "├")) (put-text-property b e 'display "│")))))))) found)) (defconst org+-fancy-table-keywords '((org+-fancy-table-lines)) "Font lock keywords for `org+-fancy-table-mode'.") (define-minor-mode org+-fancy-table-mode "Display tables with fancy lines." :lighter " ─" (if org+-fancy-table-mode (progn (font-lock-add-keywords nil org+-fancy-table-keywords 'at-end) (make-local-variable 'font-lock-extra-managed-props) (cl-pushnew 'display font-lock-extra-managed-props)) (font-lock-remove-keywords nil org+-fancy-table-keywords)) (font-lock-flush)) ``` Note, that here we add `display` to the `font-lock-extra-managed-props` list. That gives font-lock the control over those text properties. It is a quite drastic measure and may interfere with other commands directly using the `display` property. > 1 votes --- Tags: font-lock ---
thread-56388
https://emacs.stackexchange.com/questions/56388
Non-greedy regex group
2020-03-27T01:44:53.350
# Question Title: Non-greedy regex group This is related to my previous question over here. ``` (replace-regexp "\\(\\[\\[\\)\\(zotero:.+\\]\\)\\(\\[.+,[《〈][^《〈]+[》〉]\\)?.+。\\(\\]\\]\\)" "\\1cite-\\2\\3\\4,頁") ``` I'd like to use the above code to shorten Chinese citation strings to `author,title,page` format. --- # Sample Data *Original String*: `[[zotero://select/items/1_P36Y9V2B][周東平,〈《晉書·刑法志》校注舉隅〉,《中國古代法律文獻研究》,2016年,00期。]]` *Expected Result (shortened string)*: `[[cite-zotero://select/items/1_P36Y9V2B][周東平,〈《晉書·刑法志》校注舉隅〉]],頁` --- The code snippet `[《〈][^《]+[》〉]` correctly restricts the search to a single title element between s. When joined with `.+,`, however, it fails to be non-greedy and ends up picking up both article title (between `〈〉`s) and journal title (between `《》`s) at the same time. This results in a shortened citation which is lengthier than expected. ``` [[cite-zotero://select/items/1_P36Y9V2B][周東平,〈《晉書·刑法志》校注舉隅〉,《中國古代法律文獻研究》]],頁 ``` How do we make `\\3` non-greedy, as expected? --- # Update: I just realize this could be an issue specific to the data string listed above, i.e.: `周東平,〈《晉書·刑法志》校注舉隅〉,《中國古代法律文獻研究》,2016年,00期。` Somehow, the `《晉書·刑法志》` nested in `《晉書·刑法志》校注舉隅〉` complicated matters. Other simpler, but similarly structured data such as this worked as expected: `[[zotero://select/items/1_97XVI66Q][金春峯,〈周官之社會行政組織〉,收入《周官之成書及其反映的文化與時代新考》台北:東大,1993年。]]` *Result*: `[[cite-zotero://select/items/1_97XVI66Q][金春峯,〈周官之社會行政組織〉]],頁` # Answer For starters the non-greedy quantifiers are `??`, `+?`, and `*?`, and so you haven't specified any non-greedy matching in that regexp. --- I **strongly** recommend using `M-x` `re-builder` to visualise what is going on (it will show each group in a different colour). --- Looking at part of your regexp, this: ``` , [《〈][^《〈]+[》〉] ``` matches a comma and a space, followed by either or , followed by one-or-more characters *not* in that set, and finally either or In the case of: ``` , 〈《晉書·刑法志》校注舉隅〉,《中國古代法律文獻研究》 ``` The pattern does **not** match the start of that string because after `, 〈` we have a character which fails to match `[^《〈]` (because it *is* one of those two characters). Consequently that part of the regexp does not match the text until the *second* comma. This 'works' overall because you had `.+` preceding that in the pattern, so that simply extends to match everything up to that second comma. If you change that `.+` into `\\(.+\\)` in re-builder, you'll see what it is matching. --- Try the following in re-builder: ``` "\\(\\[\\[\\)\\(zotero:.+\\]\\)\\(\\[\\(.+?\\),\\(《.+?》\\|〈.+?〉\\)\\)?\\(.+\\)。\\(\\]\\]\\)" ``` I've added several extra groups so you can see exactly what each bit matches. I recommend that you spend a bit of time experimenting with that. The *key* difference to your original pattern is this: ``` \\(《.+?》\\|〈.+?〉\\) ``` in place of: ``` [《〈][^《〈]+[》〉] ``` This approach works for the examples you have shown. If you have any titles containing newlines then you would need to use `\\(?:.\\|\n\\)+?` instead of `.+?` because `.` does not match newlines. Or you could alternatively use: ``` \\(《[^》]+》\\|〈[^〉]+〉\\) ``` (Which isn't *exactly* the same thing, but would most likely be equivalent for your purposes, and is probably what you were meaning to express in the first instance.) > 5 votes --- Tags: regular-expressions ---
thread-56385
https://emacs.stackexchange.com/questions/56385
symbol's value as variable is void: command, when using ibuffer-sidebar
2020-03-26T20:03:35.083
# Question Title: symbol's value as variable is void: command, when using ibuffer-sidebar I installed ibuffer-sidebar (https://github.com/jojojames/ibuffer-sidebar) and added the following to my `~/.emacs.d/init.el`: ``` (use-package "ibuffer-sidebar.el") (require 'ibuffer-sidebar) (setq ibuffer-sidebar-use-custom-font t) (setq ibuffer-sidebar-face `(:family "Helvetica" :height 120)) ``` After doing this, all helm commands fail. E.g. `helm-find-files` says `In Find FIles source: helm-find-fules-get-candidates (void-variable command)`. Other helm commands just say `symbol's value as variable is void: command`. I'm a newbie, very excited about emacs. # Answer > 1 votes Normally this is not how people install packages, typically if you want to use use-package, you want to specify everything inside the macro, and what you might be seeing is the spillover into `helm`, because it's initialised after `ibuffer-sidebar`. I would suggest you read up the documentation, and as an example of how to use `use-package` here's the version of your `init.el`. ``` (use-package ibuffer-sidebar :ensure t :config (custom-set-variables '(ibuffer-sidebar-use-custom-font t) '(ibuffer-sidebar-face (:family "Helvetica" :height 120))) ``` This might not fix the error that you're having, but it's definitely the proper way to `use-package`. As for the error message you're receiving, it's a sign that the macro is not getting a command as a value (in lisp, functions are values too), so my best guess would be that it fails to initialise `ibuffer-sidebar` and tries to run one of its provided commands, but fails. See if this fixes the issue. --- Tags: helm, debugging, major-mode, ibuffer ---
thread-56384
https://emacs.stackexchange.com/questions/56384
Perform calculations in orgtbl with the LaTeX syntax?
2020-03-26T20:00:54.987
# Question Title: Perform calculations in orgtbl with the LaTeX syntax? This is an `orgtbl` table ``` #+begin_src emacs-lisp :results none (setq calc-language 'latex) (calc-radians-mode) #+end_src #+attr_latex: :mode math |----------+-----+----------| | Fonction | var | Dérivée | |----------+-----+----------| | cos(x) | x | -\sin(x) | | \cos(x) | x | #ERROR | |----------+-----+----------| #+TBLFM: $3=deriv($1,$2);RL ``` I would like orgmode to display \cos(x) on the @2 line when I Input cos(x). If I input \cos(x) on the @3 line, the formula deriv($1,$2) gives an error. How can I obtain the correct LaTeX syntax for the input and the output ? # Answer You can add the setting `latex` for `calc-language` to `org-calc-default-modes`. The following example Org file shows how you can do that with file-local variables: ``` |----------+-----+----------+----------| | Fonction | var | Dérivée | | |----------+-----+----------+----------| | cos(x) | x | -\sin{x} | -\cos{x} | | \cos(x) | x | -\sin{x} | -\cos{x} | |----------+-----+----------+----------| #+TBLFM: $3=deriv($1,$2);RL * Local Variables :noexport: Local Variables: eval: (plist-put org-calc-default-modes 'calc-language 'latex) End: ``` You must reopen the file for the setting to take effect. --- Alternatively, you can add the following code to your init file. With that code you can add comma-separated Calc settings to the modes of a table formula. The first setting must be a mode as described in the Org manual. The subsequent settings have the form `VARIABLE:VALUE` where `VARIABLE` is the Calc variable such as `calc-language` and `VALUE` is the value for this variable such as `latex`. Below the code there is an example Org table with such setting. ``` (defun org+-top-level-split-string (equation &optional separators table) "Split string EQUATION at top-level SEPARTORS. SEPARATORS is a regexp. EQUATION can be an org table equation as used for `org-table-eval-formula'. In that the default value [;,] for SEPARATORS is appropriate." (unless separators (setq separators "[;,]")) (unless table (setq table org-mode-syntax-table)) (let (ret (pos 1)) (with-temp-buffer (with-syntax-table table (insert equation) (goto-char (point-min)) (while (null (eobp)) (when (looking-at separators) (setq ret (cons (buffer-substring-no-properties pos (point)) ret) pos (goto-char (match-end 0)))) (forward-sexp)) (when (> (point) pos) (setq ret (cons (buffer-substring-no-properties pos (point)) ret))))) (nreverse ret))) ;; Test: (org+-table-formula-mode-split "deriv($1,$2);RL,calc-language:latex") (defvar org-calc-default-modes) ;; defined in org-table.el (declare-function org-table-eval-formula "org-table") (eval-when-compile (require 'subr-x)) (defun org+-table-eval-formula-mode (fun arg equation &rest rest) "Allow direct settings for `org-calc-default-modes'. These settings are given in the formula as comma separated list. Each setting has the form VARIABLE:VALUE where VARIABLE is one of Calc's variable names and VALUE is the value in `read' syntax." (let* ((org-calc-default-modes (seq-copy org-calc-default-modes)) (eq-flags (org+-top-level-split-string equation)) (eq (car eq-flags)) (modes (cadr eq-flags)) (settings (cddr eq-flags))) (when (stringp modes) (setq eq (concat eq ";" modes))) (dolist (setting settings) (when-let ((pos (cl-position ?: setting)) (var (intern-soft (substring setting 0 pos))) (val (read (substring setting (1+ pos))))) (setq org-calc-default-modes (nconc (list var val) org-calc-default-modes)))) (apply fun arg eq rest))) (advice-add 'org-table-eval-formula :around #'org+-table-eval-formula-mode) ``` The example org table: ``` |----------+-----+----------+----------| | Fonction | var | Dérivée | | |----------+-----+----------+----------| | cos(x) | x | -\sin{x} | -\cos{x} | | \cos(x) | x | -\sin{x} | -\cos{x} | |----------+-----+----------+----------| #+TBLFM: $3=deriv($1,$2);RL,calc-language:latex ``` > 3 votes --- Tags: latex, org-table, orgtbl ---
thread-33360
https://emacs.stackexchange.com/questions/33360
How to open .org files with visual-line-mode automatically turned on?
2017-06-07T06:06:37.310
# Question Title: How to open .org files with visual-line-mode automatically turned on? How to open .org and .txt files with visual-line-mode automatically turned on? Also, is there a way to configure cursor-movement so that cursor moves as if the visual line where a logical line? line-move-visual is not effecting Spacemacs evil mode keybindings: k (line up), j (line down). I am running Emacs 25.2.1, with Spacemacs, evil mode, org-mode on Linux. **UPDATE 1** From .spacemacs file, after adding visual-line-mode ``` (defun dotspacemacs/user-config () "Configuration function for user code. This function is called at the very end of Spacemacs initialization after layers configuration. This is the place where most of your configurations should be done. Unless it is explicitly specified that a variable should be set before a package is loaded, you should place your code here." ) (add-hook 'org-mode-hook #'visual-line-mode) (add-hook 'text-mode-hook #'visual-line-mode) (setq org-use-speed-commands t) ;; Do not write anything past this comment. This is where Emacs will ;; auto-generate custom variable definitions. (custom-set-variables ``` With emacs open to a txt file: SPC h d k k ``` k runs the command evil-previous-line (found in evil-motion-state-map), which is an interactive compiled Lisp function in ‘evil-commands.el’. It is bound to <up>, k. ``` SPC h d v line-move-visual ``` line-move-visual is a variable defined in ‘simple.el’. Its value is t ``` **UPDATE 2** Tobias's advices code worked great; j and k move cursor as if the visual line where a logical line. Then I installed org-drill. And org-drill worked fine until I restarted Emacs, then Emacs said: ``` Spacemacs encountered an error while loading your '~/.spacemaces' file. Pick your editing style for recovery: vim emacs hybrid ``` When I completed the recovery, org-drill was missing from M-x, so I reinstall org-drill. Then restarting Emacs encountered the same error. So I removed Tobias's advices code from my .spacemacs file, and now Emacs and org-drill work fine. **UPDATE 3** I placed the new eval-after-load advices code in ~/.spacemacs. And Emacs started without errors. But long lines of text in .org file did not wrap at all. So then I restored the previous advices code in ~/.spacemacs. And started Emacs from the terminal: emacs --debug-init. There where error messages. How to copy them to clipboard? Screen shot of error messages: # Answer > 9 votes You can switch on `visual-line-mode` in `org-mode` and `text-mode` by ``` (add-hook 'text-mode-hook #'visual-line-mode) ``` in your init-file (e.g. `~/.emacs`). (Thanks to user lawlist for clarifying that `org-mode` bases on `text-mode`.) In `emacs -Q` the command `visual-line-mode` also sets `line-move-visual` buffer-locally to `t` therefore point movement should already work on visual lines without any customization. If you don't like that behavior set `line-move-visual` to `nil`. `emacs-version`: `GNU Emacs 25.1.50.2 (i686-pc-linux-gnu, GTK+ Version 3.10.8) of 2016-04-25` I cite here `evil-previous-line` from `evil-commands.el`: ``` (evil-define-motion evil-previous-line (count) "Move the cursor COUNT lines up." :type line (let (line-move-visual) (evil-line-move (- (or count 1))))) ``` You can see that `line-move-visual` is explicitly set to nil there. So the behavior you experience is intended. On the other hand there is a command `evil-next-visual-line` defined right below `evil-commands.el`: ``` (evil-define-motion evil-next-visual-line (count) "Move the cursor COUNT screen lines down." :type exclusive (let ((line-move-visual t)) (evil-line-move (or count 1)))) ``` There `line-move-visual` is explicitly set to `t`. In `evil-maps.el` one finds the following two lines: ``` (define-key evil-motion-state-map "gj" 'evil-next-visual-line) (define-key evil-motion-state-map "gk" 'evil-previous-visual-line) ``` **So I guess you have just to press `gj` and `gk` instead of `j` and `k` for motion along visual lines.** Please, try that for yourself since I don't have `evil` installed. --- You can paste the following advices into your init-file and try whether they fit your purpose. The functions `evil-next-line` and `evil-previous-line` are adviced such that they respect the value of `line-move-visual` as set by `visual-line-mode`. ``` (eval-after-load "evil-commands" '(progn (defun ad-evil-next-line (count) (evil-line-move (or count 1))) (advice-add #'evil-next-line :override #'ad-evil-next-line) (defun ad-evil-previous-line (count) (evil-line-move (- (or count 1)))) (advice-add #'evil-previous-line :override #'ad-evil-previous-line))) ``` # Answer > 0 votes If you are using general.el: ``` (general-swap-key nil 'motion ;; swap evil-next-line evil-next-visual-line "k" "gk" "j" "gj") ``` --- Tags: org-mode, spacemacs, wrapping ---
thread-56397
https://emacs.stackexchange.com/questions/56397
How can emacs org-mode execute shell code remotely as sudo?
2020-03-27T10:34:29.883
# Question Title: How can emacs org-mode execute shell code remotely as sudo? My self-documenting maintainance scripts, where I document how systems have been setup, I need to execute stuff as sudo/root and want the results automatically added to the document. But for safety reasons on the target system root has login disabled. I have to connect via an admin-user, which then can sudo stuff. in my emacs init.el this adds bash execution: ``` ;; allow org mode bash execution ;; -------------------------------------- (org-babel-do-load-languages 'org-babel-load-languages '( (shell . t ) ) ) ``` Then in my document I have e.g. this bash / shell piece: ``` #+BEGIN_SRC bash :dir /sudo:adminuser@fresh_installed_computer:~/ :results output parted /dev/sda "unit GiB" "print free" parted /dev/sda "unit s" "print free" #+END_SRC ``` The error message is: Host 'fresh\_installed\_computer' looks like a remote host, 'sudo' can only use the local host. See Org-Mode Manual: 15 Working with Source Code Using Debian Stretch with Emacs 24.5.1 on the local machine, the remote machine is about to become debian buster fresh install. --- **UPDATE** When executing ``` #+BEGIN_SRC bash :dir /ssh:adminuser@fresh_installed_computer|sudo:fresh_installed_computer:~/ :results output :session echo "user $USER" #+END_SRC ``` The status line holds "Opening connection for root@fresh\_installed\_computer using sudo... \\" and then waits forever Interestingly: when I add the actual IP address like this, it suddenly works as expected: ``` #+BEGIN_SRC bash :dir /ssh:adminuser@fresh_installed_computer|sudo:XXX.XXX.XXX.XXX:~/ :results output :session echo "user $USER" #+END_SRC #+RESULTS: : user root ``` ssh to adminuser@fresh\_installed\_computer and there pinging works, so name resolving is up. ``` ping fresh_installed_computer ``` Any explanation, or do I need to stick with magic number fixed ip adress in my document? --- **UPDATE 2** The issue with resolving hostname vs IP adress could be solved by *clearing tramp proxy caches*: ``` M-x tramp-cleanup-all-connections M-: (setq tramp-default-proxies-alist nil) ``` Now all works fine! Thx # Answer > 6 votes ### Use `TRAMP` multi-hop syntax for `:dir` header. > **4.4 Combining ssh or plink with su or sudo** > > If the su or sudo option shall be performed on another host, it could be comnbined with a leading ssh or plink option. That means, TRAMP connects first to the other host with non-administrative credentials, and changes to administrative credentials on that host afterwards. In a simple case, the syntax looks like `/ssh:user@host|sudo:host:/path/to/file`. ``` :dir /ssh:user@fresh_installed_computer|sudo:adminuser@fresh_installed_computer:~/ ``` > **Tip:** Adding `:session` header to code block can be helpful too. ``` #+BEGIN_SRC bash :dir /ssh:user@fresh_installed_computer|sudo:adminuser@fresh_installed_computer:~/ :results output :session parted /dev/sda "unit GiB" "print free" parted /dev/sda "unit s" "print free" #+END_SRC ``` --- > **Note:** If the goal is to login as `adminuser` and then sudo to `root` user the tramp connection string would be updated this way instead. > > `:dir /ssh:adminuser@fresh_installed_computer|sudo:fresh_installed_computer:~/` > > ``` > #+BEGIN_SRC bash :dir /ssh:adminuser@fresh_installed_computer|sudo:fresh_installed_computer:~/ :results > output :session > parted /dev/sda "unit GiB" "print free" > parted /dev/sda "unit s" "print free" > #+END_SRC > > ``` > > Thanks to NickD for pointing this out! > > --- > > **Don't use `...|sudo:localhost:`** -- that's once again going to create a dangerous proxy on Emacs versions \< 27 > > Thanks to phils for pointing this out! --- Tags: org-mode, org-babel, tramp ---
thread-56403
https://emacs.stackexchange.com/questions/56403
Org-export: Convenient input/pasting of style information with many lines
2020-03-27T15:09:49.020
# Question Title: Org-export: Convenient input/pasting of style information with many lines When exporting an Org buffer to HTML, how can I inject a `<style>`-tag with many lines of contents into the **head** of the HTML document? I know `#+HTML_HEAD:` and `#+HTML_HEAD_EXTRA:`. But that prefix must be added to all contents lines. I also know about `#+BEGIN_EXPORT html`...`#+END_EXPORT`. But the contents of those blocks end up in the body of the HTML document. # Answer > 0 votes I did not yet find a standard way. So I added an attribute `:head` to HTML export blocks. If that attribute is set to `t` or `yes` the contents of the export block ends up in the `<head>` of the HTML document. ``` (defun org+-html-export-block (fun export-block contents info) "Take the \"head\" export attribute for EXPORT-BLOCK into account. This is an around advice for `org-html-export-block'. If the EXPORT-BLOCK has the head attribute put its contents into the :html-head property of INFO." (when (string= (org-element-property :type export-block) "HTML") (let ((attributes (org-export-read-attribute :attr_html export-block))) (if (member (plist-get attributes :head) '("t" "yes")) (progn (plist-put info :html-head (org-remove-indentation (org-element-property :value export-block))) nil) (funcall fun export-block contents info))))) (advice-add 'org-html-export-block :around #'org+-html-export-block) ``` Example Org document: ``` #+OPTIONS: html-style:nil html-scripts:nil #+TITLE: Test for Org export blocks * This is a test for Org Export Blocks. Some block that ends up in the body: #+BEGIN_EXPORT html <p>This paragraph comes from the export block.</p> #+END_EXPORT Another block that ends up in the head: #+ATTR_HTML: :head t #+BEGIN_EXPORT html <style> p { color: red; } </style> #+END_EXPORT ``` The generated HTML buffer: ``` <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"> <head> <!-- 2020-03-27 Fri 16:05 --> <meta http-equiv="Content-Type" content="text/html;charset=utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Test for Org export blocks</title> <meta name="generator" content="Org mode" /> <style> p { color: red; } </style> </head> <body> <div id="content"> <h1 class="title">Test for Org export blocks</h1> <div id="table-of-contents"> <h2>Table of Contents</h2> <div id="text-table-of-contents"> <ul> <li><a href="#org27bee3e">1. This is a test for Org Export Blocks.</a></li> </ul> </div> </div> <div id="outline-container-org27bee3e" class="outline-2"> <h2 id="org27bee3e"><span class="section-number-2">1</span> This is a test for Org Export Blocks.</h2> <div class="outline-text-2" id="text-1"> <p> Some block that ends up in the body: </p> <p>This paragraph comes from the export block.</p> <p> Another block that ends up in the head: </p> </div> </div> </div> <div id="postamble" class="status"> <p class="date">Created: 2020-03-27 Fri 16:05</p> <p class="validation"><a href="http://validator.w3.org/check?uri=referer">Validate</a></p> </div> </body> </html> ``` --- Tags: org-export ---
thread-56401
https://emacs.stackexchange.com/questions/56401
Is it possible to use emacsclient remotely?
2020-03-27T14:14:40.123
# Question Title: Is it possible to use emacsclient remotely? I'd like to use emacsclient on my laptop to connect to an emacs server on my desktop. I think I know that the emacs server process listens to a unix socket in "/tmp/emacs${UID}". So I need to make a connection between a unix socket in laptop:/tmp/emacs${UID}/socat to desktop:/tmp/emacs${UID}/server. I can make a socket locally with socat. I have tested: ``` socat -v UNIX-LISTEN:/tmp/emacs${UID}/socat UNIX-CONNECT/tmp/emacs${UID}/server emacsclient -nw -s socat . ``` That works. So now I need to connect socat to server on the remote host... ``` desktop: socat -v TCP-LISTEN:7777 UNIX-CONNECT:/tmp/emacs${UID}/server laptop: socat -v UNIX-LISTEN:/tmp/emacs${UID}/socat TCP-CONNECT:127.0.0.1:9999 ssh -L9999:127.0.0.1:7777 desktop emacsclient -nw -s socat . ``` I can successfully route traffic over this setup. I know this because my home directory is different on my laptop, and the socat on the desktop is dumping out laptop-home-directory-related paths. However, the emacsclient process on my laptop doesn't draw a frame. Is there a way to make this work? Edit: xuchunyang writes: ``` By the way, we don't need emacsclient to use the Emacs server, echo '- eval emacs-version' | nc -U /path/to/emacs/socket works as well. ``` I can confirm that connecting to the socket on the laptop works: ``` laptop $ echo '-eval emacs-version' | nc -U /tmp/emacs248200/socat -emacs-pid 184752 -print "26.3" $ ``` # Answer rpluim suggests trying emacsclient-over-tcp. Adding an answer in order to have formatting available. Setup Desktop ``` (setq server-use-tcp t server-host "127.0.0.1" server-port 6666 server-auth-dir "~/.emacs.d/server" server-auth-key "qTq/]3a$2@hmszaxJl{XvRn~9mBh,34O$8L>WS1TD%&8g*roC#Xck)9Lg]M*}\\z") (server-start) ``` Laptop ``` scp desktop:~/.emacs.d/server/server ~/.emacs.d/server/server ssh -L 6666:127.0.0.1:6666 desktop emacsclient -nw -f ~/.emacs.d/server/server . ``` Result: The emacsclient call hangs after connecting (exactly the same behaviour as seen trying to tunnel the unix socket). There is a connection to port 6666 on the laptop. > 0 votes --- Tags: emacsclient ---
thread-56412
https://emacs.stackexchange.com/questions/56412
How to temporarily disable/reset idle timers?
2020-03-27T22:07:04.550
# Question Title: How to temporarily disable/reset idle timers? I have a package which uses mouse motion, currently the idle timers aren't reset on mouse motion - causing idle timers to run, even when from a user perspective - Emacs is not idle. How can I stop idle timers from running while my function runs? # Answer No idea whether this works, but what happens if you bind `timer-idle-list` to `nil` for the period when you want to prevent an idle timer from going off? `C-h v` says that it's the list of active timers. If it's `nil` then maybe that will do what you want. FWIW, I found `timer-idle-list` just by using `C-h v` and typing `timer S-TAB`, with Icicles (`S-TAB` does apropos completion). With vanilla Emacs you could just use `M-x apropos RET timer RET` to find it. --- Otherwise, perhaps you could use `cl-flet` or similar to bind function `current-idle-time` for the duration to a function that just returns `nil`. Or just advise it to do only that. --- (You could use `cancel-timer` on each of those active idle timers. But I don't think that's what you want to do.) > 1 votes --- Tags: idle-timer ---
thread-56413
https://emacs.stackexchange.com/questions/56413
can emacs memoize regexps?
2020-03-27T23:29:06.013
# Question Title: can emacs memoize regexps? This is really a question about implementation rather than anything a user of GNU Emacs would be interested in. Emacs regexps are represented as strings. There is a nice `rx` DSL for constructing regexps out of s-expressions, but it produces a string not some other more fundamental data structure. I assume that the underlying C regexp engine uses something lower level than strings to represent a regexp matcher. Does emacs parse / compile every regexp string every time a procedure is called, or is there some memoization going on there under the hood... e.g. an LRU of the regexp string to the underlying compiled data structure. Is it possible to customise any of the parameters for that cache as a user? # Answer From a cursory look all regex matching functions end up using `compile_pattern` which first checks the built-in regex cache for a previously compiled one, compiling one when needed. The cache is a linked list with a hardcoded size of 20 items. New matches are put in the front of the list, essentially creating a LRU mechanism. See search.c for the details. > 6 votes --- Tags: regular-expressions, emacs-development ---
thread-56395
https://emacs.stackexchange.com/questions/56395
Enabling shr-external-rendering-functions Variable in EWW
2020-03-27T08:43:29.827
# Question Title: Enabling shr-external-rendering-functions Variable in EWW Began using Emacs `eww` nowadays, but now seeking to adapt it better for Html websites. That way some user said to "buffer-locally setting the variable `shr-external-rendering-functions`", as of What EWW Emacs Web Brower Would Be Used For But don't know how to do it. Any idea? # Answer > 6 votes If you want to generally change/add the rendering of nodes of a certain tag type you just add an association from the tag as symbol to the rendering function in the list `shr-external-rendering-functions`. Example: Render `<em>` nodes using a self defined function `my-tag-em`: ``` (add-to-list 'shr-external-rendering-functions '(em . my-tag-em)) ``` I have tested the code with Emacs 26.3. The rendering function recieves the node as parsed by `libxml-parse-html-region` and should insert the rendered representation of the node at point of the current buffer (which is the `eww-mode` buffer). The structure of the nodes is described in on the page about the Document Object Model (DOM) in the info manual for Elisp `M-:` `(info "(Elisp)Document Object Model")` `RET`. Each node is a list. The elements are: * **0th:** tag name as a symbol * **1st:** association list of attributes, each attribute is represented as a cons: + **car:** attribute name as a symbol + **cdr:** value as a string * **rest:** contents of the tag as children of the node Example: `M-:` `(libxml-parse-html-region (point-min) (point-max))` `RET` for the following html buffer returns the subsequent DOM. ``` <!DOCTYPE html> <html> <head> <title>Test</title> </head> <body style=none> Test of <em>emphasis</em>. </body> </html> ``` The corresponding DOM: ``` (html nil (head nil (title nil "Test")) (body ((style . "none")) " Test of " (em nil "emphasis") ". ")) ``` Next we define our rendering function `my-tag-em` such that it frames the contents of the `<em>` tag by Org-style `*` characters. One can use `shr-generic` to render the contents (i.e., the children) of the tag. ``` (defun my-tag-em (dom) "Render <em>-tag DOM as *CONTENT*." (insert "*") (shr-generic dom) ;; point is now behind the contents (insert "*")) ``` Finally, we have a look at `shr-tag-em` which is normally used by `shr` for rendering the `<em>` tag. The used function `shr-fontize-dom` is listed with additional comments. ``` (defun shr-tag-em (dom) (shr-fontize-dom dom 'italic)) (defun shr-fontize-dom (dom &rest types) (let ((start (point))) ;; remember start of inserted region (shr-generic dom) ;; inserts the contents of the tag (dolist (type types) (shr-add-font start (point) type)) ;; puts text properties of TYPES on the inserted contents )) ``` --- Tags: eww, shr ---
thread-56420
https://emacs.stackexchange.com/questions/56420
Make buffer unreachable
2020-03-28T03:19:18.550
# Question Title: Make buffer unreachable This may be a silly question, but how can I make a buffer unreachable? I have enabled live-py-mode. Every time I try to edit my python file it evaluates the code, which is a well and good but it's a little annoying how it switches focus from the source file to the eval result. Is there a way I can prevent changing focus from source to result? # Answer > 1 votes *Edit:* In hindsight, I think I've answered a somewhat different question, and that your actual question probably requires direct knowledge of `live-py-mode` (which I don't have). I would suspect that if the window in question is being *selected* and that doing so makes no sense, then this is probably a `live-py-mode` bug to be raised with its author? The following answer was aimed at preventing a particular window from being displayed at all... --- You can use the `display-buffer-no-window` action with `display-buffer-alist`, but you need to know how to identify the buffer. Here I have assumed the buffer is always named `*py-live-eval*`, and have specified a regexp matching that. ``` (add-to-list 'display-buffer-alist (cons "^\\*py-live-eval\\*$" (cons 'display-buffer-no-window '((allow-no-window . t))))) ``` --- Tags: python ---
thread-56411
https://emacs.stackexchange.com/questions/56411
tramp -- open shell prompt for existing connection
2020-03-27T21:58:26.637
# Question Title: tramp -- open shell prompt for existing connection i started using the eldritch and mysterious tramp again because a user on here helped me fix it. (thanks michael: tramp runs on odt export --). i create org mode links to my commonly-used remote conf files. when i click on them my tramp session starts up successfully. it's possibly a no-brainer, but my question is how can i drop to a shell after i'm done finishing editing my conf file? to like restart a service or similar. i know i can run `shell` or `eshell` and run ssh, but that starts a new connection which is really no different to reaching for the terminal emulator. surely i can magically just shell within my existing tramp connection? # Answer `M-x shell` runs always a new shell asynchronously, which means a new connection. If you just need to run a command on the remote host, consider `shell-command`. Something like `(shell-command "hostname")` is an example for this. > 2 votes # Answer Invoking `M-x shell` from a buffer with a remote file name should start a shell on the remote host. The same thing applies to most commands which start a process. > how can i drop to a shell after i'm done finishing editing my conf file? It sounds like you simply need to use `M-x shell` in that conf file's buffer. > 2 votes --- Tags: tramp, shell ---
thread-56416
https://emacs.stackexchange.com/questions/56416
Org ASCII export with indentation preserved
2020-03-28T01:06:53.563
# Question Title: Org ASCII export with indentation preserved Open your EMACS `-Q`, enter org mode, and ``` #+begin_src emacs-lisp (setf x '(a b c d e f)) #+end_src ``` This is how it will be aligned after `org-edit-special` (`C-c '`). Now export to an ASCII buffer with `C-c C-e t A`. You will see ``` ,---- | | (setf x '(a b c | d e f)) | `---- ``` Clearly, the indentation has changed. How does one get indentation as in the source? --- P.S. This does not happen when exporting to a LaTeX buffer. It seems to be a bug resulting from the use of tab characters and the insertion of two extra characters at the beginning of each source line. I suppose plain-text export isn't used that much. # Answer Just see to it that the whole buffer is free of tabulators before you export it. To avoid untabbing the original, use a hook. ``` (defun org*-export-untabify (backend) (untabify 0 (point-max))) (add-hook 'org-export-before-parsing-hook 'org*-export-untabify) ``` > 0 votes --- Tags: org-export, indentation ---
thread-57429
https://emacs.stackexchange.com/questions/57429
org-mode: link to tag/target inside a source code block
2020-03-28T16:37:05.103
# Question Title: org-mode: link to tag/target inside a source code block I'd like to place a link to a tag or target inside a source code block. ``` #+BEGIN_SRC emacs-lisp (use-package evil :ensure t :config ; enable per default (evil-mode t) ; <<evil-bindings>> :bind ("C-^" . evil-buffer) ; Switch to another buffer quickly #+END_SRC *** Key bindings See [[file:::/<<evil-bindings>>/]] ``` Ideally this should jump the to position of `; |<<evil-bindings>>` inside the source block when followed via `C-c C-o`. I've tried `See [[<<evil-bindings>>]]` before I tried "Method 2" in the answer from user Melioratus in How to reference source blocks in org text. My first try just prompts with `No match - create this as a new heading? (yes or no)` in the minibuffer. The "Method 2" just calls occur as mentioned in the answer. But there's another problem. When going from my first try and editing the link via `C-c C-l` and answering either just `file:::` or `file:::/regexp/` to the `Link:` prompt, it errors out with `org-insert-link: Args out of range: "file:::/<<evil-bindings>>/", 5, 4`. (I then activated and edited the link manually.) NB: I haven't configured anything related to org-mode yet (not even `(require 'org)` in my init.el). My emacs and org-mode version: * GNU Emacs 26.1 (build 2, x86\_64-pc-linux-gnu, GTK+ Version 3.24.5) of 2019-09-23, modified by Debian * Org mode version 9.1.9 (release\_9.1.9-65-g5e4542 @ /usr/share/emacs/26.1/lisp/org/) Greetings, AWG # Answer > 5 votes > In literal examples, Org interprets strings like `(ref:name)` as labels, and use them as targets for special hyperlinks like `[[(name)]]` (...) You can also add a `-r` switch which removes the labels from the source code. ``` See [[(jump)]]. #+begin_src emacs-lisp -r (let ((x 1)) (ref:jump) (print x)) #+end_src ``` --- Tags: org-mode, org-babel, org-link ---
thread-15096
https://emacs.stackexchange.com/questions/15096
How do you update a minor mode definition as you develop it?
2015-08-27T14:07:54.463
# Question Title: How do you update a minor mode definition as you develop it? I started coding a minor mode to provide some keybindings. My initial attempt had a typo: ``` (define-minor-mode borked-mode "A mode defined with a broken key binding" nil nil '(([b] . 'previous-line))) ``` I had intended to use the `b` key, and immediately realized that I should have used `"b"` instead of `[b]`. So I redefined the minor mode: ``` (define-minor-mode borked-mode "A mode defined with a broken key binding" nil nil '(("b" . 'previous-line))) ``` However, this didn't work. This set me off on a wild goose chase through all the various ways of binding keys (i.e., (kbd ...), \[ ... \], etc). Finally I realized that simply re-evaluating the `(define-minor-mode ...)` form was not changing anything, I was stuck with the original, broken key map. I then tried changing the keymap directly via `(define-key borked-mode-map ...)` and still couldn't get the corrected keymap loaded. Finally I restarted Emacs, and my minor mode was correctly loaded. **My question is:** how do you update a minor mode definition as you develop it? Is there any way to flush a broken definition, or do you have to restart emacs to clear away broken bits? # Answer > 14 votes The first time you evaluate your `define-minor-mode` it defines a variable `borked-mode-map` with the key bindings you specified. Once that symbol has been defined, however, re-evaluating your `define-minor-mode` won't change it. You could delete the various `borked-mode-xxx` symbols using `unintern` and then re-evaluate your code. Try: ``` (unintern 'borked-mode-map) ``` You might be interested in expanding the `define-minor-mode` macro to see what it is actually doing. Put point at the end and call `M-x pp-macroexpand-last-sexp`. This will open a new buffer showing the expanded macro. There you'll see the `defvar` calls used to set up your mode variables. If you read the help for `defvar` you'll see that the initial value is only used if the symbol being defined is void -- once it exists, subsequent `defvar` calls won't change its value. # Answer > 15 votes I think the best answer I can give you is to stay away from the "inline keybindings feature" of `define-minor-mode`. Use ``` (defvar borked-mode-map (let ((map (make-sparse-keymap))) (define-key map [b] 'previous-line) ... map)) (define-minor-mode borked-mode "A mode defined with a broken key binding" :global nil ...) ``` Instead. Then you can use `C-M-x` to re-evaluate those definitions. # Answer > 0 votes You can define your mode map like this: ``` (defvar dnd-mode-map (let ((map (make-sparse-keymap))) (prog1 map (define-key map "q" 'dnd-quit) (when (eq this-command 'eval-defun) (let ((mmap (assq 'dnd-mode minor-mode-map-alist))) (when mmap (setcdr mmap map))))))) ``` Now you are able to reevaluate the map definition using `eval-defun` and it will automatically update the stored map inside `minor-mode-map-alist`. --- Tags: minor-mode ---
thread-29871
https://emacs.stackexchange.com/questions/29871
How to embed svg output of org-mode src block as inline svg in html export?
2017-01-07T23:05:20.810
# Question Title: How to embed svg output of org-mode src block as inline svg in html export? I wish to embed the svg file output of gnuplot as inline svg code in the html export. Currently I do the following: 1. Manually remove the RESULTS block. 2. INCLUDE the svg file as shown in the MWE below. How can i configure the RESULTS block to do what I want automatically? ``` #+BEGIN_SRC gnuplot :file example-plot.svg :exports code plot sin(x) #+END_SRC #+RESULTS: [[file:example-plot.svg]] # I manually remove the above RESULTS block # and insert the following INCLUDE #+INCLUDE: "example-plot.svg" export html ``` # Answer > 7 votes The cleanest solution would be if the babel authors would include it as a option for blocks that can produce SVG output. The solution I give here uses a :post option that invokes another src code block filtering the results of the current block. This is a powerful technique, but it can also make the code more difficult to read and debug. First I define the postFileToIclude filter function to use in the later code block, and I test it by giving it a file link string (someplot.svg) explicitely. ``` #+NAME: postFileToInclude #+HEADER: :var text="[[file:someplot.svg]]" #+BEGIN_SRC elisp :results value raw drawer (with-temp-buffer (erase-buffer) (cl-assert text nil "PostFileToInclude received nil instead of text ") (insert text) (beginning-of-buffer) (if (re-search-forward org-any-link-re nil t) (progn (let ((fname (match-string 2))) (replace-match (format "#+INCLUDE: \"%s\" export html" fname)) )) (error "PostFileToInclude: Was not able to find link in output")) (buffer-string) ) #+END_SRC #+RESULTS: postFileToInclude :RESULTS: #+INCLUDE: "file:someplot.svg" export html :END: ``` Now we use this function in a :post argument for filtering your src block. One also needs to add a :results option, so that the output is not in an example environment. I also add a drawer, so that repeated executions will be able to correctly replace the results of previous evaluations. ``` #+BEGIN_SRC gnuplot :file example-plot.svg :exports code :post postFileToInclude :results raw drawer plot sin(x) #+END_SRC #+RESULTS: :RESULTS: #+INCLUDE: "file:example-plot.svg" export html :END: ``` # Answer > 2 votes The following code adds the option `html-embed-svg` to the `html` export backend of Orgmode. You can also set this option with the meta-comment `#+HTML_EMBED_SVG: t`. If you set this option to `t` SVG images are embedded into the exported HTML document. The default value is `nil` which stands for the standard behavior to link svg images. ``` (require 'ox-html) (require 'nxml-mode) (defcustom org+-html-embed-svg nil "Embed SVG images. You can set this variable in Org files with #+HTML_EMBED_SVG: t or #+OPTIONS: html-embed-svg:t" :type 'boolean :group 'org-export-html) (cl-pushnew '(:html-embed-svg "HTML_EMBED_SVG" "html-embed-svg" org+-html-embed-svg) (org-export-backend-options (org-export-get-backend 'html))) (defun org+-html-svg-image-embed (fun source attributes info) "Make embedding of SVG images possible in org HTML export. SVG images are embedded if :html-embed-svg is non-nil in the plist INFO. Otherwise FUN called with SOURCE, ATTRIBUTES, and INFO as arguments. SOURCE is the file name of the SVG file. This is an around advice for `org-html--svg-image' as FUN." (if (member (plist-get info :html-embed-svg) '("yes" "t" t)) (with-temp-buffer (insert-file-contents source) (with-syntax-table nxml-mode-syntax-table (while (and (search-forward "<svg") ;; barfs if a "<svg" is not found in code (nth 8 (syntax-ppss))))) (delete-region (point-min) (match-beginning 0)) (buffer-string)) (funcall fun source attributes info))) (advice-add 'org-html--svg-image :around #'org+-html-svg-image-embed) ``` --- Tags: org-mode, org-export ---
thread-56418
https://emacs.stackexchange.com/questions/56418
Org mode evaluating propertized string removes properties
2020-03-28T02:21:37.230
# Question Title: Org mode evaluating propertized string removes properties See the following code block: ``` #+BEGIN_SRC emacs-lisp (setq s #("abc" 0 3 (face (:foreground "red")))) (pp s) #+END_SRC #+RESULTS: : #("abc" 0 3 : (face : (:foreground "red"))) ``` which is as expected, but literally just by evaluating, ``` #+BEGIN_SRC emacs-lisp s #+END_SRC #+RESULTS: : abc #+BEGIN_SRC emacs-lisp (pp s) ;; how did s change? #+END_SRC #+RESULTS: : "abc" ``` I noticed this when calling `C-c C-c` on ``` #+BEGIN_SRC emacs-lisp org-mode-line-string #+END_SRC ``` actually removes fontification on the mode line of the current clocking task. This does not happen for `C-x C-e`(`eval-last-sexp`). I'm using Org 9.1.9 on Emacs 26.3. # Answer > 1 votes Let us have a look at `org-no-properties` which is used for removing the properties from the result string: ``` (defsubst org-no-properties (s &optional restricted) "Remove all text properties from string S. When RESTRICTED is non-nil, only remove the properties listed in `org-rm-props'." (if restricted (remove-text-properties 0 (length s) org-rm-props s) (set-text-properties 0 (length s) nil s)) s) ``` For removing the text properties they use the destructive in-place functions `remove-text-properties` and `set-text-properties`. That is the cause for the removal of the text properties from the original string. They should copy the string with `seq-copy` before removing the properties. The current behavior is unpleasant handling that could almost be regarded as a bug. Maybe, you should write an enhancement request with `M-x` `report-emacs-bug` `RET`. Currently you are responsible for copying. Change your source block to: ``` (seq-copy org-mode-line-string) ``` Or use the advice I proposed in the answer to your related question. --- Tags: org-babel ---
thread-56421
https://emacs.stackexchange.com/questions/56421
How to 'modify-syntax-entry' for a major mode?
2020-03-28T05:02:22.213
# Question Title: How to 'modify-syntax-entry' for a major mode? Following this answer, when I type `(modify-syntax-entry ?_ "w")` and do `M-x eval-region`, it has the effect I'm looking for, albeit only for that buffer. I've put `(modify-syntax-entry ?_ "w")` in my `.emacs` file, however and after restarting, it's *not* having effect in my C/C++ code. I'm using Emacs `GNU Emacs 26.3 (build 1, x86_64-redhat-linux-gnu, GTK+ Version 3.24.13) of 2019-12-11`. My OS is: `Fedora release 31 (Thirty One)`. *<sub>There are questions with nearly the exact same title, but their accepted answers do not work for C/C++ mode, so this is a different question.</sub>* # Answer Each major mode has its own syntax and syntax table. If you just put `(modify-syntax-entry ?_ "w")` in your init file, it gets evaluated in the buffer that is current when your init file is loaded -- not in a C/C++ buffer. To evaluate that sexp when in a C/C++ buffer you can put it in a function, which you add to the mode hook. For example (untested): ``` (add-hook 'c-mode-hook (lambda () (modify-syntax-entry ?_ "w"))) ``` But it's generally better to use a named, not an anonymous, hook function. For example: ``` (defun foo () (modify-syntax-entry ?_ "w")) (add-hook 'c-mode-hook 'foo) ``` > 12 votes # Answer Rather than modifying the syntax tables, you can instead use the built-in `superword-mode`: > Superword mode is a buffer-local minor mode. Enabling it changes the definition of words such that symbols characters are treated as parts of words: e.g., in ‘superword-mode’, "this\_is\_a\_symbol" counts as one word. You can enable it per mode using a a hook: `(add-hook 'c++-mode-hook 'superword-mode)` or globally with `(global-superword-mode 1)` in your `.emacs` > 5 votes --- Tags: syntax-table, syntax ---
thread-46891
https://emacs.stackexchange.com/questions/46891
Activating a conda environment in emacs
2019-01-03T17:23:49.480
# Question Title: Activating a conda environment in emacs I've got code that needs python 2.7 (and other environments) ``` C:\Users\Me>conda info -e # conda environments: # base * C:\Program Files\Anaconda3 python2 C:\Program Files\Anaconda3\envs\python2 ``` I would like to be able to selectively activate python2 when I start a python shell in emacs (i.e. I send a line of code to the python interpreter using elpy). being able to put this in an init file would be cool. I have tried both the conda and pyenv packages with no luck in my current configuration. Conda can't find my environments and pyenv doesn't seem to actually activate the virtual environment. Using Emacs 26.1 and conda 4.5.11 Any help would be appreciated. # Answer > 3 votes Activate your virtualenv with: ``` (pyvenv-activate "C:\Program Files\Anaconda3\envs\python2") ``` If the binaries in your virtualenv are names "python2", you will need to set ``` (setq python-shell-interpreter "python2") ``` to ensure the good python binaries will be used by Elpy. # Answer > 2 votes You can use conda.el to manage your conda environments within python. After install and setup, do `M-x conda activate python2` # Answer > 1 votes I use pyvenv to activate/manage my virtual environments and have the following called from my `init.el`... ``` (elpy-enable) (pyvenv-activate "~/.virtualenvs/dskit") ``` I have installed virtualenvwrapper which resides in `~/.virtualenvs` and creates the virtualenvs within there (e.g. `dskit` that is being activated). As you are using Conda change `~/.virtualenvs/dskit` to point to the location of the Conda environment you wish to use. Obviously you then need to install the Emacs `pyvenv` package (I use the latest version from MELPA). I'm by no means an expert in either Python, Virtual Envs or Emacs and used the following articles from realpython.com.... --- Tags: python, elpy, anaconda-mode ---
thread-57442
https://emacs.stackexchange.com/questions/57442
How to set a variable that matches different type of strings?
2020-03-29T08:14:54.457
# Question Title: How to set a variable that matches different type of strings? I have these strings: * First Type: ``` arXiv:1234.56789 arXiv:1234.56789v1 ``` * Second type: ``` hep-th/123456789 hep-th.AB/12345689 hep-th/123456789v1 hep-th.AB/12345689 ``` Belong to the second type even strings with no "-" in their names, such as `math/123456789` or `CoRR/123456789`. I have to do some "search and replace" on all these strings, so I would like to define a variable `ARXIV` that matches all of these strings. So, I have defined: ``` ;; arXiv:1234.56789vK (setq ARXIV-A "arXiv:\\([0-9]+\\)\\.\\([0-9]+\\)\\(v[0-9]+\\)?") ;; hep-th/1234567vK ;; math.XX/1234567vK (setq ARXIV-NA "\\(astro-ph\\|cond-mat\\|gr-qc\\|hep-ex\\|hep-lat\\|hep-ph\\|hep-th\\|math-ph\\|nlin\\|nucl-ex\\|nucl-th\\|physics\\|quant-ph\\|math\\|CoRR\\|q-bio\\|q-fin\\|stat\\|eess\\|econ\\)\\(\\.[A-Z]+\\)?/\\([0-9]+\\)\\(v[0-9]+\\)?") (setq ARXIV (concat "\\(" ARXIV-A "\\|" ARXIV-NA "\\)")) ``` **Test** ``` ---------- Buffer: foo ---------- -!-[arXiv:1234.56789] [arXiv:1234.56789v1] [hep-th/123456] [hep-th.QA/123456] [quant-ph.QA/123456] [hep-th/123456v12] ---------- Buffer: foo ---------- (perform-replace (concat "\\(\\[\\)?" ARXIV "\\(\\]\\)?") "\\1 BEG \\2 END \\3" t t nil 1 nil (point-min) (point-max)) ---------- Buffer: foo ---------- [ BEG arXiv:1234.56789 END 1234 [ BEG arXiv:1234.56789 END 1234 [ BEG arXiv:1234.56789v1 END 1234 [ BEG hep-th/123456 END [ BEG hep-th.QA/123456 END [ BEG quant-ph.QA/123456 END [ BEG hep-th/123456v12 END hep-th/123456 ---------- Buffer: foo ---------- ``` The problem is that `\\3` does not correspond to `\\(\\]\\)?` seeing as how `ARXIV-A` and `ARXIV-NA` do not have (always) the same length, I think. I have tried different configurations of my variables, but the problem is always the same: in replacement code `\digit` does not work as I was expecting after `ARXIV`. Indeed, ``` (perform-replace (concat "\\(\\[\\)" ARXIV "\\(\\]\\)") "\\2" t t nil 1 nil (point-min) (point-max)) ``` works as I was expecting (groups are useless here, but this is only an example to clear better my question). Is there a way to do this "search and replacement" with only one variable? P.S. Any better idea to entitle my question is welcome! # Answer > The problem is that `\\3` does not correspond to `\\(\\]\\)?` ``` (concat "\\(\\[\\)?" ARXIV "\\(\\]\\)?") ``` Gives you the following regexp: ``` "\\(\\[\\)?\\(arXiv:\\([0-9]+\\)\\.\\([0-9]+\\)\\(v[0-9]+\\)?\\|\\(astro-ph\\|cond-mat\\|gr-qc\\|hep-ex\\|hep-lat\\|hep-ph\\|hep-th\\|math-ph\\|nlin\\|nucl-ex\\|nucl-th\\|physics\\|quant-ph\\|math\\|CoRR\\|q-bio\\|q-fin\\|stat\\|eess\\|econ\\)\\(\\.[A-Z]+\\)?/\\([0-9]+\\)\\(v[0-9]+\\)?\\)\\(\\]\\)?" ``` Which has 10 groups. `\\(\\]\\)` is group 10, not group 3. `C-h``i``g` `(elisp)Regexp Backslash` confirms that only groups 1-9 can be referenced by the `\DIGIT` syntax, so you would need to modify the regexp to reduce the number of groups being captured, which you would typically do by using *non-capturing* (or "shy") groups in your regexp for the groups which you do not need to reference independently. You specify a non-capturing group by using `\\(?:` to open the group, instead of just `\\(` --- You can alternatively set/clobber an explicit group number by opening the group with `\\(?NUM:` In your case: ``` (concat "\\(\\[\\)?" ARXIV "\\(?3:\\]\\)?") ``` Would mean `\\3` would reference `\\(?3:\\]\\)` (and the original group 3 would not be accessible). --- Finally, to incorporate your own useful comment into this answer: While the `\DIGIT` syntax is limited to groups 1-9, higher group numbers are accessible in elisp with, E.g., `(match-string 10)` --- Quoting `C-h``i``g` `(elisp)Regexp Backslash` > `\(?: ... \)` > is the “shy group” construct. A shy group serves the first two purposes of an ordinary group (controlling the nesting of other operators), but it does not get a number, so you cannot refer back to its value with ‘\DIGIT’. Shy groups are particularly useful for mechanically-constructed regular expressions, because they can be added automatically without altering the numbering of ordinary, non-shy groups. > > Shy groups are also called “non-capturing” or “unnumbered groups”. > > `\(?NUM: ... \)` > is the “explicitly numbered group” construct. Normal groups get their number implicitly, based on their position, which can be inconvenient. This construct allows you to force a particular group number. There is no particular restriction on the numbering, e.g., you can have several groups with the same number in which case the last one to match (i.e., the rightmost match) will win. Implicitly numbered groups always get the smallest integer larger than the one of any previous group. ``` ``` > 2 votes --- Tags: regular-expressions, search, replace, variables ---
thread-41407
https://emacs.stackexchange.com/questions/41407
How to use org-protocol and org-capture in spacemacs?
2018-05-09T13:12:38.320
# Question Title: How to use org-protocol and org-capture in spacemacs? I've been having some problems when using `org` inside `spacemacs`. I make use of `org-protocol` to capture stuff that I find interesting when I'am browsing and have it inside `spacemacs`. The problem is that I can't seem to get it this process to work flawlessly. Sometimes everything works fine but other times instead of opening the capture inside spacemacs I get `No server buffers remain to edit` and a new browser window pops up. Othertime I get `Error (use-package): org-projectile/:config: Symbol’s function definition is void: org-projectile:per-repo` and once again a new browser window pops up. In my `.spacemacs` file I enabled the `org` layer and in `user-config` I have the following: ``` (server-start) (use-package org-capture :bind ("<f8>" . org-capture) :after org) (use-package org-protocol :after org) ``` # Answer You should enable `org-protocol` in `org-modules`. You can do this via `M-x customize-group RET org RET` or put the following in your init file: `(setq org-modules (quote (org-protocol)))`. There are also some other ways to enable modules as detailed here. > 1 votes # Answer Just inserting `org-protocol` into `org-modules` did not work for me, what helped was adding a `require`: ``` (defun dotspacemacs/user-config () (require 'org-protocol) ``` > 0 votes # Answer Although it doesn't seem to have been the issue here, for reference I was also receiving the *No server buffers remain to edit* message. Not 100% sure as I tried a number of things, but in my case it seemed to be because my capture template was pointing to a heading that didn't exist. > 0 votes --- Tags: spacemacs, org-capture ---
thread-57432
https://emacs.stackexchange.com/questions/57432
Why does org mode elisp evaluation not print text properties?
2020-03-28T20:31:44.533
# Question Title: Why does org mode elisp evaluation not print text properties? With no special header argument values, I have ``` #+BEGIN_SRC emacs-lisp (propertize "abc" 'face 'italic) #+END_SRC #+RESULTS: : abc ``` whereas `C-x C-e` on the form gives me ``` #("abc" 0 3 (face italic)) ``` why is there this discrepancy? Is there a difference between org mode source `C-c C-c` and `C-x C-e`? # Answer > 4 votes `C-c C-c` has the key-binding `org-ctrl-c-ctrl-c` which runs `org-babel-exec-src-block` if `point` is inside a source block. `C-x C-e` runs `eval-last-sexp` which has nothing to do with Orgmode. `org-babel-execute-src-block` uses `org-babel-insert-result` for inserting the result into the Org buffer. There, `org-no-properties` removes the text properties from the result string. I assume that they remove text properties because many of the properties would immediately be overwritten by `font-lock` fontification anyway. The following advice of `org-babel-insert-result` defines a new `:result` flag `props` (or `properties`). Source blocks where the `:results` header argument contains that flag keep the text properties on the result string. ``` (require 'find-func) (with-current-buffer (find-file-noselect (find-library-name "ob-core.el")) ;; This is a hack. ;; `org-no-properties' is defined by `defsubst' and the byte-compiler replaces the symbol with the lambda. ;; We need the definition of `org-babel-insert-result' containing the symbol `org-no-properties'. ;; Therefore, we eval the defun for `org-babel-insert-result' in the source file. (goto-char (point-min)) (re-search-forward "(defun org-babel-insert-result") (eval-defun nil)) (defun org+-babel-insert-result-with-props (fun result result-params &rest args) "Avoid removing text properties in `org-babel-insert-result'. Add the new result type \"raw-props\" to Org source blocks. With this result type text properties are not removed from the result. This is an :around advice for `org-babel-insert-result' as FUN. RESULT, RESULT-PARAMS, and ARGS are passed to FUN." (if (or (member "props" result-params) (member "properties" result-params)) (cl-letf* (((symbol-function 'org-no-properties) (lambda (str &rest _args) str))) (apply fun result (delete "properties" (remove "props" result-params)) args)) (apply fun result result-params args))) (advice-add 'org-babel-insert-result :around #'org+-babel-insert-result-with-props) ``` But that only works reliably with `:result` type `raw`. For an example the result string of the following source block is colored red: ``` #+BEGIN_SRC emacs-lisp :results raw drawer props (propertize "string" 'font-lock-face 'hi-red-b) #+END_SRC ``` # Answer > 1 votes > why is there this discrepancy? Is there a difference between org mode source C-c C-c and C-x C-e? As Tobias's answer mentioned, `C-x C-e` and Org Mode's `C-c C-c` are two different commands, so it's not a surprise if their results are different. For example, `C-x C-e` after `42` prints `42 (#o52, #x2a, ?*)`, as you can see, `C-x C-e` decides to print `42` not only in decimal form but also octal, hex and character form, however, no one asks Org Mode's `C-c C-c` to do the same. --- As for your particular example, you can escape the string value once more to prevent Org from removing the text properties with `prin1-to-string` or `format`: ``` #+begin_src elisp (prin1-to-string (propertize "abc" 'face 'italic)) #+end_src #+RESULTS: : #("abc" 0 3 (face italic)) #+begin_src elisp (format "%S" (propertize "abc" 'face 'italic)) #+end_src #+RESULTS: : #("abc" 0 3 (face italic)) ``` --- Tags: org-mode, org-babel ---
thread-57434
https://emacs.stackexchange.com/questions/57434
Hook on entering org latex fragment
2020-03-28T21:03:27.293
# Question Title: Hook on entering org latex fragment Hi is there a hook that gets triggered upon entering a LaTeX fragment in org? I'm trying to do ``` (add-hook <enter-org-latex-hook> 'org-cdlatex-mode) ``` but can't seem to find the correct hook to attach to. # Answer I do not know of any such hook. But you can add one. The following Elisp code shows how you can use `cursor-sensor-mode` and the `cursor-sensor-functions` text property to call hook functions when the formula overlays are entered or left. The hook where you can link in is `org+-formula-cursor-sensor-functions`. Switching on and off `cdlatex-mode` is demonstrated at the end of the code. ``` (require 'org) (require 'org-element) (defvar org+-formula-cursor-sensor-functions nil "Functions called when cursor enters or leaves LaTeX preview overlays. They are called with three arguments WINDOW, POSITION, and ACTION. ACTION can be 'entered or 'left. See text property `cursor-sensor-functions' in (info \"(elisp)Special Properties\").") (defun org+-formula-cursor-sensor-fun (window pos action) "Just run hooks in `org+-formula-cursor-sensor-functions'. Run each of these functions with args WINDOW, POS, and ACTION." (run-hook-with-args 'org+-formula-cursor-sensor-functions window pos action)) (defun org+-formula-cursor-sensor (fun beg end &rest args) "Add the cursor-sensor-functions property to the overlay between BEG and END. This is an around advice for `org--format-latex-make-overlay' as FUN. FUN is called with BEG, END, and the members of ARGS. It is assumed that FUN returns the display property of the overlay." (let* ((ret (apply fun beg end args)) (ov (cl-loop for ov being the overlays from beg to end if (eq (overlay-get ov 'display) ret) return ov))) (overlay-put ov 'cursor-sensor-functions (list #'org+-formula-cursor-sensor-fun)) ret)) (advice-add 'org--format-latex-make-overlay :around #'org+-formula-cursor-sensor) (defun org+-cdlatex-when-formula-entered (window _pos action) "Depending on ACTION switch cdlatex on or off in the buffer of WINDOW. Switch it on if ACTION is 'entered and off otherwise." (with-current-buffer (window-buffer window) (if (eq action 'entered) (cdlatex-mode) (cdlatex-mode -1)))) (defun org+-auto-cdlatex () "Automatically switch cdlatex on or off when formula overlays are entered or left." (cursor-sensor-mode) (add-hook 'org+-formula-cursor-sensor-functions #'org+-cdlatex-when-formula-entered)) (add-hook 'org-mode-hook #'org+-auto-cdlatex) ``` > 1 votes # Answer I don't know the answer to this question specifically but you may wish to see how the org-fragtog package handles movement of point in and out of LaTeX fragments. > 0 votes --- Tags: org-mode, latex ---
thread-56426
https://emacs.stackexchange.com/questions/56426
mu4e: Problem sending email with Gmail
2020-03-28T10:37:53.440
# Question Title: mu4e: Problem sending email with Gmail I use mu4e to handle my 3 email accounts - Exchange, Posteo, Gmail. While I have no problem sending emails with Exchange and Posteo, I encounter the following issue when sending via Gmail: ``` Debugger entered--Lisp error: (error "Sending failed: 535-5.7.8 Username and Password not accepted. Learn more at\n535 5.7.8 https://support.google.com/mail/?p=BadCredentials c207sm5903330pfb.47 - gsmtp in response to AUTH") signal(error ("Sending failed: 535-5.7.8 Username and Password not accepted. Learn more at\n535 5.7.8 https://support.google.com/mail/?p=BadCredentials c207sm5903330pfb.47 - gsmtp in response to AUTH")) error("Sending failed: %s" "535-5.7.8 Username and Password not accepted. Learn more at\n535 5.7.8 https://support.google.com/mail/?p=BadCredentials c207sm5903330pfb.47 - gsmtp in response to AUTH") smtpmail-send-it() message-use-send-mail-function() message--default-send-mail-function() message-multi-smtp-send-mail() message--send-mail-maybe-partially() message-send-mail(nil) message-send-via-mail(nil) message-send(nil) message-send-and-exit() org-msg-ctrl-c-ctrl-c() run-hook-with-args-until-success(org-msg-ctrl-c-ctrl-c) (cond ((memq type '(src-block inline-src-block)) (if org-babel-no-eval-on-ctrl-c-ctrl-c nil (org-babel-eval-wipe-error-buffer) (org-babel-execute-src-block current-prefix-arg (org-babel-get-src-block-info nil context)))) ((org-match-line "[ \11]*$") (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook) (user-error (substitute-command-keys "`\\[org-ctrl-c-ctrl-c]' can do nothing useful...")))) ((memq type '(inline-babel-call babel-call)) (let ((info (org-babel-lob-get-info context))) (if info (progn (org-babel-execute-src-block nil info))))) ((eq type 'clock) (org-clock-update-time-maybe)) ((eq type 'dynamic-block) (save-excursion (goto-char (org-element-property :post-affiliated context)) (org-update-dblock))) ((eq type 'footnote-definition) (goto-char (org-element-property :post-affiliated context)) (call-interactively 'org-footnote-action)) ((eq type 'footnote-reference) (call-interactively #'org-footnote-action)) ((memq type '(inlinetask headline)) (save-excursion (goto-char (org-element-property :begin context)) (call-interactively #'org-set-tags-command))) ((eq type 'item) (let* ((box (org-element-property :checkbox context)) (struct (org-element-property :structure context)) (old-struct (copy-tree struct)) (parents (org-list-parents-alist struct)) (prevs (org-list-prevs-alist struct)) (orderedp (org-not-nil (org-entry-get nil "ORDERED")))) (org-list-set-checkbox (org-element-property :begin context) struct (cond ((equal arg ...) "[-]") ((and ... ...) "[ ]") ((or ... ...) nil) ((eq box ...) "[ ]") (t "[X]"))) (org-list-struct-fix-ind struct parents 2) (org-list-struct-fix-item-end struct) (org-list-struct-fix-bul struct prevs) (org-list-struct-fix-ind struct parents) (let ((block-item (org-list-struct-fix-box struct parents prevs orderedp))) (if (and box (equal struct old-struct)) (if (equal arg ...) (message "Checkboxes already reset") (user-error "Cannot toggle this checkbox: %s" ...)) (org-list-struct-apply-struct struct old-struct) (org-update-checkbox-count-maybe)) (if block-item (progn (message "Checkboxes were removed due to empty box at ..." ...)))))) ((eq type 'keyword) (let ((org-inhibit-startup-visibility-stuff t) (org-startup-align-all-tables nil)) (if (boundp 'org-table-coordinate-overlays) (progn (mapc #'delete-overlay org-table-coordinate-overlays) (setq org-table-coordinate-overlays nil))) (let* ((--invisible-types '...) (--markers\? 'use-markers) (--data (mapcar ... ...))) (unwind-protect (progn (org-mode-restart)) (save-excursion (save-restriction ... ... ...))))) (message "Local setup has been refreshed")) ((eq type 'plain-list) (let* ((begin (org-element-property :contents-begin context)) (struct (org-element-property :structure context)) (old-struct (copy-tree struct)) (first-box (save-excursion (goto-char begin) (looking-at org-list-full-item-re) (match-string-no-properties 3))) (new-box (cond (... "[-]") (... ...) (... "[ ]") (t "[X]")))) (cond (arg (let (...) (while --dolist-tail-- ...))) ((and first-box (eq ... begin)) (org-list-set-checkbox begin struct new-box))) (if (equal (org-list-write-struct struct (org-list-parents-alist struct) old-struct) old-struct) (progn (message "Cannot update this checkbox"))) (org-update-checkbox-count-maybe))) ((memq type '(node-property property-drawer)) (call-interactively #'org-property-action)) ((eq type 'radio-target) (call-interactively #'org-update-radio-target-regexp)) ((eq type 'statistics-cookie) (call-interactively #'org-update-statistics-cookies)) ((memq type '(table-row table-cell table)) (if (eq (org-element-property :type context) 'table\.el) (message "%s" (substitute-command-keys "\\<org-mode-map>Use `\\[org-edit-special]' to ...")) (if (or (eq type 'table) (and (eq type ...) (= ... ...))) (save-excursion (if (org-at-TBLFM-p) (progn ... ...) (goto-char ...) (org-call-with-arg ... ...) (orgtbl-send-table ...))) (org-table-maybe-eval-formula) (cond (arg (call-interactively ...)) ((org-table-maybe-recalculate-line)) (t (org-table-align)))))) ((eq type 'timestamp) (funcall pcase-0)) ((eq type 'planning) (cond ((org-at-timestamp-p 'lax) (funcall pcase-0)) ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook) nil) (t (user-error (substitute-command-keys "`\\[org-ctrl-c-ctrl-c]' can do nothing useful..."))))) ((null type) (cond ((org-at-heading-p) (call-interactively #'org-set-tags-command)) ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook) (funcall pcase-1)) (t (funcall pcase-2)))) ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook) (funcall pcase-1)) (t (funcall pcase-2))) (let* ((pcase-2 #'(lambda nil (user-error (substitute-command-keys "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here")))) (pcase-1 #'(lambda nil)) (pcase-0 #'(lambda nil (org-timestamp-change 0 'day)))) (cond ((memq type '(src-block inline-src-block)) (if org-babel-no-eval-on-ctrl-c-ctrl-c nil (org-babel-eval-wipe-error-buffer) (org-babel-execute-src-block current-prefix-arg (org-babel-get-src-block-info nil context)))) ((org-match-line "[ \11]*$") (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook) (user-error (substitute-command-keys "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here")))) ((memq type '(inline-babel-call babel-call)) (let ((info (org-babel-lob-get-info context))) (if info (progn (org-babel-execute-src-block nil info))))) ((eq type 'clock) (org-clock-update-time-maybe)) ((eq type 'dynamic-block) (save-excursion (goto-char (org-element-property :post-affiliated context)) (org-update-dblock))) ((eq type 'footnote-definition) (goto-char (org-element-property :post-affiliated context)) (call-interactively 'org-footnote-action)) ((eq type 'footnote-reference) (call-interactively #'org-footnote-action)) ((memq type '(inlinetask headline)) (save-excursion (goto-char (org-element-property :begin context)) (call-interactively #'org-set-tags-command))) ((eq type 'item) (let* ((box (org-element-property :checkbox context)) (struct (org-element-property :structure context)) (old-struct (copy-tree struct)) (parents (org-list-parents-alist struct)) (prevs (org-list-prevs-alist struct)) (orderedp (org-not-nil (org-entry-get nil "ORDERED")))) (org-list-set-checkbox (org-element-property :begin context) struct (cond ((equal arg ...) "[-]") ((and ... ...) "[ ]") ((or ... ...) nil) ((eq box ...) "[ ]") (t "[X]"))) (org-list-struct-fix-ind struct parents 2) (org-list-struct-fix-item-end struct) (org-list-struct-fix-bul struct prevs) (org-list-struct-fix-ind struct parents) (let ((block-item (org-list-struct-fix-box struct parents prevs orderedp))) (if (and box (equal struct old-struct)) (if (equal arg ...) (message "Checkboxes already reset") (user-error "Cannot toggle this checkbox: %s" ...)) (org-list-struct-apply-struct struct old-struct) (org-update-checkbox-count-maybe)) (if block-item (progn (message "Checkboxes were removed due to empty box at line %..." ...)))))) ((eq type 'keyword) (let ((org-inhibit-startup-visibility-stuff t) (org-startup-align-all-tables nil)) (if (boundp 'org-table-coordinate-overlays) (progn (mapc #'delete-overlay org-table-coordinate-overlays) (setq org-table-coordinate-overlays nil))) (let* ((--invisible-types '...) (--markers\? 'use-markers) (--data (mapcar ... ...))) (unwind-protect (progn (org-mode-restart)) (save-excursion (save-restriction ... ... ...))))) (message "Local setup has been refreshed")) ((eq type 'plain-list) (let* ((begin (org-element-property :contents-begin context)) (struct (org-element-property :structure context)) (old-struct (copy-tree struct)) (first-box (save-excursion (goto-char begin) (looking-at org-list-full-item-re) (match-string-no-properties 3))) (new-box (cond (... "[-]") (... ...) (... "[ ]") (t "[X]")))) (cond (arg (let (...) (while --dolist-tail-- ...))) ((and first-box (eq ... begin)) (org-list-set-checkbox begin struct new-box))) (if (equal (org-list-write-struct struct (org-list-parents-alist struct) old-struct) old-struct) (progn (message "Cannot update this checkbox"))) (org-update-checkbox-count-maybe))) ((memq type '(node-property property-drawer)) (call-interactively #'org-property-action)) ((eq type 'radio-target) (call-interactively #'org-update-radio-target-regexp)) ((eq type 'statistics-cookie) (call-interactively #'org-update-statistics-cookies)) ((memq type '(table-row table-cell table)) (if (eq (org-element-property :type context) 'table\.el) (message "%s" (substitute-command-keys "\\<org-mode-map>Use `\\[org-edit-special]' to edit t...")) (if (or (eq type 'table) (and (eq type ...) (= ... ...))) (save-excursion (if (org-at-TBLFM-p) (progn ... ...) (goto-char ...) (org-call-with-arg ... ...) (orgtbl-send-table ...))) (org-table-maybe-eval-formula) (cond (arg (call-interactively ...)) ((org-table-maybe-recalculate-line)) (t (org-table-align)))))) ((eq type 'timestamp) (funcall pcase-0)) ((eq type 'planning) (cond ((org-at-timestamp-p 'lax) (funcall pcase-0)) ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook) nil) (t (user-error (substitute-command-keys "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))) ((null type) (cond ((org-at-heading-p) (call-interactively #'org-set-tags-command)) ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook) (funcall pcase-1)) (t (funcall pcase-2)))) ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook) (funcall pcase-1)) (t (funcall pcase-2)))) (let* ((context (org-element-lineage (org-element-context) '(babel-call clock dynamic-block footnote-definition footnote-reference inline-babel-call inline-src-block inlinetask item keyword node-property paragraph plain-list planning property-drawer radio-target src-block statistics-cookie table table-cell table-row timestamp) t)) (type (org-element-type context))) (if (eq type 'paragraph) (progn (let ((parent (org-element-property :parent context))) (if (and (eq (org-element-type parent) 'item) (= (line-beginning-position) (org-element-property :begin parent))) (progn (setq context parent) (setq type 'item)))))) (let* ((pcase-2 #'(lambda nil (user-error (substitute-command-keys "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here")))) (pcase-1 #'(lambda nil)) (pcase-0 #'(lambda nil (org-timestamp-change 0 'day)))) (cond ((memq type '(src-block inline-src-block)) (if org-babel-no-eval-on-ctrl-c-ctrl-c nil (org-babel-eval-wipe-error-buffer) (org-babel-execute-src-block current-prefix-arg (org-babel-get-src-block-info nil context)))) ((org-match-line "[ \11]*$") (or (run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook) (user-error (substitute-command-keys "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here")))) ((memq type '(inline-babel-call babel-call)) (let ((info (org-babel-lob-get-info context))) (if info (progn (org-babel-execute-src-block nil info))))) ((eq type 'clock) (org-clock-update-time-maybe)) ((eq type 'dynamic-block) (save-excursion (goto-char (org-element-property :post-affiliated context)) (org-update-dblock))) ((eq type 'footnote-definition) (goto-char (org-element-property :post-affiliated context)) (call-interactively 'org-footnote-action)) ((eq type 'footnote-reference) (call-interactively #'org-footnote-action)) ((memq type '(inlinetask headline)) (save-excursion (goto-char (org-element-property :begin context)) (call-interactively #'org-set-tags-command))) ((eq type 'item) (let* ((box (org-element-property :checkbox context)) (struct (org-element-property :structure context)) (old-struct (copy-tree struct)) (parents (org-list-parents-alist struct)) (prevs (org-list-prevs-alist struct)) (orderedp (org-not-nil ...))) (org-list-set-checkbox (org-element-property :begin context) struct (cond (... "[-]") (... "[ ]") (... nil) (... "[ ]") (t "[X]"))) (org-list-struct-fix-ind struct parents 2) (org-list-struct-fix-item-end struct) (org-list-struct-fix-bul struct prevs) (org-list-struct-fix-ind struct parents) (let ((block-item ...)) (if (and box ...) (if ... ... ...) (org-list-struct-apply-struct struct old-struct) (org-update-checkbox-count-maybe)) (if block-item (progn ...))))) ((eq type 'keyword) (let ((org-inhibit-startup-visibility-stuff t) (org-startup-align-all-tables nil)) (if (boundp 'org-table-coordinate-overlays) (progn (mapc ... org-table-coordinate-overlays) (setq org-table-coordinate-overlays nil))) (let* ((--invisible-types ...) (--markers\? ...) (--data ...)) (unwind-protect (progn ...) (save-excursion ...)))) (message "Local setup has been refreshed")) ((eq type 'plain-list) (let* ((begin (org-element-property :contents-begin context)) (struct (org-element-property :structure context)) (old-struct (copy-tree struct)) (first-box (save-excursion ... ... ...)) (new-box (cond ... ... ... ...))) (cond (arg (let ... ...)) ((and first-box ...) (org-list-set-checkbox begin struct new-box))) (if (equal (org-list-write-struct struct ... old-struct) old-struct) (progn (message "Cannot update this checkbox"))) (org-update-checkbox-count-maybe))) ((memq type '(node-property property-drawer)) (call-interactively #'org-property-action)) ((eq type 'radio-target) (call-interactively #'org-update-radio-target-regexp)) ((eq type 'statistics-cookie) (call-interactively #'org-update-statistics-cookies)) ((memq type '(table-row table-cell table)) (if (eq (org-element-property :type context) 'table\.el) (message "%s" (substitute-command-keys "\\<org-mode-map>Use `\\[org-edit-special]' to edit t...")) (if (or (eq type ...) (and ... ...)) (save-excursion (if ... ... ... ... ...)) (org-table-maybe-eval-formula) (cond (arg ...) (...) (t ...))))) ((eq type 'timestamp) (funcall pcase-0)) ((eq type 'planning) (cond ((org-at-timestamp-p 'lax) (funcall pcase-0)) ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook) nil) (t (user-error (substitute-command-keys "`\\[org-ctrl-c-ctrl-c]' can do nothing useful here"))))) ((null type) (cond ((org-at-heading-p) (call-interactively #'org-set-tags-command)) ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook) (funcall pcase-1)) (t (funcall pcase-2)))) ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook) (funcall pcase-1)) (t (funcall pcase-2))))) (cond ((or (and (boundp 'org-clock-overlays) org-clock-overlays) org-occur-highlights) (if (boundp 'org-clock-overlays) (progn (org-clock-remove-overlays))) (org-remove-occur-highlights) (message "Temporary highlights/overlays removed from current...")) ((and (local-variable-p 'org-finish-function) (fboundp org-finish-function)) (funcall org-finish-function)) ((org-babel-hash-at-point)) ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook)) (t (let* ((context (org-element-lineage (org-element-context) '(babel-call clock dynamic-block footnote-definition footnote-reference inline-babel-call inline-src-block inlinetask item keyword node-property paragraph plain-list planning property-drawer radio-target src-block statistics-cookie table table-cell table-row timestamp) t)) (type (org-element-type context))) (if (eq type 'paragraph) (progn (let ((parent ...)) (if (and ... ...) (progn ... ...))))) (let* ((pcase-2 #'(lambda nil ...)) (pcase-1 #'(lambda nil)) (pcase-0 #'(lambda nil ...))) (cond ((memq type '...) (if org-babel-no-eval-on-ctrl-c-ctrl-c nil (org-babel-eval-wipe-error-buffer) (org-babel-execute-src-block current-prefix-arg ...))) ((org-match-line "[ \11]*$") (or (run-hook-with-args-until-success ...) (user-error ...))) ((memq type '...) (let (...) (if info ...))) ((eq type 'clock) (org-clock-update-time-maybe)) ((eq type 'dynamic-block) (save-excursion (goto-char ...) (org-update-dblock))) ((eq type 'footnote-definition) (goto-char (org-element-property :post-affiliated context)) (call-interactively 'org-footnote-action)) ((eq type 'footnote-reference) (call-interactively #'org-footnote-action)) ((memq type '...) (save-excursion (goto-char ...) (call-interactively ...))) ((eq type 'item) (let* (... ... ... ... ... ...) (org-list-set-checkbox ... struct ...) (org-list-struct-fix-ind struct parents 2) (org-list-struct-fix-item-end struct) (org-list-struct-fix-bul struct prevs) (org-list-struct-fix-ind struct parents) (let ... ... ...))) ((eq type 'keyword) (let (... ...) (if ... ...) (let* ... ...)) (message "Local setup has been refreshed")) ((eq type 'plain-list) (let* (... ... ... ... ...) (cond ... ...) (if ... ...) (org-update-checkbox-count-maybe))) ((memq type '...) (call-interactively #'org-property-action)) ((eq type 'radio-target) (call-interactively #'org-update-radio-target-regexp)) ((eq type 'statistics-cookie) (call-interactively #'org-update-statistics-cookies)) ((memq type '...) (if (eq ... ...) (message "%s" ...) (if ... ... ... ...))) ((eq type 'timestamp) (funcall pcase-0)) ((eq type 'planning) (cond (... ...) (... nil) (t ...))) ((null type) (cond (... ...) (... ...) (t ...))) ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-final-hook) (funcall pcase-1)) (t (funcall pcase-2))))))) org-ctrl-c-ctrl-c(nil) funcall-interactively(org-ctrl-c-ctrl-c nil) call-interactively(org-ctrl-c-ctrl-c nil nil) command-execute(org-ctrl-c-ctrl-c) ``` I use 2-factor authentication and hence I have created an app password for mu4e. My ~/.authinfo.gpg for Gmail looks as follows: ``` machine imap.gmail.com login kaletejas2006@gmail.com password <app password> port 993 machine smtp.gmail.com login kaletejas2006@gmail.com password <app password> port 587 ``` My mu4e configuration relevant to Gmail is as follows: ``` (use-package mu4e :load-path "/usr/local/share/emacs/site-lisp/mu/mu4e" :config (setq mu4e-maildir "~/Maildir") ;; in my gmail account, any message marked for deletion will go to trash. (setq mu4e-contexts `( ,(make-mu4e-context :name "Gmail" :match-func (lambda (msg) (when msg (string-prefix-p "/Gmail" (mu4e-message-field msg :maildir)))) :vars '( ;(mu4e-maildir . "~/maildir/gmail") (mu4e-sent-folder . "/Gmail/[Gmail].Sent Mail") (mu4e-drafts-folder . "/Gmail/[Gmail].Drafts") (mu4e-trash-folder . "/Gmail/[Gmail].Trash") (mu4e-refile-folder . "/Gmail/[Gmail].Archive"))) )) ;; allow for updating mail using 'u' in the main view: (setq mu4e-get-mail-command "offlineimap") (require 'smtpmail) ;; now i set a list of (defvar my-mu4e-account-alist '(("Gmail" (mu4e-sent-folder "/Gmail/[Gmail].Sent Mail") (user-mail-address "kaletejas2006@gmail.com") (smtpmail-smtp-user "Tejas Kale") (smtpmail-local-domain "gmail.com") (smtpmail-default-smtp-server "smtp.gmail.com") (smtpmail-smtp-server "smtp.gmail.com") (smtpmail-smtp-service 587) ) )) (defun my-mu4e-set-account () "set the account for composing a message. this function is taken from: https://www.djcbsoftware.nl/code/mu/mu4e/multiple-accounts.html" (let* ((account (if mu4e-compose-parent-message (let ((maildir (mu4e-message-field mu4e-compose-parent-message :maildir))) (string-match "/\\(.*?\\)/" maildir) (match-string 1 maildir)) (completing-read (format "Compose with account: (%s) " (mapconcat #'(lambda (var) (car var)) my-mu4e-account-alist "/")) (mapcar #'(lambda (var) (car var)) my-mu4e-account-alist) nil t nil nil (caar my-mu4e-account-alist)))) (account-vars (cdr (assoc account my-mu4e-account-alist)))) (if account-vars (mapc #'(lambda (var) (set (car var) (cadr var))) account-vars) (error "No email account found")))) (add-hook 'mu4e-compose-pre-hook 'my-mu4e-set-account) ;; save attachments to downloads (setq mu4e-attachment-dir "/Users/tejas/Downloads/") ;; don't keep message buffers around. (setq message-kill-buffer-on-exit t) ;; use helm to select mailboxes. (setq mu4e-completing-read-function 'completing-read) ;; do not ask for context everytime mu4e is opened. (setq mu4e-context-policy 'pick-first) ;; do not ask when quitting. (setq mu4e-confirm-quit nil)) ``` Any idea what I'm doing wrong? Thanks... # Answer I had set the variable `smtpmail-smtp-user` to my name instead of my email ID. Correcting it got rid of the error. Thanks to @rpluim for helping me debug the issue. > 1 votes --- Tags: mu4e, smtpmail ---
thread-57451
https://emacs.stackexchange.com/questions/57451
How to sort in Dired by size and extension and have directories listed first and full date/time details
2020-03-29T21:36:42.367
# Question Title: How to sort in Dired by size and extension and have directories listed first and full date/time details I'm using the excelent `dired-fixups.el` by Dino Chiesa for sorting in Dired by size and extension (see here). The only gotcha is that I'd like to combine it with a fuller date/time description. Also, I'd like to keep directories on top of any Dired buffer, so they don't mix with files. That is, I'd like to combine `dired-fixups.el` with something like this: ``` (setq ls-lisp-format-time-list '("%d.%m.%Y %H:%M:%S" "%d.%m.%Y %H:%M:%S") ls-lisp-use-localized-time-format t) (defun ls-lisp-format-time (file-attr time-index now) "%d.%m.%Y %H:%M:%S" "%d.%m.%Y %H:%M:%S") (if (eq system-type 'gnu/linux) (setq dired-listing-switches "-alDh --group-directories-first --time-style \"+%d-%m-%Y %H:%M:%S\"")) (defun ensure-buffer-name-ends-in-slash () "change buffer name to end with slash" (let ((name (buffer-name))) (if (not (string-match "/$" name)) (rename-buffer (concat name "/") t)))) (add-hook 'dired-mode-hook 'ensure-buffer-name-ends-in-slash) (add-hook 'dired-mode-hook (lambda() (setq truncate-lines 1))) ``` However, I'm not a programmer. I've been tweaking with the code in `dired-fixups.el` to no avail. Probably it is not too difficult... Does anybody know how to get an outcome like the following snapshot, but where I can use all the sorting options in `dired-fixups.el`? ``` /home/dgm/.emacs.d/src: total used in directory 364K available 15413252 drwxr-xr-x 21 dgm dgm 12K 29-03-2020 23:27:42 .. drwxr-xr-x 14 dgm dgm 4.0K 29-03-2020 09:05:19 . drwxr-xr-x 2 dgm dgm 4.0K 05-09-2019 23:58:20 org-recipes drwxr-xr-x 2 dgm dgm 4.0K 09-08-2019 12:52:48 ambrevar drwxr-xr-x 8 dgm dgm 4.0K 21-04-2019 16:10:22 ado-mode-1.15.1.4 drwxr-xr-x 2 dgm dgm 4.0K 07-12-2018 15:57:55 ob-stata drwxr-xr-x 7 dgm dgm 4.0K 06-12-2018 11:26:01 dvc drwxr-xr-x 2 dgm dgm 4.0K 06-12-2018 11:26:01 minimal drwxr-xr-x 2 dgm dgm 4.0K 06-12-2018 11:26:01 org-bullets drwxr-xr-x 2 dgm dgm 4.0K 06-12-2018 11:26:01 smooth-scrolling drwxr-xr-x 2 dgm dgm 4.0K 06-12-2018 11:26:01 stripe-buffer drwxr-xr-x 2 dgm dgm 4.0K 06-12-2018 11:26:01 wc drwxr-xr-x 2 dgm dgm 4.0K 06-12-2018 11:26:01 word-count drwxr-xr-x 2 dgm dgm 4.0K 06-12-2018 11:26:01 bookmarkplus -rw-r--r-- 1 dgm dgm 4.9K 29-03-2020 09:05:19 dired-fixups.el -rw-r--r-- 1 dgm dgm 36K 28-03-2020 22:12:11 dired-sort-menu.el -rw-r--r-- 1 dgm dgm 17K 28-03-2020 22:10:05 dired-sort-menu+.el -rw-r--r-- 1 dgm dgm 4.6K 27-01-2020 19:47:40 org-graph-view.el -rw-r--r-- 1 dgm dgm 38K 27-01-2020 19:47:23 graph.el -rw-r--r-- 1 dgm dgm 6.0K 02-01-2020 16:08:56 window-highlight.el ``` # Answer Library Dired Sort Menu (`dired-sort-menu.el`) lets you do what you ask. From the menu, choose **Dirs First**, and choose any of these menu items at the same time (**Dirs First** is a toggle option): * **Name** * **Time Modified** * **Size** * **Extension** * **Unsorted** * **Time Created** See the screenshot at Dired Sort Menu. (If you don't want to use a *menu* you can use its code to create commands you can bind to keyboard keys.) > 1 votes --- Tags: dired, sorting ---
thread-57454
https://emacs.stackexchange.com/questions/57454
How to prevent a function being called multiple times? (locking)
2020-03-29T23:56:10.473
# Question Title: How to prevent a function being called multiple times? (locking) With a function that calls an asynchronous process, it's possible to call the same function multiple times. What is a reliable way to avoid this that properly handles `quit` and errors being raised? Is there an lisp convention for how to handle this? --- This is an example of locking function, I'm wondering if there are better ways to handle this (existing macros or conventions for e.g). ``` (defvar my-fn--lock nil) (defun my-fn () (unless my-fn--lock (unwind-protect (progn (setq my-fn--lock t) ;; Code body. (do-stuff)) ;; Protected. (setq my-fn--lock nil)))) ``` # Answer > 0 votes I'd probably use a symbol property: `function-put` to add or release the lock on the function symbol, and `function-get` to query the state. Tangentially, `C-h i g (elisp)Mutexes` is a thing; but that's not what you're looking for here. # Answer > 0 votes This can be done using `unwind-protect`, this example shows how it can be done in a macro: ``` ;; Generic macro: (defmacro with-lock-var (var &rest body) "Set VAR to t while in the scope of BODY, use to implement locking." (declare (indent 1)) ` (unwind-protect (progn (setq ,var t) ,@body) ;; Protected. (setq ,var nil))) ;; Example use: (defvar my-fn--lock nil) (defun my-fn () (unless my-fn--lock (with-lock-var ;; Code body. (do-stuff)))) ``` --- Tags: async ---
thread-36954
https://emacs.stackexchange.com/questions/36954
Using package siunitx when previewing latex fragments in org-mode
2017-11-18T17:43:24.870
# Question Title: Using package siunitx when previewing latex fragments in org-mode I'm using `siunitx` extensively in my lab reports, but I'm unable to get units to appear correctly when previewing latex fragments. This is what the latex fragment looks like: ... with preview applied: The final result is just fine: I've looked at the documentation for `preview-latex`, but it's not clear what I need to add to `preview-default-preamble` or `preview-default-option-list` in order to use a particular latex package in the preview. How do I include packages for use in rendering the preview? In addition, I'm using `\sisetup{per-mode=fraction}` to get the units formatted in the way that I like; is there a way to include this in the list of options? # Answer You can include packages for rendering latex fragments - and all latex export from org I guess - along with their options via `org-latex-packages-alist`. In your case ``` (add-to-list 'org-latex-packages-alist '("per-mode=fraction" "siunitx" t)) ``` This will most likely not help you with the question being 2 1/2 years old, but maybe someone else comes along looking for the same thing :) > 3 votes --- Tags: org-mode, preview-latex ---
thread-57463
https://emacs.stackexchange.com/questions/57463
How to suppress mu4e warning messages?
2020-03-30T13:26:03.100
# Question Title: How to suppress mu4e warning messages? **Q:** how do I suppress `mu4e` warnings about the update process? I am using `mu4e` with `mbsync`. Recently, the latter has started to emit an error/warning message about losing track of messages. When it does so, `mu4e` spits out a warning message: ``` [mu4e] Update process returned with non-zero exit code ``` That's normally fine, but it is annoying, especially as it spams my echo area every time `mu4e` checks my email. Until I figure out what the problem is with `mbsync`, I have to tolerate the "losing track of messages" warning it gives. However, I'd like to know how to tell `mu4e` to shut up about it so it doesn't continue to alert me about non-zero exit codes. How do I do that? # Answer Much simpler than I realized: just set `mu4e-index-update-error-warning` to `nil`. The docstring: ``` Whether to display warnings during the retrieval process. This depends on the ‘mu4e-get-mail-command’ exit code. ``` Here's a little function to toggle the setting: ``` (defun mu4e-toggle-ignore-warnings () "Toggle whether or not mu4e reports update process warnings to echo area." (interactive) (setq mu4e-index-update-error-warning (not mu4e-index-update-error-warning))) ``` > 3 votes --- Tags: mu4e, email, warning ---
thread-12300
https://emacs.stackexchange.com/questions/12300
Setting include file paths for clang in .dir-locals.el
2015-05-10T21:52:14.033
# Question Title: Setting include file paths for clang in .dir-locals.el I'm working on an embedded system and need to limit clang to only the header files of the embedded system code while I'm editing its code. I need to make the following work: 1. Make sure that company-mode with the clang backend only includes stuff inside the header files of the embedded system. 2. Make sure that C-c C-e includes system headers of the embedded platform In other words, if a file contains `#include <stdio.h>` it should look into the folder `/home/<user>/src/include` and not e.g. `/usr/include`. I assume this should be done by making sure that `-nobuiltininc` is always passed to clang together with the appropriate `-I/home/<user>/src/include`. My question is what should I put in the `.dir-locals.el` file under `~/src`? # Answer I had the same problem, this seemed to do the trick ``` ((c-mode . ((company-clang-arguments . (list ("-I/your/absolute/paths/here/")))))) ``` on `.dir-locals.el` > 1 votes --- Tags: company-mode ---
thread-57464
https://emacs.stackexchange.com/questions/57464
Is it possible to selectively disable syntax highlighting rules?
2020-03-30T13:27:34.233
# Question Title: Is it possible to selectively disable syntax highlighting rules? The context : * GNU Emacs 26.1 * working on Debian 10.3 * currently editing YAML files (Ansible code) Here's how my code looks like : As you can see, the syntax highlighting is puzzled by the odd number of single quotes in `it's difficult...` and applies color to everything until it reaches the next single "single quote". Is there a way to instruct the syntax highlighting logic that "single single quotes" are ok in lines starting with `- name:` and refrain it from colouring everything until the next "single single quote" ? **NB :** this is a purely cosmetics question, everything works fine, no error message, just the display pictured above. **EDIT:** Thank you @Lindydancer and @wasamasa. The solutions / workarounds you suggest are way beyond my Emacs skills, so I think I'll have to live with this cosmetic issue. Not able to pick my "favorite" answer either, sorry. BTW, while working on different topics, I tried Spacemacs and realized it can highlight my YAML snippet without being puzzled by the single quotes : May this help those investigating, and others searching for an alternative. # Answer > 0 votes Ideally you'd try fixing the highlighting in the mode itself. I am the maintainer of yaml-mode, if you have ideas how to do this without ending up writing a YAML parser, please let me know on its issue tracker. One possible workaround for programming languages with comment syntax is to put a comment starter on the affected line, then a string terminator and optionally a comment ender (or none if it's a line comment). That way syntax highlighting doesn't bleed beyond that line. I'm afraid you can't do that with YAML though. # Answer > 0 votes It's possible to override the syntax table for specific syntactic constructs by overriding the variable `syntax-propertize-function`. It should be bound to a function that set the `syntax-table` text property on the part of the buffer where the default syntax table should be overridden. One way to do this it to use the support function `syntax-propertize-rules`. In the following example `<` and `>` around words are treated as parentheses. (It's part of the test suite of my faceup package.) ``` (defvar faceup-test-mode-syntax-table (make-syntax-table) "Syntax table for `faceup-test-mode'.") (defvar faceup-test-font-lock-keywords '(("\\_<WARNING\\_>" (0 (progn (add-text-properties (match-beginning 0) (match-end 0) '(help-echo "Baloon tip: Fly smoothly!")) font-lock-warning-face)))) "Highlight rules for `faceup-test-mode'.") (defun faceup-test-syntax-propertize (start end) (goto-char start) (funcall (syntax-propertize-rules ("\\(<\\)\\([^<>\n]*\\)\\(>\\)" (1 "() ") (3 ")( "))) start end)) (defmacro faceup-test-define-prog-mode (mode name &rest args) "Define a major mode for a programming language. If `prog-mode' is defined, inherit from it." (declare (indent defun)) `(define-derived-mode ,mode ,(and (fboundp 'prog-mode) 'prog-mode) ,name ,@args)) (faceup-test-define-prog-mode faceup-test-mode "faceup-test" "Dummy major mode for testing `faceup', a test system for font-lock." (set (make-local-variable 'syntax-propertize-function) #'faceup-test-syntax-propertize) (setq font-lock-defaults '(faceup-test-font-lock-keywords nil))) ``` --- Tags: syntax-highlighting, quote ---
thread-57472
https://emacs.stackexchange.com/questions/57472
How to obtain file path from LISP file loaded by command line?
2020-03-30T18:50:45.423
# Question Title: How to obtain file path from LISP file loaded by command line? Given you started Emacs passing a LISP file through command line: ``` emacs --load .custom.d/init.el ``` how it could be possible to dynamically obtain `custom.el` directory location? Since the default `init.el` is not used, `buffer-file-name` is not a possible solution: ``` (file-name-directory (or load-file-name (buffer-file-name))) ``` I have also tried to eval `default-directory` as follows: ``` cd /tmp/username mkdir custom.d touch custom.d/init.el emacs -nw --load custom.d/init.el --eval "(print default-directory)" ``` however the directory from where emacs was invoked (i.e. `/tmp/username` in) is shown, not the `init.el` folder. # Answer Emacs manual node Action Arguments tells you this about command-line option `--load`: > Load a Lisp library named `FILE` with the function `load`. If `FILE` is not an absolute file name, Emacs first *looks for it in the current directory, then in the directories listed in `load-path`* (\*note Lisp Libraries::). > > *Warning:* If previous command-line arguments have visited files, the current directory is the directory of the last file visited. This tells you that at the time that command-line switch is interpreted, the value of `default-directory` (the "current directory") is the directory checked first. And that starts out as the directory in which you launched Emacs, which is likely the current working directory in which you issued the command to launch it. See also variable `invocation-directory`. To get the value dynamically, just evaluate variable `default-directory` at the beginning of your `custom-file`. Or if you need to get the value outside of Emacs, and if loading your `custom-file` does not change the `default-directory` then you can use switch `-f` just after that `--load custom-file`, to invoke a function that prints the value of `default-directory`. > 1 votes --- Tags: init-file, directory ---
thread-57447
https://emacs.stackexchange.com/questions/57447
Org-babel loads different Python
2020-03-29T17:33:35.437
# Question Title: Org-babel loads different Python I'm very new to org-mode and org-babel. After installing oh-my-zsh I noticed that I cannot run the source code in my org files like before. My code is like follows ``` #+BEGIN_SRC python :results output :session # some computations #+END_SRC ``` I noticed something went wrong because after I ran the source block code, the output showed the prompt you get when you call python through the terminal, given below. ``` #+RESULTS: #+begin_example WARNING: Python 2.7 is not recommended. This version is included in macOS for compatibility with legacy software. Future versions of macOS will not include Python 2.7. Instead, it is recommended that you transition to using 'python3' from within Terminal. Python 2.7.16 (default, Feb 29 2020, 01:55:37) [GCC 4.2.1 Compatible Apple LLVM 11.0.3 (clang-1103.0.29.20) (-macos10.15-objc- on darwin Type "help", "copyright", "credits" or "license" for more information. 'org_babel_python_eoe' 16286.2414 #+end_example ``` (I also got some other problem which got fixed after adding `(setq python-shell-completion-native-enable nil)` to the init.el file if that helps) When everything was working just fine, I just got ``` #+RESULTS: 16286.2414 ``` Which is what I want. I then added the following to my init.el file ``` (setq org-babel-python-command "python3") ``` After which it is loading an installation of Python 3 BUT it doesn't have the packages I previously made use of in the same file (numpy, scipy etc) when everything was working fine Any ideas on how to fix this? I also noticed when I run the code block for the first time, the Python and Clang version come up like when you open the Python REPL on the terminal, this did not happen before as well. Which Python installation does org-babel even load? Uninstall oh-my-zsh didnt work # Answer So the problem was specific to GUI emacs, the PATH variable was not the same as what I have in my .zshrc (the PATH is correct when you open emacs via the shell, the PATH can be checked by M-x getenv) So I used this neat package which loads the correct PATH even I open the GUI emacs now. > 0 votes # Answer It sounds like there might be a few things going on here, but the first thing that comes to mind is if your Emacs knows what path to find your executables here, namely `python3`? It may not be added to your PATH explicitly. Are you using a package like https://github.com/purcell/exec-path-from-shell or setting this manually in your Emacs config? Two other things that could be conflating this issue is: * The Python code that's being executed in the source block * oh-my-zsh's PATH or the PATH of bash, if that's what you're falling back to now (?) > 0 votes # Answer If preferred, you can set you PATH correctly without an additional package using: ``` ;; Use the PYTHONPATH defined in whatever shell config: zshrc or bashrc or wherever (setenv "PYTHONPATH" (shell-command-to-string "$SHELL --login -c 'echo -n $PYTHONPATH'")) ``` > 0 votes --- Tags: org-mode, org-babel ---
thread-57477
https://emacs.stackexchange.com/questions/57477
How can I open URLs from within Emacs?
2020-03-30T20:08:25.177
# Question Title: How can I open URLs from within Emacs? When I ran GNOME, I used to be able to click on any link in Emacs, and it would open in my default web browser. But now that I'm using i3, it doesn't work any more, even though I haven't changed any Emacs settings. I don't get any messages or errors—it just does nothing. I also tried `M-x browse-url-at-point`, while on a URL, but that doesn't work, either. As far as I can tell, I have the appropriate settings: `browse-url-browser-function` is `browse-url-generic`, and `browse-url-generic-program` is set to `qutebrowser`, my default browser. So why can't I open URLs? And/or how can I debug this? # Answer This took me forever to figure out, but it turns out Spacemacs had cached a bunch of environment variables. One in particular, $XAUTHORITY, was making it so that `qutebrowser` wouldn't start. Manually editing my spacemacs env file and updating that variable fixed the problem. > 2 votes --- Tags: debugging, web-browser, url ---
thread-57481
https://emacs.stackexchange.com/questions/57481
Every letter in emacs is now separated by a space
2020-03-31T03:13:49.957
# Question Title: Every letter in emacs is now separated by a space Today when I opened Emacs (26.3) for the first time since updating Linux (Arch) I was greeted with a wide (two spaces) cursor, and every letter on the screen separated by a space, like this: ``` F i l e l o c a t i o n s ``` This is true everywhere: in the text, in the mode line, in the linum numbers to the left on the window. The only place it isn't true is in a read-only buffer like the initial screen that comes up when you start Emacs. I don't see any errors in the \*Messages\* buffer. I don't know where to start. Any ideas? # Answer It's an issue with how Xft calculates the width of characters, which is triggered by Inconsolata. See Inconsolata for full details. > 4 votes # Answer You may need to specify the XFT spacing explicitly. The font may not be declared mono-spaced, the solution is to force this through the font specifier. * `Fira Code-13:spacing=90` (dual spacing) * `Fira Code-13:spacing=100` (mono spacing) > 1 votes --- Tags: fonts ---
thread-57471
https://emacs.stackexchange.com/questions/57471
disable company-mode when editing C++ over tramp
2020-03-30T18:41:50.140
# Question Title: disable company-mode when editing C++ over tramp When editing Python files over tramp, elpy continues to use my local python distribution for completion, which is fine by be for what I need. However, when editing C++, it uses `clang` output from the remote host and the round-trip is constantly hanging my editor. Right now I just manually disable company-mode, but I am wondering how I can include a hook that says, when editing C++ over tramp, turn off `company-mode`. Any ideas? # Answer > 4 votes Completely untested: ``` (add-hook 'c++-mode-hook (lambda () (when (file-remote-p default-directory) (company-mode -1)))) ``` --- Tags: tramp, company-mode ---
thread-56410
https://emacs.stackexchange.com/questions/56410
org odt export -- edit Text Body style font
2020-03-27T21:09:06.447
# Question Title: org odt export -- edit Text Body style font i run emacs 26.1, org 9.3. i would like to modify the font used by the Text Body style when i export a file to odt. i followed the instructions at https://orgmode.org/manual/Applying-custom-styles.html#Applying-custom-styles. but when i go looking in the 'stylist', there is only a single Org style there and not one that i'm interested in using or modifying. & if i use a custom org export styles file, all of my other formatting in org is lost in the export process. most of my text just uses the Text Body style. is there an easy way to copy/edit the OrgOdtStyles.xml do change the font of that style? or equally of 'Default Style'? # Answer > i would like to modify the font used by the Text Body style when i export a file to odt. The easiest way for you to achieve what you want is to use the ***FORK*** of the ODT exporter (See Project Summary (OpenDocument Text Exporter for Emacs’ Org Mode)). The *keyword* you are looking for is`#+ODT_EXTRA_STYLES` (See Applying custom styles (OpenDocument Text Exporter for Emacs’ Org Mode)) Here is a sample snippet and the corresponding output. In the snippet, 1. The `Text Body` style is modified to use `Courier New` 2. The `OrgVerse` paragaph style--this is the style used by the *verse block*--is configured to use `Comic Sans` ``` #+odt_preferred_output_format: pdf #+odt_extra_styles: <style:style style:name="Text_20_body" style:display-name="Text body" style:family="paragraph" style:parent-style-name="Standard" style:class="text"> #+odt_extra_styles: <style:paragraph-properties fo:margin-top="0cm" fo:margin-bottom="0.212cm" loext:contextual-spacing="false"> #+odt_extra_styles: <style:tab-stops/> #+odt_extra_styles: </style:paragraph-properties> #+odt_extra_styles: <style:text-properties style:font-name="Courier New1" fo:font-family="&apos;Courier New&apos;" style:font-style-name="Regular" style:font-family-generic="modern" style:font-pitch="fixed" fo:font-size="16pt"/> #+odt_extra_styles: </style:style> #+odt_extra_styles: <style:style style:name="OrgVerse" style:family="paragraph" style:parent-style-name="Preformatted_20_Text" style:master-page-name=""> #+odt_extra_styles: <loext:graphic-properties draw:fill="none" draw:fill-color="#729fcf"/> #+odt_extra_styles: <style:paragraph-properties fo:margin-left="0.499cm" fo:margin-right="0cm" fo:text-indent="0cm" style:auto-text-indent="false" style:page-number="auto" fo:background-color="transparent" fo:padding="0cm" fo:border="none" style:shadow="none"> #+odt_extra_styles: <style:tab-stops> #+odt_extra_styles: <style:tab-stop style:position="1.0cm"/> #+odt_extra_styles: </style:tab-stops> #+odt_extra_styles: </style:paragraph-properties> #+odt_extra_styles: <style:text-properties style:font-name="Comic Sans MS" fo:font-family="&apos;Comic Sans MS&apos;" style:font-style-name="Regular" style:font-family-generic="script" style:font-pitch="variable" fo:font-size="12pt"/> #+odt_extra_styles: </style:style> This is a poem by Rudyard Kipling #+begin_verse If you can keep your head when all about you Are losing theirs and blaming it on you, If you can trust yourself when all men doubt you, But make allowance for their doubting too; If you can wait and not be tired by waiting, Or being lied about, don’t deal in lies, Or being hated, don’t give way to hating, And yet don’t look too good, nor talk too wise: #+end_verse ``` *(In the above verse block, the indented line uses a SINGLE TAB)* --- Btw, as you might have guessed, the user manual for the ***FORKED VERSION*** of ODT exporter is Top (OpenDocument Text Exporter for Emacs’ Org Mode). > 1 votes # Answer > i would like to modify the font used by the Text Body style when i export a file to odt. Instead of modifying the 'Text Body`style, you are likely to have better results if you modify the paragraph style`Default Style\`. * **Note 1**: that what LibreOffice UI labels as `Default Style` actually corresponds to `Standard` in `styles.xml`, and what it labels as `Text Body` actually corresponds to `Text_20_body` in `styles.xml`. * **Note 2**: The `Text Body` style (and all other paragraph styles) inherit from `Standard` style. > 0 votes --- Tags: org-mode, org-export, odt ---
thread-57491
https://emacs.stackexchange.com/questions/57491
Print matching strings line by line
2020-03-31T12:18:28.417
# Question Title: Print matching strings line by line I was trying to use this code shared by @JordonBiondo over here to collect regex matches in a list. ``` (defun matches-in-buffer (regexp &optional buffer) "return a list of matches of REGEXP in BUFFER or the current buffer if not given." (let ((matches)) (save-match-data (save-excursion (with-current-buffer (or buffer (current-buffer)) (save-restriction (widen) (goto-char 1) (while (search-forward-regexp regexp nil t 1) (push (match-string 0) matches))))) matches))) ``` When we run this code: ``` (insert (print (format "%s" (matches-in-buffer "//select/items/[A-Z_0-9]+" (current-buffer))))) ``` We get a nice list of matching items printed out below, as expected. ``` (//select/items/1_7YBDN5YT //select/items/1_8JVACVAG //select/items/1_8JVACVAG) ``` # Question My question is: How do we print out the elements on the list line by line? ``` //select/items/1_7YBDN5YT //select/items/1_8JVACVAG //select/items/1_8JVACVAG ``` Running the code below results in an error. ``` (setq rslt (format "%s" (matches-in-buffer "//select/items/[A-Z_0-9]+" (current-buffer)))) (defun print-elements-of-list (list) "Print each element of LIST on a line of its own." (while list (print (car list)) (setq list (cdr list)))) (print-elements-of-list rslt) ``` # Error: ``` (wrong-type-argument listp "(//select/items/1_7YBDN5YT //select/items/1_8JVACVAG //select/items/1_8JVACVAG)") ``` --- # Sample Data: ``` * Lorem Ipsum Lorem ipsum dolor sit amet, consectetur adipiscing elit. [fn:105d40022edca6cb:This is a footnote with citations. [[//select/items/1_8JVACVAG][Author,Title]],pp.502-2. ]Phasellus vitae luctus risus, nec porta est. Nunc ut turpis quam. Phasellus at porta justo, non pellentesque ante. Mauris volutpat egestas tristique. Proin rhoncus diam at diam tincidunt vestibulum. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Quisque gravida gravida lorem, ullamcorper porta sem auctor non. Nullam tincidunt maximus rutrum. Fusce nec ante leo. Suspendisse vel rutrum lorem. Donec vitae mattis orci. Curabitur sed orci fringilla, molestie ex non, venenatis urna. Ut sollicitudin leo eu dolor tincidunt porta. Nullam neque justo, ullamcorper quis ligula fringilla, mollis faucibus elit. Duis at eleifend ligula. [fn:9fc32cc5941ded6: This is another. [[//select/items/1_8JVACVAG][Title]],pp,502-2. ]Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce vel consectetur ligula, eu tempus ipsum. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Mauris et mauris eget odio eleifend lobortis. Nunc non est eros. Morbi scelerisque non libero sit amet egestas. Nullam finibus sagittis dictum. Quisque feugiat, nisl ullamcorper pharetra pretium, quam metus consectetur sapien, in imperdiet purus velit ut nulla. Aenean pretium, ex vitae convallis facilisis, diam eros posuere est, ac consectetur nulla nunc vitae augue. Nullam hendrerit ligula ac nisi malesuada tempor. Duis sit amet leo ultricies, ullamcorper purus eget, rhoncus ipsum. In hac habitasse platea dictumst. Sed quis sem urna. Maecenas orci magna, eleifend at libero vel, accumsan ornare ipsum. Suspendisse potenti. In tincidunt, neque ut bibendum molestie, augue sapien semper libero, sed pretium odio felis nec mauris. [fn:1d9d0df7958ea454:For a different book see [[//select/items/1_7YBDN5YT][Author, Title]]. ] Aenean nisi quam, semper vel mi nec, hendrerit convallis turpis. Maecenas at rutrum orci, quis ultrices felis. Fusce quis mi dapibus nibh elementum condimentum et id dolor. Sed varius neque eu ante vestibulum dapibus. Sed ac pharetra turpis, a laoreet nunc. Proin dignissim magna nec magna venenatis, eget placerat nunc mollis. Praesent pretium, erat id imperdiet fringilla, nibh dui luctus ligula, at aliquam metus neque quis ex. ``` # Answer Here's a breakdown of what went wrong: * You have a function, `matches-in-buffer` which returns a list of strings * You turn the result of using that function into a string using `(format "%s" ...)` and assign it to a variable * You try to iterate over that variable as if it were a list (it isn't) * Emacs tells you that it expected a list, not a string: `(wrong-type-argument listp ...)` The correct thing to do here is to take that list and iterate over it. Luckily there's a built-in macro for that, `dolist`. Here's a cleaned up version of your code: ``` (let ((matches (matches-in-buffer "//select/items/[A-Z_0-9]+"))) (dolist (match matches) (message "%s" match))) ``` One more sidenote: You almost never use functions like `print`, `prin1`, `princ` and `terpri` in code unless you need precise control over where to print. The `with-output-to-string` and `with-output-to-temp-buffer` macros are examples of that technique. In all other cases it's easier to use `message` (display formatted result followed by newline in echo area and messages buffer) and `format` (return a formatted string) directly. > 2 votes --- Tags: list ---
thread-57496
https://emacs.stackexchange.com/questions/57496
Converting init file on Mac/Linux to Windows
2020-03-31T17:33:04.900
# Question Title: Converting init file on Mac/Linux to Windows I use a package called `Deft` that needs a directory to store and load files. To define this directory on Mac or GNU/Linux I use the following expression: ``` (setq deft-directory "~/Dropbox/org") ``` When using `Emacs` on Windows shall I change every `~` to `C:\\Users\\sbac` and every `/` to `\\` as in: ``` (setq deft-directory "C:\\Users\\sbac\\Dropbox\\org") ``` # Answer > 3 votes No. Emacs on MS Windows uses the GNU/Unix conventions of `~` and `/` as directory separator, just fine. See also the Emacs manual, nodes Minibuffer File and Windows HOME. (And on MS Windows be sure to define environment variable `HOME`.) --- Tags: init-file, microsoft-windows, directories, filenames ---
thread-57460
https://emacs.stackexchange.com/questions/57460
Check whether a string is a date in a specific format, e.g. "%Y-%m-%d"
2020-03-30T12:36:46.100
# Question Title: Check whether a string is a date in a specific format, e.g. "%Y-%m-%d" I have a string and would like to check whether it contains a date in a given date format, e.g. "%Y-%m-%d", with format as for `format-time-string`. This is for a package and users can configure the date format freely. So I cannot just hard-code a regular expression. # Answer It seems `format-time-string` uses the same format as strftime(3), and strptime(3) is the reverse of strftime(3), so I wrote an Emacs dynamic module just for strptime(3), for example, ``` (strptime "2020-04-01" "%Y-%m-%d") ;; => (0 0 0 1 4 2020 3 nil 0) ``` The result is `(SEC MINUTE HOUR DAY MONTH YEAR DOW DST UTCOFF)`, you can feed it to `encode-time` ``` (apply #'encode-time (strptime "2020-04-01" "%Y-%m-%d")) ;; => (24195 55680) (format-time-string "%Y-%m-%d" (apply #'encode-time (strptime "2020-04-01" "%Y-%m-%d"))) ;; => "2020-04-01" ``` > 3 votes # Answer A combination of `regexp-quote` and `format-spec` should help in your case. Especially, `format-spec` works with format specifiers of the format sequences consisting of one `%` character and one letter. ``` (defun my-format-spec-to-regexp (format) "Convert FORMAT with placeholders %Y, %m, and %d into a regexp." (format-spec (regexp-quote format) '((?Y . "\\(?:[0-9][0-9]\\)\\{1,2\\}") (?m . "\\(?:1[012]\\|0?[1-9]\\)") (?d . "\\(?:0?[1-9]\\|[12][0-9]\\|3[01]\\)")))) ;; Some test: (insert (prin1-to-string (my-format-spec-to-regexp "%Y\\%m\\%d"))) "\\(?:[0-9][0-9]\\)\\{1,2\\}\\\\\\(?:1[012]\\|0?[1-9]\\)\\\\\\(?:0?[1-9]\\|[12][0-9]\\|3[01]\\)" ``` > 2 votes --- Tags: regular-expressions, time-date, parsing, format-time-string ---
thread-57475
https://emacs.stackexchange.com/questions/57475
What is evil-mode's equivalent to vim insert-mode completion?
2020-03-30T19:56:09.713
# Question Title: What is evil-mode's equivalent to vim insert-mode completion? I'm making the move from Vim to Emacs + Evil-mode. I miss Vim's CTRL-X in insert mode to trigger completion of either words, tags, file paths, etc. I wonder if evil-mode has something similar? Thanks # Answer I use, > 0 votes --- Tags: evil ---
thread-57507
https://emacs.stackexchange.com/questions/57507
send email gnus error - need fully-qualified hostname
2020-04-01T09:46:42.720
# Question Title: send email gnus error - need fully-qualified hostname I'm trying to send email from emacs-gnus. But still get this error: > smtpmail-send-it: Sending failed: 504 5.5.2 : Helo command rejected: need fully-qualified hostname My config is: ``` (setq send-mail-function 'smtpmail-send-it message-send-mail-function 'smtpmail-send-it smtpmail-smtp-server "smtp.zenbox.pl" smtpmail-smtp-service 587) ``` Then I found info that it can be configuration with postfix https://serverfault.com/questions/357990/smtp-auth-with-postfix-reject-with-error-need-fully-qualified-hostname but I haven't found this line "reject\_non\_fqdn\_hostname" in my configuration. Is it problem with emacs conf or with postfix? How I can fix it? # Answer > 1 votes "smtp.zenbox.pl" wants the machine from which you're sending mail to have a fully qualified domain name. You can arrange for that either by making sure that `(system-name)` returns one, or by setting `smtpmail-local-domain` to an appropriate value. --- Tags: email, smtpmail ---
thread-57495
https://emacs.stackexchange.com/questions/57495
how to show local file listings with C-x C-f through IVY when starting in a remote file buffer
2020-03-31T17:22:52.210
# Question Title: how to show local file listings with C-x C-f through IVY when starting in a remote file buffer System: Mac OSX catalina Emacs: 26.3 I use Ivy as my completion framework. Problem is when I am editing a remote buffer over ssh using Tramp, and then I want to look at a file on my local machine. If I do C-x C-f, I get my dialogue, but I can only see options for the remote machine. I can't delete my way out of the tramp listings. So what I do now is I first C-x b into the scratch buffer, then do C-x C-f to see local machine listings. Is there a way to do this in a more natural fashion? For example when attached via tramp, hitting backspace/delete at this point does nothing further: So I go the scratch buffer and then I can get this: # Answer > Is there a way to do this in a more natural fashion? The best way I know is to type `~` twice: the first time will restart completion from your remote home directory, and the second from your local home directory. Quoth `(ivy) Using TRAMP`: ``` ‘/ C-j’ Move to the local root directory. ‘~~’ Move to the local home directory. ``` > 3 votes --- Tags: tramp, find-file, ivy ---
thread-37963
https://emacs.stackexchange.com/questions/37963
Highlight a specific phrase in any emacs buffer, regardless of mode
2018-01-08T16:34:27.970
# Question Title: Highlight a specific phrase in any emacs buffer, regardless of mode I would like to be able to highlight a particular phrase (in my case: `@dakrone`) in every emacs buffer, regardless of the mode (it's fine if it doesn't work in `fundamental-mode`). I know of something like: ``` (defun eos/add-watchwords () "Highlight FIXME and TODO in code" (font-lock-add-keywords nil '(("\\<\\(TODO\\(?:(.*)\\)?:?\\)\\>" 1 'warning prepend) ("\\<\\(FIXME\\(?:(.*)\\)?:?\\)\\>" 1 'error prepend)))) (add-hook 'prog-mode-hook #'eos/add-watchwords) ``` But I haven't gotten something like that to be applied globally instead of having to manually add every mode I want to highlight in. Is there a way do do this? # Answer You can use library `highlight.el` to highlight any text in any buffer, using either text properties or overlays. The highlighting can be independent of font-locking or be controlled by `font-lock-mode`. There are many ways to highlight, and your question is not very specific. See Highlight Library for more information. > 1 votes # Answer You can use `after-change-major-mode-hook` to generalize modes, eg: ``` (defun eos/add-watchwords () "Highlight FIXME and TODO in code" (font-lock-add-keywords nil '(("\\<\\(TODO\\(?:(.*)\\)?:?\\)\\>" 1 'warning prepend) ("\\<\\(FIXME\\(?:(.*)\\)?:?\\)\\>" 1 'error prepend)))) (add-hook 'after-change-major-mode-hook (lambda () (when (derived-mode-p 'prog-mode) (eos/add-watchwords)))) ``` > 0 votes --- Tags: highlighting ---
thread-57519
https://emacs.stackexchange.com/questions/57519
Send multiple emails using Gnus?
2020-04-01T20:08:37.923
# Question Title: Send multiple emails using Gnus? I want to send multiple emails from Gnus. I have over 1000 addresses. I have found a great solution here: https://lists.gnu.org/archive/html/help-gnu-emacs/2014-04/msg00584.html ``` (defun message-send-and-exit-multiple () (interactive) (let ((addresses (split-string (message-fetch-field "All") "," t))) (while addresses (let ((address (car addresses))) (setq addresses (cdr addresses)) (message-remove-header "To") (message-add-header (format "To: %s" address)) (if addresses (message-send) (message-send-and-exit)))))) ``` But Emacs asks me for every email: "Already sent message via mail; resend? (y or n)". So how I can automate the process? Also maybe it would be a good idea to add some sleep between sending emails? Like send 50 emails wait some time then send another? # Answer There is a easy and generic solution. You are actually calling `message-send` which calls `y-or-n-p` to ask you confirm. So you want to automatically answer "Yes" when being asked the question "Already sent message via mail; resend? (y or n)". Here is code, ``` (defvar my-default-yes-no-answer nil "Usage: (setq my-default-answer '(t . \"question1 pattern\"))") (defadvice y-or-n-p (around y-or-n-p-hack activate) (let* ((prompt (car (ad-get-args 0)))) (message "prompt=%s" prompt) (cond ((and my-default-yes-no-answer (consp my-default-yes-no-answer ) (string-match-p (cdr my-default-yes-no-answer) prompt)) (setq ad-return-value (car my-default-yes-no-answer))) (t ad-do-it)))) ``` Usage is simple. Only one liner, `(setq my-default-yes-no-answer '(t . "Already sent message vial mail"))`. > 3 votes # Answer As usual, Gnus has a configuration variable for this: `message-shoot-gnksa-feet`, which you can `M-x customize` to enable the `multiple-copies` feature. > 3 votes --- Tags: gnus, email ---
thread-57528
https://emacs.stackexchange.com/questions/57528
(void-function closure) with Magit
2020-04-02T09:47:31.500
# Question Title: (void-function closure) with Magit I have Magit installed and it used to work fine. However of late, I am running into the following error when I run `magit-status`. ``` Turning on magit-auto-revert-mode...done run-hooks: Symbol’s function definition is void: closure ``` I have tried deleting `elpa` and reinstalling packages from scratch, new versions of Magit has also been released in the meantime, but none of those helped solve the problem. This is what I get with `(setq debug-on-error t)` ``` Debugger entered--Lisp error: (void-function closure) closure() run-hooks(magit-post-display-buffer-hook) magit-display-buffer(#<buffer magit: dotemacs>) magit-setup-buffer-internal(magit-status-mode nil ((magit-buffer-diff-args ("--no-ext-diff")) (magit-buffer-diff-files nil) (magit-buffer-log-args ("-n256" "--decorate")) (magit-buffer-log-files nil))) magit-status-setup-buffer("/home/swarnendu/github/dotemacs/") magit-status(nil ((7 . 4) (("/home/swarnendu/github/dotemacs/" . config) . #<hash-table equal 19/65 0x1558fd48cbb1>) (("/home/swarnendu/github/dotemacs/" . magit-toplevel) . "/home/swarnendu/github/dotemacs/") (("/home/swarnendu/github/dotemacs/" "rev-parse" "--show-cdup") . "") (("/home/swarnendu/github/dotemacs/" "rev-parse" "--show-toplevel") . "/home/swarnendu/github/dotemacs"))) funcall-interactively(magit-status nil ((7 . 4) (("/home/swarnendu/github/dotemacs/" . config) . #<hash-table equal 19/65 0x1558fd48cbb1>) (("/home/swarnendu/github/dotemacs/" . magit-toplevel) . "/home/swarnendu/github/dotemacs/") (("/home/swarnendu/github/dotemacs/" "rev-parse" "--show-cdup") . "") (("/home/swarnendu/github/dotemacs/" "rev-parse" "--show-toplevel") . "/home/swarnendu/github/dotemacs"))) call-interactively(magit-status nil nil) command-execute(magit-status) ``` I am using GNU Emacs 28.0.50 on Ubuntu 18.04. I get the same error with Emacs 26.3. Please let me know how can I resolve this problem, thanks. # Answer > ``` > Debugger entered--Lisp error: (void-function closure) > closure() > run-hooks(magit-post-display-buffer-hook) > > ``` You should see that as a hint as to what to do next: 1. Inspect the value of `magit-post-display-buffer-hook` (using `M-x describe-variable`). 2. Grep you `~/.emacs.d` for `magit-post-display-buffer-hook` (using `M-x rgrep`). Inspect the things that you find. Maybe comment some of them to narrow things down. It's probably not an issue in Magit or we would have heard about it already. It could of course be a very recent regression but is more likely its an issue in some third-party package or even more likely your configuration. Magit provides some tooling to help you figure out whether the issue is in Magit or your own configuration. > 7 votes --- Tags: magit ---
thread-57521
https://emacs.stackexchange.com/questions/57521
How to run custom scheme written in node.js using readline in emacs?
2020-04-01T22:44:43.147
# Question Title: How to run custom scheme written in node.js using readline in emacs? I have Scheme interpreter written in JavaScript that run on top of Node.js the problem is that when I run run-scheme and I enter something it give double echo: ``` lips> 10 10 10 lips> ``` if I run ansi-term it works normally. I have the same issue if I run from `emacs -q`. What may be the problem? My scheme use readline in Node.js, it works fine from real terminal emulator, outside of Emacs. It also works with other scheme interpreter like guile. Anybody have idea what may went wrong, and why I have double echo? # Answer The solution is to use: ``` (setq comint-process-echoes t) ``` I have no idea why guile ignore that option > 0 votes --- Tags: scheme, inferior-lisp ---
thread-57534
https://emacs.stackexchange.com/questions/57534
How do I associate a file such as git's `COMMIT_EDITMSG` with a specific mode?
2020-04-02T11:39:59.360
# Question Title: How do I associate a file such as git's `COMMIT_EDITMSG` with a specific mode? I was doing following solution for markdown files: How do I associate a file extension with a specific mode? ``` (autoload 'markdown-mode "markdown-mode.el" "Major mode for editing Markdown files" t) (setq auto-mode-alist (cons '("\\.md" . markdown-mode) auto-mode-alist)) ``` --- I want to do it same operation for text show up when I want to commit a message for git. When I type `git commit` a `COMMIT_EDITMSG` file shows up which has `Fundamental` mode. Since `COMMIT_EDITMSG` does not have any extention I was not able to match it into markdown-mode as I done for `*.md` files. ``` CRM Buffer Size Mode File . COMMIT_EDITMSG 1259 Fundamental ~/folder/.git/COMMIT_EDITMSG ``` My `.gitconfig` file setup: ``` [core] pager = less -r editor = TERM=xterm-256color emacsclient -t ``` **\[Q\]** Is there a way to open git's `COMMIT_EDITMSG` file in markdown-mode? # Answer > ``` > (setq auto-mode-alist > (cons '("\\.md" . markdown-mode) auto-mode-alist)) > > ``` That `\\.md` should be `\\.md\\'` otherwise it'll match every filename containing the sequence `.md` anywhere. (I.e. You already weren't limiting your usage to just matching filename extensions. For instance `/home/alper/.mdir/foo/bar.c` would match your pattern.) --- As you can see, the regexps in `auto-mode-alist` are matched against the entire filename, so you can easily use it to match your `COMMIT_EDITMSG` files. One would normally use `add-to-list` to update the variable: ``` (add-to-list 'auto-mode-alist '("/\\.git/COMMIT_EDITMSG\\'" . markdown-mode)) ``` > 4 votes --- Tags: git, auto-mode-alist ---
thread-57532
https://emacs.stackexchange.com/questions/57532
Need help with JavaScript `{` indentation
2020-04-02T10:41:25.867
# Question Title: Need help with JavaScript `{` indentation I'd need some guidance with adjusting my indentation settings for js-mode (JavaScript). It should basically look like C/C++'s Stroustrup mode. Most of it works as expected, however there are some cases that are not indented as expected: 1. Indentation of multi-line initialiters `{` should start at column of declaration (`var` or `const`): ``` function make_curve (id, color, fillColor) { // correct const en = // correct { // desired { // current, wrong ``` The indentation does match with `const en = {`but I very much prefer to put `{` in an extra line and align `{` with the matching `}`. 2. Opening brace of function body should be aligned with `function` keyword. Example: ``` window.animate = (window.requestAnimationFrame || window.webkitRequestAnimationFrame || ... || function (callback) { // desired { // current wrong ``` My current setup is: ``` (defun my-js-mode-hook () (interactive) (setq tab-width 4 ;; this will make sure TABs are used instead of spaces indent-tabs-mode t) ) (add-hook 'js-mode-hook 'my-js-mode-hook) ``` # Answer Indentation in `js2-mode` is not as customizable as indentation in C mode. As such it's not possible to do this outside of changing the source code for `js2-mode` itself. Like you, I like to have statements inside a function indented relative to the function keyword, so I added this code to the middle of the `js2-bounce-indent` function: ``` ;; Fifth likely point: indent from 'function' keyword on previous line. (setq pos (save-excursion (forward-line -1) (goto-char (point-at-bol)) (when (re-search-forward "\\s-+\\(function\\)\\s-+" (point-at-eol) t) (goto-char (match-beginning 1)) (skip-chars-forward " \t\r\n") (current-column)))) (when pos (cl-incf pos js2-basic-offset) (push pos positions)) ``` You can do something similar for variables. Note especially the "second likely point", which looks for " = " on the previous line to choose an indentation point; adjusting this will let you do what you want. > 1 votes --- Tags: indentation, javascript ---
thread-57542
https://emacs.stackexchange.com/questions/57542
visit new file; enter shell script text; without saving/reloading, fontify the buffer to sh-mode
2020-04-02T20:27:07.220
# Question Title: visit new file; enter shell script text; without saving/reloading, fontify the buffer to sh-mode The title of this question basically says all. Visit a new buffer, let's say 'foo'. Enter shell script text in the new buffer, let's say "`#!/bin/sh`". How can I now set the mode to `sh-mode` and fontify the buffer accordingly, without the save buffer as foo, reload buffer sequence? # Answer > 1 votes You can call `M-x` `sh-mode` directly or, having added that shebang line, you could use `M-x` `normal-mode` which will at that point recognise the shell script content and set `sh-mode`. Being familiar with `M-x` `normal-mode` means you generally don't need to care what the desired mode name is. I use this frequently enough that I have `(defalias 'nm 'normal-mode)` so that I only need `M-x` `nm`. Obviously if the file is named `foo.sh` then Emacs will pick `sh-mode` by default; but if you have global mode `auto-insert-mode` enabled, then creating a new file `foo` in any `bin/` directory will make Emacs prompt you to treat the file as a shell script as well. --- Tags: font-lock ---
thread-34146
https://emacs.stackexchange.com/questions/34146
How to make emacs align and indent a bibtex entry?
2017-07-13T15:04:27.653
# Question Title: How to make emacs align and indent a bibtex entry? I want `bibtex-mode` to align and properly indent fields. I copied a bibtex entry for the following article into Emacs: (Article source here) But, with a simple paste, the alignment is lost in Emacs and the indentation is messed up: The `TAB` key doesn't work to align or indent the entry. How to solve this problem? # Answer When the cursor is somewhere in the entry, run the command `bibtex-fill-entry` (bound to `C-c` `C-q`), which will align the fields. You may also want to set variable `bibtex-align-at-equal-sign` to a non nil value to change the details of alignment. > 16 votes # Answer I had a similar issue, when using the smartparens package in bibtex-mode, where shameful amounts of spaces where inserted. For some reason unknown, bibtex-mode sets the `fill-prefix` variable to a string containing 18 spaces. `(setq fill-prefix nil)` in the `bibtex-mode-hook` fixed the issue in my case. > 3 votes # Answer As mentioned by @JonatanLindén, `fill-prefix` is set to a string containing 18 spaces. This is because `bibtex-clean-entry` is using `fill-prefix` to align continuing text after equal sign. Setting `fill-prefix` to `""` can solve the indentation issue. But to have better alignment when formating entry, you can advice `bibtex-clean-entry` to temporarily set `fill-prefix`. ``` (defun bibtex-mode-setup () (setq-local fill-prefix "")) (add-hook 'bibtex-mode-hook #'bibtex-mode-setup) (defun bibtex-reset-fill-prefix (orig-func &rest args) (let ((fill-prefix (make-string (1+ bibtex-text-indentation) ? ))) (apply orig-func args))) (advice-add 'bibtex-clean-entry :around #'bibtex-reset-fill-prefix) ``` > 3 votes # Answer Usually, you would use the `align-regexp` command (or the `align` command if `bibtex-mode` supported it). But that won't help you with the broken indentation. > 1 votes --- Tags: latex, indentation, align, bibtex ---
thread-57546
https://emacs.stackexchange.com/questions/57546
Abbrevs and UTF-8
2020-04-02T23:36:22.067
# Question Title: Abbrevs and UTF-8 For writing texts on spectroscopy I would like to use abbrevs for common notations for spectral lines. However, the method outlined in the documentation for defining abbrevs with `C-x a l` or `C-x a g` fails on me. For example, I type `Ly M-x insert-char greek small letter alpha` to get `Lyα` now I hit `C-x a l` and only `α` is displayed in the minibuffer. Why? Is the only solution for me to manually edit the abbrev-table? # Answer > 2 votes Curious. `add-abbrev` scans backward by words using `forward-word` to find out what abbrev to define. I'm not entirely sure why, but even though both "y" and "α" are defined as word characters in the syntax table (at least in the modes I tried it in, ymmv), it still considers there to be a word boundary between them. You can see this if you skip backwards and forwards by words with `M-b` or `M-f`. This is implemented in the `scan_words` function in `syntax.c`, which is sufficiently obscure that I can't tell exactly what the cause of this is; it might even be a feature. Anyway, the help for `add-global-abbrev` (and `add-local-abbrev`) says this: ``` The prefix argument specifies the number of words before point that form the expansion; or zero means the region is the expansion. A negative argument means to undefine the specified abbrev. ``` This means that you can specify a prefix argument to tell it how many words to use; `C-u 2 C-x a g` does the trick. Edit: I figured it out. `scan_words` considers two word characters to have a word boundary between them if they are from different scripts. See `word_boundary_p` in category.c, and the variable `char-script-table` which maps characters to script names. I suppose that makes a reasonable rule to use. I suppose you could advise `add-abbrev` so that it uses `forward-word-strictly`, which ignores the script and goes only by the syntax table. Or you could mess around with `find-word-boundary-function-table`, but that seems like a lot of work. --- Tags: abbrev ---
thread-57547
https://emacs.stackexchange.com/questions/57547
How to regex match words? (in multiple languages)
2020-04-03T02:53:18.003
# Question Title: How to regex match words? (in multiple languages) I have a simple regex search which matches `[A-Za-z]`, however I would like it to match other characters which would be used in dictionary words for non-english languages. e.g. `ü`, `Ø`, `ɵ` `人参`, while excluding: * White space. * Punctuation. * Numbers. * Other non-language symbols arrows, characters for drawing diagrams ... etc. How can Emacs regex match against unicode words used in language? I tried `[:word:]` but this matches numbers. # Answer > 1 votes Use the character class `[:alpha:]` E.g. `[[:alpha:]]+` to match one-or-more such characters. `C-h``i``g` `(elisp)Char Classes` says: > ``` > [:alpha:] > > ``` > > This matches any letter. For multibyte characters, it matches characters whose Unicode `general-category` property (\*note Character Properties::) indicates they are alphabetic characters. Whereas you were using: > ``` > [:word:] > > ``` > > This matches any character that has word syntax (\*note Syntax Class Table::). --- Tags: regular-expressions, unicode ---
thread-57523
https://emacs.stackexchange.com/questions/57523
How to highlight a single word in comments, which matches a function call?
2020-04-02T02:43:03.593
# Question Title: How to highlight a single word in comments, which matches a function call? While there are packages that handle this, I would like to highlight a single word in source code comments, using for example the `warning` face, when a function call returns `t`, using the word as input. How would this be achieved? # Answer > 2 votes First study the doc-string of `font-lock-keywords`. There you have `MATCHER` which can be a regexp but also can be a function that is called with one arg and should act like `re-search-forward`. In the `MATCHER` function you have the chance to consider other conditions, as that one that your function that should return t. You can use the form `(MATCHER . (SUBEXP FACENAME OVERRIDE))` for the keyword entry and append it to `font-lock-keywords` with the help of `font-lock-add-keywords`. Example: ``` (defun my-highlight-fixme-p (s) "Example predicate function for `my-highlight-mode'." (string-equal s "FIXME")) (defvar my-highlight-regexp (regexp-opt '("FIXME" "TODO") 'words) "Regexp matching in comments.") (defvar my-highlight-predicate #'my-highlight-fixme-p "Register your predicate function here.") (defvar my-highlight-keywords '((my-highlight-highlight . ( 0 ;; subexpression 'warning ;; facename t ;; override syntactic fontification for comments ))) "One of the possible constructs of keywords in `font-lock-keywords'. The HIGHLIGHT element of the keyword should always be `my-highlight-highlight'.") (defun my-highlight-highlight (bound) "MATCHER for the font lock keyword in `my-highlight-mode'." (let (found) (while (and (setq found (re-search-forward my-highlight-regexp bound t)) (null (and (nth 4 (syntax-ppss)) ;; inside comment? (funcall my-highlight-predicate (match-string 0)))))) found)) (define-minor-mode my-highlight-mode "Highlight matches for `my-highlight-regexp' in comments if they also fulfill `my-highlight-predicate'." :lighter " κ" (if my-highlight-mode (font-lock-add-keywords nil my-highlight-keywords 'append) ;; append and override (font-lock-remove-keywords nil my-highlight-keywords)) (font-lock-flush)) ``` --- Tags: font-lock, comment ---
thread-57551
https://emacs.stackexchange.com/questions/57551
file-local-variables not evaluated on load
2020-04-03T07:38:39.913
# Question Title: file-local-variables not evaluated on load Here is my example mwe-1.tex local variable declaration from within this file is ``` %%% Local Variables: %%% mode: latex %%% mode: orgtbl %%% End: ``` when I execute this command in a shell: ``` emacs -q --eval '(load-library "org-table")' mwe-1.tex ``` The actual mode is latex but not orgtbl. Did I miss something ? # Answer Using `mode` for anything but the major mode is deprecated. To enable minor modes, use `eval`: ``` %%% Local Variables: %%% mode: latex %%% eval: (orgtbl-mode 1) %%% End: ``` See `(info "(emacs) Specifying File Variables")`. > 3 votes --- Tags: file-local-variables, orgtbl ---
thread-57560
https://emacs.stackexchange.com/questions/57560
Org (and org-capture) uses English for calendar dates, no matter what I do
2020-04-03T12:54:44.510
# Question Title: Org (and org-capture) uses English for calendar dates, no matter what I do **The problem:** When I use org-capture to write on my journal, it writes the month as April and the day as Friday. But everything in my system is in Portuguese, so it should be "abril" for the month, and "sexta-feira" for the day. Org-agenda uses the names in Portuguese correctly. format-time-string outputs in English instead of Portuguese. Worse, this behavior started yesterday when I rebooted my computer. It did work fine before. **My OS:** Windows 10, with the latest updates. **What I've tried:** 1) Setting calendar variables like calendar-day-name-array and others have already been set and the buffer re-evaluated. I checked that those are the current values of those variables. NOTHING CHANGED. 2) I looked at Display months/days or timestamps in another language than English and checked if I had any LANG environment variable on Windows. I do not. NOTHING TO DO HERE. 3) I called set-language-environment and set it to Brazilian Portuguese. It was already portuguese before, but I did it again. NOTHING CHANGED. I don't know what else to try. Tips? **Edit:** The weird thing is that THIS is what shows up when I use org-capture with a datetree: The calendar itself is in portuguese, but the bottom line shows the date I picked in English. And it's captured in English. # Answer The culprit is the calendar code: it needs special treatment. See Calendar Localization in the Emacs Wiki. You need to add this code ``` (setq calendar-week-start-day 0 calendar-day-name-array ["Domingo" "Segunda" "Terça" "Quarta" "Quinta" "Sexta" "Sábado"] calendar-month-name-array ["Janeiro" "Fevereiro" "Março" "Abril" "Maio" "Junho" "Julho" "Agosto" "Setembro" "Outubro" "Novembro" "Dezembro"]) ``` to your init file *before* calendar and org-mode are loaded. EDIT: as the OP points out, he's already done the above. I also missed another point which may be crucial: `format-time-string` formats things in English. I have two machines (both running Fedora 31): in one, I had to do two things to get it to do what the OP wanted: * set the LANG environment variable and the LC\_ALL environment variable (I set them to `fr_FR.utf8` but Portuguese should not be any different). * I started emacs with the above initialization and a minimal org file: `emacs -q -l calendar.fr.el -l minimal.org.el` to make sure that no other initialization was messing things up With that, I can get dates in French in my org files. But when I tried the same thing on my other machine, and tried to set `LC_ALL=fr_FR.utf8` I got an error that the locale is not supported and trying to start emacs as above gave me this error: > (process:214680): Gtk-WARNING \**: 12:35:52.749: Locale not supported by C library. Using the fallback 'C' locale. The fallback 'C' locale does everything in English, so maybe that's what's causing `format-time-string` to speak English in the OP's case also. I installed the French langpack on this Fedora system with: ``` dnf install langpacks-fr ``` and now after restarting emacs as above, `format-time-string` does French: ``` (format-time-string "%B %A" (current-time)) "avril samedi" ``` Unfortunately, I don't do Windows, so I cannot help any further. And it may be that the OP's problem is all together different, but the telltale sign of `format-time-string` doing English strongly suggests to me that emacs is falling back to the C locale for some reason. > 1 votes --- Tags: org-mode, microsoft-windows, org-capture, time-date, localization ---
thread-52552
https://emacs.stackexchange.com/questions/52552
Helm source from a hash-table
2019-09-07T21:13:14.707
# Question Title: Helm source from a hash-table I want to build a `helm-source` from a large `hash-table`, is there a smarter/faster way to to this, than the way described below? ``` (setq tab #s(hash-table size 16 test equal data ("asdf" "asdf" "zxcv" "zxcv" "qwert" "qwert"))) (setq l '(("asdf" . "asdf") ("zxcv" . "zxcv") ("qwert" . "qwert"))) ;;; works as expected (helm :sources (helm-build-sync-source "test" :candidates l :fuzzy-match t :action (lambda (candidate) (insert candidate))) :buffer "*helm test*") ;;; does not work (helm :sources (helm-build-sync-source "test" :candidates tab :fuzzy-match t :action (lambda (candidate) (insert candidate))) :buffer "*helm test*") ``` I can build a function that transforms the `hash-table`: ``` (defun hash-to-alist (hash) (let (res) (maphash (lambda (key value) (push `(,key . ,value) res)) hash) res)) (helm :sources (helm-build-sync-source "test" :candidates (hash-to-alist tab) :fuzzy-match t :action (lambda (candidate) (insert candidate))) :buffer "*helm test*") ``` # Answer > 1 votes This is fast enough on my computer: ``` (let ((utf8-hash-table (ucs-names))) (helm :sources (helm-build-sync-source "Unicode character by name" :candidates (hash-table-keys utf8-hash-table) :action (lambda (key) (insert (gethash key utf8-hash-table)))))) ``` --- Tags: helm, hash-tables ---
thread-20025
https://emacs.stackexchange.com/questions/20025
How to open a file with tramp mode when Helm is active?
2016-02-02T23:33:20.793
# Question Title: How to open a file with tramp mode when Helm is active? I recently started using Helm with the configuration below ``` (require 'helm-config) (helm-mode 1) (define-key global-map [remap occur] 'helm-occur) (define-key global-map [remap list-buffers] 'helm-buffers-list) (define-key global-map [remap dabbrev-expand] 'helm-dabbrev) (global-set-key (kbd "M-x") 'helm-M-x) (setq helm-M-x-fuzzy-match t) ``` Today I figured out that Tramp mode doesn't work anymore. When I try to open a file with `C-x` `C-f` and enter `/sudo:root@``TAB` nothing happens. Usually I'd expect that `localhost` is substituted and tramp asks for a password. How can I have a still functional tramp mode plus a working Helm? # Answer > 5 votes the way it works for me is the following: 1. call helm-find-files (usually `C-x``C-f`) 2. write `/scp:` 3. if you have used tramp before you get a list with previous locations which you can select with `C-j` (or type a new remote by hand), pressing now `C-j` a second time or typing a `:` will connect you to the remote server 4. now helm completion on the remote starts, type `/` if you want to be located in the root directory or `~`, if you want to access your home directory # Answer > 1 votes Ok, this is an issue and it's odd Helm doesn't recognize the `/ssh:` as usual Emacs does with Tramp. The way I worked around this is as follows. With Helm you rewrite the `C-x C-f` command to use `helm-find-files`. What I did then is to remap this to another keybinding, one that is not in use. For instance, in my .emacs I did: ``` (global-set-key (kbd "C-x C-h") #'helm-find-files)` ``` I bound `helm-find-files` to `C-x c-h` whenever I want to use the helm files finder. Then with the usual `C-x C-f` I keep connecting with the remote servers or vm's using Tramp. And the nice thing about this is that after you connect with Tramp, then using the `helm-find-files` works ok with the ssh remote connection. Edit (another option): Another option, and it's one I ended up doing is to remap the Emacs Elisp function `find-file`, usually bound to `C-x C-f` to a different keybinding, like this: ``` (global-set-key (kbd "C-x C-h") 'find-file) ``` And then the `C-x C-f` can be used by Helm with helm-find-file. --- Tags: helm, tramp ---
thread-57545
https://emacs.stackexchange.com/questions/57545
Emacs (ipython) inferior python shows strange input numbers
2020-04-02T21:10:51.013
# Question Title: Emacs (ipython) inferior python shows strange input numbers In emacs, I use ipython in the inferior python mode with config: ``` (setq python-shell-interpreter "ipython" python-shell-interpreter-args "--simple-prompt -i") ``` When I edit my .py file, without any input to inferior python, the input number jumps occasionally. I suspect that I send some unintentional inputs to the inferior python. But, I don't know how. It happens quite randomly. # Answer > 0 votes Completion and other features of the python mode require communication between emacs and the ipython process. This communication is achieved by sending code to the interactive `ipython` inferior shell. These are probably the "unintentional inputs" you are sending. --- Tags: python, debugging, ipython ---
thread-57554
https://emacs.stackexchange.com/questions/57554
How to make org file type link search work with numbers?
2020-04-03T08:24:31.853
# Question Title: How to make org file type link search work with numbers? I am trying to using a link to jump to a number in another org file. Searching for keyword numbers works for internal links but does not when searching in a different file. It works with words but not numbers? Why is this and can it be fixed? a.org: ``` abcd or << abcd>> <br> 1234 or even <<1234>> [[1234]] (works) ``` b.org: ``` [[file:./a.org::1234]] (does not work)<br> [[file:./a.org::abcd]] (works) ``` # Answer > 0 votes As I mentioned in my comment, in `[[file:./a.org::1234]]` the number is interpreted as a line number. The only way to turn it into a search string is to include an adjacent non-numeric character. E.g. you can find the string "1234 " (note the space at the end) by using `[[file:./a.org::1234 ]]` (again, note the space at the end). Other than that, Org mode does not provide an escape syntax to let a number be interpreted as a search string. --- Tags: org-mode, org-link ---
thread-57557
https://emacs.stackexchange.com/questions/57557
Modifying task reveal behavior with state changes in org-agenda
2020-04-03T10:00:15.113
# Question Title: Modifying task reveal behavior with state changes in org-agenda In org-mode 9.3.6 and GNU Emacs 26.3, marking a task as done in org-agenda also reveals the task in its buffer. Only the task subheader itself is shown. Here's an example: Before (buffer left, agenda right): After changing task state to DONE in agenda: I'd like to know if this behavior can be modified so that 1) org-mode does not reveal the task in its buffer or 2) org-mode reveals the full parent-child header structure with the task. For example, something like this: Any help is very much appreciated - thanks! # Answer > 1 votes The state change is done by the function `org-agenda-todo` which goes to the buffer and does `(org-show-context 'agenda)`. The doc string for `org-show-context` says: > Make sure point and context are visible. Optional argument KEY, when non-nil, is a symbol. See ‘org-show-context-detail’ for allowed values and how much is to be shown. That leads us to the variable `org-show-context-detail` whose doc string in turn says: ``` org-show-context-detail is a variable defined in ‘org.el’. Its value is ((agenda . local) (bookmark-jump . lineage) (isearch . lineage) (default . ancestors)) You can customize this variable. This variable was introduced, or its default value was changed, in version 26.1 of Emacs. Documentation: Alist between context and visibility span when revealing a location. Some actions may move point into invisible locations. As a consequence, Org always expose a neighborhood around point. How much is shown depends on the initial action, or context. Valid contexts are agenda when exposing an entry from the agenda org-goto when using the command ‘org-goto’ (‘C-c C-j’) occur-tree when using the command ‘org-occur’ (‘C-c / /’) tags-tree when constructing a sparse tree based on tags matches link-search when exposing search matches associated with a link mark-goto when exposing the jump goal of a mark bookmark-jump when exposing a bookmark location isearch when exiting from an incremental search default default for all contexts not set explicitly Allowed visibility spans are minimal show current headline; if point is not on headline, also show entry local show current headline, entry and next headline ancestors show current headline and its direct ancestors; if point is not on headline, also show entry lineage show current headline, its direct ancestors and all their children; if point is not on headline, also show entry and first child tree show current headline, its direct ancestors and all their children; if point is not on headline, also show entry and all children canonical show current headline, its direct ancestors along with their entries and children; if point is not located on the headline, also show current entry and all children As special cases, a nil or t value means show all contexts in ‘minimal’ or ‘canonical’ view, respectively. Some views can make displayed information very compact, but also make it harder to edit the location of the match. In such a case, use the command ‘org-reveal’ (‘C-c C-r’) to show more context. ``` So you can customize the `agenda` pair and make the visibility span of the agenda context something other than `local`. E.g. you can make it `minimal` with something like this: ``` (setq org-show-context-detail (assq-delete-all 'agenda org-show-context-detail)) (add-to-list 'org-show-context-detail '(agenda . minimal)) ``` The listed visibility spans are the only values provided however, so if you don't like any of them, you will have to implement your own. --- Tags: org-mode, org-agenda ---
thread-57520
https://emacs.stackexchange.com/questions/57520
Cannot change cursor type on Windows 10
2020-04-01T21:20:26.493
# Question Title: Cannot change cursor type on Windows 10 I've used emacs on Windows 10 for a year. Recently, my "box" cursor in emacs has become a thin vertical line. I have tried setting the variable "cursor-type", but this no longer seems to have any effect. I have found a short comment that emacs might be detecting assistive technology (like speech recognition) and using a system cursor. See here. I've tried turning off speech recognition in Windows, but that doesn't seem to fix the cursor in emacs. Is there a way to force emacs to use a box cursor instead of a Windows native cursor? (If this is indeed my problem.) # Answer Found the answer on stackoverflow. ``` ;; Disable the system cursor caused by screen reader etc. (setq w32-use-visible-system-caret nil) ``` Helps to know that you need to search for "caret" instead of "cursor". > 3 votes --- Tags: microsoft-windows, cursor ---
thread-53506
https://emacs.stackexchange.com/questions/53506
User-friendly setup of Emacs with GPG, mu4e, and mu4e-send-delay
2019-11-01T15:28:58.873
# Question Title: User-friendly setup of Emacs with GPG, mu4e, and mu4e-send-delay I use `mu4e` and Emacs for email, as well as GPG for credentials and `mu4e-send-delay` for delayed sending. Sometimes the GPG prompt for the encryption password is overwritten by another message in the mini-buffer, and GPG gets the wrong password. The mini-buffer shows `Blocking call to accept-process-output with quit inhibited!` and a pop-up dialog says `Buffer *temp* modified, kill anyway?`. A copy of the message is saved in the home directory with filepath `~/*message*-20191031-185747`. This pop-up appears as many times as the number of emails to send and comes again after the value of `mu4e-send-delay-timer` (60 seconds in my case). The only solution I found (from How to force Emacs or pinentry to forget wrong GPG password?) was to kill the GPG agent with `gpgconf --kill gpg-agent` and restart Emacs. Either of them alone is not enough, I need to do both. Then I get prompted for a GPG password. I am using `GNU Emacs 26.3`, `gpg 2.2.17`, and `macOS Mojave 10.14.6`. How can I set up Emacs, mu4e, and GPG to be more user-friendly, maybe with a pop-up to request the password, and setting GPG to forget wrong passwords? # Answer > 2 votes *This was intended as a comment, but it's too long, hopefully it will give you some hints.* --- Right now I don't have a mac to try OSX configs, but this is what I have now: **pinentry**: ``` pinentry-program /usr/bin/pinentry #pinentry-program /usr/local/MacGPG2/libexec/pinentry-mac.app/Contents/MacOS/pinentry-mac default-cache-ttl 14400 max-cache-ttl 28800 enable-ssh-support ``` Modify your cache times as you prefer. It reprompts if the password is wrong. At least in linux it blocks until you pass a correct password for a number of times out of emacs. Also I have `lock-once` in `.gpg.conf`, which I'm not sure if it was needed for this or for some other stuff. As mu4e is concerned, it doesn't need any configuration beyond the getters/senders helpers, which in my case are `mbsync` and `msmtp`. I have a set of encrypted files with the passwords of each account. **.mstmprc** looks like this: ``` account a : domain from a@domain.net user a@domain.net passwordeval "gpg --quiet --for-your-eyes-only --no-tty --decrypt ~/.pwds/a-domain.gpg" ``` similarly, on **.mbsync.rc**: ``` IMAPAccount domain Host imap.domain.net User a@domain.net PassCmd "gpg --quiet --for-your-eyes-only --no-tty --decrypt ~/.pwds/a-domain.gpg" ``` This decouples the gpg needs from the minibuffer, making the apps to collect their data from the encrypted files allowing the agent to handle the heavy lifting without reprompting while the cache times allows. This also works fine with `.authinfo.gpg` files More than probably you shouldn't have pinentry emacs package active. On the delayed send, cannot tell you, never used it. --- *This is how it works in my machine and laptop, I'm not a security maven, so I'm sure that it could be improved in many ways.* --- Tags: mu4e, gpg, passwords ---
thread-57570
https://emacs.stackexchange.com/questions/57570
Get process id for the Emacs own process
2020-04-04T10:00:39.223
# Question Title: Get process id for the Emacs own process I'm supporting some elisp code that creates a temporary filename using a prefix and the user id. When I develop this, that is not enough since I will be running multiple instances concurrently. So I'm looking for either a function to create a temporary filename which I can control to some extent, or some other component to add to the name. I thought the second option should be straightforward so I looked at `process-id`, but that requires a *process*. (elisp manual: Process Information) So I looked at `get-process` but that requires a *name*, which would also be ambiguous. How do I get the process id for the running Emacs process? EDIT: I solved my problem using `make-temp-name` (yeah, I know I should not use it, but I don't want to change the handling of temporary files at this point). But for my edification, is there a way to get the process id for the Emacs process? # Answer If I do understand correctly you could use `(emacs-pid)` > 5 votes --- Tags: process ---
thread-57568
https://emacs.stackexchange.com/questions/57568
How to enter overlined characters?
2020-04-04T04:03:26.113
# Question Title: How to enter overlined characters? Example: R̅E̅S̅ What I already tried, to no avail: Type `R`, followed by `C-x 8 RET OVERLINE RET` What works but is not nice: Copy the example above and edit it. # Answer > 3 votes You need a combining overline (U+0305), not a “normal” overline U+8254. `C-x 8 RET comb TAB over TAB`. --- Tags: text-editing, unicode ---
thread-41106
https://emacs.stackexchange.com/questions/41106
Ignore both uppercase and lowercase versions of the extensions listed in completion-ignored-extensions
2018-04-19T14:45:31.607
# Question Title: Ignore both uppercase and lowercase versions of the extensions listed in completion-ignored-extensions How can I get Emacs to ignore, say, both `.pdf` and `.PDF` files without listing both `".pdf"` and `".PDF"` in `completion-ignored-extensions`? # Answer > 1 votes Quoth `(emacs) Completion Options`, the paragraph just before `completion-ignored-extensions` is described: ``` When completing file names, case differences are ignored if the variable ‘read-file-name-completion-ignore-case’ is non-‘nil’. The default value is ‘nil’ on systems that have case-sensitive file-names, such as GNU/Linux; it is non-‘nil’ on systems that have case-insensitive file-names, such as Microsoft Windows. When completing buffer names, case differences are ignored if the variable ‘read-buffer-completion-ignore-case’ is non-‘nil’; the default is ‘nil’. ``` If `read-file-name-completion-ignore-case` is `nil`, and `completion-ignored-extensions` includes only `".pdf"`, then `".PDF"` will not be ignored. If you customise `read-file-name-completion-ignore-case` to be non-`nil`, and `completion-ignored-extensions` includes only `".pdf"`, then both `".pdf"` and `".PDF"` will be ignored. If you want general file name completion (e.g. on the non-extension part) to be case-sensitive, and only `completion-ignored-extensions` matching to be case-insensitive, then you need to include both `".pdf"` and `".PDF"` in `completion-ignored-extensions`. # Answer > 0 votes Guessing that you want to include file names that *end in* `.pdf` and `.PDF`, *except* for the two file names that are *just those strings* (nothing before the dot). If you use Icicles then you can do this by setting or binding option `icicle-file-no-match-regexp` to a regexp that excludes matching file-name candidates. You could use `"^[.]pdf$"` (or `"^[.][pP][dD][fF]$"`). --- Tags: files, completion ---
thread-57555
https://emacs.stackexchange.com/questions/57555
can show-trailing-white-space be forced to ignore blank lines
2020-04-03T08:29:36.553
# Question Title: can show-trailing-white-space be forced to ignore blank lines I'm trying to use the flag `show-trailing-white-space` and it usually shows me what I want. I.e., I never want dangling white space at the end of a line containing text. However, between lines of text, I really don't care that there is white space. In fact, the editor enforces white space which is for indentation purposes. In the image shown here, the red mark between `:empty-set` and `:else` is really annoying, but the red marks at the end of the other three lines is helpful. Is there a way to tell `show-trailing-white-space` either to ignore any whitespace starting at the beginning of a line, or perhaps ignore indentation white space, or perhaps ignore whitespace before the first non-white-space-character? # Answer Looks like it's displaying trailing whitespaces and some kind of indenting whitespaces. Look at `whitespace-toggle-options` documentation and this manual page. > 0 votes --- Tags: font-lock, whitespace ---
thread-29499
https://emacs.stackexchange.com/questions/29499
How to toggle neotree in the project directory?
2016-12-22T02:45:13.647
# Question Title: How to toggle neotree in the project directory? There is a nice example of how to open neotree in the project root see: https://www.emacswiki.org/emacs/NeoTree (`find-file-in-project` and `Projectile` sections). However, I'd like to **toggle** neotree, so I can easily open and close it, while having the root set to the project path. Is this possible? # Answer Using a slightly modified version of this post, I managed to get this working: ``` (defun my-neotree-project-dir-toggle () "Open NeoTree using the project root, using projectile, find-file-in-project, or the current buffer directory." (interactive) (require 'neotree) (let* ((filepath (buffer-file-name)) (project-dir (with-demoted-errors "neotree-project-dir-toggle error: %S" (cond ((featurep 'projectile) (projectile-project-root)) ((featurep 'find-file-in-project) (ffip-project-root)) (t ;; Fall back to version control root. (if filepath (vc-call-backend (vc-responsible-backend filepath) 'root filepath) nil))))) (neo-smart-open t)) (if (and (fboundp 'neo-global--window-exists-p) (neo-global--window-exists-p)) (neotree-hide) (neotree-show) (when project-dir (neotree-dir project-dir)) (when filepath (neotree-find filepath))))) ``` Key binding to toggle, example: ``` (define-key global-map (kbd "M-e") 'my-neotree-project-dir-toggle) ``` > 3 votes # Answer It's now 2020 and you can open neotree in the current directory using `neotree-show` instead of `neotree-toggle`. `neotree-show` does exactly what the orignal op required, without the need for the elaborate function. > 3 votes --- Tags: files ---
thread-57577
https://emacs.stackexchange.com/questions/57577
Help with function advice: Unknown add-function location ‘asm-calculate-indentation’
2020-04-04T16:37:21.200
# Question Title: Help with function advice: Unknown add-function location ‘asm-calculate-indentation’ I'm trying to modify how `asm-mode` does its automatic indentation. I thought I would use the following: ``` (defun yasm-calculate-indentation (oldfun) "Add the formatting for a few other keywords I like." (cond ((looking-at-p "section") 0) ; section ((looking-at-p "global") 0) ; global ((looking-at-p "extern") 0) ; extern (:default (oldfun)))) (add-hook 'asm-mode-hook (lambda () (advice-add :around #'asm-calculate-indentation #'yasm-calculate-indentation))) ``` However I'm getting the error: `Unknown add-function location ‘asm-calculate-indentation’` Leaving me rather confused. Am I adding the hook in the wrong location to be able to access that name? I tried adding the advice from the minibuffer when editing an assembly file but it gave me the same error. This is my first time trying to use advice so maybe that's where I'm going wrong... How can I get this to work? # Answer > 3 votes Drew's answer correctly identifies the source of the error message, but there are some additional problems with the code. ``` (defun yasm-calculate-indentation (oldfun) "Add the formatting for a few other keywords I like." (cond ((looking-at-p "section") 0) ; section ((looking-at-p "global") 0) ; global ((looking-at-p "extern") 0) ; extern (:default (oldfun)))) ``` First, `oldfun` is not the name of a function, but rather a local variable whose value is a function, so it must be called as `(funcall oldfun)` instead of `(oldfun)`. ``` (add-hook 'asm-mode-hook (lambda () (advice-add :around #'asm-calculate-indentation #'yasm-calculate-indentation))) ``` Second, there is no need to call `advice-add` from a hook function. You can advise symbols before they are defined as functions; this is called forward advice. Furthermore, `asm-mode-hook` will run every time `asm-mode` is enabled, whereas the advice needs only be registered once. Putting all of this together: ``` (define-advice asm-calculate-indentation (:before-until () my-keywords) "Determine indentation for a few other keywords I like. If this advice returns non-nil, that value is used and `asm-calculate-indentation' is not called; otherwise the value returned by `asm-calculate-indentation' is used." (and (looking-at-p (rx (or "section" "global" "extern"))) 0)) ``` The convenience macro `define-advice` was added in Emacs 25; in Emacs 24 you can emulate it as follows: ``` (defun yasm-calculate-indentation () "Determine indentation for a few other keywords I like. Intended as :before-until advice for `asm-calculate-indentation'." (and (looking-at-p (rx (or "section" "global" "extern"))) 0)) (advice-add 'asm-calculate-indentation :before-until #'yasm-calculate-indentation) ``` # Answer > 2 votes ``` (advice-add :around #'asm-calculate-indentation #'yasm-calculate-indentation) ``` should be ``` (advice-add #'asm-calculate-indentation :around #'yasm-calculate-indentation) ``` `C-h f advice-add` says: ``` advice-add is a compiled Lisp function in `nadvice.el'. (advice-add SYMBOL WHERE FUNCTION &optional PROPS) Like `add-function' but for the function named SYMBOL. ... ``` `C-h f add-function` says: ``` add-function is a Lisp macro in `nadvice.el'. (add-function WHERE PLACE FUNCTION &optional PROPS) ... ``` The error message tells you that `asm-calculate-indentation` is not a known `add-function` location: ``` error: Unknown add-function location ‘asm-calculate-indentation’ ``` The known locations are listed in `C-h f add-function`: `:around` etc. --- Tags: hooks, advice ---
thread-57569
https://emacs.stackexchange.com/questions/57569
Enable ox-hugo Auto-export on saving
2020-04-04T06:17:43.513
# Question Title: Enable ox-hugo Auto-export on saving I am trying to establish an ox-hugo workflow using the Auto-saving feature described in the official website. However, when trying to enable it using the following snippet: ``` (("content-org/" . ((org-mode . ((eval . (org-hugo-auto-export-mode))))))) ``` I receive the following error: > Debugger entered--Lisp error: (invalid-function ("content-org/" (org-mode (eval org-hugo-auto-export-mode)))) (("content-org/" (org-mode (eval org-hugo-auto-export-mode)))) Any ideas why the official doc instructions would not be valid? # Answer You must put this snippet in file called `.dir-locals.el` in the project root. This file is read by emacs with special evaluation rules in place which differ from those with which `.emacs` and most other `.el` files are read. > 2 votes --- Tags: org-mode, hugo ---
thread-57586
https://emacs.stackexchange.com/questions/57586
Replace a filename in init.el using sed from bash script
2020-04-05T00:26:32.087
# Question Title: Replace a filename in init.el using sed from bash script So I have different customized themes. Different customized themes are written to a separate custom `.el` files and get called in the main `init.el` file. For example: ``` (setq custom-file "~/.emacs.d/myCustomSettings/customDarkLaptop.el") ``` will call the `customDarkLaptop.el`, where all of my customized variables like font size, comment color..etc. Suppose I want to switch to a different customized themes, I then go to `init.el` and change this ``` (setq custom-file "~/.emacs.d/myCustomSettings/customLight.el") ``` which will then load the `customLight.el` file. I would like to write a script to automate this process, user just need to enter either the part after `custom` to the desire theme. For example: * enter `Dark` will automatically have `customDark.el` Replacing text from a file can be easily be done with the `sed` command, i.e. ``` sed -i -e s/oldtext/newtext/g <enter file name here> ``` However, I am not sure how to incorporate this efficiently into my `init.el` file. What I want is something like this: * create a string variable in `init.el`: `themeName = "Dark"` * Append it to my `set-q` command file path like this: `(setq custom-file "~/.emacs.d/myCustomSettings/custom<INSERT THE VARIABLE themeName HERE>.el")` My `sed` script will just replace one thing, the variable `themeName` in `init.el`. How do you do this in elisp? # Answer > 2 votes It's not clear to me just what you need/want, or why you're using `sed` and `bash` (what you're using them for). Maybe what you really want is to just have loading your init file prompt you for which theme you want. If so, you can do that by putting code in your init file similar to this: ``` (setq custom-file (format "~/.emacs.d/myCustomSettings/custom%s" (read-string "Theme/style: " nil nil "Light"))) (load-file custom-file)) ``` If you want to be able to (re)load a given custom file anytime you can put such code in a command. That code assumes you want to set `custom-file` to the given value, rather than just load the file. You would do that in order for Emacs to thereafter update the right `custom-file` if you use Customize etc. If you don't care about that then you can just use something like this: ``` (load-file (format "~/.emacs.d/myCustomSettings/custom%s" (read-string "Theme/style: " nil nil "Light"))) ``` --- Tags: init-file, custom ---
thread-57588
https://emacs.stackexchange.com/questions/57588
Does `use-package` reduce startup time? If so, how?
2020-04-05T03:05:45.850
# Question Title: Does `use-package` reduce startup time? If so, how? My understanding of Emacs's package management is that Emacs automatically loads all installed packages. `use-package` itself is a package, which only becomes usable after `(package-initialize)`, at which point all packages have already been loaded. I was just wondering how exactly `use-package` reduce startup time for Emacs? Can anybody explain this at a high level? # Answer It doesn't do anything you couldn't be doing without it; so the answer might well be that it doesn't improve performance at all. It could vary from user to user. It *does* encapsulate some mechanisms (which you might already be using) for making good use of autoloading and deferred evaluation of code, in order to *avoid loading libraries any earlier than necessary*; so users who weren't doing that might well see noticeable improvements to their start-up times after converting their configs to `use-package`. > My understanding of Emacs's package management is that Emacs automatically loads all installed packages. Only the autoloads file for each package is `load`ed during package initialisation. If you were to `load` each individual elisp library provided by each package, that would take a lot longer. > 1 votes --- Tags: use-package, start-up ---
thread-57592
https://emacs.stackexchange.com/questions/57592
How can I get the effect of buffer-local symbol plist property values?
2020-04-05T07:02:13.347
# Question Title: How can I get the effect of buffer-local symbol plist property values? Does Emacs have a way to set buffer-local properties on symbols? It's well-known that there are buffer-local variables. But a property belongs to a symbol, not to a variable. Hence, if I have understood correctly, making a variable `foo` buffer-local has no effect on on properties set on the symbol `foo`. (Note: In Emacs Lisp, the term *property* can refer to anything having to do with property lists (plists), including their uses for text properties, symbol properties, and other things. This question is about symbol properties specifically.) # Answer I am certain that the answer is no, and that variables are the only kind of buffer-local bindings provided by elisp. (I'm sure one of the elisp language maintainers will correct me if I'm wrong about this.) There are a handful of *other* kinds of "local" values (such as frame parameters, and terminal-local variables), and other things may also be associated with buffers (such as processes), but the feature you're asking for isn't provided. However, FWIW, `(get SYM PROP)` is a PLACE form (or "generalised variable"), such that you can provide a dynamic binding for it. E.g.: ``` (require 'cl-lib) (put 'foo 'bar 'normal) (list (cl-letf (((get 'foo 'bar) 'overridden)) (get 'foo 'bar)) (get 'foo 'bar)) => (overridden normal) ``` As such, if you have control over the elisp for which you felt you needed this feature, then you may be able to adapt it to this approach (although without knowing your actual goal, it's impossible to say for sure). > 5 votes --- Tags: variables, symbols, buffer-local, property-lists ---
thread-57576
https://emacs.stackexchange.com/questions/57576
Alt-Shift-Left and -Right (M-S-<left>/<right>) do not work in emacs on Raspberry Pi (org-shiftmetaleft / org-shiftmetaright)
2020-04-04T14:39:03.000
# Question Title: Alt-Shift-Left and -Right (M-S-<left>/<right>) do not work in emacs on Raspberry Pi (org-shiftmetaleft / org-shiftmetaright) I am on a Raspberry Pi with Raspbian and any shortcut with Alt-Shift-arrow has no effect in emacs org-mode. I discovered it while trying to use org-shiftmetaleft and org-shiftmetaright. This is my `lsb_release -a` ``` No LSB modules are available. Distributor ID: Raspbian Description: Raspbian GNU/Linux 10 (buster) Release: 10 Codename: buster ``` and `M-x emacs-version` is ``` GNU Emacs 26.1 (build 2, arm-unknown-linux-gnueabihf, GTK+ Version 3.24.5) of 2019-09-23, modified by Debian ``` I tried to use `xev`to figure out, what happens when I press the keys but I don't understand what the output means: ``` FocusOut event, serial 48, synthetic NO, window 0x2c00001,mode NotifyGrab, detail NotifyAncestor FocusIn event, serial 48, synthetic NO, window 0x2c00001,mode NotifyUngrab, detail NotifyAncestor KeymapNotify event, serial 48, synthetic NO, window 0x0,keys: 2 0 0 0 0 0 4 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ``` I appreciate any ideas how to tackle this. # Answer Apparently it's not an emacs problem. It seems the openbox window manager is intercepting the shortcut. To disable this behavior I had to copy the system-shortcut-file, rename it and comment the S-A-arrow-shortcuts out. ``` mkdir ~/.config/openbox cp /etc/xdg/openbox/LXDE/rc.xml ~/.config/openpox/lxde-pi-rc.xml ``` Then `nano ~/.config/openpox/lxde-pi-rc.xml` and comment the following lines out with `<!-- ... -->` or delete them. ``` <!-- <keybind key="S-A-Left"> <action name="SendToDesktop"><to>left</to><wrap>no</wrap></action> </keybind> <keybind key="S-A-Right"> <action name="SendToDesktop"><to>right</to><wrap>no</wrap></action> </keybind> <keybind key="S-A-Up"> <action name="SendToDesktop"><to>up</to><wrap>no</wrap></action> </keybind> <keybind key="S-A-Down"> <action name="SendToDesktop"><to>down</to><wrap>no</wrap></action> </keybind> --> ``` After a system restart, M-S-right and M-S-left worked as expected in emacs org-mode. :-) > 0 votes --- Tags: org-mode, emacsclient ---
thread-57596
https://emacs.stackexchange.com/questions/57596
Getting started `use-package` question
2020-04-05T09:04:10.983
# Question Title: Getting started `use-package` question I was reading the `use-package` documentation, which says, "Here is the simplest use-package declaration:" ``` ;; This is only needed once, near the top of the file (eval-when-compile ;; Following line is not needed if use-package.el is in ~/.emacs.d (add-to-list 'load-path "<path where use-package is installed>") (require 'use-package)) (use-package foo) ``` As an Emacs beginner, I have a few questions about this part if I may. 1. Do I need `(package-initialize)` before these lines? It seems to me that without doing that, the `use-package` macro wouldn't be available. 2. I do not need the 4th line in the above snippet, right? As I have installed `use-package` from MELPA Stable, and the package is installed to the default location `~/.emacs.d/elpa/use-package-2.4`. 3. In this example, is `(use-package foo)` equivalent to `(require 'foo)`? # Answer > 15 votes > 1. Do I need `(package-initialize)` before these lines? If your version of Emacs (`M-x``emacs-version``RET`) is older than 27, and you are using the built-in package manager, then you indeed need to call `(package-initialize)` before you can call on any installed packages, such as `use-package`. From Emacs 27 onwards, `package-initialize` will effectively be called before `user-init-file` is loaded. This can be disabled by setting `package-enable-at-startup` to `nil` in the new `early-init-file`. > It seems to me that without doing that, the `use-package` macro wouldn't be available. It depends. The example is written from the perspective of someone who doesn't use the built-in package manager (e.g. the author of `use-package`), and who manually installs packages so that they can be found by Emacs on their `load-path`. This is what `package-install` and `package-initialize` effectively automate for the user. > 2. I do not need the 4th line in the above snippet, right? As I have installed `use-package` from MELPA Stable, and the package is installed to the default location `~/.emacs.d/elpa/use-package-2.4`. Correct. If you install packages using the package manager and call `package-initialize`, then you do not need to manually edit your `load-path`. > 3. In this example, is `(use-package foo)` equivalent to `(require 'foo)`? Let's find out: with point after the closing parenthesis of `(use-package foo)`, call `M-x``pp-macroexpand-last-sexp``RET`. This will print what `use-package` is actually doing under the bonnet to the buffer `*Pp Macroexpand Output*`: ``` (progn (defvar use-package--warning0 (lambda (keyword err) (let ((msg (format "%s/%s: %s" 'foo keyword (error-message-string err)))) (display-warning 'use-package msg :error)))) (condition-case-unless-debug err (unless (require 'foo nil t) (display-warning 'use-package (format "Cannot load %s" 'foo) :error)) (error (funcall use-package--warning0 :catch err)))) ``` Stripping away all of the error reporting, we're left with: ``` (require 'foo nil t) ``` Which is like `(require 'foo)`, but doesn't signal an error if the named feature `foo` can't be found. --- Tags: package, use-package ---
thread-57575
https://emacs.stackexchange.com/questions/57575
Any equivalent of R+ESS for python?
2020-04-04T14:38:50.593
# Question Title: Any equivalent of R+ESS for python? I do a lot of R coding on Emacs – on Windows – using the wonderful ESS package. What I particularly like is that I can: * start an R session, and then send lines or regions of the script I'm working on to that session * send the whole script to be evaluated * switch back and forth between R session and script editing ESS also provides some documentation when inputting an R function (for example which arguments it requires) and some autocompletion features. But these are less important to me than the above three. *Can you suggest an Emacs mode for working with python scripts, similar to ESS in the three points above?* (I have an Anaconda Windows installation.) I've explored elpy, ~~but it's extremely slow (often completely freezes Emacs) and doesn't seem to have the possibility of sending lines to the interpreter.~~ It has the right functionality but can be too slow in its base configuration. Probably it tries to do too much; for example it gives information about imported packages but frankly I don't need that. No project-management help is needed either. I've heard of anaconda mode but it doesn't seem to provide interaction with an interpreter: only autocompletion and documentation. I've also heard of python mode but haven't understood if it provides interaction with a python interpreter. Finally, Jedi is a total mystery, and EIN doesn't seem to be designed for scripting. It seems that with python part of the problem is also the choice of interpreter, if I understood correctly. In this case, which python interpreter would be best, to achieve something similar to the R+ESS seamless interaction? Most related questions on StackExchange are 4–6 years old; presumably a lot has changed in the meantime. Thank you all. # Answer > 3 votes I managed to set up something close to my requirements above. Here it is, for people who may have my same needs. Let me stress that such requirements are very subjective, so the set-up below is not meant as a fit-all solution. It specifically addresses Windows users. The setup involves the python distribution and Emacs's configuration: ## Python distribution I had to use the one from python.org. I installed several packages through `pip` – including `numpy`, `jupyter`, `panda` – and the install went smoothly. I see most people recommend the Anaconda distribution, which is surely great owing to the possibility of working in "conda environments". But this possibility turned out to be a problem for me. From what I saw, even if you only have the `base` conda environment, *you still need to activate it* before using any python executables. This means that Emacs cannot simply call, say, `ipython.exe`: it needs first to call `activate base` and *then* to call `ipython`. Alternatively you could open a command or cygwin prompt, `activate base` there, and then start Emacs from that prompt. This would be a hassle for me. I don't need conda environments, so I can do fine with the python.org distribution. (If you do need conda environments, maybe the remarks above may help you). ## Emacs configuration In my question (now edited) I was too harsh regarding `elpy`. It works smoothly if you unselect some of its modules. So if you, like me, don't need elpy's full documentation and project-management capabilities, I recommend the following settings, through Emacs's `customize-apropos`: * *Elpy Modules*: I activate only: + Inline code completion + Show function signatures + Show the virtualenv in the mode line * *elpy-project-root* is set to `nil`. This is useful if you have many files and subdirectories, which otherwise elpy would scan, making Emacs freeze from time to time. * *Elpy Shell Starting Directory* is set to `Current directory`, for the same reason. * *Elpy Shell Use Project Root* is toggled `off`, for the same reason. You can also specify the location of your python distribution in the customizable variable *Python Shell Exec Path*. In my case I set it to `c:/ProgramData/Python38-32/` and `c:/ProgramData/Python38-32/Scripts/`. This way python doesn't need to be put in you PATH environment variable. Finally, for the python shell interpreter I customized * *Python Shell Interpreter* to `ipython` and * *Python Shell Interpreter Args* to `-i --simple-prompt` according to elpy's documentation. I tried the other alternatives given there too, and all worked fine. I can also see plots made with `matplotlib`. Elpy provides several commands for sending lines, regions, or the whole buffer to the interpreter. See the documentation here. I hope this set-up will help other Emacs-python-Windows users. If you know of workarounds to Anaconda's "activate" problem, please do share them in the comments! --- Tags: python, ess, elpy, r, anaconda-mode ---
thread-57600
https://emacs.stackexchange.com/questions/57600
org agenda: only show immediate subtask for task with dependencies
2020-04-05T13:20:49.703
# Question Title: org agenda: only show immediate subtask for task with dependencies Let's say I have a project with three subtasks: ``` * TODO project [1/3] :PROPERTIES: :ORDERED: t :END: ** DONE subtask1 CLOSED: [2020-04-05 Sun 15:12] ** TODO subtask2 ** TODO subtask3 ``` I have set the first item to DONE, and the progress entry shows \[1/3\] so it seems like org mode recognized the dependency. In the agenda todo view I now only want to see subtask2, because I cannot start working on subtask3 before it's done. However I now see both subtask2 and subtask3 in agenda todo. Is it possible to configure so that I only see subtask2 there? # Answer Setting these variables made it work: ``` (setq org-agenda-dim-blocked-tasks 'invisible) (setq org-enforce-todo-dependencies t) ``` > 2 votes --- Tags: org-mode, org-agenda ---
thread-57603
https://emacs.stackexchange.com/questions/57603
How to always display inline images by default? Existing solutions don't seem to take effect
2020-04-05T16:57:21.437
# Question Title: How to always display inline images by default? Existing solutions don't seem to take effect I'm trying to always display inline images in my org mode files. I have images inserted as `[[my-image.png]]`. What I have already tried: 1. Set startup variable (see this answer: ``` (setq org-startup-with-inline-images t) ``` 2. Set inline config (see this comment): ``` (setq org-display-inline-images t) (setq org-redisplay-inline-images t) (setq org-startup-with-inline-images "inlineimages") ``` None of the two above (or any combination of) work. When I open the file, I always see the text `[[my-image.png]]` instead of the image. Using `C-c C-x C-v` works but I need to do it every time. I have actually another related problem which is I can't set `visual-line-mode` by default at startup either. Maybe I have an issue with my org-mode settings? I can't figure out what is causing these issues. # Answer 2) is wrong: there is a function `org-display-inline-images` but no variable of that name. Similarly there is a function `org-redisplay-inline-images` but again no variable of that name. If you look at the doc string of `org-display-inline-images`, you will find the conditions that the link has to obey in order to be considered as an inline image: ``` An inline image is a link which follows either of these conventions: 1. Its path is a file with an extension matching return value from `image-file-name-regexp' and it has no contents. 2. Its description consists in a single link of the previous type. In this case, that link must be a well-formed plain or angle link, i.e., it must have an explicit \"file\" type. ``` I will be the first to admit that this description is *NOT* a model of clarity. However, it does point out the fact that there *are* restrictions. The last sentence in particular is telling: `it must have an explicit "file" type`. A little experimentation shows that the following works (assuming there is a file `foo.jpg` containing the image in the same directory as the Org file): ``` #+STARTUP: inlineimages showall * Inline images? [[file:foo.jpg]] ``` If you want to set it permanently, then add ``` (setq org-startup-with-inline-images t) ``` to your init file. > 0 votes --- Tags: org-mode, inline-image ---
thread-57609
https://emacs.stackexchange.com/questions/57609
how to properly move forward to the next sexp
2020-04-05T22:53:32.553
# Question Title: how to properly move forward to the next sexp I was expecting a similar result with the two snippets below, but this is what I've got: ``` (with-temp-buffer (insert "(a)(b)(c)") (goto-char (point-min)) (list (prog1 (cons (point) (cons (sexp-at-point) nil)) (forward-sexp)) (prog1 (cons (point) (cons (sexp-at-point) nil)) (forward-sexp)) (prog1 (cons (point) (cons (sexp-at-point) nil)) (forward-sexp)))) ;; result: ((1 (a)) (4 (b)) (7 (c))) ``` and ``` (with-temp-buffer (insert "(a) (b) (c)") (goto-char (point-min)) (list (prog1 (cons (point) (cons (sexp-at-point) nil)) (forward-sexp)) (prog1 (cons (point) (cons (sexp-at-point) nil)) (forward-sexp)) (prog1 (cons (point) (cons (sexp-at-point) nil)) (forward-sexp)))) ;; result: ((1 (a)) (4 (a)) (8 (b))) ``` I'm using GNU Emacs 26.3. How can I get something similar to `((1 (a)) (? (b)) (? (c)))` on the second snippet? I think there is a proper way to parse things like this. There is a caveat, if it matters, the buffer is and must remain read-only. # Answer Here's what's happening, for the second case. You have this in the buffer, with point at position 1 (beginning of buffer): `(a) (b) (c)` After the first `forward-sexp` point is just after the first right paren (`)`). The next `(sexp-at-point)` returns the first sexp, not the second. Why? Because point is not on the second list (`(b)`), and it is just after the first list (`(a)`). Vanilla Emacs `sexp-at-point` returns the sexp that is just **before** point, if there is not really any sexp at point. (This is a bug, IMHO, but Emacs Dev does not agree with me. The correct behavior is to return `nil`, since there is **no** sexp at point.) --- You can get around this by adding this after each `(forward-sexp)`: `(forward-whitespace 1)`. Or add this instead: `(forward-char)`, if you are sure that a single space separates the sexps. Another thing you can do, if you are sure there is a next sexp, is to go forward 2 sexps and then go back one sexp, to put you at the beginning of the sexp you want. That's in fact more typical. In other words, do this: `(forward-sexp 2) (backward-sexp)` instead of just `(forward-sexp)`. Still another thing you can do, which is more robust, is to use `(next-visible-thing 'sexp)` instead of `(forward-sexp 2) (backward-sexp)`. This function ignores (skips over) comments if option `ignore-comments-flag` is non-`nil`. For this you need library `thing-cmds.el` (it in turn requires library `hide-comnt.el`). See Thing At Point Commands. --- But keep in mind that this kind of thing is in general fragile. If you can be sure of the syntax you're checking, and if it is simple, then this can be good enough. But if the syntax is complex or flexible then this is not really the best approach - this is not really the way to parse. > 6 votes --- Tags: sexp, thing-at-point ---
thread-55053
https://emacs.stackexchange.com/questions/55053
gnutls-negotiate: GnuTLS error: #<process smtpmail<1>>, -15
2020-01-21T23:59:26.280
# Question Title: gnutls-negotiate: GnuTLS error: #<process smtpmail<1>>, -15 Following Sending Mail > Since no credentials are given in this configuration, Emacs will look them up in $(HOME)/.authinfo or $(HOME)/.authinfo.gpg (encrypted). The content of this file should follow this scheme: > > ``` > machine example.org login [your login name] password [your password] > > ``` After finished the configuration and send mail ``` From: abst.proc.do@qq.com (abst.proc.do) To: igabriel_job@163.com Subject: Testing Date: Wed, 22 Jan 2020 07:56:03 +0800 Message-ID: <874kwo2wks.fsf@foxmail.com> --text follows this line-- Testing ``` but got the error: ``` gnutls-negotiate: GnuTLS error: #<process smtpmail<1>>, -15 ``` What's the problem? I did not set gnus. Ubuntu 19.10 emacs 26.3 # Answer > 1 votes Change your port to use 465 instead of 587 ``` (setq message-send-mail-function 'smtpmail-send-it smtpmail-starttls-credentials '(("smtp.gmail.com" 465 nil nil)) smtpmail-default-smtp-server "smtp.gmail.com" smtpmail-smtp-server "smtp.gmail.com" smtpmail-smtp-service 465 smtpmail-debug-info t) ``` --- Tags: email, smtpmail ---
thread-57614
https://emacs.stackexchange.com/questions/57614
Delaying (require ...) for packages that define minor modes
2020-04-06T04:24:51.650
# Question Title: Delaying (require ...) for packages that define minor modes With a package that defines a minor mode which calls an external function at run-time. Is it reasonable to move this: `(require 'my-runtime-dependency)` in the body of the code which enables the minor mode? or should it always be at the top of the file? e.g: ``` (eval-when-compile ;; Quiet warnings. (require 'my-runtime-dependency)) ;; --- Snip (defun my-mode-enable () (require 'my-runtime-dependency) ;; body. ) (defun my-mode-disable () ;; body. ) ;;;###autoload (define-minor-mode my-mode "Toggle `my-mode' in the current buffer." :global nil (cond (my-mode (my-mode-enable)) (t (my-mode-disable)))) ``` # Answer > 1 votes In general it's fine to `require` things inside functions, assuming the function in question is not necessarily going to be used, and the rest of your library doesn't need that dependency. Your example wouldn't necessitate that, though. Based on the autoload cookie, you're intending that your library doesn't get loaded *at all* until `my-mode` is invoked, at which point you're wanting to load the dependency immediately -- so there's no obvious reason why you wouldn't put the `require` at the top level. --- Tags: require ---
thread-10732
https://emacs.stackexchange.com/questions/10732
Start in insert state based on minor mode
2015-04-16T23:53:55.077
# Question Title: Start in insert state based on minor mode I would like the org capture buffer (which IIUC is in org-capture-mode, a minor mode) to start in insert state; It seems that both the evil-insert-state-modes variable and the evil-set-initial-state function operate over major modes (or at least, when I run org-capture after modifying the former or calling the latter, the buffer that opens up does not start in insert state). Does anyone ahve any suggestions? # Answer I had a similar problem as I wanted the annotation contents editor of PDF-tools to start in insert mode. For that case a working solution is to add `pdf-annot-edit-contents-minor-mode` to the list of `evil-insert-state-modes` using `M-x customize-variable`. So just add the correct minor-mode to that list. > 1 votes --- Tags: evil ---
thread-48211
https://emacs.stackexchange.com/questions/48211
Emacs manuals are missing on Debian/Ubuntu
2019-03-07T13:55:12.400
# Question Title: Emacs manuals are missing on Debian/Ubuntu I was expecting the Emacs Lisp Reference Manual at (`C-h i m elisp`). But there was no menu `elisp` or `lisp` there. `C-h v` and `C-h f` work fine for variables or functions though. `C-h i 5` takes me to file permissions. What other binding is standard to find something like this? Is that something that has to be installed? # Answer > 19 votes This is a great question! I've found the directions online to install it by hand unclear and, frankly, a bit of a pain (at least on Debian). # On Debian... Emacs on Debian doesn't come with the *Emacs Lisp Reference Manual* by default. It's kind of silly, but Debian stores it in the non-free repos. Unfortunately, a regular `apt-get install` doesn't *Just Work™*. *Note:* Before proceeding, I assume you've installed Emacs from an official Debian mirror and not compiled from source or installed from some random `.deb` from some random dude on the Internet. To begin, you need to include non-free repos. Do this by appending `non-free`<sup>1</sup> to the end of each entry in `/etc/apt/sources.list`, like ``` deb http://http.us.debian.org/debian stable main non-free ``` You'll need to run `sudo apt-get update` to refresh the package listing. Once you've updated the package listing, install the package `emacs-common-non-dfsg`, like ``` sudo apt-get install emacs-common-non-dfsg ``` Note that older releases of Debian or Ubuntu may not have `emacs-common-non-dfsg`; in those cases, you'll need to add the Emacs version number, i.e., ``` sudo apt-get install emacs25-common-non-dfsg ``` You may need to restart Emacs, or close and restart the Emacs info-browser. # Manually installing... I have not tested this, but it also ought to be possible to just point Emacs to the appropriate file. The source is called `elisp.info` and is available at gnu.org. You'll want the "Info document" link. Check `C-h v Info-default-directory-list` to see where the default `Info` directory is. You ought to be able to either place the `emacs.info` file there or add another directory to the `Info-additional-directory-list` with ``` (add-to-list 'Info-additional-directory-list "/path/to/my/info") ``` You can read more about the info path on the EmacsWiki. <sup>1</sup> **DISCLAIMER:** Although the Emacs Lisp Reference Manual is libre, including non-free repos does open you to non-free software. <sup>2</sup> This should install the *Emacs Lisp Reference Manual* as `emacs.info.gz` to `/usr/share/info`. Strictly speaking, it seems like `dpkg` is the only dependency, but I couldn't get Emacs to recognize the new contents in `/usr/share/info` without install-info. Maybe someone could clarify why, but that's more a Debian question than an Emacs one... # Answer > 3 votes Ubuntu 1. Download https://www.gnu.org/software/emacs/manual/info/elisp.info.gz to your /usr/share/info directory. 2. From a terminal run update-info-dir command. 3. From emacs C-h i m Elisp (capital E). --- Tags: help, info, ubuntu, debian ---
thread-57623
https://emacs.stackexchange.com/questions/57623
Value of confirm-kill-processes is ignored
2020-04-06T13:50:19.060
# Question Title: Value of confirm-kill-processes is ignored When closing emacs, if I have unsaved buffers its a long process of having to read the questions (at first the logic is 'n' to not save and exit), then it changes to must type `yes`. Ideally there would be no 2nd question where one has to type out `yes` or `no` (it is redundant). So I am trying to make it exit straight away with no questions (less ideal) with these lines in `init.el`: ``` ;; Dont ask to save when quitting (setq confirm-kill-processes nil) ``` But nothing of the behavior has changed. I still get asked all the same questions. If I read the help on the variable I can confirm its value has been changed to `nil`: ``` confirm-kill-processes is a variable defined in ‘files.el’. Its value is nil Original value was t Documentation: Non-nil if Emacs should confirm killing processes on exit. If this variable is nil, the value of ‘process-query-on-exit-flag’ is ignored. Otherwise, if there are processes with a non-nil ‘process-query-on-exit-flag’, Emacs will prompt the user before killing them. You can customize this variable. This variable was introduced, or its default value was changed, in version 26.1 of Emacs. ``` # Answer > 0 votes > if I have unsaved buffers its a long process of having to read the questions... Has nothing to do with: > ``` > confirm-kill-processes is a variable defined in ‘files.el’. > > Non-nil if Emacs should confirm killing processes on exit. > > ``` *Saving buffers* and *killing processes* are two entirely different things, so naturally setting `confirm-kill-processes` to `nil` (or anything else) has no bearing on whether Emacs asks you to save your un-saved work. # Answer > 0 votes ``` ;;; ============================================================================ ;;; QUITTING Emacs (defun _my-quit-emacs () "When exiting Emacs, offer to save unsaved buffers, but then quit without asking if still wish to quit if there are unsaved buffers." (save-some-buffers nil t) (kill-emacs)) (defun save-buffers-kill-terminal (&optional arg) "Override the existing quit Emacs function via C-x C-c." (interactive) (_my-quit-emacs)) (defun save-buffers-kill-emacs (&optional arg) "Override the existing quit Emacs function via the mouse." (interactive) (_my-quit-emacs)) ``` --- Tags: quitting ---
thread-57533
https://emacs.stackexchange.com/questions/57533
How to prevent a file show up for a second when emacsclient starts?
2020-04-02T11:15:14.530
# Question Title: How to prevent a file show up for a second when emacsclient starts? I am using `emacs-daemon`. When every I re-start my daemon and do `C-x C-b` my `Buffer List` seems always full. Later, when I start my `emacsclient` for a seconds(like a fast flash) it shows a file that located on the top of my `Buffer List` and opens the file I want to open. This is little annoying to face with all the time. Example: * I type `emacsclient -t file_a.py`. * For a second or less, buffer called `file_b.py` opens (my lastly opened file). * Than `file_a.py` get opens. ## This always repeats itself even I clean my buffer list doing following and open a new file (since buffer list now contains more than one file): Link: > Edit: There's also the boring old buffer menu you get with `C-x C-b`. In this menu, you can hold d until it marks each buffer for deletion, then press x to commit. Even after doing this after that `IBuffer` shows up since it is the latest opened buffer. **\[Q\]** Is it possible to prevent 1 second file show up when I start `emacsclient`? If possible I always want to keep my `Buffer List` empty, but not sure would it be a good idea, or some how keep a empty file at the top of the buffer list since it will show a blank frame. This also occurs when I using `emacs -nw` where `scratch*` buffer or latest opened buffer shows up for as seconds as well. # Answer > 0 votes The purpose of using emacs in daemon mode is to access the set of buffers you have opened since emacs started. The behaviour you are requesting is available by NOT running emacs in daemon mode, but just opening a new emacs session for each file. --- Tags: buffers, emacsclient ---
thread-57622
https://emacs.stackexchange.com/questions/57622
Translations of self-inserting keys
2020-04-06T13:17:45.793
# Question Title: Translations of self-inserting keys What exactly determines what is inserted by `self-insert-command`? If I change the input-method to `greek`, `p` will insert `π`, but will still be bound to `self-insert-command`, though it patently does not insert itself. `C-h k p` will say that `p` is still bound to `self-insert-command` and that `p` was translated to `π`, but says nothing more about this translation. Any hints as to how I might have found the answer to this myself (using EMACS) would be appreciated too. PS. I realize the question may not be entirely clear. To put it differently, what is the simplest way to let `a` insert `foo`, while remaining bound to `self-insert-command`? Does this *have to* be done by an input method, or does *translation* indicate something more general? # Answer > 1 votes `M-x describe-input-method greek RET` should tell you a lot already. Also the contents of lisp/leim/quail/greek.el are pretty self-explanatory (which is not the case for all input methods). See Input Methods and Reading Input for more details (both of which are available in Emacs Info). --- Tags: input-method, self-insert-command ---
thread-57621
https://emacs.stackexchange.com/questions/57621
Mailing lists with org-contact
2020-04-06T13:10:21.573
# Question Title: Mailing lists with org-contact Premise: I am not an expert of emacs-lisp, unfortunately. I am handling all my emails with mu4e, and since it integrates well with org-contacts, I use the latter to handle my address book. However, I have not yet figured out how to handle mailing lists with org-contacts. I know I can use aliases : ``` (setq mail-personal-alias-file (expand-file-name "/path/email-aliases.txt")) ``` but I find this rather unsatisfying. Is there any other way to specify a mailing list in org-contacts to use in mu4e? I am pretty sure someone has already cooked up a solution for himself, but could not find anything on the web. # Answer Finally, I did it myself, and I am posting it here to help people looking for a solution to my problem. I decided to use tags to specify a group of emails, thus the same contact can be part of several groups simply by tagging it several times. Here is an example of contacts file: ``` * John Doe :MailingListA:GroupB: :PROPERTIES: :EMAIL: john.doe@example.com :NICK: :DESCRIPTION: :BIRTHDAY: :END: * Nick Smith :GroupB: :PROPERTIES: :EMAIL: nick.smith@aaaa.bb :NICK: :DESCRIPTION: :BIRTHDAY: :END: * Rick Armstrong :MailingListA: :PROPERTIES: :EMAIL: rick.armstrong@bbbb.dd :NICK: :DESCRIPTION: :BIRTHDAY: :END: ``` And here is the code for parsing it and putting it in the current buffer: ``` (defun my-contact-extract-all (elem) (let ((lname (nth 0 elem)) (ladd (cdr (assoc "EMAIL" (nth 2 elem))))) (concat lname " <" ladd ">"))) (defun get-mailing-list-from-tag(tag) (let ((my-list (org-contacts-filter nil tag nil))) (mapconcat 'my-contact-extract-all my-list ", "))) (defun org-contacts-get-list-from-tag (tag) "Returns a string containing all addresses from all contacts with a certain TAG" (interactive "sEnter tag:") (message (get-mailing-list-from-tag tag)) (insert (get-mailing-list-from-tag tag))) ``` If you have suggestion on improvements to my code, please post a comment below. > 1 votes --- Tags: org-mode, mu4e, org-contacts ---
thread-57610
https://emacs.stackexchange.com/questions/57610
Comment out / uncomment source blocks on state change in org-mode config file
2020-04-05T23:18:35.087
# Question Title: Comment out / uncomment source blocks on state change in org-mode config file I started to move my config file to an org-file just recently. I wondered if it was possible to use the TODO state to activate or deactivate source blocks in the entry under the heading. This way it would be very easy to try out settings and customization. Example: with `#+TODO: ON | OFF` ``` * ON use org-bullets #+BEGIN_SRC emacs-lisp (require 'org-bullets) (add-hook 'org-mode-hook (lambda () (org-bullets-mode 1))) #+END_SRC ``` and after state change it would be ``` * OFF use org-bullets #+BEGIN_SRC emacs-lisp ;;(require 'org-bullets) ;;(add-hook 'org-mode-hook (lambda () (org-bullets-mode 1))) #+END_SRC ``` I thought about using the `org-after-todo-state-change-hook` but I know too litte elisp to go beyond that. The setting should only work in the config.org file, not in other org files. Any helpful idea is appreciated. P.S.: my `M-x emacs-version` is ``` GNU Emacs 26.1 (build 2, arm-unknown-linux-gnueabihf, GTK+ Version 3.24.5) of 2019-09-23, modified by Debian ``` # Answer If you set the todo state to the special keyword `COMMENT` the entire heading will be treated as a comment and no source blocks under it will run. > 0 votes --- Tags: org-mode, comment, todo ---
thread-57620
https://emacs.stackexchange.com/questions/57620
How to prevent agenda view from showing items' creation timestamp?
2020-04-06T12:45:05.900
# Question Title: How to prevent agenda view from showing items' creation timestamp? My agenda view shows duplicated items when they are created and scheduled in the same day, which litters this view: So for instance The item that was created today at 11:33 will show once with its creation timestamp, and then again without timestamp. I'd like to remove the former from the view and keep the latter. **EDIT** Thank y'all for your help. As @erikstokes poined out, my question was a duplicated of this one. So the only solution I could think of is to make the timestamp inactive when capturing (creating) a note. To this end I changed `%T` by `%U` in my capture template: ``` (setq org-capture-templates '(("t" "New Task" entry (file+headline agenda-path "Inbox") "* TODO %?\n %U\n %i\n") ) ) ``` I also customized `org-agenda-time-grid` as suggested in the answer by @NickD, which causes timestamps to be displayed in a more compact manner, in case they are shown. ``` (setq org-agenda-time-grid '((require-timed) "----------------" (800 1000 1200 1400 1600 1800 2000))) ``` # Answer > 1 votes IIUC, you want to remove the time grid completely: ``` (setq org-agenda-use-time-grid nil) ``` If this variable is non-nil, then the grid is shown, but you can control (to some extent) the format of the grid entries by using the `org-agenda-time-grid` variable. The doc string for `org-agenda-time-grid` should provide some guidance on what you can do with it: ``` org-agenda-time-grid is a variable defined in ‘../org-mode/lisp/org-agenda.el’. Its value is ((daily today require-timed) (800 1000 1200 1400 1600 1800 2000) "......" "----------------") You can customize this variable. Documentation: The settings for time grid for agenda display. This is a list of four items. The first item is again a list. It contains symbols specifying conditions when the grid should be displayed: daily if the agenda shows a single day weekly if the agenda shows an entire week today show grid on current date, independent of daily/weekly display require-timed show grid only if at least one item has a time specification remove-match skip grid times already present in an entry The second item is a list of integers, indicating the times that should have a grid line. The third item is a string which will be placed right after the times that have a grid line. The fourth item is a string placed after the grid times. This will align with agenda items. ``` In particular, the `remove-match` setting might be what you want: ``` (setq org-agenda-time-grid '((today remove-match) (800 1000 1200 1400 1600 1800 2000) "......" "----------------")) ``` although that keeps the entry in the grid and gets rid of the other entry. --- Tags: org-mode, org-agenda ---
thread-57479
https://emacs.stackexchange.com/questions/57479
Can page-down clamp the last line to the bottom of the window?
2020-03-30T22:39:27.070
# Question Title: Can page-down clamp the last line to the bottom of the window? When using page-down (internally `scroll-up-command`), sometimes the window ends up in a state where end end-of-file is at the top of the screen. Is there a way to page-down, clamping window position so it doesn't end up scrolling past the document end? The emacs buffer displays something like this: ``` ;;; some-file.el ends here ``` --- Note that I'm not asking for a way to prevent the window moving past the document end entirely *(although that could be nice)*, just a way to change the behavior of `scroll-up-command` # Answer This can be done using scrolling commands written in elisp. ``` ;; Scrolling that re-centers, keeping the cursor vertically centered. ;; Also clamps window top when scrolling down, ;; so the text doesn't scroll off-screen. (defun my-scroll-and-clamp--forward-line (n) "Wrap `forward-line', supporting Emacs built-in goal column. Argument N the number of lines, passed to `forward-line'." (let ((next-column (or goal-column (and (memq last-command '(next-line previous-line line-move)) (if (consp temporary-goal-column) (car temporary-goal-column) temporary-goal-column))))) (unless next-column (setq temporary-goal-column (current-column)) (setq next-column temporary-goal-column)) (forward-line n) (move-to-column next-column)) ;; Needed so `temporary-goal-column' is respected in the future. (setq this-command 'line-move)) (defmacro my-scroll-and-clamp--with-evil-visual-mode-hack (&rest body) "Execute BODY with the point not restricted to line limits. This is needed so the point is not forced to line bounds even when in evil visual line mode." `(let ((mark-found nil)) (when (and (fboundp 'evil-visual-state-p) (funcall 'evil-visual-state-p) (fboundp 'evil-visual-type) (eq (funcall 'evil-visual-type) 'line) (boundp 'evil-visual-point)) (let ((mark (symbol-value 'evil-visual-point))) (when (markerp mark) (setq mark-found mark)))) (unwind-protect (progn (when mark-found (goto-char (marker-position mark-found))) ,@body) (when mark-found (set-marker mark-found (point)))))) ;;;###autoload (defun my-scroll-and-clamp-up-command () (interactive) (my-scroll-and-clamp--with-evil-visual-mode-hack (let ((height (window-height))) ;; Move point. (my-scroll-and-clamp--forward-line height) ;; Move window. (set-window-start (selected-window) (min (save-excursion ;; new point. (forward-line (- (/ height 2))) (point)) (save-excursion ;; max point. (goto-char (point-max)) (beginning-of-line) (forward-line (- (- height (+ 1 (* 2 scroll-margin))))) (point)))))) (redisplay)) ;;;###autoload (defun my-scroll-and-clamp-down-command () (interactive) (my-scroll-and-clamp--with-evil-visual-mode-hack (let* ((height (window-height))) ;; Move point. (my-scroll-and-clamp--forward-line (- height)) (setq this-command 'line-move) ;; Move window. (set-window-start (selected-window) (save-excursion ;; new point. (forward-line (- (/ height 2))) (point))))) (redisplay)) ``` Example shortcut bindings: ``` (global-set-key (kbd "<next>") 'my-scroll-and-clamp-up-command) (global-set-key (kbd "<prior>") 'my-scroll-and-clamp-down-command) ``` > 1 votes --- Tags: scrolling ---
thread-57637
https://emacs.stackexchange.com/questions/57637
How does process-environment get initialized and why would it be different from initial-environment?
2020-04-07T01:06:20.587
# Question Title: How does process-environment get initialized and why would it be different from initial-environment? I'm trying to troubleshoot an issue with my `exec-path`. It contains a couple of paths prepended to it that I don't want. `initial-environment` contains the paths that match what I see when I echo `$PATH` in xterm but `process-environment` contains a couple extra and I can't figure out how they are getting there. I've tried setting a watcher with`debug-on-variable-change` at the start of my init.el file, but by the time the watcher gets triggered, `process-environment` already has those 2 garbage entries. Can I set that watch before Emacs launches? # Answer The C function `set_initial_environment` in `callproc.c` populates `process-environment` and `initial-environment` together. Subsequent calls to `setenv` are the *usual* way of modifying `process-environment` (but noting that it's very common to be doing that in only a temporary dynamic scope). Obviously it's just a list though, so other manipulations are also entirely possible. > Is there a way to watch a variable and enter a debugger when it is changed? Yes, see: `C-h``i``g` `(elisp)Watching Variables` > Can I set that watch before Emacs launches? There is nothing to set or watch before Emacs launches. > 2 votes # Answer The answer is related to Doom Emacs. I should have included in my original question that I was using a Doom config. The reason my initial attempt at putting a `debug-on-variable-change` in my `init.el` didn't work was because I was putting it in `.doom.d/init.el` which is loaded late in the initialization process. After reading the Doom docs about the initialization order, I saw that it starts with `.emacs.d/init.el` (of course). I put the `debug-on-variable-change` in there and saw it was happening in the function `(doom-load-envvars-file "~/.emacs.d/.local/env")` which gets called as part of Doom's initialization. ``` # -*- mode: sh -*- # Generated from a /bin/zsh shell environent # --------------------------------------------------------------------------- # This file was auto-generated by `doom env'. It contains a list of environment # variables scraped from your default shell (excluding variables blacklisted # in doom-env-ignored-vars). # # It is NOT safe to edit this file. Changes will be overwritten next time you # run 'doom sync'. To create a safe-to-edit envvar file use: # # doom env -o ~/.doom.d/myenv # # And load it with (doom-load-envvars-file "~/.doom.d/myenv"). # --------------------------------------------------------------------------- ``` I just needed to run `doom sync` from a terminal that had the environment that I wanted. > 0 votes --- Tags: environment, exec-path ---
thread-57644
https://emacs.stackexchange.com/questions/57644
Expiring search highlights in Evil
2020-04-07T04:17:22.443
# Question Title: Expiring search highlights in Evil I'm using the `evil-search` module (`(evil-select-search-module 'evil-search-module 'evil-search)`). When I perform a search, the results remain highlighted until I call `evil-ex-nohighlight`. I'd prefer that the highlights go away by themselves after a few seconds. I tried `(setq evil-ex-search-persistent-highlight nil)`, but this setting apparently doesn't apply to `evil-search`. Is there a way of having auto-expiring highlights with `evil-search`? # Answer Using `(setq evil-ex-search-persistent-highlight nil)` and `(evil-select-search-module 'evil-search-module 'evil-search)` searching for matches with `/` highlights them while I enter the pattern, then removes the highlight after pressing `RET` or aborting the search. This is the full extent of `evil-ex-search-persistent-highlight`, it does not apply to commands such as `n` and `N`. Patches welcome for these. > 1 votes --- Tags: evil, search, highlighting ---