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-58502
https://emacs.stackexchange.com/questions/58502
How to make Tramp execute only if address is reachable?
2020-05-14T02:00:51.393
# Question Title: How to make Tramp execute only if address is reachable? So I have a couple of VM I'm using (*mainly for experiment*) I use Tramp a lot on a particular file in the VM, so I started to use this: ``` (find-file "/ssh:vm@192.168.122.141:/home/vm/test.org" t) ``` I put that in my init file, so it always connects when I launch emacs... except that most of the time, I didn't plan on using the vm, so it cannot connect to it (*since the vm isn't opened before emacs is launched*) emacs stop halfway in loading the init file. So how could i make it so the aforementioned line of elisp would only open the file if the address is reachable? # Answer First of all, isn't a great idea opening remote files from your init files. I'd use bookmarks or whatever else to open them quickly when needed, also, I'd rather use any sync service like *syncthing* or a `rsync` cron task to keep them synced if, as you seem to suggest, the file also lies elsewhere. If you **absolutelly** need to do it, I'd check if the server is up using something like this (*assuming you're on some kind of un\*x*): ``` (let ((out (shell-command-to-string "nc -v -z -W 2 192.168.122.141 22"))) (if (string-match "succeeded" out 0) (find-file "/ssh:vm@192.168.122.141:/home/vm/test.org" t) (message "server down"))) ``` While probably there is a pure elisp way to do it, I'd prefer calling `nc` because is straightforward, usually comes installed by default and there are plenty of examples of its use. In this case `-W` specifies the timeout. > 1 votes --- Tags: tramp ---
thread-58515
https://emacs.stackexchange.com/questions/58515
converting c-mode hooks to use-package fails in non-obvious ways
2020-05-15T01:19:55.233
# Question Title: converting c-mode hooks to use-package fails in non-obvious ways Emacs version 26.3 on a mac I have this (simplified) c(c)-mode config: ``` (add-hook 'c-mode-common-hook '(lambda () (c-set-style "bsd"))) ``` which works when I visit a c file. When I convert to ``` (use-package cc-mode :config (c-set-style "bsd") ) ``` and restart emacs, this snippet gets applied to the *scratch* buffer and I get this odd error: > `Debugger entered--Lisp error: (error "Buffer *scratch* is not a CC Mode buffer (c-set-style)")` The scratch buffer is shown as a Fundamental buffer, not an interactive-lisp buffer. Strangely, any added config, even a `:bind (("C-c t" . tags-search))` fixes this. So, with this, ``` (use-package cc-mode :bind (("C-c t" . tags-search)) :config (c-set-style "bsd") ) ``` when I visit a c file, say `foo.c`, I now get > `Debugger entered--Lisp error: (error "Buffer foo.c is not a CC Mode buffer (c-set-style)")` The buffer/file is loaded, but the mode is Fundamental. Is there a good way to use use-package with cc-mode, given that it supports modes for many different types of code and separable hooks for a lot of these? Thanks, Kannan # Answer The code after `:config` runs as soon as the package is loaded, which is when you config file is loaded unless you delay loading the package somehow. So the `c-set-style` function is getting called somewhere except a `c-mode` file and triggering an error before Emacs is even able to switch `*scratch*` into the proper mode. Adding `:bind` appears to fix the problem as `:bind` implies `:defer`, which delays loading the package until needed. `use-package` doesn't remove the need for hooks, it just changes where you define them. Put your `add-hook` in the `:config` section of `use-package` ``` (use-package cc-mode :config (add-hook 'c-mode-common-hook (lambda () (c-set-style "bsd"))) ) ``` > 2 votes --- Tags: use-package, cc-mode ---
thread-58518
https://emacs.stackexchange.com/questions/58518
run Emacs remotely in a webpage?
2020-05-15T07:28:44.357
# Question Title: run Emacs remotely in a webpage? I am just curious: *Is there a way to run Emacs remotely from a webpage?* For example, one can set up a JupyterHub on a Ubuntu server so that many users can access server programs from a webpage. Can emacs be set up on a central server and accessed using webpages in a similar way? (I know non-gui mode emacs can be executed in Juptyer's webpage-based terminal. I'm curious if a GUI version can be also executed from within a webpage) # Answer > 2 votes The Spacemacs folks did it for some time on their homepage using Docker and Xpra, this thread explains the details: https://github.com/syl20bnr/spacemacs/issues/8634 --- Tags: web-browser, jupyter ---
thread-58522
https://emacs.stackexchange.com/questions/58522
How to `ediff-buffer` with ansi-colors (script output)? `ediff-file` works!
2020-05-15T09:02:40.187
# Question Title: How to `ediff-buffer` with ansi-colors (script output)? `ediff-file` works! # Context: files with ANSI and other terminal color codes. I often record terminal transcripts using the traditional `script` program or `expect`. Colored `ls` output, colored `grep` matches, `mc` and other interactive programs, everything works great and record is faithful! # What works: replaying, opening in emacs * One can replay such files in a terminal, either fast e.g. `cat` or on own rhythm using `less -r` (or `less -R` to see backspaces `^H` instead of obey them). * One can open them in `emacs` and even have emacs automatically apply relevant mode, for example my `.emacs.d` applies this to any file matching `script_*.txt`: ``` (add-hook 'text-mode-hook (lambda () (when (string-match "script_.*\.txt$" (buffer-name)) (progn (format-decode-buffer 'backspace-overstrike) (format-decode-buffer 'ansi-colors) (hide-dos-eol) (face-remap-add-relative 'default '((:foreground "white" :background "black"))) )))) ``` # What fails: emacs accepts `ediff-files`, refuses `ediff-buffers`. Why? How to solve? ## Detail of what works: comparing with `ediff-files` works This opens files straight into `ediff`, perfectly: ``` emacs --eval '(ediff-files "script_file1.txt" "script_file2.txt" )' ``` Differences are shown, colors from ANSI codes are blended with colors from `ediff` which was not expected as obvious. Calling `ediff-files` interactively also works. The fact is, I just figured out `ediff-files` works, while searching to write this question. I never `ediff-files` because it's much more convenient to open files with any of the convenient ways (`dired`, etc) then `ediff-buffer` after opening. `ediff-buffer` offers straightforward completion among the opened buffers, which is more selective/relevant. ## Detail of what fails: opening files interactively then invoking `ediff-buffers` fails `ediff` doesn't start, minibuffer shows: > "Sorry, \`ansi-colors' format is read-only" Notice that the very same buffers that have just been compared using `ediff-files`, when closing `ediff` then calling `ediff-buffers` yield same failure. ## Detail of what fails: saving file Trying to save a file decoded with `tty-format`/`ansi-colors` fails, too. # How to solve? A good netizen searches before they ask. Error message appears in package tty-format. Browsable copies of source code appear in various places, e.g. on https://github.com/grantdhunter/dotfiles/blob/8c11b417a373d4a8eb7a4b3772ebf956e825edfc/emacs.d/tty-format.el#L226 It looks like there is an avoidable obstacle. It looks like buffers opened with ansi-color encoding have "lost something", they have been reencoded internally by emacs and cannot be saved again. I can understand that ANSI codes that move cursor around to produce a composite buffer make not obvious what to do when saving again. ## Possible workaround: recovering convenience of `ediff-buffer` I have an idea of a possible workaround but am not savvy enough in emacs-lisp. Q1: Can someone make a function which would offer completion by buffer names (like `ediff-buffers`) but would actually figure out underlying files and calls `ediff-files` on them? Any better idea is welcome. ## Possible workaround for impossibility to save: instruct emacs to save them into another format, possibly warning about lost information This makes sense when saving snippets of text, e.g. as plain text, as color HTML, whatever. (Notice: `htmlize-buffer` does not fit, practically does no better than plain text.) Q2: Is there a way to tell emacs "when saving this file, instead of refusing at all, offer me to save to a different location and format"? I expect this would have a side-effect of allowing `ediff-buffers` to work immediately and lose color information, but maybe not. ## Something else? Perhaps there is another way to handle files with ANSI color codes that doesn't have these problems at all? Thanks anyway. # Answer Replacing tty-format with xterm-color appears to provide some of the expected benefits stated in the question text, while adding a risk of destroying information by overwrite with plain text. ## Cf. above "recovering convenience of ediff-buffer" `ediff-buffer` works again. ## Cf. above "instruct emacs to save them into another format" As soon as a buffer is opened, it is marked as "modified". Saving it saves a plain-text version of the text, keeping normal characters, plus the obvious linefeed, plus BS (a.k.a. 0x08, `^H`) and CR (0x0D, `^M`). ## How to get this behavior Here's how I adjust in `.emacs` my startup script to associate this to all files matching `script_*.txt`. ``` (require 'xterm-color) (add-hook 'text-mode-hook (lambda () (when (string-match "script_.*\.txt$" (buffer-name)) (progn (xterm-color-colorize-buffer) (hide-dos-eol) (face-remap-add-relative 'default '((:foreground "white" :background "black"))) )))) ``` ## What is not fully satisfying One has to remember not to save file over the same name because it immediately destroys all existing color information. > 1 votes --- Tags: ediff ---
thread-58523
https://emacs.stackexchange.com/questions/58523
Custom agenda search with user-input
2020-05-15T09:21:21.587
# Question Title: Custom agenda search with user-input # Original Question I am trying to use org-mode to remind me of whom I will have to follow up with, and when in a conversation with someone which topics I need to discuss with them. My current plan is to query for TODO items that also have a specific value of the property `WITH`. The `WITH` property keys will be populated with my colleagues and clients names that I am working with on these tasks. To make it quick to retrieve this information, I thought of setting up a custom agenda view with an interactive user-input to fill in the keys for the `WITH` property. I found documentation on how to setup "hardcoded" agenda views. How do I fill some parts of these queries with values provided by the user? Background: I decided to try emacs for its org-mode a week ago. So I am quite new to emacs. I am try to explore as much of its potential as quickly as I can so I gauge whether or not emacs has the potential to solve my issues. So this question is potentially a mix of an org-mode specific and a generic beginners emacs question. # Intended Workflow (I am adding this as requested in the comments) ## Background I am managing different projects and interface with various systems, clients and internal teams. Due to this there is no single system used by everyone that would make sure tickets can be filed and tracked. Often I get ad-hoc requests that I cannot complete in real-time for various reasons. If I cannot complete a request in real-time, I want to file it away and retrieve it on demand: when deadline approaches (easy), when looking for open internal or external requests, ideas (easy), or when I have a catchup with any involved party (the tricky bit) ## Plan My plan so far is to create TODOs with various stages. The exact TODO states are not important, but lets say they are: `NEW_REQUEST, PROCESSING, BLOCKED | COMPLETED` These TODOs can be of various kinds. I was thinking of using tags for this, like: `:inbound:outbound:internal:request:idea` Because essentially I am an (not very well defined) API between different parties and individuals, I want to log which individuals are involved in each request. This will allow me to follow up on any open task whenever I speak to any involved person. For this I was planning to use properties, specifically the `WITH` keyword as I was looking for a short signifier. As an example, a task could look like: ``` * PROCESSING Alice: setup computer for Bob :internal:request: DEADLINE: <2020-05-22> :PROPERTIES: :WITH: Alice, Bob :END: ``` I will configure org-capture to make it fast to create such a task. I can use / configure the agenda to show me tasks by completion based on deadline and tags. However, I have regular catchups with most people I interface with on regular intervals (which might be weekly). For non-urgent tasks I want to batch up all my requests that involve a person when I meet them anyway. If I have to report to anyone, I want to be able to get all their tasks and report what the status of the tasks they gave me is. Because this system needs to scale to 20+ people, multiple TODO states and tags, hardcoding all the combinations is impractical. In the same time retyping the match-strings all the time is not practical either. But something inbetween would potentially possible. I can define a few template searches I regularly need. For instance open tickets that are inbound involving person XXX: `TODO="-CLOSED"+inbound+WITH="XXX"` Since `C-c a m` asks the user for the match string, I thought I could do the same. The user would just need to navigate to the custom query, and type in `Alice` and an agenda view `TODO="-CLOSED"+inbound+WITH="Alice"` would get created. This is is what this question was about. I have tried setting `org-agenda-custom-commands` and it does work for static queries. But I cannot find out how to add a user-prompt to it. (might not be possible, as one of the answerers pointed out) # Answer > 5 votes Generally the values inside `org-agenda-custom-commands` are hard-coded so you have no chance to prompt for input. But one of the choices for an entry type in `org-agenda-custom-commands` is a user defined function, which will be called with a single argument. So first define a function that prompts for a value of the `WITH` property and runs `org-tags-view` on that: ``` (defun with-prop-search (who) "Search by WITH propery, which is made inheritable for this function" (interactive (list (completing-read "With: " (org-property-values "WITH")) )) (let ((org-use-property-inheritance (append org-use-property-inheritance '("WITH"))) ) (org-tags-view t (format "WITH=\"%s\"/TODO" who)) ) ) ``` This also does completion on the values of `WITH` in the current file and forces the WITH property to be inherited. Then you can either call it manually with `M-x with-prop-search` or add it to an agenda view: ``` (add-to-list 'org-agenda-custom-commands '("W" "With" (lambda (arg) (call-interactively #'with-prop-search nil)) )) ``` The `call-interactively` is only necessary because of how `with-prop-search` gets the value of `WITH` # Answer > 1 votes You can do this either with tags or with properties. Assuming an org file that looks like this: ``` * headline 1 :tag1: :PROPERTIES: :WITH: hello :END: * headline 2 :tag2: :PROPERTIES: :WITH: goodbye :END: * headline 3 ``` Then `C-c a m WITH="hello" RET` will get you an agenda containing 'headline 1' (assuming that you're using `C-c a` to invoke `org-agenda`. It might be easier to this with tags, in which case it would become: `C-c a m tag1` If you want these custom views to be available all the time, you'd use `org-agenda-custom-commands`. This defines `H` and `G` commands in the agenda dispatcher: ``` (setq org-agenda-custom-commands '(("H" "Hello" tags "WITH=\"hello\"") ("G" "Goodbye" tags "WITH=\"goodbye\""))) ``` PS Use `C-c C-x P` to set a property and its value. # Answer > -1 votes What you want to do is probably possible with Emacs, if you put enough time and energy into it. However, as you say are new to both Emacs and Org, that could be a frustrating experience and put you off both Emacs and Org. Therefore I would suggest that you try to use tags to achieve what you want. This should work pretty much out of the box. If you subsequently find that this approach does not fulfill your needs you can always then try out something different and will have the advantage of having gained a bit of experience in the meantime. --- Tags: org-mode, org-agenda ---
thread-58526
https://emacs.stackexchange.com/questions/58526
How do I build emacs from sources on macOS Catalina Version 10.15.4
2020-05-15T11:30:35.087
# Question Title: How do I build emacs from sources on macOS Catalina Version 10.15.4 I typically run gnuemacs using MacPorts. However, I have a friend who does not have admin on his managed mac, so I want to build for him a full release of emacs that will run out of his home directory. He does not have admin rights. I tried downloading the sources for all of these versions: ``` -rw-r--r-- 1 xf staff 20403483 Feb 17 2005 emacs-21.4a.tar.gz -rw-r--r-- 1 xf staff 39587396 Sep 5 2008 emacs-22.3.tar.gz -rw-r--r-- 1 xf staff 47721193 Jan 28 2012 emacs-23.4.tar.gz -rw-r--r-- 1 xf staff 39759804 Apr 10 2015 emacs-24.5.tar.xz -rw-r--r-- 1 xf staff 44415140 Aug 28 2019 emacs-26.3.tar.xz ``` None of them build properly. I always end up with some kind of `Killed` error, like: ``` emacs-26.3 % make /Applications/Xcode.app/Contents/Developer/usr/bin/make -C lib all make[1]: Nothing to be done for `all'. /Applications/Xcode.app/Contents/Developer/usr/bin/make -C lib-src all make[1]: Nothing to be done for `all'. /Applications/Xcode.app/Contents/Developer/usr/bin/make -C src VCSWITNESS='' all /Applications/Xcode.app/Contents/Developer/usr/bin/make -C ../admin/charsets all make[2]: Nothing to be done for `all'. /Applications/Xcode.app/Contents/Developer/usr/bin/make -C ../admin/unidata charscript.el make[2]: Nothing to be done for `charscript.el'. /Applications/Xcode.app/Contents/Developer/usr/bin/make -C ../admin/unidata all EMACS="../../src/bootstrap-emacs" ELC uvs.elc /bin/sh: line 1: 37172 Killed: 9 "../../src/bootstrap-emacs" -batch --no-site-file --no-site-lisp -f batch-byte-compile uvs.el make[2]: *** [uvs.elc] Error 137 make[1]: *** [../lisp/international/charprop.el] Error 2 make: *** [src] Error 2 emacs-26.3 % ``` So I tried using brew. It built emacs, but I get the same problem: ``` % brew/bin/emacs zsh: killed brew/bin/emacs % ``` So what's the proper way to build this? # Answer > 1 votes I build emacs from Github source. ``` autogen.sh ./configure make make install ``` That compile without any error. The file INSTALL provides more details on how to build and install Emacs. --- Tags: compilation, source ---
thread-58530
https://emacs.stackexchange.com/questions/58530
How show multiple cursors in the start of all lines?
2020-05-15T20:01:51.010
# Question Title: How show multiple cursors in the start of all lines? Emacs 26.3 Suppose I has the next text: ``` ACTION ADVENTURE COMEDY CRIME DRAMA FANTASY HISTORICAL HISTORICAL HORROR MAGICAL MYSTERY PARANOID PHILOSOPHICAL POLITICAL ROMANCE SAGA SATIRE SCIENCE SOCIAL SPECULATIVE THRILLER URBAN WESTERN ``` And I want by **Multiple cursors** https://github.com/magnars/multiple-cursors.el add mulitple cursors in the start of all lines. I don't know count of all lines. The result must be like this: # Answer > 2 votes The repository `README.md` -- https://github.com/magnars/multiple-cursors.el -- contains a basic usage introduction that states in relevant part: * "*When you have an active region that spans multiple lines, the following will add a cursor to each line:*" `(global-set-key (kbd "C-S-c C-S-c") 'mc/edit-lines)` * Mark many occurrences `mc/edit-lines`: "*Adds one cursor to each line in the current region.*" `mc/edit-beginnings-of-lines`: "*Adds a cursor at the start of each line in the current region.*" `mc/edit-ends-of-lines`: "*Adds a cursor at the end of each line in the current region.*" --- Tags: multiple-cursors ---
thread-58533
https://emacs.stackexchange.com/questions/58533
How to print to the stdout / stderr from an emacs graphical session?
2020-05-16T01:25:01.690
# Question Title: How to print to the stdout / stderr from an emacs graphical session? I'd like to print into the terminal that started emacs, instead of using Emacs message, whats the most convenient way to do this in emacs that uses the terminal? ``` (printf "some number %d some string %s" 1 "test") ``` # Answer This macro provides an equivilant to C's `printf` or Python's `print`: ``` (defmacro printf (fmt &rest args) `(princ (format ,fmt ,@args) #'external-debugging-output)) ``` Or as a function: ``` (defun printf (&rest args) (princ (apply #'format args) #'external-debugging-output)) ``` > 2 votes --- Tags: debugging ---
thread-58536
https://emacs.stackexchange.com/questions/58536
Any ways to make a GUI application fullscreen in EXWM?
2020-05-16T02:52:09.520
# Question Title: Any ways to make a GUI application fullscreen in EXWM? I'm used to i3wm, as well as a couple other WM, but i noticed that, as far as i know, there isn't any function or keybinding existing in EXWM (by default) to make a GUI application fullscreen (which i3wm and other support). Example: For instance, using i3wm, one can use the `Super`+`f` key combination (Super being the Windows keys on most keyboards) to force a GUI application/windows fullscreen. Just curious if this is already a thing or not. # Answer > 1 votes So it seems the answer was already in the docs on github. `We regard fullscreen as a third layout mode here. An X window in either tiling or floating mode can be made fullscreen explicitly by invoking C-c C-f.` --- Tags: exwm, x-window ---
thread-58535
https://emacs.stackexchange.com/questions/58535
How to associate a theme to a file extension?
2020-05-16T01:57:19.653
# Question Title: How to associate a theme to a file extension? It is kind of similar to this question How do I automatically load a mode for a specific set of file extensions? So I am in a situation where, when I want to write in TeX, I want to use 'whiteboard' theme. Whereas whenever I want to program in C++ or python, I want to use "afternoon" theme. I kind of expect my init file to look like ``` (if [file extention is tex] (load-theme 'whiteboard t) (load-theme 'afternoon t)) ``` Is this right? I am using Emacs 26.3 # Answer > 1 votes A theme is global, but you can cause a given theme to be used when you visit a file with a given major mode: You can use the mode hook of a mode you're interested in to start using the theme you want for that mode. `auto-mode-alist` associates file types (extensions) with major modes, and each major mode has a mode hook. So you can associate file types with themes by using mode hooks to turn on given themes. IOW: * file extension =\> specific major mode * major mode's hook =\> specific theme The theme you change to because of a mode hook will then be used everywhere (all buffers, all modes), until you visit a file with a different mode, whose mode hook says to use a different theme. That behavior might not be what you want. But it's one possibility to consider. --- Tags: init-file, themes ---
thread-45107
https://emacs.stackexchange.com/questions/45107
Ido mode - autocomplete in interactively mode
2018-10-02T12:20:12.740
# Question Title: Ido mode - autocomplete in interactively mode ### windows 10, emacs 26,1, ido mode I use `ido` mode. Suppose I start some command ``` M-x magit ``` Then `TAB` The possible completions are many and fill the screen: I need to continue typing and press `TAB` to select desire command. But... it's very slow. Is it a more interactive way? like fly filter commands' name in `ido` mode. Something similar to `helm` only I don't like `helm`. # Answer > 1 votes I recommend `Smex`: ``` (use-package smex :bind (("M-x" . smex)) :config (smex-initialize)) ``` Getting started guide on Github: > Smex is a M-x enhancement for Emacs. Built on top of Ido, it provides a convenient interface to your recently and most frequently used commands. And to all the other commands, too. Find it on emacs wiki Including example code and links. # Answer > 1 votes I think you are asking for *incremental completion*: the completion candidates are shown and updated as you type into the minibuffer. 1. You get that using Icomplete mode. It originally just showed you the candidates, without giving you a way to choose one, but starting a few Emacs releases ago it also lets you pick a candidate. It shows only some of the candidates, and it shows them in the minibuffer. Icomplete is part of vanilla Emacs, and library `icomplete+.el` offers some enhancements. 2. Icicles gives you more flexible incremental completion, and you can easily customize the behavior (change the delay or the number of chars before starting to show candidates, show candidates from the outset, toggle it on/off on the fly, etc.). Candidates are shown in buffer `*Completions*`. The default behavior of Icicles is different from Ido, but you can change the behavior to be more like Ido, if you like. # Answer > 1 votes As mentioned in the IDO documentation, you can place the following inside your Emacs init file. ``` (global-set-key "\M-x" (lambda () (interactive) (call-interactively (intern (ido-completing-read "M-x " (all-completions "" obarray 'commandp)))) ) ) ``` Make sure you have already setup `ido-mode` correctly, before settings the above global binding. --- Tags: completion, minibuffer, auto-complete-mode ---
thread-26285
https://emacs.stackexchange.com/questions/26285
Running kivy code in Emacs
2016-08-14T20:02:01.913
# Question Title: Running kivy code in Emacs I am learning about the kivy library for python. I have a test code which i run with `C-u C-c C-c` after having the python interpreter fired up with `C-p`. It runs fine the first time and the window opens, but trying to run it a second time makes nothing happen; the window doesn't show, only in the minibuffer below i see `Sent: import kivy`. ``` import kivy kivy.require(kivy.__version__) from kivy.app import App from kivy.uix.label import Label class MyApp(App): def build(self): return Label(text = "Guido Van Rossum", font_size = 90) def main(): MyApp().run() if __name__ == "__main__": main() ``` Does anyone have experience with writing kivy using emacs, or can any one help? **Edit** This is what i get in the terminal the second time i run the code: ``` >>> [INFO ] [Base ] Start application main loop [ERROR ] [Base ] No event listeners have been created [ERROR ] [Base ] Application will leave ``` # Answer > 1 votes I think this issue is caused by the fact that if you run the script with `C-u C-c C-c` and then run it a second time the same way, you are trying to run it as part of the same process/session (not sure the correct term). To illustrate this, if it needs illustrating, you can visit the `*Python*` buffer that will be open after you run the script, and at the interactive prompt and call the `dir()` function. You will see that `'App'`, `'Label'`, `'MyApp'`, `'kivy'`, etc. are already there. For reasons that I can't really explain, but that have also been mentioned here, kivy will not work this way if you try to run the same `App` twice in the same session while everything is still in memory. If you run your `.py` file from the command line with `python myfile.py` it will work every time you run it because you are starting from scratch each time. But if you open `ipython` or another interactive interpreter, import your module, and then call the `main()` function more than once, you will see the same errors for the same reason. You will see that if you got to the `*Python*` buffer and type `exit()` to end the Python process, and run your script again with `C-u C-c C-c`, that it should work as expected again (although only once, of course, for the reasons described above). This is not an issue with Emacs really, but a product of the way that kivy works and the way the running Python scripts works in Emacs. I don't think it is something that you will easily be able to "fix", nor should you really need to. However, this will hopefully put your mind at ease if you were worried that it was a bug or something. Emacs and kivy do play well together in my experience (I used them together every day at my last job), so I hope this little quirk doesn't bother you too much! # Answer > 0 votes I have the same problem, using kivy in Spyder editor. As mentioned in previous answers it happens for the way kivy works. But I found a work around for it here and here Which I copy paste below. Define the reset() function below, and simply run it BEFORE running your instance\_of\_App().run() method. ``` def reset(): import kivy.core.window as window from kivy.base import EventLoop if not EventLoop.event_listeners: from kivy.cache import Cache window.Window = window.core_select_lib('window', window.window_impl, True) Cache.print_usage() for cat in Cache._categories: Cache._objects[cat] = {} ``` --- Tags: python ---
thread-3481
https://emacs.stackexchange.com/questions/3481
Remove *.bak files from ido-mode minibuffer
2014-11-13T09:46:29.580
# Question Title: Remove *.bak files from ido-mode minibuffer I am using `ido-mode` to select files from Emacs. This works well for most cases, but for some cases I would like to modify the files that are shown in the completion buffer with `ido-find-file`. In some folders I have a lot of `*.bak` files, and I would like to have the possiblity to remove them from the completion buffer by pressing the `F1` key, for example. This is how far I got on this task: ``` (add-hook 'ido-minibuffer-setup-hook 'ido-my-keys) (defun ido-my-keys () (define-key ido-file-completion-map (kbd "<f1>") 'my-modify-files)) (defun my-modify-files () (interactive) (message-box "Here I would like to delete the .bak files from the minibuffer")) ``` # Answer > 8 votes `ido-mode` has built-in support for hiding files matching specific regexps. All you need to do is add `\.bak` to `ido-ignore-files`: ``` (add-to-list 'ido-ignore-files "\.bak") ``` After invoking `ido-find-file`, you can then hit `C-a` (`ido-toggle-ignore`) to toggle hiding of `.bak` files. # Answer > 1 votes The correct way to ignore files by extension for file name completion purposes is using the variable `completion-ignored-extensions`. The variable holds a list of strict suffix strings that are ignored for: * directory completion, if the list element ends in a `/`, or * file completion otherwise. The `ido-ignore-files` variable, on the other hand, is a list of regular expressions, and matches anywhere in the file name, unless the regex is anchored. In particular, the recommendation in another answer, ``` (add-to-list 'ido-ignore-files "\.bak") ``` tells Ido to match the substring `.bak` *anywhere* in file name, which may or may not be what you really want. On the other hand, ``` (add-to-list 'completion-ignored-extensions ".bak") ``` makes all Emacs completion machinery, not only Ido, but also out-of-the-box file completion and Dired, and likely other places, ignore files ending in `.bak` (including full name match). Note that this variable is not a list of regexes, but rather a list of literal suffixes; the dot should not be `\`-escaped. The default `completion-ignored-extensions` list contains commonly ignored suffixes such as `.elc`, `.o`, `.a`, `.so`, `~`, `.git/`, and many more. This is why the default `ido-ignore-files` list is *suspiciously short*. The completion behavior is actually more complex than just always ignoring the files; see the docstring of the variable. One important point is that if *all* completions are to be ignored according to `completion-ignored-extensions`, then *none are*. This allows, for example, descending into the `.git/` subdirectory: as soon as it becomes the only completion (after typing `.g/`, if no other directories matching `.g*/` exist), it is shown by Ido as a possible completion. Similarly, in the original question case, typing `.bak` makes Emacs "un-ignore" and immediately show files ending in `.bak`, unless other non-ignored files match by Ido rules, so that the `C-a` is not always necessary to find an ignored file. --- Tags: ido ---
thread-58555
https://emacs.stackexchange.com/questions/58555
How to insert character or word N times in a buffer or file?
2020-05-17T03:38:46.607
# Question Title: How to insert character or word N times in a buffer or file? Just curious to know how to do this, since i already know in other languages (bash, etc). I know how to insert a character in elisp, just not sure on how to do it when it's done nth time (in succession) in elisp. Here an example: Basically, inserting (in file or buffer) the character X, 10 times. `XXXXXXXXXX` something like that. # Answer > 8 votes There are many ways to write loops/iterative/repetitive behaviour in elisp. `C-h``i``g` `(elisp)Iteration` has the basic options, including `dotimes`, which is the canonical way to repeat something N times. E.g.: ``` (dotimes (_ 10) (insert "X")) ``` For the specific example of repeating a character N times, you might alternatively use `make-string`. ``` (insert (make-string 10 ?X)) ``` For more sophisticated looping options, I suggest starting at `C-h``i``g` `(cl)Iteration` # Answer > 5 votes If you want to insert the character interactively, do `C-u 10 X`. This will give you `XXXXXXXXXX`. This repeats the `self-insert-command` (here, for "X"), 10 times. See the manual node on repeating. --- Tags: insert, text ---
thread-58549
https://emacs.stackexchange.com/questions/58549
Setting html preamble in org-publish
2020-05-16T17:10:37.413
# Question Title: Setting html preamble in org-publish So I am trying to set a html preamble on my org-publish, and I am using the following code: ``` (setq org-publish-project-alist '(("org-notes" :base-directory "~/Projects/blog/" :base-extendion "org" :publishing-directory "~/Public/" :recursive t :makeindex t :html-preamble "This is just a test" :publishing-function org-html-publish-to-html) ("org-static" :base-directory "~/org/" :base-extension "css\\|js\\|png\\|jpg\\|gif\\|pdf\\|mp3\\|ogg\\|swf" :publishing-directory "~/Public/" :recursive t :publishing-function org-publish-attachment) ("org" :components ("org-notes" "org-static")))) ``` However, nothing shows up. Can anybody help me with this? # Answer So it seems that the problem was that, because I was making no changes on the posts, org-mode saw no need to recompile it. To overcome this, just add the force flag to the org-publish function. > 1 votes --- Tags: org-mode, org-publish ---
thread-58560
https://emacs.stackexchange.com/questions/58560
An ivy function for recently opened files?
2020-05-17T08:47:15.183
# Question Title: An ivy function for recently opened files? I know that setting `ivy-use-virtual-buffers` leads to recently opened files being shown in the `ivy-switch-buffer` completion. However, I don't want this. What I want is a separate function for opening recent files. When I invoke `recentf-open-file`, I want the `ivy` completion for recent files, instead of the clunky recentf menu. Doom Emacs provides a neat implementation of this, but I can't seem to find a way to do this in vanilla Emacs. Do I have to write my own function for this? This seems redundant considering the fact that `ivy` already has the mechanism to do this. # Answer You're looking for `counsel-recentf`, which comes with counsel. Just `M-x counsel-recentf` or bind it to any keys you'd like and that's all you're looking for. Loosely speaking `Ivy` is the completion backend, `counsel` provides functionality to use ivy "replacing" some popular commands with ivy-style completion. > 5 votes --- Tags: buffers, ivy, recentf ---
thread-58268
https://emacs.stackexchange.com/questions/58268
mu4e (gnus) MS safelinks decoder
2020-05-04T14:28:51.880
# Question Title: mu4e (gnus) MS safelinks decoder Today I got scared after noticing how many Microsoft ATP Safelinks had made their way into my org-mode calendar file. Therefore, is it possible to create a URL decoder to bypass Microsoft Safelinks for mu4e(gnus)? There are implementations for other mail-clients in Python? and Javascript but elisp (if possible) would be preferable. I am using mu4e 1.4.1 and emacs 26.3. Thanks in advance. **Update:** Thanks wasamasa. To wire it up to mu4e I've developed a url reader (below), based on this answer. # Answer > 1 votes This is my answer, based on code from Wasamasa and Joseph Gay. **Post version 1.6.0~54** ``` ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Microsoft safelinks decoder ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (require 'url-parse) (defun my-decode-safelink (url) ;; (print url) "Given a url string this function returns the corresponding decoded url" (if (string-match-p (regexp-quote "safelinks.protection") url) (let* ((query (url-filename (url-generic-parse-url url))) (url (cadr (assoc ".*/?url" (url-parse-query-string query) (lambda (pat x) (string-match-p x pat))))) (path (replace-regexp-in-string "3Dhttps" "https" (url-unhex-string url)))) (url-encode-url (replace-regexp-in-string (rx "/" (>= 20 (any "#$%&*^@"))) "" path))) url)) ;; Main function (defun unsafelinks () "This function filters MS safelinks from a message buffer" (interactive) (let (url current-start-pos next-change-pos) (save-excursion (goto-char (point-min)) (let ((inhibit-read-only t) (simple-url-regexp "https?://") urls) (search-forward-regexp "^$" nil t) (setq next-change-pos (or (next-single-property-change (point) 'shr-url) (point-max))) (goto-char next-change-pos) (while (< next-change-pos (point-max)) (setq url (get-text-property (point) 'shr-url) current-start-pos (point) next-change-pos (or (next-single-property-change (point) 'shr-url) (point-max))) (when url (setq text (buffer-substring-no-properties current-start-pos (point))) ;; edit widget URLs (add-text-properties current-start-pos next-change-pos (list 'shr-url (my-decode-safelink url) 'help-echo (my-decode-safelink url))) ;; edit text URLs (when-let ((link (thing-at-point 'url)) (bounds (thing-at-point-bounds-of-url-at-point))) (delete-region (car bounds) (cdr bounds)) (insert (my-decode-safelink url))) ) (goto-char next-change-pos)) (remove-overlays) (mu4e~view-activate-urls) (set-buffer-modified-p nil))))) (defun unsafelinks-advice (msg) (unsafelinks)) (advice-add #'mu4e~view-render-buffer :after #'unsafelinks-advice) ``` **Previous to version 1.6.0~123** ``` ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Microsoft safelinks decoder ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (require 'url-parse) (defun my-decode-safelink (url) "Given a url string this function returns the corresponding decoded url" (if (string-match-p (regexp-quote "safelinks.protection") url) (let* ((query (url-filename (url-generic-parse-url url))) (url (cadr (assoc "/?url" (url-parse-query-string query)))) (path (url-unhex-string url))) (replace-regexp-in-string (rx "/" (>= 20 (any "#$%&*^@"))) "" path)) url)) (defun unsafelinks (vmode) "This function filters MS safelinks from a message buffer" (interactive) (beginning-of-buffer) (let ((simple-url-regexp "https?://") urls) (save-excursion ;; edit text URLs (while (search-forward-regexp simple-url-regexp nil t) (when-let ((url (thing-at-point 'url)) (bounds (thing-at-point-bounds-of-url-at-point))) (delete-region (car bounds) (cdr bounds)) (insert (my-decode-safelink url)))) ;; edit widget URLs (beginning-of-buffer) (while (not (eobp)) (goto-char (next-overlay-change (point))) (when-let (link (get-text-property (point) 'shr-url)) (and (string-match simple-url-regexp link) ;; change overlay url echo (when (overlay-put (car (overlays-at (point))) 'help-echo (my-decode-safelink link)) t) ;; change url text-properties (add-text-properties (point) (next-overlay-change (point)) (list 'shr-url (my-decode-safelink link) 'help-echo (my-decode-safelink link))) )) (goto-char (next-overlay-change (point)))) (when vmode (gnus-article-prepare-display) (set-buffer-modified-p nil) (read-only-mode)))) (mu4e-compose-goto-top)) ;; Append it to mu4e view and compose mode hooks (add-hook 'mu4e-view-mode-hook (lambda () (unsafelinks t)) t) (add-hook 'mu4e-compose-mode-hook (lambda () (unsafelinks nil)) t) ``` # Answer > 1 votes I've ported the Python code you've linked: ``` (require 'url-parse) (defun my-decode-safelink (url) (if (string-match-p (regexp-quote "safelinks.protection.outlook.com") url) (let* ((query (url-filename (url-generic-parse-url url))) (url (cadr (assoc "/?url" (url-parse-query-string query)))) (path (url-unhex-string url))) (replace-regexp-in-string (rx "/" (>= 20 (any "#$%&*^@"))) "" path)) url)) (my-decode-safelink "https://na01.safelinks.protection.outlook.com/?url=https%3A%2F%2Foffice.memoriesflower.com%2FPermission%2F%2525%2524%255E%2526%2526*%2523%2523%255E%2524%2525%255E%2526%255E*%2526%2523%255E%2525%2525%2526%2540%255E*%2523%2526%255E%2525%2523%2526%2540%2525*%255E%2540%255E%2523%2525%255E%2540%2526%2525*%255E%2540%2Foffice.php&data=01%7C01%7Cdavid.levin%40mheducation.com%7C0ac9a3770fe64fbb21fb08d50764c401%7Cf919b1efc0c347358fca0928ec39d8d5%7C0&sdata=PEoDOerQnha%2FACafNx8JAep8O9MdllcKCsHET2Ye%2B4%3D&reserved=0") ;; "https://office.memoriesflower.com/Permission/office.php" (my-decode-safelink "https://office.memoriesflower.com/Permission/office.php") ;; "https://office.memoriesflower.com/Permission/office.php" ``` That leaves the part of wiring it up to mu4e. --- Tags: microsoft-windows, gnus, mu4e, hyperlinks ---
thread-58543
https://emacs.stackexchange.com/questions/58543
How to center region in exact middle of screen?
2020-05-16T09:08:54.513
# Question Title: How to center region in exact middle of screen? So i basically want to (as the title suggest) to center a region of text, in the center of the screen. Current example is using part of this site. From this To this And here a small gif video to show how i did it manually (for more detail): * Used `screenkey` to display the key i used. Roughly, i'm just putting a `newline` characters in front of the first line of the block of text (which is on the same line, in this example) and center it (very roughly) in the center. * Then i input `space` characters in front of each line, until it is formatted into one block of text, in the position i choose above. This is basically what i want to do (on a region selected text) but in elisp. # Answer Here's an implementation of exactly what the OP is asking for, although I don't think it is of any use to anybody (except possibly the OP, but even there I have my doubts, as the extended discussion in the comments shows). It assumes that there is one long line starting at the beginning of the buffer and that you want to reformat it as a block of some specified width that is centered in the window of the buffer. ``` (defun insertN (c count) (insert (make-string count c))) (defun center-block (text-width) "Assumption: there is one long line at the beginning of the buffer which this function is going to mangle in order to center it in the window. Assumption: the given text-width is smaller than the window body width." (interactive "NText width: ") (let* ((s (buffer-substring-no-properties (point-min) (point-max))) (slen (length s)) (W (window-body-width)) (H (window-body-height)) (L text-width) (nlines (/ (+ slen L) L)) ; number of physical lines of block ; when shrunk to the required line length (toplines (/ (+ (- H nlines) 2) 2)) ; how many lines to leave at the top (lspaces (/ (- W L) 2)) ; how many spaces to insert at the beginning (rspaces (- (- W L) lspaces)) ; how many spaces to go to the right end of the window (nspaces (+ lspaces rspaces)) ; how many spaces to insert between physical lines sub) (erase-buffer) ;; insert the proper number of newlines (insertN ?\n toplines) ;; insert the proper number of spaces at the beginning of the string (insertN ?\s lspaces) ;; break up the string into substrings of length L and insert each ;; one, followed by the appropriate number of spaces. The loop inserts ;; the *full* logical lines of the block: there might be a tail that is ;; left over if the length of the string is not a multiple of L which is ;; inserted after the loop is done. (while (>= (length s) L) (setq sub (substring s 0 L)) ; first L chars (setq s (substring s L)) ; rest ;; insert the substring (insert sub) ;; insert nspaces spaces: rspaces to reach the right end of the window ;; and lspaces to indent the next physical line. (insertN ?\s nspaces)) ;; insert what's left over. (insert s))) ``` I have commented it copiously in an attempt to make it understandable to the OP. Invoke it with `M-x center-block RET 60 RET` (or whatever width you want to specify instead of 60) while the cursor is in the window of the buffer that you are trying to modify. > 1 votes --- Tags: text ---
thread-38440
https://emacs.stackexchange.com/questions/38440
Make org-drill allow reviewing "empty" cards
2018-01-29T19:19:29.230
# Question Title: Make org-drill allow reviewing "empty" cards I'm trying to use `org-drill` with cards made up of one-line headings, which the documentation considers an "**empty card**" (that is, one without a body). The recommended way to make them show up in drill sessions is to add an empty comment to the body, like a line with only `#`. It works, but I'm trying to fix this in a way cleaner than mass-editing my org file. --- I found the variable `org-drill-card-type-alist`, whose default value is ``` '((nil org-drill-present-simple-card) ("simple" org-drill-present-simple-card) ("twosided" org-drill-present-two-sided-card nil t) (...)) ``` The `t` at the end of the `twosided` sexp means `drill-empty-p`, which means: > When supplied, DRILL-EMPTY-P is a boolean value, default nil. When non-nil, cards of this type will be presented during tests **even if their bodies are empty**. This seems to be exactly what I want, so I set the `nil` (default) and `simple` (for good measure) card types like this, using `customize-set-variable`: ``` '((nil org-drill-present-simple-card nil t) ("simple" org-drill-present-simple-card nil t) ("twosided" org-drill-present-two-sided-card nil t) (...)) ``` I eval the sexp / restart org-mode / restart Emacs, and still `M-x org-drill` ignores the empty cards. Am I doing something wrong? Is this a bug? Are there any workarounds? # Answer The `DRILL-EMPTY-P` parameter in entries of `org-drill-card-type-alist` is only considered for cards with an explicit `DRILL_CARD_TYPE` in function `org-drill-entry-status`. As a workaround treat drill-cards with nil card type as non-empty if the `DRILL-EMPTY-P` parameter of that type is set: ``` (defun org-drill-entry-status-workaround (oldfun &rest args) "Call adviced `org-drill-entry-status' as OLDFUN with ARGS. Temporarily let `org-entry-empty-p' return nil for empty drill cards with DRILL_CARD_TYPE nil." (let ((oldfun-entry-empty-p (symbol-function 'org-entry-empty-p))) (cl-letf (((symbol-function 'org-entry-empty-p) (lambda () (and (funcall oldfun-entry-empty-p) ;; in principle the old fun ;; with the exception: (null (and (org-drill-entry-p) (null (org-entry-get (point) "DRILL_CARD_TYPE")) (nth 3 (assoc nil org-drill-card-type-alist)))))))) ;; DRILL-EMPTY-P (apply oldfun args)))) (advice-add 'org-drill-entry-status :around #'org-drill-entry-status-workaround) ``` With this workaround `org-drill` works as you expect it in the following test org buffer with `emacs-version` 25.3.1 and `org-drill` 2.6.1. ``` * first :drill: :PROPERTIES: :ID: 97a78aeb-8e62-4243-b49b-faccb12dd31c :END: * second :drill: :PROPERTIES: :ID: c0acc9c5-bdca-4414-96bb-61ea2aeb85e1 :END: * Local Variables :noexport: # Local Variables: # org-drill-card-type-alist: ((nil org-drill-present-simple-card nil t)) # end: ``` > 3 votes # Answer I've just installed `org-drill` and this behavior seems a bit unsafe to me. It's documented, but I still spent quite a bit of time figuring out why the verb card from the `spanish.org` example never shows up. Turns out it's empty. I'm paranoid that I would occasionally make such mistakes and lose cards forever if it ignores empty ones. So I just redefined the `org-drill-entry-empty-p` function to always say it's non-empty. ``` (use-package org-drill ... :config (defun org-drill-entry-empty-p () nil) ) ``` > 0 votes --- Tags: org-mode, org-drill ---
thread-58554
https://emacs.stackexchange.com/questions/58554
emacs ess apply function to token under point
2020-05-16T22:21:38.067
# Question Title: emacs ess apply function to token under point I've finally committed to moving over to both `emacs` and `ess` -- and i'm having a bit of trouble getting (the famously customisable) combination to work as i'd like. Say that i have a file that contains an object called `rainfall` open in emacs and an inferior R session open. Is there a way that i can put point over the token and then send it to the `R` process for a function to be applied to that object? To make it concrete, say the source file contains the following object: ``` rainfall <- xts(runif(100, min = 0, max = 10), seq.Date(as.Date('2019-01-01'), by = 1, length = 100)) ``` I'd like to be able to put `point` anywhere inside the token `rainfall` and (via some keyboard shortcut) send it to the `R` process with some function (such as `head`, `tail`, `plot`, or `summary`) applied to it. So in the iESS\[R\] screen i'd see: `R> tail(rainfall)` and the associated output. # Answer You can achieve what you want quickly with a keyboard macro for each Emacs session. But it looks like you would want to have several standard functions available to quickly examine R objects, so it will be more flexible to do it in Emacs Lisp. ``` (require 'ess-r-mode) (defun r-summary-at-point () (interactive) (let ((sym (ess-symbol-at-point))) (if sym (ess-send-string (get-buffer-process "*R*") (concat "summary(" (symbol-name sym) ")\n") t) (message "No valid R symbol at point")))) (define-key ess-r-mode-map (kbd "C-c :") 'r-summary-at-point) ``` That function does not check to make sure the "\*R\*" process buffer exists, but will work once you have started the process, assuming the default. > 1 votes --- Tags: ess, r ---
thread-58491
https://emacs.stackexchange.com/questions/58491
Can't start an emacsclient process with xbindkeys
2020-05-13T15:01:56.673
# Question Title: Can't start an emacsclient process with xbindkeys I'm trying to launch the Emacs calculator with the XF86Calc key. I have ``` "emacsclient -c -e '(calc nil t)'" XF86Calc ``` in ~/.xbindkeysrc I can launch it from "Run Action" in xbindkeys-config. But pressing XF86Calc doesn't do anything. How does one use xbindkeys to launch an emacsclient frame ? # Answer Stupid mistake on my part. The keycode is XF86Calculator and not XF86Calc. The xbindkeysrc line works fine with the right keycode. > 1 votes --- Tags: key-bindings, emacsclient ---
thread-58575
https://emacs.stackexchange.com/questions/58575
Convert function-quoted form #'... to string
2020-05-18T12:19:24.317
# Question Title: Convert function-quoted form #'... to string I have tried `(symbol-name x)`, but it doesn't work if the argument is a lambda: * ok: `#'execute-extended-command` * not ok: ``` #'(lambda (&optional frame) (interactive) (message "hi 8")) ``` # Answer I don't know why you need this, but one way is: ``` (format "%s" #'(lambda () (interactive))) ``` ``` "(closure (t) nil (interactive))" ``` > 2 votes --- Tags: functions, string, symbol-function ---
thread-58572
https://emacs.stackexchange.com/questions/58572
general function to concat token at point with function and send to *R*
2020-05-18T05:29:39.447
# Question Title: general function to concat token at point with function and send to *R* I'm moving my `R` setup over to `emacs` and `ess` -- and am struggling with the emacs / LISP customisation process. In an answer to another question, I learnt how to create a function that concats a function name with the token at point and sends it to `*R*`. This was great as a once off -- but now my `.emacs` is filling up with boilerplate code (see the code block at the bottom). What i'd really like is a way to declare mappings in a single line: ``` (define-key ess-mode-map (kbd "C-c s") _concat_summary_token_) (define-key ess-mode-map (kbd "C-c p") _concat_print_token_) ``` The below code-block is an example of what i have at the moment -- two is okay, but i have ten already and plans to add more ... so i'm going to get lost in boilerplate! ``` (defun r-summary-at-point () (interactive) (let ((sym (ess-symbol-at-point))) (if sym (ess-send-string (get-buffer-process "*R*") (concat "summary(" (symbol-name sym) ")\n") t) (message "No valid R symbol at point")))) (define-key ess-mode-map (kbd "C-c s") 'r-summary-at-point) (defun r-print-at-point () (interactive) (let ((sym (ess-symbol-at-point))) (if sym (ess-send-string (get-buffer-process "*R*") (concat "print(" (symbol-name sym) ")\n") t) (message "No valid R symbol at point")))) (define-key ess-mode-map (kbd "C-c p") 'r-print-at-point) ``` # Answer I'll give you an hint: ``` (defun apply-r-func-at-point (func) "Apply R FUNC at point, FUNC should be a string." (let ((sym (ess-symbol-at-point))) (if sym (ess-send-string (get-buffer-process "*R*") (concat func "(" (symbol-name sym) ")\n") t) (message "No valid R symbol at point")))) (defun r-summary-at-point () (interactive) (apply-r-func-at-point "summary")) (define-key ess-mode-map (kbd "C-c s") 'r-summary-at-point) (defun r-print-at-point () (interactive) (apply-r-func-at-point "print")) (define-key ess-mode-map (kbd "C-c p") 'r-print-at-point) ``` > 3 votes --- Tags: functions, ess, r ---
thread-58512
https://emacs.stackexchange.com/questions/58512
avoid org-preview-latex to open a new window
2020-05-14T19:18:29.333
# Question Title: avoid org-preview-latex to open a new window I use emacs in frame-only mode and org to typeset latex equations and technical writing. Since it is hard to see and understand the latex equations in their raw format, I use a package called `org-fragtog` which just calls the function `org-latex-preview` to convert the latex code to an image, and insert it in the current buffer. The problem is, every time a new equation is inserted for the first time, `org-latex-preview` calls `dvipng` which opens a new window with the message: ``` "This is dvipng 1.16 Copyright 2002-2015, 2019 Jan-Ake Larsson [1] ". ``` Is there a way to suppress this window to open in the first place, or to make it open only when there is an error? When you are creating lots of equations in a row this gets in the way and stops the flow. ### Update While not knowing a lot of elisp, I could craft the function below. The only problem is it is not being called after `org-latex-preview` is executed. Anyone know why? ``` (defun kill-latex-preview-window () (interactive (let ((buffer "*Org Preview LaTeX Output*")) (if (get-buffer buffer) (progn (delete-frame (select-frame-by-name buffer)) (kill-buffer buffer) ) ) ) ) ) (add-hook 'post-command-hook 'kill-latex-preview-window ) ``` # Answer > 0 votes Thanks to everyone who helped. I contacted the package author which corrected the bug. The solution is detailed on commit 67de558 and issue 32. It basically added the function `org-compile-file` to the list of functions that are blacklisted in `frames-only-mode` in the function `frames-only-mode-use-window-functions`. This way, every time the function is called it only opens a window, and not a frame. # Answer > 1 votes Probably the simplest thing to do is to define your own preview function that locally redefines the function that pops up the buffer so that it does nothing, then redo the key binding so that it calls your function instead: ``` (defun my-org-latex-preview () (interactive) (cl-letf (((symbol-function 'display-message-or-buffer) (lambda (msg) nil))) (org-latex-preview))) (define-key org-mode-map (kbd "C-c C-x C-l" 'my-org-latex-preview) ``` Since it's a local redefinition it is unlikely to cause any problems, except in the case where you really want to see that buffer (e.g. in case of errors), but then you can switch to it manually: the buffer is still around, it is just not popped up. I see also that you opened an issue which was a good thing to do: at the very least, they should know about the problem, but there may be a less hackish solution too (or they might implement one). --- Tags: org-mode, latex, preview-latex ---
thread-58580
https://emacs.stackexchange.com/questions/58580
How could I assign keybinding for "<M-tab>"
2020-05-18T17:18:01.413
# Question Title: How could I assign keybinding for "<M-tab>" I would like to use `Meta` \+ `Tab` or `Meta` \+ `;` keybindings in `emacs` to correct a spelling instead of using the `ispell`s default one. Please note that I am open `emacs` in terminal. I have tried following but it did not help. Is there any way to fix it? * `(global-set-key (kbd "<M-tab>") 'helm-flyspell-correct)` * `(global-set-key (kbd "<M-;>") 'helm-flyspell-correct)` # Answer It is `(kbd "M-<tab>")`. Note that `M-` is outside the \<\> > 2 votes --- Tags: key-bindings, terminal-emacs ---
thread-58584
https://emacs.stackexchange.com/questions/58584
Spacemacs - What does C-c do (what things are inside this menu)?
2020-05-18T19:29:05.840
# Question Title: Spacemacs - What does C-c do (what things are inside this menu)? I'm learning emacs/spacemacs right now and I'm slightly confused about the `C-c` binding. Pressing it opens a menu with many helpful things that I cannot reach otherwise (it seems like it at least). I'm also confused what the difference is to `,` which opens the major mode commands. Here's a concrete example: I'm in org-mode. Using `,` I can access many features that this major mode offers, I can add stuff, manipulate text, and open the agenda. But if I want to, for example, add the current file to the agenda (via `org-agenda-file-to-front`) I have to press `C-c [`. I can't find this command within the major mode bindings in the `,` menu. Why are some things within `C-c` and some within `,` if they do belong to the same major mode? And what is the purpose of `C-c` in general? What stuff is being put there? # Answer I can't really answer on why some keybinding are put under `,` and some under `C-c`. To know the difference between the two, you can check what bindings they prefix with the shortcut `, C-h` and `C-c C-h`. Other usefull bindings are: `C-h m` to show what the current major mode bindings are `C-h k C-c [` to know what's bound to `C-c [` `C-h f org-agenda-file-to-front` to know what bindings are bound to that function > 2 votes --- Tags: key-bindings, spacemacs ---
thread-58592
https://emacs.stackexchange.com/questions/58592
Initialization warning after installing doom-modeline
2020-05-19T12:20:26.653
# Question Title: Initialization warning after installing doom-modeline So recently i decided to switch to Emacs (btw I am total noob) and began creating my init.el file After downloading `doom-modeline` package from melpa and following it's installation guide I get an initialization warning: ``` Warning (initialization): An error occurred while loading ‘/home/telman/.emacs.d/init.el’: File is missing: Cannot open load file, No such file or directory, doom-modeline ``` And this is my `init.el` setup: ``` (require 'package) (require 'doom-modeline) (doom-modeline-mode 1) (add-to-list 'package-archives '("melpa" . "http://melpa.milkbox.net/packages/") t) (add-to-list 'custom-theme-load-path "~/.emacs.d/themes") (load-theme 'dracula t) (global-display-line-numbers-mode) (menu-bar-mode -1) (tool-bar-mode -1) (toggle-scroll-bar -1) ``` # Answer > 0 votes You don't need to `(require 'package)` and you shouldn't need to `(require 'doom-modeline)` either. But, depending on your version of Emacs, you need to initialize the `package` library with `(package-initialize)` before you can use the packages you installed. So my crystal ball tells me you should replace the first two lines of your `init.el` with ``` (package-initialize) ``` # Answer > 0 votes You are trying to require a package which has not been installed yet. Run ``` M-x package-install ``` and then specify ``` doom-modeline ``` This will install the package so that when you next start emacs, the error should no longer occur. --- Tags: init-file, package ---
thread-58513
https://emacs.stackexchange.com/questions/58513
emacs -nw standard input is not a tty on ConEmu and Mintty
2020-05-14T20:28:25.687
# Question Title: emacs -nw standard input is not a tty on ConEmu and Mintty On my Windows XP machine I use Emacs-25.2.1. During web app development I use **ConEmu version 191012** and I need to use Emacs at the command line. When I enter `emacs -nw` on **ConEmu**, it says ``` emacs: standard input is not a tty ``` This error occurs on **MSYS2**'s default terminal **Mintty** which is invoked by `cmd.exe /A /Q /K C:\msys32\mingw32_shell.bat`, too but it doesn't occur on Windows' default **CMD.exe** and **PowerShell** so I guess it may have something to do with the Environment Variables. Several months ago, the ConEmu had a problem where the arrow keys and backspace were not working, (roughly described here) and I remember fixing it by changing or deleting an environment variable. This `standard input is not a tty` problem seemed to pop up roughly around the same after I fixed that problem but I'm not 100% sure of this. What should I do to fix this problem? # Answer > 0 votes It was the erroneous startup script of ConEmu named `Bash::Msys2-32` which was confusing the `emacs -nw` It was (the erroneous one) ``` set CHERE_INVOKING=1 & set "PATH=%ConEmuDrive%\msys32\usr\bin;%PATH%" & %ConEmuBaseDirShort%\conemu-msys2-32.exe -new_console:p %ConEmuDrive%\msys32\usr\bin\bash.exe --login -i -new_console:C:"%ConEmuDrive%\msys32\msys2.ico" ``` It should have been like (the correct one) ``` set CHERE_INVOKING=1 & %ConEmuDrive%\msys32\usr\bin\bash.exe --login -i -new_console:C:"%ConEmuDrive%\msys32\msys2.ico" -new_console:d:"C:\Documents and Settings\lenovo" ``` --- Tags: microsoft-windows, terminal-emacs ---
thread-58547
https://emacs.stackexchange.com/questions/58547
Avoid "`timestamp-wrapper`" span around timestamps when exporting org to markdown
2020-05-16T15:13:57.443
# Question Title: Avoid "`timestamp-wrapper`" span around timestamps when exporting org to markdown Version info: ``` Emacs: 26.3 Org: 9.1.9 ``` Am trying to export `org` notes to `markdown` format for publishing. Am using the `org-gfm-export-as-markdown` to preview the markdown that will be generated. Later I will wrap this in a script so I can do bulk export. However am having a tough time finding an option that will export the timestamps as normal text and not surround it with the `<span class="timestamp-wrapper"></span>` Please find the image as an example: I would like the timestamp line to look something like this in markdown: ``` ## [2018-11-14 Wed]: #journal: ``` P.S.: I tried `pandoc` but I had other issues with it. The `[` in the timestamp was exported as `\[`. For eg: `## \[2018-11-14 Wed\]: \#journal: @EmacsExport` # Answer > 1 votes \[This is a supplement to my other answer: it has very little to do with emacs, but it does address the common question of how to sustainably carry a patch for some upstream component, in the context of an emacs package. If the moderators deem it off-topic, I will delete it or perhaps incorporate it into my other answer, whichever seems most appropriate.\] My other answer describes the low-level things that you would have to do in emacs to add a timestamp-rendering function that does away with some of the things that the built-in function does. Basically, you write your own back end, `my-gfm`, which inherits from the `gfm` back end, which inherits from the `md` back end, which inherits from the `html` back end. You only provide one function in your back end to override the one in the `html` back end (since the intermediate back ends do not redefine that function). There are disadvantages however: you have to maintain your own back end and you don't get your back end in the export menu unless you expend extra effort (see `org-export-define-derived-backend`'s `:menu-entry` option), so you have to manually export with `(org-export-to-buffer 'my-gfm)` or `(org-export-to-file 'my-gfm)`. @dbx48's answer correctly advises to file an issue with the upstream `ox-gfm` project: they might do the change and that will spare you from the effort necessary to maintain your own back end in perpetuity. The question is: what to do in the meantime (or if they refuse to make that change)? What I would do is clone the `ox-gfm` github repo, create a branch, switch to it and apply the change to add a `timestamp` function at the `gfm` level: ``` git clone https://github.com/larstvei/ox-gfm.git cd ox-gfm git checkout -b timestamp ... edit ox-gfm.el and add the line `(timestamp . my-gfm-org-timestamp)` to it, somewhere in the `:translate-alist` list. ``` Then point my emacs to that: ``` (add-to-list 'load-path "/path/to/cloned/ox-gfm") ``` That allows you to use the `gfm` menu entry and to more-or-less forget that you patched `ox-gfm` -- until there is an upstream change to `ox-gfm` and you want to install the new version. Git makes that fairly easy: ``` cd /path/to/cloned/ox-gfm git remote update git checkout master git rebase git checkout timestamp git rebase master ``` That's it (and you can actually shorten that sequence, using more advanced git, but I'll skip that here). What this does is: * pull down the changes from upstream * switch to your master branch * update the master branch with the changes that you pulled down * switch to the timestamp branch * rebase your timestamp branch on your current master, thereby applying the timestamp patch to the current `ox-gfm` code. You can then continue as if nothing happened. If the change *is* applied upstream, all you have to do is get rid of the timestamp branch and just keep the master branch. The update procedure is the same for the first four steps: you just skip the last two steps since you no longer have to maintain a timestamp branch. # Answer > 2 votes That's either a bug or a feature in the `ox-gfm` package. Basically, the `ox-gfm` package defines an exporter that derives from the `ox-md` exporter, which derives from the `ox-html` exporter. The html exporter states that all timestamps need to be run through the `org-html-timestamp` function, which is what prints out the span you see. Neither the md or gfm exporter happen to override that decision, so they both print out timestamps in exactly the same way. You could file a bug (or a feature request) at https://github.com/larstvei/ox-gfm, or you could take a look at the source code an modify it to do what you want. The exporter is defined at https://github.com/larstvei/ox-gfm/blob/master/ox-gfm.el#L43-L62; you could just add a `(timestamp . your-function-here)` entry to it. # Answer > 1 votes The reason for this is the `md` export backend is derived from the `html` backend and does *not* redefine how time stamps are exported, so it falls back to however the `html` backend exports time stamps. There are various ways, some more invasive than others, to change that. The least invasive way is probably to define your own specialized backend that is almost `md` but not quite. See the doc string for the function `org-export-define-derived-backend` and in particular the example shown there: you only need a tiny modification (I think - this is untested, so caveat emptor): ``` (org-export-define-derived-backend 'my-md 'md :translate-alist '((timestamp . my-md-org-timestamp))) (defun my-md-org-timestamp (timestamp _contents info) "Transcode a TIMESTAMP object from Org to my-md. CONTENTS is nil. INFO is a plist holding contextual information." (let ((value (org-html-plain-text (org-timestamp-translate timestamp) info))) (format "%s" value))) ``` You can of course change that last function to modify the value to whatever you want, but try it as is first. EDIT: I missed the fact that you are using `ox-gfm` rather than `md`. You should derive the `my-md` backend from the `gfm` backend (and maybe call it `my-gfm` instead of `my-md`), but the rest is the same (although again you might want to rename things for clarity). EDIT: The function `org-export-define-derived-backend` is defined in the file `ox.el` which contains the generic bits of the exporter. You may need to `require` that library before you use it. Add ``` (require 'ox) ``` at the top of the code above. Here's the final code (still untested, but including the gfm changes and the renaming from the first edit): ``` (require 'org) (require 'ox) (require 'ox-html) (require 'ox-gfm) (org-export-define-derived-backend 'my-gfm 'gfm :translate-alist '((timestamp . my-gfm-org-timestamp))) (defun my-gfm-org-timestamp (timestamp _contents info) "Transcode a TIMESTAMP object from Org to my-gfm, a derived exporter from the gfm exporter, which in turn is derived from the md exporter, which is derived from the html exporter. CONTENTS is nil. INFO is a plist holding contextual information." (let ((value (org-html-plain-text (org-timestamp-translate timestamp) info))) (format "%s" value))) ``` --- Tags: org-export, markdown, pandoc ---
thread-58582
https://emacs.stackexchange.com/questions/58582
How can you automatically translate fractions into their short unicode versions? e.g. ⅔
2020-05-18T19:06:59.337
# Question Title: How can you automatically translate fractions into their short unicode versions? e.g. ⅔ Ideally one can just type fractions as normally e.g. 2/3, and either the view simply displays it as ⅔, without changing the text itself OR the text itself is changed. I need this for org mode in case that's relevant. # Answer > 3 votes You could use `prettify-symbols-mode` with something, evaluable in your sratch buffer, like this: ``` (progn (push '("2/3" . ?⅔) prettify-symbols-alist) (prettify-symbols-mode -1) (prettify-symbols-mode +1)) ``` It only adds that particular fraction and it's unicode counterpart to the list of symbols to prettify, then resets the mode If it works as expected, just add the prettification symbols you need to the mode hook you want. # Answer > 2 votes If you're willing to have the text change, you can use one of Emacs' many input methods. With e.g. `rfc3145`, you could type that as ``` &23 ``` or with `TeX` it would be ``` \\frac23 ``` Use `C-\` to choose your input method. # Answer > 0 votes EDIT: Doesn't work completely, see comment on Muihlinn's answer. Based off Muihlinn's answer, I looked into `prettify-symbols-mode` and ended up finding this macro which solved my problem cleanly: https://github.com/Ilazki/prettify-utils.el/blob/master/prettify-utils.el#L222-L243 ``` (prettify-utils-add-hook org-mode ("1/4" "¼") ("1/2" "½") ("3/4" "¾") ("1/3" "⅓") ("2/3" "⅔") ("1/5" "⅕") ("2/5" "⅖") ("3/5" "⅗") ("4/5" "⅘") ("5/6" "⅚") ("1/8" "⅛") ) ``` --- Tags: unicode, math ---
thread-58032
https://emacs.stackexchange.com/questions/58032
cannot get magit to visit actual file from diff buffer (have to use a "ffap" based workaround)
2020-04-24T13:59:09.630
# Question Title: cannot get magit to visit actual file from diff buffer (have to use a "ffap" based workaround) When in a magit diff view, pressing enter in a blob 'visit' the file. But this file is a special read only version. The magit manual mentions a way to visit the (actual writable) file: ``` C-<return> (magit-diff-visit-file-worktree) source: https://magit.vc/manual/magit/Visiting-Files-and-Blobs-from-a-Diff.html ``` This combo doesn't work, and `M-x` doesn't even mention a `magit-diff-visit-file-worktree` What am I doing wrong? ``` My system: GNU Emacs 26.2 (build 1, x86_64-apple-darwin18.5.0) of 2019-04-13 -UUU:@%%--F7 magit-diff: web-app Top L1 (Magit Diff yas Rails Projectile WK) ---- macOS 10.15.3 ``` # Answer > 1 votes I think you are simply using an older version of Magit. Using this commit d05545ec2fd7edf915eaf1b9c15c785bb08975cc, it works for me (I'm managing my Emacs packages using GNU Guix. MELPA also tracks the latest Magit commit. Something I find useful to diagnose which function is mapped to a certain key stroke is `C-h k <key strokes>`. In the present case, `C-h k C-<RET>` when looking at a hunk in magit-diff should display something like: ``` <C-return> runs the command magit-diff-visit-worktree-file (found in magit-hunk-section-map), which is an interactive compiled Lisp function in ‘/gnu/store/8h3ag9i2azawrxvl0jzrz52a533psdbq-emacs-magit-2.90.1-4.d05545e/share/emacs/site-lisp/magit-diff.el’. It is bound to <C-return>, C-j. (magit-diff-visit-worktree-file FILE &optional OTHER-WINDOW) From a diff visit the worktree version of FILE. [...] ``` --- Tags: magit ---
thread-53417
https://emacs.stackexchange.com/questions/53417
how to speed up org-babel-tangle?
2019-10-28T15:00:26.320
# Question Title: how to speed up org-babel-tangle? I have an org file of 470 lines, 20 headings and 15 noweb references. From it I tangle 2 files that are 250 lines and differ very little. Tangling takes over a minute and a lot of painful redisplay: * the modeline shows clauses being tangled * the buffer jumps to the different references How can I speed this up? I tried the following but it has no effect: ``` ;; tangle is too slow, try to speed it up (add-hook 'org-babel-pre-tangle-hook (defun my-org-babel-pre-tangle-hook () (setq inhibit-redisplay t))) (add-hook 'org-babel-post-tangle-hook (defun my-org-babel-pre-tangle-hook () (setq inhibit-redisplay nil))) ``` Also, I'm afraid that if it had effect, an exception (or user-quit) may leave `inhibit-display` on and lock me out of emacs. # Answer > 2 votes I have a growing org file of 5000 lines, 200 headings and 150 noweb references. I tangle a 3000 lines file. Using the built-in `org-babel-tangle` takes over 10 minutes. I wrote `ob-tangle.pl` to do - quickly, under a second - the limited feature tangle I need: ``` #!/usr/bin/perl # ob-tangle.pl -- simplified noweb tangle of a named org-mode SRC block # ob-tangle.pl file.org main # Named block must start with (just) 2 lines: #+NAME: and #+BEGIN_SRC: # #+NAME: main # #+BEGIN_SRC ... # ... # #+END_SRC # Tangled code is sent to STDOUT. # All BEGIN_SRC parameters (like ":comments noweb") are ignored. die "Usage: ob-tangle.pl orgFilename srcBlockName" if @ARGV != 2; my ($orgFile, $blockName, @rest) = @ARGV; my %name_src = readNamedSrcBlocks($orgFile); tangle($blockName, 0); # 0 means no added indent sub tangle { my ($blockName, $indent) = @_; my $spaces = ' ' x $indent; my $src = $name_src{$blockName}; my @src = split /^/, $src; while (my $srcline = shift @src) { chomp $srcline; # remove trailing linefeed my ($spaces2, $nowebName) = $srcline =~ /^(\s*)<<(.+?)>>\s*$/; if ($nowebName) { my $indent2 = length($spaces2); tangle($nowebName, $indent2+$indent); } else { print $spaces, $srcline, "\n"; } } } sub readNamedSrcBlocks { my ($orgFile) = @_; open(my $F, '<', $orgFile) || die "Can't open $orgFile: $!"; my $text = join('', <$F>); close $F; (%name_src) = $text =~ /^\s*#\+NAME:\s*(\S+)\s*?\n\s*#\+BEGIN_SRC.*?\n(.*?)\n\s*#\+END_SRC/msig; } Works for me -- YMMV. ``` # Answer > 1 votes Partial answer: this does it and reduces tangling time by about 40% (subjective). But I'm looking for more ways to speed it up. Compared to eg the C preprocessor `cpp`, `org-tangle` is very slow. ``` (defadvice org-babel-tangle-single-block (around inhibit-redisplay activate protect compile) "inhibit-redisplay and inhibit-message to avoid flicker." (let ((inhibit-redisplay t) (inhibit-message t)) ad-do-it)) (defadvice org-babel-tangle (around time-it activate compile) "Display the execution time" (let ((tim (current-time))) ad-do-it (message "org-tangle took %f sec" (float-time (time-subtract (current-time) tim))))) ``` --- Tags: org-babel, tangle, redisplay ---
thread-32385
https://emacs.stackexchange.com/questions/32385
how to name buffers (*shell*)
2017-04-26T07:14:22.670
# Question Title: how to name buffers (*shell*) I'm interested in naming Emacs buffers. In particular I'd like to give names to `shell` buffers that I've started. That way I can easily tell them apart when switching buffers. # Answer > 14 votes Go to the buffer you want to rename, in your case `*shell*`. Then type `M-x rename-buffer` and enter the new name for this buffer. # Answer > 1 votes If you use `Helm`. Just press `M-R` in helm buffer list. It calls helm-buffer-run-rename-buffer which will call emacs `rename-buffer` function. # Answer > 0 votes Add a function to your init.el, and create a keybinding: ``` (defun unique-shell () (interactive) (call-interactively 'shell) (rename-uniquely)) (global-set-key "\C-z" 'unique-shell) ``` Now every time you press ctrl+z, it will launch a shell with a new name. --- Tags: buffers, shell ---
thread-58612
https://emacs.stackexchange.com/questions/58612
How may I completely disable all Emacs' default bindings to the Fn keys (F2 - F12)?
2020-05-20T15:26:19.657
# Question Title: How may I completely disable all Emacs' default bindings to the Fn keys (F2 - F12)? I'm willing to allow help to remain on `F1`, but I don't want any of Emacs default bindings on any of the other `Fn` keys. If you must know why, it's because all keyboards made in the last 20 years are garbage, and I'm done putting up with "accidentally" ending up in 2C mode. # Answer ``` (global-set-key [f2] nil) ``` will 'unbind' `f2`, so you don't need to worry about accidentally entering 2C mode. There's no general way to disable all the function keys, but you can rebind them however you like, just like other keys. F5-F9 are reserved for user's to bind as they like, so they shouldn't be bound to anything already. Some package developers ignore this recommendation though. > 1 votes --- Tags: key-bindings ---
thread-58519
https://emacs.stackexchange.com/questions/58519
How to make company-lsp case sensitive?
2020-05-15T07:30:25.323
# Question Title: How to make company-lsp case sensitive? Currently if I try to complete a work, the case of the prefix is ignored with company-lsp. From looking into the code, `company-lsp` is hard-coded to use `ignore-case`. As at the time of writing `company--begin-new` calls: `(company-call-backend 'ignore-case))` Is there a way to make company-lsp case sensitive? # Answer `company-lsp` is deprecated use `company-capf` (just delete `company-lsp` and `lsp-mode` will pick it). company-capf is case-sensitive by default. > 1 votes --- Tags: company-mode, lsp-mode ---
thread-58611
https://emacs.stackexchange.com/questions/58611
Is there a way to get proper "breadcrumbs" behavior in emacs?
2020-05-20T14:30:29.890
# Question Title: Is there a way to get proper "breadcrumbs" behavior in emacs? I want something that I figured would be pretty basic, what with all the fancy mark-ring and all, but I can't find a way to get. I want a global (i.e. across files) no-nonsense "breadcrumbs" behavior - that is, the ability to jump backwards (and forwards!) through the locations I visited. I really like that locations are pushed into the ring when I search or give movement commands (I'm on spacemacs), and I would also like to have the same behavior when I jump to a new buffer, or follow links in org-mode. I've found the breadcrumbs package, but I don't know how to go about integrating the setting of those breadcrumbs in all the different movements around files (I also favor a more a solution that's more native to emacs, such as the mark-ring, but beggars can't be choosers...). # Answer > 2 votes If you use Bookmark+ then you can automatically create bookmarks for the places you visit. Such bookmarks can be persistent (default behavior) or temporary. > In general, you probably do not want such bookmarks to be created too often or too close together. You probably do not care about the names of the bookmarks created, and you do not want to be interrupted to name them. You probably want automatic bookmarking to be per-buffer, but you might sometimes want to turn it on or off for all buffers. You might want more than one automatic bookmark on a given line, but probably not. Finally, you might or might not want automatic bookmarks to be temporary (current session only) or highlighted. There are user options that control all such behavior. --- Tags: bookmarks, navigation, breadcrumbs ---
thread-58545
https://emacs.stackexchange.com/questions/58545
Emacs completion through symlink (OSX)
2020-05-16T11:23:26.437
# Question Title: Emacs completion through symlink (OSX) I have a symlink on my Desktop that points to my Dropbox folder. Clicking on this link takes me through to Dropbox, which is located elsewhere. But if I try navigating to `~/Desktop/Dropbox` using Emacs, it tells me that the symlink is the sole completion and will not go further. How can I get Emacs to let me to `TAB` through the symlink, so that I can start with `~/Desktop` and then navigate to say: `~/Desktop/Dropbox/folder/inside/Dropbox/...`? # Answer Looks like your symlink is a finder alias and not a symlink. OSX Finder handles both of them the same way, but at system level the finder alias is a plain file. Substitute the finder alias for a proper unix symlink using `ln -s` command and it should work. > 1 votes --- Tags: osx, completion, symbolic-links ---
thread-24290
https://emacs.stackexchange.com/questions/24290
How to install package without install dependencies through "package"?
2016-06-29T22:41:31.713
# Question Title: How to install package without install dependencies through "package"? I am using `:ensure t` of `use-package` to install "go-prjectile" package which depends on "go-rename". But I would like to use a local version of "go-rename" and its path is already added to `load-path`. My configuration: ``` (use-package go-rename :load-path "lisp/go-rename") (use-package go-projectile :ensure t) ``` But every time when "go-projectile" is installed, the "go-rename" is also installed from melpa too. Is there any way to only install "go-projectile" without install its dependencies? # Answer > 0 votes First thanks for the answer from @chenbin. All the following ideas from his answer and blog post. Maybe I have some mis-understand on the 4 step way to create local elpa. For me to manually maintain it is painful (For example, package from git repo, keep updating). After some googling about "local elpa" I steal code (Makefile, package-build.el) from "melpa" which would build local elpa `packages` and `archive-contents` from `recipes`. Then I only need to maintain recipes something like below (use `ob-go` as example) ``` (ob-go :fetcher github :repo "pope/ob-go") ``` The make file would cache the package from Github and create `archive-contents` to `packages` directory. Then I just need to add `("local-elpa" . "~/.emacs.d/packages")` to `package-archives` and pin it to `local-elpa`. If local elpa packages has updates, just make the packages and archive-contents, then update packages as usual. # Answer > 2 votes I think the cleanest solution is to tell `package.el` that you have already `lsp-mode` mode. You can do it in two different ways: 1. If you have installed `lsp-mode` in a format/layout that `package.el` can understand (most importantly it contains both `<pkg>-autoloads.els` and `<pkg>-pkg.el`), then just make sure that it is in one of the directories mentioned in `package-directory-list`). 2. If you installed it using a different format/layout, then use something like: ``` (add-to-list 'package--builtin-versions `(go-rename 1 2 1)) ``` It is important to do this early, i.e. before `package-activate-all` or `package-initialize` is called, so in Emacs≥27, you will want to put it into your `early-init.el`. # Answer > 1 votes See http://blog.binchen.org/posts/how-to-manage-emacs-packages-effectively.html which provides complete solution for Emacs 23.4, 24.3, 24.4, 25. In your case, the easiest way is to setup your own package repository `localelpa`: Step 1, create directory `~/.emacs.d/localelpa` Step 2, create file `~/.emacs.d/localelpa/archive-contents` with below content ``` (1 (go-rename . [(1 2 1) nil "This is go-rename, blah blah" single]) ) ``` Step 3, place go-rename-1.2.1.el at `~/.emacs.d/localelpa` Step 4, insert below code into `~/.emacs.d/init.el` and restart Emacs: ``` (add-to-list 'package-archives '("localelpa" . "~/.emacs.d/localelpa")) ``` Now you will see package goname-1.2.1 after `M-x list-packages`, in Emacs 24.4 you can tweak `package-pinned-packages` to pin that package (https://www.gnu.org/software/emacs/manual/html\_node/emacs/Package-Installation.html) What about Emacs 24.3, 23.4? Well, why not change version from 1.2.1 to 99.9.9? ;) # Answer > 1 votes I had this exact problem. I was trying to use a local version of `lsp-mode` but packages which depended on it were installing `lsp-mode` from melpa. @chenbin's solution would successfully filter out `lsp-mode` from the package list (i.e. when you `M-x list-packages`) but it would still be installed when installing any packages for which it was a dependency. I'm using `(use-package)` to specify the load path of my manually installed packages. Adding this code **before** `(package-initialize)` is called works for me: ``` (defvar local-only-packages '(lsp-mode) "Don't install these packages as dependencies, I will install them manually.") ;; When determining dependencies to install, filter out any packages you will ;; handle manually. (advice-add 'package-compute-transaction :filter-return (lambda (packages) (seq-filter (lambda (it) (not (memq (package-desc-name it) local-only-packages))) packages))) ;; When creating package-descriptions that will be initialized by ;; package.el, filter out the dependncies that are handled manually. (advice-add 'package-desc-from-define :filter-return (lambda (pkg-desc) (setf (package-desc-reqs pkg-desc) (seq-filter (lambda (it) (not (memq (car it) local-only-packages))) (package-desc-reqs pkg-desc))) pkg-desc)) ``` --- Tags: package, use-package ---
thread-47795
https://emacs.stackexchange.com/questions/47795
Spacemacs: How can I customize the highlight style of a matching parenthesis?
2019-02-13T11:15:38.687
# Question Title: Spacemacs: How can I customize the highlight style of a matching parenthesis? How do I change, in my `.spacemacs`, the style used to highlight the matching parenthesis? # Answer You can see a list with all the colors set by emacs with `M-x``list-faces-display` RET. There you can search for the faces corresponding to parenthesis matching: `show-paren-match` in this case. If you click on it to customize it, test it or even save it. If you choose to save, this setting will be saved to your *custom-file* (`C-h``v``custom-file`RET - for more info). If you want to directly set the face in your `.spacemacs` you could use `custom-set-faces` ``` (custom-set-faces '(show-paren-match ((t (:foreground "white" :background "red"))))) ``` or use your theme name with `custom-theme-set-faces`: ``` (custom-theme-set-faces 'your-theme-name-here ;; e.g. 'spacemacs-dark '(show-paren-match ((t (:foreground "white" :background "red"))))) ``` or by using the theming layer ``` (setq theming-modifications '((your-theme-name ;; e.g. spacemacs-dark (default :foreground "white" :background "red")))) ``` or by using `set-face-attribute` ``` (set-face-attribute 'show-paren-match nil :foreground "white" :background "red") ``` > 2 votes # Answer Would leave comment but don't have the reputation yet. For me it was `Highlight-Parentheses` minor mode. I use spacemacs so its likely what was bothering you too. > 1 votes --- Tags: spacemacs, highlighting, parentheses ---
thread-58620
https://emacs.stackexchange.com/questions/58620
Create shortcut for interactive compile command
2020-05-20T20:24:38.317
# Question Title: Create shortcut for interactive compile command I know that we can start `compile` interactively using `C-u M-x compile`. Is there a way to start this whenever I run `M-x compile`? If that cannot be done, how do I create a shortcut to `C-u M-x compile`? My current shortcut for `M-x compile` is: `(global-set-key (kbd "<f5>") 'compile)` This would execute normal compile (not interactive). Ideally, I would like to create a separate shortcut for interactive compile (for program that requires a lot of user inputs). Please let me know and thanks for your help **Edit:** I forgot the mention that my compile command is also customized based on mode hook. For example, below is how I customize it for C++ mode hook and Fortran mode hook: ``` (add-hook 'c++-mode-hook (lambda () (set (make-local-variable 'compile-command) (concat "g++ -g -Wall -lm " buffer-file-name " && ./a.out" ) ))) (add-hook 'fortran-mode-hook (lambda () (set (make-local-variable 'compile-command) (concat "gfortran " buffer-file-name " && ./a.out" ) ))) ``` # Answer ``` (global-set-key [f5] (lambda () (interactive) (let ((current-prefix-arg '(4))) (call-interactively 'compile)))) ``` > 1 votes --- Tags: customize, comint, compile ---
thread-58472
https://emacs.stackexchange.com/questions/58472
How to use unicode for the checkbox in customize buffers (**not** in org mode)?
2020-05-12T18:00:02.627
# Question Title: How to use unicode for the checkbox in customize buffers (**not** in org mode)? I'm trying to modify the appearance of customize buffers. I managed to modify the button but I did not find how to change the appearance of the checkbox nor the dropdown indicator (▽). Ideally I would like to replace them with corresponding unicode glyphs. You can see what is the "real" character using `describe-char` but I'm a bit clueless on where the translation into images occurs and how to modify it. # Answer Checkboxes can be disabled using: `(setq widget-image-enable nil)` and will appear as `[ ]` or `[X]` that can be then prettified: ``` (setq widget-image-enable nil) (add-hook 'custom-mode-hook (lambda () "Beautify custom checkbox symbol" (push '("[ ]" . "☐") prettify-symbols-alist) (push '("[X]" . "☑" ) prettify-symbols-alist) (prettify-symbols-mode))) ``` > 0 votes --- Tags: customize, widget ---
thread-58639
https://emacs.stackexchange.com/questions/58639
How to prevent #+BEGIN_LaTeX from generating \begin{LaTeX} when exporting to .tex source?
2020-05-21T13:19:31.163
# Question Title: How to prevent #+BEGIN_LaTeX from generating \begin{LaTeX} when exporting to .tex source? I am a beginner and have been using emacs for around a month. I'm still finding my way around. Sorry if this is a very basic question. I'm trying to write a scientific document in org-mode and using org-ref for citations and references. I'm also using CDLaTeX mode for easier math input. To let org-ref find my equation labels, I have to enclose then in a #+BEGIN\_LaTeX and #+END\_LaTeX block. I have something like this ``` #+BEGIN_LaTeX \begin{equation} \label{eq:unitary-evo-state} \ket{\psi(t)} = U(t) \ket{\psi(0)} \qq{and} \imath\hbar\ket*{\dot{\psi}} = H(t)\ket{\psi} \end{equation} #+END_LaTeX ``` When I export this to a LaTeX file, it generates the following LaTeX code ``` \begin{LaTeX} \begin{equation} \label{eq:unitary-evo-state} \ket{\psi(t)} = U(t) \ket{\psi(0)} \qq{and} \imath\hbar\ket*{\dot{\psi}} = H(t)\ket{\psi} \end{equation} \end{LaTeX} ``` The outer `\begin{LaTeX}` and `\end{LaTeX}` tags essentially insert a `\latex` before the equation. Is there a workaround for this? I was using John Kitchin's org-ref video as a reference and this behavior does not happen there. I'm using Doom emacs with TeX-Live on Ubuntu. Any help is much appreciated. Thank you very much. # Answer > 0 votes You need to use ``` #+begin_export latex \begin{equation} \label{eq:unitary-evo-state} \ket{\psi(t)} = U(t) \ket{\psi(0)} \qq{and} \imath\hbar\ket*{\dot{\psi}} = H(t)\ket{\psi} \end{equation} #+end_export ``` If you use the new templating mechanism with `C-c C-,` you can select the "export latex" entry with `l`. If this does not work with `org-ref` then I suspect that it has not been updated for recent Org mode: try updating and if all fails, contact John Kitchin about it. --- Tags: org-mode, org-export, latex ---
thread-58640
https://emacs.stackexchange.com/questions/58640
How to access variables/lists by the strings of their names, prompted interactively
2020-05-21T13:24:36.650
# Question Title: How to access variables/lists by the strings of their names, prompted interactively I have a question about how to use `interactive` to allow the user to identify a desired list element to output. Let's say I have a variable `x` assigned to a list structured like this: ``` (setq x '((y ("y1") ("y2") ("y3")) (z ("z1") ("z2") ("z3")))) ``` If I want to retrieve the text "(y1)" from this structure and show it to the user, I know that I can do so by using: ``` (message (format "%s" (nth 1 (assoc 'y x)))) ``` The problem comes when I try to do the same thing interactively. Let's say I want to write a function that asks the user for the variable name and the desired list (y or z), then retrieves the first associated element: ``` (defun find-first-associated-value (varname listname) (interactive "sWhich variable? : sWhich list? :") (message (format "%s" (nth 1 (assoc listname varname))))) ``` If I try to call this function and fill in the right values, I get the error `Wrong type argument: listp, "y"`. I can tell the reason this isn't working is that I'm passing strings (`varname` and `listname`) to `assoc`, which expects a KEY and then VALUE. The problem is that I can't figure out how to convert the user-inputted strings collected by `interactive` to those forms so that they can be understood by `assoc`. How can I fix this? I'd be very grateful for any help, and I apologize if the question is poorly worded--I'm new to programming in Lisp. # Answer > 1 votes You can use `(interactive "S")` to obtain a symbol instead of a string. Regarding your general question, `(intern STRING)` returns the canonical symbol with the given name. `(eq 'foo (intern "foo"))` =\> `t` For more information, see `C-h``i``g` `(elisp)Creating Symbols` --- Tags: interactive, symbols ---
thread-58644
https://emacs.stackexchange.com/questions/58644
How can I find corresponding balanced parentheses?
2020-05-21T14:12:18.937
# Question Title: How can I find corresponding balanced parentheses? I have this LaTeX code: ``` \caption{Lorem ipsum dolor sit amet: foo), bar), baz) and qux) consectetuer adipiscing elit.} ``` I want to put a marker immediately before the first `{` and one immediately after its corresponding `}`. `forward-list` is my usual choice in order to find balanced parentheses, but in this case it is not suitable because it moves cursor immediately after the first `)` (as its standard behaviour). How can I do this? ``` ;; my standard way (while (re-search-forward "\\\\\\<caption\\>" nil t) (setq pos1 (point-marker)) (set-marker-insertion-type pos1 t) (forward-list) (setq pos2 (point-marker)) (set-marker-insertion-type pos2 t) (save-excursion (save-restriction (narrow-to-region pos1 pos2) (goto-char (point-min)) ;; do something ))) ``` **Updates** I have found an answer here: Strict parenthesis matching Function `forward-pexp` does the trick. # Answer > -1 votes Use `forward-sexp`, bound to `C-M-f`. See these nodes of the Emacs and Elisp manuals: --- Tags: motion, sexp, delimiters ---
thread-58634
https://emacs.stackexchange.com/questions/58634
Color calendar day according to number of event in org-agenda
2020-05-21T08:43:51.167
# Question Title: Color calendar day according to number of event in org-agenda I would like to color the background of each day in calendar according to the number of events in my org-agenda. The idea is to have a quick and visual idea of what are the busiest days. The code from How to highlight weekend days in Emacs calendar? might be a good start and I would need to write a function that, given a date, returns the number of scheduled event from my org-agenda/diary (I use org-diary) and set the face to `face-busy-0`, `face-busy-1`, etc. I already wrote a Python code for doing more or less the same in the terminal (see Yearly calendar view of agenda (with colored background) but my elisp is not so good. # Answer I ended up with the code below. I guess it can be shorten/optimized (it's a bit slow) but it does the job. ``` (defface busy-1 '((t :foreground "black" :background "#eceff1")) "") (defface busy-2 '((t :foreground "black" :background "#cfd8dc")) "") (defface busy-3 '((t :foreground "black" :background "#b0bec5")) "") (defface busy-4 '((t :foreground "black" :background "#90a4ae")) "") (defface busy-5 '((t :foreground "white" :background "#78909c")) "") (defface busy-6 '((t :foreground "white" :background "#607d8b")) "") (defface busy-7 '((t :foreground "white" :background "#546e7a")) "") (defface busy-8 '((t :foreground "white" :background "#455a64")) "") (defface busy-9 '((t :foreground "white" :background "#37474f")) "") (defface busy-10 '((t :foreground "white" :background "#263238")) "") (defadvice calendar-generate-month (after highlight-weekend-days (month year indent) activate) "Highlight weekend days" (dotimes (i 31) (let ((date (list month (1+ i) year)) (count (length (org-agenda-get-day-entries "~/Documents/org/agenda.org" (list month (1+ i) year))))) (cond ((= count 0) ()) ((= count 1) (calendar-mark-visible-date date 'busy-1)) ((= count 2) (calendar-mark-visible-date date 'busy-2)) ((= count 3) (calendar-mark-visible-date date 'busy-3)) ((= count 4) (calendar-mark-visible-date date 'busy-4)) ((= count 5) (calendar-mark-visible-date date 'busy-5)) ((= count 6) (calendar-mark-visible-date date 'busy-6)) ((= count 7) (calendar-mark-visible-date date 'busy-7)) ((= count 8) (calendar-mark-visible-date date 'busy-8)) ((= count 9) (calendar-mark-visible-date date 'busy-9)) (t (calendar-mark-visible-date date 'busy-10))) ))) ``` > 6 votes --- Tags: org-agenda, highlighting, calendar ---
thread-58633
https://emacs.stackexchange.com/questions/58633
Defining #+setupfile: *path* programmatically
2020-05-21T06:36:25.033
# Question Title: Defining #+setupfile: *path* programmatically I have a project under git which allows this ``` #+BEGIN_SRC emacs-lisp (expand-file-name (car (project-roots (project-current)))) #+END_SRC ``` to find my project root automatically. Now I want to use this path to automatically define my **setup file** location at the beginning of my regular org mode files. The idea is: ``` #+SETUPFILE: (concat (expand-file-name (car (project-roots (project-current)))) "setup/setup.org") #+TITLE: example ... ``` Unfortunately, this does not work as the expression `(concat ...)` is not interpreted as an emacs-lisp expression... Is it possible to make it work? --- **update:** to be sure to be able to run the provided example, please add ``` (require 'project) ``` # Answer > 6 votes I finally use this solution ``` src_emacs-lisp[:results raw]{(concat "#+SETUPFILE: " (expand-file-name (car (project-roots (project-current)))) "setup/setup.org")} #+TITLE: My test * Test... ``` An alternative that also works is to use a regular code block (you can define elsewhere and load with `org-babel-lob-ingest` in your Emacs init.el file, Config, examples and use cases of Library Of Babel ) ``` #+NAME: Setup #+BEGIN_SRC emacs-lisp :results drawer (concat "#+SETUPFILE: " (expand-file-name (car (project-roots (project-current)))) "setup/setup.org") #+END_SRC ``` Then in your documents, use: ``` #+CALL: Setup() #+TITLE: My test * Test... ``` --- You can check it with `C-c C-e O O` or equivalently by calling `M-x org-org-export-as-org` You get: ``` # Created 2020-05-21 Thu 21:04 #+TITLE: My test #+AUTHOR: picaud #+SETUPFILE: /home/picaud/GitHub/Project/setup/setup.org * Test... ``` --- Tags: org-mode ---
thread-58645
https://emacs.stackexchange.com/questions/58645
sage-shell-mode repeat the input in the output
2020-05-21T14:24:43.673
# Question Title: sage-shell-mode repeat the input in the output I wanted to use sagemath straight in emacs instead of having a terminal open. I tried to use a shell (or eshell for that matters) in emacs and launch sage there, but every time I input a command, the ouput repeats this and then displays the result. Something like: ``` ┌────────────────────────────────────────────────────────────────────┐ │ SageMath version 8.1, Release Date: 2017-12-07 │ │ Type "notebook()" for the browser-based notebook interface. │ │ Type "help()" for help. │ └────────────────────────────────────────────────────────────────────┘ sage: 2+2 sage: 2+2 4 sage: ``` After a quick search on how to use sage in emacs, I found the neat `sage-shell-mode`. Installed it using `MELPA` (as recommended), but the problem is the same. I have no idea where it comes from and how to fix it. N.B. when I use emacs shell (or eshell), I have no problem. When I use sage in a terminal, I have no problem. Only when I use sage in emacs (in a shell or using sage-shell-mode) I got the issue. I'm using Emacs 25.2.2 and SageMath 8.1 # Answer > 0 votes This is a problem of cursor positioning - it looks identical to the problem encountered when running `ipython5` as described here: Weird shell output when using IPython 5 Unfortunately, it does not appear that SageMath allows you to pass in the `--simple-prompt` argument. The SageMath shell does work properly when it can set cursor position, and therefore works well using `M-x term` or `M-x ansi-term`, both of which provide terminal emulation. Good news for the future: I found a PR awaiting merge in the python-prompt-toolkit repo that aims to fix this problem. Then all you will need to do is install from `pip install` or build from source, and set `sage-shell:use-prompt-toolkit` to `t` in the `sage-shell-mode` package. --- Tags: shell, major-mode ---
thread-52693
https://emacs.stackexchange.com/questions/52693
Integrating org-download with org-journal; images do not download
2019-09-17T02:36:33.420
# Question Title: Integrating org-download with org-journal; images do not download I have org-journal entries which I'd like to link to images that are also stored alongside them in the filesystem. Ideally this would happen automatically when an image is dragged-and-dropped on the buffer. Org-download seems to be a good fit for this application. I can configure org-download to download and link images into regular org files, but I cannot achieve the same for org-journal files. I received some suggestions for this on Reddit. For normal org-mode files, from my `init.el`: ``` (use-package org-download :ensure t :defer t :init ;; Add handlers for drag-and-drop when Org is loaded. (with-eval-after-load 'org (org-download-enable))) ``` I would expect this to also work for org-journal files, since they are also org-mode files. But it does not, so I've tried adjusting the configuration: ``` (use-package org-download :ensure t :defer t :after (:any 'org 'org-journal) :config (org-download-enable)) ``` This also does not work. Next I tried manually instigating with `M-: (org-download-enable)` while working on an org-journal entry. That command returns `nil` and dragging and dropping images still does not work. At this point I'm not sure how to proceed. I'm new to configuring emacs, and likely am missing something simple. Any suggestions would be appreciated. # Answer In case you care about this, I found this bug and opened an issue: https://github.com/bastibe/org-journal/issues/236 Basically, org-download checks that the major mode is org-mode, but org-journal changes that to org-journal-mode. > 1 votes --- Tags: org-mode, use-package ---
thread-58656
https://emacs.stackexchange.com/questions/58656
How to insert the current date into a file using abbrev or similar?
2020-05-22T03:06:49.887
# Question Title: How to insert the current date into a file using abbrev or similar? I'd like to replicate something in emacs that I do in AutoHotkey all the time: 1. type `td` 2. have that string be replaced with the current date I'm trying to do this with Emacs abbrevs but I'm running into an `Invalid function:` error. I've also tried using a builtin function, but I get the same Invalid function error. I've done a bunch of research but no avail. Here's the code I have currently in my `.emacs`: ``` (defun insert-current-iso-date () "..." (format-time-string "%Y-%m-%d")) (define-abbrev-table 'global-abbrev-table '(("td" "" (insert-current-iso-date)))) ``` # Answer > 4 votes You need to remove the parenthesis from your custom function. It's calling for hook function name there, not its evaluation. ``` (define-abbrev-table 'global-abbrev-table '(("td" "" insert-current-iso-date))) ``` Anyway, to my understanding, you should define your abbrevs the way it's intended which is using `define-abbrev`, whose syntax is easier to follow, and not overriding the whole table definition unless you have a good reason to do so. ``` (define-abbrev global-abbrev-table "td" "" 'insert-current-iso-date) ``` And, as @NickD pointed: > you have to change the `insert-current-iso-date` to insert the string: it is not enough to return it as it does currently: > > ``` > (defun insert-current-iso-date () > (insert (format-time-string "%Y-%m-%d")) > > ``` > > And of course you have to turn on abbrev-mode. --- Tags: time-date, abbrev ---
thread-58660
https://emacs.stackexchange.com/questions/58660
helm and ff-find-other-file
2020-05-22T07:54:07.500
# Question Title: helm and ff-find-other-file When I try to use the function `ff-find-other-file` on a C file, and the header file does not exist, I expect emacs to create a header file at the current location. Since I started using helm, something else happens: ``` $ mkdir /tmp/helm-other-file $ cd /tmp/helm-other-file $ emacs a.c ``` `M-x ff-find-other-file` opens a helm buffer with two entries: ``` /tmp/helm-other-file/. /tmp/helm-other-file/.. ``` I expected that selecting the first would mean to create the buffer at that location: `/tmp/helm-other-file/a.h`. Instead, the following is created: `/tmp/helm-other-file/a.h/a.h`. That's one (new) directory too deep. If I select the `..` version, to compensate for "too deep", I get `/tmp/a.h`. That's not deep enough. If I go up a level with `C-l` after `ff-find-other-file`, then select `helm-other-file/`, I go back to this: `/tmp/helm-other-file/a.h/a.h`. How can I fix `ff-find-other-file` so that unfound header file is created at the same location as the C file, with helm? I'm aware that helm-projectile might fix this, but I don't want to bring in the whole package only for that function. # Answer > 1 votes It seems you've helm-mode enabled, the minor mode overwrites Emacs' built-in completing behavior, the thing you want is the default (it comes from `completing-read`'s `DEF` argument) value, you can either `C-RET` (`helm-cr-empty-string`) to apply the default value or `M-n` (`next-history-element`) to insert the default value then `RET`. You can also blacklist `ff-find-other-file` from helm-mode, next time helm-mode won't be involved in `ff-find-other-file`: ``` (add-to-list 'helm-completing-read-handlers-alist '(ff-find-other-file . nil)) ``` --- Tags: helm ---
thread-57493
https://emacs.stackexchange.com/questions/57493
Add a border around the region by inserting a given character
2020-03-31T17:03:45.647
# Question Title: Add a border around the region by inserting a given character There's here, for example, given text: ``` WASP-41b 0.94 1.18 3.052404 0.04 1244 transit 590 0.93 5545 WASP-42b 0.527 1.122 4.9816819 0.0561 transit 520 0.95 5315 WASP-47b 1.21 1.15 4.16071 0.052 1275 transit 650 1.11 5576 WASP-49b 0.378 1.115 2.7817387 0.0379 transit 550 0.94 5600 WASP-52b 0.46 1.27 1.7497798 0.0272 transit 460 0.87 5000 WASP-54b 0.636 1.653 3.6936411 0.04987 transit 650 1.21 6100 WASP-55b 0.627 1.335 4.4656291 0.0558 1290 transit 1100 1.16 6070 WASP-56b 0.571 1.092 4.617101 0.05458 transit 830 1.03 5600 WASP-57b 0.644 1.05 2.83891856 0.03769 transit 1480 0.89 5600 ``` Want to modify `buffer` text around given marked `region` with some character, turning it as: ``` WASP-41b 0.94 1.18 3.052404 0.04 1244 transit 590 0.93 5545 WASP-42b 0.527 1.122 4.9816819 0.0561 transit 520 0.95 5315 WASP-47b 1.21 1.15 4.16071 0.052 1275 transit 650 1.11 5576 *********************************************** WASP-49b 0.378 1.115 * 2.7817387 0.0379 transit 550 * 0.94 5600 * * WASP-52b 0.46 1.27 * 1.7497798 0.0272 transit 460 * 0.87 5000 * * WASP-54b 0.636 1.653 * 3.6936411 0.04987 transit 650 * 1.21 6100 * * WASP-55b 0.627 1.335 * 4.4656291 0.0558 1290 transit 1100* 1.16 6070 *********************************************** WASP-56b 0.571 1.092 4.617101 0.05458 transit 830 1.03 5600 WASP-57b 0.644 1.05 2.83891856 0.03769 transit 1480 0.89 5600 ``` That seems to be very simple, but would like to know how to do it. Any idea? # Answer Have a look in ibm-box-drawing-hydra.el library, maybe isn't exactly what is seeked, but gives a north. > 1 votes --- Tags: text-editing, region ---
thread-58590
https://emacs.stackexchange.com/questions/58590
Why set-window-dedicated-p doesn't work with certain buffers?
2020-05-19T09:32:56.893
# Question Title: Why set-window-dedicated-p doesn't work with certain buffers? I use emacs for latex, with pdf-tools. My layout is always a window with PDFView buffer on the right, any other buffer on the left. I always want the right window that cannot be touched by anything, so I have a command `anchor-buffer` ``` ;; custom function 'anchor-buffer' (defun anchor-buffer () "Anchor the current buffer to the current window." (interactive) (set-window-dedicated-p (selected-window) t)) ``` that doesn't allow to modify a window. Consider the following case * I have two windows (vertical split): Left window: tex source file, Right window: pdf file, pdf-view-mode (using pdf-tools) * I select the pdf buffer (on the right), and I do `M-x anchor-buffer`. According to the function above this should "glue" the buffer in the right window. At least my `anchor-buffer` function works like this in all situations I tried. * Now suppose I want to search for a reference using RefTex on the tex source (left window), and I do `C-c )`. A selection buffer opens in the right window which replaces the pdf viewer. The latter should not happen because I invoked `set-window-dedicated-p` on right window. Any idea on how to solve this? # Answer Solved. I replaced my `anchor-buffer` function with the `toggle-current-window-dedication` function shared here. Basically this `toggle-current-window-dedication`, that I report for clarity here ``` ;; A toggle switch for set-window-dedicated-p ;; see: https://stackoverflow.com/a/2903358/2720781 ;; (defun toggle-current-window-dedication () (interactive) (let* ((window (selected-window)) (dedicated (window-dedicated-p window))) (set-window-dedicated-p window (not dedicated)) (message "Window %sdedicated to %s" (if dedicated "no longer " "") (buffer-name)))) (global-set-key [pause] 'toggle-current-window-dedication) ``` is supposed to do exactly what I wanted, it worked under all conditions included the nasty case described above. Problem solved! Thanks for helping. > 0 votes --- Tags: buffers, window-splitting ---
thread-51598
https://emacs.stackexchange.com/questions/51598
Org agenda suddenly broken after installing org-mac-link
2019-07-14T09:37:37.113
# Question Title: Org agenda suddenly broken after installing org-mac-link Org agenda is suddenly broken `Symbol’s value as variable is void: org-tag-group-re`. How to fix it? --- # Diagnosis: The problematic code seems to be this: ``` ;; org-mac-link (push (expand-file-name "~/.emacs.d/lisp") load-path) (require 'org-mac-link) (add-hook 'org-mode-hook (lambda () (define-key org-mode-map (kbd "C-c g") 'org-mac-grab-link))) ``` Variables in `org-tempo` and `org-agenda` stopped functioning after getting this code to work. Anyone know why this happens? # Answer > 2 votes I have a solution that worked for me, after some trial and error. Please bear with me as this is my first time answering a question on StackExchange. I also had Org agenda break with the error message `Symbol's value as variable is void: org-tag-group-re`. For me, this occurred while trying to install org-drill. For context, I'm running Emacs 26.3 on MacOS Catalina, which was installed using homebrew. **Why it broke:** The variable `org-tag-group-re` is a regular expression that usually returns the tags (for example, :work: or :home:) associated with TODO items in agenda files. After investigation I found out that Emacs is using my *system's* version of org (9.1.9), rather than the most recent version of org (9.3.6 at time of writing). `org-tag-group-re` is defined in the most recent version of org, but is not defined in the system version of org that Emacs is using, so it has the value `nil`. **A solution:** After reading about lisp libraries and messing around with my init file a bit, I got what may be a working solution. At the beginning of my init file, I added the most recent version of org to my load path and made sure that Emacs would preferentially load newer versions of packages (at Muihlinn's suggestion). The code for that looks like this: ``` (add-to-list 'load-path "~/.emacs.d/elpa/org*") (setq load-prefer-newer t) ``` Notes: you may need to install the latest version of org if you don't have it already, and it may be located somewhere different. Also, I used the wildcard (\*) to make sure that even if I upgrade to a future version of org, I won't have to change my init file. This is related to a similar problem on stackexchange that I saw while researching the problem, but I can't find it again. If you see it and comment the link, I'll add it and give due credit. --- Tags: org-agenda, debugging ---
thread-56268
https://emacs.stackexchange.com/questions/56268
How to Visualize Transfer Rate In TRAMP Mode File Transfer
2020-03-21T01:33:15.173
# Question Title: How to Visualize Transfer Rate In TRAMP Mode File Transfer Any idea on how could be enabled a progress bar and/or speed rate metter on TRAMP mode file transfer? Trying to manage TRAMP transfer mode via `scp` instead of `ssh` to seek avoidance `base64` conversion, but due low internet speed don't know if it's stuck or just slow. # Answer > 2 votes Download and install `iftop` package, run a `M-x` `term`, then type something as: `$ iftop -i eth0 -f 'dst host 192.168.1.3'` As for: `-i` local interface `-f` filter code, as in pcap-filter man page, for destination host in the example. There will be 3 speed rates in inferior right part of the screen, meaning that for 2, 10 and 40 seconds respectively. # Answer > 1 votes This is not possible as of today. Patches welcome! --- Tags: tramp, ssh ---
thread-27461
https://emacs.stackexchange.com/questions/27461
Magit doesn't recognise git repo through ssh connection
2016-09-30T03:11:58.443
# Question Title: Magit doesn't recognise git repo through ssh connection I'm using ssh to connect to a remote server. On the server there is a git repo called `MRFLSSVM`. However, when I execute `magit-status` on: ``` /ssh:qmServer:/home/Chang/qmCodeLab/MRFLSSVM/ ``` Magit asks me to `Create repository in /ssh:qmServer:/home/Chang/qmCodeLab/MRFLSSVM/?`. Any idea how to let magit recognize that repo? (I've already installed git 2.10.0 on /usr/local/git and configured my system (CentOS) to use it by update-alternatives) -----------Edit------------------------------ ``` Error (magit): Magit requires Git >= 1.9.4, you are using 1.8.3. If this comes as a surprise to you, because you do actually have a newer version installed, then that probably means that the older version happens to appear earlier on the `$PATH'. If you always start Emacs from a shell, then that can be fixed in the shell's init file. If you start Emacs by clicking on an icon, or using some sort of application launcher, then you probably have to adjust the environment as seen by graphical interface. For X11 something like ~/.xinitrc should work. If you use Tramp to work inside remote Git repositories, then you have to make sure a suitable Git is used on the remote machines too. Error (magit): Magit requires Git >= 1.9.4, but on /ssh:qmServer: the version is 1.8.3. If multiple Git versions are installed on the host then the problem might be that TRAMP uses the wrong executable. First check the value of `magit-git-executable'. Its value is used when running git locally as well as when running it on a remote host. The default value is "git", except on Windows where an absolute path is used for performance reasons. If the value already is just "git" but TRAMP never-the-less doesn't use the correct executable, then consult the info node `(tramp)Remote programs'. ``` This problem seems to be `tramp` is not using the correct git on remote server. I've tried to change `magit-git-executable` to `usr/local/git/bin/git` which is the path both of my local and remotes installed git. But this still doesn't work. Any ideas to solve this? Thanks! # Answer > 6 votes > > Error (magit): Magit requires Git \>= 1.9.4, you are using 1.8.3. > > I've already installed git 2.10.0 on /usr/local/git The list of directories to search for executables on remote hosts is controlled by the option `tramp-remote-path`. It does begin with a "what the remote told me what I should be using" element, but in my experience that doesn't work so well. In particular it does ignore any changes to `$PATH` that you have made in your shell's configuration file, I believe. So, in your init file, put `/usr/local/git/bin` before `/usr/bin` in `tramp-remote-path`: ``` (require 'tramp) (push "/wherever/git/is/" tramp-remote-path) ``` # Answer > 0 votes If your git version is fine, the issue may be with the configuration of this git repository, for instance a syntax error in `.git/config`. In order to check for that, open a shell on the repository machine and directory, and type `git status` --- Tags: magit, tramp, ssh ---
thread-18830
https://emacs.stackexchange.com/questions/18830
Org mode export: exclude sections with todo keyword
2015-12-13T12:53:39.477
# Question Title: Org mode export: exclude sections with todo keyword I want to export an org mode document so that sections or subsections with `TODO` keywords do not appear in the exported output. How can this be achieved? The export-settings documentation does not explicitly mention anything related to this. # Answer > 9 votes There is an export option to control exporting of TODO items: > tasks: Toggle inclusion of tasks (TODO items), can be nil to remove all tasks, todo to remove DONE tasks, or a list of keywords to keep (org-export-with-tasks). Setting it to `nil` will hide tasks from your exported document. # Answer > 2 votes Or if you want to export `DONE` items but not `TODO` items, set it (`tasks`) to `done`. # Answer > 0 votes I used `tasks:nil`. For example, I use this in a sub-tree where I want to exclude tasks from export: ``` :PROPERTIES: :EXPORT_OPTIONS: tasks:nil :END: ``` --- Tags: org-mode, org-export, todo ---
thread-58667
https://emacs.stackexchange.com/questions/58667
Why TAGS file is loaded/visited automatically if it exists in project root directory?
2020-05-22T14:09:48.403
# Question Title: Why TAGS file is loaded/visited automatically if it exists in project root directory? If the root of the project has a `TAGS` file, and I load/visit a file `FOO` from this dir into a freshly started Emacs, Emacs loads/visits two files, and the buffer list shows `FOO` and `TAGS`. I also get a message `Starting a new list of tags tables`. Is this a normal behavior? Edit: this seems to happen when `projectile-mode` is enabled. Is this related? # Answer > 1 votes Projectile does do this. See `projectile-find-file-hook-function`: https://github.com/bbatsov/projectile/blob/master/projectile.el#L4760-L4773 --- Tags: ctags ---
thread-58654
https://emacs.stackexchange.com/questions/58654
Keep heading contents always visible in org-mode
2020-05-22T01:45:10.480
# Question Title: Keep heading contents always visible in org-mode How can you keep a heading's main content always visible in org-mode? Perhaps a property that can be set, so that `S-tab` never collapses it? (Not keeping the children's contents visible, unless they are also set the same way, not impacting e.g. narrowing etc.) # Answer > 2 votes The built-in `which-function-mode` normally displays the name of the function the point is currently in for languages like C and Python. But in `org-mode` it treats the current headline as the "function" name to display. Turn it on temporarily with `M-x which-function-mode` or permanently for all `org-mode` files with `(add-to-hook 'org-mode-hook #'which-function-mode)` in your `.emacs`. By default this displays the name in the `mode-line` at the bottom of the buffer. I find it gets a little crowded down there, so I add it and the buffer name to the header instead: ``` (defun header-buffer-name () (let ( (props (if (powerline-selected-window-active) '(:box "grey80" :background "grey50" :foreground "black") '(:box "grey80" ))) ) (propertize (buffer-name) 'font-lock-face props) )) (defun header-function-name () (let ( (props (if (powerline-selected-window-active) '(:box "Gold1" :background "goldenrod" :foreground "black") '(:box "Gold1" ))) (func (when which-function-mode (which-function))) ) (if func (propertize (which-function) 'font-lock-face props) "") )) (setq-default header-line-format '(:eval (list (header-buffer-name) " " (header-function-name) ))) ``` \[EDIT\] Here `(powerline-selected-window-active)` is an external function. You can find several implementations in EmacsWiki, or simply replace it with nil. --- Tags: org-mode, visibility ---
thread-58626
https://emacs.stackexchange.com/questions/58626
Merging consecutive entries that share the same headline
2020-05-20T22:17:29.280
# Question Title: Merging consecutive entries that share the same headline I've been trying to achieve the following: ``` * Riviere Contents of Riviere title * Riviere More contents of Riviere ``` turn into: ``` * Riviere Contents of Riviere title More contents of Riviere ``` I found a function that almost gets the job done. I tried adding a `heading2` variable and changing the condition to match `heading` and `heading2`: ``` (defun promote-screenings-and-readings (&optional backend) (org-map-entries (lambda () (let ((point (point)) (heading (buffer-substring-no-properties (point) (save-excursion (forward-line) (point)))) (heading2 (save-excursion (org-backward-heading-same-level 1) (forward-line)))) (when (or (string= heading heading2)) (org-map-entries (lambda () (unless (= (point) point) (org-promote))) nil 'tree) (forward-line) (delete-region point (point))))))) ``` But it still doesn't work. That's how I set `heading2`, right? If I change `string= heading "* Anything here\n"` the heading gets deleted. The reason behind this is I keep all my college slides inside an org file, and I want to avoid repetitive headlines when exporting to something other than Beamer. There are 5k lines in the document, so I think using the `:no_title:` method would be inefficient. # Answer To merge all subtrees/entries that share the same headline, you can try the following: ``` (defun merge-subtrees () (interactive) (let (headlines) (save-excursion (goto-char (point-min)) (while (re-search-forward org-complex-heading-regexp nil t) (let ((headline (match-string 4))) (if (member headline headlines) (let* ((beg (line-beginning-position)) (end (save-excursion (org-end-of-subtree))) (contents (buffer-substring (point) end))) (delete-region beg (save-excursion (org-end-of-subtree t t))) (save-excursion (when (re-search-backward (concat "^\\*.?+ " headline "\\($\\|[ \t]+:.+\\)") nil t) (org-end-of-subtree) (insert contents)))) (push headline headlines))))))) ``` Now to merge only consecutive subtrees/entries that share the same headline, try the following: ``` (defun merge-subtrees () (interactive) (save-excursion (goto-char (point-max)) (while (re-search-backward org-complex-heading-regexp nil t) (let ((headline (match-string 4))) (when (save-excursion (outline-previous-heading) (and (looking-at org-complex-heading-regexp) (string= headline (match-string 4)))) (let ((beg (org-entry-beginning-position)) (end (save-excursion (org-end-of-meta-data t) (point)))) (when (> beg (point-min)) (delete-region beg end)))))))) ``` > 0 votes # Answer The following answer does not modify the original `org-mode` buffer containing the raw data, but instead gathers the raw data into a list and then generates a new buffer containing a modified version of the original data. My personal preference is to go to the bottom of the working buffer and search backwards -- this is because point is at the beginning of a heading at each stop of the `re-...` search. \[There is a line of code that uses `nreverse` on the initial `gathered-data` because we searched from the bottom of the file to the top of the file -- the assumption is that the original raw data contained a desired order, whether that be chronological or something else.\] It is, of course, possible to search forward with a modified version of this example ... it is also possible to sort the data ..., but that is beyond the scope of this example. **TEST DATA -- ORG-MODE BUFFER**: ``` * Baz is the best. Testing ten eleven twelve. * Riviere had a cup of tea. Contents of Riviere title. * Foo is having toast. Testing one two three. * Bar had a baby. Testing seven eight nine. * Riviere had a cup of tea. More contents of Riviere. * Baz is the best. Testing thirteen fourteen fifteen. * Foo is having toast. Testing four five six. ``` **EXAMPLE CODE**: ``` (save-excursion (unless (eq major-mode 'org-mode) (error "This example only works with an 'org-mode buffer.")) (goto-char (point-max)) (let ((kill-ring nil) (kill-ring-yank-pointer nil) (interprogram-cut-function nil) (interprogram-paste-function nil) gathered-result end-result) (while (re-search-backward org-complex-heading-regexp nil t) (let ((entire-heading (match-string 0)) subtree) (org-copy-subtree) (setq subtree (car kill-ring)) (push (list (cons entire-heading subtree)) gathered-result))) (setq gathered-result (nreverse gathered-result)) (mapc (lambda (x) (if (= 0 (length end-result)) (push x end-result) (let (test) (setq end-result (mapcar (lambda (y) (if (equal (car (car x)) (car (car y))) (progn (setq test t) (append x y)) y)) end-result)) (when (null test) (push x end-result))))) gathered-result) (let ((buffer (get-buffer-create "*OUTPUT*"))) (with-current-buffer buffer (unless (eq major-mode 'org-mode) (org-mode)) (let ((buffer-read-only nil)) (erase-buffer) (mapc (lambda (z) (if (= 1 (length z)) (let ((string (replace-regexp-in-string "\n+$" "" (cdr (car z))))) (insert string "\n\n")) (let ((string (replace-regexp-in-string "\n+$" "" (car (car z))))) (insert string "\n")) (mapc (lambda (w) (let ((string (replace-regexp-in-string (concat "^" (car w) "\n") "" (cdr w)))) (setq string (replace-regexp-in-string "\n+$" "" string)) (insert string "\n"))) z) (insert "\n"))) end-result))) (unless (get-buffer-window buffer) (display-buffer buffer t))) end-result)) ``` **`*OUTPUT*` BUFFER -- USING EXAMPLE CODE**: ``` * Bar had a baby. Testing seven eight nine. * Riviere had a cup of tea. Contents of Riviere title. More contents of Riviere. * Baz is the best. Testing ten eleven twelve. Testing thirteen fourteen fifteen. * Foo is having toast. Testing one two three. Testing four five six. ``` > 0 votes --- Tags: org-mode, org-export ---
thread-58636
https://emacs.stackexchange.com/questions/58636
How to find hook running after last line of code?
2020-05-21T09:11:03.747
# Question Title: How to find hook running after last line of code? I have a repeating habit such as: ``` ** TODO some habit SCHEDULED: <2020-05-22 Fri 08:00 .+1d> :PROPERTIES: :STYLE: habit :CREATED: [2020-05-08 Fri] :LAST_REPEAT: [2020-05-21 Thu 10:07] :END: :LOGBOOK: - State "DONE" from "TODO" [2020-05-21 Thu 10:07] CLOCK: [2020-05-21 Thu 10:04]--[2020-05-21 Thu 10:06] => 0:02 :END: ``` I coded this shortcut, where I commented out my function to clock in and out: ``` (defun my-org-clock-and-mark-done () (interactive) (message "start") (org-back-to-heading) ;(my-org-clock-in-and-out nil) (org-shiftright) (message "end") ) ``` The result in the `*Messages` buffer is: ``` start Entry repeats: SCHEDULED: <2020-05-22 Fri 08:00 .+1d> end Note stored Entry repeats: SCHEDULED: <2020-05-22 Fri 08:00 .+1d> ``` I suspect that Org mode has a hook that runs after my last line of code, in this case when a repeating cookie is changed, and shows that change message twice. How can I find and disable that hook? **Update**: Following the answer by phils, I added a debugger with `(setq debug-on-message "Note stored")` so it catches only the second occurrence. It shows these functions, neither of which I could find in the list of hooks, which I found thanks to Muihlinn's comment. The list of calls is below and has two recursive edits, which I find odd: ``` org-store-log-note() org-add-log-note() recursive-edit() debug(error ...) message("%s" #("Entry repeats: SCHEDULED: ...")) org-store-log-note() org-add-log-note() recursive-edit() debug(error #("Entry repeats: SCHEDULED: ...")) message("%s" #("Entry repeats: SCHEDULED: ...")) org-auto-repeat-maybe("DONE") org-todo(right) funcall-interactively(org-todo right) call-interactively(org-todo) org-shiftright() ``` # Answer For this particular case... In that call to `org-auto-repeat-maybe` we see this: ``` (when org-log-repeat (if (or (memq 'org-add-log-note (default-value 'post-command-hook)) (memq 'org-add-log-note post-command-hook)) ;; We are already setup for some record. (when (eq org-log-repeat 'note) ;; Make sure we take a note, not only a time stamp. (setq org-log-note-how 'note)) ;; Set up for taking a record. (org-add-log-setup 'state (or done-word (car org-done-keywords)) org-last-state org-log-repeat))) ``` Where `org-log-repeat` is a user option (see which). `org-add-log-setup` does this: ``` (add-hook 'post-command-hook 'org-add-log-note 'append)) ``` And `org-add-log-note` removes itself from the hook when it runs: ``` (defun org-add-log-note (&optional _purpose) "Pop up a window for taking a note, and add this note later." (remove-hook 'post-command-hook 'org-add-log-note) ...) ``` So if `org-log-repeat` is non-nil, `post-command-hook` will be running `org-add-log-note`. > 1 votes # Answer `M-:` `(setq debug-on-message "Entry repeats: SCHEDULED")` The stack traces should show you what is causing each instance of that message. See `C-h``i``g` `(elisp)Using Debugger` for help on the debugger. When you're done, `M-:` `(setq debug-on-message nil)` > 2 votes --- Tags: org-mode, hooks, help ---
thread-233
https://emacs.stackexchange.com/questions/233
How to proceed on package.el signature check failure
2014-09-25T10:05:04.587
# Question Title: How to proceed on package.el signature check failure I just tried to install `ascii-art-to-unicode` from the gnu repository (http://elpa.gnu.org/) via `list-packages`. I get the following error: ``` package--check-signature: Failed to verify signature ascii-art-to-unicode-1.9.el.sig: ("No public key for 474F05837FBDEF9B created at 2014-09-24T16:20:01+0200 using DSA") ``` I'm using cask/pallet to manage my packages; is there some setup I missed? Some recent changes to elpa? I'm using an emacs 24.4 pre-release. # Answer > 58 votes 1. set `package-check-signature` to `nil`, e.g. `M-: (setq package-check-signature nil) RET` 2. download the package `gnu-elpa-keyring-update` and run the function with the same name, e.g. `M-x package-install RET gnu-elpa-keyring-update RET`. 3. reset `package-check-signature` to the default value `allow-unsigned`, e.g. `M-: (setq package-check-signature "allow-unsigned") RET` This worked for me. As stated in the package the following holds: If your keys are already too old, causing signature verification errors when installing packages, then in order to install this package you can do the following: * Fetch the new key manually, e.g. with something like: ``` gpg --homedir ~/.emacs.d/elpa/gnupg --receive-keys 066DAFCB81E42C40 ``` * Modify the expiration date of the old key, e.g. with something like: ``` gpg --homedir ~/.emacs.d/elpa/gnupg \ --quick-set-expire 474F05837FBDEF9B 1y ``` * temporarily disable signature verification (see variable \`package-check-signature'). # Answer > 17 votes FWIW - I had this issue with the signature org-20140407.tar.sig. Like Sigma's **package-check-signature** is/was **allow-unsigned**. I changed the **package-check-signature** value to **nil** and the problem was resolved. # Answer > 15 votes If you try to install the package `gnu-elpa-keyring-update` (which seems to have the purpose of updating the keys used by the package manager), you will see in its description that you can do: `gpg --homedir ~/.emacs.d/elpa/gnupg --receive-keys 066DAFCB81E42C40` on the commandline to get new keys manually. To make sure you are asking for the correct key (`066DAFCB81E42C40` in the example above), check the error message that emacs gives you when you try to install any package. # Answer > 5 votes It appears that the key used to sign this package (474F05837FBDEF9B) is indeed not published (therefore cannot be signed, therefore cannot be trusted). But it would seem that package.el is supposed to fail gracefully (for now) in such cases: ``` ;; If package-check-signature is allow-unsigned, don't ;; signal error when we can't verify signature because of ;; missing public key. Other errors are still treated as ;; fatal (bug#17625). (unless (and (eq package-check-signature 'allow-unsigned) (eq (epg-signature-status sig) 'no-pubkey)) (setq had-fatal-error t)) ``` So I'm wondering if for some reason your value of `package-check-signature` is different than its default value of `allow-unsigned` ? # Answer > 5 votes The answers here are a bit dated. This issue seems to have been fixed as of emacs 26.3. # Answer > 3 votes Alternatively, you could upgrade to a newer emacs, e.g. on Ubuntu: ``` sudo add-apt-repository ppa:ubuntu-elisp/ppa sudo apt-get update sudo apt-get install emacs-snapshot ``` This way you avoid doing all this: https://elpa.gnu.org/packages/gnu-elpa-keyring-update.html # Answer > 2 votes get the puglic key with: ``` gpg2 --homedir ~/.emacs.d/elpa/gnupg --receive-keys 066DAFCB81E42C40 ``` **Attention:** your version could be a different key ! # Answer > 1 votes Setting `package-check-signature` to `nil` instead of the default `allow-unsigned` fixed this for me. Fedora 29, GNU Emacs 26.2 (build 1, x86\_64-redhat-linux-gnu, GTK+ Version 3.24.8) of 2019-04-30 # Answer > 0 votes I get: ``` % gpg --homedir ~/.emacs.d/elpa/gnupg --receive-keys 066DAFCB81E42C40 gpg: key 066DAFCB81E42C40: new key but contains no user ID - skipped gpg: Total number processed: 1 gpg: w/o user IDs: 1 ``` --- Tags: package, package-repositories ---
thread-58666
https://emacs.stackexchange.com/questions/58666
Python over-indentation warning E127
2020-05-22T13:49:40.550
# Question Title: Python over-indentation warning E127 `elpy` (or rather `flake8` I suppose) complains about a line over-indented on the line 52 (see below image) I tried to change this line's begin but no change. I always use TAB to have the correct indentation (and this position is where TAB leads). Here's my `elpy` config: ``` Emacs.............: 26.3 Elpy..............: 1.33.0 Virtualenv........: None Interactive Python: python3 3.8.3 (/usr/bin/python3) RPC virtualenv....: rpc-venv (/home/david/.emacs.d/elpy/rpc-venv) Python...........: /usr/bin/python3 3.8.3 (/usr/bin/python3) Jedi.............: 0.17.0 Rope.............: 0.17.0 Autopep8.........: 1.5.2 Yapf.............: 0.30.0 Black............: 19.10b0 Syntax checker....: flake8 (/home/david/.local/bin/flake8) ``` # Answer > 3 votes You should create in your home folder a `.flake8rc` file, and add some content to ignore that error - documented here and below is a small template: ``` [flake8] # it's not a bug that we aren't using all of hacking ignore = # F812: list comprehension redefines ... F812, # H101: Use TODO(NAME) H101, # H202: assertRaises Exception too broad H202, # E127: continuation line over-indented for visual indent E127 ``` The full error code listing is here --- Tags: indentation, elpy ---
thread-58605
https://emacs.stackexchange.com/questions/58605
How to replace a list within a list?
2020-05-20T02:48:38.000
# Question Title: How to replace a list within a list? What would be the an efficient/concise way to replace a sub-list with another list? Example function call: ``` (replace-list-list-with-list '("A" "B" "C" "D") '("B" "C") '("NEW" "TEXT")) ``` Would result in: ``` '("A" "NEW" "TEXT" "D") ``` # Answer Here is a nondestructive soultion which is easy to code/understand, `my-sublist-find` searches for a sublist and `my-sublist-replace` replace a sublist. ``` (defun my-sublist-find (list sublist) "Find the first occurrence of SUBLIST in LIST. Return the indexes of the matching item or nil if not found." (when (and list sublist (>= (length list) (length sublist))) (cl-loop for start from 0 to (- (length list) (length sublist)) for end = (+ start (length sublist)) when (equal (cl-subseq list start end) sublist) return (list start end)))) (defun my-sublist-replace (list1 start end list2) "Replace the elements of LIST1 from START to END with the elements of LIST2." (nconc (seq-subseq list1 0 start) (copy-sequence list2) (seq-subseq list1 end))) (let ((list (list "A" "B" "C" "D")) (old (list "B" "C")) (new (list "NEW" "TEXT"))) (pcase (my-sublist-find list old) (`(,start ,end) (my-sublist-replace list start end new)))) ;; => ("A" "NEW" "TEXT" "D") ``` > 1 votes # Answer *(Edit: This answer is for the original question of replacing a list **item**, rather than for the modified question of replacing a sub-list. Extending this approach to recognise sub-lists is left as an exercise for the reader.)* Here's a destructive approach (but don't use it unless you *know* that you want a destructive approach -- definitely don't do so with *quoted* lists, like there are in the example in the question). ``` (defun replace-list-item-with-list (list item replacement) "Substitute a REPLACEMENT list for ITEM in LIST, by altering the lists." (catch 'substitution (let ((current list) parent) (while current (if (not (equal (car current) item)) (setq parent current current (cdr current)) (if parent (setcdr parent (nconc replacement (cdr current))) (setq list (nconc replacement (cdr current)))) (throw 'substitution t))))) list) ``` ``` (replace-list-item-with-list (list "A" "B" "C") "A" (list "NEW" "TEXT")) => ("NEW" "TEXT" "B" "C") (replace-list-item-with-list (list "A" "B" "C") "B" (list "NEW" "TEXT")) => ("A" "NEW" "TEXT" "C") (replace-list-item-with-list (list "A" "B" "C") "C" (list "NEW" "TEXT")) => ("A" "B" "NEW" "TEXT") (replace-list-item-with-list (list "A" "B" "C") "D" (list "NEW" "TEXT")) => ("A" "B" "C") ``` Assuming LIST is actually a variable, you would (as usual) need to *assign* the return value back to the list variable to handle the case where the *first* item was replaced. ``` (setq list (replace-list-item-with-list list item replacement)) ``` --- FWIW I note that the `dash` package has: ``` (-splice-list (lambda (x) (equal x "B")) (list "NEW" "TEXT") (list "A" "B" "C")) ``` > 0 votes # Answer This is a generic function that replaces a list within a list N times, taking an optional comparitor argument. ``` (defun my-list-replace-list-in-list (lst src dst &rest keyword-args) "Replace the list SRC with DST in LST, returning a new list with the replacement(s) made. Optional keyword arguments are: :test TEST -- Defines how list items are compared, defaulting to `eq'. :count COUNT -- The number of replacements to make, defaulting to nil (replace all)." (let ((result (list)) ;; Build new list. (current-count 0) (lst-iter lst) ;; Keyword arguments. (comparitor #'eq) (count nil)) ;; Extract keyword args. (let ((kw-iter keyword-args)) (while kw-iter (let ((kw-key (pop kw-iter)) (kw-val (pop kw-iter))) (cond ((eq kw-key :test) (setq comparitor kw-val)) ((eq kw-key :count) (setq count kw-val)) (t (error "Unknown keyword argument %S" kw-key)))))) (while lst-iter (unless (let ((found t) ;; Assume found until the match differs. (src-iter src) (lst-iter-test lst-iter)) (while src-iter (if (and lst-iter-test (funcall comparitor (car lst-iter-test) (car src-iter))) (progn (setq src-iter (cdr src-iter)) (setq lst-iter-test (cdr lst-iter-test))) ;; Exit. (setq src-iter nil) (setq found nil))) (when found (let ((dst-iter dst)) (while dst-iter (push (car dst-iter) result) (setq dst-iter (cdr dst-iter)))) (setq current-count (1+ current-count)) ;; Always fail when `count' is nil. (if (eq current-count count) ;; All replacements made, finish and exit. (progn (while lst-iter-test (push (car lst-iter-test) result) (setq lst-iter-test (cdr lst-iter-test))) ;; Break the main loop. (setq lst-iter nil)) ;; Keep replacing. (setq lst-iter lst-iter-test)) t)) ;; No match, build list one by one. (push (car lst-iter) result) (setq lst-iter (cdr lst-iter)))) (nreverse result))) ``` Example use: ``` (let ((list (list "A" "B" "C" "D" "A" "B" "C" "D")) (src (list "C" "D")) (dst (list "NEW" "TEXT"))) (message "Result %S" (my-list-replace-list-in-list list src dst :test #'string-equal))) ``` Outputs: ``` Result ("A" "B" "NEW" "TEXT" "A" "B" "NEW" "TEXT") ``` > 0 votes --- Tags: list ---
thread-58685
https://emacs.stackexchange.com/questions/58685
How to go up one level in helm find files
2020-05-23T23:12:42.813
# Question Title: How to go up one level in helm find files With `C-x C-f` Helm tells me I can go up one level with `C-|` or possibly `C-I`. However, when I try either, I get the following behavior instead: `C-I` Selects the highlighted file. It does not go up one level. `C-|` So I guess it was supposed to be `C-I` but that isn't doing what is advertised. How can I go up one level? # Answer It's actually "L" in lower case. You should set the default font to a monospace one, such as DejaVu Sans Mono, Hack, Noto Sans Mono, Source Code Pro, etc. They were designed to make code clearer to avoid confusion like this. > 1 votes --- Tags: helm ---
thread-58691
https://emacs.stackexchange.com/questions/58691
Sort Chinese Characters in Emacs
2020-05-24T11:14:53.420
# Question Title: Sort Chinese Characters in Emacs Is there a ready-made function that sorts Chinese characters (by pinyin or stroke number) in Emacs in an `org-table` or line by line in regular text? If not, how should one go about writing such function? (I just need a general direction as guidance, if it is too cumbersome to provide the full functioning code over here.) # Answer My code is beyond stackoverflow characters limit. So see https://gist.github.com/redguardtoo/78a68fb6ac914bd89b6f04314819d24b for full code. Here is a short version, ``` (defconst my-chinese-pinyin-order-hash #s(hash-table size 30 test equal data ( "一" 375 ;; 375 corresponds to pinyin of one hanzi "乙" 381 "二" 81 "十" 293 ;; ... skipped ... ))) (defun my-chinese-compare (w1 w2) (let ((i 0) (max-len (min (length w1) (length w2))) v1 v2 break rlt) (while (and (not break) (< i max-len)) (setq v1 (gethash (substring-no-properties w1 i (1+ i)) my-chinese-pinyin-order-hash 9999)) (setq v2 (gethash (substring-no-properties w2 i (1+ i)) my-chinese-pinyin-order-hash 9999)) (unless (eq v1 v2) (setq rlt (< v1 v2)) (setq break t)) (setq i (1+ i))) (cond ((eq i max-len) (eq max-len (length w1))) (t rlt)))) (defun my-chinese-sort-word-list (word-list) (when word-list (sort word-list #'my-chinese-compare))) (message "test: %s" (my-chinese-sort-word-list '("小明" "小红" "张三" "李四" "王二" "大李" "古力娜扎" "迪丽热巴"))) ``` I've contributed patches to he most popular Chinese IME pyim (https://github.com/tumashu/pyim) recently. So I'm familiar with Hanzi (Chinese character) processing. For example, I know https://github.com/tumashu/pyim-basedict provides a dictionary contains all the Chinese characters which are already sorted by pinyin. My code sort the charcter by its number. The number is roughly the line number of the character's pinyin in pyim-basedict's dictionary file. In my code, I only sorted the word by 2,500 mostly used Chinese characters which is PRC national standard (https://www.zdic.net/zd/zb/cc1/). > 3 votes --- Tags: fonts, org-table, sorting ---
thread-58700
https://emacs.stackexchange.com/questions/58700
Unquoting a variable name (to implement variable pointers)
2020-05-24T15:32:54.320
# Question Title: Unquoting a variable name (to implement variable pointers) I know that if I have a variable with a function name, I can call it using `funcall`, like this ``` (setq func-ref 'my-func) (funcall func-ref) ``` I am wondering if there's a similar functionality for variables (defined with `defvar`), so that I can set `var-ref` like this ``` (setq var-ref 'my-var) ``` and use it to get the value of `my-var` and/or update it. EDIT: I want to use this functionality in a function which takes as argument a reference to a variable that will be changed in the function. # Answer You can use `symbol-value` to look up dynamically bound variables. The easiest way to ensure that is by using `defvar`/`defconst`/`defcustom` for such variables, that way they'll always be dynamically bound, even with lexical-binding enabled. Plain `setq` will not do as soon as lexical binding is used and is discouraged for defining variables for that reason. To change the value, use `set` instead of `setq` and give it a symbol. > 2 votes # Answer You can `eval` to recover the value of a variable symbol. To modify it you can use `setf`: ``` (setq x 1) (setq xref 'x) (eval xref) ;; Returns 1 (setf (symbol-value xref) 2) (eval xref) ;; Returns 2 ``` The value of `x` is now 2 `setf` is the generalized version of `setq` that lets you place values in arbitrary "places" within an object. For example you can change elements within a list: ``` (setq x '(1)) (car x) ;; Returns 1 (setf (car x) 2) (car x) ;; Returns 2 ``` > 1 votes --- Tags: quote, symbols ---
thread-36138
https://emacs.stackexchange.com/questions/36138
Setting python version for live-py and python-excecute-file (SPC m c c) in spacemacs
2017-10-13T10:59:11.390
# Question Title: Setting python version for live-py and python-excecute-file (SPC m c c) in spacemacs Im new to Emacs, i hope i didn't miss anything simple. My configuration is: * OS - OSX sierra 10.12.6. * Emacs - 25.3.1 (Emacs-emacs-plus from homebrew) * python - trying to set 2.7.14. I want to make myself a decent developing environment for python, there is one problem i'm not sure how to solve. I want emacs (and all layers) to use python from this path: `/usr/local/bin/python2` I seted in .spacemacs file at `(defun dotspacemacs/user-config ()`: ``` ;; python: (setq python-shell-interpreter "/usr/local/bin/python2") (setq py-python-command "/usr/local/bin/python2") (setq python-shell-completion-native-enable nil) ``` Now when i execute `run-python`: it works well and start with desired version. But when i'm editing python file in `python-mode` and trying to launch either `live-py` or `python-execute-file` it opens up in system default python version. i.e.: different path. What i am doing wrong? Thank # Answer `SPC h d f run-python RET` and `SPC h d f live-py-mode` will tell you that those two commands are provided by different files (`python.el` and `live-py-mode.el` respectively). This will take you to the source code for `live-py-mode`: `SPC SPC find-library RET live-py-mode RET`. If you look at the variables near the top of that file, you'll see that setting `live-py-mode` like this is what you need: `(setq live-py-version "python2")` > 1 votes # Answer I also had the same problem. Then I figured it out that I can use *`C-u SPC m c c`*, and then, for example, using *python3 python\_script.py* to execute python\_script.py with specified *python3* rather than the system default *python*. However, I still don't know how to set the default version as python3. > 0 votes --- Tags: spacemacs, python ---
thread-58696
https://emacs.stackexchange.com/questions/58696
Change C-z from Minimise to Toggle Evil Mode
2020-05-24T14:41:07.690
# Question Title: Change C-z from Minimise to Toggle Evil Mode I am a fairly new emacs user and would appreciate any help you could offer. I have recently installed the evil mode package onto my emacs. The package itself works perfectly, however, the default toggle binding `C-z` is not working as expected. When outside of evil mode it minimises the current frame. If I invoke evil mode through `M-x RET evil-mode` then input `C-z`, it will toggle back as expected. I have attempted a fix by adding the following to my init.el file in an attempt to overwrite the existing key binding: ``` (setq evil-toggle-key "C-z") (require 'evil) ``` I have also tried ``` (global-unset-key (kbd "C-z")) ``` alone and in conjunction with the previous but this seems to completely unbind the key chord. Does anyone have a solution which changes `C-z` from 'minimise frame' to 'toggle evil mode'? # Answer > 0 votes A combination of those works - just unbind the global key first. ``` (global-unset-key (kbd "C-z")) (require 'evil) (setq evil-toggle-key "C-z") (evil-mode 1) ``` Until `evil-mode` is activated, the key binding does not work. I assume you have `evil-mode` started by default, so the above should suit your workflow. --- Tags: key-bindings, evil ---
thread-58709
https://emacs.stackexchange.com/questions/58709
automatic prettier for python code? (as in javascript)
2020-05-25T07:55:05.397
# Question Title: automatic prettier for python code? (as in javascript) https://github.com/prettier/prettier-emacs does formatting for javascript wonder if there's an equivalent for python code? # Answer > 2 votes Since Python has a lot of PEP regulations, one can use `Black` as their code formatter. This is found in the `Elpy` package or can be found on github. --- Tags: python, javascript ---
thread-10392
https://emacs.stackexchange.com/questions/10392
Export an org-mode file as a PDF via command line?
2015-03-30T02:54:26.137
# Question Title: Export an org-mode file as a PDF via command line? What command-line arguments do I use to get Emacs to export an org-mode file to a Beamer PDF? (I want to create a `Makefile` that produces a PDF when the user runs `make`.) I tried following this answer but couldn't get it to work: ``` $ emacs --batch foo.org -f org-beamer-export-to-pdf Symbol's function definition is void: org-beamer-export-to-pdf $ emacs --batch -l ox-beamer foo.org -f org-beamer-export-to-pdf Cannot open load file: ox-beamer ``` The above error comes from the fact that the org-mode files are in a custom location and my `~/.emacs.d/init.el` is not loaded (`--batch` implies `-q` a.k.a. `--no-init-file`). If I tell Emacs to load my init file it will work: ``` $ emacs --batch -l ~/.emacs.d/init.el foo.org -f org-beamer-export-to-pdf ``` However, this doesn't work for other users that use `~/.emacs` or `~/.emacs.el` instead of `~/.emacs.d/init.el`. I tried telling Emacs to load `user-init-file` but it didn't work: ``` $ emacs --batch --eval '(load user-init-file)' foo.org -f org-beamer-export-to-pdf Wrong type argument: stringp, nil ``` Assuming all users can successfully press `C-x C-e l P` to export a Beamer PDF when using Emacs interactively, what non-interactive command will produce a PDF? # Answer The following worked for me: ``` emacs \ -u "$(id -un)" \ --batch \ --eval '(load user-init-file)' \ foo.org \ -f org-beamer-export-to-pdf ``` Thanks go to @mutbuerger for the hint to pass `-u <username>` to get `user-init-file` defined. > 11 votes # Answer I'm using self-compiled emacs 27.0.9x on Linux and macOS. To generate my presentations, I use org-mode. ``` emacs -Q \ --batch "(require 'ox-beamer)" \ <input>.org -f org-beamer-export-to-pdf ``` works for me. > 5 votes --- Tags: org-mode, init-file, org-export, beamer, batch-mode ---
thread-58669
https://emacs.stackexchange.com/questions/58669
outshine mode changes outline-regexp from markdown's
2020-05-22T15:46:07.157
# Question Title: outshine mode changes outline-regexp from markdown's patient StackExchange, I am learning org-mode and liking its header-folding capacities, which seem much easier than outline-minor-mode. Most of my work is done in markdown mode, though, so I am trying (and failing) to set up **outshine** (from MELPA) in order to get org-like folding and restructuring. Here is the weird (to me) behavior: with *no change* to my `.emacs` (other than MELPA's adding to `package-selected-packages`), it seems that when I load a markdown file, I can get the tab-folding behavior. This is weird since `C-h m` does not show outshine mode (but it does show outline-minor-mode, which my `.emacs` loads with hooks to text-mode etc). But I don't get any restructuring commands - when I hit alt-down, for example, I get `<M-down> is undefined`. But if I manually load outshine in the markdown buffer, or load it with hooks in `.emacs`, then none of the folding works - and it seems that's because `outline-regexp` has suddenly changed to an asterisk-based one rather than a #-based one. So my main questions: * How do I get outshine to leave markdown's `outline-regexp` alone? * Should I *replace* outline-minor-mode hooks in my `.emacs` with hooks to outshine, or add outshine hooks in addition to the outline-minor-mode ones? * Outshine is supposed to also be able to do restructuring with like and such, right? Thanks in advance, as always, for your time & attention. # Answer Digging further, I feel stupid(er than usual). Removing `outshine-mode` completely, I *still* get org-like folding behavior in `markdown-mode`, and this is because org-like folding is *already* in markdown mode! (See under "Usage".) As for the restructuring commands (moving one header above another and so on), these are just done by `C-<down>` *etc.* instead of `M-<down>`. > 1 votes --- Tags: org-mode, code-folding, outline-mode, outline ---
thread-58632
https://emacs.stackexchange.com/questions/58632
How to get diffstat in magit revision buffer?
2020-05-21T05:52:26.823
# Question Title: How to get diffstat in magit revision buffer? In MacOS Mojave, I am using magit version 20190319.1911, emacs v26.1, git v2.20.1 (Apple Git-117). How do I get a diffstat in a magit revision buffer? I remember seeing such a diffstat in this buffer, but can't get it now. When I type j in a revision buffer, the response is "no diffstat in this buffer". I can get a diffstat in the log buffer, but I would prefer it in the revision buffer that is automatically updated as I move through commits in the log buffer. # Answer Type `D` to show a popup buffer with the diff arguments used in the current buffer. Change the arguments and then type `g` to refresh the buffer using the selected arguments. Note that you can also set with `s` or save (*w*rite) with `w` the arguments for future use. > 2 votes --- Tags: magit ---
thread-58031
https://emacs.stackexchange.com/questions/58031
Get magit views in to bookmarks plus
2020-04-24T13:55:06.447
# Question Title: Get magit views in to bookmarks plus After doing some changes in a git "feature branch", I use "magit diff" to review/cleanup before pushing code to GitHub. My question is a) How can I get this ^ magit buffer in to my bookmarks+ (`C-x r l`) bookmarks # Answer > 2 votes Bookmarks to Magit buffers are implemented so it works the same way as for any other type of bookmark: type `C-x r m` while in the buffer you want to bookmark. --- Tags: magit, bookmarks ---
thread-58657
https://emacs.stackexchange.com/questions/58657
Idiomatic conversion of non-nil to explicit t
2020-05-22T03:17:07.220
# Question Title: Idiomatic conversion of non-nil to explicit t Is there an idiomatic/commonly used/established convention to convert non-`nil` values to `t` that other Elisp programmers are likely to recognize? Sometimes I have a non-`nil` value, say from calling `member`, that I want to return as either `t` or `nil` (so that I don't leak implementation details (Cf. Hyrum's Law)). The Emacs Lisp Coding Conventions, for example, say nothing about this that I can see. The closest I've found is the Elisp manual's section on `nil` and `t`, which says "When you need to choose a value that represents *true*, and there is no other basis for choosing, use `t`." Ways I've come up with: ``` (and val t) ``` ``` (if val t nil) ``` ``` (not (not val)) ``` Does one of these have a benefit over the other? Is one "more idiomatic"? # Answer The better option is: ``` (not (not X)) ``` Some of the advantages are in the ability of the byte-compiler to optimize it away. Also for me it's easy to visually see that it's a "virtual no-op" yet at the same time it makes it clear that it was introduced on purpose. > 2 votes # Answer ``` (and val t) ``` is the cleanest and clearest. ``` (if val t nil) ``` is also clear but is slightly more verbose and less clean. There may be efficiency advantages to using ``` (not (not val)) ``` as Stefan mentions. However, efficiency gains are likely minimal in most cases since negation is a cheap operation. While double negation is clearly intentional, the reason why the programmer would include it is less clear. For example, it could have originally been a single negation and the second one could have been added during debugging and never been removed. There are other possibilities as well. > 1 votes --- Tags: coding-conventions, elisp-conventions ---
thread-58710
https://emacs.stackexchange.com/questions/58710
How to raise an error when unrecogized keyword arguments are passed to a function?
2020-05-25T09:15:56.733
# Question Title: How to raise an error when unrecogized keyword arguments are passed to a function? With a function that uses keyword arguments using this style of function definition: ``` (defun some-name (&rest kwargs) (plist-get kwargs 'example)) ``` Is there a convenient way to ensure only supported keyword-arguments as passed in? So a typo in a keyword argument doesn't pass by unnoticed. # Answer > 3 votes `cl-defun` handles this usecase: ``` (require 'cl-lib) (cl-defun test (&key foo bar) (list foo bar)) (test :foo 1 :bar 2) ; (1 2) (test :foo 1 :bar 2 :baz 3) ; Error: "Keyword argument :baz not one of (:foo :bar)" ``` In case you want the opposite behavior, pass `&allow-other-keys` after the key list. # Answer > 0 votes This can be done by parsing the keyword arguments directly. ``` ;; Function that takes two optional keyword arguments: `example-a', `example-b'. (defun some-name (&rest kwargs) ;; Two example keywords. (let ((example-a-as-var nil) (example-b-as-var nil)) ;; Extract keyword args. (let ((kw-iter keyword-args)) (while kw-iter (let ((kw-key (pop kw-iter)) (kw-val (pop kw-iter))) (cond ((eq kw-key :example-a) (setq example-a-as-var kw-val)) ((eq kw-key :example-b) (setq example-b-as-var kw-val)) (t (error "Unknown keyword argument %S" kw-key)))))) ;; End argument extraction/validation. ;; function body. )) ``` --- Tags: error-handling, arguments, keywords ---
thread-58715
https://emacs.stackexchange.com/questions/58715
How to keep keyboard focus on terminal after compiling tex?
2020-05-25T13:54:39.710
# Question Title: How to keep keyboard focus on terminal after compiling tex? My operation system is `macOS Catalina`. I am using `iTerm2` in order to interact with `emacs` and my default pdf viewer is `PDF Pro Reader Light`. When a `pdf` file is updated, `PDF Pro Reader Light` automatically reloads the document. --- I am using following keybinding to compile the latex files. > `C-c C-a` (TeX-command-run-all) will do the job in AUCTeX 11.89. After compilation is completed the keyboard focus is switch into the default pdf viewer and also the pdf view pops up in front of my terminal. **\[Q\]** Is there any way to keep the focus on the terminal after compiling the `tex` and prevent pdf viewer to pop-up? # Answer I have add following to my `.emacs` file by following this answer @lucky1928: > 1. Change `(setq TeX-PDF-mode nil)` to `(setq TeX-PDF-mode t)` will get pdf output. > 2. Add below configuration to remove the compile prompt: > `(setq TeX-command-force "LaTeX") (setq TeX-clean-confirm t)` When I do `C-c C-c` compiles the latex file and focus remains on the terminal. 1. Set the `PATH` variable in `.profile` as: `export PATH=$PATH:/Library/TeX/texbin` 2. Afterwards, I added following to force latex to compiled. ``` (setq TeX-PDF-mode t) (setq TeX-command-force "LaTeX") (setq TeX-clean-confirm t) ``` > 0 votes --- Tags: focus, tex ---
thread-58676
https://emacs.stackexchange.com/questions/58676
Can I show the time spent in the currently active task in my orgmode clocktable?
2020-05-23T08:18:08.493
# Question Title: Can I show the time spent in the currently active task in my orgmode clocktable? When I press `R` in my orgmode agenda to view the clocktable (or `v R` for clockReport), I get a list of clock times for **finished** tasks. Is it possible to also show the time so far spent on the **currently active** task (i.e., the time shown in the modeline), and include it in the total work time today? If so, how can I do that? Currently, if I want to see how many hours I have worked so far today, I have to clock out of and into my current task and then refresh the clocktable. # Answer > 1 votes You shoud set `org-clock-report-include-clocking-task` to non-nil for that. It's a `defcustom` so just using `setq` might not work. It didn't for me. --- Tags: org-mode, org-agenda, org-clock-table ---
thread-58731
https://emacs.stackexchange.com/questions/58731
Why `(require 'my-package)' is not evaluated from within a `defun' form?
2020-05-26T12:39:36.887
# Question Title: Why `(require 'my-package)' is not evaluated from within a `defun' form? I have an `init.el` file with the following line: `(require 'my-1)` The `my-1` package is on the load path. The `my-1` defines this function: ``` (defun my-f () "Hello." (interactive) (when (featurep 'my-2) (require 'my-2) ... some code here ...) ``` 'my-2' is also on the load path. Now the problem: calling `my-f` works (i.e. Emacs evaluates the `my-1` package), but the feature `my-2` is not loaded. If I manually evaluated `(require 'my-2)` \- everything works (this also proves that `my-2` package is on the load path). How do I `require` `my-2` package from within the `defun` so it gets evaluated? # Answer `featurep` is true when the specified feature has *already* been provided, and so this code doesn't make sense: ``` (when (featurep 'my-2) (require 'my-2) ...) ``` That `require` and `...` can only be evaluated if `my-2` had *previously* been loaded by some other means. So the `require` either (a) isn't called, or (b) is called redundantly and does nothing. You most likely want either: ``` (when (require 'my-2 nil t) ...) ``` Or: ``` (require 'my-2 nil t) (when (featurep 'my-2) ...) ``` You might prefer the latter case if `my-2` was used pervasively throughout the library and was *expected* to be present -- in which case the `require` might be at the beginning of the library, and individual functions would then only need the `featurep` check. n.b. I've assumed you don't want `require` to signal an error if it can't load `my-2`, as it seems like an optional dependency for your code in general. Use `C-h``f` to see details of `require` or `featurep`, and see `C-h``i``g` `(elisp)Loading` for more information. > 0 votes --- Tags: require ---
thread-58707
https://emacs.stackexchange.com/questions/58707
Spacemacs crashing on start with Ubuntu 20.04
2020-05-25T02:05:38.877
# Question Title: Spacemacs crashing on start with Ubuntu 20.04 I'm having a problem where every time I open Spacemacs it immediately crashes on Ubuntu 20.04. It was crashing for some actions with Magit and starting a CIDER REPL so I decided to do a fresh install. Here is my .spacemacs file. # Answer > 1 votes Addressed here. It's an issue with Emacs 26 using libraries from back in 18.04 that are not present in 20.04. --- Tags: spacemacs, linux, ubuntu ---
thread-58730
https://emacs.stackexchange.com/questions/58730
Display keybindings typed in a buffer
2020-05-26T11:53:27.253
# Question Title: Display keybindings typed in a buffer On this video stream, the window on right displays the keybindings typed with its corresponding command bound. Is there any package that does that, or a way to achieve it? # Answer > 4 votes Yes! This is `command-log-mode` which can be installed from Melpa. You have to add the function to whatever modes you want to record, like ``` (add-hook 'python-mode-hook 'command-log-mode) ``` Then, to invoke the log window as shown in the video ``` M-x clm/open-command-log-buffer ``` Open a Python file (in my example) and start manipulating the code to see your actions in the command log buffer. There is also `M-x global-command-log-mode` to capture all (or most) interactions across modes. # Answer > 2 votes > *Is there any package that does that, or a way to achieve it?* One such package is Show Key (code: `showkey.el`). Global minor mode **`showkey-log-mode`** keeps a log of such events, in a separate frame. It's refreshed with each new event, and it's kept on top of other frames without stealing the input focus. Various user options control what events get logged, etc. --- Tags: commands, help, keystrokes, logging ---
thread-58740
https://emacs.stackexchange.com/questions/58740
How to cancel a mini-buffer prompt from elisp, eg: "... changed on disk; really edit this buffer?"
2020-05-27T01:57:13.020
# Question Title: How to cancel a mini-buffer prompt from elisp, eg: "... changed on disk; really edit this buffer?" Sometimes I get a mini-buffer prompt to check if I want to edit the buffer. Instead of answering this, I would like to revert all buffers, however this prompt remains. How could I cancel this prompt? (which is no longer needed when reverting all buffers) # Answer Based upon a reading of the code for the function `ask-user-about-supersession-threat`, it *may* be sufficient to use `(signal 'file-supersession (list "My custom message"))` to cancel the mini-buffer prompt from elisp. See also the functions `abort-recursive-edit` \["*Abort the command that requested this recursive edit or minibuffer input.*"\] and `top-level` \["*Exit all recursive editing levels. This also exits all active minibuffers.*"\] > 1 votes --- Tags: revert-buffer ---
thread-3925
https://emacs.stackexchange.com/questions/3925
Hide list of minor modes in mode-line
2014-11-27T10:24:47.633
# Question Title: Hide list of minor modes in mode-line I use quite a few minor modes and usually I know which minor mode is enabled in every major mode. If I really want to see the full list, I can run `C-h v minor-mode-list`. At the same time, my mode line get really clogged, so when I vertically split frame, sometimes I cannot read end of the mode line. Actual question: how to disable showing of minor modes list in mode line? For example, now it may look like this: ``` -:--- main.c All (7,12) (C/l FlyC SScr Abbrev Fill) [main] 16:19 0.45 ``` I want it to look more concise: ``` -:--- main.c All (7,12) (C/l) [main] 16:19 ``` # Answer Diminish mode (available in Melpa) will do this. ``` (diminish 'projectile-mode) ``` > 21 votes # Answer As mbork commented, you can use delight.el to selectively modify or disable minor (and indeed major) mode text in the mode line. One of the advantages is that it takes care of the `eval-after-load` (which you need to write manually with diminish.el in most use-cases), which makes the configuration cleaner. You still need the same information -- the name of the mode, and the library which implements it (which Emacs will tell you if you ask it about the mode) -- but you can wrap it all up into a single form: ``` (require 'delight) (delight '((some-mode nil "some-library") (some-other-mode nil "some-other-library"))) ``` (Or follow the link above for some real usage examples.) I would recommend taking this approach, because even if you don't want *most* minor mode lighter text, there's a good chance that you'll find some of them useful (and you can still modify those ones to be shorter). If you truly want to eliminate **all** minor mode lighter text (and again, I don't recommend it), you could modify the `mode-line-modes` variable. The mode line variables changed a while back, so you may want to use `M-x find-variable RET mode-line-modes RET` and then manually adapt your default definition, editing out the section concerning `minor-modes-alist`. Of course then you'd need to maintain it, which isn't so flash, so you might prefer replacing the `minor-mode-alist` symbol *within* the existing value. The following is somewhat implementation-specific, but certainly nicer than setting `mode-line-modes` in its entirety, and you can toggle it on and off. ``` (define-minor-mode minor-mode-blackout-mode "Hides minor modes from the mode line." t) (catch 'done (mapc (lambda (x) (when (and (consp x) (equal (cadr x) '("" minor-mode-alist))) (let ((original (copy-sequence x))) (setcar x 'minor-mode-blackout-mode) (setcdr x (list "" original))) (throw 'done t))) mode-line-modes)) (global-set-key (kbd "C-c m") 'minor-mode-blackout-mode) ``` > 19 votes # Answer Here is what worked for me: ``` (defvar hidden-minor-modes ; example, write your own list of hidden '(abbrev-mode ; minor modes auto-fill-function flycheck-mode flyspell-mode inf-haskell-mode haskell-indent-mode haskell-doc-mode smooth-scroll-mode)) (defun purge-minor-modes () (interactive) (dolist (x hidden-minor-modes nil) (let ((trg (cdr (assoc x minor-mode-alist)))) (when trg (setcar trg ""))))) (add-hook 'after-change-major-mode-hook 'purge-minor-modes) ``` Thanks to Drew's comment, I've improved realization of this solution. Now it uses benefits of association lists and should be a bit more efficient ;-) > 9 votes # Answer Use Rich-minority with config: ``` (require 'rich-minority) (rich-minority-mode 1) (setf rm-blacklist "") ``` I also have the thought like you, but I shorten the mode-line **more paranoid**: * Remove all unwanted spaces * Remove all spaces and "min-width" of the buffer position info field. ``` ;; Remove all unwanted spaces (setq-default mode-line-format '("%e" mode-line-front-space mode-line-mule-info mode-line-client mode-line-modified mode-line-remote mode-line-buffer-identification mode-line-position (vc-mode vc-mode) " " mode-line-modes mode-line-misc-info mode-line-end-spaces)) ;; Remove all spaces and "min-width" of position info on mode-line (setq mode-line-position `((1 ,(propertize " %p" 'local-map mode-line-column-line-number-mode-map 'mouse-face 'mode-line-highlight ;; XXX needs better description 'help-echo "Size indication mode\n\ mouse-1: Display Line and Column Mode Menu")) (size-indication-mode (2 ,(propertize "/%I" 'local-map mode-line-column-line-number-mode-map 'mouse-face 'mode-line-highlight ;; XXX needs better description 'help-echo "Size indication mode\n\ mouse-1: Display Line and Column Mode Menu"))) (line-number-mode ((column-number-mode (1 ,(propertize "(%l,%c)" 'local-map mode-line-column-line-number-mode-map 'mouse-face 'mode-line-highlight 'help-echo "Line number and Column number\n\ mouse-1: Display Line and Column Mode Menu")) (1 ,(propertize "L%l" 'local-map mode-line-column-line-number-mode-map 'mouse-face 'mode-line-highlight 'help-echo "Line Number\n\ mouse-1: Display Line and Column Mode Menu")))) ((column-number-mode (1 ,(propertize "C%c" 'local-map mode-line-column-line-number-mode-map 'mouse-face 'mode-line-highlight 'help-echo "Column number\n\ mouse-1: Display Line and Column Mode Menu")))))) ) ``` Now, I can always see Twittering-mode notification and Org-mode's timer :D > 9 votes # Answer It's worth noting that `use-package` supports diminish and delight. If you use it to manage your packages you can hide the minor modes in the mode line adding the :diminish or :delight keywords. ``` (use-package abbrev :diminish abbrev-mode :config (if (file-exists-p abbrev-file-name) (quietly-read-abbrev-file))) ``` > 4 votes # Answer I'll throw my solution to this into the ring as well: ``` (defun modeline-set-lighter (minor-mode lighter) (when (assq minor-mode minor-mode-alist) (setcar (cdr (assq minor-mode minor-mode-alist)) lighter))) (defun modeline-remove-lighter (minor-mode) (modeline-set-lighter minor-mode "")) ``` `modeline-set-lighter` allows you to set the lighter of a minor mode to any string you like. `modeline-remove-lighter` allows you to remove the lighter of a minor mode completely. Then, at the end of my init-file I just call these functions for the minor modes whose lighters I want to modify: ``` (modeline-remove-lighter 'auto-complete-mode) (modeline-remove-lighter 'git-gutter+-mode) (modeline-remove-lighter 'guide-key-mode) (modeline-remove-lighter 'whitespace-mode) (modeline-set-lighter 'abbrev-mode " Abbr") (modeline-set-lighter 'auto-fill-function (string 32 #x23ce)) ``` > 3 votes # Answer You can also bluntly remove all minor modes, in the following way: ``` (setq mode-line-modes (mapcar (lambda (elem) (pcase elem (`(:propertize (,_ minor-mode-alist . ,_) . ,_) "") (t elem))) mode-line-modes)) ``` This will also work for minor modes defined in the future, since it just completely removes the use of `minor-mode-alist` from the `mode-line-format`. > 3 votes # Answer I don't see the point of installing fancy named extensions for something as simple as: ``` (setcar (alist-get minor-mode minor-mode-alist) "") ``` For example: ``` (dolist (mode '(projectile-mode whitespace-mode hs-minor-mode outline-minor-mode auto-fill-function)) (setcar (alist-get mode minor-mode-alist) "")) ``` You can do any sort of stuff this way. Replacing text is obvious from the above. Also, for example, to put flymake mode at the start of the list: ``` (let ((mode (assq #'flymake-mode minor-mode-alist))) (setq minor-mode-alist (cons mode (remq mode minor-mode-alist)))) ``` > 2 votes # Answer If you don't want to do `diminish`/`delight` on every package. You could try minions it will hide all minor mode and can be toggled using mouse. Or you can use awesome-tray which you can use to refine what to show in modeline. > 2 votes --- Tags: mode-line, minor-mode ---
thread-58747
https://emacs.stackexchange.com/questions/58747
What tools can help make the emacs debug output more readable?
2020-05-27T06:15:03.660
# Question Title: What tools can help make the emacs debug output more readable? I was expecting to find tools I can use to to e.g. prettify the stack trace, or e.g. show all variables that are bound at each level of the stack trace as you navigate, but haven't found anything. Do any tools to improve the debugging experience exist? No hits on melpa: https://melpa.org/#/?q=debug%20elisp # Answer > 3 votes Emacs 27: `C-h``i``g` `(elisp)Backtraces` > ## 18.1.7 Backtraces > > Debugger mode is derived from Backtrace mode, which is also used to show backtraces by Edebug and ERT. (\*note Edebug::, and \*note the ERT manual: (ert)Top.) > > The backtrace buffer shows you the functions that are executing and their argument values. When a backtrace buffer is created, it shows each stack frame on one, possibly very long, line. (A stack frame is the place where the Lisp interpreter records information about a particular invocation of a function.) The most recently called function will be at the top. > > In a backtrace you can specify a stack frame by moving point to a line describing that frame. The frame whose line point is on is considered the “current frame”. > > If a function name is underlined, that means Emacs knows where its source code is located. You can click with the mouse on that name, or move to it and type , to visit the source code. You can also type while point is on any name of a function or variable which is not underlined, to see help information for that symbol in a help buffer, if any exists. The ‘xref-find-definitions’ command, bound to , can also be used on any identifier in a backtrace (\*note (emacs)Looking Up Identifiers::). > > In backtraces, the tails of long lists and the ends of long strings, vectors or structures, as well as objects which are deeply nested, will be printed as underlined “...”. You can click with the mouse on a “...”, or type while point is on it, to show the part of the object that was hidden. To control how much abbreviation is done, customize ‘backtrace-line-length’. > > Here is a list of commands for navigating and viewing backtraces: > > ‘v’ Toggle the display of local variables of the current stack frame. > > ‘p’ Move to the beginning of the frame, or to the beginning of the previous frame. > > ‘n’ Move to the beginning of the next frame. > > ‘+’ Add line breaks and indentation to the top-level Lisp form at point to make it more readable. > > ‘-’ Collapse the top-level Lisp form at point back to a single line. > > ‘#’ Toggle ‘print-circle’ for the frame at point. > > ‘:’ Toggle ‘print-gensym’ for the frame at point. > > ‘.’ Expand all the forms abbreviated with “...” in the frame at point. # Answer > 1 votes It's possible to format backtraces differently using `mapbacktrace` with a custom function. One such example is always printing the items as list, I've contributed a patch introducing the `debugger-stack-frame-as-list` customizable that does that. Check out the implementation of `backtrace` in Emacs 26.1 or newer. --- Tags: debugging, edebug, debug, backtrace ---
thread-58752
https://emacs.stackexchange.com/questions/58752
Org babel remove currency form ledger output
2020-05-27T13:39:45.683
# Question Title: Org babel remove currency form ledger output Howto remove the currency from the table or get ledger -j to work so that gnuplot can work with the data? ``` #+NAME: LedgerCli #+BEGIN_SRC ledger :results raw :cmdline reg "Assets:Service Days" --exchange sd --format='| %D | %t | \n' SOME LEDGER STATEMENTS #+END_SRC #+Name: ledgercli-table #+RESULTS: LedgerCli | 2019/12/01 | 12.0 sd | | 2019/12/03 | -0.5 sd | | 2019/12/05 | -0.5 sd | | 2019/12/10 | -1.0 sd | | 2019/12/17 | -1.0 sd | | 2020/03/23 | -4.0 sd | | 2020/04/01 | -0.1 sd | | 2020/05/19 | -0.5 sd | | 2020/05/26 | -0.3 sd | #+begin_src gnuplot :var data=ledgercli-table :file gnuplot.png :exports results set xdata time set style data linespoints set timefmt "%Y/%m/%d" plot data u 1:2 #+end_src #+RESULTS: [[file:gnuplot.png]] ``` this results in ``` gnuplot> data = "/tmp/babel-sC46Yh/gnuplot-DvVaqU" gnuplot> set term png Terminal type is now 'png' set output "gnuplot.png" Options are 'nocrop enhanced size 640,480 font "arial,12.0" ' gnuplot> gnuplot> set xdata time gnuplot> set style data linespoints gnuplot> set timefmt "%Y/%m/%d" gnuplot> plot data u 1:2 warning: Skipping data file with no valid points ^ x range is invalid ``` If I manually remove all occurrences of sd from the table a plot gets produces - not what I want but that is a different problem. # Answer There are various places where that could be done, e.g. at the ledger-cli level, you might be able to convince it to skip the `sd` part, or to produce a third column, identical to the second as far as the numbers are concerned but omitting the `sd` part and then having your `gnuplot` block look at columns 1 and 3. Since I don't know much about `ledger`, I will not pursue these further. Here I'm going to add a source block to transform the input table to the form that the `gnuplot` block expects: ``` #+Name: ledgercli-table #+RESULTS: LedgerCli | 2019/12/01 | 12.0 sd | | 2019/12/03 | -0.5 sd | | 2019/12/05 | -0.5 sd | | 2019/12/10 | -1.0 sd | | 2019/12/17 | -1.0 sd | | 2020/03/23 | -4.0 sd | | 2020/04/01 | -0.1 sd | | 2020/05/19 | -0.5 sd | | 2020/05/26 | -0.3 sd | #+begin_src python :var t=ledgercli-table :results output drawer print("#+Name: ledger-cli-table-no-currency") for l in t: print(f"| {l[0]} | {l[1].split(' ')[0]} |") #+end_src #+RESULTS: :results: #+Name: ledger-cli-table-no-currency | 2019/12/01 | 12.0 | | 2019/12/03 | -0.5 | | 2019/12/05 | -0.5 | | 2019/12/10 | -1.0 | | 2019/12/17 | -1.0 | | 2020/03/23 | -4.0 | | 2020/04/01 | -0.1 | | 2020/05/19 | -0.5 | | 2020/05/26 | -0.3 | :end: #+begin_src gnuplot :var data=ledger-cli-table-no-currency :file gnuplot.png :exports results set xdata time set style data linespoints set timefmt "%Y/%m/%d" plot data u 1:2 #+end_src #+RESULTS: [[file:gnuplot.png]] ``` All you have to do is change the `gnuplot` block to read from the new table. Also, I used a python block to implement the transformation, but it could easily be done in any Org babel-supported language. > 0 votes --- Tags: org-babel, ledger ---
thread-37216
https://emacs.stackexchange.com/questions/37216
Open SVG files in XML mode
2017-12-01T08:41:17.807
# Question Title: Open SVG files in XML mode When opening a vector icon text file for editing, Emacs *first* tries to display it as an image. That is wrong ; If the file has errors, Emacs (25.3.2 - x86\_64-pc-linux-gnu, GTK+ Version 3.18.9) crashes miserably. Well, I *know* it has errors, that why I opened it in a *text editor* in the first place :/ And furthermore, Emacs will hang even if the file doesn't have errors, but just because it cannot render it (like it's just several `path`s with `id`s inside a `svg` grouping tag) which is frustrating to say the least. How can I make Emacs load text files as text files and not try to render it (because it can't) unless I explicitly told him to? PS - Yes, I know that I can switch to text-mode by pressing `C-c C-c`. ### What I tried ``` (add-to-list `auto-mode-alist '("\\.svg\\'" . xml-mode)) ``` But no, Emacs still crashes on me upon opening my icons.svg file because it tries to render it as an image (and it's actually *several* images) when actually it's not its job. ### Annex: The SVG code ``` <svg xmlns="http://www.w3.org/2000/svg"> <symbol id="cross" viewBox="0 0 20 20"> <path d="M17.1 5.2l-2.6-2.6-4.6 4.7-4.7-4.7-2.5 2.6 4.7 4.7-4.7 4.7 2.5 2.5 4.7-4.7 4.6 4.7 2.6-2.5-4.7-4.7"/> </symbol> <symbol id="play" viewBox="0 0 15 15"> <path d="M690 60H40l330 570L700 60z" /> </symbol> </svg> ``` # Answer You'll probably like to either disable `auto-image-file-mode` or tweak `image-file-name-extensions`. BTW, if Emacs crashes or hangs for a particular SVG file, I suggest you `M-x report-emacs-bug` about it. Maybe there's not much Emacs's code can do about it (e.g. the problem is in the SVG rendering livbrary), but it might be a good reason to change the default so that image-mode is not used by default on SVG files (hell, it might even be a security hole). > 4 votes # Answer I have a solution that does 2 things: 1. Attempt to open any XML file in nXML mode, and this obviously needs to include SVG files. 2. If such a file is an SVG file, then define `C-c C-c` to `image-mode`. For the first item, I use `magic-mode-alist` to select `nxml-mode` on some sequences at the beginning of the buffer: `<?xml`, some DOCTYPE line with XHTML, and `<svg` followed by a newline character, a space, or `>`. This will work with SVG files that use an XML prolog or not (I assume no initial spaces, but this could be changed). Here's the code: ``` (when (boundp 'magic-mode-alist) (push '("\\`<\\(\\?xml\\|!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML\\|svg[\n >]\\)" . nxml-mode) magic-mode-alist) ) ``` For the second item, I use code for a `find-file` hook: ``` (defun my-find-file-hook () (when (and (string= major-mode "nxml-mode") (save-excursion (and (re-search-forward "<[a-z]" 1024 t) (progn (backward-char) (looking-at "svg[\n >]"))))) (global-set-key "\C-c\C-c" 'image-mode))) (add-hook 'find-file-hook 'my-find-file-hook) ``` If the buffer is in nXML mode, it searches for the root element and if it is `svg`, then it defines `C-c C-c`. Note that this is just a heuristic. In particular, a `<svg` sequence in an initial XML comment could yield a false positive, but I think that this never occurs in practice. > 1 votes --- Tags: images, xml ---
thread-58754
https://emacs.stackexchange.com/questions/58754
thing-at-point does not bound url properly due to backslash in url
2020-05-27T15:10:10.230
# Question Title: thing-at-point does not bound url properly due to backslash in url I am trying to filter URLs and elisp `thing-at-point 'url` doesn't bounds a url properly because it has backslashes `\`in it. I believe that backslashes are unsafe in urls, but that's a separate topic. The fact is that I am receiving emails with URLs that have them. So my question is if there is any way to ensure that thing-at-point allows backslashes, so that urls can be properly bounded? The relevant functions should be available at thingatpt.el Thank you in advance. ## Update This is phils' solution ``` (defun thing-at-point-bounds-of-url-at-point (&optional lax) "Return a cons cell containing the start and end of the URI at point. Try to find a URI using `thing-at-point-markedup-url-regexp'. If that fails, try with `thing-at-point-beginning-of-url-regexp'. If that also fails, and optional argument LAX is non-nil, return the bounds of a possible ill-formed URI (one lacking a scheme)." ;; Look for the old <URL:foo> markup. If found, use it. (or (thing-at-point--bounds-of-markedup-url) ;; Otherwise, find the bounds within which a URI may exist. The ;; method is similar to `ffap-string-at-point'. Note that URIs ;; may contain parentheses but may not contain spaces (RFC3986). (let* ((allowed-chars "--:=&?$+@-Z_[:alpha:]~#,%;*()!'\\\\") (skip-before "^[0-9a-zA-Z]") (skip-after ":;.,!?") (pt (point)) (beg (save-excursion (skip-chars-backward allowed-chars) (skip-chars-forward skip-before pt) (point))) (end (save-excursion (skip-chars-forward allowed-chars) (skip-chars-backward skip-after pt) (point)))) (or (thing-at-point--bounds-of-well-formed-url beg end pt) (if lax (cons beg end)))))) ``` and this is the original and url bounded by `thing-at-point-bounds-of-url-at-point` (both edited) original: ``` https://eur01.safelinks.protection.outlook.com/?url=http%3A%2F%2Fwww.disney.com%2F&amp\;data=02%7C01%7CDonald.Duck%40disney.com%7Cfd8a40dd8138470286be08d8020da460%7C07ef1208413c4b5e9cdd64ef305754f0%7C0%7C0%7C637261604914185764&amp\;sdata=UdFaQR32cGXKu7ZrBU%2BGg8TJ%2BOeTZUMBV9N%2BE8Vi22s%3D&amp\;reserved=0 ``` bounded: ``` https://eur01.safelinks.protection.outlook.com/?url=http%3A%2F%2Fwww.disney.com%2F&amp ``` # Answer In Emacs 26.3 at least, the allowed characters are hard-coded in `thing-at-point-bounds-of-url-at-point`; so you would need to modify that function accordingly, to add a backslash to the `allowed-chars` binding. The comments below on escaping would apply here too: use `"\\\\"`. (And likewise for having no idea whether or not this will have unwanted side-effects.) *Edit: Initial answer follows, before I'd realised that `thing-at-point` doesn't use `url-get-url-at-point` at all...* --- ``` url-get-url-filename-chars is a variable defined in `url-util.el'. Its value is "-%.?@a-zA-Z0-9()_/:~=&" Documentation: Valid characters in a URL. ``` It's used (by `url-get-url-at-point`) both in a regexp character alternative, and also with `skip-chars-*`, which means you'd need to use the latter's escaping for a backslash: `"\\\\"` (which is merely redundant for the former). I don't know what all of the practical consequences of modifying this value might be. > 1 votes --- Tags: regular-expressions, url, thing-at-point ---
thread-58621
https://emacs.stackexchange.com/questions/58621
How to get kill-buffer-hook to detach a screen session prior to kill-buffer?
2020-05-20T20:30:06.570
# Question Title: How to get kill-buffer-hook to detach a screen session prior to kill-buffer? I keep many screen session running in the backgroud, which I access with `M-x eshell-command "screen -r <myscreen>"`. Before I kill the `*screen*` buffer, I have to detach the session with `C-a d`. It would be nice to have that integrated into `kill-buffer` via `kill-buffer-hook`, but I don't know how because the `*screen*` buffer is read-only, so `insert` doesn't work. My non-working idea is: ``` (add-hook `term-mode-hook (add-hook 'kill-buffer-hook (insert (kbd "C-a d")))) ``` What's the proper elisp command to send control-sequence inputs to a terminal via a hook? # Answer An elisp `insert` into the terminal *buffer* does not communicate with the terminal *process* at all. `(term-send-raw-string (kbd "C-a d"))` is probably what you want to do. Something like this? ``` (defun my-screen-detach () "Send 'C-a d' to the terminal." (if (derived-mode-p 'term-mode) (when (process-live-p (get-buffer-process (current-buffer))) (message "Sending screen detach key sequence.") (term-send-raw-string (kbd "C-a d"))) (user-error "Not a `term-mode' buffer."))) (defun my-term-exec-hook () "Custom `term-exec-hook' behaviours." ;; If "screen" was the command being run in the terminal, then ;; arrange to send a 'detach' screen command if we kill the ;; buffer. (let ((proc (get-buffer-process (current-buffer)))) ;; (message "%S" (process-command proc)) (if (member "/usr/bin/screen" (process-command proc)) (add-hook 'kill-buffer-hook 'my-screen-detach nil :local) (remove-hook 'kill-buffer-hook 'my-screen-detach :local)))) (add-hook 'term-exec-hook 'my-term-exec-hook) ``` > 0 votes # Answer @phils is right about screen implicitly detaching when its buffer is killed. This does, in fact, work cleanly under Ubuntu, CentOS and XQuartz (& probably elsewhere as well). I found that to get the behavior I was looking for, all I really needed was to disable the exit query when screen is started. Taking many cues from phils, here is my solution: ``` (defun my-term-exec-hook () "Custom `term-exec-hook' behaviors." ;; suppress query on exit for screen (let ((proc (get-buffer-process (current-buffer)))) (if (member "/usr/bin/screen" (process-command proc)) (set-process-query-on-exit-flag proc nil)))) (add-hook 'term-exec-hook 'my-term-exec-hook) ``` many thanks! > 0 votes --- Tags: hooks, kill-buffer, term ---
thread-58763
https://emacs.stackexchange.com/questions/58763
Launch emacs in eww mode, display local .html file at startup
2020-05-28T00:30:08.843
# Question Title: Launch emacs in eww mode, display local .html file at startup I'm new to Emacs and I'm going about customizing my install on Mac OS Catalina. I have a twist on a common request. I had the idea to customize the **emacs startup screen**, but I see those options are limited based on what I've read so far. You can switch out the logo, maybe change the bg color, customize the text string associated with that screen, but you can't really dig into it per say because it's all in the source code. So I got the idea of **displaying a local html file** (or one on a LAN) instead. I got that to display on launch, but it's showing in HTML code mode/buffer. I found this line for my .emacs file elsewhere: `(setq initial-buffer-choice "~/.emacs.d/startup.html")` My question is... **Is there a way to launch Emacs in eww browser mode and display a local `startup.html` file?** *(Which is like hitting a nail with a sledgehammer I know but, I was curious.)* Related to this, can you specify a handler for links to files within a page displayed by eww? (e.g. .mp4,.mp3, html, pdf,.csv, etc.) # Answer Put this in $HOME/.emacs.d/init.el and start up emacs: ``` (setq inhibit-startup-screen t) (eww-open-file "/path/to/startup.html") ``` If you want to visit a URL instead, just replace the second line with ``` (eww "https://example.com/index.html") ``` > 3 votes --- Tags: init-file, start-up, html, eww ---
thread-58720
https://emacs.stackexchange.com/questions/58720
I have to enable `hl-todo-mode` in LaTeX-mode?
2020-05-25T18:39:43.193
# Question Title: I have to enable `hl-todo-mode` in LaTeX-mode? Currenty I am on `LaTeX-mode-hook` and added following line `global-hl-todo-mode` into `.emacs` file to use hl-todo. On its readme it says: > To highlight keywords turn on `hl-todo-mode` in individual buffers or use the the global variant `global-hl-todo-mode`. My setup: ``` ; L A T E X ; (setq LaTeX-item-indent 0) (add-hook 'LaTeX-mode-hook 'turn-on-auto-fill) (add-hook 'LaTeX-mode-hook 'hl-todo-mode) (require 'tex) (add-hook 'LaTeX-mode-hook (lambda () (TeX-global-PDF-mode t) (global-hl-todo-mode t) ; <= added here )) (global-hl-todo-mode 1) ; <= added bottom of the page ``` --- When I open `emacs -nw file.tex`, I need to disable and than re-enable `global-hl-todo-mode` in order to use it. Is there any way to fix this issue? Please note that, this was working perfectly fine in `python-mode`. # Answer I had a similar problem with AUCTeX and fic-mode. It's caused by the style-hooks executed by AUCTeX after loading the file. You can enable your minor mode in the `TeX-update-style-hook`, see. this TeX stackexchange question. > 2 votes # Answer The question is: do you want `hl-todo-mode` to be turned on for *every* mode that is allowed by `hl-todo-include-mode` (by default that is `prog-mode` and `text-mode`) except for the excluded modes in `hl-todo-exclude-mode` (by default, `org-mode`)? OR you just want it turned on for `LaTeX-mode`? If the former, then add ``` (global-hl-todo-mode) ``` in your init file (`.emacs` or `.emacs.d/init.el`). If you only want it for LaTeX-mode, then add ``` (add-hook 'LaTeX-mode-hook #'hl-todo-mode) ``` to your init file. EDIT in response to the OP's comment: Something else is interfering. Try with `emacs -q -l minimal.el` where `minimal.el` does the following: ``` (add-to-list `load-path "/path/to/hl-todo-mode.el") (load-library "hl-todo-mode") (global-hl-todo-mode) ``` and then open a `tex` file and type `TODO`: it should be properly fontified with the following text properties (which you can check with `C-u C-x =` while your cursor is on that word): ``` face (:inherit hl-todo :foreground "#cc9393") fontified t ``` Assuming that that is the case (as it is in my tests), there is something in your init file that breaks this: bisect through it to determine what is doing the breakage. > 1 votes --- Tags: todo, tex ---
thread-58772
https://emacs.stackexchange.com/questions/58772
Trying to install org-ref package, but getting error 'emacs-25.1' unavailable
2020-05-28T07:01:04.983
# Question Title: Trying to install org-ref package, but getting error 'emacs-25.1' unavailable I am trying to install `org-ref` package but getting error ``` package-compute-transaction: Package 'emacs-25.1' is unavailable. ``` I searched `Stack overflow`, `Stack Exchange Emacs`, and `github`. I've found many solutions like this but isn't working for me. I am using `Emacs 25.1` in `Ubuntu 16.4`. **Edit: I am using Emacs 24.5.1** version. I was able to install `org-ref` earlier but need to reinstall as it got corrupted. # Answer > 1 votes You need to upgrade your emacs to at least Emacs 25.1. I'm not sure if each Ubuntu LTS provides updated stable packages beyond the point they released the distro, `emacs26` now, but if not you can either compile it yourself or look for a suitable ppa as Kevin Kelley's --- Tags: package, org-ref, emacs24 ---
thread-58746
https://emacs.stackexchange.com/questions/58746
Altering syntax highlighting for a particular expression
2020-05-27T05:37:39.377
# Question Title: Altering syntax highlighting for a particular expression In c-mode, I would like all lines beginning with ``` exec sql ``` to have that expression grey and the rest of the line in the default face. How might I achieve that? # Answer The following will do something similar to what you asked for. ``` (let ((re "^[ ]*\\(exec sql\\)\\(.*\\)$")) (font-lock-add-keywords 'c-mode `((,re 1 font-lock-preprocessor-face t))) (font-lock-add-keywords 'c-mode `((,re 2 font-lock-string-face t)))) ``` The numbers represent subexpression matches, and the `t` mean that already present fontification should be overridden. Have a look at the documentation of `font-lock-keywords`. > 2 votes --- Tags: font-lock, syntax-highlighting, cc-mode ---
thread-58631
https://emacs.stackexchange.com/questions/58631
how to open a file without using Ivy
2020-05-21T03:30:12.387
# Question Title: how to open a file without using Ivy Under most operations, when I open a file with `C-x C-f` Ivy pops up my narrowing list at the bottom and its great. However, I have a current situation when I'd like to open a file on a remote host in a directory that has 60,000 files in it. So when I `C-x C-f` into that directory over tramp, it takes an awfully long time until I can find the file I am looking for. Sometimes, though I know what the file name is and I'd just like to type it and not have Ivy butt in so that I can get on with it. How would I bet go about doing this? # Answer > 4 votes In default Ivy configurations, `C-x C-f` is bound to `counsel-find-file` which will invoke `ivy-completing-read` even if global `ivy-mode` is turned off! Rather than going through the clumsy steps of disabling Ivy, calling the non-Counsel `find-file`, then turning Ivy back on, I have implemented this solution. In the given use case of many files, you can enter a portion of the file name, then use `TAB` to get completion on the matching set. ``` (defun gjg/find-file-no-ivy () (interactive) (let ((ivy-state ivy-mode)) (ivy-mode -1) (call-interactively 'find-file) (ivy-mode ivy-state))) (global-set-key (kbd "C-x F") 'gjg/find-file-no-ivy) ; steals key from set-fill-column ``` The function restores the state of `ivy-mode`. Bind to any key that works for you! --- Tags: find-file, ivy ---
thread-58783
https://emacs.stackexchange.com/questions/58783
Automatically open headline on internal link
2020-05-28T15:46:26.997
# Question Title: Automatically open headline on internal link The following example implements an internal link to a headline: ``` * Heading1 - Important facts * Heading2 - Jump to [[*Heading1][Link]] ``` When following/opening the "Link" with `C-c C-o`, point moves to "Heading1". If the headline is closed, I would like it to open (unfold, expand) automatically when point lands. If the headline is already open, then do nothing (meaning, `org-cycle` can't be used). # Answer > 2 votes Something like this perhaps: ``` (defun sw-org-unfold-headline-maybe () (when (eq (car (org-element-at-point)) 'headline) (org-show-subtree))) (add-hook 'org-follow-link-hook #'sw-org-unfold-headline-maybe) ``` The hook runs the function after the link has been followed and the function checks that it's at a headline before it unfolds it. There may be some spurious headline unfoldings though: I doubt that the function is selective enough as is. --- Tags: org-link ---
thread-58786
https://emacs.stackexchange.com/questions/58786
Regexp: how to search-replace any html attribute in current buffer
2020-05-28T18:49:46.667
# Question Title: Regexp: how to search-replace any html attribute in current buffer Disclaimer: I'm still trying to learn elisp so I have not gotten yet to the RegExp section of the Elisp intro or Emacs manual. I would like to know how to search and replace an HTML buffer that has elements with any number of attributes with my desired string (that to be filled by me). Basically, I need help building the RegExp that would match all the attributes that look like `attr="[whatever string"` # Answer Using web-mode you can traverse the dom tree element by element and then traversing element attributes killing/sparing each one manually without having to code anything, just learning the keybindings. Doing it automatically will require some coding. I guess you can do something similar with other related modes with more or less effort. If you're looking for a quick and dirty regexp to match what resembles an attribute using `C-M-%` it could be something like `[[:word:]]+="[^"]+"` > 1 votes --- Tags: regular-expressions, query-replace-regexp ---
thread-45090
https://emacs.stackexchange.com/questions/45090
Make Org Table with #+NAME label collapsible
2018-10-01T17:09:00.920
# Question Title: Make Org Table with #+NAME label collapsible I have an org table with has a NAME label like: ``` #+NAME: TBL | Foo | Bar | ``` In the past I have always been able to expand and collapse the whole table by cycling using `TAB` on the `#+NAME` line. However in the latest version of emacs (26.1), this doesn't seem to work. If I replace `#+NAME: TBL` with `#+RESULTS: TBL` it works fine. Pressing TAB on the RESULTS line hides the table, pressing it again reveals the table once more. Is there an org setting to define which which blocks can be expanded/folded, or some other requirement I'm missing? Thanks # Answer > 1 votes I don't know if the foldable elements are documented elsewhere, but the "folding" is done in the functions `org-hide-block-toggle-maybe` and `org-hide-block-toggle` (the former just calls the latter and ignores errors). The list is as follows: ``` (center-block comment-block dynamic-block example-block export-block quote-block special-block src-block verse-block) ``` Instead of using #+RESULT for this (which is specifically meant for results of source blocks), I would use an example block: ``` #+BEGIN_EXAMPLE #+NAME: TBL | Foo | Bar | #+END_EXAMPLE ``` I tried to find an org version that actually folds #+NAME (or #+TABLE) elements and I couldn't come up with one, although I went back five years to version 8.1 (of course, I could have made a mistake). Are you sure that this was ever the case? If so, what version of org-mode (`M-x org-version` will tell) was that? UPDATE: `org-hide-block-toggle` is used for blocks, but not for results. Results are handled through the `org-tab-first-hook` variable: `ob-core.el` adds `org-babel-hide-result-toggle-maybe` to the hook and that is what folds/unfolds results. AFAICT however, that is not used for #+NAME folding - still looking. # Answer > 0 votes I am also concerned with the change of the behaviour. I don't remember the emacs & org versions but I used to set a header like `#+TBLNAME` which was able to expand and collapse. It was terrificly useful as long as I was learning with tables and using them a lot. Following your tests I have figured out something like `#+begin_table` and it seems to work pretty good, you can expand and collapse over `#+begin`. You can even set a header `#+name:` and it also works expand&collapse over `#+name` with the table above it. ``` #+name: number-prototypes #+begin_table |-------------------+------+--------| | Propose | Date | Number | |-------------------+------+--------| | Researcher | 2011 | 5 | | Researcher 2 & 3 | 2019 | 13 | |-------------------+------+--------| #+end_table ``` UPDATE: By the way it doesn't work for literate programming :-/ Feedback is welcome ;-) # Answer > 0 votes The following Elisp code lets you toggle the visibility of the element following the `#+NAME:` line with the `TAB`-key. Note that a table is a special element. Therefore, the code also works for tables. ``` (defun org+-at-keyword-line-p (name) "Return non-nil if point is in a line with #+NAME: keyword. Therefore, NAME stands for the string argument NAME, not for the Org keyword. The return value is actually the first non-space sequence after #+NAME:" (save-excursion (goto-char (line-beginning-position)) (and (looking-at (concat "^[[:blank:]]*#\\+" name ":[[:blank:]]*\\([^[:space:]]+\\)?")) (or (match-string 1) "")))) (defun org+-hide-named-paragraph-toggle (&optional force) "Toggle the visibility of named paragraphs. If FORCE is 'off make paragraph visible. If FORCE is otherwise non-nil make paragraph invisible. Otherwise toggle the visibility." (interactive "P") (when (org+-at-keyword-line-p "NAME") (save-excursion (forward-line) (let* ((par (org-element-at-point)) (start (org-element-property :contents-begin par)) (end (org-element-property :contents-end par)) (post (org-element-property :post-affiliated par))) (cond ((eq force 'off) (org-flag-region start end nil 'org-hide-block)) (force (org-flag-region start end t 'org-hide-block)) ((eq (get-char-property start 'invisible) 'org-hide-block) (org-flag-region start end nil 'org-hide-block)) (t (org-flag-region start end t 'org-hide-block))) ;; When the block is hidden away, make sure point is left in ;; a visible part of the buffer. (when (invisible-p (max (1- (point)) (point-min))) (goto-char post)) ;; Signal success. t)))) (add-hook 'org-tab-after-check-for-cycling-hook #'org+-hide-named-paragraph-toggle) ``` Tested with Emacs 26.3 and `org-version` 9.2.6. --- Tags: org-mode, org-table, emacs26 ---
thread-34914
https://emacs.stackexchange.com/questions/34914
How to export org-mode to ODT with endnotes?
2017-08-16T02:31:28.850
# Question Title: How to export org-mode to ODT with endnotes? If an org-mode document includes footnotes, and you export to ODT, you get footnotes at the bottom of every page. For a journal submission, I need these to be endnotes. This is fairly easy in LaTeX export, but I can't find the switch for ODT export. I did find that I can manually edit the ODT in LibreOffice to move footnotes to "end of document," so I think I can do what I need by hand. But... would be nice if it could "just work." # Answer > If an org-mode document includes footnotes, and you export to ODT, you get footnotes at the bottom of every page. There are two ways to achieve this: ### Snippet 1: Use footnotes on OpenDocument side, but use custom styles to place the footnotes at the end of the document. ``` #+odt_extra_styles: <text:notes-configuration #+odt_extra_styles: text:note-class="footnote" #+odt_extra_styles: text:default-style-name="Footnote" #+odt_extra_styles: text:citation-style-name="Footnote_20_Symbol" #+odt_extra_styles: text:citation-body-style-name="Footnote_20_anchor" #+odt_extra_styles: text:master-page-name="Footnote" style:num-format="1" #+odt_extra_styles: text:start-value="0" text:footnotes-position="document" #+odt_extra_styles: text:start-numbering-at="document"/> Body text[fn:1][fn:2] * Footnotes [fn:1] Footnote one [fn:2] Footnote two ``` ### Snippet 2: Use actual endnotes on OpenDocument side ``` #+odt_endnote_regexp: . Body text[fn:1][fn:2] * Footnotes [fn:1] Footnote one [fn:2] Footnote two ``` The difference between the two snippets is this: 1. In the first snippet, an org-side footnote is mapped to a \`footnote' note-class on OpenDocument side. 2. In the second snippet, an org-side footnote is mapped to a \`endnote' note-cass on OpeDocument side. For more information see Add support for endnotes · Issue #74 Note that this feature is exclusive to the **fork** of OpenDocument exporter, i.e. this feature is **NOT** available in the standard Emacs or Org mode repositories. > 1 votes --- Tags: org-export, odt ---
thread-58792
https://emacs.stackexchange.com/questions/58792
How to search and replace in *open buffers*
2020-05-29T10:56:23.733
# Question Title: How to search and replace in *open buffers* I want to interactively search and replace in all (or, preferably, a regexp subset of) my *buffers* (**not files**). ## Scenario * Being a pack-rat sort of guy, I never delete my buffers until I'm sure I don't need them anymore (e.g. new project), or until the system crashes and I lose them. So I know that all the files I've modified (the targets of the search and replace) are in a buffer somewhere. * The files are strewn all over creation so I can't use `Dired`. * There are 10k files in scope, so I'd prefer to avoid file-based operations (*though I've already wasted so much time on this I've eclipsed the amount of time I would have saved not using the file-based approach*). ## What I'm doing now Right now I'm using `multi-occur-in-matching-buffers` and repeating a query replace for each matching file. *I'm told Icicles will do this, but reading the manual, I can't make heads or tails of how to do it. (I used `M-99 M-x icicle-search`; I get prompted for a "context", which I can't find a definition for in the manual and furnishes as a completion a list of previous mini-buffer entries, which doesn't make sense to me.) Icicles is far more than I need, but if I have to use it, I will.* ## Things I've tried * I tried `tags-query-replace` but it doesn't work; I always get zero matches, even though it ends bringing up a buffer with a match in plain sight. * I've read the FAQ (see responses above). I may end up having to use file-based operations (which are annoying because I have to find and reload each file manually) Since Icicles supposedly does what I want I thought I'd throw the question out. The other option is to use the Refactor facility in our IDE but that wouldn't be Emacs!! ❤ # Answer `Ibuffer` is what you're looking for. * `M-x ibuffer` * Mark your buffers any way you prefer: using `m` to mark them manually, `% g` by regexp content-matching, `* M` to mark by major mode, or whatever other option which suits your fancy -err needs. * Use `Q` to make a regexp search and replace on marked buffers or `I` for plain search and replace. * Do the replaces, then go back to ibuffer * `S` will save the marked buffers. There are more ways to achieve the same using other popular tools, but `ibuffer` is powerful, fit your needs, comes with emacs and can do a lot more than this pretty much effortlessly. To learn more about it, press `?` on a `ibuffer` buffer. > 5 votes --- Tags: buffers, search, icicles ---
thread-27060
https://emacs.stackexchange.com/questions/27060
Embed Image as Base64 on HTML export from Orgmode
2016-09-13T16:17:14.580
# Question Title: Embed Image as Base64 on HTML export from Orgmode The goal is to make a self-contained html file when exporting from orgmode so that the images are intrinsic to the file and a single html file will can be distributed (I am trying to do this for a class I teach and want to give students a single html they can open in a browser). I found a snippet of code on line that gives the idea of what I want: ``` #+BEGIN_SRC python :results output html :exports results with open('/home/britt/Pictures/Britt0001.jpg', 'rb') as image: data = image.read() print '<img src="data:image/jpg;base64,%s">' % data.encode("base64") #+END_SRC ``` And I am trying to get it into elisp and thus remove the dependancy on python and as a step to creating my own elisp function that could have some more detail. Here is what I have gotten to. Advice appreciated. ``` #+BEGIN_src elisp :results output html :exports results (setq myim (concat "<img src=\\"data:image/jpg;base64," (tob64 "/home/britt/Pictures/Britt0001.jpg") ">")) (print myim) #+END_SRC ``` and where `tob64` is ``` (defun tob64 (filename) (base64-encode-string (with-temp-buffer (insert-file-contents filename) (buffer-string)))) ``` This doesn't give the correct formatting and quoting. The goal to be worked toward is some variant of `org-html-export-to-html` where the elisp function could live and be invoked when an option like `#+OPTIONS: embed-images-on-html-export:t` was invoked. And as an aside, why doesn't the functionality of exporting to html with embedded images already exist in org-mode? Is there some bigger issue that makes this problematic for me to be working towards? # Answer See http://kitchingroup.cheme.cmu.edu/blog/2015/05/09/Another-approach-to-embedding-org-source-in-html/. You may also find this: https://github.com/KitchinHUB/kitchingroup-66/blob/master/manuscript.org#the-custom-export-code-labelexport-code an interesting way to encode base64 data in html. Your code works for me: ``` #+BEGIN_SRC emacs-lisp :results html :exports both (defun tob64 (filename) (base64-encode-string (with-temp-buffer (insert-file-contents filename) (buffer-string)))) (format "<img src=\"data:image/png;base64,%s\">" (tob64 "/Users/jkitchin/t.png")) #+END_SRC ``` outputs a base64 encoded image I can see in the export. To get this to work automatically in export, you probably want to use a function in org-export-before-processing-hook that will go through and replace your file links with an html block containing the output of a function like the one above. > 5 votes # Answer As an alternative, you can use the ox-pandoc package. Pandoc itself has a command line option called --self-contained which will embed images in html. To you use this for just the pandoc HTML5 exporter, by putting this in your .emacs: ``` (setq org-pandoc-options-for-html5 '((standalone . t) (self-contained . t))) ``` Also, you could have it for html4 instead/as well: ``` (setq org-pandoc-options-for-html5 '((standalone . t) (self-contained . t))) ``` Or to use --self-contained for all pandoc: ``` (setq org-pandoc-options '((standalone . t) (self-contained . t))) ``` Note that the `(standalone . t)` part is optional, I include only because this then replicates the defaults that pandoc has. You could remove it if you like, or replace it with your own set of options. Finally, you can do the same thing for a single file by using the header: `#+PANDOC_OPTIONS: self-contained:t` > 4 votes # Answer From the reddit thread https://www.reddit.com/r/orgmode/comments/7dyywu/creating\_a\_selfcontained\_html/ ``` (defun replace-in-string (what with in) (replace-regexp-in-string (regexp-quote what) with in nil 'literal)) (defun org-html--format-image (source attributes info) (progn (setq source (replace-in-string "%20" " " source)) (format "<img src=\"data:image/%s;base64,%s\"%s />" (or (file-name-extension source) "") (base64-encode-string (with-temp-buffer (insert-file-contents-literally source) (buffer-string))) (file-name-nondirectory source)))) ``` > 3 votes --- Tags: org-mode, images, html ---
thread-27620
https://emacs.stackexchange.com/questions/27620
orgmode, capturing original document title
2016-10-06T20:48:46.750
# Question Title: orgmode, capturing original document title I have a basic capture template: ``` ("a" "Article" entry (file+headline "~/GitLab/Reports/Bibliography/references.org" "Article") "* %^{Title} \n%?") ``` that asks you to fill the Title field. Now, my question is how to automatically fill this using the title of the original document (the original #+TITLE my title). One must certainly use *sexp* with something like: ``` ("a" "Article" entry (file+headline "~/GitLab/Reports/Bibliography/references.org" "Article") "* %(...some elisp instructions...) \n%?") ``` The problem is that I do not find/know a function returning the title. I mean: ``` ("a" "Article" entry (file+headline "~/GitLab/Reports/Bibliography/references.org" "Article") "* %(org-capture-get :original-file-nondirectory) \n%?") ``` fills with the original file name, but the equivalent for title: ``` %(org-capture-get :title) ``` does not exist. I also try, from an org-mode file: ``` #+TITLE: Titi Toto #+BEGIN_SRC emacs-lisp (plist-get (org-export-get-environment) ':title) #+END_SRC #+RESULTS: | Titi Toto | ``` but ``` (plist-get (org-export-get-environment) ':title) ``` does not work anymore when used in the capture template. Any help is welcome # Answer You need a function that collects the title of the original file (the file visited by the current buffer when org-capture was called). If you have `org-collect-keywords` (added in `b4e91b7e949`), you can use: ``` (defun get-title (file) (let (title) (when file (with-current-buffer (get-file-buffer file) (pcase (org-collect-keywords '("TITLE")) (`(("TITLE" . ,val)) (setq title (car val))))) title))) ``` Then, in the template, add: ``` %(get-title (org-capture-get :original-file)) ``` If you have an older version installed, replace `(pcase ...)` with: ``` (save-excursion (goto-char (point-min)) (when (re-search-forward "^[ \t]*#\\+title:[ \t]*\\(.*\\)$" nil t) (setq title (match-string 1)))) ``` > 2 votes # Answer org-roam has a function that does this here ``` (defun org-roam--extract-titles-title () "Return title from \"#+TITLE\" of the current buffer." (let* ((prop (org-roam--extract-global-props '("TITLE"))) (title (cdr (assoc "TITLE" prop)))) (when title (list title)))) (defun org-roam--extract-global-props (props) "Extract PROPS from the current org buffer. The search terminates when the first property is encountered." (let ((buf (org-element-parse-buffer)) res) (dolist (prop props) (let ((p (org-element-map buf 'keyword (lambda (kw) (when (string= (org-element-property :key kw) prop) (org-element-property :value kw))) :first-match t))) (push (cons prop p) res))) res)) ``` > 2 votes --- Tags: org-mode, org-capture ---
thread-58809
https://emacs.stackexchange.com/questions/58809
Why can't I directly invoke the result of apply-partially?
2020-05-30T10:52:41.660
# Question Title: Why can't I directly invoke the result of apply-partially? I'm confused about return value of `apply-partially`. Documentation states that it returns a function, and source of the function shows that it actually retruns a lambda. But I can't invoke the return value directly, only via `funcall`. Creating lambda directly at the call place allows me to invoke it directly. Here are three examples of what am I talking about: ``` ((apply-partially 'string-prefix-p ".") ".emacs") ;; => (invalid-function (apply-partially 'string-prefix-p ".")) ((lambda (x) (string-prefix-p "." x)) ".emacs") ;; => t (funcall (apply-partially 'string-prefix-p ".") ".emacs") ;; => t ``` Why is it working in such way? # Answer `((lambda ...) ...)` is a special case, and IIRC the *only* such special case. Lots of elisp functions return functions, and `apply-partially` is no different to any of the others in this regard. > source of the function shows that it actually returns a lambda Most functions are (ultimately) lambdas. See `C-h``i``g` `(elisp)What Is a Function` for details. `C-h``i``g` `(elisp)Function Indirection` might also be of interest. > 2 votes --- Tags: elisp, functions, apply ---