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-62644
https://emacs.stackexchange.com/questions/62644
Matching against variable keys in `cl-case`
2021-01-07T08:32:04.333
# Question Title: Matching against variable keys in `cl-case` In `cl-case` clauses (though naturally not the initial keyform), keys are apparently quoted: ``` (let ((mark ?.)) (case mark (mark 'mark) (?. ?.))) ; 46 (?.) (let ((mark ?.)) (case 'mark (mark 'mark) (?. ?.))) ; mark ``` My reading of neither the cl-lib manual nor CLHS entry for `case` describe this behavior. Is this the intended behavior of `cl-case`? If so, is this behavior documented? Is there a succinct way to match the keyform against a variable in a `cl-case` (as opposed to using a `cond`)? # Answer > 2 votes That behavior is actually described there, albeit in terse form: * "Macro: cl-case keyform clause...": `cl-case` is a macro, macros do not evaluate their arguments. * "This macro evaluates KEYFORM \[...\]": One of the arguments is evaluated, the rest aren't. * Therefore the key forms aren't evaluated. If you find yourself in that situation, just use `cond` and the appropriate equality predicate. To shorten matching for several keys, use `memq`, `memql`, `member` or `cl-find` with the `:test` keyword. In fact, I almost always use `cond` and only rarely resort to pattern matching constructs. --- Tags: conditionals, cl ---
thread-48767
https://emacs.stackexchange.com/questions/48767
How to delete ^M in the diffs of Magit?
2019-04-04T16:16:16.930
# Question Title: How to delete ^M in the diffs of Magit? I had an issue with a file that had inconsistent line ending. My file would show a `^M` for every line ending. I ran into this article that shows how to get rid of the `^M` character and set the buffer file encoding to fix the issue. However, I still see the `^M` character when I stage and commit my file in Magit. Magit show a file that has `^M` as a line ending character even when I fixed this in the file buffer. Do I need to make Magit aware of my file system encoding. If so, how? Issue seen in macOS Mojave and Emacs 26.1. # Answer > Do I need to make Magit aware of my file system encoding. If so, how? By configuring Git accordingly using `core.eol` and related variables described in git-config(1). By asking a search engine about "git end of file" you can find more information. One complication when it comes to Magit is that it may display diffs for multiple files in the same Emacs buffer. The eol encoding can only be set per buffer, not for a certain area of the buffer, so Magit doesn't even try to use the correct encoding and just assumes `lf`. > 3 votes # Answer You can configure magit to hide those trailing carriage return characters by setting `magit-diff-hide-trailing-cr-characters` to `t`. This is particularly useful when editing Windows files from a Linux system e.g. when using Emacs under WSL (Windows Subsystem for Linux) to manage a git repo that was setup from the Windows side. > 2 votes --- Tags: magit, character-encoding ---
thread-62635
https://emacs.stackexchange.com/questions/62635
How can I evaluate a Python buffer, switch to it, see its results, then switch back?
2021-01-06T16:40:52.507
# Question Title: How can I evaluate a Python buffer, switch to it, see its results, then switch back? Suppose, we have a buffer with Python code in it. I want to evaluate it, switch to Python buffer and see the results. Then easily switch back to code buffer. I tried the following: ``` (defun my-python-mode () (local-set-key (kbd "<kp-insert>") (lambda () (interactive) (elpy-shell-send-buffer-and-go) (elpy-shell-switch-to-shell-in-current-window) (let ((py-buffer (get-buffer "*Python*"))) (message (buffer-name py-buffer)) (if py-buffer (progn ; (other-window 1) (switch-to-buffer py-buffer) (end-of-buffer)))))))) ``` I added a callback to `kp-insert` but my function doesn't switch to python buffer when I click `kp-insert`. If there is no python buffer previously, it runs python interpreter, but doesn't switch to it. ``` (add-hook 'inferior-python-mode-hook (lambda () (local-set-key (kbd "<kp-add>") lambda () (interactive) message "aaa"))) ``` I tried this to switch back from interpreter, but it doesn't work. How can I set up an ergonomic python environment in Emacs? **Update 1** I created a function that splits the window, runs the code and switches to Python buffer. Unfortunately, when there is no Python buffer, it just splits the window, but doesn't switch to buffer and doesn't send my code to Python. So I have to click the key twice. Is it possible to fix this? ``` (defun aaa () (interactive) (if (= (length (window-list)) 1) (split-window-right)) (elpy-shell-send-buffer-and-step) (let ((py-buffer (get-buffer "*Python*"))) (other-window 1) (if py-buffer (progn (switch-to-buffer py-buffer) (end-of-buffer) )))) ``` # Answer > Suppose, we have a buffer with Python code in it. I want to evaluate it, switch to Python buffer and see the results. Then easily switch back to code buffer. It's unclear whether you're using a split window. I suggest doing that if you aren't (e.g. `split-window-right`). You can then use `other-window` (`C-x o`) to switch between windows. There are tons of packages to facilitate switching between windows (e.g. ace-window). For sending Python to the interpreter, I suggest using `elpy-shell-send-statement-and-step`. This will keep your point within the Python source code buffer. If your window is split with the Python interpreter in the adjacent window, you will see the output. > How can I set up an ergonomic python environment in Emacs? This is a super broad question. There are tons of Python related packages out there. You can check MELPA or browse Github. Personally, I just use `elpy` and roll the rest myself. For example, I use this function to switch to the most recently used window: ``` (defun my-switch-to-last-window () "Switch to the most recently used window. See URL `https://emacs.stackexchange.com/a/7411/15177'" (interactive) (let ((win (get-mru-window t t t))) (unless win (error "Last window not found")) (let ((frame (window-frame win))) (raise-frame frame) (select-frame frame) (select-window win)))) ``` > 2 votes --- Tags: buffers, elpy ---
thread-61495
https://emacs.stackexchange.com/questions/61495
What does =slug= means in the context of =org-roam=?
2020-10-31T09:36:47.397
# Question Title: What does =slug= means in the context of =org-roam=? I'm trying of configuring `org-roam-bibtex` (not there yet), but I keep finding this `${slug}` function, which I don't understand. See for example This post. What is it? What is its utility? # Answer There could be other uses that I'm not aware of, but slug is the text passed into the template system from your search. > 1 votes # Answer The *slug* is used to construct the filename. By default org-roam uses the title of the note, using the `org-roam--title-to-slug` function. A note titled =This is my note title!!= will be turned into the slug `"this_is_my_note_title"`, which has no spaces or exclamation marks in the filename. (I prefer dashes myself) In the post you link to, you can see how it constructs the filename by combining the slug with the timestamp `:file-name "literature/%<%Y-%m-%d-%H-%M-%S>-${slug}"` I hadn't seen the word *slug* used for this before but Wikipedia says it's the part of the URL that has human readable keywords. > 4 votes --- Tags: bibtex, org-roam ---
thread-62665
https://emacs.stackexchange.com/questions/62665
Partly delete a key sequence?
2021-01-08T17:20:54.360
# Question Title: Partly delete a key sequence? I'm relatively new to Emacs, so apologies if I'm using any terminology incorrectly. I have installed Doom Emacs in Evil mode, so command shortcuts are commenced with SPC instead of Meta. When entering a key sequence, a menu pops up to show me the available options for the next key (I believe this is provided by the `which-key` package). What I would like to be able to do is to go back a step if I haven't found what I'm looking for in the current "menu", rather than having to abort and start from the beginning with a new key chord. E.g.: I enter `SPC h d` (help -\> doom). How can I delete the `d` to return to the first level menu, as opposed to starting again with `ESC SPC h`? # Answer I have just found this from its Github page. https://github.com/justbur/emacs-which-key#paging-options Not one key but, If you press also for `C-h u` you can go for previous state. > which-key-undo can be used to undo the last key press when in the middle of a key sequence. > 3 votes --- Tags: keystrokes, which-key ---
thread-62647
https://emacs.stackexchange.com/questions/62647
What means Unmerged into origin/master in magit?
2021-01-07T13:03:16.500
# Question Title: What means Unmerged into origin/master in magit? In the magit buffer I see `Unmerged into origin/master`, yet I'm not noticing see any issues while merging with magit or with git on the commandline. Searching for the the subject brought me here\[0\], yet I don't understand it's meaning. Maybe someone can shed some light here for me. \[0\] https://magit.vc/manual/magit/Getting-Started.html # Answer As far as I know, that message means that you have commits in your local repository that hasn't been pushed in the remote repository. If you push your commits in the local repository, then you get away of that message. After reading your question, I created a commit in my dotfiles repository and I got that messaage (see image below). After pushing the commits (i.e. pressing `p u`) to the remote repository, that message disappeared (see image below). Note that in my remote repository, the most significant branch is `main`, that's why the message shows `origin/main` instead of `origin/master`. > 5 votes --- Tags: magit, git ---
thread-62670
https://emacs.stackexchange.com/questions/62670
Is there a tagged union/sum type in elisp? If not, what to use instead?
2021-01-09T02:28:14.283
# Question Title: Is there a tagged union/sum type in elisp? If not, what to use instead? In many programming languages, if one wants a variable that can take a discrete number of values, one has the capacity to define the permissible values in advance, using something like an enum. Does elisp have any functionality like that? My use case: I'm using the same configuration file across multiple computers. I'm reading an identifier from an environment variable, and I'd really like to store that in an elisp variable as a sum type, so that I can do something like ``` (cond ((eq which-computer home) (do-home-config)) ((eq which-computer office) (do-office-config)) (t (message "unknown computer"))) ``` where `which-computer` is a variable that can only take the values `home` and `office`. Is that a thing one can do in elisp? (I don't really know what to tag this question, since apparently using the elisp tag is, like, verboten.) # Answer > 1 votes Elisp variables aren't declared with a type. You can test a variable to determine the type of its current value; but if you're using `setq` or similar to assign values, then nothing prevents you from assigning values of arbitrary types to any given variable. `cl-deftype` and friends do allow you to define a custom type which allows a fixed set of values, and you can then use things like `cl-typep`, `cl-typecase`, `cl-etypecase`, and `cl-check-type` with that type; but I honestly don't think this is a useful complication for your particular use-case. You can read more about these from: `C-h``i``g` `(cl)Type Predicates` Personally I'm not sure you even need to be *storing* a variable at all, if this is your sole use-case for it. ``` (let ((computer (getenv "MY_COMPUTER_TYPE"))) (cond ((equal computer "home") (do-home-config)) ((equal computer "office") (do-office-config)) (t (message "unknown computer")))) ``` If you *were* going to store a variable, I'd probably use much the same approach. The following would result in a variable which was either `home` or `office` or `nil`. ``` (defconst my-computer-type (let ((computer (getenv "MY_COMPUTER_TYPE")) (allowed '("home" "office"))) (and (member computer allowed) (intern computer))) "Symbol for my computer type.") (cond ((eq my-computer-type 'home) (do-home-config)) ((eq my-computer-type 'office) (do-office-config)) (t (message "unknown computer"))) ``` --- Tags: variables, conditionals ---
thread-62661
https://emacs.stackexchange.com/questions/62661
Org Roam Database Missing
2021-01-08T09:49:12.263
# Question Title: Org Roam Database Missing Running Doom Emacs 2.0.9 on Emacs 27.1. I have in installation of org-roam with the following set-up: ``` (setq org-roam-directory "~/Documents/organize/org-mode") ``` FWIW, I use the same directory as my org directory: ``` (setq org-directory "~/Documents/organize/org-mode") ``` I have created a few notes with several backlinks and everything works as expected. One thing is bothering me, though. There is no trace of the database needed to run roam. Where should the roam database file be? In what name? # Answer > 4 votes The variable which you are looking is `org-roam-db-location` It's defined in `org-roam-db.el` ``` The full path to file where the Org-roam database is stored. If this is non-nil, the Org-roam sqlite database is saved here. It is the user's responsibility to set this correctly, especially when used with multiple Org-roam instances. References References in org-roam-db.el: (defcustom org-roam-db-location ...) 1 reference (defun org-roam-db ...) 3 references (defun org-roam-db-mark-dirty ...) 1 reference (defun org-roam-db--initialized-p ...) 1 reference (defun org-roam-db-clear ...) 1 reference (defun org-roam-db-build-cache ...) 1 reference ``` --- Tags: org-mode, doom, org-roam ---
thread-62673
https://emacs.stackexchange.com/questions/62673
Highlight current line in org-agenda
2021-01-09T08:35:53.197
# Question Title: Highlight current line in org-agenda Running Doom Emacs v2.0.9 on Emacs 27.1. In the agenda buffer, how do I get the current line highlighted? `global-hl-line-mode` is enabled and the current line in other buffers is highlighted as expected. However, agenda buffer does not show this highlighting. # Answer (add-hook 'org-agenda-finalize-hook #'hl-line-mode) > 2 votes # Answer Even you are using `global-hl-line-mode`. You have to still be sure local variables(Which can be different for different buffers) are correct. I have like that definition in my files. Reverse should be correct for you. ``` ;; Don' use globl-hl-line-in-org-agenda (add-hook 'org-agenda-mode-hook (lambda () (setq-local global-hl-line-mode nil))) ``` I highly recommend to use `helpful` package to see this variables in good format. > 0 votes --- Tags: org-mode, org-agenda, highlighting, hl-line-mode ---
thread-62678
https://emacs.stackexchange.com/questions/62678
nov-mode returns binary buffer and "File mode specification error: (error Invalid version syntax: ‘’ (must start with a number))"
2021-01-09T09:27:10.970
# Question Title: nov-mode returns binary buffer and "File mode specification error: (error Invalid version syntax: ‘’ (must start with a number))" When opening an epub file with Nov-mode I get a binary buffer in fundamental mode and an error message `File mode specification error: (error Invalid version syntax: ‘’ (must start with a number))`. This issue happens in ALL my epub files and was not present when I installed nov-mode from MELPA for the first time (something must have changed in a recent version). Here's a stack trace of the error when I use a org-link to access an epub file. ``` Debugger entered--Lisp error: (error "Invalid version syntax: ‘’ (must start with a number)") signal(error ("Invalid version syntax: ‘’ (must start with a number)")) error("Invalid version syntax: `%s' (must start with a number)" "") version-to-list("") version<("" "9.0") byte-code("\301\010\302\"\203\024\0\303\304\305\"\210\306\307\310\"\210\202\034\0\311\304\312\305\313\310%\210\301\207" [org-version version< "9.0" org-add-link-type "nov" nov-org-link-follow add-hook org-store-link-functions nov-org-link-store org-link-set-parameters :follow :store] 6) nov-mode() set-auto-mode-0(nov-mode nil) set-auto-mode() normal-mode(t) after-find-file(nil t) find-file-noselect-1(#<buffer my_ebookfile.epub> "/home/pathfiletothefile/my_ebookfile.epub" nil nil "/home/pathfiletothefile/my_ebookfile.epub" (30673310 66306)) find-file-noselect("/home/pathfiletothefile/my_ebookfile.epub" nil nil nil) find-file-other-window("/home/pathfiletothefile/my_ebookfile.epub") org-open-file("/home/pathfiletothefile/my_ebookfile.epub" nil) apply(org-open-file "/home/pathfiletothefile/my_ebookfile.epub" nil nil) org-link-open-as-file("/home/pathfiletothefile/my_ebookfile.epub" nil) org-link-open((link (:type "file" :path "/home/pathfiletothefile/my_ebookfile.epub" :format bracket :raw-link "/home/pathfiletothefile/my_ebookfile.epub" :application nil :search-option nil :begin 2077938 :end 2078198 :contents-begin 2078097 :contents-end 2078196 :post-blank 0 :parent (paragraph (:begin 2077938 :end 2078199 :contents-begin 2077938 :contents-end 2078199 :post-blank 0 :post-affiliated 2077938 :parent (item (:bullet "- " :begin 2077927 :end 2078199 :contents-begin 2077938 :contents-end 2078199 :checkbox on :counter nil :structure (... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...) :pre-blank 0 :post-blank 0 :post-affiliated 2077927 :tag nil :parent (plain-list ...))))))) nil) org-open-at-point(nil) funcall-interactively(org-open-at-point nil) call-interactively(org-open-at-point nil nil) command-execute(org-open-at-point) ``` This is my configuration of the mode ``` (use-package nov :ensure t :mode ("\\.epub\\'" . nov-mode) ) ``` and I am using version 20201207.3 on emacs 26.3. There are similar threads here and here but none deals with an invalid version syntax error. I can provide an epub file if necessary, but as I said, this happens in ALL the files in my library. Thank you in advance for any help. # Answer > 2 votes The reason this happens is because there is Org integration in nov.el that tries to use the recommended APIs and uses the value of `org-version` to figure that out. Granted, it's more robust to instead check for the existence of the APIs instead, I'll look into that instead. However, under no circumstances should `org-version` be an empty string, this means that your Org installation is broken, something you can verify with `M-x org-version`. I cannot reproduce your issue with a fresh install from Git: ``` $ git clone https://code.orgmode.org/bzg/org-mode.git $ cd org-mode $ make $ emacs --batch -L lisp -l org --eval '(princ org-version)' 9.4.4 ``` Even if I omit the `make` step, I get lots of warnings, but it ultimately prints out the correct version. Therefore something is seriously screwed up with your Org installation and you should look into fixing it. --- Tags: org-mode, package, error ---
thread-62684
https://emacs.stackexchange.com/questions/62684
Changing Breakpoint Icons in GDB
2021-01-10T02:21:26.773
# Question Title: Changing Breakpoint Icons in GDB So I've recently started using gud's `M-x gdb` instead of gdb on it's own, as it provides Emacs with some nice IDE features, mainly being able to see where you are in the code, and where you have set breakpoints. Emacs will place an image to the left of a line if a breakpoint has been set there, as seen here: What I would like to do is change that image, so that it's no longer a red circle and instead something a bit less... ugly... I did some digging into the code, and found what I think is where the icons are set/handled. In `lisp/progmodes/gdb-mi.el`, we have the following blocks: ``` (defconst breakpoint-xpm-data "/* XPM */ static char *magick[] = { /* columns rows colors chars-per-pixel */ \"10 10 2 1\", \" c red\", \"+ c None\", /* pixels */ \"+++ +++\", \"++ ++\", \"+ +\", \" \", \" \", \" \", \" \", \"+ +\", \"++ ++\", \"+++ +++\", };" "XPM data used for breakpoint icon.") (defconst breakpoint-enabled-pbm-data "P1 10 10\", 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 1 1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 1 1 1 0 0 0 1 1 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 1 1 1 0 0 0 1 1 1 1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 1 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0" "PBM data used for enabled breakpoint icon.") (defconst breakpoint-disabled-pbm-data "P1 10 10\", 0 0 1 0 1 0 1 0 0 0 0 1 0 1 0 1 0 1 0 0 1 0 1 0 1 0 1 0 1 0 0 1 0 1 0 1 0 1 0 1 1 0 1 0 1 0 1 0 1 0 0 1 0 1 0 1 0 1 0 1 1 0 1 0 1 0 1 0 1 0 0 1 0 1 0 1 0 1 0 1 0 0 1 0 1 0 1 0 1 0 0 0 0 1 0 1 0 1 0 0" "PBM data used for disabled breakpoint icon.") ``` Which I believe are the variable I want to change. However, these are in the Emacs sources and are declared with `defconst`, so what could I put in my `init.el` to be able to change these and have my icons look a bit nicer? Or at least be able to change their color. # Answer > 0 votes I have found the answer! Just below that code block, there are a couple declarations for you to use if you want to set your own icons: ``` (defvar breakpoint-enabled-icon nil "Icon for enabled breakpoint in display margin.") (defvar breakpoint-disabled-icon nil "Icon for disabled breakpoint in display margin.") ``` Using these, you can set the icons for enabled and disabled breakpoints to whatever you want. For example: ``` (setq breakpoint-enabled-icon '(image :type xpm :ascent 100 :pointer hand :data "/* XPM */ static char *magick[] = { /* columns rows colors chars-per-pixel */ \"10 10 2 1\", \" c #D78787\", \"+ c None\", /* pixels */ \"+++ +++\", \"++ ++\", \"+ +\", \" \", \" \", \" \", \" \", \"+ +\", \"++ ++\", \"+++ +++\", };")) ``` This'll keep the icon the same shape, but instead of the bright red it's a more toned down red. You could also change the icon's shape. For example, if you want a cross in the middle of your circle, you could do something like this: ``` (setq breakpoint-enabled-icon '(image :type xpm :ascent 100 :pointer hand :data "/* XPM */ static char *magick[] = { /* columns rows colors chars-per-pixel */ \"10 10 2 1\", \" c #D78787\", \"+ c None\", /* pixels */ \"+++ ++ +++\", \"++ ++ ++\", \"+ ++ +\", \" ++ \", \"++++++++++\", \"++++++++++\", \" ++ \", \"+ ++ +\", \"++ ++ ++\", \"+++ ++ +++\", };")) ``` --- Tags: gdb, gud, icons ---
thread-61746
https://emacs.stackexchange.com/questions/61746
Mercury mode colors
2020-11-15T10:33:38.817
# Question Title: Mercury mode colors I cannot get colors to work in `mercury-mode`. Mercury is supported under prolog-mode and in the source of prolog-mode there is quite a bit of it defined(eg. see below). ``` ;; Mercury specific patterns (types (if (eq prolog-system 'mercury) (list (regexp-opt prolog-types-i 'words) 0 'font-lock-type-face))) (modes (if (eq prolog-system 'mercury) (list (regexp-opt prolog-mode-specificators-i 'words) 0 'font-lock-constant-face))) (directives (if (eq prolog-system 'mercury) (list (regexp-opt prolog-directives-i 'words) 0 'prolog-warning-face))) ``` When I try using it, only face other than the `default` is the `font-lock-comment-face`. I am not familiar with writing or debugging emacs modes. How should I approach debugging this problem? If any one is using mercury-mode and got it working with colors please tell me how. # Answer Found the bug and fixed it here. > 0 votes --- Tags: faces ---
thread-41216
https://emacs.stackexchange.com/questions/41216
ffap.el currently ignores file path with whitespace. How can I change this behaviour?
2018-04-25T09:01:53.457
# Question Title: ffap.el currently ignores file path with whitespace. How can I change this behaviour? When I invoke ffap on the file path that include whitespace, such as "/path/to/dir name/filename.txt", ffap.el stop searching file path before the "/path/to/dir" part. I've checked the ffap.el, but there are many options and I couldn't find the appropriate configuration settings to change this behaviour, that trying to find proper file name beyond the whitespace character. What is the best settings not to ignore whitespace when ffap trying to find the file name that include white space? # Answer > 2 votes There are very good odds that `ffap` is already doing something like what you'd like, but it's hidden from you. Try calling `ffap` on one of your filepaths; when it offers you only a partial result, hit `C-i` or `TAB` (one is an alias of the other). For me, I'm offered a set of completions that include the paths containing spaces. "Use a different package" is seldom what folk hope to hear, but in this case, it might help. I use `helm` to view completions for most of my commands; when I call `ffap` on a file path with a space in the name, `helm` correctly shows me both a completion only up to the space, and completions past the space. This is a re-packaging of completion information already offered by `ffap`, but it's a lot easier to use and see. This is not to say you should use `helm` -- it's excellent, but also a bit of a commitment. My main suggestion is: `ffap` is probably already doing what you want, but in a hard-to-use way; a better completion system could fix that. # Answer > 0 votes Starting with Emacs-28 the following will do: ``` (setq ffap-file-name-with-spaces t) ``` Be aware that `ffap` is checking if the file or folder exists! So please don't check some arbitrary text.. I'm also recommending substituting some standard file bindings with ``` (ffap-bindings) ``` if you want the regular`find-file` behaviour you can revert to the original behaviour with the universal argument `C-u C-x C-f`. --- Tags: ffap ---
thread-62692
https://emacs.stackexchange.com/questions/62692
magit: squash commits in feature branch, but ability to unravel later if needed
2021-01-10T16:45:04.777
# Question Title: magit: squash commits in feature branch, but ability to unravel later if needed Does magit offer a way to squash a bunch of commits, but preserve some sort of record of the micro commits - should you need to step through them the next day. # Answer Just create a branch before squashing. In magit: 1. Optional: copy the name of the current branch (you can find it on the first line of the `*magit*` buffer). 2. `b n` to create a new branch. Paste the name of the current branch if it helps you, and give the new branch a unique name (e.g. with a `-detailed-history` suffix). (But better yet, don't squash. A detailed commit history is useful and squashing rarely has any benefit.) > 2 votes # Answer Magit does not provide any feature specifically for this use-case. It does however expose a `git` feature that can be used in this and other situations when you have to recover some discarded work: the reflog. The reflog commands are available from the same popup menu as the log commands: `l`. Search the web for information about what the reflog is and how to use it. While viewing a reflog you can use `l o RET` to view the *log* for the reflog entry at point. > 1 votes --- Tags: magit ---
thread-62695
https://emacs.stackexchange.com/questions/62695
How to make org-mode style links?
2021-01-10T17:45:44.133
# Question Title: How to make org-mode style links? I have a regular expression and an path, e.g. `("[Bb]ackup" . "/home/user/backup.org")`. Now I want every substring in the buffer that matches the regexp to look like an org-link and to be clickable so that a click opens the file. (I can't use actual org-links because it needs to work in non-org buffers as well.) I know about `make-button` but I'd like links to be created (or removed) dynamically as I type similar to syntax highlighting. `make-button` can't do that as far as I can see since you don't specify a regexp but the start and end point of the button in the buffer and you'd have to recalculate these yourself on each button press. `highlight-regexp` looks close to what I want but afaics it only allows me to apply faces, so it can't make clickable links. # Answer > 2 votes If you want a straight font-lock approach, I think this is what you want. ``` (defun next-notes (limit) (when (re-search-forward "[Nn]otes" limit t) (let ((map (make-sparse-keymap))) (define-key map [mouse-1] (lambda () (interactive) (find-file "~/notes.org"))) (set-text-properties (match-beginning 0) (match-end 0) `(local-map ,map mouse-face 'highlight help-echo "mouse-1: click me")) t))) (font-lock-add-keywords nil '((next-notes (0 'link t))) t) ``` You can also use button-lock-mode: ``` (cl-loop for (regex . path) in '(("[Cc]heatsheet" . "/Users/jkitchin/backup.org")) do (button-lock-register-global-button regex `(lambda (event) (interactive "e") (find-file ,path)) ;; I like to press return on functional text to activate it. :keyboard-binding "RET" ;; These are the rest of the properties :face (list 'link) :help-echo (format "Click me to open %s" path))) (button-lock-mode +1) ``` It works (lightly tested) I think. It is sort of tedious to debug, I am not sure if `(button-lock-clear-all-buttons)` actually clears everything, and had to restart emacs a few times while testing it. I wrote https://github.com/jkitchin/scimax/blob/master/scimax-functional-text.el sort of for this purpose. Hre is what it looks like. It feels a little clunky to use eval here, but it is a macro, and variables don't seem to expand in the call the right way. If anyone knows why or how to fix it, I would love to know. It has been a long time since I used this often, so it probably could use some attention. ``` (require 'scimax-functional-text) (cl-loop for (regex . path) in '(("notes" . "~/notes.org") ("[bB]ackup" . "~/backup.org")) do (eval `(scimax-functional-text ,regex ((find-file ,path)) :face '(link)))) (button-lock-mode +1) ``` --- Tags: org-mode, font-lock, text-properties, hyperlinks ---
thread-62687
https://emacs.stackexchange.com/questions/62687
Show only headers in outline mode when I open my dot emacs
2021-01-10T09:01:33.883
# Question Title: Show only headers in outline mode when I open my dot emacs I use `outline-minor-mode` to organize my .emacs file. I have this code at the end to activate it in the file: ``` ;;; Local Variables: ;;; eval: (outline-minor-mode 1) ;;; eval: (hide-body) ;;; outline-regexp: "^;;; " ;;; End: ``` When the file opens however, it shows all the contents, but I would like to see only the headings. How can I achieve this? # Answer I was using the incorrect function. Using `find-function` I discovered that the correct function is `outline-hide-subtree`. My dot emacs now has these local variables: ``` ;; Local Variables: ;; eval: (outline-minor-mode 1) ;; eval: (while (re-search-forward outline-regexp nil t) (outline-hide-subtree)) ;; outline-regexp: "^;;; " ;; End: ``` When I open my dot emacs now, only headings (with this form: `;;; HEADING:`) appear. Many thanks to @lawlist. > 1 votes --- Tags: init-file, outline-mode ---
thread-47900
https://emacs.stackexchange.com/questions/47900
Spacemacs keeps installing and uninstalling auctex-latexmk
2019-02-19T04:24:03.917
# Question Title: Spacemacs keeps installing and uninstalling auctex-latexmk Running spacemacs 0.200.13. Everytime I start spacemacs, it either installs auctex-latexmk or deletes it saying that it is an orphan package. Here is some more information: * I have latex layer enabled * I also have a private layer. But that does not have anything to do with latex or auctex What is going wrong here? How do I set things right? # Answer Try the fix given at https://github.com/syl20bnr/spacemacs/issues/8467#issuecomment-284254636 It fixed the issue for me, replacing just `latex` in the layers list with ``` (latex :variables latex-build-command "LatexMk") ``` `auctex-latexmk` gets installed and remains installed after this change. > 1 votes --- Tags: spacemacs, latex, auctex ---
thread-62699
https://emacs.stackexchange.com/questions/62699
How do I change the color of the menu bar in terminal Emacs?
2021-01-11T06:14:33.313
# Question Title: How do I change the color of the menu bar in terminal Emacs? I am using Emacs in a terminal. This is what the menu bar looks like: The menu bar has a white foreground and a black background. I want a green background with a pink foreground instead. Is there a way to do this? (Emacs version: GNU Emacs 25.2.2) # Answer > 0 votes To get a green background and a bold pink foreground for the menu bar, add this to your Emacs configuration: ``` (set-face-attribute 'menu nil :inverse-video nil :background "green" :foreground "pink" :bold t) ``` Result: # Answer > 1 votes Fonts and colors are assigned to faces, and faces are assigned to text in both the buffers and the UI. The text in the menu and menu popups uses the `menu` face, so if you run `M-x customize-face RET menu RET` you'll be able to change it to look how you want. --- Tags: terminal-emacs, colors, menu-bar ---
thread-61799
https://emacs.stackexchange.com/questions/61799
org-ref Error: org-ref-list-index: No catch for tag: --cl-block-nil--, 0 #813
2020-11-17T15:30:11.840
# Question Title: org-ref Error: org-ref-list-index: No catch for tag: --cl-block-nil--, 0 #813 On a fresh install of Emacs I am unable to get org-ref to produce citations in my pdfs. I simply get question marks and in Org PDF Latex Output I get a lot of `LaTeX Warning: Citation XXX on page XX undefined on input line XX.` Doing `C-c ]` works fine and so does `M-x org-ref`. However, if I run `M-x org-ref` after inserting a citation somewhere in the document, I get the following error: `org-ref-list-index: No catch for tag: --cl-block-nil--, 0`. So I wonder if that might have something to do with it. My org file (thesis.org) and bib file (bibliography.bib) are in the same folder. **Edit 1**: producing just the .tex file and then running pdflatex, then bibtex then two times pdflatex in terminal according to this answer works. Would still like to have org-ref work within Emacs. **Edit 2:** Running with the debugger, I get this Backtrace: ``` Debugger entered--Lisp error: (no-catch --cl-block-nil-- 2) throw(--cl-block-nil-- 2) org-ref-list-index("einstein" ("knuthwebsite" "latexcompanion" "einstein")) SOME CODE HERE THAT IS TOO LONG TO POST, LOOKS LIKE: #f(compiled-function (link) #<bytecode 0x174a8c1>)((link (:type "cite"... org-ref-bad-cite-candidates() org-ref() funcall-interactively(org-ref) call-interactively(org-ref record nil) command-execute(org-ref record) execute-extended-command(nil "org-ref" "org-ref") funcall-interactively(execute-extended-command nil "org-ref" "org-ref") call-interactively(execute-extended-command nil nil) command-execute(execute-extended-command) ``` * Org-ref version: 20201013.1427 * OS: Ubuntu 20.10 * Emacs version: 26.3 The output of `M-x org-ref` (when it does work) is: (I transcribed this from the screen, so please allow typos) ``` * Bibliography Using the bibtex files: (bibliography.bib) * Miscellaneous org-latex-prefer-user-labels = nil bibtex-dialect = BibTeX biblatex is not required. biblatex is not used. org-version = 9.4 completion backend = org-ref-helm-bibtex org-latex-pdf-process is defined as (%latex -interaction nonstopmode -output-directory %o %f %latex -interaction nonstopmode -output-directory %o %f %latex -interaction nonstopmode -output-directory %o %f) natbib is not required. natbib is not used. cleveref is not required. cleveref is not used. * Utilities Check buffer again ``` **thesis.org** ``` * Header Some text. cite:knuthwebsite bibliographystyle:unsrt bibliography:bibliography.bib ``` **bibliography.bib** ``` @article{einstein, author = "Albert Einstein", title = "{Zur Elektrodynamik bewegter K{\"o}rper}. ({German}) [{On} the electrodynamics of moving bodies]", journal = "Annalen der Physik", volume = "322", number = "10", pages = "891--921", year = "1905", DOI = "http://dx.doi.org/10.1002/andp.19053221004" } @book{latexcompanion, author = "Michel Goossens and Frank Mittelbach and Alexander Samarin", title = "The \LaTeX\ Companion", year = "1993", publisher = "Addison-Wesley", address = "Reading, Massachusetts" } @misc{knuthwebsite, author = "Donald Knuth", title = "Knuth: Computers and Typesetting", url = "http://www-cs-faculty.stanford.edu/\~{}uno/abcde.html" } ``` **init.el** ``` (require 'package) (add-to-list 'package-archives '("melpa" . "https://melpa.org/packages/") t) ;; Comment/uncomment this line to enable MELPA Stable if desired. See `package-archive-priorities` ;; and `package-pinned-packages`. Most users will not need or want to do this. ;;(add-to-list 'package-archives '("melpa-stable" . "https://stable.melpa.org/packages/") t) (package-initialize) (custom-set-variables ;; custom-set-variables was added by Custom. ;; If you edit it by hand, you could mess it up, so be careful. ;; Your init file should contain only one such instance. ;; If there is more than one, they won't work right. '(inhibit-startup-buffer-menu nil) '(inhibit-startup-screen t) '(package-selected-packages (quote (helm-swoop org-superstar org-brain org use-package tidal py-autopep8 org-bullets flycheck elpy)))) (custom-set-faces ;; custom-set-faces was added by Custom. ;; If you edit it by hand, you could mess it up, so be careful. ;; Your init file should contain only one such instance. ;; If there is more than one, they won't work right. ) ;; ------------------------------------------------------------- ;; org (add-hook 'org-mode-hook (lambda () (org-superstar-mode 1))) ;; ------------------------------------------------------------- ;; latex (require 'ox-latex) (add-to-list 'org-latex-classes '("mimosis" "\\documentclass{mimosis} [NO-DEFAULT-PACKAGES] [PACKAGES] [EXTRA]" ("\\chapter{%s}" . "\\chapter*{%s}") ("\\section{%s}" . "\\section*{%s}") ("\\subsection{%s}" . "\\subsection*{%s}") ("\\subsubsection{%s}" . "\\subsubsection*{%s}") ("\\mboxparagraph{%s}" . "\\mboxparagraph*{%s}") ("\\mboxsubparagraph{%s}" . "\\mboxsubparagraph*{%s}"))) ;; ------------------------------------------------------------- ;; org-ref (require 'org-ref) (setq reftex-default-bibliography '("~/test/bibliography.bib")) ;; see org-ref for use of these variables (setq org-ref-bibliography-notes "~/test/notes.org" org-ref-default-bibliography '("~/test/bibliography.bib") org-ref-pdf-directory "~/test/papers") (setq bibtex-completion-bibliography "~/test/bibliography.bib" bibtex-completion-library-path "~/test/papers" bibtex-completion-notes-path "~/test/helm-bibtex-notes") ;; ------------------------------------------------------------- ;; helm (require 'helm) (global-set-key (kbd "C-x C-f") 'helm-find-files) ;; helm-swoop (require 'helm-swoop) (global-set-key (kbd "M-i") 'helm-swoop) (global-set-key (kbd "M-I") 'helm-swoop-back-to-last-point) (global-set-key (kbd "C-c M-i") 'helm-multi-swoop) (global-set-key (kbd "C-x M-i") 'helm-multi-swoop-all) (define-key isearch-mode-map (kbd "M-i") 'helm-swoop-from-isearch) (define-key helm-swoop-map (kbd "M-i") 'helm-multi-swoop-all-from-helm-swoop) (setq helm-multi-swoop-edit-save t) (setq helm-swoop-use-fuzzy-match t) ``` # Answer > 1 votes I have pushed a lot of commits to fix issues like these in the last two weeks. The issues were due to differences in dolist, and cl-lib, etc. I think they are all working now. The answer is probably to update to the latest org-ref, and all the issues should go away. If not, I would consider it a bug in org-ref still and it would be helpful to report it at https://github.com/jkitchin/org-ref/issues. # Answer > 1 votes \[This is not an answer: it's more debugging suggestions to avoid a long comment thread\] I evaluated `(org-ref-list-index "einstein" '("knuthwebsite" "latexcompanion" "einstein"))` in 26.3 and I get `2` there as well: no error (I started with `emacs -q` and initialized the package system by hand in order to load org-ref which I installed from MELPA). Note that `org-ref-list-index` uses `dolist`.`dolist` in 26.3 is a macro that does not have any advice around it: please confirm with `C-h f dolist RET`. In 28.50.0 however, there is an advice: the doc string says: ``` dolist is a Lisp macro in ‘subr.el’. (dolist (VAR LIST [RESULT]) BODY...) Probably introduced at or before Emacs version 21.1. This macro has :around advice: ‘cl--wrap-in-nil-block’. Loop over a list. Evaluate BODY with VAR bound to each car from LIST, in turn. Then evaluate RESULT to get return value, default nil. ``` That sounds to me as if there is some incompatibility: it seems that somethings throws `--cl-block-nil--` but `dolist` does not catch it and you end up with the error. In a vanilla 26.3 system, nobody should throw that, but apparently somebody does in your setup. OTOH, in 28.50.0, `dolist` has an advice that I'm guessing adds a catch for that, presumably because somebody does throw it. So you seem to have something that throws that condition but a `dolist` that is incapable of catching it. BTW, this is mostly guesswork - just in case it wasn't clear :-) TODO: * try evaluating `(org-ref-list-index "einstein" '("knuthwebsite" "latexcompanion" "einstein"))` in your `*scratch*` buffer and see if you get the error. * try the same thing but with `emacs -q -l min-init.el` so as to avoid most of your initializations. You will still need something like this in your min-init.el: ``` (require 'package) (package-initialize) (require 'org-ref) ``` If you get the error with both of those, something would seem to be curdled in your installation: I would upgrade emacs and start from scratch. --- Tags: bibtex, org-ref ---
thread-61458
https://emacs.stackexchange.com/questions/61458
Show hover text of internal links in exported HTML in org-mode?
2020-10-29T01:00:20.050
# Question Title: Show hover text of internal links in exported HTML in org-mode? Is there a way to show hover text of internal links in exported HTML in org-mode? Sometime I would like to have a quick peek of the reference details of a `org-ref` citation link when reading the exported HTMLs of my notes. # Answer The best way is to define your own cite export function like this and then set it on the cite link. ``` (defun my-html-cite-export (keys desc format) (mapconcat (lambda (key) (format "<a class='org-ref-reference' href=\"#%s\" title=\"%s\">%s</a>" key (org-ref-format-entry key) key)) (org-ref-split-and-strip-string keys) ",")) (org-link-set-parameters "cite" :export #'my-html-cite-export) ``` This has some limitations, it only applies on cite links, and not the many other types of cite links, and it only supports html export. There isn't another way to do this at this time though. > 1 votes --- Tags: org-mode, org-export, org-ref ---
thread-62714
https://emacs.stackexchange.com/questions/62714
How do I remove all the trailing dashes in the mode line of terminal Emacs?
2021-01-11T20:28:19.407
# Question Title: How do I remove all the trailing dashes in the mode line of terminal Emacs? In terminal Emacs: Look at the mode line. Notice that there are lots of dashes (hyphen-minuses, to be precise) (`-----`) at the end of the mode line (after "(Lisp Interaction)"). How do I remove these dashes? These dashes only seem to appear in terminal Emacs but not in GUI Emacs. (I am using GNU Emacs 25.2 on Ubuntu 18.04 bionic beaver). # Answer It appears that the dashes are caused by the variable `mode-line-end-spaces`, which is the last item in `mode-line-format` by default. The default value of `mode-line-end-spaces` is `(:eval (unless (display-graphic-p) "-%-"))`, which explains why the dashes only appear in terminal Emacs but not in GUI Emacs. This seems to remove the dashes, but I'm not sure if there are any adverse side effects: ``` (setq-default mode-line-end-spaces nil) ``` This also seems to remove the dashes: ``` (setq-default mode-line-format (remove 'mode-line-end-spaces mode-line-format)) ``` Result: Perhaps someone more experienced with Emacs Lisp could comment on the validity of the methods above. > 4 votes --- Tags: terminal-emacs, mode-line ---
thread-46320
https://emacs.stackexchange.com/questions/46320
Is possible to execute sql query direct in org mode?
2018-11-29T17:09:49.707
# Question Title: Is possible to execute sql query direct in org mode? windows 10, emacs 26.1 I know that in org mode I can insert source code and **execute** them. Nice. But what about sql: Here in my.org file: ``` #+name: some_query #+BEGIN_SRC sql SELECT * FROM invoice WHERE id IN (1,2,3) #+END_SRC ``` Is it possible to execute query direct in org mode and get result? # Answer > 1 votes Yes. `ob-sql` is what I would use. Link to documentation with examples: https://orgmode.org/worg/org-contrib/babel/languages/ob-doc-sql.html You can specify your connection credentials directly as parameters of the source block: ``` #+begin_src sql :engine postgresql :dbhost HOSTNAME :dbuser USERNAME :dbpassword PASSWORD :database DBNAME SELECT * FROM TABLE LIMIT 100 #+end_src ``` The results are formatted as org-mode table in `RESULTS` block below after execution. You could also configure the credentials under a header with (source): ``` * some header that the sql source block will be in :PROPERTIES: :header-args+: :results table :header-args+: :engine mssql :header-args+: :dbhost 123.123.123.123 :header-args+: :database database-name-a :header-args+: :dbuser username-a :header-args+: :dbpassword password-a :END: ``` --- Tags: org-mode, sql ---
thread-8109
https://emacs.stackexchange.com/questions/8109
How can I build a regexp insensitive to case?
2015-02-09T21:14:35.873
# Question Title: How can I build a regexp insensitive to case? I have a bunch of keywords: * `set` * `write` * `quit` which each can be shortened down to one letter: * `s` `se` `set` * `w` `wr` `wri` `writ` `write` * `q` `qu` `qui` `quit` Further, these keywords are case-insensitive, so the following are added to the mix: * `s` `S` `se` `sE` `Se` `SE` ... * `w` `W` `wr` `wR` `Wr` `WR` ... * `q` `Q` `qu` `qU` `Qu` `QU` ... Given a list of the basic keywords `("set" "write" "quit")`, how can I create a regular expression that will match them as I describe? --- I've approached it by providing a list to `regexp-opt`, but the case-insensitivity list is proving hard to write. Here is what I have so far: ``` (defun mumps--command-variants (command &optional stack) "Returns the possible abbreviations of COMMAND. For example, input of \"set\" would yield the list \(\"s\" \"se\" \"set\")" (let ((case-insensitive-command-list (mumps--case-insensitize command)))) (if (= 1 (length command)) (cons command stack) (mumps--command-variants (substring command 0 (1- (length command))) (cons command stack)))) ``` ### Note on use-case This is going to be used to create font-lock keywords for a major mode for editing MUMPS code. MUMPS is an... interesting language: command names are case-insensitive (and can be abbreviated like this), but *everything* else in the language is case-sensitive (and cannot be abbreviated). Furthermore, there is no syntactical difference between a expression which uses a command and that which uses a function (a subroutine of commands), but one is case-insensitive/abbreviated and the other is not. # Answer After reading the comments in a previous answer, it appears that you would like to write a font-lock rule which would match one regexp without case, whereas the others would still be matched with a case. The easiest way to do this is to break out the matcher of the font-lock rule to a function, for example: Before: ``` ... (MY-REGEXP (0 font-lock-variable-name-face) (1 another-face) ...) ... ``` After: ``` (defun my-match-the-regexp (limit) (let ((case-fold-search t)) (re-search-forward MY-REGEXP limit t))) (my-match-the-regexp (0 font-lock-variable-name-face) (1 another-face) ...) ``` > 6 votes # Answer The docstring for `re-search-forward` says: > Search case-sensitivity is determined by the value of the variable `case-fold-search`, which see. Hence, you can set `case-fold-search` to `t`: > Documentation: Non-`nil` if searches and matches should ignore case. *EDIT* For font locking, you can set `font-lock-keywords-case-fold-search` to `t`: > Documentation: Non-nil means the patterns in `font-lock-keywords` are case-insensitive. This is set via the function `font-lock-set-defaults`, based on the CASE-FOLD argument of `font-lock-defaults`. > 4 votes # Answer I have exactly the same issue in a different language (but similarly odd, from the sound of it). Let's start with a single keyword to match: `"write"` You can build up a solution starting with the regular expression provided in this answer (or actually one of its comments) about matching a word and all initial substrings: ``` w(?:r(?:i(?:t(?:e)?)?)?)? ``` From this basic pattern, you can generate regular expressions for whatever keyword you need to match. To introduce case insensitivity as described, a quick modification including both lower- and upper-case for each letter is available: ``` [wW](?:[rR](?:[iI](?:[tT](?:[eE])?)?)?)? ``` From here the addition of word boundaries `\b` and some hideous escaping, we have a regular expression that's ready for deployment as a matcher in an element in font-lock-keywords: ``` (setq mumps-write-regex "\\b[wW]\\(?:[rR]\\(?:[iI]\\(?:[tT]\\(?:[eE]\\)?\\)?\\)?\\)?\\b") (setq mumps-font-lock-keywords `( (,mumps-write-regex . 'font-lock-keyword-face) ;; ...other matchers and faces here... )) ``` This should match all of the scenarios described in the question, with case insensitivity, but requires manual generation of the regular expression. --- As is explored in the question parts of this are also doable through `regexp-opt`, which should generate optimized regular expressions to match sequences of words, if combined with a bit of lisp: ``` ;; function to generate a list of initial substring (defun initial-substrings (word) (setq word (downcase word)) (cond ((> (length word) 0) (cons word (initial-substrings (substring word 0 -1) start))) (t '()) )) ;; generate a regular expression that matches that list (setq mumps-write-regex (regexp-opt (initial-substrings "write") 'words)) ⇒ "\\<\\(w\\(?:r\\(?:i\\(?:te?\\)?\\)?\\)?\\)\\>" ``` The generated regular expression closely resembles our initial case-sensitive regular expression, though it avoids the innermost `(?:e)?` and uses probably more proper boundary matching with `<` and `>`. To generalize this `regexp-opt` approach to case-insensitive matches, it can get a little out of control because one needs to generate all case-permuted versions of all of the strings and substrings. Instead, a better approach is to use this generated case-sensitive regular expression inside a matcher function -- as Lindydancer shows in another answer -- that sets `case-fold-search` to `t` just for that `font-lock-keywords` element: ``` ;; matcher function leveraging the generated regex with case insensitivity (defun mumps-write-matcher (limit) (let ((case-fold-search t)) (re-search-forward mumps-write-regex limit 'no-error))) ``` Putting it all together, a `regexp-opt` based approach that doesn't involve writing regular expressions manually is: ``` ;; function to generate a list of initial substring (defun initial-substrings (word) (setq word (downcase word)) (cond ((> (length word) 0) (cons word (initial-substrings (substring word 0 -1) start))) (t '()) )) ;; generate a regular expression that matches that list (setq mumps-write-regex (regexp-opt (initial-substrings "write") 'words)) ;; matcher function leveraging the generated regex with case insensitivity (defun mumps-write-matcher (limit) (let ((case-fold-search t)) (re-search-forward mumps-write-regex limit 'no-error))) ;; set the local font-lock-keywords variable (setq mumps-font-lock-keywords `( (,'mumps-write-matcher . 'font-lock-keyword-face) ;; ...other matchers and faces here... )) ``` --- Neither of the approaches above cover the question's original requirements about accepting a list of different keywords, all of which should be matched together in a case-insensitive fashion. At a minimum, you could craft a regex for each keyword and separate them with `\|` in the regular expression in either approach. In the `regexp-opt` aproach, using `append` to join the lists returned by `initial-substrings` prior to invoking `regexp-opt` should work. > 2 votes --- Tags: regular-expressions, programming ---
thread-62649
https://emacs.stackexchange.com/questions/62649
How to set a "#+SETUPFILE: .xxx.setup" as dir local?
2021-01-07T15:05:23.997
# Question Title: How to set a "#+SETUPFILE: .xxx.setup" as dir local? I need this line in every my org files. It's tedious to include it in everyone of them. # Answer > 1 votes Currently I'm capitalizing on the `org-export-before-parsing-hook`, which runs before the buffer is parsed by the back-end. dir-local.el ``` ((org-mode . ((org-export-before-parsing-hook . ((lambda (bach-end) (goto-char 0) (insert "#+SETUPFILE: ./assets/my-theme-readtheorg.setup\n"))))))) ``` It won't actually alter your file. For `org-export-before-parsing-hook` is risky, you may consider to add it to `safe-local-variable-values` to avoid Emacs's querying. --- Tags: org-mode, directory-local-variables ---
thread-31438
https://emacs.stackexchange.com/questions/31438
Possible not to use undo-tree in evil mode?
2017-03-13T09:15:13.097
# Question Title: Possible not to use undo-tree in evil mode? Every so often I run into bugs in undo-tree, where I can't redo, with the following: ``` primitive-undo: Unrecognized entry in undo list undo-tree-canary ``` Links to references to this issue: This is **really bad** and can cause loss of work if you didn't happen to save the newest version of the file. --- Since I never use the branching undo tree functionality, is it possible to use emacs linear undo with evil mode? --- Note: I've tried setting `(global-undo-tree-mode -1)` directly after `(evil-mode 1)` which disables undo tree, but redo (Ctrl-R) doesnt work after doing this. # Answer > 4 votes Since answering this question, `evil` now supports pluggable undo systems. So if you want to use undo-fu instead of undo-tree you can do this as follows. ``` (use-package evil :init (setq evil-undo-system 'undo-fu)) (use-package undo-fu) ``` Valid options for `evil-undo-system` include: * `undo-fu` the `undo-fu` package. * `undo-tree` the undo-tree package. * `undo-redo` for emacs-28's undo/redo support. # Answer > 8 votes The author of `undo-tree.el`, Toby Cubitt, is presently too busy to fix this particular bug. If he has time in the future, he may look into the issue further. The author has indicated that he has difficulty reproducing the error reliably, and was recently unable to reproduce it using the master branch. It only occurs when using undo/redo-in-region. The author suggests just turning off the undo/redo-in-region feature in the meantime. I would strongly encourage anyone who is motivated to come up with a reliable way to reproduce the issue starting from `emacs -q` using both the current stable release of Emacs (e.g., 25.2.1) and also with the most recent version of the master branch, and then submit those recipies to bug tracking number 16377 with carbon copies to the participants (Stefan, Toby, Barry, and Keith). The main tracking number is 16377, and there is a related tracking number 16523: https://debbugs.gnu.org/cgi/bugreport.cgi?bug=16377 https://debbugs.gnu.org/cgi/bugreport.cgi?bug=16523 Here is the workaround that turns off the `undo/redo-in-region` feature: ``` (setq undo-tree-enable-undo-in-region nil) ``` # Answer > 1 votes Apparently you can edit evil-pkg.el in ~/.emacs.d/elpa/evil-xxxxxxx/ dir and delete undo-tree as a requirement : ``` (define-package "evil" "20140109.605" "Extensible Vi layer for Emacs." '((goto-chg "1.6"))) ``` source # Answer > 1 votes Edit, this is now a package which can be used for undo/redo with evil-mode - undo-fu. --- Adding answer to own question since I've been using evil w/o undo-tree for some time now. This works surprisingly well to undo/redo which wraps emacs undo without anything heavy like `undo-tree` or `redo+`. ``` (global-undo-tree-mode -1) (defun simple-redo () (interactive) (let ( (last-command (cond ;; Break undo chain, avoid having to press Ctrl-G. ((string= last-command 'simple-undo) 'ignore) ;; Emacs undo uses this to detect successive undo calls. ((string= last-command 'simple-redo) 'undo) (t last-command)))) (condition-case err (progn (undo) t) (user-error (message "%s" (error-message-string err))))) (setq this-command 'simple-redo)) (defun simple-undo () (interactive) (let ( (last-command (cond ;; Emacs undo uses this to detect successive undo calls. ((string= last-command 'simple-undo) 'undo) ((string= last-command 'simple-redo) 'undo) (t last-command)))) (condition-case err (progn (undo-only) t) (user-error (message "%s" (error-message-string err))))) (setq this-command 'simple-undo)) ``` --- Tags: evil, undo, undo-tree-mode ---
thread-62727
https://emacs.stackexchange.com/questions/62727
How do I splat the arguments to the `or` function?
2021-01-12T07:24:30.993
# Question Title: How do I splat the arguments to the `or` function? I would like to evaluate a list of booleans like ``` (nil nil t) ``` into a single boolean, such that if any element is true, then the expression evaluates to true. I first looked at the `(or)` function in elisp, but it does not take a list of booleans as an argument. Instead it requires its arguments to be "un-wrapped" outside of a list. In other words, ``` (or (nil nil t)) ``` simply evaluates to the entire list `(nil nil t)` because it treats the it as a single argument. I would like something that instead evaluates exactly to `t`. - *I understand that `(nil nil t)` is truthy, but that's beside the point*. How can I convert `(or (nil nil t))` into just `(or nil nil t)` or just `t`? After some thought, I can think of ``` (eval (cons 'or '(nil nil t))) ``` but is there some other more idiomatic way that I'm missing? # Answer If you wanted this for a *function* you would use `apply`, but as `or` is a special form you can't do that. In particular, `or` only evaluates as many arguments as it needs to. You could write a macro: ``` (defmacro or-list (list) `(or ,@(eval list))) (setq mylist '(a b c)) ``` `(or-list mylist)` then expands to `(or a b c)` > 3 votes # Answer How about this? ``` (defun or-list (list) (cl-some #'identity list)) ``` Here `cl-some` takes two arguments: a predicate and a list and returns non-nil if the predicate applied to some member of the list is non-nil. In our case, the `identity` function is a good predicate since we only want to test whether our list members are themselves non-nil. > 2 votes --- Tags: conditionals, mapping, iteration, boolean ---
thread-62731
https://emacs.stackexchange.com/questions/62731
Changing the default binding to open a link in an org mode file using RET
2021-01-12T09:57:07.160
# Question Title: Changing the default binding to open a link in an org mode file using RET To open a link in an `org-mode` file one normally types `C-c C-o`. I find this rather cumbersome. I would like to rebind the command `org-open-at-point` to `RET` but *only* when the cursor rests on the link. I am *not* using `evil`. # Answer > 3 votes You just need to set ``` (setq org-return-follows-link t) ``` in your init file (or use the Customize interface to do the same). Check also `org-tab-follows-link` and `org-mouse-1-follows-link`. EDIT: Actually, do not change `org-tab-follows-link` \- just read its doc string with `C-h v org-tab-follows-link` and heed its pronouncements :-) --- Tags: org-mode, org-link, org-roam ---
thread-62713
https://emacs.stackexchange.com/questions/62713
org-reveal - change table font-size globally
2021-01-11T20:26:18.840
# Question Title: org-reveal - change table font-size globally I can use below code to change font size to 60%, how can I make it take effect for all tables? ``` #+REVEAL_HTML: <div style="font-size: 60%;"> | Name | Blueprint | | LOCAL_PRODUCT_MODULE | product_specific | | LOCAL_PROPRIETARY_MODULE | vendor_specific | | LOCAL_ODM_MODULE | device_specific | #+REVEAL_HTML: </div> ``` # Answer > 3 votes You can use this code to declare a style that will change table formatting globally: ``` #+begin_export html <style> .reveal td {font-size: 60%;} </style> #+end_export ``` Of course you can style `th` the same way if needed. --- Tags: org-mode, org-reveal ---
thread-50737
https://emacs.stackexchange.com/questions/50737
Force opening file in new buffer
2019-05-28T12:22:34.927
# Question Title: Force opening file in new buffer Is there a way in emacs to open a file (or a `dired` directory) in a new buffer, even if there's a buffer with the same file (or directory)? `find-file` and `find-alternate-file` always return the open buffer instead of creating a new one. EDIT: The use case I have is that I am using `dired-single` to navigate through directories using a single buffer (so that new directories are opened in the same buffer using `find-alternate-file`). However, if I have **two** separate buffers for two different directories (which I do when copying files from directory to another, for example) and I navigate in one buffer to the directory of the other, I end up with a **single** buffer and two frames. I would instead like to have two separate buffers showing the same directory. Much like what happens when I explore directories in my file explorer. # Answer > 1 votes You can do the following to create an arbitrary number of buffers visiting the same file: * Create a new buffer * Set its `buffer-file-name` to the desired file's path * Probably also call `rename-buffer` to match (this is cosmetic) * Revert the buffer Thusly created buffers differ from regular cloned buffers in that their contents is not shared. Thus, it can be used to e.g. see the file contents as it is on disk right now, as opposed to whatever is in the existing Emacs buffer. Putting it all together: ``` (defun revisit-file () "Open the file that the current buffer is visiting in a new buffer." (interactive) (let* ((fn buffer-file-name) (buf (create-file-buffer fn))) (with-current-buffer buf (setq buffer-file-name fn) (revert-buffer t t)) (switch-to-buffer-other-window buf))) ``` However, this approach doesn't work with dired buffers, as they're not literally visiting a file. Here, it is enough to trick `dired` into creating a new buffer by temporarily setting `dired-buffers` to `nil`: ``` (defun revisit-dired () "Open the directory that the current buffer is visiting in a new dired buffer." (interactive) (switch-to-buffer-other-window (save-window-excursion (let (dired-buffers) (dired default-directory))))) ``` --- Tags: buffers, dired ---
thread-10125
https://emacs.stackexchange.com/questions/10125
Can emacs support go to declaration of function in an entire project?
2015-03-19T02:12:38.837
# Question Title: Can emacs support go to declaration of function in an entire project? Does emacs have a function or library that can allow the user to go to the function declaration even if it was defined in another file? If so, what languages is there support for? The inspiration for this question, comes from the below article which talks about some of the reasons why emacs will never be able to compete with IDE's. http://henrikwarne.com/2012/06/17/programmer-productivity-emacs-versus-intellij-idea/ # Answer You can jump to any definition/reference of entire project as large as Linux kernel source tree (more than 36k) in an instant. See my C/C++ guide for details. For C/C++, I suggest using GNU Global that supports C, C++, Yacc, Java, PHP4 and assembly. The key is, if you want to have IDE features of a language, you have to install plugin of that language. Here are some packages for dynamic languages that I know of: * Live web development: skewer-mode. * Javascript: Tern. But before that, remember to install js2-mode. As for what `js2-mode` does, see the description; but in essence, `js2-mode` is a complete Javascript parser that generates an AST to do proper IDE features. If you install `skewer-mode` than you will have `js2-mode` by default, since `skewer-mode` depends on it. * Python: elpy, see the IDE features * Ruby: robe provides these features: > * Jump to method definition > * Jump to super or a constructor called at point > * Jump to a module or class (provided it has at least one method defined) > * Display method documentation > * Display information about method called at point using ElDoc > * Method and constant name completion You can also use `ctags` to support vast many languages such as shell script or Tcl... > 15 votes # Answer I ran into a similar issue with emacs, so I made Dumb Jump. I tried many of the solutions mentioned in the accepted answer, but I always ran into one or more of the following issues: * Solution only worked for a single programming language * Solution required an index (TAG) file or persistent process I badly wanted a solution that "just worked" and didn't require customization or setup. That is, I wanted to clone a random repo on Github and navigate around it like any other of my own projects. Right now Dumb Jump has basic support for: * JavaScript * Emacs Lisp * Python * Go * PHP * Ruby * Faust * R * Lua * Rust * ...and more It's available via MELPA and GitHub issues and PRs are more than welcome. > 24 votes # Answer The primary solution for this in emacs is using TAGS files, which are created by programs such as etags or gtags. I myself use (and recommend) exuberant ctags, and etags-select.el to help you narrow down destinations when the search symbol lies in multiple destinations. The supported languages are quite numerous, see the individual tools' manuals. There is even support for adding your own language, whereby you can provide a regular expression that instructs ctags how to isolate the tags you are interested in. > 5 votes # Answer You can probably achieve this (and MUCH more IDE-like features, like refactorization) with the neat a "language server" feature + lsp-mode https://vxlabs.com/2018/06/08/python-language-server-with-emacs-and-lsp-mode/ > 0 votes --- Tags: project, ide ---
thread-62736
https://emacs.stackexchange.com/questions/62736
Magit: rebase and push, basic questions
2021-01-12T13:38:14.120
# Question Title: Magit: rebase and push, basic questions I was learning magit and found this screenshot at Command to visit Github pull request of current branch with Magit: I was wondering why we have Rebase and Push (and not just Push) at the top. What would be the difference in pushing vs rebasing in this instance? Thanks! # Answer The upstream branch and the push-target are configured separately, that is why both values are displayed in the status buffer. These settings can point at the same branch, but for branches such as `master`, they tend to identify the same branch. See The Two Remotes to learn about the upstream and the push-target. (The upstream actually can be a local branch, which is why I talked about branches instead of remotes above.) See this qa for why the term "rebase" is used instead of "upstream". > 1 votes --- Tags: magit, git ---
thread-37887
https://emacs.stackexchange.com/questions/37887
Send region to shell in another buffer
2018-01-04T14:17:10.863
# Question Title: Send region to shell in another buffer Is this possible with stock emacs: I'm editing a `.txt` file that has a snippet of bash code When I do `C-x b RET` I can switch to a preopened `M-x shell` buffer named `guesuser@productionServerShellSession` I have the snippet of bash code selected in a `.txt` file. It's a multi line pipe command ending with `\` on each line. I often find myself copying the region, switching buffer and pasting and pressing enter to run the snippet in shell. Can this be made easier with fewer key strokes? What I did: Researched https://stackoverflow.com/questions/6286579/emacs-shell-mode-how-to-send-region-to-shell # Answer Emacs provides the function `process-send-region` to do this. If your buffer always has the same name, you can hard-code it in: ``` (defun my-send (beg end) (interactive "r") (process-send-region "guesuser@productionServerShellSession" beg end)) ``` The first line defines a new function, `my-send`, with two arguments, `beg` and `end`. The second line declares that this function is interactive, and will use the current region (that's what the "r" flag does). So when we call it, `beg` and `end` are filled with the start and end points of the active region. The last line sends that region to your shell. If you want to send the region to different buffers, you'll need to add some sort of logic to accommodate this. As a simple example, you could store your target buffer in a variable: ``` (defun my-set-target () (interactive) (setq my-target (buffer-name))) ``` Calling this command will store the current buffer name in the variable my-target. Modifying the original command: ``` (defun my-send (beg end) (interactive "r") (process-send-region my-target beg end)) ``` There are lots of ways you could smooth these out, to handle various errors (what if my-target hasn't been defined yet, or what if the region doesn't include a terminating newline, etc). But that should get you started. Actually, I've been wanting this for a while, so I made a more complete version: ``` (defun tws-region-to-process (arg beg end) "Send the current region to a process buffer. The first time it's called, will prompt for the buffer to send to. Subsequent calls send to the same buffer, unless a prefix argument is used (C-u), or the buffer no longer has an active process." (interactive "P\nr") (if (or arg ;; user asks for selection (not (boundp 'tws-process-target)) ;; target not set ;; or target is not set to an active process: (not (process-live-p (get-buffer-process tws-process-target)))) (setq tws-process-target (completing-read "Process: " (seq-map (lambda (el) (buffer-name (process-buffer el))) (process-list))))) (process-send-region tws-process-target beg end)) ``` > 7 votes # Answer * You can write a command that does all of that. Someone else here will no doubt give you code for that. * Or you can use a keyboard macro: just use `<f3>` and `<f4>` to record what you are already doing and `<f4>` to replay it. See the Emacs manual, node Keyboard Macros. * You can also simplify the part about recopying the region by using the *secondary selection*. It stays the same regardless of where the cursor is, until you change it on purpose. So you can paste/yank it any number of times, regardless of where you are. Press and hold **`M-`** (`Alt` key) while you use the mouse to select the text as the secondary selection. If you use library `second-sel.el` then you can use command `yank-secondary` (or `secondary-dwim`, for more flexibility) to yank (paste) the secondary selection. I bind it to **`C-M-y`**. See the Emacs manual, node Secondary Selection. * Another way to simplify the code-copying part is to put that code in a file and insert the file each time you need the code. **`C-x i`** (command `insert-file`) does that. See the Emacs manual, node Misc File Ops. > 2 votes # Answer This is a modification to Tyler's solution. It addresses two issues with the original: 1. When a process has no buffer, which I encountered for `emacs-server` and `ispell` processes, function `process-buffer` returns `nil`, which causes function `buffer-name` to return the name of the current buffer, which will never be what you want, and which will clutter your `completing-read` selection with as many copies of the current buffer as you have processes that lack buffers. 2. When no process buffers exist, a message to that effect should appear. Both Tyler's original solution and this modification work not only for `shell` buffers, but also for `term` and `ansi-term` buffers, with a small difference. For `shell` buffers, the region sent will not appear in the target buffer, but for `term` and `ansi-term` buffers, that text will appear. `(defun tws-region-to-process (arg beg end) "Send the current region to a process buffer. The first time it's called, will prompt for the buffer to send to. Subsequent calls send to the same buffer, unless a prefix argument is used (C-u), or the buffer no longer has an active process." (interactive "P\nr") (when (or arg ;; user asks for selection (not (boundp 'tws-process-target)) ;; target not set ;; or target is not set to an active process: (not (process-live-p (get-buffer-process tws-process-target)))) (let (procs buf) (setq procs (remove nil (seq-map (lambda (el) (when (setq buf (process-buffer el)) (buffer-name buf))) (process-list)))) (if (not procs) (error "No process buffers currently open.") (setq tws-process-target (completing-read "Process: " procs))))) (process-send-region tws-process-target beg end))` What remains missing from this answer, and from Tyler's original, is how to send a region to an `e-shell` buffer. As Tyler mentioned in the comments, `eshell` uses a different approach that would require a different solution. > 2 votes # Answer The philosopher's question, does Emacs extended through stock functions still constitute "stock emacs"? Here are a handful of functions for these kinds of tasks which rely only on stock Emacs (no dash, s, or whathaveyou). The idea works by defining an "on-demand window" and a setter function: ``` (defvar my-on-demand-window nil "Target on-demand window. An on-demand window is one which you wish to return to within the current Emacs session but whose importance doesn't warrant a permanent binding.") (defun my-on-demand-window-set () "Set the value of the on-demand window to current window." (interactive) (setq my-on-demand-window (selected-window)) (message "Set on-demand window to: %s" my-on-demand-window)) ``` With the window stored, you can do useful things like jump to it from anywhere: ``` (defun my-on-demand-window-goto () "Make `my-on-demand-window' current." (interactive) (let ((win my-on-demand-window)) (unless win (error "No on-demand window set! See `my-on-demand-window-set'.")) (if (eq (selected-window) my-on-demand-window) (error "Already in `my-on-demand-window'")) (let ((frame (window-frame win))) (raise-frame frame) (select-frame frame) (select-window win)))) ``` But more to your question, you can send a line or region to the on-demand window. It's set up here to insert the region, or the current line if no region is selected, followed by a `newline-and-indent`. You can modify the behavior after insert to your taste; remove `newline-and-indent` if you simply want to insert; use `comint-send-input` instead to press "RET" in a comint buffer (i.e. shell); use `eshell-send-input` to press "RET" in an eshell buffer; etc. ``` (defun my-send-line-or-region (&optional beg end buff) "Send region defined by BEG and END to BUFF. Use current region if BEG and END not provided. If no region provided, send entire line. Default BUFF is that displayed in `my-on-demand-window'." (interactive (if (use-region-p) (list (region-beginning) (region-end) nil) (list nil nil nil))) (let* ((beg (or beg (if (use-region-p) (region-beginning)) nil)) (end (or end (if (use-region-p) (region-end)) nil)) (substr (string-trim (or (and beg end (buffer-substring-no-properties beg end)) (buffer-substring-no-properties (line-beginning-position) (line-end-position))))) (buff (or buff (window-buffer my-on-demand-window)))) (if substr (with-selected-window my-on-demand-window (setq-local window-point-insertion-type t) (insert substr) (end-of-line) (newline-and-indent)) ; <-- change this line here for behavior "after insert" (error "Invalid selection")))) ``` I bind it to a key like F5: ``` (global-set-key (kbd "<f5>") '(lambda () (interactive) (progn (funcall 'my-send-line-or-region)))) ``` Although not stock, I would be remiss if I didn't mention `right-click-context`. The following binds the send region command to a mouse right-click context menu (less keystrokes, right? :). You can highlight a region with the mouse and immediately send it to the on-demand window: ``` (use-package right-click-context :config (right-click-context-mode 1) (add-to-list 'right-click-context-global-menu-tree '("Send region to on-demand-window" :call (my-send-line-or-region)))) ``` > 2 votes --- Tags: buffers, shell, region ---
thread-50881
https://emacs.stackexchange.com/questions/50881
Why AUCTeX/pdflatex show me help in Japanese?
2019-06-06T15:36:05.413
# Question Title: Why AUCTeX/pdflatex show me help in Japanese? I had this error message displayed to me by AUCTeX (already corrected using `\ddot{\boldsymbol x}`) ``` ERROR: Extra }, or forgotten $. --- TeX said --- <recently read> } l.51 \[ \boldsymbol M\ddot\boldsymbol x + \boldsymbol K\boldsymbol x = --- HELP --- 括弧または数式モードのデリミタが正しく対応していません.おそらく{・\[・ \(あるいは$のうちのいずれかを書き忘れたのでしょう. ``` Google's Translate says it's Japanese... In the `*scratch*` buffer I have ``` (getenv "LANG") "C.UTF-8" ``` I'm on Debian Sid with an updated Debian TeXLive and `auctex-12.1.2` installed with `elpa` What's going on? --- **Addendum** I had consistently the help message in Japanese using either `pdflatex` or `xelatex` or `luatex` while from the shell I had, in all cases, the help message in English. Both in Emacs and the shell I have `LANG` set to `C.UTF-8`. The problem was *solved* (so to say) restarting Emacs. In a new copy of Emacs, with a new instance of AUCTeX I have again the help messages in English. The strange behaviour I experienced is likely due to a casual interaction between the user and Emacs/AUCTeX and I don't expect that we can find what happened, on the other hand I don't want to remove the question but it's fine if you close it. # Answer > 1 votes A brute force search over the AUCTeX documentation points me to this node, of which the last paragraph says the following. > See ‘tex-jp.el’ for more information. Then I look at the source of `tex-jp.el` and find the following lines. ``` (defcustom japanese-TeX-error-messages t "*If non-nil, explain TeX error messages in Japanese." :group 'AUCTeX-jp :type 'boolean) ... (if japanese-TeX-error-messages (setq TeX-error-description-list '(("\\(?:Package Preview Error\\|Preview\\):.*" . "`preview'へ`auctex'オプションを直接与えるのは避けてください. プレビューの実行時以外でこのエラーが出た場合,余りにこみいったことを しすぎか,でなければAUCTeXがひどい失敗をしています.") ...) ``` We should probably set the variable `japanese-TeX-error-messages` to `nil` in the init file or using the Easy Customization Interface. Restart Emacs now and Japanese shall never appear again now. We should probably file an issue to the AUCTeX maintainer and this option should be set to `nil` by default instead of `t`. --- Tags: auctex, error-handling ---
thread-62745
https://emacs.stackexchange.com/questions/62745
How do I make a public reply to a particular post in an Emacs bug report?
2021-01-13T05:34:35.843
# Question Title: How do I make a public reply to a particular post in an Emacs bug report? I am looking at the thread of a particular Emacs bug report through the bug-gnu-emacs archives. Suppose I want to make a public reply to one of the posts in the thread. On the web page of the post, I see a button I can use to reply: If I click on the button, my email client will fill in the post author's personal email address in the "To" email field (e.g. `john.smith@example.com`). If I actually send the email, will the reply be made public? I want to make a public reply. How can I ensure that I am making a public reply? I thought that I have to send replies to `123456@debbugs.gnu.org` (where `123456` represents the bug report number), so do I need to add `123456@debbugs.gnu.org` to the "CC" field or something? # Answer Great question. I never noticed those buttons on the web page before. Yes, if you click that button it will open your mail client with only the person you're replying to in the `To` list. To have the mail also go to the bug list (for that bug thread) you need to also include the bug number in the `To` list (or the `Cc` list, I think), in this form: `12345@debbugs.gnu.org`, just as you guessed. --- You might even want to file an enhancement request to have the button also address the bug thread. (Using `M-x report-emacs-bug` might be sufficient for that, even though the web site is more general than just Emacs; dunno.) > 5 votes --- Tags: emacs-development ---
thread-62705
https://emacs.stackexchange.com/questions/62705
How to rearrange menu bar to show mode-specific items first
2021-01-11T13:53:16.910
# Question Title: How to rearrange menu bar to show mode-specific items first The Emacs menu bar places mode-specific menus after most of the default menu items, but before the "Help" menu\*. Specifically: "File", "Edit", "Options", "Buffers", "Tools", mode-specific menu items, "Help". For example: * Lisp Interaction mode: * Prolog mode: Is there a way to rearrange the menu items such that the mode-specific menu items always appear before all the other menu items? For example, in Lisp Interaction mode, I would like the "Lisp-Interaction" menu item to be the first menu item (i.e. appearing to before "File"). --- * The "Help" menu always appears last because of the variable `menu-bar-final-items` which is `'(help-menu)` by default. # Answer > 0 votes Change the value of the variable `menu-bar-final-items`: ``` (setq menu-bar-final-items '(file edit options buffer tools help-menu)) ``` Example results: * Lisp Interaction mode: * Prolog mode: The menu bar has been changed to show mode-specific menu items first. # Answer > 0 votes I do exactly that in Menu-Bar+ (code: `menu-bar+.el`. This is what I do, for that. First, I add a divider pseudo-menu: ``` (defvar menu-bar-divider-menu (make-sparse-keymap "Divider")) (define-key global-map [menu-bar divider] (cons "||" menu-bar-divider-menu)) (define-key menu-bar-divider-menu [menu-bar-divider-hint] '("<-- Current mode menus to left. || Common menus to right -->" . describe-menubar)) ``` Then I move all of the standard menus, plus a couple Menu-Bar+ menus, to `menu-bar-final-items`: ``` (setq menu-bar-final-items (append '(divider file edit options buffer tools search) (and (boundp 'menu-bar-frames-menu) '(frames)) (and (boundp 'menu-bar-doremi-menu) '(doremi)) '(help-menu) (and (fboundp 'show-tool-bar-for-one-command) '(pop-up-tool-bar)))) ``` You can click the divider, `\\`, to show help about the menu bar (command `describe-menubar`), which is this (it describes the predefined menus for Menu-Bar+): ``` (defun describe-menubar () "Explain the menu bar, in general terms." (interactive) (with-output-to-temp-buffer "*Help*" (princ (substitute-command-keys "To the right of the menu bar divider (\"||\") are the general menus that usually appear in every buffer. To the left of this symbol, there may also be additional menus that are specific to the buffer's mode \(use `\\[describe-mode]' for information on a buffer's mode). The general menus are as follows: Buffers File Tools Edit Frames Do Re Mi Help Use the \"Frames\" menu to resize, tile, and hide/show frames. Use the \"Do Re Mi\" menu to incrementally change things. The \"Help\" menu extends the \"Help\" menu described in the Emacs manual (`\\[info]'). For information on a menu item, use the \"This\" item in the \"Describe\" submenu of the \"Help\" menu.")) (if (fboundp 'help-print-return-message) (help-print-return-message) (print-help-return-message)) (with-current-buffer standard-output (help-mode) (buffer-string)))) ; Return the text we displayed. ``` Because local menus are added before `menu-bar-final-items`, then end up at the left of the menu-bar. So the effect is to have, from left to right: local menus, divider, non-local menus. --- Tags: menu-bar ---
thread-17872
https://emacs.stackexchange.com/questions/17872
Algorithm on deciding splitting vertically or horizontally
2015-11-05T13:01:46.193
# Question Title: Algorithm on deciding splitting vertically or horizontally When I do `M-x compile`, emacs will split my window to launch compilation and show its logs in a new window. As I understand, it has some algorithm to decide how to split the window. So, when I have just one window with code opened on my big monitor, for some reason, instead of more-convenient horizontal split (showing compile-log side-by-side on the right and code on left), it splits window vertically. How could that be tweaked? Thank you. # Answer > 6 votes The function that splits the window is `split-window-sensibly`, which can be tweaked by `split-width-threshold` and `split-height-threshold`, as Stefan suggested. Alternatively, you can tell Emacs to use a different function to split the window by setting `split-window-preferred-function` (the default is `split-window-sensibly`). For more details see `C-h v split-window-sensibly RET`. # Answer > 5 votes `C-h v split-width-threshold RET` should give you some useful info about that. There's also `split-height-threshold`, of course. # Answer > 1 votes I haven't found any answer to the original post, which I take to be: “How can I make sure that my window is always split horizontally, no matter what”, so here is what's worked for me: ``` (setq split-width-threshold nil) ``` It is strange that this works, as – according to the documentation of the variable `split-width-threshold` – this should have exactly the opposite effect: “If this is nil, ‘split-window-sensibly’ is not allowed to split a window horizontally.” So maybe this is a result of some bug, but it works for me, unlike other methods I tried. In particular, the following, suggested by the documentation of `split-window-sensibly`, ***does not* work** for me: ``` (setq split-height-threshold nil) (setq split-width-threshold 0) ``` HTH. P.S. My emacs version: GNU Emacs 26.3 (build 2, x86\_64-pc-linux-gnu, GTK+ Version 3.24.14) of 2020-03-26, modified by Debian --- Tags: window-splitting ---
thread-62580
https://emacs.stackexchange.com/questions/62580
Remove zombie buffers from recentf
2021-01-03T19:51:19.217
# Question Title: Remove zombie buffers from recentf I want to get rid of invalid recentf entries, that is buffers that no longer exist on disk, because I renamed or just plain deleted them ; I just did a `M-x recentf-cleanup` and apparently lost all my history :/ what would be a sure and safe way to clean this list up? # Answer `recentf-cleanup` shouldn't remove all your history. According to the documentation (`C-h f recentf-cleanup RET`): > recentf-cleanup is an interactive compiled Lisp function in ‘recentf.el’. > > (recentf-cleanup) > > Cleanup the recent list. That is, remove **duplicates**, **non-kept**, and **excluded files**. One can also edit recentf list manually with the following bit of elisp : ``` (delete "/the/file/you/want/to/remove.example" recentf-list) ``` (I'm not an expert, it may introduce bugs or there's probably a cleaner/more appropriate way to do it, I don't know. But it appears to work on my emacs.) Edit : There's also : `M-x recentf-edit-list RET` > recentf-edit-list is an interactive compiled Lisp function in \` recentf.el'. > > (recentf-edit-list) > > Show a dialog to delete selected files from the recent list. > 2 votes --- Tags: buffers, recentf ---
thread-45820
https://emacs.stackexchange.com/questions/45820
When to use quote for lists? Modifying quoted lists in Elisp
2018-11-07T13:37:40.063
# Question Title: When to use quote for lists? Modifying quoted lists in Elisp The Common Lisp Hyper Spec says: > The consequences are undefined if literal objects (including quoted objects) are destructively modified. This is further motivated at the Constant Modification Issue that lead to the corresponding clarification in the CL Spec.: > CLtL states that an implementation is permitted to "collapse" constants appearing in code to be compiled if they are EQUAL. This implicit sharing of compiled data structures may result in unpredictable behavior if destructive operations are performed. However, CLtL does not explicitly allow or disallow destructive operations on constants. Does Emacs Lisp have the same behavior/rules as Common Lisp in that aspect? In the Emacs Lisp Manual there are many examples where quoted lists are assigned to variables and afterwards modified. Section "Altering the CDR of a List" gives such an example: ``` > (setq x '(1 2 3)) => (1 2 3) (setcdr x '(4)) => (4) x => (1 4) ``` On the other hand there is a warning not to use quoted list as non-last element of `nconc` in the Emacs manual: > A common pitfall is to use a quoted constant list as a non-last argument to nconc. If you do this, your program will change each time you run it! Here is what happens: ``` (defun add-foo (x) ; We want this function to add (nconc '(foo) x)) ; foo to the front of its arg. (symbol-function 'add-foo) => (lambda (x) (nconc (quote (foo)) x)) (setq xx (add-foo '(1 2))) ; It seems to work. => (foo 1 2) (setq xy (add-foo '(3 4))) ; What happened? => (foo 1 2 3 4) (eq xx xy) => t (symbol-function 'add-foo) => (lambda (x) (nconc (quote (foo 1 2 3 4) x))) ``` Is there a complete list of correct rules when to use quoted lists and when not anywhere in the Elisp manual? Or are those examples in the Emacs manual even erroneous because they modify quoted lists? Maybe a question of itself: Is there a Spec for Elisp? --- An even more simple example for the modification of a function `add-foo` through the modification of its return value: (This is used in the discussion with Drew in the comments.) ``` (defun add-foo () '(1 2 3)) (setq x (add-foo)) (setq x (nconc x 4)) (add-foo) ``` The last statement gives `(1 2 3 . 4)`. # Answer The docstring for `quote` addresses when it should (and shouldn't) be used: > Return the argument, without evaluating it. ‘(quote x)’ yields ‘x’. > > Warning: ‘quote’ does not construct its return value, but just returns the value that was pre-constructed by the Lisp reader (see info node ‘Printed Representation’). > > This means that '(a . b) is not identical to (cons 'a 'b): the former does not cons. Quoting should be reserved for constants that will never be modified by side-effects, unless you like self-modifying code. See the common pitfall in info node ‘Rearrangement’ for an example of unexpected results when a quoted object is modified. (The common pitfall mentioned in ‘Rearrangement’ is the one quoted in the question.) As far as I can tell, no similar, broad-reaching statement is in the Emacs Lisp manual. The docstring suggests the `setcdr` example is if not erroneous (the behavior might be desirable), then at least potentially perplexing, as following it could lead to situations with results unexpected for those not aware of the breadth of this issue. The CONSTANT-MODIFICATION issue from the CLHS definitely applies. > 2 votes --- Tags: list, quote ---
thread-62744
https://emacs.stackexchange.com/questions/62744
How to set time to AM/PM for Org clocking?
2021-01-13T04:37:14.810
# Question Title: How to set time to AM/PM for Org clocking? Currently, clocking time format is this: ``` CLOCK: [2021-01-12 Tue 22:45]--[2021-01-12 Tue 23:23] => 0:38 CLOCK: [2021-01-12 Tue 16:29]--[2021-01-12 Tue 17:08] => 0:39 ``` Can I change this instead to the AM/PM 12-hour format that I have grown up with? I looked for the answer online, and I found this good question/answer as a reference: https://stackoverflow.com/questions/22720526/set-clock-table-duration-format-for-emacs-org-mode I am using org-version 9.3 and emacs-version 27.1. Apparently for org versions 9.1 and above: ``` (setq org-duration-format (quote h:mm)) ``` the above variable, `org-duration-format` is to be used. However, I cannot find documentation on how to change this to 12 hour AM/PM format. The equivalent in elisp string formatting would be `"%I:%M %p"`. However, `org-duration-format` does not accept string values. The online documentation for formatting time in elisp can be found here. # Answer Org mode uses ISO 8601 timestamps, so you cannot use the 12-hour AM/PM format as a storage format: Org mode files will always use the 24-hour format. However, you can change the *appearance* of a timestamp in an emacs buffer by using the variables `org-display-custom-times` and `org-time-stamp-custom-formats`. That is described in the Custom time format section of the manual. You lose some functionality by doing this, so it is important to read that section and understand the trade-offs. If you do decide to go ahead with it, you need to add something like this to your init file: ``` (setq org-display-custom-times t) (setq org-time-stamp-custom-formats '("<%m/%d/%y %a>" . "<%m/%d/%y %a %I:%M %p>")) ``` or use the Customize interface to set them. Reading the doc strings of these variables (e.g. `C-h v org-display-custom-times RET`) is *always* a good idea. If you only want it for some files, then don't set `org-display-custom-times` globally; just set `org-time-stamp-custom-formats` and then use ``` #+STARTUP: customtime ... ``` at the top of your Org mode file. > 1 votes --- Tags: org-mode, org-clock ---
thread-62547
https://emacs.stackexchange.com/questions/62547
How do I specify the window height of the Python interpreter?
2020-12-31T22:43:10.283
# Question Title: How do I specify the window height of the Python interpreter? Suppose I am editing a file in python-mode. If I start the Python interpreter using `M-x run-python` (or `C-c C-p`), the Python interpreter opens in a window (`*Python*`) in the bottom half of the frame. Is there a way to automatically set the height of the Python interpreter window? I don't want the interpreter to take up half the height of the frame. I want it to take up less than half of the frame height. # Answer You can use shackle, for example ``` (require 'shackle) (setq shackle-rules '(("*Python*" :align bottom :size 0.25))) ``` Or if you use `use-package` ``` (use-package shackle :ensure t :defer t :commands shackle-mode :config (setq shackle-rules '(("*Python*" :align bottom :size 0.25)))) ``` As you can see `:align` tells us where the buffer will appear and `:size` (between 0 and 1) lets you decide how much the frame it will take. > 0 votes --- Tags: python, window, comint, inferior-buffer ---
thread-62762
https://emacs.stackexchange.com/questions/62762
Source of "Pattern t is deprecated. Use `_' instead" message
2021-01-14T09:15:18.633
# Question Title: Source of "Pattern t is deprecated. Use `_' instead" message Loading a certain file (that shall remain nameless) generates the message: > Pattern t is deprecated. Use \`\_' instead No position information is given that would identify what expression generates the message. This looks to be from a library, rather than Emacs Lisp. What might be the source of this message (if possible to identify without source code)? # Answer > 1 votes `pcase` (part of cl-lib) generates this message when usage conforms to: ``` (pcase ... ... (t ...) ) ``` To address the message, replace `t` with `_` (which is special to `pcase`). ``` (pcase ... ... (_ ...) ) ``` --- Tags: warning, libraries ---
thread-62720
https://emacs.stackexchange.com/questions/62720
Open org link in the same window
2021-01-12T00:09:20.143
# Question Title: Open org link in the same window When I follow from one Org file to another via a link, the new file appears in alternative window if there is one. Is there a way to follow links staying in the same window? For example, I use a frame with two horizontally split windows. Left is for code, right is for docs in Org format. If I follow a link in the right window, the new Org file is opened on the left side, and I do not see the buffer with a code anymore. # Answer The behaviour for opening files is set in `org-link-frame-setup`. By default, the behaviour for opening files is `file-find-other-window`. The following two alternative commands will change that so that `find-file` is executed instead of `find-file-other-window`: ``` (setf (cdr (assoc 'file org-link-frame-setup)) 'find-file) ``` ``` (setf (cdr (rassoc 'find-file-other-window org-link-frame-setup)) 'find-file) ``` > 9 votes # Answer This works for me: ``` (setq org-link-frame-setup '((vm . vm-visit-folder-other-frame) (vm-imap . vm-visit-imap-folder-other-frame) (gnus . org-gnus-no-new-news) (file . find-file) (wl . wl-other-frame))) ``` The above code was automatically generated by Emacs when I customized the variable. I merely recast it using `setq`. > 7 votes --- Tags: org-mode, window ---
thread-62768
https://emacs.stackexchange.com/questions/62768
Effective concatenation
2021-01-14T13:08:15.493
# Question Title: Effective concatenation How can I concatenate two sequences of lists (either lists of lists or vectors of lists) in constant time (independent of their size)? # Answer > 2 votes I'm not sure you can avoid some size dependent time cost as you'll need to iterate over one list or the other to join them together. If you know your new list is shorter than the list you are adding to then you can just `push` them to the front: ``` (let ((l '(4 5 6 7)) (n '(2 3))) (cl-map 'nil (lambda (x) (push x l)) n) l) ==> (3 2 4 5 6 7) ``` That said I tend to favour the dash functions and just -concat: ``` (let ((l '(4 5 6 7)) (n '(2 3))) (-concat n l))) ``` which according to disassemble ends up with almost the same byte code but probably because it can optimise the simple example. --- Tags: optimization, sequences ---
thread-62754
https://emacs.stackexchange.com/questions/62754
How to customize the rendering of the straight lines in mode line?
2021-01-13T21:05:35.707
# Question Title: How to customize the rendering of the straight lines in mode line? Here are two examples of what I mean: 1. The lines are rendered in a different color as the background, so they are clearly seen: 2. The lines are rendered in the same color as the background, so they can not be seen: So, I would like to know how to tweak that, probably setting a face attribute. Whether to render it clearly or hide it. # Answer Following @lawlist advise, using `:box` attribute for `mode-line-inactive` made it. The mode lines images shown in the question are from inactive frames. The second image shows an inactive frame with a mode line that does not render the straight lines. Using: ``` (set-face-attribute 'mode-line-inactive nil :box t) ``` renders the straight line with foreground color: as it is indicated in Face Attributes section of Emacs Lisp manual. > 1 votes --- Tags: faces, mode-line, rendering, customize-face ---
thread-62758
https://emacs.stackexchange.com/questions/62758
How to use header-args variables to fill cell values of a table
2021-01-13T23:20:57.037
# Question Title: How to use header-args variables to fill cell values of a table I have an org-mode file as such: ``` * Header level 1 :header-args: :var filename="somefile.csv" ** Header level 2 :header-args: :var foo="bar" #+begin_src emacs-lisp foo #+end_src #+RESULTS: : bar | / | | | | | | | Datetime | Price | Attr | Note | |---+-------------------------+-------+-------+------| | | 2021-01-13 13:45:46 UTC | 12.4 | | | |---+-------------------------+-------+-------+------| #+TBLFM: @3$3=12.4 #+TBLFM: @3$4='(message "%S" foo) ``` I would like to be able to `C-c C-c` on the second formula and have "bar" written on the Attr cell for that entry. Is this possible using header-args? Thank you very much. # Answer Assuming you meant to define `header-args` in properties, as I suggested in a comment, you could * name the code block with `#+name: my-name` e.g. * then in order to use the value of the code block, you can execute the code block using `(org-sbe "my-name")`. Something like this: ``` * Header level 1 :PROPERTIES: :header-args: :var foo="somefile.csv" :END: ** Header level 2 :PROPERTIES: :header-args: :var foo="foobar" :END: #+name: my-name #+begin_src emacs-lisp foo #+end_src #+RESULTS: my-name : foobar | / | | | | | | | Datetime | Price | Attr | Note | |---+-------------------------+-------+--------+------| | | 2021-01-13 13:45:46 UTC | 12.4 | foobar | | |---+-------------------------+-------+--------+------| #+TBLFM: @3$3=12.4 #+TBLFM: @3$4='(org-sbe "my-name") ``` Read the doc string of `org-sbe` with `C-h f org-sbe`. Note that it is the name of the code block that matters: the name of the variable `foo` does not (it's a local variable of the code block, so it's not visible from the outside). EDIT: Here's a slight modification to deal with multiple variables. The assumption is that the code block returns a list of the values of the variables which are defined in the header. Then the table formula puts those values in successive rows in the third column: ``` * Header level 1 :PROPERTIES: :header-args: :var foo="somefile.csv" :END: ** Header level 2 :PROPERTIES: :header-args: :var foo="foobar" :var bar="barfoo" :END: #+name: my-name #+begin_src emacs-lisp :results drawer (list foo bar) #+end_src #+RESULTS: my-name :results: (foobar barfoo) :end: | / | | | | | | | Datetime | Price | Attr | Note | |---+-------------------------+-------+--------+------| | | 2021-01-13 13:45:46 UTC | 12.4 | foobar | | | | 2022-01-13 13:45:46 UTC | 13.4 | barfoo | | |---+-------------------------+-------+--------+------| #+TBLFM: @3$3=12.4 :: @4$3=13.4 #+TBLFM: @3$4..@>$4='(my-func (- @# 3)) ** code :noexport: #+begin_src emacs-lisp (defun my-func (n) (let ((x (read (org-sbe "my-name")))) (nth n x))) #+end_src ``` The `my-func` function basically does the "array" indexing: `org-sbe` returns the list as a string (unfortunately: that's a quirk of org-babel), so we invoke the lisp reader (`read`) to turn it back into a Lisp list and then we extract the n^th element of the list. The function is called with the row number of the cell minus 3 to make it 0-based. > 1 votes --- Tags: org-mode, variables, arguments, header-line ---
thread-62759
https://emacs.stackexchange.com/questions/62759
How do I make C-x b (switch-to-buffer) ignore some buffers?
2021-01-13T23:55:03.477
# Question Title: How do I make C-x b (switch-to-buffer) ignore some buffers? I want `C-x b` (i.e. `switch-to-buffer`) to ignore some buffers. For example, I want to ignore `*Ibuffer*`. In other words, when I press `C-x b`, I should not see `Switch to buffer (default *Ibuffer*):` . `*Ibuffer*` should be skipped. Is there a way to make `C-x b` ignore particular buffers? # Answer Command `switch-to-buffer` is designed to do just what it does. You can advise it to do something different, but typically if you want different behavior for a given key sequence then you are better off using a different command. (This is all the more true in the case of `switch-to-buffer`, which is used not only as a command, i.e., interactively, but from Lisp code in many places, including in the core Emacs code.) What you're interested in is the interactive part: the part that reads a buffer name from you. That's realized for `switch-to-buffer` by function `read-buffer-to-switch`. But that function is hard-coded to exclude only the current buffer. That function in turn is defined using function `read-buffer`, which, fortunately, offers more possibilities. You can define a command that uses `read-buffer` in a way that provides only the buffer-name choices you want, and then bind that command to `C-x b`. `C-h f read-buffer` tells you that there's a `PREDICATE` argument that filters the list of available buffers to present only some of them. Use that. This code reuses the `interactive` spec from `switch-to-buffer`, except that it uses `read-buffer` with a predicate that excludes buffer `*Ibuffer*`: ``` (defun my-switch-to-buffer (buffer-or-name &optional norecord force-same-window) "Switch to another buffer, besides `*Ibuffer*'." (interactive (let ((force-same-window (cond ((window-minibuffer-p) nil) ((not (eq (window-dedicated-p) t)) 'force-same-window) ((pcase switch-to-buffer-in-dedicated-window (`nil (user-error "Cannot switch buffers in a dedicated window")) (`prompt (if (y-or-n-p (format "Window is dedicated to %s; undedicate it" (window-buffer))) (progn (set-window-dedicated-p nil nil) 'force-same-window) (user-error "Cannot switch buffers in a dedicated window"))) (`pop nil) (_ (set-window-dedicated-p nil nil) 'force-same-window)))))) (list (read-buffer "Buffer: " (other-buffer (current-buffer)) (confirm-nonexistent-file-or-buffer) (lambda (name.buf) (not (string= "*Ibuffer*" (car name.buf)))))))) (switch-to-buffer buffer buffer-or-name norecord force-same-window)) (global-set-key (kbd "C-x b") 'my-switch-to-buffer) ``` > 2 votes --- Tags: buffers, interactive ---
thread-62774
https://emacs.stackexchange.com/questions/62774
Disable minor mode in specific major-modes or changing buffers (i.e. selectrum for prog-modes but not in shell)
2021-01-14T19:13:48.073
# Question Title: Disable minor mode in specific major-modes or changing buffers (i.e. selectrum for prog-modes but not in shell) This is similar to many other questions but nothing is leaping out.. I'm a fan of selectrum (similar to helm and ido I gather): e.g. hit `M-x` and start typing, it'll find matches and list them. I'd like `selectrum-mode` enabled during all modes (at least prog-modes), but not during a shell (`M-x shell`); I'm fine with a specific list of modes to disable it (i.e. enable for all, then disable selectively) or enable for specific modes, i.e. it's handy during non-prog to `find-file` for opening, but when in shell I want regular shell (bash/etc) based tab completion to occur. Simple enable of selectrum is: ``` (selectrum-mode +1) ``` But this is global in all modes, all the time, so the simpler tab-completion goes instead to selectrum. I tried putting it in an add-hook: ``` (add-hook 'prog-mode-hook 'selectrum-mode) ``` but this just enables it globally when first entering a prog-mode, I think; its not limited to prog modes. And really, I'd like it on all the time, barring some modes. The question is can selectrum be non-global at all, and even if it's a global-only minor mode, can it be toggled on and off automagically? Without changing `selectrum-mode`'s code to be non-global (if that's possible), I wonder if there's a way to enable/disable it selectively per mode. What is best practice? If it's global, could it be toggled on and off when toggling buffers? Perhaps a code fragment to hook switching buffers and disable as appropriate; i.e. on switch buffer, check if entering the list of modes, and then check if `selectrum-mode` is on, and then `(selectrum-mode -1)` if needed. This seems cumbersome and likely there is a more elegant approach. Your help is appreciated; always love to learn something! edit: Noticed there is a hook `buffer-list-update-hook` which might be usable, so perhaps I'll learn enough elisp to build the if-mode-active disable code, but I'm sure there's a much more elegant solution. # Answer > 1 votes Attempting answering my own question: **Try 1: partially works**, but as per comments below doesn't seem reliable Create a wrapper global mode, that is selective about when it enables. ``` (define-global-minor-mode my-global-selectrum-mode selectrum-mode (lambda () (when (not (memq major-mode (list 'shell-mode))) (selectrum-mode)))) (my-global-selectrum-mode 1) ``` **edit: Try 2:** Enable/disable the global minor mode on buffer changes ``` ;; turn selectrum on globally (selectrum-mode +1) ;; Turn off selectrum on first entry into a new comint-mode (shell) buffer. (add-hook 'comint-mode-hook (lambda () (selectrum-mode -1))) ;; Toggle selectrum after every buffer switch, avoiding the minibuffer. (add-hook 'buffer-list-update-hook (lambda () (unless (eq major-mode 'minibuffer-inactive-mode) (selectrum-mode (if (derived-mode-p 'comint-mode) -1 +1))))) ``` Stolen from: https://lists.gnu.org/archive/html/help-gnu-emacs/2018-07/msg00002.html --- Tags: completion, minor-mode ---
thread-62764
https://emacs.stackexchange.com/questions/62764
How to see the source code of a built-in function?
2021-01-14T10:00:17.473
# Question Title: How to see the source code of a built-in function? I want to see the source code of the function `other-buffer`. When I use `M-x`\- `xref-find-definitions`, Emacs shows:`visit tags table (default TAGS)`. Then I press `RET`, Emacs shows:`File /TAGS does not exist`. What should I do if I want to see the source code? I'm reading an introduction book and I got stuck with the expression: `(other-buffer (current-buffer) t)` This is why I want to see the source code. And this is my second day learning Emacs. System: macOS # Answer Unless you've compiled your Emacs you have to download the C source code separately. If you're on GNU, some distros allow downloading the source code using the package manager, which makes upgrading a bit easier. For example here's a tutorial for installing the source code on Fedora. Once you have the source code tree in a directory, say `~/src/emacs-27.1/src`, add ``` (setq find-function-C-source-directory (concat "~/src/emacs-" emacs-version "/src")) ``` to your init.el. The `(concat "~/src/emacs-" emacs-version "/src")` bit evaluates to `"~/src/emacs-27.1/src"` (assuming your Emacs is version 27.1), so you don't need to update this setting when you upgrade Emacs. The variable `find-function-C-source-directory` stores the directory Emacs looks into for the C source files (see `C-h``v` `find-function-C-source-directory`). --- Since you're on MacOS I can't suggest anything in particular but to try ``` git clone https://git.savannah.gnu.org/git/emacs.git ``` That should get you the full source tree. Place it on a directory of your choice and set `find-function-C-source-directory`, then both `xref-find-definitions` and links in `describe-function`/`describe-variable` (`C-h f`/`C-h v`) and should work. > 2 votes # Answer Usually the way to do that is to type M-x describe-function in the minibuffer, then enter other-buffer. That will show you a help window on the function with the documentation on that function. At the top is usually a link to the source code of the function you can click on to get there. `other-buffer` is implemented in the C source code though so you unless you installed emacs from source you probably can't get to it this way. > 2 votes --- Tags: source ---
thread-55824
https://emacs.stackexchange.com/questions/55824
What are the downsides of changing the syntax class of quotes in text-mode and backslash in AUCTeX?
2020-02-27T18:24:12.243
# Question Title: What are the downsides of changing the syntax class of quotes in text-mode and backslash in AUCTeX? It bothered me that sexp navigation commands didn't treat a quoted string as a single expression in text-mode. This is because the quote character `"` is in the punctuation syntax class in the text-mode syntax table. I decided to make it a string delimiter: ``` (modify-syntax-entry ?\" "\"" text-mode-syntax-table) ``` Similarly, I wanted sexp navigation commands in AUCTeX buffers to treat the initial backslash in a macro as part of the macro (as happens in the built-in latex-mode), so I changed the class of `\` to expression prefix: ``` (modify-syntax-entry ?\\ "'" LaTeX-mode-syntax-table) ``` Now, I've been told that modifying syntax tables is "dangerous" and can have "far-reaching unintended consequences", but I've been using those for months and so far I haven't noticed any consequences other than *improved* sexp navigation. So my question is: what can actually go wrong? A good answer would be a specific example of some text and some commands that have different outcomes with and without the syntax class change, where the outcome with the change is clearly inferior in some way. Is there any actual danger or is this just an abstract fear some people have? # Answer > 0 votes I'm relatively inexperienced with writing and modifying major modes, but I've messed around a little. I can't give a definitive answer as to why this happened, but I had some unexpected behavior while working on a major mode for a language in which comments can be initiated with `#n` (case-insensitive) and, notably, must be terminated with a semicolon. If a semicolon is omitted the comment runs through subsequent lines with the comment ending only once a semicolon is found. To get the desired highlighting behavior, I modified the syntax table like this: ``` (modify-syntax-entry ?# ". 1" st) ; sets comments to start with: (modify-syntax-entry ?n ". 2" st) ; #n or (modify-syntax-entry ?N ". 2" st) ; #N (modify-syntax-entry ?\; ">" st) ; and run until terminated by a semicolon! ``` This turned out to have some weird and unexpected consequences when leveraging regular expressions for setting font lock keywords later. In particular, it seemed like the letter "n" was no longer matched by `"\w"`. This, in turn, would cause `"font-lock-variable-name-face"` matches to begin mid-word on the letter `"n"`, so this assignment: ``` #var strange 10; ``` would get highlighted as if the variable name was `"nge"` with `"stra"` getting the the default face: The only way I could get things to work properly, while continuing to use `modify-syntax-entry` this way, was to avoid `"\w"` in regular expressions instead using `"[a-zA-Z0-9_]"` which still worked. Again I'm no expert at lisp or major modes -- and I certainly might've been doing something really stupid with my font lock keywords -- but that's at least one scenario where messing with `modify-syntax-entry` was dangerous, leading to clearly worse behavior. --- Tags: syntax-table ---
thread-62775
https://emacs.stackexchange.com/questions/62775
Issue with face heading for certain todo keyword in orgmode
2021-01-14T20:01:24.450
# Question Title: Issue with face heading for certain todo keyword in orgmode When I define todo keywords relative to "done" states, the formatting of the heading disappear as below Where should I start to look ? # Answer > 1 votes See `org-headline-done`. > Documentation: Face used to indicate that a headline is DONE. This face is only used if \`org-fontify-done-headline' is set. If applies to the part of the headline after the DONE keyword. IOW you have to set `org-fontify-done-headline` to nil. --- Tags: org-mode, faces, todo ---
thread-62788
https://emacs.stackexchange.com/questions/62788
Wait for result of fzf without blocking input
2021-01-15T15:07:48.487
# Question Title: Wait for result of fzf without blocking input I'm trying to make use of the fzf fuzzy finder to search through a list via a term process. The way I do this is very similar to fuzzy-finder.el or fzf.el. This is by launching fzf with: ``` (progn (advice-add 'term-handle-exit :after #'after-term-handle-exit) (switch-to-buffer (make-term "*fzf*" shell-file-name nil shell-command-switch "fzf")) (term-char-mode)) ``` This allows the user to type normally as if they were working with the fzf process directly. When the process exits, the selected value is parsed using the term-exit-handler by looking for the first line in the buffer beginning with " \>": ``` (defun after-term-handle-exit (proc-name msg) (let* ((lines (split-string (buffer-string) "\n")) (selects (-filter (lambda (s) (string-match-p "\s*>\s+" s)) lines)) (choice (string-trim-left (car selects) "\s*>\s+"))) (setq fzf-result choice))) ``` This all works fine and sets the variable `fzf-result` just fine but what I would like to do is make the `progn` wait for the process to finish and then return the result. Normally I think this would be fine because I could just spin until fzf-result is non-nil but in this case fzf needs input from the user (via emacs) and so such a method just results in a freeze. I know I could use a callback but I want to avoid this if at all possible. I was wondering if there is a way this could be achieved with threads? Or by explicitly passing keyboard inputs to the process? Thanks for any advice # Answer > 2 votes I think I have found a solution, although It's quite hacky. Basically, I use the following loop to pass key presses to the fzf process: ``` (while (null fzf-result) (command-execute (read-key-sequence nil))) ``` In the term exit handle I then set this variable, `fzf-result`, kill the buffer, and add one last key to the unread command events (this is to finally get it out of the loop): ``` (setq fzf-result choice) (kill-buffer) (setq unread-command-events (listify-key-sequence "\n")) ``` I can then return `fzf-result` as I like. Remembering to set it back to nil. --- Tags: term, async, fuzzy-search ---
thread-62760
https://emacs.stackexchange.com/questions/62760
Merge Columns Together in Org-Mode Tables
2021-01-14T04:28:47.037
# Question Title: Merge Columns Together in Org-Mode Tables Is there a way to merge columns together in an org-mode table? Often when I auto-create a table it will split certain fields into unnecessary columns. I would like a way to select those columns and then merge them together into one column. --- Example Input data: ``` Col1 Col2 Col3 a b longer data with spaces a b another bit ``` What I get: ``` |Col1|Col2|Col3 | | | | |a |b |longer |data|with|spaces| |a |b |another|bit | | | ``` Now imagine the same problem but with many rows that have extra columns on the end. I want a way to select `Col 3` and everything to the right and merge them together as one column. Eg: ``` |Col1|Col2|Col3 | |a |b |longer data with spaces| |a |b |another bit | ``` # Answer > 1 votes Could I suggest another approach: Prepare the text for easier conversion to a table. Look at the document string of `org-table-convert-region` to see what options and assumptions it has about field separator characters. First, select the table text and run interactively the `query-replace-regexp` command with arguments `+``<tab>`. That is "two or more spaces" to "a tab character". At the prompt, press `!` to replace all. Then, select the text again and run the command `org-table-convert-region` and you'll have your correctly formatted table in two easy steps. # Answer > 0 votes Here's a blow-by-blow account of the method I describe in the comments. We start with a table like this (it's better to have the spaces around each `|`, so I just realigned your table above with TAB to get that): ``` | Col1 | Col2 | Col3 | | | | | a | b | longer | data | with | spaces | | a | b | another | bit | | | ``` Now place the cursor *on* the top `|` character after "Col3", place the mark there with `C-<space>`, move the cursor to the bottom row between the `|` and the `b` of "bit"., You have now marked a rectangle of width one character that includes the whole column of `|`. Now kill the rectangle with `C-x r k`. We end up with a table like this: ``` | Col1 | Col2 | Col3 | | | | a | b | longer data | with | spaces | | a | b | another bit | | | ``` Now lather, rinse, repeat: Place the cursor on the `|` after "Col3", mark it with `C-<space>`, move the cursor to the space after the `|` in the same character column but on the bottom row of the table and kill that rectangle. You end up with this table: ``` | Col1 | Col2 | Col3 | | | a | b | longer data with | spaces | | a | b | another bit | | ``` Do the whole thing again with the remaining column of `|`. You end up with this table: ``` | Col1 | Col2 | Col3 | | a | b | longer data with spaces | | a | b | another bit | ``` You can, if you want, squash multiple spaces into a single space: select the table as a region in the usual way (place the cursor at the beginning of the table, set the mark with `C-<space>`, move the cursor to the end of the table) and then replace multiple spaces with a single space using a regexp: `M-C-% <space><space>* RET <space> RET !` (where I've made the spaces explicit: when you type the command, just press the space bar every time you see ). The final `!` says "replace all matches". That gives: ``` | Col1 | Col2 | Col3 | | a | b | longer data with spaces | | a | b | another bit | ``` Then realign the table with TAB and you are done: ``` | Col1 | Col2 | Col3 | | a | b | longer data with spaces | | a | b | another bit | ``` Once you have the keystrokes in your fingers, it goes fast. And although it's tedious for a table with many columns to be merged, it's not too bad. With only a little more effort, you can get a keyboard macro to do the rectangle killing, so all you have to do is move to the top `|` and execute the macro (the squashing of spaces and the final alignment are still done separately at the end). Further automation is possible but more complicated, so I'll stop here. # Answer > 0 votes An other approach is to get what you want with auto-create and an argument. Example Input data: ``` Col1 Col2 Col3 a b longer data with spaces a b another bit ``` `M-:` Eval: `(org-table-create-or-convert-from-region 2)` Just type (o-t-c-o-c and `TAB` 2) Gives you what you want: ``` | Col1 | Col2 | Col3 | | a | b | longer data with spaces | | a | b | another bit | ``` When you specify a number, use that many spaces, or a TAB, as field separator Shortcut: `C-u 2` `C-c |` # Answer > 0 votes You can delete all pipe char in a rectangle with this function : ``` (defun delete-pipe-char-in-rectangle (start end) "Delete all '|' in a rectangular region" (interactive "r") (kill-rectangle start end) (with-temp-buffer (yank-rectangle) (goto-char (point-min)) (while (search-forward "|" nil t) (replace-match "")) (kill-rectangle (point-min) (point-max))) (goto-char start) (yank-rectangle)) ``` If you find it handy, you can bind it to a key of your choice. for instance for a global binding ``` (bind-key "C-c m" #'delete-pipe-char-in-rectangle) ``` Or only in org-mode ``` (bind-key "C-c m" #'delete-pipe-char-in-rectangle org-mode-map) ``` (`bind-key' is a macro that come whith the` bind-key' package) --- Tags: org-mode, org-table ---
thread-62793
https://emacs.stackexchange.com/questions/62793
org-agenda jumps to the wrong month
2021-01-15T15:41:21.740
# Question Title: org-agenda jumps to the wrong month If I try to jump (using "j") in `org-agenda` to the month September, it sometimes takes me to January. I am using org 9.4.4. If I type any of these configurations, I am still going to January: ``` sept septe septem septemb septembe ``` If I type: ``` Sep sep September september ``` I go to September. Is this a bug? # Answer > 2 votes Following comments, it doesn't looks like a bug to me, `parse-time-months` contains "sep" and "september" nothing in between. If `org-read-date` cannot parse what you give defaults to current date (in use). As further reference Org manual says: > The function understands English month and weekday abbreviations. If you want to use un-abbreviated names and/or other languages, configure the variables parse-time-months and parse-time-weekdays So it is the expected behavior and I assume that there are some typos in the examples, either in the manual itself as well in the `org-read-date` docstring. --- Tags: org-mode, org-agenda, time-date ---
thread-46026
https://emacs.stackexchange.com/questions/46026
Turn on noweb references for all org buffers
2018-11-16T06:25:59.033
# Question Title: Turn on noweb references for all org buffers I want to use the noweb style references in Emacs org for literate programming. Consider the following working code. ``` #+NAME:Header #+BEGIN_SRC c++ #include <iostream> #+END_SRC Blah blah #+BEGIN_SRC c++ :tangle test.cpp :noweb yes <<Header>> int main (void) { std::cout << "Hello World" << std::endl; } #+END_SRC ``` I don't want to have to specify `:noweb yes` every time to expand noweb references since I will always be expanding them by default. How do I change my .emacs file to tell org mode this? # Answer > 4 votes There's an example for doing just what you are asking in the Org Manual: https://orgmode.org/manual/System\_002dwide-header-arguments.html#System\_002dwide-header-arguments Here it is for convenience: ``` This example sets :noweb header arguments to yes, which makes Org expand :noweb references by default. (setq org-babel-default-header-args (cons '(:noweb . "yes") (assq-delete-all :noweb org-babel-default-header-args))) ``` # Answer > 4 votes you can either set a global property on the top of the org file: ``` #+PROPERTY: header-args :noweb yes ``` or you can set a "tree node" property at any node level that is a parent of your src block: ``` * Parent Node :PROPERTIES: :header-args: :noweb yes :END: ``` Big warning: if you will want to add more of such properties either add them on the same line: ``` #+PROPERTY: header-args :noweb yes :result output ``` ``` * Parent Node :PROPERTIES: :header-args: :noweb yes :result output :END: ``` or use concatenation to accumulate your values (otherwise your property value will equal to the last entry: ``` #+PROPERTY: header-args :noweb yes #+PROPERTY: header-args+ :result output ``` ``` * Parent Node :PROPERTIES: :header-args: :noweb yes :header-args+: :result output :END: ``` Notice the use of `+` sign in order to concatenate and not overwrite # Answer > 1 votes Try setq `org-babel-default-header-args`. --- Tags: org-mode ---
thread-62796
https://emacs.stackexchange.com/questions/62796
Company mode won't autocomplete variables with underscores
2021-01-15T17:43:56.957
# Question Title: Company mode won't autocomplete variables with underscores I have web-mode and company installed but company just seems to autocomplete the variables without underscores: With Emacs Lisp Mode With Web-mode ``` ;; --- Company --- ;; Autocomplete with dropdown system (use-package company :ensure t :init :config (setq company-dabbrev-ignore-case t) (setq company-dabbrev-downcase nil) (setq company-idle-delay 0.2) (setq company-echo-delay 0) (setq company-minimum-prefix-length 2) (setq company-tooltip-minimum-width 110) (setq company-dabbrev-code-everywhere t) (setq company-dabbrev-code-modes t) (setq company-tooltip-align-annotations t) (setq company-selection-wrap-around t) (setq company-transformers '(company-sort-by-occurrence company-sort-by-backend-importance)) ;; (define-key global-map (kbd "C-.") 'company-files) (add-hook 'after-init-hook 'global-company-mode) (setq company-backends '((company-files company-yasnippet company-dabbrev company-keywords company-capf company-php ))) ) ``` # Answer In your setting of `company-backends`, don't use `company-dabbrev` in that group, use `company-dabbrev-code`. > 2 votes # Answer I found out the problem is not a company problem but the syntax of the mode. By default Emacs consider the underscores as a word separator so the variable new\_var are two words instead of one. To make Emacs consider new\_var as one word you have to change the syntax with a hook: ``` (add-hook 'web-mode-hook (lambda () (modify-syntax-entry ?_ "w"))) ``` > 1 votes --- Tags: company-mode, company ---
thread-62813
https://emacs.stackexchange.com/questions/62813
Adapt a function to work when windows are split only vertically
2021-01-16T10:55:57.233
# Question Title: Adapt a function to work when windows are split only vertically As @drew asked me to do here I'm asking one question per problem I'm trying to enable/disable visual-fill-column when there is one window/multiple windows. ``` (defun my-visual-fill-one-window () (global-visual-fill-column-mode -1) (if (one-window-p) (global-visual-fill-column-mode 1) (global-visual-fill-column-mode -1))) (add-hook 'window-state-change-hook 'my-visual-fill-one-window) ``` Could it be possible to adapt this function to work not when there's only one window but when they are just split vertically # Answer Try replacing `one-window-p` with `window-full-width-p`. > **Function: window-full-width-p *&optional window*** > > This function returns non-nil if *window* has no other window to the left or right in its frame, i.e., its total width equals that of the root window on that frame. If *window* is omitted or nil, it defaults to the selected window. https://www.gnu.org/software/emacs/manual/html\_node/elisp/Window-Sizes.html. > 1 votes --- Tags: window-splitting ---
thread-47878
https://emacs.stackexchange.com/questions/47878
How can I disable a specific lint error for Emacs Lisp using Flycheck?
2019-02-17T16:57:23.797
# Question Title: How can I disable a specific lint error for Emacs Lisp using Flycheck? In Python with flake8 we can do that with #noqa in the end of line. How the same can be done with Emacs Lisp? My ambition is to disable a particular lint error by just make a annotation with a comment like is provided in the above picture. This is possible in Emacs Lisp or there is a better way for it? # Answer Avoiding a specific flycheck decoration is not built-in but can easily be added. The flycheck overlays are generated by `flycheck-add-overlay` which is luckily only called via the hook `flycheck-process-error-functions`. Functions in that hook are run with a single arg -- the error -- until one of them succeeds. The strategy is to add a function in `flycheck-process-error-functions` in front of `flycheck-add-overlay` that returns `t` when the error should be ignored. That function can be added locally for buffers in `emacs-lisp-mode`. In the following example flycheck errors are ignored in `emacs-lisp-mode` if the line with the error ends in `;noflycheck`. You can add the code to your init file. ``` (defcustom flycheck-elisp-noflycheck-marker ";noflycheck" "Flycheck line regions marked with this marker string are ignored." :type 'string :group 'flycheck) (defun flycheck-elisp-noflycheck (err) "Ignore flycheck if line of ERR ends with `flycheck-elisp-noflycheck-marker'." (save-excursion (goto-char (cdr (flycheck-error-line-region err))) (looking-back flycheck-elisp-noflycheck-marker (max (- (point) (length flycheck-elisp-noflycheck-marker)) (point-min))))) (defun elisp-noflycheck-hook () "Add the ;;;###noflycheck thing to elisp." (require 'flycheck) (add-hook 'flycheck-process-error-functions #'flycheck-elisp-noflycheck nil t)) (add-hook 'emacs-lisp-mode-hook #'elisp-noflycheck-hook) ``` The application in your usage example would be like follows. ``` (require 'prelude-packages) ;noflycheck ``` > 4 votes # Answer In February 2020, the calculation method of the error region is refactored. The function `flycheck-error-line-region`is no longer available. > (goto-char (cdr (flycheck-error-line-region err))) Tobias's answer needs an update. ``` (goto-char (cdr (flycheck--exact-region err))) ``` > 1 votes --- Tags: flycheck ---
thread-62816
https://emacs.stackexchange.com/questions/62816
What techniques or functions can help manage hundreds of buffers?
2021-01-16T14:31:14.640
# Question Title: What techniques or functions can help manage hundreds of buffers? After several months of work, my Emacs easily accumulates 400 or 500 buffers. This makes restoring from `desktop-mode` irritatingly slow. I'd love to be able to delete buffers in bulk, ideally from the buffer list. For example, "mark for deletion every buffer associated with a file whose name matches regexp" or similar. But I can't find such a function, and looking at the way the buffer list is implemented, I can't figure out how to write one myself. What functions or techniques exist for managing a large number of buffers? # Answer I would activate electric-buffer-list and apply this small function : ``` (defun buffer-list-mark-for-deleting (rxp) "Mark all *Buffer Lines* lines matching the regexp RXP for deleting" (interactive "sRegexp to delete : " ) (with-current-buffer "*Buffer List*" (goto-char (point-min)) (while (search-forward-regexp rxp nil t) (Buffer-menu-delete)))) ``` For instance, the regexp "^ +\* \*\[hH\]elm" will mark all entry beginning with " * helm" or " * Helm" with the "D" letter. Selecting any non mark buffer will delete the marked ones. You can build much more complex regexps using re-builder and write some specific functions for your needs. Of course, you can bind this function to a key sequence according to your desire. > 2 votes --- Tags: buffers ---
thread-62817
https://emacs.stackexchange.com/questions/62817
Running slime in spacemacs
2021-01-16T15:51:07.180
# Question Title: Running slime in spacemacs I just installed a fresh spacemacs, and I'm trying to get SLIME working, but for some reason the package won't remain installed. After opening a new spacemacs ``` M-x package-install RET slime ``` This works fine and I'm able to `M-x slime` and evaulate my lisp code. However, when I close spacemacs and reopen it, slime is no longer there, and I must repeat these steps. I suspect it is because spacemacs isn't looking in the right spot for the slime package, but I'm not too familiar with how this works. Has anyone experienced this problem? # Answer > 1 votes I managed to answer this one myself. Since some spacemacs configuration seems to have been reseting or preventing a load containing slime, I decided to just git clone slime into a different directory outside of .emacs.d and do this: ``` ;; Setup load-path, autoloads and your lisp system ;; Not needed if you install SLIME via MELPA (add-to-list 'load-path "~/slime") (require 'slime-autoloads) (setq inferior-lisp-program "/usr/bin/sbcl") ``` This seems to have solved my issue. --- Tags: spacemacs, slime ---
thread-62824
https://emacs.stackexchange.com/questions/62824
How to investigate defmacro* (with asterisk) error on an old emacs package
2021-01-16T20:31:17.230
# Question Title: How to investigate defmacro* (with asterisk) error on an old emacs package I'm trying to load the defhook package without success. The code defines a macro using `defmacro*` (with the asterisk at the end), and I can't find any info about it. (The fact that the '\*' is ignored by search engines doesn't help either.) The code in question is as follows: ``` (defmacro* defhook (name (hook-sym &key (op 'add) (interactive-spec t) (append nil) (validate-hook-name t) (eval-after nil) (local nil) (hook-args nil)) &rest body) ... ``` And when I start Emacs with `--debug-init`, I get the following error: ``` Debugger entered--Lisp error: (void-function defmacro*) (defmacro* defhook (name (hook-sym &key (op 'add) (interactive-spec t) (append nil) (validate-hook-name t) (eval-after nil) (local nil) (hook-args nil)) &rest body) "Create a hook function and add it to the appropria..." nil (progn (or (not (null defhook-user-prefix)) (cl--assertion-failed '(not (null defhook-user-prefix)) nil (list (null defhook-user-prefix)) (list))) nil) (let* ((post-hook-action t) (post-defhook-action t) (our-name (symbolp name)) (our-local local) (our-append append) (our-op (cl-assert-rtn op (member op '(add delete no-op)) t)) (our-hook-sym (defhook-check-sym-syntax hook-sym "HOOK-NAME")) (our-hook-args hook-args) (tmp-int-spec interactive-spec) (our-int-spec (if (eq tmp-int-spec t) (interactive) tmp-int-spec)) (our-val-hook-name validate-hook-name) (our-eval-after (or eval-after 'simple)) (our-hook-name (cl-assert-rtn our-hook-sym (or (not our-val-hook-name) (string-match-p "-\\(hook\\|function\\|hooks\\|functions\\)$" (symbol-name our-hook-sym))) t)) (our-func-name (defhook-create-function-name (defhook-check-sym-syntax name "NAME") our-hook-sym)) (our-func-sym (intern our-func-name)) (began-in-hook (member our-func-sym (if (boundp our-hook-sym) (symbol-value our-hook-sym) (set our-hook-sym nil)))) (our-body body) (our-docstring (if (stringp (car our-body)) (progn (setq our-docstring (car-safe ...))))) (defhook-done-form (list 'defhook-done (list 'quote our-func-sym) (list 'quote our-hook-sym) (list 'quote our-op) (list 'quote began-in-hook) ''nil (list 'quote our-hook-args)))) (if :Comment-Ignore-Test-Code nil (defhook test1 (foo-hook) (message "foo-hook-test1") (message "foo-hook-test1 again")) (defhook test2 (foo-hook) (message "foo-hook-test 2"))) (cond ((eq 'no-op our-op) defhook-done-form) ((eq 'delete our-op) (remove-hook our-hook-sym our-func-sym) defhook-done-form) (t (remove-hook our-hook-sym our-func-sym) (let ((defhook-delayed-done-form (list ... ... ... ...)) (defhook-executed-form (list ... ... ...))) (list 'let (list (list ... ...)) (list 'eval-after-load (list ... our-eval-after) (list ... ...)) (list 'defhook-done (list ... our-func-sym) (list ... our-hook-sym) (list ... our-op) (list ... began-in-hook) 'pending-load (list ... our-hook-args)))))))) eval-buffer(#<buffer *load*-955329> nil "~/.emacs.d/org-status/defhook.el" nil t) ; Reading at buffer position 30747 load-with-code-conversion("~/.emacs.d/org-status/defhook.el" "~/.emacs.d/org-status/defhook.el" nil nil) load("~/.emacs.d/org-status/defhook.el") eval-buffer(#<buffer *load*> nil "~/.emacs.d/init.el" nil t) ; Reading at buffer position 1253 load-with-code-conversion("~/.emacs.d/init.el" "~/.emacs.d/init.el" t t) load("~/.emacs.d/init" noerror nomessage) startup--load-user-init-file(#f(compiled-function () #<bytecode 0x1ff01aa07dd1>) #f(compiled-function () #<bytecode 0x1ff01aa07de5>) t) command-line() normal-top-level() ``` Removing the asterisk from `defmacro` produces another error: ``` entered--Lisp error: (invalid-function (lambda (name (hook-sym &key (op 'add) (interactive-spec t) (append nil) (validate-hook-name t) (eval-after nil) (local nil) (hook-args nil)) &rest body) "Create a hook function and add it to the appropria..." (progn (or (not (null defhook-user-prefix)) (cl--assertion-failed '(not (null defhook-user-prefix)) nil (list (null defhook-user-prefix)) (list))) nil) (let* ((post-hook-action t) (post-defhook-action t) (our-name (symbolp name)) (our-local local) (our-append append) (our-op (cl-assert-rtn op (member op '...) t)) (our-hook-sym (defhook-check-sym-syntax hook-sym "HOOK-NAME")) (our-hook-args hook-args) (tmp-int-spec interactive-spec) (our-int-spec (if (eq tmp-int-spec t) (interactive) tmp-int-spec)) (our-val-hook-name validate-hook-name) (our-eval-after (or eval-after 'simple)) (our-hook-name (cl-assert-rtn our-hook-sym (or (not our-val-hook-name) (string-match-p "-\\(hook\\|function\\|hooks\\|functions\\)$" ...)) t)) (our-func-name (defhook-create-function-name (defhook-check-sym-syntax name "NAME") our-hook-sym)) (our-func-sym (intern our-func-name)) (began-in-hook (member our-func-sym (if (boundp our-hook-sym) (symbol-value our-hook-sym) (set our-hook-sym nil)))) (our-body body) (our-docstring (if (stringp (car our-body)) (progn (setq our-docstring ...)))) (defhook-done-form (list 'defhook-done (list 'quote our-func-sym) (list 'quote our-hook-sym) (list 'quote our-op) (list 'quote began-in-hook) ''nil (list 'quote our-hook-args)))) (if :Comment-Ignore-Test-Code nil (defhook test1 (foo-hook) (message "foo-hook-test1") (message "foo-hook-test1 again")) (defhook test2 (foo-hook) (message "foo-hook-test 2"))) (cond ((eq 'no-op our-op) defhook-done-form) ((eq 'delete our-op) (remove-hook our-hook-sym our-func-sym) defhook-done-form) (t (remove-hook our-hook-sym our-func-sym) (let ((defhook-delayed-done-form ...) (defhook-executed-form ...)) (list 'let (list ...) (list ... ... ...) (list ... ... ... ... ... ... ...)))))))) (lambda (name (hook-sym &key (op 'add) (interactive-spec t) (append nil) (validate-hook-name t) (eval-after nil) (local nil) (hook-args nil)) &rest body) "Create a hook function and add it to the appropria..." (progn (or (not (null defhook-user-prefix)) (cl--assertion-failed '(not (null defhook-user-prefix)) nil (list (null defhook-user-prefix)) (list))) nil) (let* ((post-hook-action t) (post-defhook-action t) (our-name (symbolp name)) (our-local local) (our-append append) (our-op (cl-assert-rtn op (member op '...) t)) (our-hook-sym (defhook-check-sym-syntax hook-sym "HOOK-NAME")) (our-hook-args hook-args) (tmp-int-spec interactive-spec) (our-int-spec (if (eq tmp-int-spec t) (interactive) tmp-int-spec)) (our-val-hook-name validate-hook-name) (our-eval-after (or eval-after 'simple)) (our-hook-name (cl-assert-rtn our-hook-sym (or (not our-val-hook-name) (string-match-p "-\\(hook\\|function\\|hooks\\|functions\\)$" ...)) t)) (our-func-name (defhook-create-function-name (defhook-check-sym-syntax name "NAME") our-hook-sym)) (our-func-sym (intern our-func-name)) (began-in-hook (member our-func-sym (if (boundp our-hook-sym) (symbol-value our-hook-sym) (set our-hook-sym nil)))) (our-body body) (our-docstring (if (stringp (car our-body)) (progn (setq our-docstring ...)))) (defhook-done-form (list 'defhook-done (list 'quote our-func-sym) (list 'quote our-hook-sym) (list 'quote our-op) (list 'quote began-in-hook) ''nil (list 'quote our-hook-args)))) (if :Comment-Ignore-Test-Code nil (defhook test1 (foo-hook) (message "foo-hook-test1") (message "foo-hook-test1 again")) (defhook test2 (foo-hook) (message "foo-hook-test 2"))) (cond ((eq 'no-op our-op) defhook-done-form) ((eq 'delete our-op) (remove-hook our-hook-sym our-func-sym) defhook-done-form) (t (remove-hook our-hook-sym our-func-sym) (let ((defhook-delayed-done-form ...) (defhook-executed-form ...)) (list 'let (list ...) (list ... ... ...) (list ... ... ... ... ... ... ...)))))))(defhook-emacs-startup-hook-monitor (emacs-startup-hook) "Used by `defhook-startup' to determine if `emacs-s..." (setq defhook-emacs-startup-hook-monitor t)) (defhook defhook-emacs-startup-hook-monitor (emacs-startup-hook) "Used by `defhook-startup' to determine if `emacs-s..." (setq defhook-emacs-startup-hook-monitor t)) eval-buffer(#<buffer *load*-549255> nil "~/.emacs.d/org-status/defhook.el" nil t) ; Reading at buffer position 31058 load-with-code-conversion("~/.emacs.d/org-status/defhook.el" "~/.emacs.d/org-status/defhook.el" nil nil) load("~/.emacs.d/org-status/defhook.el") eval-buffer(#<buffer *load*> nil "~/.emacs.d/init.el" nil t) ; Reading at buffer position 1253 load-with-code-conversion("~/.emacs.d/init.el" "~/.emacs.d/init.el" t t) load("~/.emacs.d/init" noerror nomessage) startup--load-user-init-file(#f(compiled-function () #<bytecode 0x1fe411c5883d>) #f(compiled-function () #<bytecode 0x1fe411c58851>) t) command-line() normal-top-level() ``` Do you have any pointers to fix this? # Answer > 1 votes Add this line to your init file or to the beginning of the old package: ``` (require 'cl) ``` --- Emacs Lisp is a dialect of the Lisp language family. Common Lisp is another dialect of Lisp with more features and an official standard. Emacs has a Common Lisp emulation package which provides features found in Common Lisp but not in Emacs Lisp. The modern way to use Common Lisp emulation is `(require cl-lib)`. The `cl-lib` package is distributed with Emacs. To avoid name conflicts, the functions and macros in this package have a name that starts with `cl-`. For example, there's a `cl-defmacro` which extends Emacs Lisp's built-in `defmacro` with extra features from Common Lisp, and there's a `cl-reduce` which implements Common Lisp's `reduce` function. The old way is `(require 'cl)`. The modern package called `cl` (also distributed with Emacs) uses `cl-lib` to emulate an old `cl` package with different naming conventions: functions and macros that don't exist in Emacs Lisp just have their name from Common Lisp (e.g. `reduce`), and for those that exist in Emacs Lisp, the `cl` package calls its version with an asterisk at the end, e.g. `defmacro*`. So `defmacro*` is the old-style Common Lisp emulation version of `defmacro`, provided by `cl`. --- Tags: init-file, elisp-macros ---
thread-62752
https://emacs.stackexchange.com/questions/62752
Flyspell not reading the complete word - FRENCH LANGUAGE
2021-01-13T16:27:31.867
# Question Title: Flyspell not reading the complete word - FRENCH LANGUAGE I am using flyspell for the first time. For word with "^" inside, it looks like they are read as two separate words. For example, below, the word "maître" is underlined, and the word proposed start with "t" And there I understood from my first research on the web, that it might come from utf-8 not set for ispell. I tried to change the value of `ispell-encoding8-command` initially set to `--encoding=` : ``` (setq ispell-encoding8-command "--encoding=utf-8" ) ``` but it did not work Ispell : 3.1.20 Aspell : 0.60.8 # Answer > 0 votes Just change the dictionnary of ispell like @Hubisan said `M-x ispell-change-dictionnary RET fr_FR RET` --- Tags: flyspell, ispell ---
thread-62826
https://emacs.stackexchange.com/questions/62826
Output of shell command in source block is displayed as table
2021-01-16T22:00:37.773
# Question Title: Output of shell command in source block is displayed as table The output of the shell commands is displayed as table. How can I have it displayed as "simple" lines of text ? # Answer > 1 votes I usually use `#+begin_shell :results drawer` which wraps the results in a drawer. You can also use `:results raw` but that has some disadvantages: Org mode does not know where the results end, so you cannot delete them with `org-babel-remove-result`. You can also use a different wrapper, e.g. `#+begin_shell :results drawer :wrap example` will wrap the results in a ``` #+begin_example ... #_end_example ``` block. --- Tags: org-mode, org-babel ---
thread-62829
https://emacs.stackexchange.com/questions/62829
string-join list with function as list member
2021-01-16T23:50:17.250
# Question Title: string-join list with function as list member I want to `string-join` a list of strings, one of which is returned by a function call. Like this: ``` (defun foobar () "foobar") (string-join '("foo" (foobar) "bar") "|") ``` That results in `Wrong type argument: characterp, foobar` and not in `"foo|foobar|bar"` as expected. What's the elegant way to do that? # Answer A quoted list doesn't evaluate its args, so it consists of a string, a list containing a symbol and another string. You can selectively evaluate it using backquote and unquote: ``` `("foo" ,(foobar) "bar") ;=> ("foo" "foobar" "bar") (string-join `("foo" ,(foobar) "bar") "|") ;=> "foo|foobar|bar" ``` > 2 votes --- Tags: quote, eval, backquote ---
thread-62818
https://emacs.stackexchange.com/questions/62818
How to change cursor color in emacs 27?
2021-01-16T16:24:08.543
# Question Title: How to change cursor color in emacs 27? Note that I'm using a theme (not sure if that changes things). I have ``` (set-cursor-color "White") ``` But my cursor is still yellow. # Answer > 1 votes Had to do the set-cursor-color after the custom-enabled-themes --- Tags: themes, cursor ---
thread-55493
https://emacs.stackexchange.com/questions/55493
How to develop a package I also have installed?
2020-02-13T02:06:47.010
# Question Title: How to develop a package I also have installed? When developing a package which is also installed via an online repository, there is a practical problem. * `/source/my-emacs-package` git repository where I have my code. * `~/.config/emacs/elpa/my-emacs-package-20200127.1052` The location the package is installed. Currently I'm manually removing & symlinking files between these directories, however this is quite cumbersome since you need to remember to remove the `*.elc` files and the path name changes after each update. --- How should I switch to my local git repository temporarily while developing my package? Using a single switch for example, at the beginning of my `init.el`. ``` ;; Set to t to load local packages. (defconst use-my-local-packages nil) ``` # Answer Since asking this question I've found `use-package` & `straight` can be used for this purpose. Given this `use-package` example. ``` (use-package recomplete :commands (recomplete-ispell-word)) ``` Can be made to use the local path: ``` (use-package recomplete :commands (recomplete-ispell-word) ;; This causes my local copy to be used. :straight (recomplete :type git :host gitlab :local-repo "/my/local/path/to/emacs-recomplete" :repo "ideasman42/emacs-recomplete")) ``` > 1 votes # Answer consider passing in a command line argument that alters the load-path perhaps? eg here I have a "-chat" switch. ``` (add-to-list 'command-switch-alist '("chat" . rgr/load-chats)) (defun rgr/load-chats(switch) (require 'rgr-chat)) ``` Modify this to modify the load-path right at the start of your init.el or whatever your startup is. > 0 votes --- Tags: git, package-development ---
thread-62803
https://emacs.stackexchange.com/questions/62803
Pull from git before applying org-capture?
2021-01-16T04:42:30.077
# Question Title: Pull from git before applying org-capture? I'm using org-capture to take project-specific notes by having a notes file in each of several git repositories. Looking forward, however, I can see danger here: if I'm working on project (1) and I think to drop a note in project (2), I'll probably forget to commit it; doing this on multiple computers and syncing via github just *begs* for merge conflicts. Does anyone know a way to solve at least part of this problem by having org-capture automatically pull from remote before it starts a note? I thought of trying to just use advice to do it, but there's no obvious way to do that given that the specific repository isn't selected until after org-capture is run... # Answer You can always use `defadvice`. This is kind of hook that can get triggered in many situation. ``` (defadvice next-line (before nextline-before activate) (message "Are you using next line?")) ``` For more https://www.emacswiki.org/emacs/AdvisingFunctions > 1 votes --- Tags: magit, git, org-capture ---
thread-53241
https://emacs.stackexchange.com/questions/53241
Using dired via tramp on a remote machine
2019-10-19T09:53:12.090
# Question Title: Using dired via tramp on a remote machine Maybe I am missing something rather simple but I completely fail to use `dired` on a remote machine. I can connect via `ssh` directly without emacs and I can edited a file using Tramp on the remote machine from within Emacs, as it should be. But when I want to use `dired` to show the home directory on the remote machine I just get an buffer with just one line but not the files in this directory. I did ``` C-x C-f /ssh:martin@martins-mbp.fritz.box:/Users/Martin/ ``` and was expecting that the whole directory is shown as it is on my local machine. During completion, i.e. before I press `Enter` above, I see the files and directories on my remote machine. Any hint is gratefully acknowledge. **EDIT** Just to document my findings: I disabled `dired-quicksort` and switched back to macOS' `ls` and it works fine now. I do not have the time to investigate this further but maybe this will help others in the future. # Answer > 4 votes I had the same problem and it was caused by the fact that one of the `ls` switches I use normally in dired was not working on the server shell. Removing all the switches except `-l` with `C-u s` solved the problem. # Answer > 1 votes If you use dired instead of find-file, this command should invoke tramp to use dired `C-x C-d /ssh:martin@martins-mbp.fritz.box:/Users/Martin/` --- Tags: dired, tramp ---
thread-62837
https://emacs.stackexchange.com/questions/62837
How do I use an advice to change the definition of goto-char within a function?
2021-01-17T16:46:15.417
# Question Title: How do I use an advice to change the definition of goto-char within a function? Suppose a third-party plugin contains the following function: ``` (defun example-function () (interactive) ;; ... do many things ... (goto-char (point-max)) ;; ... do many things ... (goto-char (point-max)) ;; ... do many things ... (goto-char (point-max))) ``` The function uses `goto-char` in various places in its body. I want to change the behavior of the function such that every time it calls `(goto-char (point-max))`, it will also call `(recenter -1)`. To that end, I added this advice to redefine the calls to `goto-char`: ``` (advice-add 'example-function :around (lambda (orig-fun &rest args) (cl-labels ((goto-char (pos) (goto-char pos) (recenter -1))) (apply orig-fun args)))) ``` However, the `cl-labels` appears to have no effect; `goto-char` still retains its old behavior inside `example-function`. What is wrong with the advice? (Emacs version: GNU Emacs 25.2) # Answer > 3 votes (Caveat: All from memory; I might have some of this wrong.) WRT your code: ``` (lambda (orig-fun &rest args) (cl-labels ((goto-char (pos) (goto-char pos) (recenter -1))) (apply orig-fun args)))) ``` You never call `goto-char` in the body of that `cl-labels` form, so your override wouldn't be used. It's the `orig-fun` definition which would be calling `goto-char`, but *that* code is not within the lexical scope of the `cl-labels` code. Generally, using `cl-letf` with `(symbol-function 'foo)` as the PLACE allows dynamically-scoped overrides (i.e. seen by other functions as well as the immediate code), but even then I think this kind of override could only work in uncompiled code, as `goto-char` has its own byte-code op, meaning that calls to it are compiled away to just that op code when it's byte-compiled (which also inhibits writing advice for `goto-char` itself). # Answer > 1 votes I am not sure what is wrong with your code, but it seems like it should not work because you are recursively calling goto-char inside the definition. You would have to redefine the goto-char function (which is in the C code I think). I think you need to advise the goto-char function temporarily like this: ``` (defun example-function () (interactive) ;; ... do many things ... (goto-char (point-max)) ;; ... do many things ... (goto-char (point-max)) ;; ... do many things ... (goto-char (point-max))) (defun modified-goto-char (orig-fun &rest args) (apply orig-fun args) (recenter -1)) (advice-add 'example-function :around (lambda (orig-fun &rest args) (advice-add 'goto-char :around #'modified-goto-char) (apply orig-fun args) (advice-remove 'goto-char #'modified-goto-char))) ``` --- Tags: advice ---
thread-62842
https://emacs.stackexchange.com/questions/62842
Start emacs from the command line with remote ssh file open
2021-01-17T20:04:28.443
# Question Title: Start emacs from the command line with remote ssh file open How to start Emacs from the command line with and open file trough ssh? What I usually do is first open Emacs and do: `C-X C-F /ssh:my_remote_server:/file.txt RET` How can I directly open the file from the command line doing something similar to: `emacs --remote "/ssh:my_remote_server:/file.txt"` # Answer > 2 votes To open a file when starting a new instance of Emacs you can generally do: ``` emacs "/ssh:server:file" ``` as described in `man emacs`: ``` SYNOPSIS emacs [ command-line switches ] [ files ... ] ``` If you use Emacs daemon and want to open a file within an existing instance of Emacs you can do `emacsclient "/ssh:server:file"` as well but it will cause emacsclient to block the terminal: ``` $ emacsclient "/ssh:freebsd:Makefile" Waiting for Emacs... ``` If you want to use `emacsclient` without blocking the terminal do: ``` emacsclient --eval "(with-current-buffer (window-buffer) (find-file \"/ssh:server:file\"))" ``` --- Tags: tramp, start-up, ssh ---
thread-62846
https://emacs.stackexchange.com/questions/62846
How can I set frame title to include Babel language when point is in a block
2021-01-17T22:30:09.203
# Question Title: How can I set frame title to include Babel language when point is in a block My frame title is currently set as `(setq frame-title-format '(buffer-file-name "%f" ("%b")))`, or for example `/path/to/file.org`. I'd like to set my frame title to include the language name of the Babel block, if the point is within a block. For example if I move the point inside a `#+begin_src python` block, then the frame title would be `/path/to/file : python`, and reset to `/path/to/file` when the point leaves that block. Reason: I'm trying to use 3rd-party software (Talon voice) that has support for different vocabularies. It selects vocabularies based on the app, or the window title. I'd like to automatically load and unload Python support, for example, if I'm in a `#+BEGIN_SRC jupyter-python` block or not. # Answer This is not beautiful, but may work well enough for you. ``` (defun set-frame-title () (setq frame-title-format (if (org-in-src-block-p) (format "%s - %s" (buffer-file-name) (org-element-property :language (org-element-context))) (buffer-file-name)))) (add-hook 'post-command-hook 'set-frame-title) ``` if performance is not good, you can look into cursor-sensor-functions. This is a lot more invasive though, and you have to hook into font-lock to get all the properties set up I think. > 2 votes --- Tags: org-mode, org-babel, talon ---
thread-62849
https://emacs.stackexchange.com/questions/62849
Org ref not exporting authordate when using natbib
2021-01-18T00:10:36.750
# Question Title: Org ref not exporting authordate when using natbib I am trying to export an org file with rounded brackets: > In order to be proficient in mathematics students must be able to perform fundamental skills with fluency (Williamson 2017:18). But when using the latex header below I numeric: > In order to be proficient in mathematics students must be able to perform fundamental skills with fluency (1:18). #+LATEX\_HEADER: \usepackage\[round\]{natbib} #+LATEX\_HEADER: \setcitestyle{authoryear} I tried to set the cite style but it did not work. Though it did work to set the note sep: #+LATEX\_HEADER: \setcitestyle{notesep={:}} How can I fix this? # Answer > 0 votes Try ``` #+LATEX_HEADER: \usepackage[round]{natbib} #+latex_header: \setcitestyle{authoryear,open={(},close={)}} #+latex_header: \bibliographystyle{abbrvnat} ``` and use citep:key for the citations. --- Tags: org-export, latex, bibtex, org-ref ---
thread-62761
https://emacs.stackexchange.com/questions/62761
Seeing file names in TODO entries when using org-attach
2021-01-14T08:36:25.880
# Question Title: Seeing file names in TODO entries when using org-attach I use `org-attach` mostly to "move" files and store them under various TODO items. I find this an invaluable feature for keeping receipts and other important documents. The limitation of org-attachments is that there is no way of knowing **what** files are kept under the item just by looking at the entry. Org uses the keyword `:ATTACH:` to indicate that that entry has an attachment. One can also tell this by the fact that there is an `ID` generated under properties. It would however be a nice feature to be able to see at least the filenames one has under that entry, without having to actually call `org-attach`. # Answer \[Capturing and summarizing the comments as an answer.\] Although `org-attach` does not provide an automatic way to add the list of files in the attachment directory of a headline node to that node explicitly, it does provide some mechanisms which could be used to do so. There is no problem about getting the current list: ``` (org-attach-file-list (org-attach-dir)) ``` evaluated at a particular node, would return the list of files; inserting it in e.g. a drawer should not be too difficult. Keeping the two lists in sync is doable as well: one possibility is to add a function to `org-attach-after-change-hook` that recalculates the list and recreates the drawer from scratch. This is just an outline of course: an implementation would be nice. One other possibility (which apparently meets the OP's requirements) is to manually create links to the entries. This too requires maintenance to keep things in sync, but assuming that links are mostly added and almost never deleted, the method will probably work well. It is based on the fact that Org mode supports attachment links: one can then use the standard link creation mechanism of Org mode, `C-c C-l` (bound to `org-insert-link`) as follows: ``` C-c C-l att TAB RET <select attachment file with TAB completion> RET RET ``` The attachment link type uses `org-attach-complete-link` which provides tab completion for the files in the attachment directory of the node. The above invocation creates a link without a description, so the link looks like this: ``` [[attachment:filename]] ``` but a description can of course be provided if required. Note that the link does not contain the path of the attachment directory: the value of that is retrieved from the metadata stored in the node (the ID property that is added) in order to retrieve the file. That keeps the clutter in the Org mode file down a bit. > 1 votes # Answer Thanks to @NickD I did submit a feature request to the orgmode team and received a very helpful response from them. I believe that listing all the attached files used to be the built-in, but was removed a few years ago. One can, however, still implement it for personal use. The function and correspondence can be found at this public message URL: https://orgmode.org/list/87sg70vsvy.fsf@localhost/ > 1 votes --- Tags: org-mode, org-agenda, attachment, org-attach ---
thread-62469
https://emacs.stackexchange.com/questions/62469
mouse click in margins to move point (gui macos) rather than error?
2020-12-26T19:14:09.420
# Question Title: mouse click in margins to move point (gui macos) rather than error? Currently, I have text modes configured with wide margins for readability with ``` (defun text-margins () (setq left-margin-width 16) (setq right-margin-width 16)) (add-hook 'text-mode-hook 'text-margins) ``` in my init. And this is great, except that sometimes I want to use the mouse to move point to the beginning of a line (in the GUI, on MacOS). Clicking on a line inside the text moves point to the location clicked, as expected. However, clicking on my nice wide margin next to a line doesn't move point. Instead, it beeps at me with an error and leaves point where it started. Is there any way to catch a mouse event inside a margin, so that I can give it a function to move point rather than just yell at me? # Answer Ok y'all, I figured it out myself. The following code works even on the bottom half of split windows and on inactive windows. ``` (defun set-point-to-margin-click (event) (interactive "e") (let ((position (cddr (mouse-position))) (clicked-window (posn-window (event-start event)))) (select-window clicked-window) (let ((topline (car (cdr (window-body-edges))))) (move-to-window-line 0) (line-move-visual (- position topline))))) (global-set-key (kbd "<left-margin> <mouse-1>") 'set-point-to-margin-click) (global-set-key (kbd "<right-margin> <mouse-1>") 'set-point-to-margin-click) ``` > 0 votes --- Tags: mouse, gui-emacs, margins ---
thread-55334
https://emacs.stackexchange.com/questions/55334
Gnus Inbox display read and unread emails
2020-02-06T06:42:55.837
# Question Title: Gnus Inbox display read and unread emails I set the `.gnus` as ``` ;;; package --- gnus ;;; ;;; (setq user-mail-address "abst.proc.do@qq.com" user-full-name "abst.proc.do") (setq gnus-select-method '(nnimap "qq.com" (nnimap-address "imap.qq.com") (nnimap-server-port 993) (nnimap-stream ssl))) (setq send-mail-function 'smtpmail-send-it smtpmail-smtp-server "smtp.qq.com" smtpmail-smtp-service 465 smtpmail-stream-type 'ssl gnus-ignored-newsgroups "^to\\.\\|^[0-9. ]+\\( \\|$\\)\\|^[\"]\"[#'()]") ``` After run M-x gnus and `L` gnus-group-list-all-group ``` 0: Deleted Messages 0: Drafts 1:*INBOX 0: Junk 0: Sent Messages U *: nndraft:drafts 1:*nnfolder+archive:sent.2020-02 ``` However, if enter Inbox, it display just the one new email. ``` R. [ 5: -> abst.proc.do ] Re: Group Buffer ``` How could I set `Inbox` to display all the emails both read and unread. Add `(dispaly . all)` to group parameters for "inbox" as: ``` ((modseq) (uidvalidity . "1579733041") (display . all) (active 1 . 60) (permanent-flags %* %Answered %Flagged %Deleted %Draft %Seen)) ``` but it still display only the unread mails. # Answer The visibility of articles in a group is controlled by its group parameters. You can use `G p` or `G c` when on the group in the \*Group\* buffer to change them. In this case you'd want something like ``` ((display . all)) ``` See the Group Parameters for more details. > 2 votes # Answer There is a clumsy distinction between "read" and "ancient" articles denoted "R" and "O" respectively. OP's report that ``` R. [ 5: -> abst.proc.do ] Re: Group Buffer ``` appears suggests he is indeed getting read articles *viz.* the `R` mark. He could try `/o` to try to pull in the other 60 messages which might have the `O` mark. I have never had to specially configure Gnus to get "ancient" articles to display, so something is definitely awry. > 2 votes # Answer Type `G-c` over the folder and search for `Permanently visible'`. Tick the checkbox next to that and press `[done]`. > 0 votes --- Tags: gnus ---
thread-19422
https://emacs.stackexchange.com/questions/19422
Library for automatically inserting python docstring in Google style
2016-01-11T00:02:57.973
# Question Title: Library for automatically inserting python docstring in Google style I'm looking for an elisp package that automatically inserts Python docstring for a method. I found a package, which is very close to my purpose. But it's in reStructured text, not in Google style. sphinx-doc.el https://github.com/naiquevin/sphinx-doc.el Describing arguments in docstrings (Google python style guide) https://www.chromium.org/chromium-os/python-style-guidelines#TOC-Describing-arguments-in-docstrings My expectation is when I call `M-x sphinx-doc-google` within the following function, ``` def some_function(a, b, c): ``` I need a result like this. ``` def some_function(a, b, c): """ Args: a: b: c: Returns: """ ``` I know it's not difficult to implement by myself. I just want to ask this question to avoid the reinvention. # Answer > 12 votes # Package The code described in the following section have now been made available in a separate package. Please see this repository for details: https://github.com/Xaldew/yasnippet-radical-snippets. --- # Old Answer I use the package called yasnippet for something similar to this. After some minor changes I adapted it to use the the Google docstring style instead: Do note however that it requires some setup: The snippet itself needs to execute some utility elisp code to generate the text. This is typically solved by creating a file called `.yas-setup.el` with the code inside the `python-mode` snippet directory. It is however also possible to place the code somewhere inside your `.emacs` instead. The code for the snippet is: ``` # -*- mode: snippet -*- # Insert Google style docstring and function definition. # name: Python Google style Docstring # key: defg # type: snippet # contributor: Xaldew # -- def ${1:name}($2): \"\"\"$3 ${2:$(python-args-to-google-docstring yas-text t)} ${5:Returns: $6 } \"\"\" ${0:$$(let ((beg yas-snippet-beg) (end yas-snippet-end)) (yas-expand-snippet (buffer-substring-no-properties beg end) beg end (quote ((yas-indent-line nil) (yas-wrap-around-region nil)))) (delete-trailing-whitespace beg (- end 1)))} ``` The code for the `.yas-setup.el` is: ``` (defun python-args-to-google-docstring (text &optional make-fields) "Return a reST docstring format for the python arguments in yas-text." (let* ((indent (concat "\n" (make-string (current-column) 32))) (args (python-split-args text)) (nr 0) (formatted-args (mapconcat (lambda (x) (concat " " (nth 0 x) (if make-fields (format " ${%d:arg%d}" (cl-incf nr) nr)) (if (nth 1 x) (concat " \(default " (nth 1 x) "\)")))) args indent))) (unless (string= formatted-args "") (concat (mapconcat 'identity (list "" "Args:" formatted-args) indent) "\n")))) ``` Note that `python-split-args` is provided by the *standard* snippets. I.e.: https://github.com/AndreaCrotti/yasnippet-snippets/tree/master You do however get those by default when you install the package through `package.el`. With everything setup properly, you should be able to write "defg" followed by `Tab` to expand the snippet (See the image for an example). ~~There is still an issue with using this inside nested indentation, e.g., within classes or as nested functions. In those cases the docstring is erroneously indented an extra time for some reason. I'll update this post if I manage to fix that.~~ The snippet should now work inside other scopes by forbidding `yasnippet` from auto-indenting the second expansion. # Answer > 3 votes As lunaryorn mentioned that style is not popular and there aren't any packages. However there is a package called sphinx-doc which will generate doc string in sphinx format(demo). You can modify that package to generate strings as per your requirement. # Answer > 0 votes I tried to use Xaldev's answer, but it seems it doesn't work with type-annotations. So, I wrote this snippet. It contains python's script to analyze defs and generate documentation and some elisp's code, which you should add to your `user-config` part. disclaimer: code is quite dirty, but for me it generates such a pleacant docs: ``` def test(region: str = "foo", bar: t.List[t.Any] = [1, 2], baz: int = 0) -> None: """ Args: region (str): (default: 'foo') bar (t.List[t.Any]): (default: [1, 2]) baz (int): (default: 0) Returns: None: nothing """ def __init__(self) -> None: """Initialize object Returns: None: nothing """ ... ... ``` You're welcome to try and change it for your purposes. # Answer > -1 votes You can use this code. Move the cursor on your function name and then F9. ``` (defun chomp (str) "Chomp leading and tailing whitespace from STR." (let ((s (if (symbolp str) (symbol-name str) str))) (replace-regexp-in-string "\\(^[[:space:]\n]*\\|[[:space:]\n]*$\\)" "" s))) (defun get-function-definition(sentence) (if (string-match "def.*(.*):" sentence) (match-string 0 sentence))) (defun get-parameters(sentence) (setq y (get-function-definition sentence)) (if y (if (string-match "(.*)" y) (match-string 0 y)))) (autoload 'thing-at-point "thingatpt" nil t) ;; build-in librairie (defun python-insert-docstring() (interactive) (setq p (get-parameters (thing-at-point 'sentence))) (forward-line 1) (insert " \"\"\"\n") (insert "\tArgs:\n") (setq params (split-string p "[?\,?\(?\)?\ ]")) (while params (if (/= (length (chomp (car params))) 0) (progn (insert " ") (insert (chomp (car params))) (insert ": \n"))) (setq params (cdr params))) (insert " Returns:\n \"\"\"\n")) (global-set-key (kbd "<f9>") 'python-insert-docstring) ``` --- Tags: python, doc-strings ---
thread-62859
https://emacs.stackexchange.com/questions/62859
Help with regex in re-builder : lines without "|" nor ";" at the beginning
2021-01-18T09:23:45.053
# Question Title: Help with regex in re-builder : lines without "|" nor ";" at the beginning I am starting regex with Emacs and cannot get the right regex. I would like to match the line `1` and `4` in the image below, where `variable-pitch` is "active" and do not match `2` and `3` where is "inactive" so I am basically trying to say : `line with 'variable-pitch' not containing with ";" or "|"` Following this post, I switched re-builder to `string` mode. Edit : Following the different comments * here is the text if you want to try * i changed the the screenshot with `re-builder` actually set to string # Answer > 0 votes > I switched re-builder to `string` mode Did you? You've used `\\(...\\)` to (apparently successfully) match a sub-group, which indicates you're using `read` syntax. In `string` syntax that would be `\(...\)`. --- Regarding this: ``` [^;|\\|].*\\(variable-pitch.*\\) ``` `[^;|\\|]` says to match anything other than `;`, `|`, `\`, or (again) `|`. Note also that newlines are not excluded. Following that you match `.*`, which is zero or more non-newline characters. Finally you match a subgroup consisting of `variable-pitch` followed by zero or more non-newline characters. --- > so I am basically trying to say: line with 'variable-pitch' not containing with ";" or "|" So something like this? ``` "^[^;|\n]*variable-pitch[^;|\n]*$" ``` Note that you can only use `\n` in `read` syntax (because it's an escape sequence for reading strings, not an escape sequence for regexps). If you're using `string` syntax in re-builder then you'll need to type a literal newline instead. --- Tags: regular-expressions ---
thread-62863
https://emacs.stackexchange.com/questions/62863
Is it possible to displaying Inline Images in Emacs markdown-mode
2021-01-18T16:37:15.967
# Question Title: Is it possible to displaying Inline Images in Emacs markdown-mode I am using `GNU Emacs 26.3` inside a remotely connected linux machine. I was wondering is it possible to display inline images in Emacs `markdown-mode`? Seems like it is possible (link) in `org-mode`? Using `M-x markdown-toggle-inline-images` gives `Cannot show images` message in the minibuffer. --- basic setup: ``` (add-to-list 'load-path "~/.emacs.d/markdown-mode") (autoload 'markdown-mode "markdown-mode.el" "Major mode for editing Markdown files" t) (add-to-list 'auto-mode-alist '("\\.md\\'" . markdown-mode)) ``` `md` file: ``` # test ![](images/hellow_word.png) ``` # Answer > 4 votes Yes it is possible (at least with Emacs 27 running locally) with `M-x markdown-toggle-inline-images` or `C-c C-x TAB` --- Tags: images, markdown ---
thread-62783
https://emacs.stackexchange.com/questions/62783
Ignore spurious focus events for after-focus-change-function
2021-01-15T10:06:54.793
# Question Title: Ignore spurious focus events for after-focus-change-function I'm on Emacs 27.1, Fedora 33, GNOME 3.38.2. In the latest `NEWS` it is reported that > The hooks `focus-in-hook` and `focus-out-hook` are now obsolete. Instead, attach to `after-focus-change-function` using `add-function` and inspect the focus state of each frame using `frame-focus-state`. The documentation for `after-focus-change-function` says > Depending on window system, focus events may also be delivered repeatedly and with different focus states before settling to the expected values. Code relying on focus notifications should "debounce" any user-visible updates arising from focus changes, perhaps by deferring work until redisplay. Indeed, after evaluating this code, ``` (defun focus-test () (message "ffs: %s" (frame-focus-state))) (add-function :after after-focus-change-function #'focus-test) ``` every time I switch buffer by selecting one with the mouse my message buffer shows ``` ffs: nil ffs: t ffs: nil ffs: t ``` That is, Emacs sees two back and forth focus changes where I did none, and most importantly it has hallucinations of focus-out events which defeat the usefulness of the `after-focus-change-function`+`frame-focus-state` method for triggering functions based on focus events. My question is, how do I "'debounce' any user-visible updates arising from focus changes"? (I made a naive attempt with ``` (defun focus-test () (sit-for 0) (message "ffs: %s" (frame-focus-state))) ``` but it didn't work.) # Answer > 2 votes I've settled with these home-made remakes of the obsoleted hooks: ``` ;; Set up hooks to be run on focus in and focus out ;; Mutter sends spurious focus events, including sending focus out ;; events when Emacs never really was unfocused. ;; The timer filters out these false focus out events, while ;; checking the ‘last-focus-state’ allows ignoring repeated events ;; of the same kind. ;; REVIEW: false focus out events are still received sometimes when ;; using the menu bar. ;; Based on a suggestion by DasEwigeLicht on ;; https://www.reddit.com/r/emacs/comments/kxsgtn/ignore_spurious_focus_events_for/ (defvar focus-events-timer nil) (defvar last-focus-state (frame-focus-state)) (defvar my-focus-in-hook nil "Normal hook run when all frames lose input focus.") (defvar my-focus-out-hook nil "Normal hook run when a frame gains focus.") (defun change-of-focus-functions () (unless (equal last-focus-state (frame-focus-state)) (if (frame-focus-state) (run-hooks 'my-focus-in-hook) (run-hooks 'my-focus-out-hook))) (setq focus-events-timer nil) (setq last-focus-state (frame-focus-state))) (defun run-change-of-focus-functions-with-timer () (unless (timerp focus-events-timer) (setq focus-events-timer (run-at-time "0.05 sec" nil ; Delay chosen by trial and error. Test it if you change it. #'change-of-focus-functions)))) (add-function :after after-focus-change-function #'run-change-of-focus-functions-with-timer) ;; Test (defun focus-in-test () (message "focus-in")) (defun focus-out-test () (message "focus-out")) (add-hook 'my-focus-in-hook #'focus-in-test) (add-hook 'my-focus-out-hook #'focus-out-test) ;; Actual use (add-hook 'my-focus-out-hook #'do-auto-save) ``` --- Tags: gui-emacs, focus, emacs27 ---
thread-45558
https://emacs.stackexchange.com/questions/45558
Change list bullets in org-mode depending on embedding level
2018-10-24T20:47:45.820
# Question Title: Change list bullets in org-mode depending on embedding level Is it possible to change the face of list bullets dynamically, mimicking the behaviour of WYSIWYG textprocessors like MS Word? # Answer Following NickD's advice, I've changed the look of list bullets using overlays: ``` (font-lock-add-keywords 'org-mode '(("^[[:space:]]*\\(-\\) " (0 (prog1 () (compose-region (match-beginning 1) (match-end 1) "•")))))) ``` Furthermore, I've increased the indentation offset in order to emphasize the degree of embedding: ``` (setq-default org-list-indent-offset 4) ``` I'm happy with the result, even though it's not exactly what I was looking for in my question: **COMMENT:** Of course, with this approach, one could get closer to the intended look with the following: ``` (setq-default org-list-indent-offset 4) (font-lock-add-keywords 'org-mode '(("^\\(-\\) " (0 (prog1 () (compose-region (match-beginning 1) (match-end 1) "•")))))) (font-lock-add-keywords 'org-mode `((,(concat "^[[:space:]]\\{" (number-to-string (+ 2 org-list-indent-offset)) "\\}\\(-\\) ") (0 (prog1 () (compose-region (match-beginning 1) (match-end 1) "◦")))))) (font-lock-add-keywords 'org-mode `((,(concat "^[[:space:]]\\{" (number-to-string (* 2 (+ 2 org-list-indent-offset))) "\\}\\(-\\) ") (0 (prog1 () (compose-region (match-beginning 1) (match-end 1) "▸")))))) (font-lock-add-keywords 'org-mode `((,(concat "^[[:space:]]\\{" (number-to-string (* 3 (+ 2 org-list-indent-offset))) "\\}\\(-\\) ") (0 (prog1 () (compose-region (match-beginning 1) (match-end 1) "▹")))))) ``` But this presupposes that the indentation is accurate in terms of the number of spaces. The best solution would be to make the font-lock depend on the logical embedding level using something like `(org-list--depth (org-element-at-point))`. > 1 votes # Answer This can be achieved with the package org-superstar-mode. Previously there was another package org-bullets which is no longer maintained. This seems to be the successor. > 2 votes --- Tags: org-mode, faces ---
thread-50122
https://emacs.stackexchange.com/questions/50122
Move cursor to opened file in sr-speedbar
2019-04-24T09:49:04.430
# Question Title: Move cursor to opened file in sr-speedbar i wonder how i can configure the sr-speedbar mode to automatically move the cursor to a file, which i open by pressing enter in the sr-speedbar. Thanks for your input. # Answer I encountered the same problem when using `sr-speedbar`. I fix it with the following hacky stuff in my config file: ``` (with-eval-after-load 'sr-speedbar (add-hook 'speedbar-visiting-file-hook #'(lambda () (select-window (next-window))) t)) ``` This is inspired by code I found near the end of the SrSpeedbar page of the Emacs Wiki, under the title « Make Sr-speedbar open files in the next window, instead of in the previous window ». I just found out more logical to use `speedbar-visiting-file-hook` than the `before` hook. Edit: Actually, the problem comes from custom hooks added by `sr-speedbar` author. Another very effective way of fixing this problem in just to remove these problematic hooks: ``` (with-eval-after-load 'sr-speedbar (advice-add 'sr-speedbar-open :after #'(lambda () ;; Remove weird sr-speedbar hooks (remove-hook 'speedbar-before-visiting-file-hook #'sr-speedbar-before-visiting-file-hook) (remove-hook 'speedbar-before-visiting-tag-hook #'sr-speedbar-before-visiting-tag-hook) (remove-hook 'speedbar-visiting-file-hook #'sr-speedbar-visiting-file-hook) (remove-hook 'speedbar-visiting-tag-hook #'sr-speedbar-visiting-tag-hook)) ``` > 2 votes # Answer **Alternative answer with more features**: * If you want to handle the case where there are several windows opened in the current frame it's better to identify the SR-Speedbar window instead of the 'next-window. * You can also implement the ability to setect the default behaviour or the new by using a customizable user-option defined with defcustom form. * And for dynamic control, define a variable initialized to the user-option's value which can be changed by a command and then used in the hook to determine whether point should move back to the SR-Speedbar frame or not. This is what I have written in my PEL package: ``` (defcustom pel-sr-speedbar-move-point-to-target-on-select t "When on, a SR-Speedback select moves point to the target buffer window. Otherwise it leaves point inside the SR-Speedbar buffer window. This behaviour can be modified by the command `pel-sr-speedbar-toggle-select-behaviour'." :group 'pel-pkg-for-speedbar :type 'boolean :safe #'booleanp) (defvar pel--sr-speedbar-move-point-to-target-on-select pel-sr-speedbar-move-point-to-target-on-select "Global behaviour of `pel-sr-speedbar-move-point-to-target-on-select.") ;;-pel-autoload (defun pel-sr-speedbar-toggle-select-behaviour () "Toggle SR-Speedbar selection behaviour." (interactive) (pel-toggle-and-show 'pel--sr-speedbar-move-point-to-target-on-select "Move to target on SR-Speedbar select" "Stay in SR-Speedbar buffer after select")) (defun pel--select-sr-speedbar-buffer-window () "Select SR-Speedbar buffer window." (let ((sp-win (get-buffer-window "*SPEEDBAR*"))) (if sp-win (select-window sp-win) (error "Can't find buffer *SPEEDBAR*")))) (defun pel-sr-speedbar-visiting-control () "Hook callback: determine what buffer to select. This function is used by SR-speedbar hooks `speedbar-visiting-file-hook' and `speedbar-visiting-tag-hook'. It returns point to the SR-Speedbar buffer window when pel--sr-speedbar-move-point-to-target-on-select is nil, otherwise it leaves it in the window of the file selected by the SR-Speedbar selection user action." (unless pel--sr-speedbar-move-point-to-target-on-select (pel--select-sr-speedbar-buffer-window))) ;; Inside the init file or something similar: (defun pel--sr-speedbar-setup() "Setup the sr-speedbar hooks." ;; Remove sr-speedbar hooks that switch back to the speedbar buffer (remove-hook 'speedbar-before-visiting-file-hook #'sr-speedbar-before-visiting-file-hook) (remove-hook 'speedbar-before-visiting-tag-hook #'sr-speedbar-before-visiting-tag-hook) (remove-hook 'speedbar-visiting-file-hook #'sr-speedbar-visiting-file-hook) (remove-hook 'speedbar-visiting-tag-hook #'sr-speedbar-visiting-tag-hook) ;; Instead add hooks that a command can control the behaviour (add-hook 'speedbar-visiting-file-hook 'pel-sr-speedbar-visiting-control t) (add-hook 'speedbar-visiting-tag-hook 'pel-sr-speedbar-visiting-control t)) (with-eval-after-load 'sr-speedbar (advice-add 'sr-speedbar-open :after (function pel--sr-speedbar-setup))) ``` The default behaviour of doing a selection from the SR-Speedbar is to switch to the window of the target. That can be changed by customization **and** changed dynamically while editing by executing the command pen-sr-speedbar-toggle-select-behaviour. The function pet-toggle-and-show takes a symbol and toggle its value between nil and non-nil, displaying the interpretation of the new value. > 0 votes --- Tags: navigation, speedbar ---
thread-62861
https://emacs.stackexchange.com/questions/62861
Autocompletion of tags in orgmode
2021-01-18T12:38:31.987
# Question Title: Autocompletion of tags in orgmode Is it possible to have in the completion window the list of ALL tags ? `TAG1` \+ `TAG2` \+ `TAG3` \+ `TAG4`\+ `TAG5` # Answer > 0 votes `org-tag-alist` is the global value that a file specific `#+TAGS:` specification *overrides*. You can do what you want by specifying the tags you want to add to `org-tag-persistent-alist`, whose value is *augmented* by a `#+TAGS:` spec. Note BTW, that both of these are supposed to be alists so the correct specification is: ``` (setq org-tag-persistent-alist '(("TAG1") ("TAG2") ("TAG3"))) ``` You can disable the persistent tags in a particular file by specifying: ``` #+STARTUP: noptag ``` See the doc string of the variable with `C-h v org-tag-persistent-alist RET` (and similarly for the other variable). --- Tags: org-mode, org-tags ---
thread-62862
https://emacs.stackexchange.com/questions/62862
How to change syntax highlight inside #if 0?
2021-01-18T14:15:50.303
# Question Title: How to change syntax highlight inside #if 0? In `cc-mode`, I want a way set all syntax highlight colours to slightly more desaturated versions when inside a `#if 0 ... #endif` block. If that would be troublesome/hard to maintain (having to set all the colours manually), just setting all the text inside the block to a single colour would be fine too. I've tried this, but is intended for use with a single keyword. I'm using `spacemacs 0.300.0@26.3` # Answer > 1 votes Emacs has a built-in package for ifdefs. To quote from https://www.gnu.org/software/emacs/manual/html\_node/emacs/Other-C-Commands.html: ``` ‘M-x hide-ifdef-mode’ Hide-ifdef minor mode hides selected code within ‘#if’ and ‘#ifdef’ preprocessor blocks. If you change the variable ‘hide-ifdef-shadow’ to ‘t’, Hide-ifdef minor mode shadows preprocessor blocks by displaying them with a less prominent face, instead of hiding them entirely. See the documentation string of ‘hide-ifdef-mode’ for more information. ``` --- Tags: syntax-highlighting ---
thread-41368
https://emacs.stackexchange.com/questions/41368
How can I use more than 9 regex capture groups in Emacs Lisp?
2018-05-07T10:06:26.070
# Question Title: How can I use more than 9 regex capture groups in Emacs Lisp? I have to do a regexp replacement with more than 9 capture groups. How can I do it? Here there is my code (with `\\10` and `\\12` that they do not work as I expected to): ``` (perform-replace "\\\\href{https://doi.org/\\(.*\\)}{\\\\emph{\\(JHEP\\|JCAP\\)}\\([ ]*\\)?{\\\\bfseries\\([ ]*\\)?\\([0-9]+\\)}\\([ ]*\\)?(\\([0-9]\\)\\([0-9]\\)\\([0-9]\\)\\([0-9]\\))\\([ ]*\\)?\\([0-9]+\\)}" "\\\\href{https://doi.org/\\1}{\\\\emph{\\2} {\\\\bfseries \\9\\10\\5} (\\7\\8\\9\\10) \\12}" t t nil 1 nil a z) ``` # Answer > 7 votes Going by the Emacs source code, it is absolutely possible to use more than 9 regex capture groups: ``` /* Since we have one byte reserved for the register number argument to {start,stop}_memory, the maximum number of groups we can report things about is what fits in that byte. */ #define MAX_REGNUM 255 /* But patterns can have more than 'MAX_REGNUM' registers. Just ignore the excess. */ typedef int regnum_t; ``` However you've run into a different limitation, a maximum of 9 backreferences: ``` case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { regnum_t reg = c - '0'; if (reg > bufp->re_nsub || reg < 1 /* Can't back reference to a subexp before its end. */ || group_in_compile_stack (compile_stack, reg)) FREE_STACK_RETURN (REG_ESUBREG); laststart = b; BUF_PUSH_2 (duplicate, reg); } break; ``` It is possible to overcome this limitation by using Lisp code instead of a replacement pattern: ``` (defvar big-rx (rx (group (+ "x")) " " (group (+ "x")) " " (group (+ "x")) " " (group (+ "x")) " " (group (+ "x")) " " (group (+ "x")) " " (group (+ "x")) " " (group (+ "x")) " " (group (+ "x")) " " (group (+ "x")) " " (group (+ "x")))) (let ((text (mapconcat 'identity (mapcar (lambda (x) (make-string x ?x)) (number-sequence 1 11)) " "))) (when (string-match big-rx text) (setq text (replace-match (make-string 1 ?y) t t text 1)) (setq text (replace-match (make-string 11 ?y) t t text 11)))) ;; => "y xx xxx xxxx xxxxx xxxxxx xxxxxxx xxxxxxxx xxxxxxxxx xxxxxxxxxx yyyyyyyyyyy" ``` The above example uses eleven capture groups and replaces the first and eleventh one. --- Tags: regular-expressions ---
thread-62711
https://emacs.stackexchange.com/questions/62711
Can't run org-refile function in Spacemacs
2021-01-11T18:42:47.740
# Question Title: Can't run org-refile function in Spacemacs I am using GNU Emacs 27.1 with Spacemacs 0.300. I am new to Emacs and Org-mode. I want to use the function org-refile with the shortcut C-c C-w. However, this is what I get: Why can't I use that function? Besides, do you recommend using Spacemacs or Vanilla Emacs for someone who is learning? Thanks in advanced! EDIT The issue had something to do with Spacemacs and its key bindings. I ended up switching to Vanilla Emacs. Since I am just starting with Emacs, I feel more in control than with Spacemacs. # Answer You can disable `eyebrowse-mode` than it can work. ``` (add-hook 'org-mode-hook '(lambda () (eyebrowse-mode -1))) ``` > 0 votes --- Tags: org-mode, spacemacs ---
thread-62878
https://emacs.stackexchange.com/questions/62878
inludegraphics macro does not ask for width etc. but only for llx, lly
2021-01-19T14:17:13.333
# Question Title: inludegraphics macro does not ask for width etc. but only for llx, lly Using GNU Emacs 26.3, I have a tex file with `\usepackage{graphicx}` and AUCTeX enabled. However, inserting a `includegraphics` macro does not prompt for the optional arguments defined in `graphicx.el` `LaTeX-graphicx-key-val-options` but only for `llx, lly` and `urx, ury`. Any ideas on how to debug the wrong behavior? # Answer > 0 votes `graphicx.el` has this entry for `includegraphics`: ``` '("includegraphics" (TeX-arg-conditional (member "graphics" (TeX-style-list)) (["llx,lly"] ["urx,ury"]) ([ LaTeX-arg-graphicx-includegraphics-key-val ])) ``` I suspect you're also loading the `graphics` package besides `graphicx` in your .tex file. --- Tags: auctex, debugging ---
thread-50233
https://emacs.stackexchange.com/questions/50233
Hide lines by regex
2019-04-30T10:05:19.040
# Question Title: Hide lines by regex I am reading detailed line oriented log file (100MB). I want to skip some parts by using regex. Usually I `M-x flush-lines` but this is destructive operation. I want to hide many lines by regex and expect it would be efficient when I navigate across file. Extra plus if interactive search skips hidden parts. From the comments on yue's answer: * I want incremental exclusion (first regex, then next regex). * I search for anomalies in log and know what to exclude but I don't know what I will have found. # Answer > 5 votes I agree with comments that suggest using `flush-lines`. I would likely use that in this case, especially since your use case is line-oriented. --- But if you want to make text that matches a regexp invisible, so that search, query-replace, etc. ignore it but it is still present, then you can do that with libraries Zones and Isearch+. For example, you can use `C-x n R` (command `zz-set-zones-matching-regexp`) to set the value of the current izones variable to the list of zones that match a given regexp. Then use command `isearchp-make-zones-invisible` to make those zones invisible. If you want to make other lines, which match other regexps, then use `C-x n r`, not `C-x n R`. The former *adds* zones to the zone set; the latter *sets* the zone set (removing any existing zones in it). There are also these related commands: `isearchp-make-zones-visible`, `isearchp-toggle-zones-invisible`, and the same for anti-zones (complement of zones). `C-x n R` and `C-x n r` match a regexp against your text, like `re-search-forward` does - the search hits define the zones. They are not line-oriented like `flush-lines`, `occur`, and `grep`. So if you want an entire line to become invisible then you need to use a *regexp that matches the entire line* (containing whatever text you're interested in). # Answer > 3 votes You want to use occur. This feature is built-in and it does exactly what you want. There is also a package called loccur, which does the same, but does not create a new window (it just hides all non matching lines). # Answer > 1 votes Try this: `M-x` `query-replace-regexp` `RET` `.*FOO.*` `C-q``C-j``RET` `\,(propertize \& 'invisible t)` `RET` See also `C-h``i``g` `(elisp)Invisible Text` # Answer > 1 votes I found this most easy solution. https://github.com/vapniks/hide-lines Some functions are here which can be useful for your scenario > ``` > hide-lines : Hide lines matching the specified regexp. > Keybinding: M-x hide-lines > hide-lines-not-matching : Hide lines that don’t match the specified regexp. > Keybinding: M-x hide-lines-not-matching > hide-lines-matching : Hide lines matching the specified regexp. > Keybinding: M-x hide-lines-matching > hide-lines-show-all : Show all areas hidden by the filter-buffer command. > Keybinding: M-x hide-lines-show-all > hide-blocks-not-matching Hide text that is not between lines matching START-TEXT and END-TEXT. Keybinding: M-x hide-blocks-not-matching > hide-blocks-matching Hide text that is between lines matching START-TEXT and END-TEXT. Keybinding: M-x hide-blocks-matching > hide-lines-kill-hidden Kill or delete all hidden areas. Keybinding M-x hide-lines-kill-hidden > > ``` --- Tags: hideshow ---
thread-62876
https://emacs.stackexchange.com/questions/62876
LaTeX Table Is Out of Place | Org-mode
2021-01-19T12:51:24.153
# Question Title: LaTeX Table Is Out of Place | Org-mode I am making my tables in pure LaTeX becuase Org-mode doesn't have the functionality to create what I want. My problem is, I am pasting the LaTeX code for the table under a heading but when I get the pdf export, I see that the table has moved under another heading, above some other text. I had this happen to me before in this document again with an image (since I had used #+CAPTION on it) but using `\usepackage{placeins}` in LaTeX header and `\FloatBarrier` at the end of the image did work. I tried doing the same thing for the table but it simply won't work. # Answer > 2 votes Your preamble shows that you use the `float` package. When you use the `float` package, the correct placement parameter for *right here* is `H`. So write your table like this in the Org mode file: ``` #+ATTR_LATEX: :placement [H] #+CAPTION: My Table | a | b | |----+------| | 1 | 1 | | 2 | 4 | | 3 | 9 | | .. | ... | ``` Without the `float` package, @mankoff's answer stands: `:placement [!h]` is the best that you can do. But note that float placement is a complicated problem: Lamport's book describing the method (Section C.9.1) devotes four pages to the description - there are six rules (that "you will have to read ... slowly and carefully to understand what LaTeX is doing") and fifteen formatting parameters. So if LaTeX seems to be doing something wrong, you will have to go back and figure out which rule you are breaking. Float placement has a long, contentious history: see https://tex.stackexchange.com/questions/8625/force-figure-placement-in-text for some perspective. EDIT: As the OP pointed out in the question and which I forgot about, he is *NOT* using Org mode tables. Instead he is inserting the table as raw LaTeX code (because Org mode can only deal with simple tables that don't have e.g. spanning columns). So all the talk about `#ATTR_LATEX:` is irrelevant in this case. Org mode will deal with a raw LaTeX table in the Org mode file by exporting it verbatim into the resulting `.tex` file. So all the OP has to do in that case is make sure that the placement indicator is present in the raw LaTeX table (the following assumes that the `float` package is used for LaTeX: that enables the use of the `H` indicator; as pointed out above, without that package, the best one can do in order to place the table *here* is to use the `!h` placement indicator): ``` #+LATEX_HEADER: \usepackage{float} * An Org mode table Here comes an Org mode table: #+ATTR_LATEX: :placement[H] #+CAPTION: My Table | a | b | |----+------| | 1 | 1 | | 2 | 4 | | 3 | 9 | | .. | ... | * A raw LaTeX table Here comes a raw LaTeX table - the spanning `style` column could not be done with an Org mode table (but it could probably be done with a table.el table - that's left as an exercise): \begin{table}[H] \caption{My raw \LaTeX table} \centering \begin{tabular}{|l|l|r|} \hline\hline \emph{type} & \multicolumn{2}{c|}{\emph{style}} \\ \hline smart & red & short \\ rather silly & puce & tall \\ \hline\hline \end{tabular} \end{table} ``` In general, it is *always* a good idea to look at the exported LaTeX file and see what Org mode did: even if you don't know any LaTeX, you should be able to figure out what needs to be done for simple changes and even if not, you can ask questions about it on the TeX SE site. IOW, Org mode export is enough for simple documents, but if you have something that is beyond what Org mode can do, you will need to learn some LaTeX. And this applies to the other exporters as well: Org mode can deal with 90% of what you need day to day, but you will need to know something about the target language in order to cover the remaining 10%. # Answer > 2 votes Try adding `#+ATTR_LATEX: :placement [!h]` as a header to the table. That says: Place the table *here*. The trouble with it is that if the table doesn't fit here, you'll end up with lots of blank space and the table on the next page. Alternatively, `\clearpage` at the end of a section forces all floats (tables, figures) to be placed. --- Tags: org-mode, latex ---
thread-61215
https://emacs.stackexchange.com/questions/61215
Paste very specific Unicode in scratch buffer freezes emacs -Q
2020-10-15T17:27:20.057
# Question Title: Paste very specific Unicode in scratch buffer freezes emacs -Q I experienced a freeze which can be reproduced very easily on `GNU Emacs 28.0.50 (build 1, x86_64-pc-linux-gnu, GTK+ Version 3.24.18, cairo version 1.16.0) of 2020-08-25` . 1. `emacs -Q` 2. Copy the Unicode U+27B0 into the scratch buffer: ➰ 3. Emacs frozen for a whole minute and displays ➰. Remarkably, the response time for other symbols in this Unicode table is quite different, *e.g.* * ➑ takes 30 seconds * ➐ is instant. Is this issue known? ## Updates ### what-cursor-position `C-u C-x =` on the pasted symbol gives (screenshot because Emacs frozen): ### Profiling & Benchmarking Unfortunately, this scenario escaped the profiling... ...and the benchmarking which outputs immediately the result when the symbol is not yet present. # Answer I fixed this issue and couple other ones at the same time: it prevented me to use `telega` and `elfeed` as Emacs slows down considerably when some fancy Unicode should be rendered. This "bug" or font issue reaches nightmare level as it can't be debugged through standard approaches (it depends on buffer contents). Moreover, it wastes package maintainer time as it is highly non-reproducible. Fortunately, the package unicode-fonts (available on Melpa) fixes this problem. Basically, 1. Install the minimum useful fonts (DejaVu Sans, DejaVu Sans Mono, Quivira, Symbola, Noto Sans and Noto Sans Symbols). 2. Put this in your configuration ``` (use-package unicode-fonts :ensure t :config (unicode-fonts-setup)) ``` It will take a couple seconds to set up the first time. The mapping will be written persistently with `pcache` for subsequent startup. > 2 votes --- Tags: unicode, frozen-emacs ---
thread-61906
https://emacs.stackexchange.com/questions/61906
doom emacs "Symbol's function definition is void: make-treemacs-theme"
2020-11-24T02:32:15.963
# Question Title: doom emacs "Symbol's function definition is void: make-treemacs-theme" I'm using doom emacs with current commit `c83e5e75e24706a0d6c15f3156d33b1c4f9dc365`. When I do `SPC o p` I get error > Symbol's function definition is void: make-treemacs-theme Below is the screenshot - How can I fix this issue? # Answer This fixed the problem for me: ``` ~/.emacs.d/bin/doom build ``` Doing `doom build` recompiles and symlinks all installed packages. I figured this out after seeing a comment on a Github issue about this exact error: > This is caused by lsp-treemacs byte-compiled against old treemacs. > 4 votes --- Tags: doom, treemacs ---
thread-62891
https://emacs.stackexchange.com/questions/62891
lexical-binding: How to create a let-bound function that recursively calls itself
2021-01-20T04:08:13.927
# Question Title: lexical-binding: How to create a let-bound function that recursively calls itself The custom function below `my-jump-to` *works* after being evaluated in a scratch buffer, but does *not* work when I stick it into a library with `lexical-binding` non-nil in the header. When byte-compiling, I get a warning: `reference to free variable ‘the-fn’`. When I restart Emacs *after* byte-compiling, and try to use the function, I get a `*Backtrace*`: `Debugger entered--Lisp error: (void-variable the-fn)`. I tried using the trick of putting a `#'` in front of the `(lambda ...`, but that did not appear to have any effect. I tried using a `backtick` in front of the `(lambda ...`, and placing a comma before `the-fn`, but that didn't work either. Is it possible to make this work inside a library with `lexical-binding` non-nil in the header, and if so, then how can that be achieved? ``` (defun my-jump-to () "Jump to an imenu item using ido." (let* ((completion-ignore-case t) (collection (imenu--make-index-alist)) (first-amended-collection nil) (the-fn (lambda (index-alist depth) (dolist (entry index-alist) (setq imenu-list--line-entries (append imenu-list--line-entries (list entry))) (push entry first-amended-collection) (when (imenu--subalist-p entry) (funcall the-fn (cdr entry) (1+ depth)))))) second-amended-collection) (funcall the-fn collection 0) (mapc (lambda (elt) (push (cons (car elt) (list elt)) second-amended-collection)) first-amended-collection) (let ((choice (ido-completing-read "SELECT: " second-amended-collection nil 'confirm))) (imenu (car (cdr (assoc choice second-amended-collection))))))) ``` # Answer > 2 votes Your problem is that the let-bound symbol `the-fn` is not yet available when you define the lambda. Use `letrec` instead of `let*`. It first binds all variables and afterwards sets them. Example: ``` (defun my-test () (letrec ((the-fn (lambda (recursive) (message "Calling the-fn with arg %s." recursive) (when recursive (funcall the-fn nil))))) (funcall the-fn t))) ``` This example is equivalent to: ``` (defun my-test () (let* (the-fn) (setq the-fn (lambda (recursive) (message "Calling the-fn with arg %s." recursive) (when recursive (funcall the-fn nil)))) (funcall the-fn t))) ``` The same but with immediate byte-compilation and a call of `my-test` for testing: ``` (let ((lexical-binding t)) ;; The actual defun but with byte-compilation: (defalias 'my-test (byte-compile (lambda () (let* (the-fn) (setq the-fn (lambda (recursive) (message "Calling the-fn with arg %s." recursive) (when recursive (funcall the-fn nil)))) (funcall the-fn t)))))) (my-test) ``` The message output is: ``` Calling the-fn with arg t. Calling the-fn with arg nil. ``` --- Tags: lexical-binding ---
thread-62893
https://emacs.stackexchange.com/questions/62893
Opening Gnus messages to the full height of the screen
2021-01-20T05:27:35.157
# Question Title: Opening Gnus messages to the full height of the screen I recently switched from RMAIL to GNUS. In RMAIL one views email messages in full screen and presses "n" to go to the next message or "p" to go to the previous one. I have also configured Gnus to use "n" and "p" regardless of whether the message is read or not. However, I would like to view my email messages in full screen, rather than having the message occupy only two thirds of the screen. How can I achieve this? # Answer Gnus's Window Layout management is quite powerful. And as always it gives full opportunity to hit ourselves in the foot. ;-) I am not sure about completely removing the top window but definitely you can customize the default height/width of the windows. `gnus-buffer-configuration` is the variable to look for. This is an alist with various window/frame settings. But the relevant part is this, ``` (article (vertical 1.0 (summary 0.25 point) (article 1.0))) ``` Following is an excerpt from chapter "(gnus)Top \> Various \> Window Layout": ``` C-h i gnus RET m Window Layout RET ``` > This “split” says that the summary buffer should occupy 25% of upper half of the screen, and that it is placed over the article buffer. As you may have noticed, 100% + 25% is actually 125% (yup, I saw y’all reaching for that calculator there). However, the special number ‘1.0’ is used to signal that this buffer should soak up all the rest of the space available after the rest of the buffers have taken whatever they need. There should be only one buffer with the ‘1.0’ size spec per split. > 2 votes --- Tags: gnus ---
thread-62898
https://emacs.stackexchange.com/questions/62898
What difference does it make changing the order of arguments to 'append'
2021-01-20T10:45:41.570
# Question Title: What difference does it make changing the order of arguments to 'append' I want to understand the implications of `append`'s property that "All arguments except the last one are copied, so none of the arguments is altered." (from the Elisp manual) Say I have a list `mylist` (the order of its elements is irrelevant), ``` (setq mylist '(a b)) ``` First, I want to add a couple of elements to it. Using `append` I can do ``` (setq mylist (append mylist '(c d))) ``` or ``` (setq mylist (append '(c d) mylist)) ``` If I understand right, the resulting list is ``` mylist | | --- --- --- --- --- --- --- --- --> | | |--> | | |--> | | |--> | | |--> nil --- --- --- --- --- --- --- --- | | | | | | | | --> a --> b --> c --> d ``` in the first case and ``` mylist | | --- --- --- --- --- --- --- --- --> | | |--> | | |--> | | |--> | | |--> nil --- --- --- --- --- --- --- --- | | | | | | | | --> c --> d --> a --> b ``` in the second case. *Both settings leave nothing else in memory*, right? Second, I want to concatenate `mylist` and `another-list` (again invariant wrt to the order of its elements), ``` (setq another-list '(0 1)) ``` (I'll use the first value of `mylist`). I can do ``` (setq another-list (append mylist another-list)) ``` or ``` (setq another-list (append another-list mylist)) ``` In my reasoning the first setting yields ``` another-list | | --- --- --- --- --- --- --- --- --- --- --- --- --> | | |--> | | |--> | | |--> | | |--> | | |--> | | |--> nil --- --- --- --- --- --- --- --- --- --- --- --- | | | | | | | | | | | | --> a --> b --> c --> d --> 0 --> 1 ``` while `mylist` still resides unaltered somewhere in memory. The second setting yields ``` another-list mylist | | | --- --- --- --- -> --- --- --- --- --- --- --- --- --> | | |--> | | |--> | | |--> | | |--> | | |--> | | |--> nil --- --- --- --- --- --- --- --- --- --- --- --- | | | | | | | | | | | | --> 0 --> 1 --> a --> b --> c --> d ``` which is all the code I've used has put in memory, which is to say that compared with the first setting of `another-list` I've spared one copy of `mylist`. Is this right? Last thing, when Emacs evaluates `(append mylist '(c d))` and `(append '(c d) mylist)`, what do they look like in memory? Can you show it with a cons cells diagram? # Answer > 4 votes That's pretty much it, but keep in mind that there is always more going on. For example, the source code that you type in is also read into a bunch of cons cells. This is true whether you're typing at the repl, or be reading from a source file. (Reading byte-compiled code will have a somewhat different result, but with identical semantics.) Thus, after the very first `(setq mylist '(a b))`, you'll have this in memory: ``` ┌─┬─┐ ┌─┬─┐ ┌─┬─┐ │╷│╶┼─→│╷│╶┼───→│╷│/│ └┼┴─┘ └┼┴─┘ └┼┴─┘ └→setq └→mylist │ ┌─┬─┐ ┌─┬─┐ └→│╷│╶┼──→│╷│/│ └┼┴─┘ └┼┴─┘ └→quote │ ┌─┬─┐ ┌─┬─┐ └→│╷│╶┼─→│╷│/│ mylist───────────────────────→└┼┴─┘ └┼┴─┘ └→a └→b ``` `mylist` is pointing to part of the source code, rather than to a new list. Then, after running `(setq mylist (append mylist '(c d)))` you'll have the above plus this: ``` ┌─┬─┐ ┌─┬─┐ ┌─┬─┐ │╷│╶┼─→│╷│╶┼───→│╷│/│ └┼┴─┘ └┼┴─┘ └┼┴─┘ └→setq └→mylist │ ┌─┬─┐ ┌─┬─┐ ┌─┬─┐ └→│╷│╶┼────→│ │╶┼───→│╷│/│ └┼┴─┘ └┼┴─┘ └┼┴─┘ └→append └→mylist │ │ ┌─┬─┐ ┌─┬─┐ └→│╷│╶┼──→│╷│/│ └┼┴─┘ └┼┴─┘ └→quote │ ┌─┬─┐ ┌─┬─┐ ┌─┬─┐ ┌─┬─┐ └→│╷│╶┼─→│╷│/│ mylist─→│╷│╶┼─→│╷│╶┼───────────────────────────────→└┼┴─┘ └┼┴─┘ └┼┴─┘ └┼┴─┘ └→c └→d └→a └→b ``` That is, `mylist` is now pointing to a list whose first two conses are new, but whose other conses are not. This is why you never want to call `setcar`, `setcdr`, `nconc`, or any other function that modifies a value in place on any value that came directly from the reader; they will happily modify source code that you will want to run again. # Answer > 4 votes I think it's useful to contrast how `append` and `nconc` behave in this regard. The way `nconc` concatenates its arguments is by modifying the end of each argument to point to the next argument. It does so "destructively", meaning it modifies its arguments in-place, without first making a copy. Here's an example. **N.B.:** instead of using quoted constant lists like `'(1 2)` I am using `list` to allocate fresh list objects that are safe to modify; see `(info "(elisp) Mutability")`. ``` (setq a (list 1 2)) (setq b (list 3 4)) (setq c (nconc a b)) ``` Here's the resulting box diagram: ``` a, c b | | | --- --- --- --- -> --- --- --- --- --> | | |--> | | |--> | | |--> | | |--> nil --- --- --- --- --- --- --- --- | | | | | | | | --> 1 --> 2 --> 3 --> 4 ``` What happened is `a` was traversed until its final cdr, which was modified in place to point to `b`. As a result, `a` and `c` are both `equal` and `eq` now, but the new `a` is no longer `equal` to the old `a`. By contrast, `b` was the last argument to `nconc` and thus the final tail of the concatenated list, so it wasn't even traversed, let alone modified. In fact, the final tail doesn't even have to be a list; whatever it is is just slapped onto the end of the result as the final cdr: ``` (nconc (list 1 2) 3) ;; => (1 2 . 3) ``` --- The way `append` concatenates its arguments is practically the same, except it makes a copy before modifying any argument (it also accepts sequences that aren't lists, but that's irrelevant here). Using the same example as before, here's the resulting box diagram: ``` a | | --- --- --- --- --> | | |--> | | |--> nil --- --- --- --- | | | | --> 1 --> 2 c b | | | --- --- --- --- -> --- --- --- --- --> | | |--> | | |--> | | |--> | | |--> nil --- --- --- --- --- --- --- --- | | | | | | | | --> 1 --> 2 --> 3 --> 4 ``` What happened is `a` was copied, the copy's final cdr was modified in place to point to `b`, and the result was assigned to `c`. As a result, `a` and `b` are still `equal` and `eq` to their previous selves, and `a` is neither `equal` nor `eq` to `c`. Again, the final tail need not be a list, because it won't be traversed or copied: ``` (append (list 1 2) 3) ;; => (1 2 . 3) ``` --- Back to your question: > *Both settings leave nothing else in memory*, right? Apart from objects that are no longer referred to and might eventually be garbage-collected, such as the original value of `mylist` of `'(a b)`. See also db48x's answer. > which is to say that compared with the first setting of `another-list` I've spared one copy of `mylist`. Is this right? Yes, as was the case with `b` in my example above. > Last thing, when Emacs evaluates `(append mylist '(c d))` and `(append '(c d) mylist)`, what do they look like in memory? Can you show it with a cons cells diagram? I think db48x's answer has already covered that. HTH. --- Tags: list ---
thread-62895
https://emacs.stackexchange.com/questions/62895
Disable quote replacement in sgml-mode
2021-01-20T09:59:44.080
# Question Title: Disable quote replacement in sgml-mode In sgml-mode, when I type quotes `"`, they are automatically replaced by `&#34;`. The culprit is the function `sgml-name-self`. Perhaps it is called automatically on characters in the variable `sgml-specials` (?); however, when I set `sgml-specials` to `nil`, the issue persists. How to turn this automatic replacement off? Any help would be greatly appreciated, *this automatic replacement drives me insane*. # Answer `sgml-mode` will not set up the key bindings to insert replacements for `'` and `"` if you set `sgml-specials` to `nil`, as long as do that before `sgml-mode` is loaded. > 0 votes --- Tags: html, quote ---
thread-62903
https://emacs.stackexchange.com/questions/62903
Disable "10 repeater intervals were not enough"
2021-01-20T16:38:28.600
# Question Title: Disable "10 repeater intervals were not enough" I sometimes get the message: 10 repeater intervals were not enough to shift date past today. Continue? (y or n) When I mark a repeating TODO as done. I would not like to be asked this. In other words, I would like the answer to this to always be "yes". Automatically. I imagine there is a setting to set the number of repeater intervals to infinite or a large number or to disable this message. I have not been able to find a setting to do this. Any help is much appreciated. # Answer Seems there is no setting for this: https://code.orgmode.org/bzg/org-mode/src/7fa8173282f85c2ca03cc7f51f28f6adfb250610/lisp/org.el#L10425 You could try writing a patch to add a setting and submitting it to the org mailing list? > 1 votes --- Tags: org-mode ---
thread-62905
https://emacs.stackexchange.com/questions/62905
Emacs ignore \n in buffer
2021-01-20T20:27:57.400
# Question Title: Emacs ignore \n in buffer I would like to change the default behavior in emacs when '\n' meta-characters are encountered by the cursor. The default behavior is such that at '\n', (1) right-key sends the cursor to the beginning of the next line, (2) up-key sends the cursor to the end of the prev line, (3) down-key sends the cursor to the end of the next line. How can I get emacs to ignore '\n' meta-characters in a given buffer? Or how can I get emacs to ignore either one of the keys identified in (1), (2) and (3)? # Answer > 0 votes You can reassign the keys to new functions that don't move if the char at point is a newline: ``` (defun maybe-down () "Move down if char at point is not a newline." (interactive) (if (char-equal (char-after) 10) (ignore) (next-line))) (define-key (current-local-map) [down] 'maybe-down) ``` And similarly for `[right]` with `(right-char)`. --- Tags: key-bindings, motion, newlines ---
thread-62911
https://emacs.stackexchange.com/questions/62911
How to recover from a backup file
2021-01-21T06:35:24.670
# Question Title: How to recover from a backup file I can recover a file from an *auto-save* via `M-x recover-this-file`. So far so good. But how can I recover a file from it's last backup (if, of course, I have switched backups on)? # Answer For that, I use https://github.com/lewang/backup-walker. ``` (autoload 'backup-walker-start "backup-walker" "" t) ``` > 1 votes --- Tags: auto-save, backup, recover ---
thread-62882
https://emacs.stackexchange.com/questions/62882
How to search word under cursor using counsel-git-grep
2021-01-19T18:45:27.740
# Question Title: How to search word under cursor using counsel-git-grep I am using `counsel-git-grep` to grep for a string in the current Git repository. When I do `M-x counsel-git-grep` it opens following in the mini-buffer. ``` 2 git grep: 3 chars more ``` --- Let say if the cursor on top of ``` def hello_word(): ^ |__cursor is here and when I entered `M-x counsel-git-grep` ``` I want following to open: ``` 2 git grep: hello_word 3 chars more ``` \[Q\] How can I pass the word under cursor to the `counsel-git-grep` search? # Answer > 1 votes I've wrapped a couple of function in my dotemacs to achieve this: ``` ;; from https://github.com/abo-abo/swiper/issues/1068 (defun my-ivy-with-thing-at-point (cmd &optional dir) "Wrap a call to CMD with setting " (let ((ivy-initial-inputs-alist (list (cons cmd (thing-at-point 'symbol))))) (funcall cmd nil dir))) (use-package counsel :config (setq counsel-ag-base-command "ag --vimgrep -a %s")) (defun my-counsel-ag-from-here (&optional dir) "Start ag but from the directory the file is in (otherwise I would be using git-grep)." (interactive "D") (my-ivy-with-thing-at-point 'counsel-ag (or dir (file-name-directory (buffer-file-name))))) (defun my-counsel-git-grep () (interactive) (my-ivy-with-thing-at-point 'counsel-git-grep)) ``` --- Tags: search, counsel ---
thread-62689
https://emacs.stackexchange.com/questions/62689
Key binding of a function interferes with global key binding
2021-01-10T14:02:50.217
# Question Title: Key binding of a function interferes with global key binding The key binding `\` of the function `w3m-show-source` interferes with the function with the same key binding `hydra-master-body` (which I set up in the `init` file). I have used the function `global-set-key` to change the key binding of `w3m-show-source` to `ctrl-,`. Now the function `w3m-show-source` has two key bindings `\` and `ctrl-,`. How can I *remove* `\` from the function `w3m-show-source` so that it will execute `hydra-master-body`? # Answer > 1 votes Find out the solution. The command was `(add-hook 'w3m-mode-hook (lambda () (define-key w3m-mode-map (kbd "\\") nil)))` --- Tags: key-bindings ---
thread-62912
https://emacs.stackexchange.com/questions/62912
What is the difference between these two lists?
2021-01-21T07:34:00.523
# Question Title: What is the difference between these two lists? I'm reading *An Introduction to Programming in Emacs Lisp* by Robert J. Chassell. When the book is introducing `setcar`, it points out that when we use this function to a list, the list should be initialized in this way: ``` (setq list1 (list 'a 'b 'c)) ``` instead of ``` (setq list2 '(a b c)) ``` And then ``` (setcar list1 'A) ``` But if I evaluate `list1` and `list2`, Emacs gives me the same list `(a b c)`. I don't see any difference here. As a matter of fact, `(setcar list2 'A)` is also evaluated successfully. > Page 76 > ...Because we intend to use `setcar` to change the list, this `setq` should not use the quoted form `'(antolope giraffe lion tiger)`, as that would yield a list that is part of the program and bad things could happen if we tried to change part of the program while running it. > Generally speaking an Emacs Lisp program's components should be constant (or unchanged) while the program is running. So we instead construct an animal list by using the `list` function, as follows: `setq animals (list 'antelope 'giraffe 'lion 'tiger))` # Answer Internally, in function definitions, Emacs stores the list if it is written as `'(a b c)`. If you modify it using destructing operations like `setcar` you actually change the function definition. > 1 votes --- Tags: list ---
thread-62918
https://emacs.stackexchange.com/questions/62918
sin of pi radians
2021-01-21T11:32:28.153
# Question Title: sin of pi radians I'm computing sin of pi radians in emacs using this function: ``` #+begin_src emacs-lisp :eval never-export :exports both (sin pi) #+end_src #+RESULTS: : 1.2246467991473532e-16 ``` The manual docs mentions that the argument is passed in radians. Just to be sure, I confirmed that sin pi radians is infact zero: https://en.wikipedia.org/wiki/Sine#Special\_values But it seems to be working fine for cosine functions: ``` #+begin_src emacs-lisp :eval never-export :exports both (cos pi) #+end_src #+RESULTS: : -1.0 ``` I guess I'm missing something here. Can somebody point what I'm doing wrong ? # Answer > 20 votes **The Emacs Lisp constant `pi` is not actually the number .** Rather, the Emacs Lisp constant `pi` is an *approximation* to , good to about 16 digits -- `pi` is exactly 3.141592653589793115997963468544185161590576171875, which is the IEEE 754 binary64 floating-point number closest to . This is also the floating-point number closest to 3.141592653589793, which is why, when you evaluate `pi`, Emacs will show the much shorter `3.141592653589793` as an unambiguous abbreviation for it. **So when you pass `pi` to the `sin` function, you are not asking it to compute sin(), which is zero. Instead, you are asking it to compute sin(3.141592653589793115997963468544185161590576171875), which is slightly above zero because 3.141592653589793115997963468544185161590576171875 is slightly below .** The Emacs Lisp function `sin` may also return some additional error, but the error is very small: the value of Emacs Lisp `(sin pi)` differs from the true value of sin(3.141592653589793115997963468544185161590576171875) by less than .000000000000002% (that is, 2 × 10⁻¹⁷) of the magnitude of the true value. In particular, the true value of sin(3.141592653589793115997963468544185161590576171875) is irrational and so doesn't have a finite decimal expansion, but it is roughly **1.2246467991473531772260659322749979970830539012998** × 10⁻¹⁶, whereas Emacs Lisp returns **1.224646799147353**20717376402945839660462569212467758006379625612680683843791484832763671875 × 10⁻¹⁶, which is wrong only after the sixteenth digit. (Again, this is the nearest floating-point number to 1.2246467991473532 × 10⁻¹⁶, which is why Emacs Lisp prints it unambiguously and more concisely as `1.2246467991473532e-16`.) **This number returned by `(sin pi)` is not simply some random error!** It turns out that it is actually a good approximation to the *error in Emacs Lisp's approximation* of ! This happens because when is near , sin() = ( − ) + (( − )³); this is the Taylor series of sine about . So if `pi` = − with absolute error , then `(sin pi)` computes an approximation to sin( − ) ≈ − ( − ) = , good to about 16 digits. If you add the value of the Emacs Lisp constant `pi` ( − = 3.141592653589793115997963468544185161590576171875) and the value of `(sin pi)` (1.22464679914735320717376402945839660462569212467758006379625612680683843791484832763671875 × 10⁻¹⁶), using exact arbitrary-precision arithmetic, what you get is **3.14159265358979323846264338327950**5878966979117714660462569212467758006379625612680683843791484832763671875, in which, if you are a Standard Nerd, you will start to recognize all the digits up to the 32nd or so, since `pi` \+ sin(`pi`) ≈ `pi` \+ = − + = . The familiarity ends there (or earlier if you did not spend an inordinate time as a Standard Nerd Child memorizing digits of ) because `pi` and `(sin pi)` each only have about 16 digits of precision, and so together they have only 32 digits of precision. --- **You should be aware, though, that the mathematical sine function is said to be *ill-conditioned* near (and near any odd multiple of ). What this means is that it *magnifies errors* in inputs near .** Specifically: * Suppose you want to find the sine of some number near . * Suppose you don't actually know itself, but only an approximation ⋅(1 + ), with relative error . + For example, perhaps is a physical dimension, and you made a small error in measurement because you don't have an infinitely precise ruler or compass to measure with in the real world. * If you then compute sin(⋅(1 + )), you will get, at best, an approximation sin()⋅(1 + ) to sin(). The relative error of the result may be *arbitrarily large* even if the relative error of the input is very small, *and even if the sine function is evaluated exactly*. The last part means that sine's being ill-conditioned near is a property of the *function*, not of the system of floating-point arithmetic. Even if you used some kind of infinite-precision transcendental arithmetic system with no rounding error whatsoever (arbitrary-precision rational arithmetic wouldn't cut it because sine is transcendental), the sine function *itself* could magnify your small input error near into a large output error. > Example: Suppose the true value of is the floating-point number nearest to 3.14159000000001, but the approximation you have owing to measurement error is the floating-point number nearest to 3.14159 -- this is in error by only a fraction ≈ 3 × 10⁻¹⁵ of the true value. > > Then sin() ≈ **2.653589783138678** × 10⁻⁶ but your approximation to it will be sin(⋅(1 + )) ≈ **2.6535897**9335273 × 10⁻⁶ in which about half the digits are wrong. > > So while you have storage for 16 digits of precision, and your *input* was good to nearly all of them, only 9 digits of the *output* are good and your output error in sin()⋅(1 + ) is ≈ 4 × 10⁻⁹, *a million times worse* than the input error, *because of the question you asked* (and *not* because you used floating-point arithmetic to answer it). **The lesson is that if you find yourself trying to answer the question of the sine of an input near , you should consider trying to rephrase the question another way -- for example, perhaps instead of measuring directly near , you can measure the much smaller = − , and then use the approximation sin() = + (³).** This phenomenon is, incidentally, related to why the historic trigonometric functions with crazy-sounding names like versine and exsecant exist -- it wasn't to torture students in school, but rather to allow navigational and astronomical questions to be phrased so they admit computational approximations without magnifying errors. --- **Why does it seem to work with cosine?** The true value of cos(3.141592653589793115997963468544185161590576171875) is an irrational number: −0.9999999999999999999999999999999925012010866907120… Emacs Lisp returns a floating-point number (always a rational number), and the two nearest floating-point numbers are −1 and −0.99999999999999988897769753748434595763683319091796875. Although Emacs Lisp doesn't always guarantee to return the nearest floating-point number to the true answer for transcendental functions like cosine, in this case it happens to do so, giving −1. (Usually when the nearest floating-point number is *that much closer* (relative error below 10⁻³²) than the next-nearest (relative error above 10⁻¹⁶), math libraries will return the nearest one.) So Emacs Lisp happens to return −1 as an approximation to cos(3.141592653589793115997963468544185161590576171875), even though the question wasn't to compute cos(). **This isn't just an accident of high-quality math library implementation, though!** It's also because, unlike the sine function, the cosine function is *well-conditioned* near : even if your inputs are badly approximated near , so you ask for cos(⋅(1 + )) when you want cos(), what you will get is cos()⋅(1 + ) where is a relative error much smaller than the relative error in the input. > Example: Suppose you have a *much worse* approximation to given by 3.14159264305308116860260270186699926853179931640625 (abbreviated `3.141592643053081`), which is ⋅(1 + ) whose relative error from is more than 10⁻⁹. > > If you ask for the cosine of this approximation when you really want cos(), it turns out that cos(⋅(1 + )) = cos(3.14159264305308116860260270186699926853179931640625) = −0.99999999999999994448884937843286910504136142018913… = cos()⋅(1 + ) whose relative error from the result you wanted (−1) is \< 10⁻¹⁶. > > That is, the relative error of the result is a million times *better* than the relative error of the input. **So cosine is much more tolerant to bad approximations of inputs near than sine is.** In more formal terms, the *condition number* of the function cos() is ⋅cos′()/cos() = −⋅tan() which approaches zero at (well-conditioned), whereas the condition number of the function sin() is ⋅sin′()/sin() = /tan() which approaches infinity at (ill-conditioned). In general, you should avoid trying to ask about functions at approximations to points where they are ill-conditioned, and phrase your questions in terms of functions at approximations to points where they are well-conditioned -- the *condition number* is roughly the factor by which the *function itself* magnifies errors (before any additional rounding errors in the computation take effect). # Answer > 6 votes I think this is simply the expected answer. As a float, `1.2246467991473532e-16` is not different from zero, given the floating point error Emacs Lisp can handle. One get the same answer in R for instance: ``` sin(pi) #> [1] 1.224647e-16 ``` and also in Python, as shown in this thread. Actually, this is said in the Emacs Lisp manual: > Floating-point computations often involve rounding errors, as the numbers have a fixed amount of precision. Most programming languages, other than computer algebra systems (e.g., Maxima or Maple) will give such approximate answers. # Answer > 5 votes You are doing nothing wrong. This function is working with floating point numbers which have good, but limited, accuracy. 1.2246467991473532e-16 is pretty close to 0 (0.0... with 15 zeros before the 1224... kicks in). --- Tags: math ---