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-41360
https://emacs.stackexchange.com/questions/41360
Using org-beamer: display image on every page except the title page
2018-05-06T17:58:32.227
# Question Title: Using org-beamer: display image on every page except the title page Using `org-beamer-export-to-pdf` with the following document, I am able to display an image on every slide ``` #+LATEX_HEADER:\usepackage{eso-pic}% http://ctan.org/pkg/eso-pic #+BEAMER_HEADER:\newcommand\AtPagemyUpperLeft[1]{\AtPageLowerLeft{\put(\LenToUnit{0.85\paperwidth},\LenToUnit{0.9\paperheight}){#1}}}\AddToShipoutPictureFG{\AtPagemyUpperLeft{{\includegraphics[width=1.cm,keepaspectratio]{logo.png}}}} * A Slide goes here ** With some content * Another slide ** Yet more content ``` This works well because it places the image on top of the page headers, where other attempts like ``` #+BEAMER_HEADER:\logo{\includegraphics[height=.8cm]{logo.png}\vspace{6cm}\hspace{0.5cm}} ``` The image would be covered by the header. What I'd like to do now is to skip the title page when displaying the image. The solutions suggested in TeX forums often suggest placing the `\AddToShipoutPictureFG` after building the title page. However,I'm not sure how to control the placement of that command using org-beamer. # Answer > 1 votes First, a solution for using a logo in the header: ``` #+BEAMER_HEADER:\logo{\includegraphics[height=.8cm]{logo.png}\vspace{6cm}\hspace{0.5cm}} * A Slide goes here :PROPERTIES: :BEAMER_OPT: plain :END: ** With some content * Another slide ** Yet more content ``` https://lists.gnu.org/archive/html/emacs-orgmode/2016-07/msg00116.html Second, a solution for your actual question: ``` #+LATEX_HEADER:\usepackage{eso-pic}% http://ctan.org/pkg/eso-pic #+BEAMER_HEADER:\newcommand\AtPagemyUpperLeft[1]{\AtPageLowerLeft{\put(\LenToUnit{0.85\paperwidth},\LenToUnit{0.9\paperheight}){#1}}} * A Slide goes here ** With some content * Another slide #+LATEX: \AddToShipoutPictureFG{\AtPagemyUpperLeft{{\includegraphics[width=1.cm,keepaspectratio]{logo.png}}}} ** Yet more content ``` https://orgmode.org/manual/Quoting-LaTeX-code.html Thanks for your question. It helped me figure out how to put a logo in the header. --- Tags: org-mode, org-export, pdf, beamer ---
thread-60810
https://emacs.stackexchange.com/questions/60810
Expanding some elisp into HTML inside Org
2020-09-23T13:30:58.687
# Question Title: Expanding some elisp into HTML inside Org I am creating an HTML file containing some notes exported from org mode. I would like to add all images from a folder into the HTML file generated i.e the images should display in the webpage when opened. Is there a way to insert a bit of local Emacs-Lisp code in the org mode file such that on exporting to HTML, the code block expands to something a sequence of `<img>` tags containing file names from the folder `images`. (I guess I am looking for something like a kind of local macro expansion?) To be precise I want something like ``` blah blah blah blah <<< Elisp code that expands to HTML inside Org file>>> blah blah blah blah blah ``` to be converted into ``` blah blah blah blah <figure> <img src="./images/image1.png" width="300px" /> </figure> <figure> <img src="./images/image2.png" width="300px" /> </figure> . . . <figure> <img src="./images/image700.png" width="300px" /> </figure> blah blah blah blah blah ``` Note that I don't want this expanded HTML gunk inside the org mode file itself, but inside the exported HTML file. # Answer > 2 votes Something like this perhaps - I've written the code block in python but you can do it in any language you want: ``` * foo blah blah blah #+begin_src python :results output :exports results :var n=700 :wrap export html for i in range(1,n+1): print('<figure>\n <img src="./images/image{}.png" width="300px" />\n</figure>\n'.format(i)) #+end_src blah blah blah blah blah bla ``` The `:wrap export html` is the important thing: it will wrap the results in ``` #+begin_export html #+end_export ``` allowing the exporter to just copy them verbatim to the HTML output file. The `:exports results` header makes sure that the block will be evaluated when you export and will produce the boilerplate, but as long as you are careful *NOT* to evaluate it in the buffer with `C-c C-c` you won't see the results there. If you do evaluate it by mistake, you can get rid of the results with `M-x org-babel-remove-result RET`. --- Tags: org-mode, html ---
thread-60800
https://emacs.stackexchange.com/questions/60800
How can I automatically block out "free time" in an org-agenda view?
2020-09-22T21:30:13.977
# Question Title: How can I automatically block out "free time" in an org-agenda view? Was just thinking. I've noticed a lot of people schedule their free time in to their agendas/planners. I think it would be useful to automatically schedule out free time when opening the agenda. For example, if I have schedule tennis practice, and a meeting, my current agenda would like like this: ``` 8:00-10:00 Scheduled: Tennis Practice 16:30-18:00 Meeting ``` Whereas, it could look like this: ``` 8:00-10:00 Scheduled: Tennis Practice 10:00-16:30 Free 16:30-18:00 Scheduled: Meeeting 18:00-20:00 Free ``` ...without having to schedule to free time explicitly. To me, this is a lot easier to comprehend than the above time graph, particularly since I find looking at my watch more useful than the time grid. How can I do this? # Answer This does not quite reproduce what you want, but it's close. Try setting `org-agenda-use-time-grid` to `t`. That will show you a time grid like this: ``` Weather: 6:34...... Sunrise 8:00...... ---------------- 10:00...... ---------------- 12:00...... ---------------- 14:00...... ---------------- 16:00...... ---------------- 18:00...... ---------------- Weather: 18:37...... Sunset 20:00...... ---------------- ``` Then check out the variable `org-agenda-time-grid`. Its doc string says: ``` org-agenda-time-grid is a variable defined in ‘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. ``` So changing the fourth item (or not: you might leave it as a bunch of dashes) should do what you want: ``` (setq org-agenda-use-time-grid t) (setq org-agenda-time-grid '((daily today require-timed) (800 1000 1200 1400 1600 1800 2000) "......" "----Free----")) ``` What this does not do is coalesce a range of free times into one. I think that would require substantial changes in the code. > 4 votes --- Tags: org-mode, org-agenda ---
thread-60817
https://emacs.stackexchange.com/questions/60817
Table formulas involving percentages
2020-09-23T20:55:40.423
# Question Title: Table formulas involving percentages I'm creating a table with percentages and calculating a simple sum of a column. The only thing left is to show the result of the formula as a percentage. Here is my MWE: ``` | Element | $ | | E1 | 35% | | E2 | 65% | |---------+-----| | Total | 1. | #+TBLFM: @>$>=vsum(@2..@-1) ``` My question is: how can I show the result of the formula as `100%` instead of `1`? The percentage signs are important because the table will be exported to latex. # Answer After a bit of trial and error, it seems that something like this might work: ``` | Element | $ | |---------+------| | E1 | 35% | | E2 | 65% | |---------+------| | Total | 100% | #+TBLFM: @>$>=vsum(@I..II)*100;%.0f%% ``` You always think of the entries as the corresponding decimal fraction (35% = 35/100 = 0.35 etc) and the result is the sum of the fractions, so you convert the fraction into the percentage by multiplying by 100 and formatting the result as a float with, in this case, 0 digits after the decimal point and appending a % sign (but a % sign has special meaning in format strings so to get a literal percent sign, it needs to be escaped with another percent sign). > 6 votes --- Tags: org-mode, org-table, calc ---
thread-60820
https://emacs.stackexchange.com/questions/60820
does tramp mode look at .dir-locals
2020-09-24T03:15:36.697
# Question Title: does tramp mode look at .dir-locals I'm using emacs over tramp to edit a project inside a vm on my local machine. It has something like this: ``` ssh:vm:~/projects/project/.dir-locals.el ssh:vm:~/projects/project/src/tests/file-i'm-editing.f90 ``` On my local machine I have .dir-locals.el setup properly, but when I'm editing files on the vm, it doesn't seem to use the .dir-locals.el file. Is this expected or should it be using that file? I have edited the file on the vm to have the correct paths. # Answer > 8 votes ``` enable-remote-dir-locals is a variable defined in ‘files.el’. Its value is nil You can customize this variable. This variable was introduced, or its default value was changed, in version 24.3 of Emacs. Probably introduced at or before Emacs version 24.3. Documentation: Non-nil means dir-local variables will be applied to remote files. ``` n.b. I believe this is disabled by default as a performance measure, to reduce the overheads of working with remote files. --- Tags: tramp, directory-local-variables ---
thread-60825
https://emacs.stackexchange.com/questions/60825
"Not an Org time string: [2020 09 23 Wed 13:41]" on org-clock-in?
2020-09-24T09:59:51.433
# Question Title: "Not an Org time string: [2020 09 23 Wed 13:41]" on org-clock-in? I can't `org-clock-in` anymore in org-mode. I don't know how I've achieved this. The time the error shows isn't the current time of day when I run `org-clock-in`. It seems stuck in the past. There are no other clocks running. For a moment it seemed to work again after I ran `package-initialize`, however I restarted Emacs and the problem returned. The other thing I've been playing with is `desktop-save` where I've been limiting how many buffers it restores on restart using `'(desktop-restore-eager 5)`. I am wondering if I've caused this after running `package-autoremove` yesterday which cleared out four packages (Is `org` dependent on something else?), however I can't find a log that will let me go back and see what those packages were (yes stupid me). I understand that the time-stamp is missing hyphens between the numerals. My `.emacs.el` file is purely just loading packages as opposed to running custom functions. I don't think I've got anything in there or in `customize-group` that would adjust the date format. ``` Debugger entered--Lisp error: (error #("Not an Org time string: [2020 09 23 Wed 13:41]" 24 46 (fontified nil line-prefix #(" " 0 8 (face org-indent)) wrap-prefix #(" " 0 8 (face org-indent)) org-category "notes"))) signal(error (#("Not an Org time string: [2020 09 23 Wed 13:41]" 24 46 (fontified nil line-prefix #(" " 0 8 (face org-indent)) wrap-prefix #(" " 0 8 (face org-indent)) org-category "notes")))) error("Not an Org time string: %s" #("[2020 09 23 Wed 13:41]" 0 22 (org-category "notes" wrap-prefix #(" " 0 8 (face org-indent)) line-prefix #(" " 0 8 (face org-indent)) fontified nil))) org-parse-time-string(#("[2020 09 23 Wed 13:41]" 0 22 (org-category "notes" wrap-prefix #(" " 0 8 (face org-indent)) line-prefix #(" " 0 8 (face org-indent)) fontified nil))) org-time-string-to-time(#("[2020 09 23 Wed 13:41]" 0 22 (org-category "notes" wrap-prefix #(" " 0 8 (face org-indent)) line-prefix #(" " 0 8 (face org-indent)) fontified nil))) org-find-open-clocks("/Users/patrick/Documents/org/notes.org") org-resolve-clocks() org-clock-in(nil) funcall-interactively(org-clock-in nil) call-interactively(org-clock-in record nil) command-execute(org-clock-in record) execute-extended-command(nil "org-clock-in") smex-read-and-run(("org-clock-in" "toggle-debug-on-error" "org-time-stamp-inactive" "org-agenda-clock-in" "org-time-stamp" "package-initialize" "org-roam-mode" "helm-M-x" "org-babel-tangle" "package-install" "package-autoremove" "load-theme" "compare-windows" "helm-projectile-ag" "org-archive-subtree" "comment-line" "package-delete" "org-capture" "ilog-show-in-new-frame" "org-refile" "eval-expression" "customize-group" "org-roam-find-file" "mc/mark-all-like-this" "package-list-packages" "iedit-mode" "list-packages" "org-clock-out" "helm-do-ag" "server-start" "balance-windows" "split-window-right" "org-roam-buffer-toggle-display" "org-mode" "org-roam" "load-file" "org-agenda" "describe-mode" "org-clock-goto" "save-some-buffers" "helm-projectile-grep" "helm-ag" "ido-mode" "customize" "helm-mode" "lisp-mode" "multi-occur" "org-version" "windmove-up" "desktop-save" ...)) smex() funcall-interactively(smex) call-interactively(smex nil nil) command-execute(smex nil nil :special) xah-fly-M-x() funcall-interactively(xah-fly-M-x) call-interactively(xah-fly-M-x nil nil) command-execute(xah-fly-M-x) ``` Would anyone have a suggestion on how to figure out what I've broken? Thank you for your time. # Answer You probably have a bad time stamp in one of your Org mode files. In particular, the time stamp that causes the error is missing the dashes: `2020-09-23 Wed 13:41`. The question is how to find the file that contains that time (non)stamp. Backtrace to the rescue: ``` ... org-find-open-clocks("/Users/patrick/Documents/org/notes.org") ... ``` That's where I would start looking: see if the string is in that file, fix it with dashes and you should be OK. I would run `M-x org-lint` in that file (and eventually on every other Org mode file that you can get your hands on) to identify any more problems that might exist. In fact, run it before you fix it and see what it says. How the bad time string ended up in there cannot be determined, except by you: did you enter the time stamp manually? If so, don't do that: use the helpful functions that Org mode provides, in particular `org-time-stamp` which is conveniently bound to `C-c .` and the scheduled/deadline versions `org-schedule` bound to `C-c C-s` and `org-deadline` bound to `C-c C-d`. > 2 votes --- Tags: org-mode, org-clock ---
thread-60832
https://emacs.stackexchange.com/questions/60832
How to add more default face highlight colors
2020-09-24T20:20:03.637
# Question Title: How to add more default face highlight colors Using (highlight-symbol-at-point) at some point the highlight start repeating colors. I find the variable that holds the default face highlight color values in Emacs is: hi-lock-face-defaults It holds this value: ``` ("hi-yellow" "hi-pink" "hi-green" "hi-blue" "hi-salmon" "hi-aquamarine" "hi-black-b" "hi-blue-b" "hi-red-b" "hi-green-b" "hi-black-hb") ``` I want to add more default colors. What is the best way to do it? # Answer Set variable `hi-lock-face-defaults` to the *names* of the faces you want. ``` (add-to-list 'hi-lock-face-defaults "highlight") ; Add a face (`highlight`). ``` or ``` (setq hi-lock-face-defaults ; Set to just these 3 faces. '("dired-flagged" "highlight" "hi-yellow")) ``` or ``` (setq hi-lock-face-defaults ; Add multiple faces. (append '("dired-flagged" "highlight") hi-lock-face-defaults)) ``` > 3 votes --- Tags: faces, variables, hi-lock ---
thread-53105
https://emacs.stackexchange.com/questions/53105
Getting error "Failed to download 'gnu' archive" on Emacs 26.3
2019-10-11T19:46:24.130
# Question Title: Getting error "Failed to download 'gnu' archive" on Emacs 26.3 I'm currently using Ubuntu 18.04, and trying out Emacs for the first time. However, whenever I run the command `package-refresh-contents`, I get the the follow error: > Failed to download 'gnu' archive This is my ~/.emacs.d/init.el file: ``` (setq gnutls-algorithm-priority "NORMAL:-VERS-TLS1.3") ;(setq package-check-signature nil) ; Set up melpa package repository (require 'package) (setq package-enable-at-startup nil) (add-to-list 'package-archives '("gnu", "https://elpa.gnu.org/packages/") '("melpa", "https://melpa.org/packages/")) (package-initialize) ``` These are the steps I've tried so far: 1. Upgraded from Emacs 26.2 to 26.3. According to this Reddit thread, this was supposedly fixed in Emacs 26.3. Since I'm using Kelley PPA to download Emacs, I had to upgrade from Ubuntu 16.04 to 18.04 to get Emacs 26.3, and it still didn't fix the issue. 2. Set `(setq gnutls-algorithm-priority "NORMAL:-VERS-TLS1.3")` as suggested here. 3. Set `(setq package-check-signature nil)` as suggested here. 4. Changed the URLs from https to http. I've found no other suggestions when I searched online. Any help would be appreciated. Updating with error message printed in Messages buffer when running the command `package-refresh-contents` after starting emacs with the flag `--debug-init`: > For information about GNU Emacs and the GNU system, type C-h C-a. > Importing package-keyring.gpg...done Contacting host: elpa.gnu.org:443 > gnutls.el: (err=\[-50\] The request is invalid.) boot: (:priority NORMAL:-VERS-TLS1.3 :hostname elpa.gnu.org :loglevel 0 :min-prime-bits 256 :trustfiles (/etc/ssl/certs/ca-certificates.crt) :crlfiles nil :keylist nil :verify-flags nil :verify-error nil :callbacks nil) > Failed to download ‘gnu’ archive. \[2 times\] > You can run the command ‘package-refresh-contents’ with M-x pa-r- RET > Failed to download ‘gnu’ archive. Updating with error message after removing the gnutls-algorithm-priority setting: > For information about GNU Emacs and the GNU system, type C-h C-a. > delete-backward-char: Text is read-only \[4 times\] > Importing package-keyring.gpg...done > Contacting host: elpa.gnu.org:443 \[2 times\] > Failed to download ‘gnu’ archive. > You can run the command ‘package-refresh-contents’ with M-x pa-r- RET > Failed to download ‘gnu’ archive. Updated with debugger info after running command `toggle-debug-on-error` and then running `package-refresh-contents`: > Debugger entered--Lisp error: (wrong-type-argument stringp ((\\, "https://elpa.gnu.org/packages/"))) > string-match("\\\`https?:" ((\\, "https://elpa.gnu.org/packages/")) nil) > package--download-one-archive(("gnu" (\\, "https://elpa.gnu.org/packages/")) "archive-contents" nil) > package--download-and-read-archives(nil) > package-refresh-contents() > funcall-interactively(package-refresh-contents) > call-interactively(package-refresh-contents record nil) > command-execute(package-refresh-contents record) > execute-extended-command(nil "package-refresh-contents" "package-refr") > funcall-interactively(execute-extended-command nil "package-refresh-contents" "package-refr") > call-interactively(execute-extended-command nil nil) > command-execute(execute-extended-command) # Answer > 0 votes Thanks to @npostavs, who provided the solution in their comments. Here's the fixed `init.el` file, for quick and easy reference: ``` ;(setq package-check-signature nil) ; Set up melpa package repository (require 'package) (setq package-enable-at-startup nil) (add-to-list 'package-archives '("gnu" . "https://elpa.gnu.org/packages/")) (add-to-list 'package-archives '("melpa" . "https://melpa.org/packages/")) (package-initialize) ``` --- Tags: package-repositories ---
thread-57516
https://emacs.stackexchange.com/questions/57516
How can I run imenu in all project files?
2020-04-01T16:46:55.327
# Question Title: How can I run imenu in all project files? Is there any package which will allow to run the imenu in all project files of a current mode? More specifically I have a Go project defined by `projectile` and I would like to search for a symbol in the whole project. I know about `imenu-anywhere` \- but it only searches through symbols in opened buffers. # Answer > 1 votes My solution is way too hacky: A file that you want to have Imenu to access is likely to be tracked by Git. Use find-file-noselect on all those files (I don't know how to detect binary files with Emacs so limiting on VCS-tracked files is better), and accept the risk of hooks and advices, auto-loading functions, etc. ``` ;;;###autoload (defun open-project-files-in-background () "Open/find all source files in the background which are tracked by Git." (let ((default-directory (vc-root-dir))) (save-window-excursion (dolist (file (split-string (shell-command-to-string "git ls-files"))) (unless (find-buffer-visiting file) (with-current-buffer (find-file-noselect file) (if (equal (get major-mode 'derived-mode-parent) 'prog-mode) (bury-buffer) (kill-buffer)))))))) ;;;###autoload (defun open-project-files-in-background-maybe (&rest _args) "Prepare a project-wide `Imenu'." (interactive) ;; 'vc-root-dir returns nil when not tracked, so checking if (not ;; that it is in a list that contains nil) is enough for both ;; (non-nil and in the list of fully opened projects) (defvar fully-opened-projects '(nil) "List of project paths, each has all tracked files opened.") (let ((git-dir (vc-root-dir))) (unless (member git-dir fully-opened-projects) (open-project-files-in-background) (push git-dir fully-opened-projects)))) (advice-add 'imenu-anywhere :before 'open-project-files-in-background-maybe) ``` # Answer > 0 votes Imenu *is for* open buffers. Consider using a command such as `find-grep-dired`, `find-dired`, `find-name-dired`, `find-time-dired`, or `xref-find-definitions`. --- Tags: projectile, imenu, find ---
thread-60835
https://emacs.stackexchange.com/questions/60835
Why my minor mode bindings do not get precedence over global/major mode bindings? BUG?
2020-09-25T08:48:33.447
# Question Title: Why my minor mode bindings do not get precedence over global/major mode bindings? BUG? EDIT: ANSWER The cause for the problem in this question was pointed out in the Emacs mailing list. It is due to the `(kbd ...)` forms not getting evaluated because the keymap in the `define-minor-mode` is passed as a quoted list. The `(kbd ...)` forms can be used by using a backquoted list and then placing a `,` before each `(kbd ...)` form so that they get evaluated. END EDIT I know there are similar questions like mine, but I could not find an answer to my question. This question was edited (below) because it appears to be a bug (please confirm). I want my minor-mode bindings to get precedence over the pdf-view major mode bindings. I define my minor mode with the following code: ``` (define-minor-mode pdf-continuous-scroll-mode "Emulate continuous scroll with two synchronized buffers" nil " Continuous" '(((kbd "j") . (lambda () (interactive) (print "pushed j"))) ((kbd "k") . (lambda () (interactive) (print "pushed k"))) ((kbd "C-n") . (lambda () (interactive) (print "pushed C-n"))) ((kbd "C-p") . (lambda () (interactive)(print "pushed C-p")))) (print "loaded minor mode")) ``` Now when I evaluate this while I am viewing a document with PDF-tools and enable the minor mode, then the `j`/`k` bindings work but the `C-n/C-p` bindings do not because Emacs still uses the pdf-view major mode keybindings (i.e. it scrolls the document). I find here that minor-mode keymaps should have highest precedence behind overlay keymaps. I checked if maybe there is some overlay keymap used in PDF-tools but I could not find one. Can anybody explain why my minor mode bindings do not get precedence over de pdf-view major mode bindings? EDITS 1. I find the `C-n` and `C-p` do not even get precedence over the global-keymap. I can just start emacs using `emacs -Q`, evaluate the code and activate the minor mode. Then still `C-n` and `C-p` do not work. Please someone confirm this is a bug, then I will report the bug. END EDIT # Answer > 3 votes I think it's a bug. If you don't use that alist as the `KEYMAP` arg, but instead you create a keymap, assign it to a variable, use `define-key` with `(kbd "C-n")` etc., and use that variable as the `KEYMAP` arg, then it works. Please consider using `M-x report-emacs-bug`, to report this. ``` (setq toto-map (make-sparse-keymap)) (defun foo () "..." (interactive) (message "my C-n")) (define-key toto-map (kbd "C-n") 'foo) (define-minor-mode pdf-continuous-scroll-mode "Emulate continuous scroll with two synchronized buffers" nil " Continuous" toto-map (print "loaded minor mode")) ``` --- Tags: key-bindings, minor-mode ---
thread-60844
https://emacs.stackexchange.com/questions/60844
Why does this function (that uses save-excursion) leave me at another buffer
2020-09-25T23:49:18.753
# Question Title: Why does this function (that uses save-excursion) leave me at another buffer I'm trying to write a command that allows me to search for an org-mode entry and inserts a link to it at point (using its `id`). Here's the code: ``` (defun org-link-to-entry () (interactive) (let (link description) (save-excursion (setq link (org-id-complete-link)) (org-id-goto (string-remove-prefix "id:" link)) (setq description (org-get-heading t t t t))) (insert (format "[[%s][%s]]" link description)) )) ``` As far as I understand it, the only form that changes point is `org-id-goto`, and that is inside a save-excursion. In my setup, the code actually inserts the link at the proper place, but leaves me at the start of the heading with the given `id`. This question seems related, but no enough: Why save-excursion doesn't save point position? I've also tried using `save-current-buffer` (as in https://emacs.stackexchange.com/a/17577/27223) both around `save-excursion` and the `let` binding, but both also leave me at the buffer where the entry with `id` is. I'm on Spacemacs, if that's relevant. Note that this is what I get when I pull-up the documentation for `save-excursion`: > `save-excursion` is a special form in ‘C source code’. > > `(save-excursion &rest BODY)` > > Probably introduced at or before Emacs version 20. > > Save point, and current buffer; execute BODY; restore those things. Executes BODY just like ‘progn’. The values of point and the current buffer are restored even in case of abnormal exit (throw or error). > > If you only want to save the current buffer but not point, then just use ‘save-current-buffer’, or even ‘with-current-buffer’. > > Before Emacs 25.1, ‘save-excursion’ used to save the mark state. To save the mark state as well as point and the current buffer, use ‘save-mark-and-excursion’. What am I doing wrong? How to make this function leave me at the point and buffer I was before calling it? # Answer You're probably looking for `save-window-excursion`. Note the docstring warnings; but as `org-id-goto` uses `pop-to-buffer-same-window` which will use the *current* window unless called from a minibuffer or the current window is dedicated, you would be ok in *most* situations. `save-excursion` just ensures that elisp code acting on a buffer will be able to continue acting afterwards on the same buffer at the same point. Whether or not the window configuration changed in the interim is not relevant to that use-case -- the buffer being acted on needn't even be visible (and frequently isn't). > 2 votes --- Tags: org-mode, buffers, save-excursion ---
thread-60846
https://emacs.stackexchange.com/questions/60846
How to reference the contents of a variable in a keyboard macro definition?
2020-09-26T09:21:10.580
# Question Title: How to reference the contents of a variable in a keyboard macro definition? I have a macro called `f5`, which I globally bind the keyboard key `<f5>` to: ``` (fset 'f5 [?i ?\[ ?* ?* ?P ?1 ? ?\] escape ?h ?a]) (global-set-key (kbd "<f5>") 'f5) ``` So when I press f5, it inserts `[**P1 ]`, and backs up the cursor and leaves me in input mode, which is fine. But I have reached a stage where, depending on what I am doing, I don't want it to always insert "P1". Sometimes I might like it to insert, say, "P2". What I really want is that it inserts the content of a variable, which variable I can set depending on what I am doing. But I don't know how to reference the contents of a variable in a macro definition. Surely this is possible; how is it done? # Answer You can use `eval-expression` when recording your macro. `M-:` `(insert MYVARNAME)` `RET` > 1 votes --- Tags: keyboard-macros ---
thread-60849
https://emacs.stackexchange.com/questions/60849
funcall/apply lambda
2020-09-26T19:42:53.820
# Question Title: funcall/apply lambda Please look at the following elisp expressions. ``` (funcall 'lambda '() 1) ;; or (apply 'lambda '() 1 ()) ``` The interpreter says that lambda is not a valid function for both the above expressions. Why? Is it because `lambda` is a macro? If so, is there a variant of `funcall/apply` for macros? # Answer > 2 votes Yes, `lambda` is a macro. There is a function that is like `funcall` for macros called `eval`. --- Tags: functions, apply, funcall ---
thread-60799
https://emacs.stackexchange.com/questions/60799
Weekly org-capture-template without days?
2020-09-22T21:26:53.870
# Question Title: Weekly org-capture-template without days? I'm hoping to replicate my manual weekly capture template using the more baked-in functionality. Given this org-capture-template: ``` ("z" "Test" entry (file+olp+datetree "~/docs/eng-log.org" "Worklog") "**** TODO %?" :tree-type week) ``` I'd like this output: ``` * Worklog ** 2020 *** 2020-W39 **** TODO testing? ``` Instead, I get this: ``` * Worklog ** 2020 *** 2020-W39 **** 2020-09-22 Tuesday ***** TODO testing? ``` Is there a way to remove the day marker? # Answer > 2 votes You can override the function `org-datetree-find-iso-week-create` and remove the part that add the day entry. Here is the source of the original function: https://code.orgmode.org/bzg/org-mode/src/master/lisp/org-datetree.el#L111 Just remove the last `org-datetree--find-create` call. --- Tags: org-mode, org-capture ---
thread-60848
https://emacs.stackexchange.com/questions/60848
How to properly generate a concat'd function name with defmacro?
2020-09-26T17:45:29.487
# Question Title: How to properly generate a concat'd function name with defmacro? I have a macro like this: ``` (defmacro my-fun-generator (x) `(defun ,(intern (concat "fun-" x)) () ,(concat "Print " x) (interactive) (print ,x))) ``` This works (found an example online): ``` (dolist (str '("foo" "bar" "baz")) (eval `(my-fun-generator ,str))) ``` But this errors with `(wrong-type-argument sequencep str)` on the first `concat`: ``` (dolist (str '("foo" "bar" "baz")) (my-fun-generator str)) ``` Is it saying the `str` is not of type sequence? Wouldn't `str` be of type string? Is a string a sequence? Just, why doesn't the second version work? # Answer ``` (dolist (str '("foo" "bar" "baz")) (my-fun-generator str)) ``` Yes, a string is a sequence, but the symbol `str` is not a string - it's a symbol (which is not a sequence). What you want to pass to the macro is not `str` but the *value* of `str`. Instead, you're passing the symbol `str` to the macro. *Macros do not evaluate their arguments*, by default. That's why the example you copied *substitutes* the value of `str` for `str` in the sexp (list) `(my-fun-generator...)`, and it then evaluates the resulting sexp. After the substitution, in the first loop iteration, the sexp to be `eval`d is the *list* `(my-fun-generator "foo")`. It's because of that `eval` that `my-fun-generator` is then used as a macro - expanded and its result evaluated. > 0 votes --- Tags: elisp-macros, eval ---
thread-60860
https://emacs.stackexchange.com/questions/60860
org-mode html publish fails with invalid regex error
2020-09-27T11:26:51.583
# Question Title: org-mode html publish fails with invalid regex error I am using org-mode for generating a static website for my notes. For this, I followed the tutoriala at: https://orgmode.org/worg/org-tutorials/org-publish-html-tutorial.html And this is the relevant part on my .emacs file: ``` ;; Org-mode html publish (require 'ox-publish) (setq org-publish-project-alist '( ("org-notes" :base-directory "~/org/" :base-extension "org" :publishing-directory "~/public_html/" :recursive t :publishing-function org-html-publish-to-html :headline-levels 4 ; Just the default for this project. :auto-preamble t ) ("org-static" :base-directory "~/org/" :base-extension "css\\|js\\|php\\|jpg\\|png\\" :publishing-directory "~/public_html/" :recursive t :publishing-function org-publish-attachment ) ("org" :components ("org-notes" "org-static")) )) ``` And I used this one for quite some time now. But lately, when I do `M-x org-publish-project` and pick `org-static`, it fails with the error message `Invalid regexp: "Unmatched ( or \\("`. I wonder where is the problem in my config and how this started failing all of a sudden. The project `org-notes` still works fine. # Answer > 1 votes Check the comment from @NickD, regex: ``` :base-extension "css\\|js\\|php\\|jpg\\|png\\" ``` is indeed wrong if we follow the tutorial exactly. I removed the last `\\`. Still, as I said, this was working before. The actual error was that a package named `cl` is not supported by Emacs anymore. For that, I had to see which packages are depending on it and I evaluated following on `*scratch*`: ``` (require 'loadhist) (file-dependents (feature-file 'cl)) ``` and saw that the package `htmlize`, which I use for org publishing was depending on it. The newer versions of this package are updated to work without the `cl` package. So, I had to reinstall `htmlize` basically and things started working again. --- Tags: org-mode, org-export ---
thread-60862
https://emacs.stackexchange.com/questions/60862
Evaluate docstring in macros
2020-09-27T12:15:35.127
# Question Title: Evaluate docstring in macros Macros like `defun` (or `defmacro` itself) have an optional `docstring` argument, but since they are macros and not functions, `docstring` isn't evaluated, but is taken as-is. I need the `docstring` to be evaluated so that instead of something like this - ``` "does a, then b, then c" ; b is hardcoded ``` I can put something like this instead - ``` (concat "does a, then " (getenv "<some-shell-variable>") " , then c") ; b isn't hardcoded ``` Is it possible to do this without having to tweak the definitions of `defun` and `defmacro`? By tweak, I don't mean overwriting the definitions, but writing new macros like `prefix-defun` and `prefix-defmacro` based on the existing definitions of `defun` and `demacro`, except, the docstring is evaluated by replacing all instances of `docstring` with `(eval docstring)`. # Answer > 1 votes You can set the doc string of any function, variable, or face to any string you want, whether (generated dynamically or not). For a function `foo`, put the string you want on symbol `foo` as the value of property `function-documentation`: ``` (defun foo () ; `foo' gets no doc string from this defun. (interactive) (message "FOOOOOOOO")) (put 'foo 'function-documentation "I'm `foo'.") ; Give function `foo' a doc string. (put 'foo 'function-documentation "I'm NEW `foo' doc.") ; Redefine the doc string. ``` Same thing for a defvar or defcustom - use symbol property `variable-documentation`: ``` (defvar foo 42) ; Variable `foo' has no doc string. (put 'foo 'variable-documentation "I'm `foo'.") ; Give var `foo' a doc string. (put 'foo 'variable-documentation "I'm NEW `foo' .") ; Redefine the doc string. ``` See the Elisp manual, node Documentation Basics and its subnodes. Same thing for `defface`\- use symbol property `variable-documentation`. But `defface` requires a doc string. You can nevertheless change it dynamically, as you can for a function or variable. ``` (defface foo '((t :foreground "Red")) "0000") ; Doc string "0000". (put 'foo 'face-documentation "11111") ; Change doc string to "1111". ``` # Answer > 3 votes ``` (defun foo () (:documentation (concat "does a, then " (getenv "<some-shell-variable>") " , then c")) ...BODY...) ``` This is effectively a duplicate of Is it possible to attach generated doc string to a lambda? except that question is very `lambda`-oriented, and so Stefan's answer doesn't point out that you can do the same thing with `defun`. If you need the docstring to be `eval`'d on-demand (i.e. every time you request it), you can do that as well, but apparently not with `:documentation`. Refer to my answer to the earlier question for some options for doing that. --- Tags: elisp-macros, doc-strings ---
thread-60857
https://emacs.stackexchange.com/questions/60857
symbol-name without adding to obarray
2020-09-27T07:20:36.547
# Question Title: symbol-name without adding to obarray I found out that querying a symbol's name using `symbol-name` adds the symbol to `obarray`. ``` (intern-soft "random-name") ; gives nil (symbol-name 'random-name) ; adds random-name to obarray, gives "random-name" (string). (intern-soft "random-name") ; gives random-name ``` My concern is that this bloats `obarray` with empty symbols (i.e no value or function definition). Is there 1. something like `symbol-name` which doesn't add the to the obarray? 2. a way to clear the obarray of "useless" (all cells other than the name cell are empty) symbols? **Edit** - I just found out that even evaluating a symbol adds it to the `obarray`. So I am assuming this language (or any lisp) is designed in a way that you don't have to worry about the size of `obarray`. Is this correct? # Answer > 1 votes `C-h f make-symbol`: > `make-symbol` is a built-in function in ‘C source code’. > > `(make-symbol NAME)` > > Return a newly allocated uninterned symbol whose name is `NAME`. > > Its value is void, and its function definition and property list are `nil`. This function does not change global state, including the match data. And as others have said in comments, you can also intern a symbol in a different obarray. That doesn't solve your problem of obarray bloating. But that should be a non-problem anyway. You use another obarray as a separate namespace. You can have a symbol `foo` in multiple obarrays. The symbols are different/separate, with different properties, etc. You may have an X-Y problem. If you think so, try to instead ask about something you're really trying to do. E.g., why do you think you want/need to *"clear the obarray of 'useless' (all cells other than the name cell are empty) symbols"*? --- Tags: symbols ---
thread-60738
https://emacs.stackexchange.com/questions/60738
Using company mode to complete sentence
2020-09-19T09:57:06.050
# Question Title: Using company mode to complete sentence As I understand, company mode can help complete the word, but not a sentence. I would like to complete a fragment of sentence. I would like to complete fragment e.g. "portal and hepatic doppler" but not like "portal-and-hepatic-dopler" as is usual with programming. I do not wish to use abbreviation expansion I'm looking for a solution to be used with emacs-org. # Answer Rencently, I use TabNine with Company-mode to complete words and short sentence in Org-mode. And it provide me a very good experice, maybe you can try it and enjoy it. https://github.com/TommyX12/company-tabnine my integration is as below: ``` (require 'company-tabnine) ;; The free version of TabNine is good enough, ;; and below code is recommended that TabNine not always ;; prompt me to purchase a paid version in a large project. (defadvice company-echo-show (around disable-tabnine-upgrade-message activate) (let ((company-message-func (ad-get-arg 0))) (when (and company-message-func (stringp (funcall company-message-func))) (unless (string-match "The free version of TabNine only indexes up to" (funcall company-message-func)) ad-do-it)))) ;; TabNine (add-to-list 'company-backends #'company-tabnine) ``` > 0 votes --- Tags: completion, company-mode ---
thread-60865
https://emacs.stackexchange.com/questions/60865
Spacemacs, Lisp, Pasting and the missing Space
2020-09-27T14:02:16.243
# Question Title: Spacemacs, Lisp, Pasting and the missing Space When editing Lisp or Clojure in Spacemacs (Emacs with Evil) I find the pasting behavior anoying. Say I have yanked `bar` and want to paste it as a parameter to `(foo)` so I get `(foo bar)`. The problem is, I have to insert a space between `o` and `)` before pasting or afterwards. Is there a way to tell Spacemacs to automatically insert the space in Lisp/Clojure mode (with paredit) when pasting? # Answer > 1 votes I don't know if there is a regular command for that (maybe there is one in the emacs-lisp state) but of course you could define your own custom function. e.g. ``` (defun custom-lisp-paste (&optional count) (interactive "*P") (forward-char) (insert " ") (evil-paste-after count)) ``` And bind it to your prefered key. you could optionally add `evil-forward-word-end` before forward-char. I am using `evil-paste-after` and `evil-forward-word-end` here, but I think generally it is preferable to use the underlying Emacs functions directly. It is described in the Emacs lisp intro by Chassell how to insert text from the kill ring... --- Tags: spacemacs, evil, whitespace, yank, paredit ---
thread-60883
https://emacs.stackexchange.com/questions/60883
Use LaTeX accents with tex insert method
2020-09-28T23:26:52.217
# Question Title: Use LaTeX accents with tex insert method With this answer I learned how to insert math symbols with latex syntax directly into my buffer. What I can't figure out is how to make accents insert properly. I want `\hat{\beta}` to insert beta hat ( β̂ ), preferably with circumflex directly on top. # Answer > 1 votes `M-x describe-input-method RET tex RET` will tell you the (somewhat depressing) news: lots of letters can be "hatted" but they are Latin letters only. Input methods are limited in the kind of transformation they do. There is no "hatted beta" Unicode symbol either, so the only way to do it is by writing your notes in LaTeX (or Org mode using LaTex) and produce PDF: then you can write `$\hat{\beta}$`. If you write in Org mode (with LaTeX), you can turn on automatic preview of LaTeX fragments and see the hatted beta as an image overlay in the emacs buffer. Or you can use AucTex and its preview feature. More details about the Org mode/LaTeX preview method can be found in this answer. More details about AucTex and its LaTeX preview feature can be found in the AucTeX/Preview LaTeX manuals. --- Tags: latex, unicode, insert, symbols, math ---
thread-60872
https://emacs.stackexchange.com/questions/60872
Open the manuals in the default web browser without accessing the internet
2020-09-28T10:14:44.003
# Question Title: Open the manuals in the default web browser without accessing the internet I am talking about this to be precise. Suppose there are an emacs installation and a web browser on an X session (desktop). I know you can open the manuals in emacs itself using `M-x info`, but is it possible to open the same manual in the browser (with the basic CSS, like in the website, one node per page)? The default browser was set using XDG's `mimeapps.list`. I searched emacs' package files, but there are no html files listed among them. However, there are a lot of gzipped files with "html" in their name. # Answer > 2 votes I often need to link to the emacs manuals, for example, this markdown link: (emacs) Echo Area, is created via `M-x chunyang-Info-markdown-current-node-html` since it's difficult to do it manually. With the following, you can also type `O` to open the corresponding HTML manuals in your web browser. ``` (defvar chunyang-Info-html-alist '( ;; Special cases come first ("org" . "http://orgmode.org/manual/%s") ("find" . "https://www.gnu.org/software/findutils/manual/html_node/find_html/%s") ("standards" . "https://www.gnu.org/prep/standards/html_node/%s") ("magit" . "https://magit.vc/manual/magit/%s") ("slime" . "https://www.common-lisp.net/project/slime/doc/html/%s") ;; Haha, just for some fun ("geiser" . (lambda (_) ;; (info "(geiser) First aids") ;; http://www.nongnu.org/geiser/geiser_3.html#First-aids (if (string= Info-current-node "Top") "http://www.nongnu.org/geiser/" (let ((node (replace-regexp-in-string " " "-" Info-current-node)) (number (save-excursion (goto-char (point-min)) (re-search-forward "^[0-9]") (match-string 0)))) (format "http://www.nongnu.org/geiser/geiser_%s.html#%s" number node))))) ("gawk" . "https://www.gnu.org/software/tar/manual/html_node/%s") ;; GNU info documents. Taken from my memory or see https://www.gnu.org/software/ (("awk" "sed" "tar" "make" "m4" "grep" "coreutils" "guile" "screen" "libc" "make" "gzip" "diffutils" "wget" "grub") . (lambda (software) (format "https://www.gnu.org/software/%s/manual/html_node/%%s" software))) ("gcc-5" . "https://gcc.gnu.org/onlinedocs/gcc/%s") (("gdb" "stabs") . (lambda (software) (format "https://sourceware.org/gdb/onlinedocs/%s/%%s" software))) ;; Emacs info documents. Taken from `org-info-emacs-documents' (("ada-mode" "auth" "autotype" "bovine" "calc" "ccmode" "cl" "dbus" "dired-x" "ebrowse" "ede" "ediff" "edt" "efaq-w32" "efaq" "eieio" "eintr" "elisp" "emacs-gnutls" "emacs-mime" "emacs" "epa" "erc" "ert" "eshell" "eudc" "eww" "flymake" "forms" "gnus" "htmlfontify" "idlwave" "ido" "info" "mairix-el" "message" "mh-e" "newsticker" "nxml-mode" "octave-mode" "org" "pcl-cvs" "pgg" "rcirc" "reftex" "remember" "sasl" "sc" "semantic" "ses" "sieve" "smtpmail" "speedbar" "srecode" "todo-mode" "tramp" "url" "vip" "viper" "widget" "wisent" "woman") . (lambda (package) (format "https://www.gnu.org/software/emacs/manual/html_node/%s/%%s" package))))) (defun chunyang-org-info-map-anchor-url (node) "Return URL associated to Info NODE." (require 'org) ; for `org-trim' ;; See (info "(texinfo) HTML Xref Node Name Expansion") for the ;; expansion rule (let* ((node (replace-regexp-in-string "[ \t\n\r]+" " " (org-trim node))) (node (mapconcat (lambda (c) (if (string-match "[a-zA-Z0-9 ]" (string c)) (string c) (format "_%04x" c))) (string-to-list node) "")) (node (replace-regexp-in-string " " "-" node)) (url (if (string= node "") "" (if (string-match "[0-9]" (substring node 0 1)) (concat "g_t" node) node)))) url)) (defun chunyang-Info-get-current-node-html () (cl-assert (eq major-mode 'Info-mode)) (let* ((file (file-name-nondirectory Info-current-file)) (node Info-current-node) (html (if (string= node "Top") "" (concat (chunyang-org-info-map-anchor-url node) ".html"))) (baseurl (cl-loop for (k . v) in chunyang-Info-html-alist when (cond ((stringp k) (equal file k)) ((listp k) (member file k))) return (if (stringp v) v (funcall v file))))) ;; Maybe it's a good idea to assuming GNU softwares in this case (cl-assert baseurl nil "Unsupported info document '%s'" file) (format baseurl html))) (defun chunyang-Info-browse-current-node-html () (interactive) (let ((url (chunyang-Info-get-current-node-html))) (browse-url url))) (bind-key "O" #'chunyang-Info-browse-current-node-html Info-mode-map) (defun chunyang-Info-markdown-current-node-html (&optional arg) "ARG will be passed to `Info-copy-current-node-name'." (interactive "P") (let ((description (Info-copy-current-node-name arg)) (link (chunyang-Info-get-current-node-html))) (let ((markdown (format "[%s](%s)" description link))) (kill-new markdown) (message "Copied: %s" markdown)))) ``` If you need the offline HTML manuals, you need to get a local copy, the easiest is goto https://www.gnu.org/software/emacs/manual/elisp.html and click "HTML compressed" to download the HTML manual for Emacs Lisp manual, you need to do the same thing for Emacs manual, then change `chunyang-Info-html-alist` to your local file address. You can also build the HTML manuals from source code, see https://github.com/casouri/emacs-manuals/blob/master/build.sh for example. --- Tags: html, web-browser, manual ---
thread-53272
https://emacs.stackexchange.com/questions/53272
Show effort and clock time in agenda view
2019-10-22T10:44:18.083
# Question Title: Show effort and clock time in agenda view I use Org mode for my to-do list, clocking, and setting effort estimates. I can show the effort estimates for tasks scheduled for today with the columns view and this setting (thanks to this thread): ``` (setq org-columns-default-format "%60ITEM(Task) %TODO %6Effort(Estim){:} %6CLOCKSUM(Clock) %TAGS") ``` Then I call the day's agenda with `C-c a a` and column view with `C-c C-x C-c`. I see a list of tasks with a scheduled or deadline date of today, as well as a sum of the effort estimate: ``` Task | TODO | Estim | Clock | TAGS | ------------------------------------------------------------------------------- Tuesday 22 October 2019 | | 20:25 | | | gtd: 7:00...... Scheduled: Some task | TODO | | 1:00 | | 8:00...... ---------------- ... ``` How can I skip the second step and show the effort estimate and its sum in the agenda view? # Answer > 8 votes A solution to (part) of your problem could be to use the `org-agenda-prefix-format` variable. To insert the effort information before every entry in the agenda and todo list views just put this in your config: ``` (setq org-agenda-prefix-format '((agenda . " %i %-12:c%?-12t%-6e% s") (todo . " %i %-12:c %-6e") (tags . " %i %-12:c") (search . " %i %-12:c"))) ``` This is what the result looks like in the agenda view (00:30 being the effort estimate): ``` waiting: 0:30 In 5 d.: TODO [#A] Weekly planning ``` `org-agenda-prefix-format` has out-of-the-box support for inserting the effort using %e. The clocksum information is harder, since the the sum is calculated on-the-fly when you enter column-mode, so I'm not sure it is possible to have it in the prefix. From the docs: > If any of the columns has a summary type defined (see Column attributes), turning on column view in the agenda visits all relevant agenda files and make sure that the computations of this property are up to date. This is also true for the special ‘CLOCKSUM’ property. Org then sums the values displayed in the agenda. --- Tags: org-mode ---
thread-60891
https://emacs.stackexchange.com/questions/60891
How to sign git commit using VC?
2020-09-29T14:21:03.593
# Question Title: How to sign git commit using VC? I am just wondering how can VC can be used to sign commit using gpg, Currently I am using vc without sign mean I am using `vc-next-action` to perform git commit # Answer vc doesn't know anything about signing commits. magit does, though. If you're willing to have all your commits signed you can set `commit.gpgSign` in your git configuration file. > 2 votes --- Tags: vc ---
thread-60650
https://emacs.stackexchange.com/questions/60650
How to disable remapping by a package
2020-09-14T16:01:42.563
# Question Title: How to disable remapping by a package I recently used a package that overwrote `C-x C-s` to something other than `save`, causing me to lose a lot of work. Is there a way I can advise emacs to check for a blacklist of keybindings that it shouldn't allow to be remapped? Edit: The package in question is (the otherwise excellent) `atomic-chrome`, and this looks to be the offending line: ``` (defvar atomic-chrome-edit-mode-map (let ((map (make-sparse-keymap))) (define-key map (kbd "C-x C-s") 'atomic-chrome-send-buffer-text) (define-key map (kbd "C-c C-c") 'atomic-chrome-close-current-buffer) map) "Keymap for minor mode `atomic-chrome-edit-mode'.") ``` # Answer > 1 votes One solution could be to advise the `define-key` function and check which key is being bound against a block list: ``` (defvar define-key-block-list '("C-x C-s")) (defun define-key-filter (define-key &rest args) (if (cl-member (nth 1 args) define-key-block-list :key 'kbd :test 'equal) (message "Blocked %s from being bound" (key-description (nth 1 args))) (apply define-key args))) (advice-add 'define-key :around #'define-key-filter) (global-set-key (kbd "C-x C-s") (lambda () (interactive) (message "test"))) ;; Blocked C-x C-s from being bound ``` --- Tags: key-bindings, package ---
thread-60876
https://emacs.stackexchange.com/questions/60876
Item not showing in agenda
2020-09-28T16:31:25.657
# Question Title: Item not showing in agenda In my org mode file I have: ``` * TODO [#A] Call UPS 1 <2020-09-25 Fri> * TODO [#A] Call UPS 2 <2020-09-25 Fri> * TODO [#A] Call UPS 3 <2020-09-25 Fri .+1w> ``` But only: `TODO [#A] Call UPS 3` Shows up in the Agenda. However, all 3 TODO's do show up in the Global TODO List. I don't understand why, when all 3 TODO's have the same priority and the same date, that only the one with a repeating date shows up in the Agenda. Any help is appreciated...... Thanks ahead of time. # Answer Suppose that I have a file `foo.org` with the following contents: ``` * TODO [#A] Call UPS 1 <2020-09-25 Fri> * TODO [#A] Call UPS 2 <2020-09-25 Fri> * TODO [#A] Call UPS 3 <2020-09-25 Fri .+1w> ``` and this file is the only file in the agenda file list; and I use the default weekly agenda; and I have set up the agenda keybinding as the manual recommends (i.e. just the following in my init file, so that I don't get tripped up by other settings): ``` (setq org-agenda-files '("/path/to/foo.org")) (setq org-agenda-span 'week) (define-key global-map (kbd "C-c a") #'org-agenda) ``` and I start emacs and construct the agenda with `C-c a a`, then the agenda looks like this: ``` Week-agenda (W40): Monday 28 September 2020 W40 Tuesday 29 September 2020 Wednesday 30 September 2020 Thursday 1 October 2020 Friday 2 October 2020 foo: TODO [#A] Call UPS 3 Saturday 3 October 2020 Sunday 4 October 2020 ``` with just the third item in the Friday, Oct 2 slot, as discussed in the comments. That item shows because it is in the future, whereas the others do not show because they are in the past. If I instead make the agenda a daily agenda by changing the value of `org-agenda-span` in the init file: ``` (setq org-agenda-span 'day) ``` I restart emacs, and get an agenda I see this: ``` Monday 28 September 2020 W40 ``` That's it: none of them is for today's date, so nothing shows up. If I make the agenda monthly with ``` (setq org-agenda-span 'month) ``` restart emacs and show the agenda, I now see this (with most of the empty entries elided to save space): ``` Month-agenda (W40-W44): Monday 28 September 2020 W40 ... Friday 2 October 2020 foo: TODO [#A] Call UPS 3 Saturday 3 October 2020 ... Friday 9 October 2020 foo: TODO [#A] Call UPS 3 Saturday 10 October 2020 ... Friday 16 October 2020 foo: TODO [#A] Call UPS 3 Saturday 17 October 2020 ... Friday 23 October 2020 foo: TODO [#A] Call UPS 3 Saturday 24 October 2020 Sunday 25 October 2020 Monday 26 October 2020 W44 Tuesday 27 October 2020 ``` with just the repeating entry showing every Friday. Finally, if I make the monthly agenda start earlier so that it includes the 09/25 date by adding this to my init file: ``` (setq org-agenda-start-day "-1w") ``` so that the monthly agenda starts one week before today, then restart emacs and get an agenda, I get this (again eliding most of the empty days to keep things short): ``` Month-agenda (W39-W43): Monday 21 September 2020 W39 Tuesday 22 September 2020 ... Friday 25 September 2020 foo: TODO [#A] Call UPS 1 foo: TODO [#A] Call UPS 2 foo: TODO [#A] Call UPS 3 Saturday 26 September 2020 ... Friday 2 October 2020 foo: TODO [#A] Call UPS 3 Saturday 3 October 2020 ... Friday 9 October 2020 foo: TODO [#A] Call UPS 3 Saturday 10 October 2020 ... Friday 16 October 2020 foo: TODO [#A] Call UPS 3 Saturday 17 October 2020 ... ``` Now all of them show up on Fri, Sept. 25 and the third, repeating one shows up every Friday after that. You can also switch time frames interactively: get rid of the customizations except for the `org-agenda-files` one and restart emacs. Then `C-c a a` should give you a weekly agenda, as in the first display above. Pressing `b` moves the time frame back a week; pressing `f` moves forward a week (or a day or a month depending on `org-agenda-span`). The manual is indispensable. For this particular subject, check the chapter on Agenda Views and the section Commands in the Agenda Buffer for all the keys that you can use in the agenda buffer to do various useful things. I hope this answers your question. > 1 votes # Answer Just to summarize the above - my question is "How do I include a non-repeating TODO that has a plain date that is in the past, in today's view of the Agenda?" I believe I found the answer - using a SCHEDULED date vs a plain (Not SCHEDULED nor DEADLINE) date makes a non-repeating item that has a date in the past show in today's Agenda view, with the agenda view showing only today (no past days). This is what I wanted. I have tested this quite a bit so I am pretty confident this will work. If anyone ever wants to test this in future, this may help: ``` * Testme01 - This does NOT show in Agenda for today (2020-09-29), nor in Global list of TODO's <2020-09-28 Mon> * Testme02 - This DOES show in Agenda for today (2020-09-29), but NOT in Global list of TODO's SCHEDULED: <2020-09-28 Mon> ``` @NickD - thanks again for your time and attention and help to this and my other questions :) You are a great help to me and the community. PS I arrived late into our chat and I think by that time you had (understandably) left. > 0 votes --- Tags: org-mode ---
thread-60895
https://emacs.stackexchange.com/questions/60895
Remove everything except match of regexp?
2020-09-29T17:45:25.907
# Question Title: Remove everything except match of regexp? I have a file with a structure like: ``` some text and numbers and a final number: 1.213,31 some other number 1231 and text again some text and a final number: 53,00 something else again a final number: 1.233,54 ``` Now I want to create a file looking like: ``` 1.213,31 53,00 1.233,54 ``` I can use `higlight-regexp` and the regexp `[0-9,.]+$` to match the correct content, but I don't know how to remove the rest of the file or alternatively copy everything higlighted by this regexp into another buffer. So how can I do this? # Answer > 1 votes Just use `query-replace-regexp` with `.*?\([0-9\,\.]+\)$ → \1`. And then `keep-lines` with the same regexp. # Answer > 1 votes > alternatively copy everything \[matching\] this regexp into another buffer. You can do that with `occur` `C-u``M-s``o` `: \([0-9,.]+\)$` `RET` `\1` `RET` Or, if less-specific is fine, just: `C-u``M-s``o` `[0-9,.]+$` `RET` --- Tags: regular-expressions, copy-paste ---
thread-60879
https://emacs.stackexchange.com/questions/60879
Emacs converting spaces to tabs when using X11 primary selection in a terminal window
2020-09-28T20:38:34.213
# Question Title: Emacs converting spaces to tabs when using X11 primary selection in a terminal window When I use emacs in a terminal window on linux, I am often getting spaces unexpectedly converted to tabs when I cut and paste using the X11 primary selection. What reproduces the problem for me is the following: Open a terminal window. (I tested using both lxterminal and aterm.) Start emacs with the -nw option. *Type* the following text character by character on the keyboard: ``` 1234567 1234567 ``` (If you copy and paste it from the stackexchange question, it won't reproduce the problem.) Triple-click on this line of text to copy it to the X11 primary selection. Open a new terminal window, and in that window do `od -a`. Click the middle mouse button to paste the text into the terminal. This is echoed by the od command with an `ht` rather than an `sp`. I'm pretty sure this is emacs doing this, because if I use the lightweight editor mg instead, it doesn't happen. I've also tested that this still happens if I hide my .emacs file, so that it's not resulting from any customizations that I've done there. Can anyone explain how to get rid of this behavior? Update: Gilles' comment shows that this happens at line 265 of this file https://github.com/emacs-mirror/emacs/blob/master/src/cm.c , which has the following code: `if (tabcost < (deltax * tty->Wcm->cc_right)) {` . I would like to find a solution for this problem that doesn't involve my having to make my own private fork of emacs. I would be happy to see an answer that would suggest an approach to doing this by submitting a patch to emacs. Perhaps this behavior could be turned off by setting a certain flag in lisp. If that seems like a reasonable approach, then it would be great to see an answer saying so, and maybe pointing to an example of how well-behaved emacs C code would access such a flag. If I was an emacs maintainer, I would just rip all the code out, because I just don't think this is reasonable behavior for a terminal-based application in the year 2020, but possibly some people depend on this behavior and it would cause problems if it were simply removed. # Answer ### Analysis There's a space in the buffer, but in certain circumstances, when Emacs needs to print a sequence of spaces, it chooses to print a tab instead because that requires writing fewer characters to the terminal. This is what's happening when you insert the characters one by one. It doesn't happen when Emacs is printing the line all in one go, for example when you paste the whole line, or if you scroll away then back (you need to scroll enough to make the line disappear to be sure), or if you switch to another buffer and then back. The decision to print a tab happens deep inside the C code, in `calccost()` in `cm.c`. I don't fully understand how this works: in this particular case, writing one space or writing one tab would have the same effect, but apparently Emacs prefers to write one tab (I can confirm this with Emacs 26.3 on my machine). I can't find a way to disable this behavior from Lisp code. It's parametrized by `tty->Wcm->cc_tab`, `tty->Wcm->cm_usetabs` and `tty->Wcm->cm_tabwidth` (which in some places are written `TabCost (tty)`, `UseTabs (tty)` and `TabWidth (tty)`). As far as I can tell these are derived only from terminal characteristics and can't be influenced by Lisp code. `TabWidth` is read from the `tw` termcap value if present (it isn't on modern Linux, I think it's obsolete), defaulting to 8. `UseTabs` is true if `TabWidth` is 8 on modern Unix-like platforms (`tabs_safe_p`). `TabCost` is calculated from `TabWidth` and `UseTab` so it's no help. So the only way to disable this behavior (without recompiling Emacs) is to convince Emacs that the width of a tab is not 8. ### Workaround: use a terminal that doesn't copy tabs In xterm, unlike the other terminals I tried (lxterminal, gnome-terminal, rxvt), when you copy the line, the clipboard contains a space, not a tab. ### Workaround: redisplay Anything that redraws the screen makes the tab go away, for example `M-x redraw-display` or `C-l` (`recenter-top-bottom`). This works even for a line like `1<TAB>2` where a tab is present in the buffer and a tab would be actually advantageous for display. ### Workaround: tell Emacs that your terminal doesn't support tabs It's a bit complicated for what it does, and it can have a secondary effect in other applications that have behavior based on the terminal name (for example, loss of colors). But you can change your terminal's description to pretend that its tab width is not 8. Any value other than 8 will make Emacs avoid tabs, but I recommend choosing a large value to avoid confusing other applications. Create a file with the following content. I'll call it `my-terminal-descriptions.terminfo`; the name doesn't matter since you only need it once and for all. ``` xterm-256color-notab|xterm with 256 colors avoiding tabs, tw#9999, use=xterm-256color, ``` Run the following command to compile this new terminal description: ``` tic -x my-terminal-descriptions.terminfo ``` Run Emacs with `TERM` set to `xterm-256color-notab`. For example: ``` alias emacs='env TERM=xterm-256color-notab emacs' ``` > 2 votes --- Tags: tabs ---
thread-60903
https://emacs.stackexchange.com/questions/60903
How to force filename completion in shell buffers to use quotes instead of backslashes
2020-09-29T21:26:12.800
# Question Title: How to force filename completion in shell buffers to use quotes instead of backslashes I have a directory with the file `a file name with spaces` and in Emacs I have a bash in a shell buffer. Rhen I type ``` ls a<TAB> ``` and shell mode completes to ``` a\ file\ name\ with\ space ``` However I would like the completion to look like ``` 'a file name with space' ``` How can I achieve this? What function do I have modify? # Answer > 3 votes An interesting question. It's not configurable at all, so I recommend looking at `pcomplete-insert-entry`. This is where the completed text is inserted, and it's what calls `comint-quote-filename`. Note that it handles some fun edge cases that you'll also have to handle. In particular, if there's already a backslash in the buffer then it handles the insertion a little differently so as to avoid ending up with an extra backslash. You'll want to add something similar for quote characters, I'm sure. You'll also probably want to make sure that your changes don't break anything when pcomplete is used in other modes. It's mostly used by eshell, but in principle it can be used with anything that uses comint-mode. --- Tags: shell-mode, quote ---
thread-51620
https://emacs.stackexchange.com/questions/51620
Unicode characters in org-mode tables
2019-07-15T04:51:53.970
# Question Title: Unicode characters in org-mode tables Here's an org-mode table with some unicode math characters in it: Note that the columns don't align. I can manually fix the issue by inserting literal tab characters after each character via `ctrl-q TAB`: It would be nice to have a command that did this, instead of having to manually add sufficient tab characters to each cell. Is there a good way to approach this in elisp? # Answer > 1 votes What's probably happening is that your regular font is missing those glyphs, so they get filled in from another font, which uses a different width. Here's what `M-x describe-char` shows for me when the point is on the `a`: ``` character: a (displayed as a) (codepoint 97, #o141, #x61) preferred charset: ascii (ASCII (ISO646 IRV)) code point in charset: 0x61 ... display: by this font (glyph code) xft:-DAMA-Ubuntu Mono-normal-normal-normal-*-17-*-*-*-m-0-iso10646-1 (#x44) ``` and here's the : ``` character: ∈ (displayed as ∈) (codepoint 8712, #o21010, #x2208) preferred charset: unicode (Unicode (ISO10646)) code point in charset: 0x2208 ... display: by this font (glyph code) xft:-GNU -FreeSans-normal-normal-normal-*-17-*-*-*-*-0-iso10646-1 (#xDC0) ``` --- Tags: org-table, unicode ---
thread-60907
https://emacs.stackexchange.com/questions/60907
exporting table from R
2020-09-30T05:44:09.113
# Question Title: exporting table from R I'm trying to export a table from an R code block and have read Results of Evaluation (The Org Manual) which states that tables can be output with header options of `:exports results :results value table`. To get the table in the correct format I'm using the R package `toOrg` function from orgutils. Unfortunately it doesn't appear to work with this simple example... ``` #+STARTUP: align #+TITLE: Test #+AUTHOR: Me #+PROPERTY: header-args:R :session *org-R* #+PROPERTY: header-args:R :cache yes #+PROPERTY: header-args:R :results graphics #+PROPERTY: header-args:R :width 1024 #+PROPERTY: header-args:R :height 768 #+PROPERTY: header-args:R :tangle yes #+begin_src R :session *org-R* :eval yes :exports none :results output silent library(orgutils) library(tidyverse) #+end_src #+begin_src R :session *org-R* :eval yes :exports both :results value table employee <- c('John Doe','Peter Gynn','Jolie Hope') salary <- c(21000, 23400, 26800) startdate <- as.Date(c('2010-11-1','2008-3-25','2007-3-14')) employ.data <- data.frame(employee, salary, startdate) employ.data %>% toOrg() #+end_src ``` Compiling to HTML I only get the code, no table is shown in the Org buffer itself (figures are shown inline) and no table in the resulting HTML. If I execute just the R code within an R session it prints... ``` > employee <- c('John Doe','Peter Gynn','Jolie Hope') > salary <- c(21000, 23400, 26800) > startdate <- as.Date(c('2010-11-1','2008-3-25','2007-3-14')) > employ.data <- data.frame(employee, salary, startdate) > employ.data %>% toOrg() | employee | salary | startdate | |------------+--------+------------| | John Doe | 21000 | 2010-11-01 | | Peter Gynn | 23400 | 2008-03-25 | | Jolie Hope | 26800 | 2007-03-14 | ``` Really can't see what I'm doing wrong here and any pointers would be gratefully received. # Answer > 2 votes First, two remarks: your example is not perfectly reproducible (you do not import the convenient R library for the `%>%` operator, and there is a typo in the header of your second src block). I don't know whether this explains everything, but this might explain a part of your problem. Not sure of why you need an external R package for such a simple example. Using the standard org mode approach, this just works: ``` #+begin_src R :session *org-R* :exports both :results value table :colnames yes employee <- c('John Doe','Peter Gynn','Jolie Hope') salary <- c(21000, 23400, 26800) startdate <- as.Date(c('2010-11-1','2008-3-25','2007-3-14')) employ.data <- data.frame(employee, salary, startdate) employ.data #+end_src ``` Otherwise, if you really want to use this package, then the result-type should not be a `value`; it should be `raw output` instead. The following src block is perfectly equivalent to the previous one: ``` #+begin_src R :session *org-R* :exports both :results output raw :colnames yes employee <- c('John Doe','Peter Gynn','Jolie Hope') salary <- c(21000, 23400, 26800) startdate <- as.Date(c('2010-11-1','2008-3-25','2007-3-14')) employ.data <- data.frame(employee, salary, startdate) toOrg(employ.data) #+end_src ``` --- Tags: org-export, r ---
thread-60900
https://emacs.stackexchange.com/questions/60900
How to enable mode for all files
2020-09-29T20:49:27.613
# Question Title: How to enable mode for all files What do I put in my `init` to enable a mode for all files? Say I want to have `auto-fill-mode` enabled at all times. I've seen this post and some others, but all are focused on a specific task. I'd like to document a general solution to a common search that uses best practices. # Answer > 1 votes It depends on the mode. In your case you can do: ``` (auto-fill-mode 1) ``` --- Tags: init-file ---
thread-60913
https://emacs.stackexchange.com/questions/60913
package-installed-p vs fboundp
2020-09-30T12:23:32.303
# Question Title: package-installed-p vs fboundp What should I use: ``` (when (package-installed-p 'ivy) (global-set-key (kbd "C-x b") #'ivy-switch-buffer)) ``` or: ``` (when (fboundp 'ivy-switch-buffer) (global-set-key (kbd "C-x b") #'ivy-switch-buffer)) ``` or: ``` (eval-after-load ivy ...) ; haven't tested it yet ``` I try to rebind key based on a package presence. We are in 2021 so it is safe to assume of presence of `package.el` but what if I installed a package from git/hg? **UPDATE** With `fboundp` & compilation of `.emacs` it doesn't redefine key. Works with `package-installed-p` though... I haven't `(ivy-mode +1)` so function definition `ivy-switch-buffer` can be in form of `autoload`... # Answer > 1 votes You should use `eval-after-load` \- the function will not be defined if the package is not loaded, so checking whether it's installed does not help and checking whether the function is defined (the `fboundp` stuff) will not load it. BTW, `ivy` should be quoted in the `eval-after-load` call: ``` (eval-after-load 'ivy (global-set-key (kbd "C-x b") #'ivy-switch-buffer)) ``` That's assuming that the function `ivy-switch-buffer` is defined in a file that provides the symbol `ivy` when loaded. That's usually the last thing done when loading a file: if you check `ivy.el` there should be a `(provide 'ivy)` at the bottom. Alternatively, you can use a file name (in various forms) as argument: ``` (eval-after-load "ivy" ...) ``` Do `C-h f eval-after-load RET` and read the doc string for all the gory details. EDIT: as the OP points out in a comment, `package-installed-p` works *if you call it after calling `package-intiialize`*: `package-initialize` loads the files in `package-load-list`so afterwards, checking whether the package is installed (i.e. it was in `package-load-list`) or whether it is loaded do the same thing. I still prefer `eval-after-load` because it will DTRT without extra conditions, but to each his/her own. --- Tags: package, conditionals ---
thread-60917
https://emacs.stackexchange.com/questions/60917
org-mode and following links to `#+name: target` things
2020-09-30T18:48:44.340
# Question Title: org-mode and following links to `#+name: target` things I have the following in my org-mode buffer: ``` #+name: my-element-name ``` and then I made a link to that: ``` and here is a link to [[my-element-name]]. ``` According to the org-mode manual on internal links, that ought to work, but when I try to following the link with `C-c C-o`, I get an error: `Wrong type argument: stringp, nil`. I'm using org 9.4 from ELPA; I've used edebug on some of the functions and it seems that something isn't working deep inside `org-link-search` but I couldn't figure out where. I see some regexp matching in that function...this seems like something that ought to work. Using NAME instead of "name" didn't make a difference. Is this expected to work? It seems like it. (More generally, what's the difference between "dedicated targets" -- the ones `<<like-this>>` -- versus "named elements" with `#+NAME: some-name-here`?) # Answer A `name` keyword is an "affiliated" keyword: it is affiliated to the following element, so it cannot exist on its own. Try: ``` #+name: my-table | a | b | #+name: my-code-block #+begin_src emacs-lisp (message "foo") #+end_src [[my-table]] [[my-code-block]] ``` If you do `M-x org-lint` in your buffer, you'll see something like this: ``` 6 low Orphaned affiliated keyword: "NAME" 17 high Unknown fuzzy location "my-element-name" ``` > 2 votes --- Tags: org-mode ---
thread-60836
https://emacs.stackexchange.com/questions/60836
Undefined reference when exporting to latex from Org Mode with org-ref
2020-09-25T08:53:40.463
# Question Title: Undefined reference when exporting to latex from Org Mode with org-ref I installed org-ref (via Melpa) to work with my bibliography entries in Org Mode. The installation seemed to be successful. I was able to add a citation with the command C-c \]. When I export to LaTeX with `C-c C-e C-s l o` a .pdf file is produced, but with the warning of an undefined reference. But the bibtex file is found and an entry with the bibtex key is available. Here are my entries in the Emacs startup file (nearly unchanged to the recommended basic settings from the Github page): ``` ;; org-ref (setq reftex-default-bibliography '("~/Documents/Bibliography/references.bib")) ;; see org-ref for use of these variables (setq org-ref-bibliography-notes "~/Documents/Bibliography/notes.org" org-ref-default-bibliography '("~/Documents/Bibliography/references.bib") org-ref-pdf-directory "~/Documents/Bibliography/Bibtex-Pdfs/") (setq bibtex-completion-bibliography "~/Documents/Bibliography/references.bib" bibtex-completion-library-path "~/Documents/Bibliography/Bibtex-Pdfs" bibtex-completion-notes-path "~/Documents/Bibliography/helm-bibtex-notes") ;; open pdf with system pdf viewer (works on mac) (setq bibtex-completion-pdf-open-function (lambda (fpath) (start-process "open" "*open*" "open" fpath))) ;; alternative ;; (setq bibtex-completion-pdf-open-function 'org-open-file) (setq org-latex-pdf-process (list "latexmk -shell-escape -bibtex -f -pdf %f")) (require 'org-ref) ``` An excerpt from my org mode file: ``` ** Installed version - emax64-26.3-20191225 cite:Freeman2015 - [[https://github.com/m-parashar/emax64][m-parashar / emax64]] ``` And the entry in the BibTeX File: ``` % Encoding: UTF-8 @Book{Freeman2015, author = {Freeman, Eric}, editor = {Freeman, Eric [Verfasser/in] and Robson, Elisabeth [Verfasser/in] and Sierra, Kathy [Verfasser/in] and Bates, Bert and Schulten, Lars and Buchholz, Elke}, publisher = {O'Reilly Verlag}, title = {Entwurfsmuster von Kopf bis Fuß}, year = {2015}, address = {[Erscheinungsort nicht ermittelbar]}, isbn = {9783955619879}, note = {1 Online-Ressource}, file = {:Freeman2015_EntwurfsmusterVonKopfBisFuss.pdf:PDF}, groups = {Erzeugungsmuster}, keywords = {Entwurfsmuster. Java 8. Software-Design}, language = {Deutsch}, url = {http://www.content-select.com/index.php?id=bib_view&ean=9783955619879}, } @Comment{jabref-meta: databaseType:bibtex;} @Comment{jabref-meta: grouping: 0 AllEntriesGroup:; 1 StaticGroup:Erzeugungsmuster\;0\;1\;0x8a8a8aff\;\;\;; } ``` Thanks to NickD for his hint. My bibliography link which is necessary for LaTeX export how Tyler mentioned. Perhaps the problem can be found here. ``` * Bibliographie <<bibliography>> [[bibliography:../../Documents/Bibliography/references.bib]] ``` # Answer Make sure you have a bibliography link in your document. Even with a defined default bibliography you need this for LaTeX export: # Citations > org-ref uses the bibliography link to determine which bibtex files to get citations from, and falls back to the bibtex files defined in the variable reftex-default-bibliography or org-ref-default-bibliography if no bibliography link is found. **Note that you must include a bibliography link in your document if you are exporting your document to pdf**; org-ref-default-bibliography is not used by the LaTeX exporter. See also discussion here and here > 0 votes # Answer I found a solution. I have to add an citation style too. For example\> ``` <<bibliographystyle link>> [[bibliographystyle:unsrt]] ``` > 0 votes --- Tags: org-mode, org-export, org-ref ---
thread-60924
https://emacs.stackexchange.com/questions/60924
How to add function call highlighting in ESS?
2020-10-01T02:58:14.873
# Question Title: How to add function call highlighting in ESS? I currently have some syntax highlighting in my ESS code (e.g., for brackets, `=`, and strings). I would like to add highlighting of function calls, like RStudio's "Highlight R function calls" option. How can I do this? # Answer > 4 votes `ess-R-font-lock-keywords` is a user option that is mentioned in the ESS manual as: > Font-lock patterns for ESS R programming mode. (There is a corresponding ess-S-font-lock-keywords for S buffers.) The default value highlights function names, literals, assignments, source functions and reserved words. Example configuration: ``` (setq ess-R-font-lock-keywords '((ess-R-fl-keyword:keywords . t) (ess-R-fl-keyword:constants . t) (ess-R-fl-keyword:modifiers . t) (ess-R-fl-keyword:fun-defs . t) (ess-R-fl-keyword:assign-ops . t) (ess-R-fl-keyword:%op% . t) (ess-fl-keyword:fun-calls . t) (ess-fl-keyword:numbers) (ess-fl-keyword:operators . t) (ess-fl-keyword:delimiters) (ess-fl-keyword:=) (ess-R-fl-keyword:F&T))) ``` Setting `ess-fl-keyword:fun-calls` to `t` turns on function call highlighting. I also found out from a stack overflow answer that these can also be set manually through the ESS \> Font Lock submenu. --- Tags: spacemacs, ess, r ---
thread-24646
https://emacs.stackexchange.com/questions/24646
Resolving duplicate ID's in org-mode
2016-07-17T02:51:39.727
# Question Title: Resolving duplicate ID's in org-mode For a variety of reasons it's possible to end up with duplicate heading Id's (manually-set ID conflicts, copy pasta, duplicate files, etc.). When refiling you may get a message ``` WARNING: 17 duplicate IDs found, check *Messages* buffer ``` Followed by a (possibly) long list of locations of duplicate Id's: ``` Duplicate ID "271b2fbe-cb4f-4eb8-86d5-91544028ccae", also in file /home/erik/data.org Duplicate ID "bc7ea3e9-f821-4bee-9ce6-255083721a8a", also in file /home/erik/data.org Duplicate ID "24afb249-8481-46a5-8237-06a0c22295eb", also in file /home/erik/data.org Duplicate ID "6a545fe0-bd19-4523-8a6d-f7500a114f5f", also in file /home/erik/data.org ``` It's fairly simple to kill/copy the id and search through the document to replace duplicate ids, but that is rather onerous. I'm curious what mechanisms are available in org-mode to assist in resolving these or alternatively what people may have come up with to resolve this occasional problem with their own agendas. It looks like the duplicate logic is limited to what is currently baked into `org-id-update-id-locations` and would be easy to extract, but I'd like to hear some other thoughts before I write a helper. # Answer > 4 votes for `org-id-update-id-locations` ``` (defun my/org-id-update-id-locations (&optional files silent) "Scan relevant files for IDs. Store the relation between files and corresponding IDs. This will scan all agenda files, all associated archives, and all files currently mentioned in `org-id-locations'. When FILES is given, scan these files instead." (interactive) (if (not org-id-track-globally) (error "Please turn on `org-id-track-globally' if you want to track IDs") (let* ((org-id-search-archives (or org-id-search-archives (and (symbolp org-id-extra-files) (symbol-value org-id-extra-files) (member 'agenda-archives org-id-extra-files)))) (files (or files (append ;; Agenda files and all associated archives (org-agenda-files t org-id-search-archives) ;; Explicit extra files (if (symbolp org-id-extra-files) (symbol-value org-id-extra-files) org-id-extra-files) ;; Files associated with live Org buffers (delq nil (mapcar (lambda (b) (with-current-buffer b (and (derived-mode-p 'org-mode) (buffer-file-name)))) (buffer-list))) ;; All files known to have IDs org-id-files))) org-agenda-new-buffers file nfiles tfile ids reg found id seen (ndup 0)) (when (member 'agenda-archives files) (setq files (delq 'agenda-archives (copy-sequence files)))) (setq nfiles (length files)) (while (setq file (pop files)) (unless silent (message "Finding ID locations (%d/%d files): %s" (- nfiles (length files)) nfiles file)) (setq tfile (file-truename file)) (when (and (file-exists-p file) (not (member tfile seen))) (push tfile seen) (setq ids nil) (with-current-buffer (org-get-agenda-file-buffer file) (save-excursion (save-restriction (widen) (goto-char (point-min)) (while (re-search-forward "^[ \t]*:ID:[ \t]+\\(\\S-+\\)[ \t]*$" nil t) (setq id (match-string-no-properties 1)) (if (member id found) (progn ;added logic (if org-clone-delete-id (org-entry-delete nil "ID") (org-id-get-create t)) ;end of added logic (message "Duplicate ID \"%s\", also in file %s" id (or (car (delq nil (mapcar (lambda (x) (if (member id (cdr x)) (car x))) reg))) (buffer-file-name))) (when (= ndup 0) (ding) (sit-for 2)) (setq ndup (1+ ndup))) (push id found) (push id ids))) (push (cons (abbreviate-file-name file) ids) reg)))))) (org-release-buffers org-agenda-new-buffers) (setq org-agenda-new-buffers nil) (setq org-id-locations reg) (setq org-id-files (mapcar 'car org-id-locations)) (org-id-locations-save) ;; this function can also handle the alist form ;; now convert to a hash (setq org-id-locations (org-id-alist-to-hash org-id-locations)) (if (> ndup 0) (message "WARNING: %d duplicate IDs found, check *Messages* buffer" ndup) (message "%d unique files scanned for IDs" (length org-id-files))) org-id-locations))) ``` You will need to run it twice to verify the IDs have been updated. `eval-region` it to try out. I was searching for something similar to this because `org-clone-subtree-with-time-shift` didn't update subheading ids when it clones. The issue was apparent when I ran `org-id-update-locations` because Duplicate id warning will pop up for all the subheadings of the clones. I solved it by adding the following logic. It loops until it runs out of headings and updates the id of the heading. ``` (while (outline-next-heading) (if org-clone-delete-id (org-entry-delete nil "ID") (org-id-get-create t) ) ) ``` The following is the updated `org-clone-subtree-with-time-shift` function. ``` (defun my/org-clone-subtree-with-time-shift(n &optional shift) "Clone the task (subtree) at point N times. The clones will be inserted as siblings. In interactive use, the user will be prompted for the number of clones to be produced. If the entry has a timestamp, the user will also be prompted for a time shift, which may be a repeater as used in time stamps, for example `+3d'. To disable this, you can call the function with a universal prefix argument. When a valid repeater is given and the entry contains any time stamps, the clones will become a sequence in time, with time stamps in the subtree shifted for each clone produced. If SHIFT is nil or the empty string, time stamps will be left alone. The ID property of the original subtree is removed. In each clone, all the CLOCK entries will be removed. This prevents Org from considering that the clocked times overlap. If the original subtree did contain time stamps with a repeater, the following will happen: - the repeater will be removed in each clone - an additional clone will be produced, with the current, unshifted date(s) in the entry. - the original entry will be placed *after* all the clones, with repeater intact. - the start days in the repeater in the original entry will be shifted to past the last clone. In this way you can spell out a number of instances of a repeating task, and still retain the repeater to cover future instances of the task. As described above, N+1 clones are produced when the original subtree has a repeater. Setting N to 0, then, can be used to remove the repeater from a subtree and create a shifted clone with the original repeater." (interactive "nNumber of clones to produce: ") (unless (wholenump n) (user-error "Invalid number of replications %s" n)) (when (org-before-first-heading-p) (user-error "No subtree to clone")) (let* ((beg (save-excursion (org-back-to-heading t) (point))) (end-of-tree (save-excursion (org-end-of-subtree t t) (point))) (shift (or shift (if (and (not (equal current-prefix-arg '(4))) (save-excursion (goto-char beg) (re-search-forward org-ts-regexp-both end-of-tree t))) (read-from-minibuffer "Date shift per clone (e.g. +1w, empty to copy unchanged): ") ""))) ;No time shift (doshift (and (org-string-nw-p shift) (or (string-match "\\`[ \t]*\\([+-]?[0-9]+\\)\\([dwmy]\\)[ \t]*\\'" shift) (user-error "Invalid shift specification %s" shift))))) (goto-char end-of-tree) (unless (bolp) (insert "\n")) (let* ((end (point)) (template (buffer-substring beg end)) (shift-n (and doshift (string-to-number (match-string 1 shift)))) (shift-what (pcase (and doshift (match-string 2 shift)) (`nil nil) ("d" 'day) ("w" (setq shift-n (* 7 shift-n)) 'day) ("m" 'month) ("y" 'year) (_ (error "Unsupported time unit")))) (nmin 1) (nmax n) (n-no-remove -1) (org-id-overriding-file-name (buffer-file-name (buffer-base-buffer))) (idprop (org-entry-get beg "ID"))) (when (and doshift (string-match-p "<[^<>\n]+ [.+]?\\+[0-9]+[hdwmy][^<>\n]*>" template)) (delete-region beg end) (setq end beg) (setq nmin 0) (setq nmax (1+ nmax)) (setq n-no-remove nmax)) (goto-char end) (cl-loop for n from nmin to nmax do (insert ;; Prepare clone. (with-temp-buffer (insert template) (org-mode) (goto-char (point-min)) (org-show-subtree) (and idprop (if org-clone-delete-id (org-entry-delete nil "ID") (org-id-get-create t))) (while (outline-next-heading) (and idprop (if org-clone-delete-id (org-entry-delete nil "ID") (org-id-get-create t))) ) (goto-char (point-min)) (unless (= n 0) (while (re-search-forward org-clock-line-re nil t) (delete-region (line-beginning-position) (line-beginning-position 2))) (goto-char (point-min)) (while (re-search-forward org-drawer-regexp nil t) (org-remove-empty-drawer-at (point)))) (goto-char (point-min)) (when doshift (while (re-search-forward org-ts-regexp-both nil t) (org-timestamp-change (* n shift-n) shift-what)) (unless (= n n-no-remove) (goto-char (point-min)) (while (re-search-forward org-ts-regexp nil t) (save-excursion (goto-char (match-beginning 0)) (when (looking-at "<[^<>\n]+\\( +[.+]?\\+[0-9]+[hdwmy]\\)") (delete-region (match-beginning 1) (match-end 1))))))) (buffer-string))))) (goto-char beg))) ``` # Answer > 2 votes `M-x org-delete-property-globally` did the trick for me, once I knew which file had the messy IDs. --- Tags: org-mode ---
thread-60871
https://emacs.stackexchange.com/questions/60871
Defining a time slot in Org Agenda
2020-09-28T09:50:48.110
# Question Title: Defining a time slot in Org Agenda When in Org Agenda `C-S` on a task allows to set a date and a time, like for example `SCHEDULED: <2020-10-20 mar. 10:00>`. I'd like to set a time slot (e.g. from 10:00 to 12:00) instead of an hour (e.g. 10:00). # Answer > 1 votes Simply write `<2020-10-20 mar. 10:00-12:00>` instead. If you have the timegrid enabled you'll even be able to see the time span. --- Tags: org-mode, org-agenda ---
thread-60927
https://emacs.stackexchange.com/questions/60927
Org mode make an inactive todo item active on a specific date
2020-10-01T06:08:12.507
# Question Title: Org mode make an inactive todo item active on a specific date I'm using org mode to keep track of my schoolwork at university right now, a feature I really like is being able to schedule recurring items since many classes have homework be due on the same day of each week. What I'm wondering is, is it possible to specify when a todo item becomes "activated" or shows up in my agenda? For example, one of my classes has a quiz that's due every Friday but it only gets released every Monday. What I'd love to do is somehow program a todo item that's due on one day (an upcoming Friday for example) but remains "inactive" until the Monday so it's not cluttering my agenda on days where working on it is impossible. I've heard that the way Org mode would have us think about scheduled items isn't strictly intuitive but I'm hoping there's a feature somewhere for this use case. Thanks! # Answer If you write ``` * TODO Quiz DEADLINE: <2020-10-09 -5d> ``` on, Monday 2020-10-05, you should get some thing like ``` task: In 4 d.: TODO Quiz ``` in your agenda. Note that this will only appear on Monday. If on Sunday you look at the agenda for the next day, this entry will not appear. > 2 votes --- Tags: org-mode, org-agenda ---
thread-60822
https://emacs.stackexchange.com/questions/60822
How to specify prefix argument in key binding
2020-09-24T04:41:11.033
# Question Title: How to specify prefix argument in key binding The description of `C-x C-e` mentions: > ...Interactively, with a non '-' prefix argument, print output into current buffer. I understand this to mean this logic is triggered when I issue `C-u C-x C-e`, but how would I bind this to `C-c c`? How do I specify the prefix in the binding? Same for `C-SPC`: > With prefix argument (e.g., C-u C-SPC), jump to the mark, and set the mark from position popped off the local mark ring (this does not affect the global mark ring). My normal binding looks like this: ``` (global-set-key (kbd "C-c ,") 'pop-global-mark) ``` # Answer > 6 votes `C-u` invokes the function `universal-argument`, and you want to ensure that `eval-last-sexp` is called as if you invoked it interactively, which is done with `call-interactively`. You can simulate `universal-argument` by let-binding `current-prefix-arg`. Putting that all together for `C-u C-x C-e`: ``` (global-set-key (kbd "C-c c") (lambda () (interactive) (let ((current-prefix-arg 1)) (call-interactively #'eval-last-sexp)))) ``` For `C-u C-SPC`: ``` (global-set-key (kbd "C-c ,") (lambda () (interactive) (let ((current-prefix-arg '(4))) (call-interactively #'set-mark-command)))) ``` Strictly speaking, as @NickD points out, `current-prefix-arg` should be bound to `'(4)` to be exactly equivalent to `C-u`, but for `eval-last-sexp` that doesn't matter. # Answer > 0 votes @rpluim gives us the answer and inspires me to produce this handy-dandy Lisp macro. (I'm only presenting it as an "answer" to get the formatting) ``` (cl-defmacro ph/defprefixed (command &key (prefix 4) no-read-only) `(defun ,(intern (format "ph/prefixed-%s" command)) () ,(format "Execute `%s' with prefix argument." command) (interactive ,(when no-read-only "*")) (let ((current-prefix-arg (list ,prefix))) (call-interactively (function ,command))))) ``` Used thus: ``` (ph/defprefixed set-mark-command) ``` it expands to this: ``` (defun ph/prefixed-set-mark-command () "Execute `set-mark-command' with prefix argument." (interactive nil) ; nil is ignored (let ((current-prefix-arg (list 4))) (call-interactively (function set-mark-command)))) ``` And thus: ``` (ph/defprefixed eval-last-sexp :no-read-only t) ``` Expansion: ``` (defun ph/prefixed-eval-last-sexp () "Execute `eval-last-sexp' with prefix argument." (interactive "*") (let ((current-prefix-arg (list 4))) (call-interactively (function eval-last-sexp)))) ``` --- Tags: key-bindings, prefix-argument ---
thread-60929
https://emacs.stackexchange.com/questions/60929
How to avoid own address in Cc with `gnus-summary-followup`
2020-10-01T08:14:42.843
# Question Title: How to avoid own address in Cc with `gnus-summary-followup` I receive an email sent also to other people in Cc. If I reply to it with `gnus-summary-followup`, Gnus includes me in the Cc list. How can I avoid that? # Answer > 1 votes The behaviour you want is the default if you've told emacs your email address using `user-mail-address`. Another option is to set `message-dont-replyto-names` ``` message-dont-reply-to-names is a variable defined in `message.el'. Its value is nil You can customize this variable. This variable was introduced, or its default value was changed, in version 24.3 of Emacs. Documentation: Addresses to prune when doing wide replies. This can be a regexp, a list of regexps or a predicate function. Also, a value of nil means exclude `user-mail-address' only. If a function email is passed as the argument. ``` See Wide-Reply for more details (or `(info "(message)Wide Reply")`) --- Tags: gnus, email ---
thread-39396
https://emacs.stackexchange.com/questions/39396
Rebind TAB to show help in counsel minibuffer
2018-03-13T00:48:21.503
# Question Title: Rebind TAB to show help in counsel minibuffer I'm in the process of migrating from helm to ivy/counsel, and I would like to replicate a binding that I had in my previous setup. When browsing the results minibuffer (for example in `counsel-M-x`), I would like to have the help for the current result displayed when pressing `TAB`. To get help currently I need to do `M-o h`. Since this is an ivy action, I'm not sure how to add a key binding to just TAB. # Answer I've found the solution, `(intern (ivy-state-current ivy-last))` will return the symbol of the current ivy result, which I can then pass to `describe-function` or `describe-variable`. ``` (defun counsel-describe-function-or-variable () "Display help about the currently selected ivy result. Assumes the symbol is a function and tries with a variable describe-function fails." (interactive) (let ((inhibit-message t) (current-symbol (intern (ivy-state-current ivy-last)))) (condition-case nil (describe-function current-symbol) ('error (describe-variable current-symbol))))) (define-key counsel-describe-map (kbd "TAB") 'counsel-describe-function-or-variable) ``` I didn't find a way to properly distinguish between `counsel-describe-variable` and the rest of the describe commands, so I catch the error and try `describe-variable` when `describe-function` fails. > 3 votes # Answer I have adapted your answer and extend it to toggle *Help* window (helpful when we want it gone from the screen without leaving the minibuffer) and perform Ivy's native TAB (albeit with one more key stroke). ``` ;;;###autoload (defun my-ivy-toggle-help/tab (&rest _args) "Either describe current symbol or perform partial complete. If last command is `self' and \"*Help*\" window is shown, delete it; else describe current symbol. Ivy's native 2nd <TAB> is performed at the 3rd one." (interactive) (let ((help-window (get-buffer-window "*Help*")) (symbol (intern (ivy-state-current ivy-last)))) (if (equal last-command 'my-ivy-toggle-help/tab) (if help-window (with-selected-window help-window (quit-window)) (ivy-partial-or-done)) (describe-symbol symbol)))) ``` > 1 votes --- Tags: key-bindings, ivy, counsel ---
thread-60942
https://emacs.stackexchange.com/questions/60942
Which setting controls the replacing of selection with the character we type?
2020-10-02T02:34:25.437
# Question Title: Which setting controls the replacing of selection with the character we type? When wanting to replace a region of text with another, I usually mark them with `C-SPC` (`set-mark-command`), press some arrow/movement keys, then type the text that I want. To illustrate: ``` I like biscuits. ``` Say I want to replace `like` with `love` and my cursor is at the letter `l`. I press `C-SP M-f`, then type `love`. Usually this works with no problem. But sometimes, after I accidentally press some combination of keys, a setting changes and when I type `l`, the selected `like` is not replaced. My question is, which setting is this? # Answer > 0 votes What happens when `like` is not replaced? Is the letter you typed inserted at the cursor (which is then after the `e` in `like`)? A guess is that you've somehow toggled Delete-Selection mode: turned it off instead of on. When the mode is on and the region is active (i.e., text is selected/highlighted), text you type replaces the selected text. When off, text you type is inserted at the cursor. Do you see the same thing when you start Emacs with `emacs -Q` (no init file)? By default, Delete-Selection mode is off. Probably something in your init file is probably turning Delete-Selection mode on, and then you are likely doing something that turns it off. Maybe the command that toggles the mode on/off, which is `delete-selection-mode`, is bound to some key that you sometimes hit accidentally. To find out, use `C-h w` (command `where-is`), and type `delete-selection-mode` at the prompt. It will tell you which key, if any, that command is bound to. If this doesn't help, you may need to provide more info about what you use in your init file. Try to provide a step-by-step recipe, starting from `emacs -Q`, to reproduce the problem. --- For more info about `delete-selection-mode`: `C-h f delete-selection-mode`. --- Tags: text-editing ---
thread-60947
https://emacs.stackexchange.com/questions/60947
emacs lisp manual
2020-10-02T11:21:50.197
# Question Title: emacs lisp manual What does this text mean, in node `Simple Lambda Expression Example` of the Emacs Lisp manual: > As these examples show, you can use a form with a lambda expression as its car to make local variables and give them values. In the old days of Lisp, this technique was the only way to bind and initialize local variables. But nowadays, it is clearer to use the special form `let` for this purpose The use of `let` is clear to me, but what does car have to do with this? # Answer The application of a lambda expression was used to populate the local variables in the expression, so for example what you can today write as ``` (let ((x 12)) (message (number-to-string (- (* 4 x) (/ x 2))))) ``` you wrote as ``` ((lambda (x) (message (number-to-string (- (* 4 x) (/ x 2))))) 12) ``` The lambda expression is the car of the whole form. > 3 votes --- Tags: help, manual ---
thread-60829
https://emacs.stackexchange.com/questions/60829
When a heading is DONE, I don't see the link
2020-09-24T17:11:41.113
# Question Title: When a heading is DONE, I don't see the link I am using: * Spacemacs: 0.200.13 * Org: 9.4 I have set org-fontify-done-headline to nil (Original value was t), to no avail. Desired result: Link is displayed as it is in TODO\_NEXT state. # Answer > 1 votes In a recent thread in the Org mode mailing list, Kyle Meyer had this to say: > In v9.4, the default of org-fontify-done-headline changed to t, which results in the org-headline-done face applied. You can set it to nil to restore the previous behavior. So you might try ``` (setq org-fontify-done-headline nil) ``` in your .emacs and see if that works for you. --- Tags: org-mode, spacemacs ---
thread-60954
https://emacs.stackexchange.com/questions/60954
Regex for the last line of a string
2020-10-02T15:37:13.317
# Question Title: Regex for the last line of a string I'm trying to search for the last line in a string (lines separated by `\n`) using string match but I cannot make it work as intended. The code below evaluates to 0 while I would have expected 4. I guess my regex is wrong (it was supposed to be a newline (`\n`) followed by anything but a newline (`.*`) until the end of the string (`$`). ``` (string-match "\n.*$" "\n \n \n ") ``` # Answer > 8 votes `$` matches at the end of a line, not the end of a string. If you want to match at the end of a string you need to use the `\'` operator: ``` (string-match "\n.*\\'" "\n \n \n ") => 4 ``` See `(info "(elisp)Regexp Backslash")` for more details (or Regexp-Backslash) --- Tags: regular-expressions, string ---
thread-60841
https://emacs.stackexchange.com/questions/60841
Can I set up the org-mode #+OPTIONS: differently for different export targets?
2020-09-25T17:18:12.373
# Question Title: Can I set up the org-mode #+OPTIONS: differently for different export targets? I would like to set the `#+OPTIONS:` settings in an `org-mode` file to behave differently if the `org-mode` file is exported to `HTML` or to `PDF`. More precisely, I would like to have control of * the **table of contents**, * the **numbering of the sections** and * the **depth of the headers**. I would like to setup my `org-mode` document such that the behaviour is different if I export the same file to different format: * For PDF export `C-c C-e l p`, no table of contents, the sections numbered: ``` #+OPTIONS: toc:nil num:t H:7 ``` * For HMTL export `C-c C-e h h`, with table of contents, the sections not numbered: ``` #+OPTIONS: toc:2 num:nil H:4 ``` How can I do this? # Answer > 2 votes EDIT 2021-04-05): there is a better solution, based on an idea of Juan Manuel Macías on the Org mode mailing list. It is based on macro expansion and the fact that you can evaluate arbitrary Lisp code in the macro definition. The details are presented in this Emacs SE question: Can org options be applied to specific export modes only?. --- Here is one possible solution that uses the `#+INCLUDE:` mechanism. Another possible option is (probably) an options filter, but I have not investigated that. The idea is to have an Org mode file like this: ``` #+INCLUDE: opts.<SUFFIX> * Links https://emacs.stackexchange.com/questions/60841/can-i-setup-the-orgmode-options-differently-for-different-export-targets * Foo foo ** bar bar *** baz baz **** hunoz hunoz ***** hukerz hukerz ``` and a bunch of options files, one for each possible export backend: `opts.html` ``` #+OPTIONS: toc:2 num:nil H:4 ``` `opts.latex`: ``` #+OPTIONS: toc:nil num:t H:7 ``` etc. The trick is to then replace the `<SUFFIX>` with the relevant backend at the time you export. `org-export-as`, the main function that gets called when you are exporting a file, does things in a definite order: * include file processing * macro expansion * babel processing * options filters * pruning of tree * parse-tree filters * collect properties * transcode tree * final output filters The point is that you cannot use later things to change earlier things, since the earlier things are already done. Since the includes are processed first, we cannot use any of the other mechanisms to change the suffix. Fortunately, there are various hooks that are applied at specific times during the export process. One such hook is `org-export-before-processing-hook`, which is the first thing that is done, *before* the `include file processing` step. This hook is a list of functions (as is any hook), but the functions in this hook are expected to take a single argument: the export backend. The hook runs through the list and calls each function with the current export backend. Perfect! All we need to do is define a function that does the edit of the `#+INCLUDE:` line and add it to the hook, like this: ``` (defun ndk/org-export-edit-suffix (backend) (replace-string "opts.<SUFFIX>" (format "opts.%s" backend))) (add-hook 'org-export-before-processing-hook #'ndk/org-export-edit-suffix) ``` and we are done. When you export to HTML, the backend is "html" and we include `opts.html` and when you export to PDF, the backend is "latex" and we include `opts.latex`. One obvious caveat: make sure that you do not have another instance of the replacement string `opts.<SUFFIX>` in your file or it will be modified as well. You can make the `replace-string` arguments longer to match e.g. the whole `#+INCLUDE:` line, if that is a problem. # Answer > 1 votes The solution given by @NickD is correct. A solution that would work also for nested org files would be using macros (see related question and the macros defined by fniessen). In a test case where the content `main.org` is separated from the settings `header.org`, one can export differently for different backends as follows: * In the content file `main.org`, the settings are "#+INCLUDED": ``` #+INCLUDE: headers.org * The first section Contents here ``` * The backend dependent settings are included in `headers.org` using macros: ``` #+MACRO: if-latex-else (eval (if (org-export-derived-backend-p org-export-current-backend 'latex) "#+OPTIONS: toc:nil H:7 num:t" "#+OPTIONS: toc:2 num:nil H:4")) {{{if-latex-else}}} ``` --- Tags: org-mode, org-export ---
thread-60922
https://emacs.stackexchange.com/questions/60922
Efficiently calling multiple variants of the grep command
2020-09-30T23:14:35.430
# Question Title: Efficiently calling multiple variants of the grep command # The context I commonly execute the following variants of the `grep` command * `grep --color -RHIn ''` (search in the current working directory) * `grep --color -RHIn --include='*.org' '' ~/repos/dotfiles/emacs` (search in all the Org files present in a directory that contains configurations of other Emacs users) * `grep --color -RHIn --include='init.el' ~/repos/dotfiles/emacs` (search in all `init.el` files located in the directory mentioned above) * `grep --color -RHIn --include='*.org' --include='*.el' '' ~/repos/dotfiles/emacs` (search in all `.el` and `.org` files files located in the directory mentioned above) Whenever I want to use one of thoose variants, I press `M-x grep` and manually type them. I'm looking for ways which can help me avoid manually typing those variants whenever I want to execute any of those # Additional context I've tried the following ``` (let ((grep-command "grep --color -RHIn ''")) (call-interactively grep)) (let ((grep-command "grep --color -RHIn --include='*.org' '' ~/repos/dotfiles/emacs")) (call-interactively grep)) ... ``` The problem with this is that `call-interactively` considers the global value of the variable `grep-command` instead of the one provided by `let`. If this worked, then I would only need to do ``` ; Variant 1 (global-set-key (kbd "C-x g 1") (let ((grep-command "grep --color -RHIn ''")) (call-interactively grep))) ; Variant 2 (global-set-key (kbd "C-x g 2") (let ((grep-command "grep --color -RHIn --include='*.org' ''")) (call-interactively grep))) (... more variants) ``` # The question Do you know a better way to automate this so that I don't have to manually type any of the `grep` variants? Is there a package that would display something like a menu that would show a menu item with a description for each variant such that when an item is selected, `grep` is executed with the corresponding variant of the selected item? If you don't have any idea, I would really appreciate if you could explain how I can make a command (`(call-interactively 'grep)`, in this scenario) to consider the value of a variable provided by `let`. # Answer The O.P. may be interested in the `hydra` library by Abo-Abo: https://github.com/abo-abo/hydra Here is a custom example that does not rely upon `hydra` to select from pre-defined choices. The letter `c` at the beginning of the `interactive` statement is an interactive code: https://www.gnu.org/software/emacs/manual/html\_node/elisp/Interactive-Codes.html There may be a better way to get a preferred default command line as the first choice in the minibuffer that does not involve let-binding `grep-host-defaults-alist` to `nil`, but this seems to work: ``` ;;; Needed so that `pick-a-grep' works correctly the first time it is tried; ;;; otherwise, the let-bound `grep-command' gets ignored the first time around. (require 'grep) (defun pick-a-grep (choice) "Choices for selecting from pre-defined `grep-command'." (interactive "c[3] is one too many. | [D]o you like eggs?") (cond ((eq choice ?3) (let ((grep-host-defaults-alist nil) (grep-command "grep --color -RHIn ''")) (call-interactively 'grep))) ((eq choice ?D) (let ((grep-host-defaults-alist nil) (grep-command "grep --color -RHIn --include='*.org' '' ~/repos/dotfiles/emacs")) (call-interactively 'grep))) (t (message "You did not select any of the expected choices.")))) ``` > 2 votes # Answer As suggested in the answer of @lawlist, you can accomplish this with the hydra package. ``` (require 'grep) (global-set-key (kbd "C-. g") (defhydra hydra-grep-variants (:color blue) " _r_: Search recursively _co_: Search configurations (*.org) _ce_: Search configurations (*.el) _cm_: Search configurations (*.org, *.el) " ("r" (let ((grep-host-defaults-alist nil) (grep-command "grep --color -RHIn '' .")) (call-interactively 'grep))) ("co" (let ((grep-host-defaults-alist nil) (grep-command "grep --color -RHIn --include='*.org' '' ~/SourceCode/dotfiles/emacs")) (call-interactively 'grep))) ("ce" (let ((grep-host-defaults-alist nil) (grep-find-command (concat "find " path/configs " -type f -name '*.el' ! -path '*/elpa/*' -exec grep --color -HIn '' {} +"))) (call-interactively 'find-grep))) ("cm" (let ((grep-host-defaults-alist nil) (grep-find-command (concat "find " path/configs " -type f \\( -name '*.org' -o -name '*.el' \\) ! -path '*/elpa/*' -exec grep --color -HIn '' {} +"))) (call-interactively 'find-grep))))) ``` Just press `C-. C-g {key}` to choose a `grep` variant. > 0 votes --- Tags: commands, grep ---
thread-60886
https://emacs.stackexchange.com/questions/60886
How to customize scrolling for any action that moves the point?
2020-09-29T08:06:51.407
# Question Title: How to customize scrolling for any action that moves the point? Say I have an action that moves the point (adds 100 to it for example). It should be possible to wrap this with a function or macro that gives additional behavior, eg: ``` (global-set-key (kbd "<f5>") 'move-point-plus-100) ``` Say I want to animate the motion with smooth scrolling and recenter the view. This should be possible using a macro, for example. ``` (global-set-key (kbd "<f5>") (with-fancy-scroll-motion 'move-point-plus-100)) ``` Then I can separate scrolling behavior from the actions that move the point, allowing for separate configuration & control. Does something like this exist already? Or would it need to be written? --- * I'm aware of scroll locking & smooth scroll mode, but I'd rather have the ability to apply this per key binding, then adding a global mode which might run when I don't want it to. # Answer Since I couldn't find any existing packages that did this, I wrote my own: scroll-on-jump. This defines macros and utilities to advise existing functions to have customized scrolling behavior on jump. See demo video. > 0 votes --- Tags: motion, scrolling ---
thread-60970
https://emacs.stackexchange.com/questions/60970
How to replace focus-out-hook with after-focus-change-function in emacs 27?
2020-10-03T12:29:56.580
# Question Title: How to replace focus-out-hook with after-focus-change-function in emacs 27? In my old emacs, I have defined the following code. ``` (add-hook 'focus-out-hook (lambda () (save-some-buffers t))) ``` After upgrade to emacs 27, it said focus-out-hook is obsoleted, and the new one is after-focus-change-function, but simply replace it doesn't work. The following doesn't work ``` (add-hook 'after-focus-change-function (lambda () (save-some-buffers t))) ``` Looks to me the first is a hook, so need to use add-hook, but for the new function to work, how to use it? My purpose is to save a buffer after I switch to another app. # Answer You could try using something like: ``` (add-function :after after-focus-change-function #'your-function-here) ``` So, in your case, something like this should do what you are after: ``` (add-function :after after-focus-change-function (lambda () (save-some-buffers t))) ``` If you look at the documentation of `after-focus-change-function` with `C-h v after-focus-change-function RET`, you will notice that it suggests to use `add-function` to modify it: > \[...\] Code wanting to do something when frame focus changes should use `add-function` to add a function to this one \[...\] Note also that the documentation suggests that your function should call `frame-focus-state` to retrieve the last known focus state of each frame, so you could do something like: ``` (add-function :after after-focus-change-function (lambda () (unless (frame-focus-state) (save-some-buffers t)))) ``` Note that `frame-focus-state` returns `nil` when the selected frame is not focused. > 8 votes --- Tags: hooks, functions, obsolete ---
thread-60963
https://emacs.stackexchange.com/questions/60963
disable table mode using either #+BEGIN_EXAMPLE or ‘:’ literal line , but insert latex math block $ ... $
2020-10-02T23:02:04.787
# Question Title: disable table mode using either #+BEGIN_EXAMPLE or ‘:’ literal line , but insert latex math block $ ... $ I’m trying to typeset a grammar in org markup, but want to use latex symbols in the grammar: ``` a -> hello | $\neg$ world | universe ``` • Now, without using `#+BEGIN_EXAMPLE` or `:` literal-line prefix, the `|` syntax gets interpreted as a table. • The issue is that using either solution **causes the Math latex statement to no longer be recognized.** Thanks # Answer Unfortunately there is no way to escape `|`. The usual suggestion is to use `\vert` instead of `|`. That will become a vertical bar in exported PDF output, although it will certainly not look pretty in the buffer itself. But it does solve the problem of Org mode interpreting `|` as a table starter and it will not affect use of LaTeX fragments in your file. This is also the suggested workaround when you want to include a vertical bar in the text of an entry in a table - see e.g. this question. > 0 votes --- Tags: org-mode, org-export, spacemacs, latex, org-table ---
thread-60967
https://emacs.stackexchange.com/questions/60967
how to find number of arguments expected by an elisp function in emacs
2020-10-03T06:42:49.473
# Question Title: how to find number of arguments expected by an elisp function in emacs I have some code that I use in my .emacs file that works with version 25.5 where the definition of windows--sanitize-window-sizes looks something like this: ``` (defun window--sanitize-window-sizes (frame horizontal) ;; emacs 25.5 ``` That I want to make work both there and in emacs 27.1 where the definition of windows--sanitize-window-sizes looks something like this: ``` (defun window--sanitize-window-sizes (horizontal) ;; emacs 27.1 ``` So, how do I check in my calling function how many arguments the function expects, what do I write to ask this question, as in: ``` (cond ((not (fboundp 'window--sanitize-window-sizes)) t ; no function to call, assume sizes ok ) ((= (max-number-of-arguments 'window--sanitize-window-sizes) 1) ;; probably something like (cdr (arguments-accepted 'window--sanitize-window-sizes)) (window--sanitize-window-sizes size) ; 27.1 expects only size ) (t (window--sanitize-window-sizes frame size) ; 25.5 expects only size ) ) ``` I presume there is a function I can apply to a symbol that tells me how many arguments are expected (min max) or maybe something more complex to handle `&optional` and `&rest` cases. # Answer 2nd Edit: Turns out there is a builtin, `func-arity`. It works exactly like the `lambda-arity` included below. Might be worth checking if it's defined in your emacs 25 though. 1st Edit: having re-read your use-case, maybe just do `(if (< (string-to-number emacs-version) ...` instead. --- Not built-in, no. There's `help-function-arglist` which returns the signature, such as `(arg1 &optional arg2 &rest args)`. Luckily, EmacsWiki has a parser for this, relevant code extracted from https://www.emacswiki.org/emacs/parser-fn.el ``` (require 'help-fns) (defun lambda-arity (function) "Return minimum and maximum number of args allowed for FUNCTION. FUNCTION must be a symbol whose function binding is a lambda expression or a macro. The returned value is a pair (MIN . MAX). MIN is the minimum number of args. MAX is the maximum number or the symbol `many', for a lambda or macro with `&rest' args." (let* ((arglist (help-function-arglist function)) (optional-arglist (memq '&optional arglist)) (rest-arglist (memq '&rest arglist))) (cons (- (length arglist) (cond (optional-arglist (length optional-arglist)) (rest-arglist (length rest-arglist)) (t 0))) (cond (rest-arglist 'many) (optional-arglist (+ (length arglist) (length optional-arglist) -1)) (t (length arglist)))))) (defun function-arity ( function ) (if (subrp function) (subr-arity function) (lambda-arity function))) ``` > 2 votes # Answer In addition to function `func-arity` (which @Tommy mentioned), there is function `subr-arity`, for functions defined in C source code, not Lisp. `C-h f subr-arity` says: > `subr-arity` is a built-in function in ‘C source code’. > > `(subr-arity SUBR)` > > Return minimum and maximum number of args allowed for `SUBR`. > > `SUBR` must be a built-in function. The returned value is a pair `(MIN . MAX)`. `MIN` is the minimum number of args. `MAX` is the maximum number or the symbol `many`, for a function with `&rest` args, or `unevalled` for a special form. > 1 votes # Answer Check the actual Emacs version, and act based on what you know to be correct for that version. Just knowing how many arguments are expected is insufficient. Imagine that the function changes again in future to add a second argument which is different to the original second argument -- you don't want your code to get the two mixed up. You can test `(version< emacs-version VERSION-STRING)` or just `(< emacs-major-version INTEGER)` if that's sufficient (which is fairly likely with API changes). > 0 votes --- Tags: functions, arguments ---
thread-60975
https://emacs.stackexchange.com/questions/60975
company-mode: no completions found
2020-10-03T15:25:30.417
# Question Title: company-mode: no completions found I am new to emacs (long-time vim user). Specifically, I am using doom-emacs. Doom is supposedly set up to use `company-mode` for auto completion, but I have not gotten it to work. I have the following source code: ``` class CompleteUserBankruptcyJob < ApplicationJob queue_as :default def perform(user) CompleteUserBankruptcy.call(user) end end ``` If I type in `def perfo`, I would expect company to suggest `perform`. However, it does not suggest anything at all. If I manually trigger suggestions via `C-SPC`, it says "No completion found". Finally, if I run `company-diag` in the buffer, I get the following information: ``` Emacs 27.1 (x86_64-apple-darwin18.7.0) of 2020-08-12 on builder10-14.porkrind.org Company 0.9.13 company-backends: (company-capf company-yasnippet) Used backend: company-yasnippet Major mode: ruby-mode Prefix: nil Completions: none ``` I have no idea how to debug further. If it is any help, I have my personal configuration files in this repo, but I have not modified any company-mode related settings, so it should all be using the default from doom-emacs, which for company I believe are located here. Finally, I believe that the list of backends is not being set correctly in `ruby` major mode (and may be failing in other modes as well), given the references to company in this file. # Answer > 0 votes I'm not sure which completion backend Doom uses by default these days for Ruby (whether it's LSP or Robe), but the Troubleshooting section of `company/README.org` says this: > For instance, go-mode requires guru to be installed on your system, and ruby-mode requires that you have a Robe server running (M-x robe-start). Meaning, you need to have `robe` (the package) installed (perhaps it already is) and to type `M-x robe-start` to launch the background process. And to possibly deal with any errors you see if it fails to launch (e.g. run `bundle install`). Yes, I'm also not sure why `company-robe` is not in the list of backend, but perhaps it will be added automatically as soon as the `robe` package is (auto)-loaded. --- Tags: company-mode, doom, company ---
thread-28366
https://emacs.stackexchange.com/questions/28366
Go to window by buffername
2016-11-03T08:44:38.027
# Question Title: Go to window by buffername I would like to be able to switch to an open window by typing the name of the buffer which is displayed in it. It would be something like C-x b which opens the selected buffer only if it is not opened in another windows and in that case the focus switch to that window. # Answer For a slightly different approach, you can install the https://github.com/abo-abo/ace-window package (available from melpa) and bind `ace-window` to some key sequence. When you invoke it, it gives each window a letter or number, which you can type to select. If you turn on `ace-window-display-mode` this letter is also added to the mode line so you can see it in advance. The answer to Defining the window pointed by "other-window" has a screencast showing it in action. The package has extra features, for example if invoked with one universal argument it swaps the current window with the target window. The https://github.com/abo-abo/ace-window/wiki has an extended example, with scrolling other windows, `winner-mode` to save and restore window configurations and so on. > 2 votes # Answer You can use `interactive` to select a buffer, `get-buffer-window` to find the window showing that buffer, and `select-window` to switch to that window: ``` (defun open-window-by-buffer (buffer) (interactive "bBuffer: ") (select-window (get-buffer-window buffer) nil)) ``` I love `ido-mode` for selecting things like open buffers, so here's a solution using that: ``` (defun open-window-by-buffer () (interactive) (let ((buffer (ido-completing-read "Buffer: " (mapcar 'buffer-name (buffer-list))))) (select-window (get-buffer-window buffer) nil))) ``` > 2 votes # Answer If you use Icicles then you can use command `icicle-select-window`, bound to **`C-0 C-x o`** to trip among windows using their buffer names. More generally, **`C-x o`** trips among windows or frames, as follows (`C-h k C-x o`): > **`C-x o`** runs the command **`icicle-other-window-or-frame`** which is an interactive compiled Lisp function in `icicles-cmd1.el`. > > `(icicle-other-window-or-frame ARG)` > > Select a window or frame, by name or by order. > > This command combines Emacs commands `other-window` and `other-frame`, together with Icicles commands **`icicle-select-window`**, **`icicle-select-frame`**, and **`icicle-choose-window-for-buffer-display`**. > > Use the *prefix argument* to choose the behavior, as follows: > > * With *no* prefix arg or a *non-zero* numeric prefix arg: If the selected frame has multiple windows, then this is `other-window`. Otherwise, it is `other-frame`. > * With a *zero* prefix arg (e.g. **`C-0`**): If the selected frame has multiple windows, then this is `icicle-select-window` with windows in the frame as candidates. Otherwise (single-window frame), this is `icicle-select-frame`. > * With plain **`C-u`**: If the selected frame has multiple windows, then this is `icicle-select-window` with windows from all visible frames as candidates. Otherwise, this is `icicle-select-frame`. > * With plain **`C-u C-u`**: Same as `icicle-select-window` with a negative prefix arg: Select a window from any frame, including iconified and invisible frames. > * With plain **`C-u C-u C-u`**: This is `icicle-choose-window-for-buffer-display`, with windows from all frames (i.e., iconified and invisible) frames as candidates. > > If you use library `oneonone.el` with a *standalone minibuffer* frame, and if option `1on1-remap-other-frame-command-flag` is non-nil, then frame selection can include the standalone minibuffer frame. > > By default, Icicle mode remaps all key sequences that are normally bound to `other-window` to `icicle-other-window-or-frame`. If you do not want this remapping, then customize option `icicle-top-level-key-bindings`. > 1 votes --- Tags: buffers, window, navigation ---
thread-60960
https://emacs.stackexchange.com/questions/60960
How can I create a new label using Magit forge?
2020-10-02T19:03:39.690
# Question Title: How can I create a new label using Magit forge? Using Magit Forge, I'd like to create a new label for a new issue. I can edit the `Labels` field using command `forge-edit-topic-labels`, but that command accepts only labels that already exist. How can I create a new label? # Answer > 1 votes There's no support for that. I feel this is the sort of thing that one has to do infrequently enough for it to be okay to have to do it using the web interface. # Answer > 2 votes I agree with tarsius that Forge doesn't appear to support that operation, but I disagree with his philosophy slightly. If a feature that doesn't exist would be useful to you, you should create it! I so rarely label github issues that I've never thought to create a label from within Magit, but maybe I can help some. The API endpoint you need is documented at https://developer.github.com/v3/issues/labels/#create-a-label; it looks quite straight forward, and certainly Forge will already have done all the hard work with authentication and so on. From a quick scan through the code, it looks like you would have to add two new functions. First you should add one called `forge--add-new-label`, which is responsible for sending the API request to github. All the functions of this type appear to call `forge--ghub-post` with a URL of the API endpoint and the data that needs to be posted. The second function should probably be called `forge-add-new-label`; it will be the interactive function that prompts the user to input the name of the label, a color, and a description. It will then call `forge--add-new-label` to post the data. I recommend looking at `forge-create-mark`; it prompts for similar information. The stuff it does with faces is unnecessary though; that's for local display of the mark. --- Tags: magit ---
thread-60988
https://emacs.stackexchange.com/questions/60988
Emacs keybinding for switching tab via number
2020-10-04T12:55:40.607
# Question Title: Emacs keybinding for switching tab via number In Emacs 27.1, using `tabbar`. Trying to switch to tabs using numbers. Editing `~/.emacs` with following lines doesn't switch tabs using `C-1`. Produces `C-u 1` and so on. What is missing here? Any other comfortable option? ``` (require 'tabbar) (global-set-key (kbd "C-1") 'tab-bar-select-tab 1) ; move to 1st tab (global-set-key (kbd "C-2") 'tab-bar-select-tab 2) ; move to 2nd tab ``` # Answer > 2 votes `global-set-key` doesn't take 3 arguments. ``` (global-set-key (kbd "C-1") (lambda () (interactive) (tab-bar-select-tab 1))) ``` Or better yet: ``` (defun move-to-first-tab () "Move to first tab." (interactive) (tab-bar-select-tab 1)) (global-set-key (kbd "C-1") 'move-to-first-tab) ``` --- Tags: init-file, tabbar ---
thread-60946
https://emacs.stackexchange.com/questions/60946
Encrypted Email and Mailing Lists
2020-10-02T10:51:05.753
# Question Title: Encrypted Email and Mailing Lists My organization uses PGP-encrypted email, but are unable to use it with our mailing list because we send emails to the mailing list address, and not to the addresses on our member's individual PGP keys. I was told by one of my colleagues that Thunderbird's Enigmail plugin had an option to "Edit per-recipient rules." Using this, they were able to send encrypted emails to me and other members encrypted with their own PGP keys. I'm using Notmuch as an email frontend on Emacs and smtpmail to send it. I haven't been able to find any similar options on here^1, here^2 and here^3. # Answer Looking through `man gpg`, I was able to find the `--group` option, which allowed me to include the following in my `$HOME/.gnupg/gpg.conf` file: ``` group ${mailing list email} = 12345 12345 12345... ``` Writing an email after doing `M-x mml-secure-message-sign-encrypt` and sending it normally, it was encrypted to the key-id's I specified in the group! > 0 votes # Answer > My organization uses PGP-encrypted email, but are unable to use it with our mailing list because we send emails to the mailing list address, and not to the addresses on our member's individual PGP keys. Check out https://schleuder.org "an OpenPGP-enabled mailing list manager with resending capabilities". > I was told by one of my colleagues that Thunderbird's Enigmail plugin In the newest release Enigmail is no longer supported but there's now builtin openpgp support. > 0 votes --- Tags: email, gpg ---
thread-54784
https://emacs.stackexchange.com/questions/54784
Managing path for reproductible scientific paper using session, org-babel and org-mode
2020-01-08T21:33:10.287
# Question Title: Managing path for reproductible scientific paper using session, org-babel and org-mode I'm starting using `org-mode` and `org-babel` to support my day by day scientific work and produce reproductibles papers. Lot of people use `rMarkdown`/`jupyter` to do that, but i'm interested by investing some time to do more or less the same things using `org-babel` and `org-mode`. Running chunk of code using org-babel is as simple as running chunk of code with RMarkdown/KnitR, and it seems org-babel is much powerfull on this side, so **no problem with that actually** For me, problem arrives when i try to manage path, and start using `:session` property, especially with shell (sh/bash). I define the workspace :dir for source code like this : ``` :PROPERTIES: :export_file_name: reproductiblepaper :header-args: :dir ~/home/xxx/reproductible_paper tangle:yes session: reproductible :END: ``` It's common to use git or any cvs to download and run code producing result, so naively i wrote in my org code : ``` #+begin_src sh git clone git@gitlab.com:xxx/yyy/mygitproject.git #+end_src ``` Folder appear in `~/home/xxx/reproductible_paper/mygitproject/` as expected. After that, i don't want to rewrite my `:dir` path for each `#+BEGIN_SRC ... #+END_SRC` block, so i use the :session capacity, and i wrote ``` #+begin_src sh cd mygitproject #+end_src ``` BUT, using this strategy cannot work. When you write and export org file multiple time in a writing/publishing workflow (write -\> execute/publish -\> write), each command rerun using the same shell session !, bypassing the `:header-args: dir:` defined in property. The result was weird, and multiple run create an infinity of nested folder due to git clone and cd command. Following your advice what is the best way to manage path in this use case ? Killing session each run ? Use environment variable without `:session` to define directory path ? **UPDATE 1** a) Using absolute path, env substitution, and session : ``` :PROPERTIES: :export_file_name: reproductiblepaper :header-args: :dir ~/home/xxx/reproductible_paper tangle:yes session: reproductible :END: ``` ``` #+NAME: absfolder #+BEGIN_SRC sh ABS="/home/xxx/reproductible_paper" #+END_SRC ``` ``` #+begin_src sh git clone git@gitlab.com:xxx/yyy/mygitproject.git #+end_src ``` ``` #+begin_src sh :noweb yes <<absfolder>> cd $ABS/mygitproject pwd #+end_src ``` If you use this solution, and killing each time the session, it works, but you cannot use interactive evaluation without creating an unstable state in your shell session. Why not. But to do this in a clean way i need : * a way/command to kill/reset session at each re-export. * a starting script which clean previous state files/folders manipulation Any advice do that in org ? b) I suppose there is probably another way to do the same thing without using a session, using :var or :dir and using link dependency between each code block ? # Answer > 2 votes Your use case is a bit unusual, but I think you can get what you want with a few tweaks. As you've discovered, when you use the `session` argument, you will re-use the same active bash/R session each time you re-run your code. That's an issue if you use `cd`. You could protect against this by including a block resetting your directory at the start of your file: ``` #+begin_src sh cd ~/home/xxx/reproductible_paper #+end_src ``` This will allow you to continue using relative paths for the rest of your script. If you don't want this block to appear in your final document, you can hide it from the output with the header argument `:exports none` Another thing that might help is to selectively exclude some code blocks from evaluation at export. You probably don't need to `clone` the same git repository every time you change some code further down in your document. You can control this with the `eval` header: ``` #+begin_src sh :eval noexport git clone git@gitlab.com:xxx/yyy/mygitproject.git #+end_src ``` The `noexport` option will allow you to interactively run the code the first time you need it, or anytime you want to repeat the code (e.g., when the repository has been updated). But it won't get run automatically whenever you export your document. # Answer > 1 votes I'm not sure how this is specific to Org. If you write a script that changes state *dependent on current state*, and don't unchange/reset the state elsewhere in the script, and repeatedly run the script, the state will be changed each time you run it. What about `cd ${project_root}/mygitproject`?, where `${project_root}` is absolute? If you use the absolute path, not the relative path, your problem may be solved. --- Tags: org-mode, org-babel, literate-programming ---
thread-60987
https://emacs.stackexchange.com/questions/60987
completion-ignored-filenames?
2020-10-04T09:37:10.793
# Question Title: completion-ignored-filenames? Is there a way to do ignore whole file names the same way as 'completion-ignored-extensions' ignores filename extensions? For example, I would like to blacklist `__pycache__/`, so that if the default directory contains `__init__.py` and `__pycache__/` (and these two are the only files whose names start with underscore), I can do `C-x C-f _ TAB` and get right to `__init__.py` as the only choice, without Emacs offering me `__pycache__/` after me hitting `TAB` once more to reveal the second underscore. Is this possible? # Answer Not too sure what the context of your question is. If you're using function `read-file-name` then you can pass it a `PREDICATE` argument that will exclude any files or dirs you want to exclude as completion candidates. `C-h f read-file-name` tells us: > Sixth arg `PREDICATE`, if non-`nil`, should be a function of one argument; then a file name is considered an acceptable completion alternative only if `PREDICATE` returns non-`nil` with the file name as its argument. So a `PREDICATE` value of `foo` would exclude file `__pycache__`: ``` (defun foo (filename) "Return non-nil if FILENAME is not `__pycache__'." (setq filename (directory-file-name filename)) (not (string= filename "__pycache__"))) (read-file-name "File: " nil nil t nil 'foo) ``` The reason for using `directory-file-name` is so that this works for a `FILENAME` value that is a directory name, as well as a value that is an ordinary file name. > 1 votes # Answer From the documentation of `completion-ignored-extensions` ``` It ignores directory names if they match any string in this list which ends in a slash. ``` so you can simply add `__pycache__/` to the variable ``` (add-to-list 'completion-ignored-extensions "__pycache__/") ``` > 1 votes --- Tags: completion, find-file ---
thread-60512
https://emacs.stackexchange.com/questions/60512
Is there a better way of writing this with use-package?
2020-09-06T05:32:32.513
# Question Title: Is there a better way of writing this with use-package? I feel like there is a better way of writing this with `use-package` but I just can't get the usual way to work. ``` (use-package eshell :hook (eshell-mode . (lambda () (define-key eshell-mode-map (kbd "C-<backspace>") (lambda () ; clear shell (interactive) (message "I am some other function")))))) ``` I tried using the `:bind (:map eshell-mode-map ("C-<backspace>" . <lambda here>))`, but that just binds the function to the global key map for some reason. Maybe because `eshell-mode-map` is `nil` till eshell is launched. Could someone suggest a better utilisation of use-package to write what I already have? # Answer > 1 votes The keybindings created with `:bind` expect a function name (not sure how lambdas are expanded) so you can define a named function in the `:init` clause of `use-package` which should work as expected... ``` (use-package eshell :after esh-mode :init (defun my-clear-shell () (interactive) (message "I am some other function")) :bind (:map eshell-mode-map ("C-<backspace>" . my-clear-shell))) ``` # Answer > 0 votes Rewrite your config to keep it simple: ``` (defun your-eshell-clear () (interactive) (message "TODO impl your-eshell-clear")) (defun your-eshell-setup () (define-key eshell-mode-map (kbd "C-<backspace>") #'your-eshell-clear)) (add-hook 'eshell-mode-hook #'your-eshell-setup) ``` You can simplly put it to your init file, it will not slow your Emacs startup. If you need, you can group it via `progn` or `with-eval-after-load` or `use-package`, thought they does not provide actual benefits, and `use-package` sometimes can make your init file more complex and harder to understand. --- Tags: key-bindings, keymap, eshell, use-package ---
thread-58255
https://emacs.stackexchange.com/questions/58255
Adding bookmarks in pdf-tools
2020-05-03T15:51:24.457
# Question Title: Adding bookmarks in pdf-tools Is there a way to add and view bookmarks in pdf-tools? Or else How could I go about adding this feature? I'm not actually sure if this is even a feature of pdfs. All I know is I can do this with document viewer app on ubuntu. # Answer > 2 votes org-pdftools is able to set pdf page links, which can then be saved in an org-mode file. Alternatively, if you want to have something embedded in the pdf file, you can add an annotation somewhere on the page (see annotations keybindings list), and then list/jump to them via `C-c C-a l` and `SPACE`. I think that these two features are the closest thing that there is to the bookmarks feature in document viewer. --- Tags: bookmarks, pdf-tools ---
thread-61010
https://emacs.stackexchange.com/questions/61010
Search for file content with swiper-all or similar interface
2020-10-06T13:00:56.607
# Question Title: Search for file content with swiper-all or similar interface I've been using swiper-all to search for content in buffers. This works really great as I easily can navigate between the files and select the ones I want to work with. Is there some way I can use a similar interface to search in files on disk. E.g. recursively in current directory. # Answer If you are willing to install RipGrep, `counsel-rg` (included in counsel) could offer the interface you are looking for. From its docstring: > Grep for a string in the current directory using rg. > 2 votes --- Tags: search, files ---
thread-22115
https://emacs.stackexchange.com/questions/22115
How to set Org-mode heading color for level after 8?
2016-05-07T04:55:34.533
# Question Title: How to set Org-mode heading color for level after 8? I can only set color and font-face for Level between 1 to 8. Is there a way to set heading color for Org Level 9 and beyond? # Answer As you can guess from your screenshot, the face for level 9 is the same as the face for level 1. You can confirm this by hitting `C-u C-x =` with your cursor on a level 9 headline which shows: ``` There are text properties here: face org-level-1 ``` AFAICT, if you want a different face for level 9 (and further), it involves adding one or more new faces (with e.g. `defface`), changing the defconst `org-level-faces` (add your new face(s) there) and change the value of `org-n-level-faces`. e.g. the following should work (only lightly tested) : ``` (progn (defface org-level-9 ;; originally copied from org-level-8 (org-compatible-face nil ;; not inheriting from outline-9 because that does not exist '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown")) (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon")) (((class color) (min-colors 8)) (:foreground "green")))) "Face used for level 9 headlines." :group 'org-faces) (setq org-level-faces (append org-level-faces (list 'org-level-9))) (setq org-n-level-faces (length org-level-faces))) ``` > 6 votes # Answer Based on YoungFrog's answer: ``` (progn (progn (face-spec-set 'org-level-5 ;; originally copied from org-level-8 (org-compatible-face nil ;; not inheriting from outline-9 because that does not exist '((((class color) (min-colors 16) (background light)) (:foreground "brightblue")) (((class color) (min-colors 16) (background dark)) (:foreground "brightblue")) (((class color) (min-colors 8)) (:foreground "green"))))) (face-spec-set 'org-level-6 ;; originally copied from org-level-8 (org-compatible-face nil ;; not inheriting from outline-9 because that does not exist '((((class color) (min-colors 16) (background light)) (:foreground "brightcyan")) (((class color) (min-colors 16) (background dark)) (:foreground "brightcyan")) (((class color) (min-colors 8)) (:foreground "green"))))) (face-spec-set 'org-level-7 ;; originally copied from org-level-8 (org-compatible-face nil ;; not inheriting from outline-9 because that does not exist '((((class color) (min-colors 16) (background light)) (:foreground "deepskyblue")) (((class color) (min-colors 16) (background dark)) (:foreground "deepskyblue")) (((class color) (min-colors 8)) (:foreground "green"))))) (face-spec-set 'org-level-8 ;; originally copied from org-level-8 (org-compatible-face nil ;; not inheriting from outline-9 because that does not exist '((((class color) (min-colors 16) (background light)) (:foreground "Purple")) (((class color) (min-colors 16) (background dark)) (:foreground "Purple")) (((class color) (min-colors 8)) (:foreground "green"))))) (defface org-level-9 ;; originally copied from org-level-8 (org-compatible-face nil ;; not inheriting from outline-9 because that does not exist '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown")) (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon")) (((class color) (min-colors 8)) (:foreground "green")))) "Face used for level 9 headlines." :group 'org-faces) (setq org-level-faces (append org-level-faces (list 'org-level-9))) (setq org-n-level-faces (length org-level-faces)))) ``` Note that you can use `counsel-colors-emacs` to insert the colors if you counsel installed. > 0 votes --- Tags: org-mode ---
thread-61007
https://emacs.stackexchange.com/questions/61007
org-journal sort entries by date at insert time
2020-10-06T10:54:38.077
# Question Title: org-journal sort entries by date at insert time I want to switch from daily files to monthly (or even yearly). The problem I'm facing is: `org-journal-new-entry` and `org-journal-new-scheduled-entry` simply append at the bottom of a file. This can result in unsorted days - can this be sorted?. (extreme) example: **config** ``` (use-package org-journal :ensure t :defer t :bind ("C-c n j" . org-journal-new-entry) ("C-c n s" . org-journal-new-scheduled-entry) :custom (org-journal-file-format "%Y-%m.org") (org-journal-enable-agenda-integration t) :config (setq org-journal-dir org-journal-directory) (setq org-journal-file-type 'monthly) (setq org-journal-date-format " %d/%m/%y - %A") (setq org-journal-file-header "#+title: %B Journal") ``` Then: 1. Add new scheduled in the future 2. Add new entry today 3. Add new entry in the past **Result**: ``` #+title: October Journal * 08/10/20 - Thursday :PROPERTIES: :CREATED: 20201008 :END: ** First: New Scheduled <2020-10-08> * 06/10/20 - Tuesday :PROPERTIES: :CREATED: 20201006 :END: ** 12:46 Second: new Entry * 05/10/20 - Monday :PROPERTIES: :CREATED: 20201005 :END: ** Third: new scheduled in past <2020-10-05> ``` **my goal** would be to have entries in the file correctly sorted from top to bottom (basically the oppositve of my result) # Answer I'm not sure how this is handled in `org-journal`, by base `orgmode` provides `datetree` as an option for capture templates. These are created and inserted in sorted order. This allows you to define an appropriate capture element to add entries to your journal.org file. From the org manual, (org) Template elements: ``` ‘(file+olp+datetree "filename" [ "Level 1 heading" ...])’ This target(1) creates a heading in a date tree(2) for today’s date. If the optional outline path is given, the tree will be built under the node it is pointing to, instead of at top level. Check out the ‘:time-prompt’ and ‘:tree-type’ properties below for additional options. (2) A date tree is an outline structure with years on the highest level, months or ISO weeks as sublevels and then dates on the lowest level. Tags are allowed in the tree structure. ``` > 1 votes --- Tags: org-mode, org-agenda, org-journal ---
thread-61005
https://emacs.stackexchange.com/questions/61005
Create a new tag using ~org-roam-insert~ whose name is part of an existing tag
2020-10-06T06:46:03.127
# Question Title: Create a new tag using ~org-roam-insert~ whose name is part of an existing tag I'm using org-roam's `org-roam-insert` to insert a new tag. Currently I have two tags, `Emacs` and `EmacsLisp`, now I want to add a new tag called `Lisp`. However, I found it impossible. Here is the screenshot: As you can see, there are no options for me to create a new tag `Lisp`. I can only select the existing tag `EmacsLisp`. Is it a bug or I'm missing something here? # Answer This is a mild infelicity of the `ivy` completion framework you are using. To accept the current input rather than the current candidate, hit `C-M-j` (`ivy-immediate-done`). Alternatively, set `ivy-use-selectable-prompt` to `t` in your init and then you can simply navigate to the prompt line with, for example, `C-p` and just select it in the usual way by hitting `RET`. > 2 votes --- Tags: org-roam ---
thread-61017
https://emacs.stackexchange.com/questions/61017
Inserting timestamp in mini buffer in Emacs
2020-10-06T17:31:10.740
# Question Title: Inserting timestamp in mini buffer in Emacs I keep on saving various org files in their respective folders using Filename as **YYYY-MM-DD.org** files . So I ended up typing C-x C-w 2020-10-06.org at least thirty times today. Can this process be automated ? # Answer > 5 votes I have the following in my `.emacs`: ``` ;; date (global-set-key "\C-\M-d" (lambda (arg) (interactive "P") (let ((separator (pcase arg ('(4) "-") (0 "/") (_ "")))) (insert (format-time-string (concat "%Y" separator "%m" separator "%d")))))) ``` If I press `\C-\M-d`, it inserts `20201006` into the active buffer, mini or not. If I prefix it with `C-u`, it inserts `2020-10-06`; prefixing it with `M-0` inserts `2020/10/06`. # Answer > 2 votes Here's a function that manufactures a filename out of today's time stamp and writes the file out: ``` (defun write-file-timestamp () (interactive) (let ((fname (format-time-string "%Y-%m-%d.org"))) (write-file fname t))) ``` The `t` argument in the `write-file` call asks for confirmation if the file exists already: you can omit it if you don't care, but it's probably a bad idea, since you are using the *same* file name in supposedly different directories - but if you make a mistake and you are in the wrong directory, you'll blow away your file without any warning. You can use the function with `M-x write-file-timestamp RET` but you will probably want to add a key binding for it: ``` (global-set-key (kbd "[f12]") #'write-file-timestamp) ``` to bind it e.g. to the F12 function key. EDIT: @choroba's answer is a direct reply to your explicit question: it inserts a timestamp into the minibuffer; it also provides a general way of inserting a timestamp anywhere. This answer is much more limited: it targets only the implied question of automating the writing of files with a name derived from the current date. --- Tags: org-mode, key-bindings, minibuffer, time-date, format-time-string ---
thread-61003
https://emacs.stackexchange.com/questions/61003
Org Latex preview produces empty box when I use a certain package, how can I debug the issue?
2020-10-06T03:46:19.523
# Question Title: Org Latex preview produces empty box when I use a certain package, how can I debug the issue? The following line in my org file is causing problems ``` #+LaTeX_HEADER: \usepackage{prooftrees} ``` If this line is there, then org latex preview produces an empty box. If I remove it, things work just fine. The output of \*Org Preview LaTeX Output\* is: ``` This is dvipng 1.17 Copyright 2002-2015, 2019 Jan-Ake Larsson [1] ``` so I can't tell what's going wrong. Finally, the \*Messages\* buffer only says: "Creating image...done", which doesn't help me understand why it's failing. I know that the prooftrees package works, because I can get it to work in my normal latex compilation, so this seems to be a problems specifically with emacs org-mode. How can I troubleshoot this issue? How can I see what latex it's generating and what commands it's running to produce the image? Thanks Edit: The issue was with dvipng: this program would output a messed up png after processing the output dvi file. I tried changing to imagemagick but got a mysterious error. Changing to dvisvgm fixed the issue, so I guess this program is somehow better at processing dvi files that contain prooftrees. To change to dvisvgm I did * M-x customize-variable ENTER org-preview-latex-default-process * then changed the value to "dvisvgm" To catch the temporary tex files before emacs deleted them I used the following shell command in the /tmp directory: ``` inotifywait -mr --format '%w%f' -e create . | while read file; do if echo "$file" | grep '^./orgtex.*\.tex$' > /dev/null; then echo "file: $file"; cp $file ${file}.bkp; fi; done ``` # Answer > 0 votes The preview code writes a TeX file into the `/tmp` directory with a name like `orgtexXXXXXX.tex` \- there should also be a log file with name `orgtexXXXXXX.log`. Check the log file for errors and peruse the tex file to see if there are any obvious problems. Depending on your setting of `org-preview-latex-default-process`, the tex file may go through a different set of commands to get the final image. The default value is `dvipng` I believe, although `imagemagick` and `dvisvgm` are also possible. Check `org-preview-latex-process-alist` to see which path is actually taken. For `dvipng`, the (simplified) commands are ``` latex orgtexXXXXXX.tex dvipng orgtexXXXXXX.dvi ``` For `imagemagick` they are: ``` pdflatex orgtexXXXXXX.tex convert orgtexXXXXXX.pdf orgtexXXXXXX.png ``` I've omitted all options on the "simplified" commands. The alist contains all the options, but you probably don't need them to debug your problem. --- Tags: org-mode, latex ---
thread-61019
https://emacs.stackexchange.com/questions/61019
Umlauts in Emacs on Mac
2020-10-06T17:51:05.020
# Question Title: Umlauts in Emacs on Mac Sorry for the newbie question. I have been using Aquamacs more many years. As it is not as actively developed as it used to and became increasingly buggy in the past two years I want to make the switch to Emacs. I installed Emacs with homebrew and things are working well. However, I am struggling with setting up my keyboard. The homebrew emacs-version (emacsformacosx) has Meta on command which I like. Is there any way to set up the left option key so that it does the same as it does globally that is produce special characters e.g. `ü` by typing `option + ¨ + u`? I tried ``` (setq ns-command-modifier 'meta) (setq ns-option-modifier 'none) ``` which works for the Umlauts but takes away functions from command such as open files with `command + o`. Can anyone help? # Answer The following setting makes the left alt/option key behave like a system default key (so that one may use special symbols, foreign language characters, and so forth), and the right alt/opion key behaves as the Meta key: ``` (setq ns-alternate-modifier 'none ns-right-alternate-modifier 'meta) ``` > 1 votes --- Tags: key-bindings, osx, keyboard-layout ---
thread-61024
https://emacs.stackexchange.com/questions/61024
Run latexmk inside z shell instead of shell
2020-10-06T19:40:58.980
# Question Title: Run latexmk inside z shell instead of shell # Problem I am using `latexkm` to compile `.tex` documents, and recently I got this error while compiling: ``` Running `latexmk' on `AF2021_serie5' with ``latexmk -bibtex-cond -pdf -synctex=1 AF2021_serie5'' Rc files read: NONE Latexmk: This is Latexmk, John Collins, 17 Apr. 2020, version: 4.69a. Latexmk: applying rule 'biber AF2021_serie5'... Rule 'biber AF2021_serie5': The following rules & subrules became out-of-date: 'biber AF2021_serie5' ------------ Run number 1 of rule 'biber AF2021_serie5' ------------ ------------ Running 'biber "AF2021_serie5"' ------------ sh: biber : commande introuvable Latexmk: Errors, so I did not complete making targets Collected error summary (may duplicate other messages): biber AF2021_serie5: Could not open biber log file for 'AF2021_serie5' Latexmk: Use the -f option to force complete processing, unless error was exceeding maximum runs, or warnings treated as errors. TeX Output exited abnormally with code 12 at Tue Oct 6 21:15:40 ``` I am apparently not the only one to have had this problem (1) but the solution in the link did not fix it for me. # Solutions tried that do not fix the problem I figured that 1. I am using `zsh` as my default shell when I open a terminal, while emacs seems to load `sh`. 2. Compiling the `.tex` files with `latexmk` from the terminal does not generate this error. 3. Launching emacs with `SHELL=/bin/zsh emacs` and then using `C-c C-c latexmk`does not generate this error. 4. Adding ``` (setq-default shell-file-name "/bin/zsh") (setq-default explicit-shell-file-name "/bin/zsh") ``` to my `.emacs` does not fix the problem; however when I click on `Run Shell Interactively`, I can compile the `.tex`with `latexmk` and it does not generate this error. 5. Adding ``` (setq tex-shell-file-name "/bin/zsh") (setq TeX-shell "/bin/zsh") ``` to my `.emacs` does not fix the error. It still seems that latexmk is ran through `/bin/sh`. # Additional information ## Part of my `.emacs`: ``` ;; == AucTeX == ;; (setq TeX-auto-save t) (setq TeX-parse-self t) (setq preview-auto-cache-preamble t) ; stop preview pestering ; (setq-default TeX-master nil) (add-hook 'LaTeX-mode-hook 'visual-line-mode) ; Word wrapping (add-hook 'LaTeX-mode-hook 'LaTeX-math-mode) (setq LaTeX-electric-left-right-brace t) ; Automatic close parenthesis (add-hook 'LaTeX-mode-hook 'turn-on-reftex) (setq reftex-plug-into-AUCTeX t) (setq TeX-PDF-mode t) ; Compile as a PDF (setq reftex-ref-macro-prompt nil) ; Disable annoying reference prompt screen ;; == RefTeX == ;; (setq reftex-bibliography-commands '("bibliography" "nobibliography" "addbibresource")) ;; === LatexMK - automatically recompile and run bibtex ===;; (add-hook 'LaTeX-mode-hook (lambda () (push '("latexmk" "latexmk -bibtex-cond -pdf -synctex=1 %s" TeX-run-TeX nil t :help "Run latexmk on file") TeX-command-list))) (add-hook 'TeX-mode-hook '(lambda () (setq TeX-command-default "latexmk"))) ``` ## result of `which biber` (from `zsh`) `/usr/bin/vendor_perl/biber` ## result of `which biber` (from `sh`) `/usr/bin/vendor_perl/biber` # Final question, I guess What can I add to my `.emacs` so that `latexmk` is ran inside of `zsh` instead of `sh`? # Answer I don't think it has anything to do with `zsh` vs `sh`. I believe it has to do with subprocessess of emacs not having the path required to find the `biber` executable, whereas interactive shells apparently do. Try adding the path to `exec-path`: evaluate the following form ``` (add-to-list 'exec-path "/usr/bin/vendor_perl") ``` and try your `latexmk` run. If that works, add the line to your init file, restart emacs and test again. EDIT: The doc string for `exec-path` says: > List of directories to search programs to run in subprocesses. Each element is a string (directory name) or nil (try default directory). so it should resolve the `sh: biber : commande introuvable` done in the subshell, particularly since you say that in an interactive `sh`, doing `which biber` finds the executable. Not sure why you are still having problems. > 1 votes --- Tags: latex, auctex, shell, bibtex, zsh ---
thread-61025
https://emacs.stackexchange.com/questions/61025
Which `ls` program is used when running dired over tramp?
2020-10-06T22:07:23.300
# Question Title: Which `ls` program is used when running dired over tramp? How does dired determine which `ls` program to use when running over tramp? I couldn't find it anywhere in the document. If it is `insert-directory-program`, what would it do if the path doesn't exist on the remote host? # Answer > 3 votes Tramp does not use `insert-directory-program`. It has its own mechanism to detect a proper `ls` program. Dired is not involved at all. It calls `insert-directory`, and let the local implementation, or the Tramp implementation run. --- Tags: dired, tramp ---
thread-61039
https://emacs.stackexchange.com/questions/61039
Tell ESS to use a different R program when on a Tramp remote session
2020-10-07T13:18:16.110
# Question Title: Tell ESS to use a different R program when on a Tramp remote session I'm trying to configure ESS to use a different R program path when I'm on a remote session. Now, every time I ssh into the hpc cluster I use, I set the variable inferior-ess-R-program to /weird/path/to/R to make ESS open up a remote R session, but I'd like to figure out how to this automatically. I use R on my local machine via ESS as well, so changing the variable permanently it not an option. Thanks! # Answer I don't know which Tramp version you use. But in the more recent versions, you can set connection-local variables. Check the Tramp manual for details. > 2 votes --- Tags: tramp, ess, r, remote ---
thread-34488
https://emacs.stackexchange.com/questions/34488
saving clipboard takes forever on quit
2017-07-28T11:59:42.757
# Question Title: saving clipboard takes forever on quit When closing spacemacs, I get the message "Saving clipboard to x clipboard manager...". The saving process ends up taking so much time that I have to kill emacs from the terminal. How can I disable emacs from doing this process upon quitting? Or at least how can I figure out what emacs function is responsible for displaying this message? # Answer As the message says: > Saving clipboard to x clipboard manager... Try `emacs -Q` and copy then close emacs, you get this message: > Error saving to X clipboard manager. > > If the problem persists, set 'x-select-enable-clipboard-manager' to nil. So add `(setq x-select-enable-clipboard-manager nil)` to your .emacs file > 2 votes --- Tags: spacemacs, clipboard ---
thread-61033
https://emacs.stackexchange.com/questions/61033
org-export to ignore strings within drawers
2020-10-07T10:23:24.433
# Question Title: org-export to ignore strings within drawers I have the following set up for an annotated bibliography document. ``` ** Kim, M. (2008): An inquiry into the development of the ethical theory of emotions in the "Analects" and the "Mencius" :PROPERTIES: :UNNUMBERED: t :END: :CITED: [[Nivison, D. S. (1996). The ways of confucianism: investigations in Chinese philosophy. Chicago: Open Court.]] :END: ``` The `CITED` drawer is used to keep track of important works that are cited or referenced within the book or article. Exporting via LaTeX to pdf unexpectedly prints out items within the `CITED` drawer. How do I suppress this unwanted behavior? # Answer > 1 votes I found the way to do it from here. ``` #+OPTIONS: d:(not "CITED") ``` --- Tags: org-mode, org-export, latex ---
thread-58375
https://emacs.stackexchange.com/questions/58375
Long Emacs start-up time (20~60s) on Windows 10
2020-05-08T18:37:21.567
# Question Title: Long Emacs start-up time (20~60s) on Windows 10 I have a working setup of emacs on Windows 10 that I like so far. However, I find that emacs start-up takes very long. It can be anywhere from 20s to 60s. I tried installing the benchmark-init package which profiles the start-up and saves the results which can be accessed after start-up is complete. This is what it looks like. I can't quite tell if just one package is the bottleneck or not. There seems to be a uniform spread. ``` Module Type ms Total ms --------------------------------------------------------------------------------------------------- ispell require 364 364 default load 265 265 evil-vars require 216 216 undo-tree require 213 328 wid-edit require 196 196 compile require 189 189 easy-mmode require 187 187 ewoc require 170 170 subr-x require 167 167 spacemacs-common require 165 165 etags require 137 397 xref require 136 260 flyspell require 133 496 comint require 131 243 project require 124 124 rect require 121 121 evil-commands require 121 813 tree-widget require 119 314 pcomplete require 115 115 reveal require 114 114 diff require 114 114 thingatpt require 112 112 ansi-color require 112 112 shell require 111 469 color require 110 110 windmove require 109 109 dash require 109 109 powerline-separators require 109 219 bind-key require 107 293 ggtags require 106 862 powerline require 101 403 spaceline require 95 773 s require 95 95 spaceline-segments require 88 184 powerline-themes require 82 82 spaceline-config require 73 257 evil-common require 70 448 evil-types require 60 60 evil-integration require 57 385 ~/.emacs.d/recentf load 56 56 evil-core require 51 51 evil-search require 49 556 evil-jumps require 44 44 evil-repeat require 42 42 evil require 40 2763 evil-states require 40 40 evil-maps require 39 39 evil-macros require 38 38 evil-ex require 38 507 evil-command-window require 38 38 evil-digraphs require 36 36 evil-keybindings require 35 35 ``` Any advice appreciated. # Answer I also run Emacs on Windows and I used to have a start up time of about 20 seconds, just like you. I've gotten my startup time down to 3-5 seconds by following many of the principles in this post. Also, if you don't want to use Doom Emacs, you can still use many of the tips that its creator suggests. One tip I've found for speeding up things is to use the MELPA Stable distribution for some packages, and use the normal MELPA distribution for others, depending on which loads up faster. In general MELPA Stable is faster because all the debugging code has been removed, but there are exceptions. Other than that, bisection and profiling your code are the only ways to find where the bottlenecks are. I've found profile-dotemacs to be more useful for this. > 1 votes # Answer Windows is bad at handling many small files. You could try to put as much as possible (elisp code, even autoloads) in as less as possible files. Also lazy loading is cruicial (`use-package` helps a lot here). I heard that with Windows also `magit` crawls, because Windows is bad at spawning multiple small processes in fast succession. (there should be a speedup in the working (or it's even finished)) Running Emacs in WSL is reported to be much faster, also magit. > 0 votes --- Tags: start-up, performance ---
thread-61061
https://emacs.stackexchange.com/questions/61061
`org-babel-load-file` doesn't always tangle source file
2020-10-08T02:10:15.667
# Question Title: `org-babel-load-file` doesn't always tangle source file I'm on Org 9.3. I run the following test. ``` [OP@localhost bug1]$ ls real.org test.org ``` The contents of `real.org` are: ``` [OP@localhost bug1]$ cat real.org #+PROPERTY: header-args :tangle yes #+begin_src emacs-lisp (setq count (+ 1 count)) #+end_src ``` The contents of `test.org` are: ``` [OP@localhost bug1]$ cat test.org #+begin_src emacs-lisp (setq count 0) #+end_src #+begin_src emacs-lisp (org-babel-load-file "real.org") count #+end_src ``` I then do: ``` [OP@localhost bug1]$ touch real.el ``` Now executing `test.org`, I get: ``` #+begin_src emacs-lisp (setq count 0) #+end_src #+RESULTS: : 0 #+begin_src emacs-lisp (org-babel-load-file "real.org") count #+end_src #+RESULTS: : 0 ``` And the file `real.el` is still empty. I have two questions: * Why does this happen? * Is there a way to force .el file regeneration every time? Some further observations: * If the org file being loaded (`real.org` in the above) is a symlink, the .el file is never regenerated. * If the org file being loaded is newer, even if the .el file exists, the .el file will be regenerated. * Finally, obviously if the .el file doesn't exist, it is created. # Answer `touch real.el` generates an empty file (if the file does not exist already) and gives it the current time as its modification time, so it is newer than `real.org`. Since it is newer, it will not be regenerated: `org-babel-load` tangles only if the org file is newer\[1\]. So that gives you a few ways to ensure regeneration: * delete `real.el` every time. * touch `real.org` every time. * add or delete a character to `real.org` and save it every time. * open `real.org`, mark it modified with `(set-buffer-modified-p t)` and save it. All of those make `real.el` either non-existent or older than `real.org` so it will be regenerated. \[1\] Clicking on the link is supposed to take you to the definition of `org-babel-load-file` but it seems to take a while to do so: be patient (like wait-for-30-seconds patient). Not sure why it is so slow. > 1 votes --- Tags: org-mode, org-babel ---
thread-46648
https://emacs.stackexchange.com/questions/46648
Adding custom word list to company
2018-12-17T16:41:02.500
# Question Title: Adding custom word list to company Is it possible to add my personal custom list of words to the company database. Kindly guide me in a simple way. I am not a programmer. # Answer Yes, it is possible. I use the following. ``` (setq company-ispell-available t) (setq company-ispell-dictionary "/path/to/your/wordlist/file") (add-to-list 'company-backends 'company-ispell) ``` The other answers are valid alternatives, here we are passing a custom-populated file to `company` to help auto-complete. > 1 votes # Answer Can't give you an answer regarding Company, but I would assume that it provides that possibility. Otherwise, the built-in, old but still very useful library `completion.el` offers that possibility. From the doc (which is only in the file's `Commentary` section): ``` ;; SAVING/LOADING COMPLETIONS ;; Completions are automatically saved from one session to another ;; (unless save-completions-flag or enable-completion is nil). ;; Activating this minor-mode (calling completion-initialize) loads ;; a completions database for a saved completions file ;; (default: ~/.completions). When you exit, Emacs saves a copy of the ;; completions that you often use. When you next start, Emacs loads in ;; the saved completion file. ``` > 1 votes # Answer I suppose you use `company`'s backend `company-ispell` to input plain words, Insert below code into your `~/.emacs.d/init.el`, ``` (defvar my-ispell-words '("helle1" "helle2" "word1" "word2")) (defadvice ispell-lookup-words (after ispell-lookup-words-after-hack activate) (let* ((word (car (ad-get-args 0))) (my-words (all-completions word my-ispell-words) )) (when my-words (setq ad-return-value (nconc my-words ad-return-value))))) ``` > 1 votes --- Tags: company-mode, company ---
thread-61064
https://emacs.stackexchange.com/questions/61064
Buggy org export to LaTeX `itemize` and `enumerate` functions
2020-10-08T11:37:52.510
# Question Title: Buggy org export to LaTeX `itemize` and `enumerate` functions A similar question has been put to the TeX community over here, which led to the insight that this is an `org-export` issue. Hence the current question: The `org` document below generates a `tex` file that compiles as follows: ``` #+TITLE: Annotated Bibliography #+OPTIONS: H:3 author:nil * Section Heading ** Subsection Heading *** Numbered Heading **** Yang, X. (2006). A Moral Psychology without the Concept of Reason? History of Philosophy Quarterly, 23(4), 295–318. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus at vestibulum libero. Morbi mattis elit nunc, eu molestie neque dignissim ac. Praesent commodo neque volutpat ligula gravida, a placerat nunc fermentum. Curabitur pellentesque mollis nisi id aliquet. Integer pellentesque nulla a maximus dapibus. In non nisi turpis. Mauris condimentum hendrerit velit, vel ultrices purus commodo vel. * Section Heading ** Subsection Heading *** Unnumbered Heading **** Yang, X. (2006). A Moral Psychology without the Concept of Reason? History of Philosophy Quarterly, 23(4), 295–318. :PROPERTIES: :UNNUMBERED: t :END: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus at vestibulum libero. Morbi mattis elit nunc, eu molestie neque dignissim ac. Praesent commodo neque volutpat ligula gravida, a placerat nunc fermentum. Curabitur pellentesque mollis nisi id aliquet. Integer pellentesque nulla a maximus dapibus. In non nisi turpis. Mauris condimentum hendrerit velit, vel ultrices purus commodo vel. ``` # Generated TeX document: ``` % Created 2020-10-08 Thu 19:05 % Intended LaTeX compiler: pdflatex \documentclass[12pt,a4paper]{article} %\documentclass[12pt,a4paper]{ctexart} \usepackage{xeCJK} \usepackage{zhnumber} % package for Chinese formatting of date time (use /zhtoday) \usepackage[yyyymmdd]{datetime} % set date time to numeric % For Generation of Citations and Bibliography \usepackage[notes, isbn=false, backend=biber]{biblatex-chicago} \bibliography{/Users/satibodhi/Creation/notes/bibliography/thesis} % Set default indentation \setlength\parindent{24pt} % Set Paper Size, Page Layout (another variable is 'bindingoffset') \usepackage[margin = 1.5in, paper = a4paper, inner = 2.5cm, outer = 2.5cm, top = 3cm, bottom = 2.5cm]{geometry} % Keep paragraph indentation while having a line break in between paragraphs. \edef\restoreparindent{\parindent=\the\parindent\relax} \usepackage{parskip} \restoreparindent % Indent first paragraph. \usepackage{indentfirst} \usepackage{titlesec} \usepackage{titling} \usepackage{fontspec} % packages for title and section-heading font setting. \usepackage{newunicodechar} % custom fallback font for certain unicode characters. \usepackage{tocloft} % adding the tocloft package for toc customization % Set Header and Numbering Depth \setcounter{tocdepth}{5} \setcounter{secnumdepth}{5} % Set Font. \setsansfont{Times New Roman} \setmainfont{Calibri} % Set serifed font to Calibri. Originally set to 'Times New Roman', but it cannot display certain characters such as ①②③. \setCJKmainfont{Songti TC} \setCJKsansfont{Kaiti TC} % Set Chinese font. NOTE: Remember to append CJK before of the font class. CJK HAS to be there for the font to show. \setCJKmonofont{PingFang TC} % Set fallback fonts for ㊀ characters. \newCJKfontfamily\fallbackfont{PingFang TC} \newunicodechar{㊀}{{\fallbackfont ㊀}} \newunicodechar{㊁}{{\fallbackfont ㊁}} \newunicodechar{㊂}{{\fallbackfont ㊂}} \newunicodechar{㊃}{{\fallbackfont ㊃}} \newunicodechar{㊄}{{\fallbackfont ㊄}} \newunicodechar{㊅}{{\fallbackfont ㊅}} \newunicodechar{㊆}{{\fallbackfont ㊆}} \newunicodechar{㊇}{{\fallbackfont ㊇}} \newunicodechar{㊈}{{\fallbackfont ㊈}} \newunicodechar{㊉}{{\fallbackfont ㊉}} % WHEN \documentclass is set to {article}, % zhnum[style={Traditional,Financial}] doesn't work with the section counter, % so we define our own counter and increase it every time in \thesection. \newcounter{mysec}[section] \renewcommand\thesection{% \addtocounter{mysec}{1}% \zhnum[style={Traditional,Financial}]{mysec}、} % 大標題序號:壹、貳、參、… \renewcommand\thesubsection{\zhnum{subsection}、} % added a 、小標題序號:一、二、三、… \renewcommand\thesubsubsection{(\zhnum{subsubsection})} % added parentheses % (full-width, don't know if that's what you want) 副標題序號:(一)(二)(三) \renewcommand\theparagraph{\arabic{paragraph}} % arabic numbering for paragraph \renewcommand\thesubparagraph{} % no subparagraph numbering % we have to adjust the spacing in the toc because the section label is longer than usual \addtolength\cftsecnumwidth{1em} \addtolength\cftsubsecindent{1em} \addtolength\cftsubsubsecindent{1em} % Set formats for each heading level. 'sffamily' will point to the sans-serif font. In this case, 「楷體」. % here we need to make sure the normal section counter is accessed \titleformat{\section}{\LARGE\bfseries\sffamily\filcenter} {\zhnum[style={Traditional,Financial}]{section}、}{.5em}{} \titleformat*{\subsection}{\Large\bfseries\sffamily} \titleformat*{\subsubsection}{\large\bfseries\sffamily} % Set formats for each heading level. 'sffamily' will point to the sans-serif font. In this case, 「楷體」. % The `titlesec` package is used over here to make use of `\paragraph` and `\subparagraph` as headings. Up to five levels of headings can be implemented this way. % no extra version for numberless is necessary since no numbers are used anyways % also you get newlines from omitting the [display] in \titleformat already \titleformat{\paragraph}[block] {\large\bfseries\sffamily}{\theparagraph}{0em}{} \titleformat{\subparagraph}[block] {\large\bfseries\sffamily}{}{0em}{} % we need the following so that they don't indent (second argument, 0em); % you'll have to adjust the spacing though since this is not display style anymore: \titlespacing*{\paragraph}{0em}{3.25ex plus 1ex minus .2ex}{.75ex plus .1ex} \titlespacing*{\subparagraph}{0em}{3.25ex plus 1ex minus .2ex}{.75ex plus .1ex} % Set title font. \renewcommand{\maketitlehooka}{\sffamily} % Set quotation font. \usepackage{etoolbox} \newCJKfontfamily\quotefont{Kaiti TC} \AtBeginEnvironment{quote}{\quotefont\normalsize} % Tweak default settings. \renewcommand{\baselinestretch}{1.2} % Set line width. \renewcommand{\contentsname}{\hfill\bfseries\Large 目\hspace{0.5cm} 錄\hfill} % Translate content page title to Chinese. \renewcommand{\cftaftertoctitle}{\hfill} % Center contents title. \renewcommand{\abstractname}{摘要} % Translate abstract title to Chinese. \renewcommand{\tablename}{表} % Translate table to Chinese. \renewcommand{\figurename}{圖} % Translate figure to Chinese. % For text-boxes \usepackage{mdframed} \BeforeBeginEnvironment{minted}{\begin{mdframed}} \AfterEndEnvironment{minted}{\end{mdframed}} % For tables \usepackage{float} \restylefloat{table} % [FIXME] ox-latex 的設計不良導致 hypersetup 必須在這裡插入 \usepackage{hyperref} \hypersetup{ colorlinks=true, %把紅框框移掉改用字體顏色不同來顯示連結 linkcolor=[rgb]{0,0.37,0.53}, citecolor=[rgb]{0,0.47,0.68}, filecolor=[rgb]{0,0.37,0.53}, urlcolor=[rgb]{0,0.37,0.53}, pagebackref=true, linktoc=all,} \usepackage{hyperref} \usepackage{graphicx} \usepackage{longtable} \usepackage{wrapfig} \usepackage{rotating} \usepackage[normalem]{ulem} \usepackage{amsmath} \usepackage{textcomp} \date{\today} \title{Annotated Bibliography} \begin{document} \maketitle \tableofcontents \clearpage \section{Section Heading} \label{sec:org3a53a1d} \subsection{Subsection Heading} \label{sec:orgc4856dc} \subsubsection{Numbered Heading} \label{sec:orgb9d37be} \begin{enumerate} \item Yang, X. (2006). A Moral Psychology without the Concept of Reason? History of Philosophy Quarterly, 23(4), 295–318. \label{sec:org53c352d} Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus at vestibulum libero. Morbi mattis elit nunc, eu molestie neque dignissim ac. Praesent commodo neque volutpat ligula gravida, a placerat nunc fermentum. Curabitur pellentesque mollis nisi id aliquet. Integer pellentesque nulla a maximus dapibus. In non nisi turpis. Mauris condimentum hendrerit velit, vel ultrices purus commodo vel.\\ \end{enumerate} \section{Section Heading} \label{sec:orgeab8943} \subsection{Subsection Heading} \label{sec:org1be7ca4} \subsubsection{Unnumbered Heading} \label{sec:org70aa910} \begin{itemize} \item Yang, X. (2006). A Moral Psychology without the Concept of Reason? History of Philosophy Quarterly, 23(4), 295–318. \label{sec:org25ccf60} Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus at vestibulum libero. Morbi mattis elit nunc, eu molestie neque dignissim ac. Praesent commodo neque volutpat ligula gravida, a placerat nunc fermentum. Curabitur pellentesque mollis nisi id aliquet. Integer pellentesque nulla a maximus dapibus. In non nisi turpis. Mauris condimentum hendrerit velit, vel ultrices purus commodo vel.\\ \end{itemize} \end{document} ``` As can be observed from the output below, there is no empty line between the label and the text body in the unnumbered section, which resulted in the text and heading mixing together in the second subsubsection. # Output: The issue doesn't seem to lie entirely with differences between `numbered` and `unnumbered` property settings because while differences remain when they are swapped: A lone subsubsection which is numbered yields the same undesirable result. ``` #+TITLE: Annotated Bibliography #+OPTIONS: d:(not "CITED") H:3 author:nil * Section Heading ** Subsection Heading *** Subsubsection Heading **** Yang, X. (2006). A Moral Psychology without the Concept of Reason? History of Philosophy Quarterly, 23(4), 295–318. :PROPERTIES: :END: :CITED: :END: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus at vestibulum libero. Morbi mattis elit nunc, eu molestie neque dignissim ac. Praesent commodo neque volutpat ligula gravida, a placerat nunc fermentum. Curabitur pellentesque mollis nisi id aliquet. Integer pellentesque nulla a maximus dapibus. In non nisi turpis. Mauris condimentum hendrerit velit, vel ultrices purus commodo vel. ``` Only when `d:(not "CITED")` is removed from the options do we get what we want in the output. Commenting out the second section without removing it entirely also yields normal results. So my guess is that drawer settings somehow interfere with the LaTeX export function that result in having/not having an empty line added between the label and text body in the generated TeX file. Is there a quick fix for this? --- # Update: Adding a drawer to the numbered heading breaks the desired behavior. Whether it is `PROPERTIES` or `CITED` or any other, it doesn't matter. ``` #+TITLE: Annotated Bibliography #+OPTIONS: H:3 author:nil * Section Heading ** Subsection Heading *** Numbered Heading **** Yang, X. (2006). A Moral Psychology without the Concept of Reason? History of Philosophy Quarterly, 23(4), 295–318. :CITED: :END: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus at vestibulum libero. Morbi mattis elit nunc, eu molestie neque dignissim ac. Praesent commodo neque volutpat ligula gravida, a placerat nunc fermentum. Curabitur pellentesque mollis nisi id aliquet. Integer pellentesque nulla a maximus dapibus. In non nisi turpis. Mauris condimentum hendrerit velit, vel ultrices purus commodo vel. * Section Heading ** Subsection Heading *** Unnumbered Heading **** Yang, X. (2006). A Moral Psychology without the Concept of Reason? History of Philosophy Quarterly, 23(4), 295–318. :PROPERTIES: :UNNUMBERED: t :END: :CITED: :END: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus at vestibulum libero. Morbi mattis elit nunc, eu molestie neque dignissim ac. Praesent commodo neque volutpat ligula gravida, a placerat nunc fermentum. Curabitur pellentesque mollis nisi id aliquet. Integer pellentesque nulla a maximus dapibus. In non nisi turpis. Mauris condimentum hendrerit velit, vel ultrices purus commodo vel. ``` So it is confirmed that the bug has got something to do with the way drawers are coded. # Answer > 1 votes It is not possible to nest an indefinite number of titles (see `org-export-headline-levels`). The limit depends on the back-end (see also `org-latex-classes`). ``` #+OPTIONS: H:4 ``` In Org Mode, inferior headlines are converted in list items. ### TLDR; In the following snippet, the fourth heading is converted into an `enumerate` environment. ``` #+OPTIONS: H:3 * First headline ** Second headline *** Third headline **** Malformed headline :PROPERTIES: :END: Subsequent text ``` What happened? An enigmatic code conversion: the following text seems to be just below the "title". More precisely, after an Org -\> LaTeX conversion, we can see that the LaTeX code produces a visual rendering identical to the Org code as if there was no vertical spacing between the title and the following text in the original Org code. Below, we can see that the sentence "Subsequent text" is included inside the `enumerate` environ­ment. It seems wrong for a LaTeX author¹ although it's the expected behavior in Org Mode. Indeed, everything between two headlines is usually part of the same group (see below). ``` \begin{enumerate} \item Malformed headline \label{sec:org025ca38} Subsequent text \end{enumerate} ``` *In any case, the back-end limit for document structuring is reached before: in LaTeX, lists are not used as section titles.* This issue doesn't occur using the "right code" (see below). A possible issue is assigning properties to a paragraph, is this sensible? > ``` > #+OPTIONS: H:4 > > * First headline > ** Second headline > *** Third headline > **** Malformed headline > :PROPERTIES: > :END: > > Subsequent text > > ``` > ``` > \paragraph{Malformed headline} > \label{sec:org6999b6a} > Subsequent text > > ``` --- ¹ <sub>For me, the paragraph should be outside the *enumerate* environment.</sub> --- Tags: org-export, latex, debugging ---
thread-61030
https://emacs.stackexchange.com/questions/61030
Modifying entry display in org-agenda-log-mode agenda view
2020-10-07T06:32:40.517
# Question Title: Modifying entry display in org-agenda-log-mode agenda view The day view of my org-agenda in org-agenda-log-mode shows the estimated effort for each entry (e.g., the `1:00`, the `0:05`, the `0:45`, etc)---I'd like to remove that if possible. Is there any way to edit what columns are shown in the log mode? # Answer That's controlled by the variable `org-agenda-prefix-format` which has different settings for the agenda, todo, tag and search display. You can find the value with `C-h v org-agenda-prefix-format RET`. E.g. mine is at the default value: ``` ((agenda . " %i %-12:c%?-12t% s") (todo . " %i %-12:c") (tags . " %i %-12:c") (search . " %i %-12:c")) ``` If you look at yours, the agenda part should have a `%e` in it: that's what displays the effort and getting rid of that should do what you want. There may be a width and a punctuation char (e.g the `%-12:c` part above says: display the category (%c) in a 12-char wide field, padded with spaces on the right (that's the `-12`) and followed by a colon (that's the \`:)). You can customize the variable: when you hit `C-h org-agenda-prefix-format RET`, you get the description of the variable (which you should read carefully - it is a somewhat complicated variable) as well as its current value, plus you get a link that allows you to customize the variable: that's the easiest way to modify it. In the customize buffer, just edit the format string associated with the agenda and get rid of the %e spec (including the width stuff in between the `%` and the `e`, if any). > 1 votes --- Tags: org-mode, org-agenda ---
thread-61029
https://emacs.stackexchange.com/questions/61029
Org mode: include LaTeX bibliography in the TOC
2020-10-07T04:44:12.603
# Question Title: Org mode: include LaTeX bibliography in the TOC This question is related to ox-bibtex. The snippet ``` #+BIBLIOGRAPHY: main abbrv ``` prints out an unnumbered section "Reference" excluded from the TOC in both LaTeX & html export. Is there a portable & Org mode specific way to include bibliography as a section in the TOC? # Answer > 1 votes There is no way to do this portably in Org mode AFAIK. This is only for LaTeX - if I figure out the HTML export, I'll edit, but at this point that's unlikely. `ox-bibtex` translates bibliography specs like this ``` #+BIBLIOGRAPHY: path/to/acm-comp-surveys.bib plain ``` to the following LaTeX code: ``` \bibliographystyle{plain} \bibliography{/path/to/acm-comp-surveys.bib} ``` and when you run `bibtex` on that, you will produce a `.bbl` file which looks like this: ``` \begin{thebibliography}{1} \bibitem{Finerman:1969:EN} Aaron Finerman. \newblock An editorial note. \newblock {\em ACM Computing Surveys}, 1(1):1--1, March 1969. \end{thebibliography} ``` If you look in the `article.cls` file, you find a definition of `thebibliography` environment that starts out like this: ``` \newenvironment{thebibliography}[1] {\section*{\refname}% ... ``` i.e. an unnumbered section with name `\refname`, which happens to be defined like this: ``` \newcommand\refname{References} ``` That explains what you see. But this means that all of this is under the control of LaTeX and not under the control of Org mode. So your only avenue of modifying things is to change the LateX and the easiest way to do that is to redefine `thebibliography` environment to do what you want - just copy the original definition into a file `mybib.sty` with a couple of modifications: first, use `\renewenvironment` since you are redefining an existing environment, second, use an unstarred section to make it numbered and third, change the title to whatever you want - I hardwire it to `Bibliography` here - the rest is copied verbatim: ``` \renewenvironment{thebibliography}[1] {\section{Bibliography}% \@mkboth{\MakeUppercase\refname}{\MakeUppercase\refname}% \list{\@biblabel{\@arabic\c@enumiv}}% {\settowidth\labelwidth{\@biblabel{#1}}% \leftmargin\labelwidth \advance\leftmargin\labelsep \@openbib@code \usecounter{enumiv}% \let\p@enumiv\@empty \renewcommand\theenumiv{\@arabic\c@enumiv}}% \sloppy \clubpenalty4000 \@clubpenalty \clubpenalty \widowpenalty4000% \sfcode`\.\@m} {\def\@noitemerr {\@latex@warning{Empty `thebibliography' environment}}% \endlist} ``` Now add ``` #+LATEX_HEADER: \usepackage{mybib} ``` at the top of your Org mode file and export again. That's it. --- Tags: org-mode, org-export ---
thread-61040
https://emacs.stackexchange.com/questions/61040
C-M-l locks the screen in Ubuntu
2020-10-07T13:27:41.990
# Question Title: C-M-l locks the screen in Ubuntu Emacs Manual says that `C-M-l` is to Scroll heuristically to bring useful information onto the screen (`reposition-window`). When I type `C-M-l` in Ubuntu, Emacs 27.1, the OS is automatically locking the screen. Which alternative keybinding could I use to call the `reposition-window` command? # Answer I accept the coments of @phils and @Stefan. We have to use `ESC`,if we are finding problem combination `C-M-*`. > 1 votes --- Tags: ubuntu ---
thread-47704
https://emacs.stackexchange.com/questions/47704
Disable mouse drag to select
2019-02-08T18:14:51.557
# Question Title: Disable mouse drag to select I often run into an issue where I will click in a Emacs frame to make it active and accidentally slide my cursor so that it changes from a click to a drag. This means that some text is highlighted which can change behavior of the next commands I run (I am using `evil-mode`, so this puts me into visual state, but this is applicable outside of evil mode as well). I don't want to completely disable the mouse, as I find it quite useful I just want to disable selecting text on a drag operation. I tried the following, but it lead to weird behavior (when the pointer leaving frames it will select text and it will still select one character sometimes). `(define-key evil-motion-state-map [down-mouse-1] 'ignore)` Is there a way to accomplish disabling drag to select (in evil specifically or outside)? # Answer If I understand you correctly, you want to set the point on click but *not* set the region on drag. You can enable this behaviour globally with: ``` (progn (global-set-key [mouse-1] 'mouse-set-point) (global-unset-key [down-mouse-1]) (global-unset-key [drag-mouse-1])) ``` > 0 votes --- Tags: frames, mouse, fullscreen ---
thread-61065
https://emacs.stackexchange.com/questions/61065
can't get company-reftex-labels to work properly
2020-10-08T13:57:17.797
# Question Title: can't get company-reftex-labels to work properly I have tried to set the company-backend as described on their github page and did not end up with the sweet resulting pop-up completion, in ref as in their image My image: their image: What am I doing wrong? My relevant configs are as follows ``` (defun require-package (package &optional min-version no-refresh) "Install given PACKAGE, optionally requiring MIN-VERSION. If NO-REFRESH is non-nil, the available package lists will not be re-downloaded in order to locate PACKAGE." (if (package-installed-p package min-version) t (if (or (assoc package package-archive-contents) no-refresh) (package-install package) (progn (package-refresh-contents) (require-package package min-version t))))) (require-package 'company) (add-hook 'after-init-hook 'global-company-mode) (eval-after-load "company" '(add-to-list 'company-backends 'company-auctex 'company-jedi 'company-math 'company-reftex-citations 'company-reftex-labels 'company-shell ) ) (setq company-dabbrev-downcase 0) (setq company-idle-delay 0) (require-package 'company-reftex) (add-hook 'LaTeX-mode-hook 'turn-on-reftex) ; with AUCTeX LaTeX mode (add-hook 'latex-mode-hook 'turn-on-reftex) ; with Emacs latex mode (setq reftex-plug-into-AUCTeX t) ``` Cheers! # Answer > 1 votes The following snippet works for me. I use `use-package`, so it is slightly different, but I hope it is easy enough to edit. You can evaluate this with `emacs -q` and then calling `M-x eval-buffer` on the snippet. ``` (require 'package) (setq package-user-dir (expand-file-name "~/.emacs.d/elpa/") package-enable-at-startup nil) (add-to-list 'package-archives '("melpa" . "https://melpa.org/packages/") t) (package-initialize) (unless (package-installed-p 'use-package) (package-refresh-contents) (package-install 'use-package)) (eval-when-compile (require 'use-package)) (defcustom dotemacs-extras-directory (expand-file-name "extras" user-emacs-directory) "Path for third-party packages and files." :type 'string :group 'dotemacs) ;; Enable Company (use-package company :ensure t :custom (company-idle-delay 0.0 "Recommended by lsp") (company-ispell-available t) (company-ispell-dictionary (expand-file-name "wordlist" dotemacs-extras-directory)) :config (global-company-mode 1)) ;; Enable LaTeX (use-package tex-site :ensure auctex :mode ("\\.tex\\'" . LaTeX-mode)) (add-hook 'LaTeX-mode-hook #'reftex-mode) (add-hook 'latex-mode-hook #'reftex-mode) (defun sb/company-latex-mode () "Add backends for latex completion in company mode." (use-package math-symbol-lists ; Required by ac-math and company-math :ensure t) (use-package company-math :ensure t) (use-package company-reftex :ensure t) (use-package company-bibtex :ensure t) (make-local-variable 'company-backends) (setq company-backends '(( company-capf ;; company-tabnine company-bibtex company-math-symbols-latex company-latex-commands company-math-symbols-unicode company-reftex-labels company-reftex-citations company-yasnippet company-files company-ispell company-dabbrev )))) (dolist (hook '(latex-mode-hook LaTeX-mode-hook)) (add-hook hook #'sb/company-latex-mode)) ``` Both `company-bibtex` and `company-reftex` work. You can check the completion provider on the modeline or through `M-x company-diag`. The downside is that all the completions are merged, I do not know how to fix it. You can see this issue. --- Tags: company-mode, reftex-mode ---
thread-61069
https://emacs.stackexchange.com/questions/61069
Face setting doesn't work for client sessions
2020-10-08T19:37:37.240
# Question Title: Face setting doesn't work for client sessions I wanted to change the colours of Anzu's counter, taking the foreground from the Isearch match background and the background from the fringes, like this So I evaluated ``` (face-spec-set 'anzu-mode-line `((t :foreground ,(face-attribute 'isearch :background) :background ,(face-attribute 'fringe :background))) 'face-defface-spec) ``` and it worked. I added it to my `init.el`, restarted the emacs server... and then it looked like this: How do I fix that? --- PS If I launch Emacs from the command line instead of opening a client frame, then the faces get the right colours. It also works if I put strings in place of the `face-attribute` forms: ``` (face-spec-set 'anzu-mode-line '((t :foreground "magenta3" :background "grey95")) 'face-defface-spec) ``` # Answer > 0 votes Update: Emacs 27 provides `server-after-make-frame-hook`, which makes it easier to copy face properties for client sessions. ``` (defun my-anzu-faces () (face-spec-set 'anzu-mode-line `((t :foreground ,(face-attribute 'isearch :background) :background ,(face-attribute 'mode-line-inactive :background))) 'face-defface-spec)) (if (daemonp) (add-hook 'server-after-make-frame-hook #'my-anzu-faces) (my-anzu-faces)) ``` This works for client sessions as well as stand-alone ones. --- Well, it seemed that the problem was that the face properties which I wanted `anzu-mode-line` to take were still unspecified at the time of setting it, so I kept on messing around with hooks and `with-eval-after-load` until I came up with this ``` (add-hook 'after-make-frame-functions (lambda (frame) (with-selected-frame frame (face-spec-set 'anzu-mode-line `((t :foreground ,(face-attribute 'isearch :background) :background ,(face-attribute 'fringe :background))) 'face-defface-spec)))) ``` As you can probably guess, I'm not sure it is the optimal solution, but it is a solution. # Answer > 0 votes Use `custom-set-faces` instead (not tested). ``` (custom-set-faces '(anzu-mode-line ((t (:foreground ,(face-attribute 'isearch :background) :background ,(face-attribute 'fringe :background)))))) ``` --- Tags: init-file, emacsclient, faces, server ---
thread-61085
https://emacs.stackexchange.com/questions/61085
org table apply formula from specific row onwards
2020-10-09T12:12:59.510
# Question Title: org table apply formula from specific row onwards ``` | BookmarkLevel | BookmarkPageNumber | ActualPageNumber | |---------------+--------------------+------------------| | 1 | 11 | | | 2 | 11 | | | 2 | 34 | | | 1 | 59 | | | 2 | 59 | | | 3 | | 3 | | 3 | | 10 | | 2 | | 17 | | 3 | | 17 | | 3 | | 29 | | 3 | | 35 | | 3 | | 39 | | 3 | | 43 | | 4 | | 43 | | 4 | | 45 | ``` #+tblfm: $2=$3+58 Where `BookmarkPageNumber` is empty, I would like to use `ActualPageNumber` (from the TOC) to calculate its values (by adding a constant to it). How should `tblfm` be written for the effect? # Answer In this particular situation, you could use a range formula to fill in rows 7 through the last row: ``` #+TBLFM: @7$2..@>$2 = $3 + 58 ``` Counting rows is probably not what you want to do though and is error-prone, so you could say ``` #+TBLFM: $2 = if ($2 > 0, $2, $3+58) ``` leaving the non-empty entries alone, and changing the empty entries (which in a numerical context evaluate to 0). See Formula Syntax for Calc but be forewarned that the conversions that Org mode makes behind the scenes sometimes make it frustrating to figure out a formula that works. The formula debugger is your friend but is not a panacea. Another possibility is using Lisp for the formula and handling the conversions yourself. E.g. here is a more robust check for empty vs 0 cells: ``` #+TBLFM: $2 = '(if (not (equal $2 "")) $2 (+ (string-to-number $3) 58)) ``` See Formula syntax for Lisp. > 1 votes --- Tags: org-table, formula ---
thread-61094
https://emacs.stackexchange.com/questions/61094
Replace selection in one movement
2020-10-09T21:43:16.663
# Question Title: Replace selection in one movement I'm getting started using spacemacs with vim bindings for editing and one thing I would like to do sometimes is replace some text with some other text. For example I might have ``` k x = (1 + 1) * x ``` and I want to select replace `(1 + 1)` with `2`. Normally in vim I would just type `f(v%s2<Esc>`. However in spacemacs `s` doesn't work on selections like it does in vim, this instead puts `2` around the selection ``` k x = 2(1 + 1)2 * x ``` Which is not what I wanted. (Strangely `s` seems to work perfectly in normal mode) Now obviously in this case I can just do `di` to delete and enter insert mode separately but in general `di` has some important drawbacks: * It cannot be repeated across several lines using visual selection mode (a very common use case) * It cannot be repeated with `.` since it is two actions. Is there another option that I could use to achieve the functionality of my old `s`? Or do I have to modify my configs somehow? # Answer > 2 votes Let me just preface this by saying that I am not very familiar with spacemacs except for the fact that it is similar to vim so I might be missing emacsy solutions. That being said, a friend of mine who uses spacemacs tested these suggestions for me and has confirmed that they work. --- You can just use the exact sequence you have been using but replace the `s` with a `c`. (As in `f(v%c2<Esc>`). You can also achieve the same effect without visual mode with the `c` command with the motion `ab` which is the motion over the whole of a parenthetical. Combined with the `f` command to reach the start of the parenthetical the whole set of commands would be `f(cab2<Esc>`. --- Tags: spacemacs, selection ---
thread-61083
https://emacs.stackexchange.com/questions/61083
Write a function using org refile interface to jump to item, with destination as an argument
2020-10-09T10:42:10.340
# Question Title: Write a function using org refile interface to jump to item, with destination as an argument I would like to create a function that uses the refile interface to jump to a heading (C-u C-c C-w or 'Refile-Goto'), where I can enter the filename and Heading as arguments. Following instructions here - org-refile to a known fixed location , I have written the following function that successfully refiles subtrees with arguments. ``` ;;Org-Refile with parameters (defun my/refile-params (file headline) (interactive) (let ((pos (save-excursion (find-file file) (org-find-exact-headline-in-buffer headline)))) (org-refile nil nil (list headline file nil pos)))) (map! :leader :desc "file away" "zf" (lambda () (interactive) (my/refile-params "~/orgnotes/casenotes.org" "Destination"))) ``` I have created another function that successfully calls Refile-Goto, but requires manually enter the destination. ``` ;;Org-Refile-Goto without parameters (defun my/refile-goto () (interactive) (setq current-prefix-arg '(4)) (call-interactively (org-refile))) (map! :leader :desc "file away" "zn" (lambda () (interactive) (my/refile-goto))) ``` All seems good, but when I combine the two as below, instead of just jumping, it refiles, and throws up a Wrong Type Argument error to boot. ``` ;;Org-Refile-Goto with Parameters *Not Working* (defun my/refile-params-goto (file headline) (interactive) (setq current-prefix-arg '(4)) (call-interactively (my/refile-params file headline))) (map! :leader :desc "Go to @In-Progress" "zg" (lambda () (interactive) (my/refile-params-goto "~/orgnotes/casenotes.org" "Destination"))) ``` All help greatly appreciated. NB: Using doom, if that helps understanding the keyboard mapping. Including the mapping lines, as they include 'lambda', which is mysterious black magic to me, so I may be getting it wrong. # Answer > 0 votes I learnt that `call-interactively` takes a symbol for a command, and no arguments. I was evaluating (my/refile-params file headline), then trying to interactively call the value it returns. That's not a command, so I got a wrong type argument error. Using `current-prefix-arg` and `call-interactively` wasn't working, so instead I passed the prefix argument as the first argument in the org-refile call, as below: ``` (defun my/refile-params-goto (file headline) (interactive) (let ((pos (save-excursion (find-file file) (org-find-exact-headline-in-buffer headline)))) (org-refile '(4) nil (list headline file nil pos)))) (map! :leader :desc "file away" "zg" (lambda () (interactive) (my/refile-params-goto "~/orgnotes/casenotes.org" "Destination"))) ``` Working just great now. --- Tags: org-mode ---
thread-56286
https://emacs.stackexchange.com/questions/56286
JetBrains Mono Ligatures Emacs27+
2020-03-22T10:41:48.160
# Question Title: JetBrains Mono Ligatures Emacs27+ I know there is already a post asking this, but the author is using Emacs 26.3 and for what I've read starting with Emacs 27 there is now proper support for ligatures, but they should be enabled in some way (?) I'm on Emacs 28 now, and I'd like to know the steps to obtain proper ligatures for my font. Btw I use Arch # Answer > 1 votes I think you misunderstand what's been included in Emacs 27. Emacs 27 includes a new *font backend* based on the HarfBuzz library. The front end bits still need to be worked on according to Eli Zaretskii in this reddit post > > I'm wondering if anyone is working on native support > > It's already supported in Emacs 27, but someone should code the Lisp part of that: define the character sequences to be ligated, figure out when and how to enable which parts of them, etc. > > Patches welcome. # Answer > 1 votes For Emacs 27.1 I had success with Mickey Petersen's ligature.el The requirements are pretty specific, but the installation instructions worked without modification for JetBrains Mono --- Tags: fonts, emacs27 ---
thread-61088
https://emacs.stackexchange.com/questions/61088
Emacs 27.1 daemon segfaulting when loading theme as emacsclient connects
2020-10-09T14:00:55.640
# Question Title: Emacs 27.1 daemon segfaulting when loading theme as emacsclient connects Emacs 27.1 from: 1. Homebrew/Linuxbrew, compiled from source, on either RHEL 6.10 or Ubuntu 16.04 Xenial. 2. EVM, using pre-compiled Travis binaries on Ubuntu 16.04 Xenial. crashes for me with a segmentation fault when connecting a second terminal-based `emacsclient`: ``` Starting Emacs daemon. Fatal error 11: Segmentation fault Backtrace: /tmp/tmp/emacs-27.1-travis-linux-xenial/bin/emacs[0x4aacc9] /tmp/tmp/emacs-27.1-travis-linux-xenial/bin/emacs[0x408f6b] /tmp/tmp/emacs-27.1-travis-linux-xenial/bin/emacs[0x4a959e] /tmp/tmp/emacs-27.1-travis-linux-xenial/bin/emacs[0x4a9933] /tmp/tmp/emacs-27.1-travis-linux-xenial/bin/emacs[0x4a9970] /lib/x86_64-linux-gnu/libpthread.so.0(+0x11390)[0x7f77c9db6390] Segmentation fault ``` I have tried building with debug symbols and the stack trace was no more informative. Sometimes it seems to take more variations/clients connecting before it crashes but a reliable reproduction is: 1. Start `emacs --fg-daemon`. 2. Connect with `emacsclient -t`. 3. Suspend the first client. 4. Connect with another `emacsclient -t`. 5. Server crashes. I have narrowed it down to theme loading, with this `.emacs` being sufficient: ``` (defun my/after-make-frame-functions-hook (frame) (with-selected-frame frame (load-theme 'tango-dark t))) (if (daemonp) (add-hook 'after-make-frame-functions 'my/after-make-frame-functions-hook)) ``` I have also tried this: 1. with `emacs -Q -l ~/.emacs --fg-daemon` to rule out any site or other init files. 2. with multiple different themes. 3. with `--bg-daemon` (more likely to mess up your console - it is easier to use `--fg-daemon` and test clients from a different terminal). 4. using the new `server-after-make-frame-hook` instead of `after-make-frame-functions`. 5. without `load-theme` but still running a hook/same structure - fixes the problem. 6. using `(server-start)` from inside an existing Emacs process - ***FIXES*** the problem. Does anybody else see this? Am I doing anything obviously wrong here? The code has worked for multiple major releases. What is the next thing to try? ***EDIT*** The same problem exists in the `emacs-27` branch (`0407b15500`) and `master` (`5824c209ba`). The GDB stack trace of master is more informative: ``` Program received signal SIGSEGV, Segmentation fault. 0x0000000000000000 in ?? () (gdb) bt #0 0x0000000000000000 in ?? () #1 0x0000000000490e45 in load_color2 (f=f@entry=0xa1d440, face=face@entry=0xb1e930, name=XIL(0x7ffff4d337dc), target_index=target_index@entry=LFACE_FOREGROUND_INDEX, color=color@entry=0x7fffffff80c0) at xfaces.c:1195 #2 0x0000000000491a6c in load_color (target_index=LFACE_FOREGROUND_INDEX, name=<optimised out>, face=0xb1e930, f=0xa1d440) at xfaces.c:1258 #3 map_tty_color (f=f@entry=0xa1d440, face=face@entry=0xb1e930, idx=idx@entry=LFACE_FOREGROUND_INDEX, defaulted=<optimised out>) at xfaces.c:6185 #4 0x0000000000491db7 in realize_tty_face (cache=0xa96c20, attrs=0x7fffffff8130) at xfaces.c:6259 #5 realize_face (cache=cache@entry=0xa96c20, attrs=attrs@entry=0x7fffffff8130, former_face_id=former_face_id@entry=0) at xfaces.c:5829 #6 0x00000000004933be in realize_default_face (f=<optimised out>) at xfaces.c:5745 #7 realize_basic_faces (f=f@entry=0xa1d440) at xfaces.c:5603 #8 0x0000000000495ae0 in update_face_from_frame_parameter (f=f@entry=0xa1d440, param=param@entry=XIL(0x2340), new_value=new_value@entry=XIL(0x7ffff4d337fc)) at xfaces.c:3669 #9 0x0000000000419773 in Fmodify_frame_parameters (frame=<optimised out>, alist=<optimised out>) at frame.c:3353 #10 0x000000000050ff53 in Ffuncall (nargs=3, args=args@entry=0x7fffffff8300) at eval.c:2806 #11 0x0000000000546958 in exec_byte_code (bytestr=XIL(0x7ffff4cbc72c), vector=XIL(0x7ffff4cbc6cd), maxdepth=<optimised out>, args_template=<optimised out>, nargs=nargs@entry=140737300383440, args=<optimised out>, args@entry=0x18) at bytecode.c:632 #12 0x000000000050fc11 in fetch_and_exec_byte_code (args=0x18, nargs=140737300383440, syms_left=<optimised out>, fun=XIL(0x7ffff4cbc6d0)) at eval.c:2928 #13 funcall_lambda (fun=XIL(0x7ffff4cbc6d0), nargs=nargs@entry=3, arg_vector=0x18, arg_vector@entry=0x7fffffff8488) at eval.c:3009 #14 0x000000000050fe9f in Ffuncall (nargs=4, args=args@entry=0x7fffffff8480) at eval.c:2820 #15 0x0000000000546958 in exec_byte_code (bytestr=XIL(0x7ffff4d43e34), vector=XIL(0x7ffff4d43ab5), maxdepth=<optimised out>, args_template=<optimised out>, nargs=nargs@entry=140737300937400, args=<optimised out>, args@entry=0x17) at bytecode.c:632 #16 0x000000000050fc11 in fetch_and_exec_byte_code (args=0x17, nargs=140737300937400, syms_left=<optimised out>, fun=XIL(0x7ffff4d43ab8)) at eval.c:2928 #17 funcall_lambda (fun=XIL(0x7ffff4d43ab8), nargs=nargs@entry=1, arg_vector=0x17, arg_vector@entry=0x7fffffff86b8) at eval.c:3009 #18 0x000000000050fe9f in Ffuncall (nargs=2, args=args@entry=0x7fffffff86b0) at eval.c:2820 #19 0x0000000000546958 in exec_byte_code (bytestr=XIL(0x7ffff4e983ec), vector=XIL(0x7ffff4d43805), maxdepth=<optimised out>, args_template=<optimised out>, nargs=nargs@entry=2, args=<optimised out>, args@entry=0x16) at bytecode.c:632 #20 0x000000000050fc11 in fetch_and_exec_byte_code (args=0x16, nargs=2, syms_left=<optimised out>, fun=XIL(0x7ffff4d43808)) at eval.c:2928 #21 funcall_lambda (fun=XIL(0x7ffff4d43808), fun@entry=<error reading variable: Cannot access memory at address 0x308>, nargs=nargs@entry=140737488324816, arg_vector=0x16, arg_vector@entry=0x2) at eval.c:3009 #22 0x000000000051278c in apply_lambda (fun=<error reading variable: Cannot access memory at address 0x308>, args=<optimised out>, count=<error reading variable: Cannot access memory at address 0x300>) at eval.c:2953 Backtrace stopped: previous frame inner to this frame (corrupt stack?) Lisp Backtrace: "modify-frame-parameters" (0xffff8308) "set-frame-parameter" (0xffff8488) "disable-theme" (0xffff86b8) "load-theme" (0xffff88d0) "progn" (0xffff8a18) "unwind-protect" (0xffff8ad8) "let" (0xffff8bf8) "my/after-make-frame-functions-hook" (0xffff8e70) "run-hook-with-args" (0xffff8e68) "make-frame" (0xffff9130) "server-create-tty-frame" (0xffff93c8) "server-process-filter" (0xffff9948) ``` # Answer > 0 votes This is a bug in Emacs. The current workaround is not to load a theme with a suspended frame. This can often happen if you use daemon mode with init code like that shown. Theme-loading code of that style can be adjusted to not run more than once. For example, see later answers to this question. There is a patch in the `emacs-27` branch already but obviously it is not released yet. The patch currently only prevents a crash; it errors when you try to load a theme with a suspended frame. ***EDIT*** The patch has been modified to allow loading themes with suspended frames. --- Tags: themes, crash, emacs27 ---
thread-61101
https://emacs.stackexchange.com/questions/61101
Keep displaying current org heading info in some way
2020-10-10T12:07:31.353
# Question Title: Keep displaying current org heading info in some way Often I have a problem that I browse through the content of the heading but I forget what is a heading I'm currently at. So I leave the mark, go back to the heading, read it, and jump back to the mark. It disrupts the workflow and wastes time. I think the solution to this problem would be displaying the current heading (or entire heading path separated by "/" or similar) in the echo area while I browse/edit heading content or make it stick to the top in a similar way `position: sticky` in CSS3 works. Are there any plugins or configuration options that address this issue? # Answer > 6 votes You can add something to either the mode line or the header line to keep track of such things. Here I use the header line because the mode line is usually rather crowded, whereas the header line is not used as frequently. You can add a header line to any buffer by ``` (setq header-line-format "foo") ``` That makes `header-line-format` a buffer-local variable with the value `foo` which is displayed at the top of the buffer window. Whenever the value of `header-line-format` changes, the buffer is marked for redisplay, so you always see the currently set value. You can have the header line dynamically change by doing this: ``` (setq header-line-format '(:eval FORM)) ``` The form is evaluated whenever emacs thinks that it should be \- but you can force the re-evaluation if needed - my experiments show that it is not needed: emacs does the right thing on its own. So all we have to do for this particular case is write a function `ndk/org-breadcrumbs` that calculates what you want to show and do ``` (setq header-line-format '(:eval (ndk/org-breadcrumbs))) ``` The function is modeled after a similar calculation that is done in the agenda for the `%b` specification in `org-agenda-prefix` where the name `breadcrumbs` is used to indicate the chain of headings that get you to the current heading. ``` (defun ndk/heading-title () "Get the heading title." (save-excursion (if (not (org-at-heading-p)) (org-previous-visible-heading 1)) (org-element-property :title (org-element-at-point)))) (defun ndk/org-breadcrumbs () "Get the chain of headings from the top level down to the current heading." (let ((breadcrumbs (org-format-outline-path (org-get-outline-path) (1- (frame-width)) nil "->")) (title (ndk/heading-title))) (if (string-empty-p breadcrumbs) title (format "%s->%s" breadcrumbs title)))) (setq header-line-format '(:eval (ndk/org-breadcrumbs))) ``` If you just want the title of the containing section, you can just use `ndk/heading-title`: ``` (setq header-line-format '(:eval (ndk/heading-title))) ``` but the extended `breadcrumbs` version seems attractive to me. Setting the `header-line-format` variable can be done for a single buffer as above, or if you want this for *every* Org mode buffer it can be done in the mode hook: ``` (defun ndk/set-header-line-format() (setq header-line-format '(:eval (ndk/org-breadcrumbs)))) (add-hook 'org-mode-hook #'ndk/set-header-line-format) ``` --- Tags: org-mode ---
thread-61100
https://emacs.stackexchange.com/questions/61100
How does if() work in org spreadsheets?
2020-10-10T11:49:40.190
# Question Title: How does if() work in org spreadsheets? I got the impression from the manual that ``` | a | | | b | | #+TBLFM: $2=if($-1==a, 1, 0) ``` should produce "1" in the first row and "0" in the second. But instead I get ``` | a | 1 | | b | b = a ? 1 : 0 | #+TBLFM: $2=if($-1==a, 1, 0) ``` What am I misunderstanding here? # Answer You are probably better off using Lisp formulas for things like this. As @db48x's answer points out, there are a couple of cooks in that kitchen and what they are doing is not always obvious. Formula debugging can help but it is not always effective (I presume that's how @db48x discovered the "(a)" thing, but that may not be the case). I find the string conversions unpredictable, so for non-numeric things in particular, I tend to stay away from calc formulas and do it in Lisp instead. In this particular case, try the following: ``` | a | 1 | | b | 0 | #+TBLFM: $2 = '(if (string= $-1 "a") 1 0) ``` The disadvantage(?) is that you have to learn some Lisp, but that's a good thing: otherwise, how are you going to tinker with all those Emacs settings? > 5 votes # Answer I don't know exactly what's going on here, but after doing a little debugging I found that this works: ``` | a | | | b | | #+TBLFM: $2=if("$1"=="(a)", 1, 0) ``` It looks to me like it's doing algebraic simplification in order to get an answer, and if that fails it can be left with a more complicated form than you expected. `b = a ? 1 : 0` is a ternary expression that hasn't been evaluated to a value, presumably because `a` and `b` are treated as variables rather than strings. So you have to put them in quotes, but then "$-1" evaluates to a string with parenthesis for unknown reasons, so you have to include those parentheses on the other side of the equation as well. > 3 votes --- Tags: org-mode, org-table, calc, spreadsheet ---
thread-61109
https://emacs.stackexchange.com/questions/61109
How do i implement my own hooks in elisp?
2020-10-10T17:13:36.707
# Question Title: How do i implement my own hooks in elisp? What code do i need to implement in order to create a hook which can be set by the user and which is called in my own function? # Answer Welcome to SE (emacs)! Look up `run-hooks` which gives the whole story but the tl;dr is expose a hook variable `my-fancy-hook` to the user and at the right place in yr own code put: ``` (run-hooks 'my-fancy-hook) ``` > 2 votes --- Tags: hooks ---
thread-61108
https://emacs.stackexchange.com/questions/61108
Make :tangle don't add a newline at the end of the file
2020-10-10T17:09:10.017
# Question Title: Make :tangle don't add a newline at the end of the file # The context I'm storing all my custom defined yasnippet snippets in an Org file (see below) ``` $ cat ~/.emacs.d/snippets/snippets.org #+PROPERTY: header-args:yasnippet :mkdirp yes #+begin_src yasnippet :tangle ~/.emacs.d/snippets/org-mode/a # key: a # -- a foo bar #+end_src #+begin_src yasnippet :tangle ~/.emacs.d/snippets/org-mode/b # key: b # -- b foo bar #+end_src ``` # The problem When tangling any code block present in the Org file shown above (i.e. snippet definition) a newline is inserted at the end of the last line which is causing yasnippet insert a newline whenever a snippet is triggered. I don't want a newline to be inserted whenever an snippet is triggered since newlines are unnecessarily added to my files and I manually have to delete them. The behavior of yasnippet of adding newlines after an snippet expansion is mentioned in the FAQ file located in the yasnippet master branch repository > If there is a newline at the end of a snippet definition file, YASnippet will add a newline when expanding that snippet. # Additional context It is worth mentioning that this problem is not present when creating a new snippet with `yas-new-snippet` since the variable `require-final-newline` is set to `nil` in the opened buffer. The behavior present in the buffers which are opened after `yas-new-snippet` has been executed is set by `yasnippet` itself. ``` $ grep -R 'require-final-newline' ~/repos/yasnippet ... ~/repos/yasnippet/yasnippet.el: (set (make-local-variable 'require-final-newline) nil) ~/repos/yasnippet/yasnippet.el: (set (make-local-variable 'require-final-newline) nil) ... ``` # The question * Is there a way to change the behavior of tangling so that a newline is not inserted at the end of the file? * What other workarounds could I try to overcome this issue? I was thinking in executing a function that iterates over all files in my custom snippets directory and delete the last character if and only if it is a newline. # Answer > 3 votes Here's an implementation using `org-babel-post-tangle-hook` as I hinted in my comment: ``` #+PROPERTY: header-args:yasnippet :mkdirp yes :padline no * foo #+begin_src yasnippet :tangle ./snippets/a # key: a # -- a foo bar #+end_src #+begin_src yasnippet :tangle ./snippets/b # key: b # -- b foo bar #+end_src * Code :noexport: #+begin_src emacs-lisp (defun ndk/zap-newline-at-eob () (goto-char (point-max)) (when (equal (char-before) ?\n) (delete-char -1) (save-buffer))) (add-hook 'org-babel-post-tangle-hook #'ndk/zap-newline-at-eob) #+end_src ``` When the hook runs, each function in the hook is called on each tangled file. The function zaps one newline at the end of the file and saves the buffer. That creates backup files, so as the OP points out in a comment, one might want to prevent that by locally binding `make-backup-files` to nil: ``` (defun ndk/zap-newline-at-eob () (let ((make-backup-files nil)) (goto-char (point-max)) (when (equal (char-before) ?\n) (delete-char -1) (save-buffer)))) ``` You probably want to remove the function from the hook after you are done here (unfortunately, setting the hook locally in this buffer does not work: the tangling happens in a different buffer and only the global value of the hook is in effect there). I doubt that you want the newline zapping in anything other than yasnippet blocks, so adding a code block like this will help: ``` #+begin_src emacs-lisp (remove-hook 'org-babel-post-tangle-hook #'ndk/zap-newline-at-eob) #+end_src ``` --- Tags: org-mode, yasnippet, tangle ---
thread-61115
https://emacs.stackexchange.com/questions/61115
How to pass the current scopes function symbol as an argument to an elisp function
2020-10-10T19:18:21.017
# Question Title: How to pass the current scopes function symbol as an argument to an elisp function I am trying to create an org-capture template which works with yankpad and yasnippets to such that if I am working with some c code like this: example.c ``` static int somefunc(int a) { if (a ==5) { return 1; } else { return 0; } } ``` I want to be able to, with a single org-capture, yank the entirety of the function and its signature into an org file like so: example.org ``` #+NAME: example_proto #+BEGIN_SRC C int somefunc(int a); #+END_SRC #+NAME: example_func #+BEGIN_SRC C static int somefunc(int a) { if (a ==5) { return 1; } else { return 0; } } #+END_SRC ``` This requires the following: * Get the scope of the current function. * Get the prototype of the current function. * Pass these into an org-capture template. * Use yasnippets in the org-capture template. The main piece I can't figure out is how to find out what function defines the current scope programmatically so that I can pass it as an argument to other elisp functions (to determine scope, callees, etc). If someone can point me in the right direction that'd be much appreciated. # Answer > 1 votes You'll end up doing it the same way most programming modes do syntax highlighting: by matching regular expressions against the buffer contents. You'll want to search backwards for the beginning of the function, and then search forwards from there to find the end of it. Using LSP is a nice idea, but the protocol doesn't deal in the actual syntax of the document; it's all done by cursor position. When you want to jump to the definition of a symbol, for example, the editor sends the current cursor position and asks the server for the cursor position of the definition. Edit: though because you're doing this for C, you can just reuse `narrow-to-defun`; it will at least find the boundaries of the function for you. Doesn't work for all languages, but it would work for most. --- Tags: yasnippet, org-capture, c, lsp, symbol-function ---
thread-61119
https://emacs.stackexchange.com/questions/61119
How to track down where Emacs message "<Scroll_Lock> is undefined" comes from?
2020-10-10T22:06:43.900
# Question Title: How to track down where Emacs message "<Scroll_Lock> is undefined" comes from? I am using Emacs 25.5 and now am getting the message: "\<Scroll\_Lock\> is undefined" appearing regularly in the *Messages* buffer. If I turn on debug-on-error, it doesn't stop on it and show me where it is coming from. I suspect it is related to one of the issues preventing me from upgrading to Emacs 27.1 (which is scroll-lock mode keeps getting turned on, which is a feature I don't want). But I don't know what is triggering it or how to even grep for it. It's not in any of my personal .el files. By the way this Lenovo Flex 5 doesn't even have a key labeled scroll lock. Perhaps it is a feature of the touchpad. # Answer > 1 votes I figured out that I should add the following code to my .emacs file: ``` (defvar in-xxx-message nil) (defun xxx-message (&rest args) (cond (args (let ((result (apply 'format args))) (if (and (not in-xxx-message) (or (string-match "<Scroll_Lock>" result) (string-match "is undefined" result) ) ; or ) ; and (let ((in-xxx-message t)) (error result) ) ; let ;; else (orig-message result) ) ; if ) ; let ) ; args (t (orig-message)) ) ; cond ) ; defun (defalias 'orig-message (symbol-function 'message)) (defalias 'message 'xxx-message) ``` Then I got the `*Backtrace*` buffer I was hoping for. It turns out that `subr.el` defines a function `undefined()` that it maps to all keys that don't have a keydef. So, my "hack" was the solution I was looking for. I presume something has happened in a recent update (to Windows perhaps) that has started returning this keycode. I still haven't found out why, but at least I know how to make it a no op. This isn't quite the answer I want, but I did figure out that I could just add a keybinding for it and solve my *problem*. I would still like to know how to find obscure messages in Emacs and get to the root cause. If I find a better way, to find messages I will add that as an answer. (Or maybe I'll get lucky and someone will tell me.) Anyway, my workaround: ``` (defun do-nothing () (interactive)) (global-set-key (kbd "<Scroll_Lock>") 'do-nothing) ``` --- Tags: key-bindings, debugging ---
thread-23923
https://emacs.stackexchange.com/questions/23923
Change dd command in evil mode to not write to clipboard
2016-06-12T20:54:09.130
# Question Title: Change dd command in evil mode to not write to clipboard I would like to use normal modes commands like `d` `c` `x` etc without the content being copied to clipboard. I want to make emacs so that only `y` command will write anything to the clipboard. Other commands like `d` should only delete the content without writing anything to the clipboard. # Answer `(setq save-interprogram-paste-before-kill nil)` Separating the clipboard and kill-ring is more efficient for my workflow, for clipboard, I use https://github.com/rolandwalker/simpleclip API `simpleclip-set-content` and `simpleclip-get-content` > 1 votes # Answer If you do `C-h k d` you'll see that `d` is bounded to `evil-delete`, so: ``` (define-key evil-normal-state-map "dd" 'my/very-special-evil-delete) ``` should do the work. There's a "`/dev/null`-ish" (`blackhole`) register in vim which probably `evil` mocks. > 0 votes # Answer This adds an advice around evil stuff to drop it to `_` register. ``` (defun meain/evil-delete-advice (orig-fn beg end &optional type _ &rest args) "Make d, c, x to not write to clipboard." (apply orig-fn beg end type ?_ args)) (advice-add 'evil-delete :around 'meain/evil-delete-advice) (advice-add 'evil-change :around 'meain/evil-delete-advice) ``` > 0 votes --- Tags: evil, clipboard ---
thread-61122
https://emacs.stackexchange.com/questions/61122
Regex to replace subset of repeated pattern
2020-10-11T02:26:00.020
# Question Title: Regex to replace subset of repeated pattern ``` ABC、DEF, GHI, JKL、MNO PQR、STU, VWX、YZ ``` How do I replace all `,` s with in the repeated pattern above? The repeated pattern can be mapped with the regex below: ``` "^\\([A-Z]+、\\)\\(\\([A-Z]+\\), \\)+" ``` However, because the `,` is a subset of group `\\2`, even though it can be separated from its preceding letters in the regex, there is no way to replace it using `replace-regexp` without some form of nested group code. Also, `DEF,` doesn't seem the match like `GHI,` and `STU,` with the regex. ``` (replace-regexp "^\\([A-Z]+、\\)\\(\\([A-Z]+\\), \\)+" "\\1\\2、") ``` What's the right way to do this, then? --- # Update: @jue's answer below resulted in this: # Answer In elisp you normally search for what you're looking for in a loop, potentially establishing sub-groups of interest, and then you act on the match data if the search succeeded. Here you can simply replace every `,` with within the subgroup. ``` (save-excursion (while (re-search-forward "^[A-Z]+、\\(\\(?:[A-Z]+, \\)+\\)" nil t) (goto-char (match-beginning 1)) (let ((bound (match-end 1))) (while (search-forward "," bound t) (replace-match "、"))))) ``` Edit: Or more simply: ``` (save-excursion (while (re-search-forward "^[A-Z]+、" nil t) (while (re-search-forward "\\=\\([A-Z]+\\), " nil t) (replace-match "\\1、 ")))) ``` That `\=` construct anchors the match to the current position of point, so that only the intended sequence of cases will be matched for that loop. Other options are supplying a BOUND argument to the search, or using narrowing to temporarily limit the searchable text. --- > Also, DEF, doesn't seem the match like GHI, and STU, with the regex. That's because re-builder was highlighting the text which was referred to by back-reference `\2` (being the ultimate match for that repeated subgroup) differently to the rest of the text. Try adding more matches for that group in a line, and it will become more obvious. > 2 votes --- Tags: regular-expressions, replace ---
thread-61137
https://emacs.stackexchange.com/questions/61137
How to shorten signature display in echo area?
2020-10-11T18:38:51.737
# Question Title: How to shorten signature display in echo area? Currently, the signature of the current function the pointer is on is shown as follows: as you can see, the signature is so large that it overflows the echo area. I was wondering if there could be a way to shorter to something like this: ``` 1/1 | FunctionName(..., current_arg type, ...) (return_type_n, return_type_m) ``` in other words, the signature from the screenshot shows as: ``` 1/1 | CreateSubscription(..., identificacion_tipo model.IdentificacionTipo, ...) (*service.Subscription, error) ``` # Answer The string displayed by `lsp-mode` is not generated by `lsp-mode` but by the server. If you want to achieve that open a feature request against the server that you are using. > 2 votes --- Tags: lsp-mode ---
thread-61148
https://emacs.stackexchange.com/questions/61148
pyvenv conditional on hostname
2020-10-12T12:45:06.420
# Question Title: pyvenv conditional on hostname I'm trying to setup activating virtual environments conditional on hostname. Until recently I've been using... ``` (pyvenv activate "~/.virtualenv/default") ``` ...across all hosts, but because work laptop is locked down and stuck on an old (3.6.9) version that isn't going to get updated any time soon and I've have started using features of Python 3.8.3 I've switched to using the Conda Virtual Environment which is installed in `~/.miniconda3`. I've read a few threads and based on this and this I could write an `if` statement. However, I prefer the solution here, so I've started with... ``` (setq virtualenv-byhost '(("kimura" . "~/.virtualenvs/python3_9") ("work" . "~/.miniconda3/"))) ``` Next step though has me a little stumped since I'm still getting started with Lisp and haven't sat down and started learning it formally. ``` (pyvenv-activate (cdr (assoc system-name virtualenv-byhost))) ``` If I understand it `(assoc system-name virtualenv-byhost)` associates whatever `system-name` returns with the `virtualenv-byhost`, but how does it know which to pick and pass onto the parent `pyvenv-activate`? Is that what `cdr` is doing and if so what is it doing and how? # Answer You can figure this one out on your own by using `C-x C-e` to evaluate the individual forms. For example if you place point after `system-name` and hit `C-x C-e`, it will display your hostname (say, "kimura") in the echo area. If you reposition point after `(assoc system-name virtualenv-byhost)`, it will display `("kimura" . "~/.virtualenvs/python3_9")`. Repeating this with point after `(cdr (assoc system-name virtualenv-byhost))` will display `"~/.virtualenvs/python3_9"`. From this you can deduce that `pyenv-activate` receives a string denoting the path associated with the host name. One more thing to use here is `F1 v` to inspect variables and `F1 f` to inspect functions. It will tell you that `system-name` holds the hostname, `assoc` looks up a pair in an association list (which `virtualenv-byhost` happens to be) and `cdr` returns the tail of a pair. Once you learn the Lisp basics, you'll be able to figure out everything that way, by using the Emacs introspection, evaluation and documentation facilities on everything you don't know yet. > 1 votes --- Tags: conditionals ---
thread-61135
https://emacs.stackexchange.com/questions/61135
Get bibtex key from helm-bibtex
2020-10-11T15:48:26.617
# Question Title: Get bibtex key from helm-bibtex I would like to get the bibtex key of references in my `.bib` database as a string via `helm-bibtex`. ``` (defun get-bibtex-key () (interactive) (with-temp-buffer (helm-bibtex) (if (string-prefix-p "cite" (buffer-string)) (substring (buffer-string) 5) ;; Remove "cite: " from string. (buffer-string)) (buffer-string))) ``` The code above correctly returns the desired value, but inserts text into the current buffer instead of storing its value within the `get-bibtex-key` function-variable as a string, which makes further deployment such as this impossible: ``` (bibtex-completion-get-entry (get-bibtex-key)) ``` The above code when run just dumps the value returned by `(get-bibtex-key)` into the current buffer. How can I get output from `(helm-bibtex)` behave like the code below? ``` (with-temp-buffer (insert "Hi!") (buffer-string)) ``` # Answer > 2 votes You can also get the keys using `helm-marked-candidates`: ``` (defun get-bibtex-key (_) (let ((keys (helm-marked-candidates))) (print keys))) (helm-add-action-to-source "Get bibtex keys" 'get-bibtex-key helm-source-bibtex 0) ``` Then: 1. `M-x helm-bibtex` 2. `M-a` 3. `RET` # Answer > 1 votes If I understand correctly, you can use the `(bibtex-completion-candidates)` function, which returns a list of bibtex items. You then get the list containing the "=key=" string using `assoc`, taking the `cdr` (last) element of the alist which is the citation key. Finally pass this list of keys through `completing-read` so you can select one from the list, returning it as a string: ``` (defun get-bibtex-key () (interactive) (completing-read "Citation key: " (mapcar #'(lambda (x) (cdr (assoc "=key=" x))) (bibtex-completion-candidates)))) ``` --- Tags: string, helm-bibtex ---
thread-61133
https://emacs.stackexchange.com/questions/61133
Setting `scroll-margin` for `term-mode` using `unless` is not working
2020-10-11T14:17:21.910
# Question Title: Setting `scroll-margin` for `term-mode` using `unless` is not working I want to set default value of `scroll-margin` to 3 but for `ansi-term` I want it to be 0. To do this I have added a hook to `term-mode-hook` which worked fine. ``` (setq scroll-margin 3) (add-hook 'term-mode-hook (lambda () (make-local-variable 'scroll-margin) (setq scroll-margin 0))) ``` But earlier I used `unless` to do the same thing which didn't work and I don't understand why. Could someone please help why below snippet didn't work to do the same task? ``` (unless (derived-mode-p 'term-mode) (setq scroll-margin 3)) ``` # Answer When you add the second bit of code into your init.el: ``` (unless (derived-mode-p 'term-mode) (setq scroll-margin 3)) ``` and that code gets executed, it asks: "Is the mode of the current buffer a derived mode of `term-mode`?" - the answer is "No", since the current buffer is `*scratch*`, the major mode is `lisp-interaction-mode` and that is *not* a derived mode of `term-mode`. You can do that experiment yourself: create a file `foo.el` in the current directory and add this to is: ``` (message (symbol-name major-mode)) (message (buffer-name)) (message (if (derived-mode-p 'term-mode) "True" "False")) (unless (derived-mode-p 'term-mode) (setq scroll-margin 3)) ``` Now start up emacs with this file as your init file: ``` emacs -Q -l foo.el` ``` and check the `*Messages*` buffer - you should see something like this: ``` lisp-interaction-mode *scratch* False ``` As you can see, the conditional evaluates to nil, so the setting of `scroll-margin` is skipped.\[1\] To summarize: when the contents of init.el are evaluated, that is done in a buffer that is unrelated to any `term-mode` buffer you later create, so it cannot possibly have an effect. The first code fragment: ``` (setq scroll-margin 3) (add-hook 'term-mode-hook (lambda () (make-local-variable 'scroll-margin) (setq scroll-margin 0))) ``` says: unconditionally set `scroll-margin` to 3. Then, when you create a new buffer and set its major mode to `term-mode` (or a derived mode of it), the `term-mode-hook` is run: that calls all of the functions in the hook and in particular the function you added, which sets `scroll-margin` to 0 locally in that buffer. The effect is that `scroll-margin` is 3 in all buffers, except for `term-mode` buffers (and buffers whose mode is a derived mode of `term-mode`) where `scroll-margin` is set to 0 for those buffers only. \[1\] The details might vary, depending on how exactly you start. E.g. if I copy the above `foo.el` to `$HOME/.emacs` and start up emacs without any options, I get `fundamental-mode` instead of `lisp-interaction-mode`but there is no other significant difference. > 0 votes --- Tags: term, conditionals ---